Engineering the Perfect AI Developer Agent Rulebase (AGENTS.md)
Tired of AI agents installing unapproved packages, reinventing API structures, forgetting project conventions after 10 messages, or creating broken database migrations? Learn how to craft deterministic rulebases that guide developer agents with senior-architect precision across any tech stack.
Theory: Cognitive Foundations of Agent Steering
1.1 The Fundamental Paradigm Shift
To write effective rules, you must distinguish between the three evolutionary stages of developer AI. Many developers mistakenly treat autonomous agents like simple chat assistants, causing immense frustration:
| Generation | Paradigm | Tools | How It Operates | Primary Failure Mode |
|---|---|---|---|---|
| Gen 1 | Inline Autocomplete | Copilot Tab | Predicts 1-5 lines based on immediate surrounding code. | Syntactic typos, wrong variable names. |
| Gen 2 | Conversational Chat | ChatGPT, Claude Web | Human pastes code snippets into chat, copies answers back. | Out-of-date context; manual human glue code required. |
| Gen 3 | Autonomous Agents | Antigravity, Cursor, Claude Code, Cline | Direct terminal execution, file reading/writing, compiler checks, and multi-turn agentic loops with tool execution. | Architectural drift, dependency pollution, silent breaking changes. |
1.2 The Three Deadly Sins of Agent Hallucination
AGENTS.md), rules established in message #1
are forgotten
by message #12 via context entropy.
1.3 The "Explain the WHY" Rule (LLM Cognitive Psychology)
In traditional management, senior engineers sometimes give bare directives like "Always add trailing slashes to URLs." With LLMs, rules that include technical rationales have over 3x higher compliance rates than dogmatic commands. Explaining the mechanism activates the attention heads relating to error prevention:
Bad Rule (Dogmatic Command)
Always include trailing slashes on all API URLs in both backend routes and frontend requests.
Why it fails: The LLM treats this as a superficial styling preference. During complex refactoring, it frequently drops it.
Perfect Rule (With Technical Rationale)
All backend URL routes and client-side requests must always include a trailing slash ('/'). Omitting the trailing slash causes Django to issue an HTTP 301 redirect (APPEND_SLASH=True), which drops the POST/PUT/DELETE request payload and converts it into an empty GET request.
Why it works: The transformer attention connects "trailing slash" with "preventing HTTP 301 POST data loss". The model proactively checks every URL it outputs.
1.4 Token Economics: Density vs. Bloat
Never dump your entire company wiki or 5,000 lines of API specs into an agent rulebase. Overloading the context window dilutes attention weight and degrades reasoning capacity.
How Agent Rules Work Across Different IDEs
Modern AI IDEs have distinct discovery paths, scoping rules, and priority levels for user rules. Understanding these mechanics ensures your team can collaborate seamlessly regardless of which IDE each developer prefers.
| IDE / Tool | Target Rule File | Scope Mechanism | Execution Capability | Rule Priority |
|---|---|---|---|---|
| Google Antigravity | .agents/AGENTS.md.agents/rules/*.md |
Global workspace + on-demand skills/ |
Full sandboxed terminal + MCP + file tools | Strict User Rules (Takes highest precedence over system defaults) |
| Cursor | .cursor/rules/*.mdc(legacy: .cursorrules) |
Glob patterns (e.g. globs: backend/**/*.py) |
Terminal Agent Mode | User Rules override default agent system instructions |
| Windsurf (Codeium) | .windsurfrules |
Workspace root | Cascade reasoning engine | Injected into Cascade scratchpad context |
| Claude Code (Anthropic) | CLAUDE.md |
Workspace root | Autonomous Bash CLI tool | Startup context session initialization |
| GitHub Copilot | .github/copilot-instructions.md |
Repository root | Chat & Workspace extensions | Chat prompt context augmentation |
| Cline / Roo Code | .clinerules |
Mode-based (Code, Architect, Ask) | VS Code workspace execution | System prompt injection |
2.2 Universal Cross-IDE Harmonization
In real software teams, some developers use Antigravity, others use Cursor, and others use Claude Code. Rather
than maintaining 5 separate rule files, keep .agents/AGENTS.md (or root AGENTS.md) as your
canonical single source of truth, and
symlink it to the other locations:
# Run from your project root
mkdir -p .cursor/rules && ln -sf ../.agents/AGENTS.md .cursor/rules/AGENTS.mdc
ln -sf .agents/AGENTS.md .windsurfrules
ln -sf .agents/AGENTS.md CLAUDE.md
mkdir -p .github && ln -sf ../.agents/AGENTS.md .github/copilot-instructions.md
What to Prepare: The Essential Pre-Rule Blueprints
An AI agent cannot adhere to your standards if your standards exist only in your head. When an agent is forced to invent UI layouts, pagination parameters, or error formats, it will invent average, generic patterns. Before writing your rulebase, prepare these concrete assets:
Provide your agent with exact design references and URLs so it understands the expected visual caliber:
Place actual, working HTML/Vue/React templates in an
admin_template/ or
blueprints/ folder. When your rule says "Use the admin_template table pattern", the
agent reads and copies this exact structure:
<!-- Production Table Component Blueprint -->
<div class="card overflow-hidden">
<!-- Action Bar: Search, Filters & Create -->
<div class="p-4 border-b border-light-grey flex flex-col md:flex-row items-center justify-between gap-4 bg-white">
<div class="relative w-full md:w-80">
<i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-prep-grey"></i>
<input type="text" v-model="searchQuery" @input="debouncedSearch" placeholder="Search by name, code..." class="input-field pl-9">
</div>
<div class="flex items-center gap-3 w-full md:w-auto justify-end">
<button @click="navigateToCreate" class="btn-primary">
<i class="fa-solid fa-plus mr-1"></i> Add New Entity
</button>
</div>
</div>
<!-- Table Structure -->
<div class="overflow-x-auto">
<table class="w-full text-left border-collapse text-sm">
<thead class="bg-off-white text-xs uppercase font-semibold text-prep-grey border-b border-light-grey">
<tr>
<th class="py-3 px-4 cursor-pointer" @click="sortBy('name')">
Name <i :class="sortOrder === 'asc' ? 'fa-sort-up' : 'fa-sort-down'" class="fa-solid text-forti-black ml-1"></i>
</th>
<th class="py-3 px-4">Status</th>
<th class="py-3 px-4">Updated</th>
<th class="py-3 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-light-grey">
<tr v-if="isLoading">
<td colspan="4" class="py-12 text-center text-prep-grey">
<i class="fa-solid fa-spinner fa-spin mr-2"></i> Loading items...
</td>
</tr>
<tr v-else-if="items.length === 0">
<td colspan="4" class="py-12 text-center text-prep-grey">No records found.</td>
</tr>
<tr v-else v-for="item in items" :key="item.id" class="hover:bg-off-white/50 transition-colors">
<td class="py-3 px-4 font-medium text-forti-black cursor-pointer hover:underline hover:text-prep-green" @click="editItem(item.id)">
{{ item.name }}
</td>
<td class="py-3 px-4">
<span class="bg-success/10 text-success ring-1 ring-inset ring-success/20 px-2 py-0.5 rounded text-xs font-medium">
{{ item.status }}
</span>
</td>
<td class="py-3 px-4 text-prep-grey">{{ formatDate(item.updated_at) }}</td>
<td class="py-3 px-4 text-right space-x-3">
<button @click="editItem(item.id)" class="text-prep-grey hover:text-prep-green" title="Edit"><i class="fa-solid fa-pen"></i></button>
<button @click="confirmDelete(item.id)" class="text-prep-grey hover:text-danger" title="Delete"><i class="fa-solid fa-trash"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
Embed your exact, working pagination and filtering helpers directly inside your rules or reference directory. Here is an example of standard pagination code seeds:
from django.core.paginator import Paginator
def paginate_queryset(queryset, request, per_page=50):
try:
page_num = int(request.GET.get('page', 1))
except (ValueError, TypeError):
page_num = 1
paginator = Paginator(queryset, per_page)
page_obj = paginator.get_page(page_num)
return page_obj, {
'total_pages': paginator.num_pages,
'current_page': page_obj.number,
'total_items': paginator.count,
'per_page': per_page
}
export interface PaginationMeta {
totalPages: number;
currentPage: number;
totalItems: number;
perPage: number;
}
export function parsePaginationParams(query: Record<string, any>, defaultPerPage = 50) {
const page = Math.max(1, parseInt(query.page) || 1);
const perPage = Math.min(100, Math.max(1, parseInt(query.perPage) || defaultPerPage));
const skip = (page - 1) * perPage;
return { page, perPage, skip };
}
Provide the exact pattern for mutation buttons so the agent never leaves save buttons unprotected against rapid clicking using an in-flight request guard:
<!-- Vue 3 Pattern -->
<button
type="submit"
:disabled="isSubmitting"
class="btn-primary flex items-center justify-center min-w-[120px]">
<i v-if="isSubmitting" class="fa-solid fa-spinner fa-spin mr-2"></i>
<span>{{ isSubmitting ? 'Saving...' : 'Save Changes' }}</span>
</button>
Clearly sketch your repository file structure. An agent that knows the exact folder hierarchy will never create rogue folders outside of whitelisted directories and will respect environment variables:
project_root/
├── frontend/ # Client application (Vue/React/Vite)
├── backend/ # Server application (Django/FastAPI/Express)
├── doc/ # Architecture docs and codebase_index.md
├── .agents/ # AGENTS.md, rules, templates, and guides
├── .env.example # Sanitized template for all required variables
└── requirements.txt # Or package.json lockfiles (strictly synchronized)
Step-by-Step Rulebase Construction Prompts
To build your custom rulebase inside your IDE, work through
these 15 steps sequentially. For each step, answer the guiding
questions, understand the consequence of omission, and copy the provided prompt template into your AI agent. Each step produces one section of your
AGENTS.md:
Step 1 Project Structure, Root Hygiene & Dependencies
Guiding Questions: What are the ONLY allowed root folders? Where does the virtual environment or package manager operate? How are dependencies synchronized between local development and production? Should a run script be generated?
scripts/, temp/, test-results/) directly in the root.
Without lockfile synchronization rules, agents install packages locally without saving them to
lockfiles,
breaking deployment.
I am creating the "Project Structure & Dependency Rules" section of my developer agent rulebase (AGENTS.md).
Here are my project parameters:
- Backend: [e.g. Django in backend/ / FastAPI / Express / Rails]
- Frontend: [e.g. Vue 3 + Vite in frontend/ / Next.js / SvelteKit / none]
- Allowed Root Folders: [List allowed folders, e.g. frontend/, backend/, venv/, doc/ ONLY]
- Root Files: [e.g. requirements.txt, .env, .env.example]
- Dependency Management: [e.g. python virtualenv in venv/ with strict requirements.txt updates; frontend npm install locally within frontend/]
- Deployment Architecture: [e.g. SFTP upload of pre-compiled dist/ and direct virtualenv python execution; OR Docker containers; OR Vercel/Netlify]
- Running Script: [e.g. Always create a shell script with steps: activate venv, makemigrations, migrate, runserver]
Write a dense, professional markdown rule specification following the "Explain the Why" principle. Include explicit rules preventing root clutter and enforcing lockfile synchronization.
Step 2 Environment Configuration Strategy (Dev vs. Production)
Guiding Questions: How are environment
variables structured? Do you have separate .env files for development and production?
How does the frontend resolve API base URLs in each
environment? Where are secret keys, database passwords, allowed hosts, and CORS origins stored?
localhost:8000 directly
into frontend components, commit secret keys into git, or forget to create .env.example
templates. This breaks production deployments and creates security vulnerabilities.
Generate the "Environment Configuration & Secrets Management" section for my AGENTS.md.
Requirements:
- Backend Environment: [e.g. Root .env and .env.example; all secrets loaded via os.getenv() in settings.py]
- Frontend Environment: [e.g. frontend/.env.development (VITE_API_BASE_URL=http://localhost:8000/) and frontend/.env.production (VITE_API_BASE_URL=/)]
- Secret Key: [e.g. Always auto-generate a Django SECRET_KEY in .env by default]
- Allowed Hosts & CORS: [e.g. Must always be stored only in .env, never hardcoded in settings.py]
- Production Settings: [e.g. Always configure STATIC_ROOT, MEDIA_ROOT, DEBUG=False for production]
- Why Explanation: Include technical rationale for why hardcoded URLs break production and why .env.example must always mirror .env structure.
Step 3 Backend Architecture, User Models & Multi-Level RBAC
Guiding Questions: Are you using third-party wrappers (like DRF) or native ORM and framework views? What database is used in dev vs production? How is role-based access control (RBAC) structured? Does the user model need granular permission fields?
Generate the "Backend Architecture & User Permissions" section for my AGENTS.md.
Stack Specifications:
- Framework: [e.g. Django Vanilla without DRF / Express TypeScript / FastAPI / Rails]
- Forbidden Libraries: [e.g. Strictly NO Django REST Framework / NO Passport.js]
- Development Database: [e.g. SQLite]
- Custom User Model: [e.g. Inherits from AbstractUser with a JSONField named `menu_access` for granular multi-level permissions controlling modules, submodules, tabs, and actions (view, create, edit, delete, export)]
- Rights Management: When building admin management interfaces, always provide a dedicated Rights Management module where superusers configure granular rights across modules, submodules, and actions.
- Hydration Endpoint: Provide a `/users/me/` endpoint returning authenticated user, superuser status, and permission matrix.
- Auth Decorator: Forbid HTML redirect decorators; require custom decorator returning 401 JSON when unauthenticated.
Step 4 API Contracts, Pagination & Standardized JSON Signatures
Guiding Questions: What are your exact standardized JSON response envelopes for list, create, update, delete, and error responses? Do you have a reusable pagination utility? How many items per page by default? How are search queries and sort fields whitelisted?
{data: [...]}, others {results: [...]}, others flat arrays. This makes frontend
parsing inconsistent and causes runtime crashes when the client expects one format and receives another.
Generate the "API Contracts, Pagination & Standardized JSON Signatures" section of AGENTS.md.
Requirements:
1. Standard JSON Envelopes:
- List: `{'<entities>': data, 'pagination': pagination_meta}`
- Create: `{'id': obj.id, 'detail': '... created successfully.'}`, status 201
- Update: `{'detail': '... updated successfully.'}`, status 200
- Delete: `{'detail': '... deleted successfully.'}`, status 200
- Error: `{'error': 'Error message'}`, status 400/401/403/404
2. Reusable Pagination Utility: [e.g. Create a helper in backend/utils/pagination.py returning page_obj and metadata dict; default 50 items per page]
3. Sanitized Query Filtering: Always whitelist valid `sort_by` fields before calling .order_by() to prevent SQL injection. Use Q objects for multi-field search.
Include concrete code seed for the pagination helper.
Step 5 Trailing Slashes, Atomic Transactions & DateTime Standards
Guiding Questions: What is your URL trailing slash convention? When are database mutations wrapped in atomic transactions? How are dates and times serialized across API boundaries? Do you need orphan file cleanup for deleted model records?
Generate the "Data Integrity, URL Conventions & DateTime Standards" section of AGENTS.md.
Requirements:
1. Mandatory Trailing Slashes: All backend URL routes AND all client-side API requests must always include a trailing slash. Explain that [e.g. Django] issues HTTP 301 redirects when omitted, which drops POST/PUT/DELETE payloads and converts them to GETs.
2. Atomic Transactions: Mandate [e.g. transaction.atomic / database transactions] for any view or service writing to multiple tables or uploading files alongside DB records.
3. DateTime Standard: UTC ISO 8601 strings across all API boundaries (USE_TZ=True, store in UTC, serialize as isoformat).
4. Orphan Media Cleanup: Deleting model records with file/image fields must remove physical files from disk via signals or custom delete overrides.
5. Migration Safety: [e.g. The agent must never run makemigrations or migrate; only run manage.py check]
Step 6 Authentication, CSRF & API Client Configuration
Guiding Questions: How does the frontend authenticate with the backend? Do you use session-based auth with CSRF tokens, or JWT, or Firebase? How does the SPA acquire a CSRF cookie on initial page load? Is there a centralized HTTP client (like Axios) with interceptors?
withCredentials: true and CSRF token headers in the HTTP client. Every POST/PUT/DELETE request
will fail with a 403 Forbidden error, and the agent will spiral into workarounds like disabling CSRF
protection entirely — creating a massive security vulnerability.
Generate the "Authentication, CSRF & API Client Configuration" section for AGENTS.md.
Specifications:
1. Auth Strategy: [e.g. Django session-based auth with HTTP-only cookies / Firebase Auth connected to Django AbstractUser / JWT with refresh tokens]
2. CSRF Handshake: [e.g. Provide a lightweight @ensure_csrf_cookie endpoint at users/csrf/ so the SPA can acquire a valid CSRF cookie on app startup]
3. Centralized HTTP Client: [e.g. Create frontend/src/axios.js configured with:
- withCredentials: true
- xsrfCookieName: 'csrftoken'
- xsrfHeaderName: 'X-CSRFToken'
- An interceptor attaching the CSRF token from cookies
- An automatic handshake call to users/csrf/ on app startup]
4. Media URL Resolution: [e.g. Provide a getMediaUrl(path) utility that resolves /media/ paths to full URLs in dev and relative paths in production]
5. Mandatory Trailing Slashes on All API Requests: Reiterate that all Axios endpoints must include trailing slashes.
Step 7 Design System Tokens, Typography & Utility Classes
Guiding Questions: What are your exact design tokens — brand colors, neutrals, status colors, font families?
What reusable UI utility classes (.card, .btn-primary,
.input-field) should every component use? Do you use a CSS framework like Tailwind, or vanilla
CSS?
#333 in one file, #1a1a1a in another, text-gray-800 in a third. The
result is an inconsistent UI that looks like it was built by 10 different developers. Providing explicit
tokens guarantees visual cohesion.
Generate the "Design System Tokens & Common Classes" section for AGENTS.md.
My Design System:
1. Color Palette:
- Primary dark/text: [e.g. forti-black (#030302)]
- Brand/accent: [e.g. prep-green (#6B6C62)]
- Secondary neutrals: [list your neutral colors]
- Backgrounds & borders: [list bg/border colors]
- Status colors: success (#3A7D44), warning (#D4A843), danger (#C4392A), info (#4A6FA5)
2. Typography: [e.g. Inter (font-sans) for body, Outfit (font-heading) for headings]
3. CSS Framework: [e.g. Tailwind CSS with extended config / Vanilla CSS with custom properties]
4. Utility Classes: Define these under @layer components:
- .card: [exact class list]
- .btn-primary: [exact class list with hover, focus, transition states]
- .btn-secondary: [exact class list]
- .input-field: [exact class list]
- .sticky-header: [exact class list]
Include exact tailwind.config.js color extension and style.css @layer components code.
Step 8 Layout, Sidebar Navigation & Mobile Responsiveness
Guiding Questions: What is the app shell layout (sidebar + main content)? What goes in the sidebar header, navigation links, and user profile footer? How should navigation links be dynamically filtered based on user permissions? How does the mobile drawer work?
Generate the "Layout & Navigation" section for AGENTS.md.
Specifications:
1. App Shell: [e.g. AdminLayout.vue with fixed sidebar + scrollable main content area]
2. Sidebar Structure:
- Header: [e.g. Branded logo header with dark background]
- Navigation Links: [e.g. Dynamic links with active state indicator, filtered by user menu_access permissions and is_superuser]
- User Footer: [e.g. Initials avatar, truncated name/email, dedicated logout button with danger styling]
3. Mobile Drawer: [e.g. Hamburger toggle fixed top-left, backdrop overlay, drawer slides in from left]
4. Icons: [e.g. FontAwesome Free icons ONLY. NO emojis anywhere in the interface.]
5. Permission Filtering: Navigation items must be dynamically filtered based on the authenticated user's permission matrix.
Step 9 Tables, Search, Sorting & State Persistence
Guiding Questions: How do data tables handle search, filtering, and debounced real-time search? How is column sorting implemented? How is reactive state management applied so that table state is persisted when navigating between edit pages and back? What do loading/empty states look like?
Generate the "Tables, Lists & State Persistence" section for AGENTS.md.
Specifications:
1. Search: Real-time, debounced by 300ms, automatically resets pagination to page 1 on input.
2. Pagination: [e.g. 50 items per page by default]
3. Column Sorting: Clickable headers with clear sort indicator icons (active vs inactive states). Default sort: ascending by primary name field.
4. Table State Persistence: [e.g. Apply a Pinia/Zustand store to save current page, search query, and sort state per table, so navigating back from edit preserves position]
5. Clickable Entity Names: The primary name/identifier in each row must be a clickable link to the edit page.
6. Action Icons: Standardize per-row actions: edit (fa-pen, hover green), delete (fa-trash, hover red), view (fa-eye).
7. Status Badges: [e.g. Subtle tinted backgrounds with inset rings: bg-success/10 text-success ring-1 ring-inset ring-success/20]
8. Loading State: [e.g. Spinner + "Loading items..." spanning all columns]
9. Empty State: [e.g. "No records found." spanning all columns]
10. Row Hover: Subtle hover states with transition.
Step 10 Forms, Editors & Standard Header Cards
Guiding Questions: Should multi-field editing always use dedicated pages instead of modals? What is the standard header card layout for every form page (back button, title, autosave badge, action buttons)? How are form inputs grouped into sections? What is the responsive grid layout?
Generate the "Forms, Editors & Standard Header Cards" section for AGENTS.md.
Specifications:
1. Modal Ban: For editors with more than one field, never use modals. Always use a dedicated view/page.
2. Standard Header Card: Every form/editor page must feature:
- Circular back button [e.g. w-9 h-9 rounded-full with ring styling]
- Page title (heading font, bold) and descriptive subtitle
- Autosave/Status Badge on edit views: saved (green), saving (spinner), unsaved (amber), error (red)
- Primary action buttons on the right side
3. Section Grouping: Group form inputs into distinct card panels with uppercase tracking-widest section headers.
4. Responsive Layout: [e.g. 2-column input section + 1-column sidebar for metadata on large screens (grid-cols-1 lg:grid-cols-3)]
5. Custom Selects: [e.g. Native HTML select elements are forbidden; mandate custom styled dropdown components matching design tokens]
Step 11 Notifications, Dialog Bans & In-Flight Guards
Guiding Questions: Should the agent ever use alert(), confirm(), or
prompt()? What notification system should be used for success/error feedback? How are double-submissions prevented on form buttons?
alert(), confirm()) are
the most common agent shortcut. They cannot be styled,
block the entire browser thread, look completely unprofessional, and are impossible to automate in testing.
Without in-flight guards, rapid clicking on
save buttons creates duplicate database records.
Generate the "Notifications, Dialog Bans & In-Flight Request Guards" section for AGENTS.md.
Specifications:
1. Browser Dialog Ban: Never use vanilla browser dialogs (alert(), confirm(), prompt()). Always develop custom modal components.
2. Notification System: Implement a toast/notification system to inform users about success/error/warning events.
3. Confirmation Modals: Always use custom styled confirmation dialogs for destructive actions (delete, cancel).
4. In-Flight Mutation Guards: Every button triggering an async mutation (form submit, delete, status toggle) must:
- Bind to an isSubmitting/isLoading reactive state
- Be disabled while the request is in flight (:disabled="isSubmitting")
- Display a spinning icon (fa-spinner fa-spin)
- Prevent duplicate submissions from rapid clicking or repeated Enter keypresses
Include the exact code pattern for the in-flight guard button.
Step 12 Image Upload, Search-Select & Scrollable Containers
Guiding Questions: How should image upload components work (drag & drop, thumbnail gallery, reordering, default image selection)? How should search-select components work for assigning related entities using infinite scroll? Should scrollable containers have fade gradients?
<input type="file"> with no preview, no
drag-and-drop, and no client-side resizing — resulting in 8MB raw images being uploaded to the server. Without
search-select rules, assigning entities uses a basic dropdown that fails with 1,000+ options.
Generate the "Image Upload, Search-Select & Scrollable Containers" section for AGENTS.md.
Specifications:
1. Image Uploader Component:
- Support both single and multiple image uploads based on module needs
- Drag and drop with hidden original file input
- Thumbnail gallery above the drop zone: set default image, reorder, delete, view
- If default image is deleted, auto-set a new default
- On upload, resize to maximum [e.g. 1500x1500px] while keeping original aspect ratio
2. Search-Select Components:
- Dedicated search component with real-time search input filtering across key properties
- Scrollable area displaying [e.g. 20 items at a time] using infinite scroll
3. Scrollable Containers:
- Any container with overflow scroll must implement a bottom fade/gradient that disappears when scrolled to the bottom
- [e.g. In Vue, use @scroll listener and dynamic classes based on scroll position]
Step 13 Router Guards, Auth Synchronization & Mobile Webapp
Guiding Questions: How does the frontend router guard protect authenticated routes? How is the initial user auth state synchronized before route evaluation? How should the app be prepared for mobile webapp use on iOS and Android? Should datetime formatting be centralized?
Generate the "Router Guards, Auth Sync & Mobile Webapp" section for AGENTS.md.
Specifications:
1. Navigation Guards: [e.g. Implement router.beforeEach that coordinates with auth store:
- Check if user auth has been initialized (authStore.isInitialized)
- If not, await /users/me/ response before evaluating route permissions
- Routes with meta: { requiresAuth: true, permission: '...' } must verify auth and user permissions
- Unauthorized access redirects to Access Denied or Dashboard view]
2. Component Breakdown: [e.g. Always break down modules into as many reusable components as possible]
3. Mobile Webapp: Always prepare the project for iOS/Android webapp use (viewport meta, touch optimizations, manifest).
4. DateTime Display: [e.g. Format dates exclusively at display layer using centralized helpers in utils.js that convert UTC to local timezone using Intl.DateTimeFormat. When sending dates to backend, always convert to UTC ISO 8601 strings.]
Step 14 Integrations: AI, Payments, Email & Third-Party Services
Guiding Questions: Which AI provider is used for generative features? Which payment processor? How is email configured? Are AI model identifiers stored in environment variables or hardcoded? Should the agent always consult the latest docs before implementing?
.env, making it impossible to switch
models without redeploying code.
Generate the "Integrations & Third-Party Services" section for AGENTS.md.
Rules:
1. AI Features: [e.g. Always use Google Gemini. Always search for the actual model's dev docs before starting development. Model identifiers must be stored in .env, never hardcoded.]
2. Payments: [e.g. Always use Stripe when payment or subscription functionality is needed.]
3. Email: [e.g. Configure SMTP using environment variables with sensible defaults. Include example .env settings for EMAIL_HOST, EMAIL_PORT, EMAIL_USE_TLS, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, DEFAULT_FROM_EMAIL, SITE_HOST]
4. Authentication: [e.g. Always ask the developer whether they want raw Django session-based login or Firebase Auth. If Firebase, connect it with the native AbstractUser model.]
Include concrete .env example blocks and settings.py integration code for email.
Step 15 Version Control, Testing, Documentation & Deployment
Guiding Questions: Should the agent automatically commit to git? What testing CLI commands can the agent run? Why are automated browser tests forbidden? Where does documentation live? How is deployment documented? Should a help system be created?
git commit and
git push on every change, creating hundreds of meaningless commits and potentially pushing
broken code to production. Without browser testing bans, agents launch headless Chrome instances that hang
indefinitely. Without deployment documentation rules, the agent omits critical ownership/permission
setup instructions for SQLite, media folders, and .env files.
Generate the "Version Control, Testing Boundaries, Documentation & Deployment" section for AGENTS.md.
Rules:
1. Git Version Control:
- Initial Setup: [e.g. git init, create initial commit, publish to private GitHub repo]
- Ongoing Commits: [e.g. NEVER commit or push automatically after initial setup. Developer handles VCS.]
- Gitignore: [e.g. Always include /media/, **/migrations/* (except __init__.py), venv/, .env]
2. Testing Boundaries:
- Browser Testing: STRICTLY FORBIDDEN. No Playwright, Puppeteer, Selenium, or headless browsers. Human developer tests visually.
- CLI Checks: [e.g. Permitted and encouraged: manage.py check, manage.py test, eslint, tsc --noEmit]
- Seed Scripts: Must exercise real service methods and API endpoints, not raw database inserts.
3. Documentation:
- Location: [e.g. Always in doc/ folder]
- Codebase Index: [e.g. Always consult doc/codebase_index.md before writing new code]
- Updates: [e.g. Update docs on major system changes]
4. Deployment Documentation:
- [e.g. Describe SFTP workflow where frontend dist/ is built locally and uploaded. Include Apache config, ownership/permissions for SQLite, media, .env.]
5. Help System: [e.g. Build static HTML help system in frontend/public/help/ with contextual HelpTooltip components at the final stage of development.]
How to Verify & Stress-Test Your Rulebase
5.1 Static Verification: The Adversarial Auditor Prompt
Before trusting your rulebase on live features, feed it to an advanced LLM (e.g. Gemini 1.5 Pro or Claude 3.5 Sonnet) using this adversarial prompt to uncover contradictions, vague phrasing, and missing error invariants:
You are a Principal Software Architect and AI Prompt Engineer specializing in autonomous developer agent steering.
Analyze this draft developer agent rulebase (AGENTS.md) with extreme adversarial rigor:
1. Contradictions: Are there any conflicting directives across different sections?
2. Ambiguities: Where have I used vague adjectives ("clean", "modern", "proper", "optimal") without defining concrete technical invariants or metrics?
3. Blind Spots & Missing Guardrails: What critical development failure modes (e.g., race conditions, migration lockouts, error response envelopes, secret leaks) have been omitted?
4. Token Efficiency: Which sentences contain redundant fluff that should be condensed to improve attention weight?
5. Rationale Strength: Are there dogmatic commands lacking technical "Why" explanations?
Here is my draft rulebase:
[PASTE YOUR DRAFT AGENTS.MD HERE]
5.2 The Empirical Crucible Test
The ultimate test of an agent rulebase is empirical execution. Create a fresh git branch and prompt your agent with a non-trivial CRUD feature:
Implement a complete "Warehouse Inventory Management" module:
1. Backend model: Product (sku, name, category, stock_quantity, unit_price, status, image).
2. Backend API: List with pagination, search, sorting; Create; Update; Delete; Details.
3. Frontend Table: View products with search, sorting, status badges, and action icons.
4. Frontend Form: Dedicated editor page to create and edit products with image upload.
Follow all workspace rules in AGENTS.md strictly.
5.3 The 10-Point Compliance Audit Scorecard
Score the agent's output against this checklist. Any failure indicates a rule that requires sharpening:
| # | Check Item | Pass Indicator | Failure Indicator |
|---|---|---|---|
| 1 | Folder Hygiene | Files created strictly inside allowed directories. | Created temp/, scripts/, or root clutter. |
| 2 | Migration Safety | Ran checks; did NOT run makemigrations. |
Generated new migration files in git. |
| 3 | Trailing Slashes | All backend paths & Axios calls end with /. |
axios.post('/api/products') (missing slash). |
| 4 | Auth Decorator | Used custom @api_login_required (401 JSON). |
Used default @login_required (302 HTML redirect). |
| 5 | JSON Signatures | Matched standard {'products': [...], 'pagination': ...}. |
Returned flat array or `{data: [...]}`. |
| 6 | Atomic Integrity | Wrapped multi-table writes in transaction.atomic. |
Plain save calls without transaction rollback protection. |
| 7 | No UI Emojis | FontAwesome Free icons used exclusively. | Used 📦 or ✅ in buttons or labels. |
| 8 | Custom Selects | Used custom styled select component. | Used native browser <select> element. |
| 9 | Dedicated Editor | Navigated to dedicated page with standard header card. | Popped up a modal dialog for multi-field editing. |
| 10 | In-Flight Guard | Save button disabled with spinner during request. | Button clickable multiple times causing duplicate rows. |
5.4 The "Bug-to-Rule" Hardening Loop
AGENTS.md, and
commit it. Over time, your rulebase becomes an impenetrable immune system tailored to your team's exact
standards.