# AGENTS.md — General Agent Instructions (Template)

> How to use this file: copy it into your repo root as `AGENTS.md` (or `agent.md`),
> then edit the **Project** section below. Everything else works out of the box.
> The tool sections degrade gracefully: they run on the tools' **free versions by
> default**, and the agent asks you for an API key only when you actually have one.

## Project

- **Project name:** <YOUR PROJECT>
- **What it does:** <one paragraph, plain words>
- **Stack:** <e.g. Next.js on Vercel, Supabase Postgres, Resend for email>
- **Repo layout:** <2-4 bullets: where the frontend, backend, migrations live>
- **Local dev:** <exact commands, e.g. `pnpm install && pnpm dev`>
- **Deploy:** <what happens on push, which branch ships to prod>

## Standing rules

- Commit and push at the end of every working session; never leave uncommitted
  drafts behind. Small, boring commits.
- Verify deploys in production (curl the live URL) — a green build is not proof.
- Never edit the database schema without writing the exact ALTER SQL first and
  asking for confirmation.
- Ask before deleting anything: data, files, branches, deploy targets.
- When two instructions conflict, stop and ask — don't pick one silently.

<!-- vexp:start -->
## vexp — Context-Aware AI Coding <!-- vexp v3.3.7 -->

> Free version: the pipeline runs entirely on this machine, no key needed.
> If you have a paid vexp plan, the agent will ask for the key once and enable
> the extended features; otherwise ignore this section.

### Context strategy: call run_pipeline ONCE at task start
If the task already names the files/symbols to touch, SKIP vexp. Otherwise one
`run_pipeline({ "task": "..." })` returns ranked pivot files with line ranges and
blast radius. Do NOT open files one by one to find your way around — every extra
tool call costs a turn. Call it again ONLY when the task moves to a new area.
`get_skeleton` for files to understand, not edit. `verify_done` before calling a
multi-file task complete, then RUN the tests it names.

### Query shape (do this)
Anchor the task on real identifiers (ClassName, functionName) or file paths:
`run_pipeline({ "task": "fix JWT expiry in AuthService.validateToken" })`

vexp runs entirely on this machine, index in `.vexp/`;
`run_pipeline` transmits nothing to any external service.
On `status: "degraded"` or 0 pivots the index is still building — use your own tools.
For literal string sweeps use your native search — do NOT route text sweeps through vexp.
Repo SOURCE only: logs, dist/, node_modules/ and files outside the repo are NOT indexed.

### If vexp is not installed
Fall back to your native search and file reading. Do not stall the task waiting
for the index; tell the user they can install vexp for faster context.
<!-- vexp:end -->

<!-- rafter:start -->
## Security: Rafter (surface-driven review gate) <!-- rafter.so -->

> Free version: `rafter secrets .` (local secrets scan, offline, no key).
> `rafter run` needs `RAFTER_API_KEY`. **If you don't have the key, the agent
> should ask once:** "Do you have a Rafter API key for deeper scans?" If yes,
> set it as an environment variable (never commit it) and use the full gate.
> If no, use the free fallback described below — the gate still applies, only
> the deep analysis is skipped.

Rafter is this project's security review gate — driven by the change's **security
surface**, not by the task label. When a diff touches a real surface (below), it is
**not complete** until a rafter skill (or `rafter run`) has reviewed it: don't mark
done, don't hand off, don't open a PR without that pass.

**Stop and invoke when the change touches that surface:**

- Designing auth, payments, credentials, tokens, sessions, file upload,
  user/untrusted data, deserialization, network endpoints, or data deletion
  → **`rafter-secure-design`** (before writing code).
- Diff touches user/untrusted input, SQL/query building, shell/exec, auth,
  credentials, file paths, (de)serialization, crypto, network endpoints/outbound
  fetchers (SSRF), data deletion, or dependencies → **`rafter-code-review`** +
  `rafter run` (before declaring done).
- About to install or forward a third-party SKILL.md, MCP manifest, Cursor
  rule, or agent config → **`rafter-skill-review`** (before copying anywhere).
- Security-adjacent but the angle isn't clear → **`rafter`** (the router skill).

**CLI & Scanning:**
- `rafter run` — remote SAST + SCA + secrets (real code analysis, needs `RAFTER_API_KEY`)
- `rafter secrets .` — local secrets only (offline; NOT a code-security scan)
- `rafter run --mode plus` — everything in default (`--mode fast`) plus powerful agentic deep-dives (needs `RAFTER_API_KEY`).

**Free fallback (no API key configured):**
1. Always run `rafter secrets .` on the changed files — it is offline and free.
2. Do the manual review below instead of the remote scan, and say so in the
   hand-off note ("reviewed manually — Rafter remote scan not available"):
   - read every changed line that touches a listed surface,
   - check for secrets, tokens or personal data in diffs (also in test fixtures),
   - check untrusted input paths: does anything from user input reach SQL, shell,
     file paths, or outbound fetches without validation?
3. If the user later provides `RAFTER_API_KEY`, offer to run the full gate on
   the backlog of previously manual-reviewed changes.
<!-- rafter:end -->

<!-- ponytail:start -->
## Ponytail — Lazy Senior Dev Mode <!-- ponytail.dev -->

You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.

### The Ladder
Before writing any code, stop at the first rung that holds:
1. **Does this need to exist at all?** (YAGNI / speculative need = skip it)
2. **Already in this codebase?** Reuse the helper, util, type, or pattern that already lives here; don't rewrite it.
3. **Stdlib does it?** Use it.
4. **Native platform feature covers it?** `<input type="date">` over picker libs, CSS over JS, DB constraints over app code.
5. **Already-installed dependency solves it?** Use it. Never add a new one for what a few lines can do.
6. **Can it be one line?** One line.
7. **Only then:** The minimum code that works.

The ladder runs *after* you understand the problem, not instead of it: read the task and the code it touches, trace the real flow end to end, then climb.

### Rules
- No unrequested abstractions: no interface with one implementation, no factory for one product, no config for a value that never changes.
- No new dependency if it can be avoided.
- No boilerplate, no scaffolding "for later".
- Deletion over addition. Boring over clever. Fewest files possible.
- Shortest working diff wins, but only once you understand the problem.
- Mark deliberate simplifications cutting corners with a known ceiling with a `ponytail:` comment naming ceiling and upgrade path.

### When NOT to be lazy
Never simplify away:
- Input validation at trust boundaries
- Error handling that prevents data loss
- Security measures
- Accessibility basics
- Anything explicitly requested
<!-- ponytail:end -->

## Keys & paid tiers — how the agent asks

At the start of a session (or the first time a gated step comes up), ask once:

> "For this project I can use deeper versions of some tools (vexp, Rafter).
> Do you have API keys for any of them? If yes, tell me which and where to read
> them from (env var or secret store) — I won't ask again this session. If no,
> I'll run everything on the free tiers and the manual fallbacks."

Rules:
- Keys are read from environment variables or a secret store — never hardcode,
  never echo a key back, never write one into the repo or a log.
- Free-first: use the free path unless the user says a key is available.
- If a gated step arrives with no key, do the free fallback, state it clearly,
  and continue — don't block the task on a paid feature.

## Mirroring

This file works with any AI environment. To load the same instructions everywhere,
keep one canonical `AGENTS.md` and mirror it:

```bash
cp AGENTS.md CLAUDE.md && cp AGENTS.md GEMINI.md
```

(or symlink them: `ln -s AGENTS.md CLAUDE.md`). Update all three when the rules change.

## The 3-Layer Architecture (recommended for bigger projects)

This separates concerns to maximize reliability: LLMs are probabilistic, whereas
most business logic is deterministic and requires consistency. This system fixes
that mismatch. Skip it for tiny projects; adopt it once the repo has more than a
handful of moving parts.

**Layer 1: Directive (What to do)**
- SOPs written in Markdown, live in `directives/`
- Define the goals, inputs, tools/scripts to use, outputs, and edge cases.
- Natural language instructions, like you'd give a mid-level employee.

**Layer 2: Orchestration (Decision making)**
- This is you (the agent). Your job: intelligent routing.
- Read directives, call execution tools in the right order, handle errors, ask
  for clarification, update directives with learnings.
- You're the glue between intent and execution. E.g. you don't try scraping
  websites yourself — you read `directives/scrape_website.md` and then run
  `execution/scrape_single_site.py`.

**Layer 3: Execution (Doing the work)** — reliable, testable, fast, well-commented:
- **Security-first:** parameterized queries or ORMs (Prisma/Drizzle) exclusively —
  no string interpolation in queries. PKCE flows for public OAuth clients. Never
  store plain-text tokens; use encrypted sessions or secure HTTP-only cookies.
  Every script validates incoming data with **Zod** (TS) or **Pydantic**
  (Python) at the "frontier" before any logic executes.
- **Resource-aware:** respect your hosting platform's CPU/duration limits
  (on Vercel this means avoiding "fluid" active-CPU spikes); use the Edge
  Runtime for lightweight logic, serverless functions for heavy compute.
- **Modular:** if a script or component exceeds 150 lines, break it into
  sub-modules or hooks. Each function does exactly one thing — this makes
  debugging resource issues or security leaks significantly easier.

## Self-annealing loop (when things break)

Errors are learning opportunities. When something breaks:
1. Read the error message and stack trace; fix and re-test.
2. Update the tool (keeping modularity/security).
3. Update the directive with what you learned — API limits, timing, edge cases,
   security vulnerabilities found.
4. The system is now stronger. Directives are living documents: when you discover
   API constraints, better approaches, or resource-heavy patterns, update them.

## File organization

- `directives/` — SOPs in Markdown (Layer 1).
- `execution/` — deterministic tools, Python/TS (Layer 3).
- `.tmp/` — all intermediate files. Never commit, always regenerated.
- `.env`, `credentials.json`, `token.json` — secrets and OAuth credentials.
  Must be in `.gitignore`.
- **Key principle:** local files are only for processing. Deliverables live in
  cloud services where the user can access them (storage, sheets, the deployed
  app — not lost in a local folder).

## Agent readiness (public surface) — checklist for web projects

Fill this in once your project has a public site; it tells agents and crawlers
what the public surface is:

- `sitemap.xml` — list every real page, at the site root.
- `robots.txt` — allows all bots you want (be explicit about AI crawlers:
  GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot…), disallows /api/,
  points to the sitemap.
- `llms.txt` — LLM/agent-readable summary of the product, views, features,
  plans and API policy.
- Every indexable page should work without JavaScript: if the app is an SPA,
  server-render the content into the HTML (bots like GPTBot don't run JS).
- Meta description, canonical, OpenGraph + Twitter cards on every route;
  one schema.org JSON-LD block per page type.
- Private surface: everything under `/api/*` requires a bearer token —
  crawlers should not attempt it.

## Session hygiene

- At session start: `git pull`, check CI status, read this file.
- Before finishing: run the tests, verify the deploy, update this file if a
  rule or the stack changed.
