ai-guide.md

Universal Specification for AI-Native Resources

A structured approach to documentation that prioritizes intent-to-action mappings over comprehensive reference material, enabling AI agents to locate necessary information efficiently.

1. Overview

ai-guide.md is a documentation specification designed to make APIs, libraries, databases, and codebases immediately usable by AI agents. Rather than requiring agents to parse extensive documentation and infer appropriate actions, ai-guide.md provides direct mappings between user intent and implementation.

Design Principle

An AI agent should locate the necessary implementation details in minimal tokens. This specification emphasizes actionable information over comprehensive explanation: "how do I accomplish X?" rather than "what are all possible operations?"

Action Reference

Direct mapping from user intent to specific implementation. "Need to detect VPN usage?" maps to exact endpoint or function call.

Common Patterns

Pre-composed sequences for typical multi-step workflows. Production-ready implementations for standard use cases.

Mental Models

Concise explanations of system behavior and constraints. Core concepts without implementation details.

Known Issues

Critical failure modes and common implementation errors. Edge cases that typically require debugging time.

2. Rationale

2.1 Current State

AI agents currently expend significant context window capacity parsing documentation designed for human consumption:

2.2 Proposed Approach

ai-guide.md restructures the documentation model:

3. Getting Started

3.1 Basic Template

Begin with this template structure and populate with resource-specific information:

# ai-guide.md - [Your Resource Name]

## Action Reference
- Need to [outcome]? → [specific action/endpoint/function]
- Need to [outcome]? → [specific action/endpoint/function]
- Need to [outcome]? → [specific action/endpoint/function]

## Common Patterns
1. [Use case name]: [step 1] + [step 2] + [step 3]
2. [Use case name]: [step 1] + [step 2]

## Mental Model
[One sentence explaining how this actually works]

## Known Issues
- Don't [common mistake]: [why/consequence]
- Always [required step]: [why]

## Examples
```[language]
[Minimal working code that runs immediately]
```

3.2 Implementation Steps

  1. Identify common operations: List the most frequently performed operations with your resource
  2. Create direct mappings: Map each operation to the specific code, endpoint, or function required
  3. Document multi-step patterns: Capture sequential operations that users typically perform together
  4. List failure modes: Document the most common implementation errors and their consequences
  5. Provide working example: Include one complete, executable example

Scope Constraint

Do not attempt comprehensive coverage. Focus on frequent operations rather than documenting every feature. ai-guide.md prioritizes action over understanding.

4. Technical Specification

4.1 Action Reference (Required)

Maps user intent to implementation in simple conditional format. Each entry should be immediately actionable.

## Action Reference
- Need to [specific outcome]? → [exact action]
- Need to [specific outcome]? → [exact action]

Examples:

- Need to authenticate? → POST /auth/login with {email, password}
- Need to list users? → GET /users?limit=20
- Need to upload file? → POST /files with multipart/form-data

4.2 Common Patterns (Required)

Pre-composed sequences for typical multi-step workflows. Focus on actual usage rather than theoretical capabilities.

## Common Patterns
1. [Use case]: [step 1] + [step 2] + [step 3]
2. [Use case]: [step 1] + [step 2]

Examples:

E-commerce checkout: validate cart + calculate tax + create payment intent + confirm order

User onboarding: create account + send verification email + log first session

4.3 Mental Model (Optional, Recommended)

Concise explanation of system behavior and constraints.

## Mental Model
[How this thing actually works in one sentence]

Examples:

"Users are soft-deleted, posts are immutable, comments are nested 3 levels max."

"All writes go to primary DB, reads can use replicas, cache invalidates on write."

4.4 Known Issues (Optional, Recommended)

Critical failure modes and edge cases. Information typically discovered through debugging or found in issue trackers.

## Known Issues
- Don't [common mistake]: [why/consequence]
- Always [required step]: [why]
- Never [antipattern]: [why]

Examples:

Don't call /sync endpoint more than once per minute: rate limited, will return 429

Always check inventory before showing "in stock": inventory updates are async

Never store passwords in users table: use auth.passwords with bcrypt

4.5 Examples (Optional)

Minimal, executable code samples. Should run without modification. Keep examples concise and focused on common cases.

## Examples
```[language]
[Working code]
```

5. Discovery and Placement

For ai-guide.md to function, AI agents must be able to locate the specification. Standard placement locations enable reliable discovery.

5.1 Standard Locations

Resource Type Location Example
Web APIs/SaaS /.well-known/ai-guide.md https://api.stripe.com/.well-known/ai-guide.md
Code Repositories /ai-guide.md (root) github.com/user/repo/ai-guide.md
npm Packages package.json metadata "aiGuide": "./ai-guide.md"
Python Packages pyproject.toml URL [project.urls] "AI Guide" = "..."

5.2 Discovery Mechanisms

5.2.1 robots.txt (Recommended)

User-agent: *
Disallow: /admin

# AI Agent Resources
AI-Guide: /.well-known/ai-guide.md

5.2.2 HTTP Headers

Link: </.well-known/ai-guide.md>; rel="ai-guide"
X-AI-Guide: /.well-known/ai-guide.md

5.2.3 HTML Meta Tag

<link rel="ai-guide" href="/.well-known/ai-guide.md" />

5.2.4 OpenAPI/Swagger Extension

openapi: 3.0.0
info:
  title: My API
  x-ai-guide: /.well-known/ai-guide.md

5.3 Discovery Flow

AI Agent encounters resource
    ↓
Check cache (seen before?)
    ↓
Try /.well-known/ai-guide.md
    ↓
Check HTTP headers
    ↓
Parse robots.txt
    ↓
Check repo root /ai-guide.md
    ↓
Check package metadata
    ↓
Fallback: search /docs/ai-guide.md

5.4 Existing Implementations

Review implementations in production environments:

Search GitHub for ai-guide.md files

6. Reference Implementations

6.1 REST API (Payment Processing)

# ai-guide.md - PaymentAPI

## Action Reference
- Need to create payment? → POST /payments with {amount, currency, customer_id}
- Need to refund? → POST /payments/{id}/refund with {amount}
- Need to check status? → GET /payments/{id}
- Need payment history? → GET /customers/{id}/payments?limit=50
- Need to save card? → POST /payment-methods with {customer_id, card_token}

## Common Patterns
1. Simple checkout: create customer + create payment + confirm
2. Subscription: create customer + attach payment method + create subscription
3. Refund flow: get payment + verify refundable + create refund + notify customer
4. Saved card payment: list payment methods + create payment with method_id

## Mental Model
All payments are two-phase: create (reserves) then confirm (captures). 
Refunds are async and may take 5-10 days. Always webhook for final status.

## Known Issues
- Don't create payment without idempotency key: duplicate charges possible
- Always verify webhook signatures: prevents spoofing
- Never store raw card numbers: use tokens from client-side SDK
- Check payment.status before refunding: only "succeeded" can be refunded
- Amount must be in cents: $10.00 = 1000

## Examples
```javascript
// Create and confirm payment
const payment = await api.post('/payments', {
  amount: 1000, // $10.00
  currency: 'usd',
  customer_id: 'cus_123',
  idempotency_key: uuid()
});

await api.post(`/payments/${payment.id}/confirm`);
```

6.2 Database Schema

# ai-guide.md - E-commerce Database

## Action Reference
- Need active products? → SELECT * FROM products WHERE status='active'
- Need product with category? → JOIN products p, categories c ON p.category_id=c.id
- Need to check stock? → SELECT quantity FROM inventory WHERE product_id=?
- Need to create order? → INSERT INTO orders + INSERT INTO order_items (transactional)
- Need to update price? → UPDATE products SET price=? WHERE id=?

## Common Patterns
1. Product listing: active products + category join + inventory check + limit 20
2. Product detail page: product + category + inventory + related products (same category)
3. Checkout: validate cart + check inventory + create order + decrement inventory
4. Order history: orders + order_items join + product details

## Mental Model
Products soft-delete (status='inactive'). Inventory updates via triggers.
Orders are immutable once placed. Prices stored in cents.

## Known Issues
- Don't DELETE products: set status='inactive' (foreign key constraints exist)
- Always wrap order creation in transaction: order + items must be atomic
- Check inventory.quantity > 0 before showing "in stock": no negative stock
- Price is in cents: multiply by 100 before INSERT
- category_id must exist: validate against categories table first

## Examples
```sql
-- Get products for listing page
SELECT p.id, p.name, p.price/100 as price_dollars, c.name as category,
       i.quantity > 0 as in_stock
FROM products p
JOIN categories c ON p.category_id = c.id
LEFT JOIN inventory i ON p.id = i.product_id
WHERE p.status = 'active'
LIMIT 20;
```

6.3 React Component Library

# ai-guide.md - DesignSystem Components

## Action Reference
- Need button? → <Button variant="primary">Text</Button>
- Need form input? → <Input value={state} onChange={setState} label="Label" />
- Need modal? → <Modal isOpen={bool} onClose={fn}>...</Modal>
- Need table? → <DataTable data={array} columns={config} />
- Need loading? → <Spinner /> or <Button loading={true} />
- Need icons? → <Icon name="check" size={20} />

## Common Patterns
1. Form with validation: Form + Input with error + Button with loading
2. Confirm dialog: Modal + ModalBody with question + danger Button
3. Data table with actions: DataTable + custom column render for buttons
4. Loading states: Spinner for page, Button loading for actions

## Mental Model
All components controlled (pass value + onChange). Theme required at root.
Variants control styling. No uncontrolled components.

## Known Issues
- Don't forget ThemeProvider at app root: components won't style correctly
- Never use defaultValue: always controlled (value + onChange)
- Modal needs isOpen AND onClose: won't close without onClose handler
- Icon names must match exactly: check /src/icons/ directory for list
- Form doesn't auto-prevent default: add onSubmit with e.preventDefault()

## Examples
```jsx
// Complete login form
<Form onSubmit={handleSubmit}>
  <Input 
    label="Email" 
    type="email"
    value={email} 
    onChange={setEmail}
    error={errors.email}
  />
  <Input 
    label="Password" 
    type="password"
    value={password} 
    onChange={setPassword}
  />
  <Button type="submit" loading={submitting}>
    Login
  </Button>
</Form>
```

6.4 CLI Tool

# ai-guide.md - DeployTool CLI

## Action Reference
- Need to deploy? → deploy --env production --tag v1.2.3
- Need to rollback? → rollback --env production --version 1
- Need to check status? → status --env production
- Need to view logs? → logs --env production --tail 100
- Need to run migrations? → migrate --env production --direction up

## Common Patterns
1. Standard deploy: build + test + deploy --env staging + test + deploy --env production
2. Hotfix deploy: deploy --env production --tag hotfix-xxx --skip-tests
3. Rollback flow: status + rollback --version N + verify + notify team
4. Database migration: migrate up + verify + deploy app

## Mental Model
All commands idempotent. Production requires confirmation.
State stored in S3, changes are logged to CloudWatch.

## Known Issues
- Don't deploy without --tag: will fail (tag required for production)
- Always check status before rollback: need to know previous version
- Never run migrate down in production: irreversible, requires backup restore
- Can't rollback more than 5 versions: old artifacts deleted
- Production commands prompt for confirmation: use --yes to skip in CI

## Examples
```bash
# Deploy to production
deploy --env production --tag v1.2.3

# Rollback one version
rollback --env production --version 1

# Check current status
status --env production
```

7. Implementation Guidelines

⚠️ Critical: Review Before Implementation

Before creating or deploying ai-guide.md files, review security, maintenance, and legal considerations to avoid common pitfalls.

Read Implementation Considerations →

7.1 For Resource Maintainers

  1. Create ai-guide.md using provided template
  2. Place in /.well-known/ or repository root
  3. Add to robots.txt for agent discovery
  4. Add HTTP header if API endpoint (optional)
  5. Validate with AI agents (test with Claude, GPT, or similar)

7.2 For AI Tool Developers

  1. Implement discovery flow checking standard locations in priority order
  2. Parse ai-guide.md when agent encounters resource
  3. Prioritize ai-guide.md over general documentation in context
  4. Cache parsed specifications for performance

7.3 For Developers

  1. Check for ai-guide.md before parsing comprehensive documentation
  2. Contribute ai-guide.md to frequently-used libraries and tools
  3. Request ai-guide.md from library maintainers

8. Frequently Asked Questions

8.1 How does this differ from AGENTS.md?

AGENTS.md specifies project-specific coding conventions and development workflows. ai-guide.md provides usage specifications for resources (APIs, libraries, databases). These specifications serve complementary purposes: AGENTS.md defines "development practices within this project," while ai-guide.md defines "how to use this resource."

8.2 Should existing documentation be replaced?

No. Comprehensive documentation should be maintained. ai-guide.md serves as a quick-reference specification for AI agents, analogous to a reference card that accompanies full documentation.

8.3 How to handle APIs with many endpoints?

Focus on the most frequently-used operations rather than attempting comprehensive coverage. If the resource is too complex to summarize effectively, consider whether it could be simplified or modularized into smaller, more focused specifications.

8.4 How to maintain ai-guide.md currency?

Treat it as you would a README file. Update when introducing breaking changes or adding significant features. The constrained scope makes maintenance less resource-intensive than comprehensive documentation.

8.5 Can multiple ai-guide.md files coexist?

Yes. Large projects may include one specification at the repository root and domain-specific specifications in subdirectories. AI agents will use the specification closest to the relevant resource.

8.6 What about internal/private resources?

ai-guide.md functions equally well for internal APIs and tools. Place it in internal documentation or repository. Discovery mechanisms operate identically in private contexts.

8.7 Is validation tooling available?

Not currently. The specification is intentionally flexible to encourage adoption. As implementation patterns emerge, optional validation tools may be developed.

8.8 How much detail should be included?

Include enough detail for an AI agent to implement the operation without additional context. The goal is actionability, not completeness. When in doubt, test with actual AI agents and refine based on their performance.