mex documentation
A structured reference covering installation, navigation routing, CLI commands, and drift detection. Everything you need to prevent AI agent context loss.
1. Installation
Prerequisites
- Node.js (v18 or later) — required for the CLI engine (drift detection, sync, scanner)
- Git — required for cloning mex and for staleness detection
- Bash-compatible shell — required for the shell scripts (
setup.sh,sync.sh,update.sh). Works out of the box on macOS and Linux. - An AI coding tool — Claude Code, Cursor, Windsurf, or GitHub Copilot. mex generates context files that these tools read automatically
Setup
From your project root:
The setup script does the following, in order:
- Builds the CLI
Runsnpm installandnpm run buildinside.mex/. If Node.js isn't available, it skips this step and continues (the scaffold still works, you just won't have CLI commands). - Detects project state
Scans for source files to determine if this is an existing codebase, a fresh project, or a partially populated scaffold. - Copies tool config
Asks which AI tool you use and copies the appropriate config file to your project root (CLAUDE.md,.cursorrules,.windsurfrules, or.github/copilot-instructions.md). You can select multiple tools. All config files contain the same content — they point the AI to read.mex/ROUTER.mdat the start of every session. - Pre-scans the codebase
If the CLI was built successfully and source files exist, runsmex init --jsonto generate a structured brief of your codebase (entry points, dependencies, folder structure, tooling). This brief is fed to the AI so it doesn't have to explore the filesystem itself (~5-8k tokens vs ~50k). - Populates the scaffold
If Claude Code is installed and was selected as the tool, it launches an interactive Claude session with a population prompt. Otherwise, it prints the prompt for you to paste into your AI tool. The AI reads your codebase (or the scanner brief) and fills every scaffold file — architecture, stack, conventions, decisions, setup, patterns.
--dry-run flag to preview what would happen without making any changes.Using the mex command
After setup, the CLI is available at node .mex/dist/cli.js. To use the shorter mex command instead:
This creates a global symlink. After linking, you can run mex check, mex sync, etc. from your project root.
Updating mex
To pull the latest mex infrastructure without touching your populated content:
This fetches the latest version from GitHub and updates only infrastructure files — shell scripts, CLI source code, package.json, test files, and tool configs. Your content files (ROUTER.md, AGENTS.md, context files, patterns) are never overwritten. If CLI source files changed, it automatically rebuilds the CLI.
For contributors / forking
If you're forking mex or working on the CLI itself:
The CLI entry point is src/cli.ts. It builds to dist/cli.js via tsup.
Ready to build? Check out the Contributing Guide for good first issues and PR guidelines.
2. How It Works
The Problem
AI coding agents start every session with zero memory. They don't know what they built yesterday, what conventions were agreed on, or what's currently broken. Developers compensate by stuffing everything into a single config file (like CLAUDE.md), but that floods the context window, wastes tokens, and degrades the agent's attention. Meanwhile the project changes and nobody updates the docs — the agent's understanding drifts from reality.
The Solution
mex is two things:
- A structured markdown scaffold — a set of navigable files that give AI agents persistent project knowledge
- A CLI — drift detection and targeted sync that keeps those files honest
The scaffold lives in a .mex/ directory inside your project. The agent doesn't load everything at once — it navigates to only what it needs for the current task, keeping token usage minimal.
The Scaffold Files
AGENTS.md Project Anchor
The always-loaded identity file. Contains:
- What This Is — one-sentence description of the project
- Non-Negotiables — hard rules the agent must never violate (3-7 items). Not preferences — rules. Things that cause real damage if broken
- Commands — exact commands to dev, test, lint, build
- Scaffold Growth — instruction to update the scaffold after every task
This file is kept deliberately small (target: under 150 tokens) so it can be loaded every session without cost concerns.
ROUTER.md Session Bootstrap
The navigation hub. Read at the start of every session. Contains:
- Current Project State — what's working, what's not built yet, known issues. This is the primary drift prevention mechanism — it re-grounds the agent every session
- Behavioural Contract — the 5-step loop the agent follows for every task (see below)
- Routing Table — a lookup table that maps task types to the right context file:
Task type Load Understanding how the system works context/architecture.md Working with a specific technology context/stack.md Writing or reviewing code context/conventions.md Making a design decision context/decisions.md Setting up or running the project context/setup.md Any specific task Check patterns/INDEX.md
context/ Knowledge Files
Five files covering different dimensions of the project:
| File | What it contains |
|---|---|
| architecture.md | How the major pieces connect — system flow, component boundaries, external dependencies |
| stack.md | Technology choices and reasoning — language, framework, database, key libraries, and why each was chosen over alternatives |
| conventions.md | Naming conventions, code structure patterns, file organization rules |
| decisions.md | Append-only decision log — architectural choices with context and reasoning |
| setup.md | How to run the project locally — environment setup, dependencies, dev server, common issues |
Each context file has YAML frontmatter with:
triggers— keywords that indicate when this file should be loadededges— pointers to related fileslast_updated— when the file was last modified
The agent only loads the context files relevant to the current task. A developer fixing a bug loads architecture.md and maybe a debug pattern. A developer setting up their environment loads setup.md. No wasted tokens.
patterns/ Task-Specific Guides
Patterns are the accumulated wisdom of working on this project — the things you'd tell a teammate sitting next to you. Each pattern covers a repeatable task type and includes:
- Context — what to load or know before starting
- Steps — the workflow, in order
- Gotchas — things that go wrong, what to watch out for
- Verify — checklist to run after completing the task
- Debug — what to check when this task type breaks
patterns/INDEX.md is the lookup table — the agent checks it before starting any task. If a matching pattern exists, it follows it.
Patterns fall into four categories:
- Common tasks (add endpoint, add component)
- Integration patterns (external dependencies with gotchas)
- Debug/diagnosis (when something breaks at a boundary)
- Deploy/release workflows
The Behavioural Contract
Every task follows a 5-step loop defined in ROUTER.md:
- CONTEXT
Load the relevant context file(s) from the routing table. Checkpatterns/INDEX.mdfor a matching pattern. Narrate what's being loaded. - BUILD
Do the work. If a pattern exists, follow its steps. If deviating, state the deviation and why before writing code. - VERIFY
Loadcontext/conventions.mdand run the verify checklist item by item. Each item is stated explicitly with pass/fail — no summarizing. - DEBUG
If verification fails, checkpatterns/INDEX.mdfor a debug pattern. Follow it. Fix the issue and re-run VERIFY. - GROW
After completing the task:- If no pattern exists for this task type, create one and add it to INDEX.md
- If a pattern exists but was deviated from or a new gotcha was discovered, update it
- If any context file is now out of date, update it surgically
- Update "Current Project State" in ROUTER.md if the work was significant
The GROW step is what makes the scaffold compound over time. Setup seeds the initial knowledge, but real patterns come from real work. Every task has the potential to leave the scaffold smarter than it was before.
Edge System
Every scaffold file can declare edges in its YAML frontmatter — pointers to related files with conditions for when to follow them. This creates a navigable web rather than a flat list of files:
During setup, Pass 3 wires all edges — ensuring every context file has at least 2 edges and every pattern has at least 1. Edges are bidirectional where it makes sense.
Domain-Specific Context Files
If a project has domains complex enough that cramming them into architecture.md would make it too long or too shallow, mex creates additional context files. For example:
- A project with a complex auth system gets
context/auth.md - A data pipeline project gets
context/ingestion.md - A project with Stripe gets
context/payments.md
These are created during setup when the AI determines a domain has enough depth to warrant its own file. They use the same YAML frontmatter format and get added to the routing table in ROUTER.md.
3. CLI Commands
All CLI commands run from your project root (not from inside .mex/). The CLI locates the scaffold by walking up to the git root and looking for a .mex/ directory.
If you've run npm link, use mex <command>. Otherwise, use node .mex/dist/cli.js <command>.
mex check
Runs all 8 drift checkers against your scaffold files. Zero tokens, zero AI — purely deterministic analysis.
Output: Lists every issue grouped by file, with severity icons (✗ error, ⚠ warning, ℹ info) and a drift score out of 100.
The score starts at 100 and deducts points per issue: -10 per error, -3 per warning, -1 per info. Also reports total files checked.
| Flag | What it does |
|---|---|
| --quiet | One-line summary only. Example: mex: drift score 92/100 (1 warning) |
| --json | Full drift report as JSON — every issue with file, line number, severity, code, and message. Useful for CI pipelines or programmatic consumption. |
| --fix | Runs the check, then automatically jumps into sync if any errors are found. |
Exit code: Exits with code 1 if any errors are found, 0 otherwise. This makes it usable as a CI gate.
Score color coding: Green for 80+, Yellow for 50-79, Red for below 50.
mex sync
Detects drift, then builds targeted prompts for AI to fix only the broken scaffold files. Runs in a loop: check → fix → verify → repeat until clean.
How it works:
- Runs
mex checkinternally to find all issues - Groups issues by file and shows which files need attention (error & warning counts)
- Asks you to choose a mode:
- Interactive (default) — launches a Claude Code session with a combined prompt covering all broken files. You watch the agent fix them in real-time.
- Show prompts — prints the targeted prompt so you can paste it into any AI tool manually.
- Exit — stop and come back later.
- After the AI fixes files, re-runs the drift check automatically
- Shows the score change (e.g.,
Drift score: 72 → 95/100 (+23)) - If issues remain, asks whether to run another cycle
The sync prompt is precise — it includes the current file content, the specific issues found, filesystem context showing what actually exists (for missing path issues), and recent git diffs for referenced paths. The AI is instructed to fix only what's broken, not rewrite correct sections.
| Flag | What it does |
|---|---|
| --dry-run | Shows the targeted prompt that would be sent to AI, without executing. Useful for reviewing what sync would do. |
| --warnings | By default, sync only fixes files that have errors. This flag includes warning-only files as well. |
Filtering logic: By default, if a file has at least one error, all of its issues (errors and warnings) are included in the sync. Files with only warnings are skipped unless --warnings is passed.
mex init
Scans the codebase and generates a structured brief for AI consumption. This is what setup.sh runs internally during first-time setup.
The scanner analyzes five dimensions of the project:
| Scanner module | What it extracts |
|---|---|
| manifest | Dependencies, versions, scripts from package.json (or equivalent) |
| entry-points | Main entry files (e.g., src/index.ts, app.py) |
| folder-tree | Directory structure, excluding node_modules, .git, dist, etc. |
| tooling | Build tools, linters, formatters, CI config |
| readme | Existing README content |
Without --json, it wraps the brief in a prompt instructing the AI how to use it to populate the scaffold.
| Flag | What it does |
|---|---|
| --json | Outputs the raw scanner brief as JSON (no wrapper prompt). Useful for piping into other tools or debugging what the scanner found. |
mex watch
Installs a git post-commit hook that automatically runs mex check --quiet after every commit.
Behavior:
- 100/100 score: Stays silent (no output)
- Issues found: Prints the one-line summary after commit
- Appends gracefully if a hook already exists
- Marked with
# mex-drift-checkcomment
mex watch --uninstall
- Only hook file? Deletes it.
- Appended to existing hook? Removes exactly the mex block.
- Not installed by mex? Warns and skips.
mex commands
Quick-reference listing of all CLI commands and shell scripts with descriptions. Useful when you forget a flag or command name.
& shell scripts with descriptions.
Shell Scripts
These are bash scripts that run from your project root. They auto-build the CLI if needed. All support --help.
| Script | What it does |
|---|---|
| bash .mex/setup.sh | First-time setup — detects project state, copies tool config, scans codebase, launches AI to populate the scaffold. Supports --dry-run |
| bash .mex/sync.sh | Interactive menu — choose between check, sync, or exporting the sync prompt. |
| bash .mex/update.sh | Pulls latest mex infrastructure from GitHub without touching your populated content. Auto-rebuilds CLI if source files changed. |
Platform Note The CLI commands (node .mex/dist/cli.js ...) work on any platform with Node.js, including Windows cmd and PowerShell. The shell scripts require a bash-compatible shell.
4. Drift Detection
What Is Drift
Drift is when scaffold files say one thing but the codebase says another. A scaffold file claims src/utils/auth.ts exists — but it was renamed to src/lib/auth.ts last week. A context file says the project uses npm run lint — but that script was removed from package.json. Architecture docs reference a dependency at version 4 — but package.json has version 5.
Drift is inevitable. Code changes constantly. Documentation doesn't keep up. The longer drift goes unchecked, the more the agent's understanding diverges from reality — leading to wrong assumptions, broken suggestions, and wasted time.
mex detects drift deterministically. No AI, no tokens — just static analysis of your scaffold files against the actual codebase. Run mex check and you get a list of every claim in your scaffold that no longer holds true.
How It Works
The drift engine operates in three stages:
1Claim Extraction
The engine parses every markdown file in the scaffold (context files, pattern files, ROUTER.md, AGENTS.md) and extracts claims — things the scaffold asserts about the codebase:
| Claim type | Extracted from | Example |
|---|---|---|
| path | Inline code containing / or a known file extension | src/routes/api.ts |
| command | Inline code or code blocks starting with npm/yarn/pnpm/make/etc. | npm run test |
| dependency | Bold text (**Name**) inside sections with headers matching "dependencies", "stack", "key libraries", etc. | **Express** |
| version | Bold text with a version number in a dependency section | **React 18** |
The extractor is smart about what isn't a claim:
- Template placeholders with
<>,[],{}are skipped - URL routes like
/api/users(no file extension) are skipped - HTTP methods like
GET /api/bookmarksare skipped - Code snippets containing
=,(),;are skipped - Wildcard patterns like
*_streaming_client.pyare skipped
⚠ Negation awareness
Claims inside sections with headings like "Not Built", "Deliberately Not Using", "Removed", or "Deprecated" are marked as negated and excluded from validation. This prevents false positives when the scaffold intentionally documents what doesn't exist.
2Checker Execution
Eight checkers run against the extracted claims and scaffold files:
Path Checker
MISSING_PATHValidates every path claim points to a file on disk. Searches project root, scaffold root, and repo root (for .mex/ paths). Falls back to deep recursive search up to 5 directories.
Error for most paths. Warning inside pattern files or if containing placeholders ("example", "foo").
Edge Checker
DEAD_EDGEValidates that every target in YAML frontmatter edges arrays points to an existing file in project or scaffold root.
Always Error. Dead edges break the navigation web.
Index Sync Checker
INDEX_MISSING_ENTRYINDEX_ORPHAN_ENTRYCross-references patterns/INDEX.md with actual files to find unlisted patterns or orphaned references.
Always Warning.
Command Checker
DEAD_COMMANDValidates that npm/yarn/pnpm/make commands claimed in the scaffold actually exist in package.json or Makefile.
Always Error. Prevents hallucinated scripts.
Staleness Checker
STALE_FILEUses git history to detect scaffold files that haven't been updated in a long time. Triggers depending on two metrics: elapsed days and elapsed commits.
| Metric | Warning | Error |
|---|---|---|
| Days since change | > 30 | > 90 |
| Commits since change | > 50 | > 200 |
Dependency Checker
DEPENDENCY_MISSINGVERSION_MISMATCHChecks if claimed dependencies exist in your manifest (e.g. package.json) and validates exact version strings. Ignores known runtimes like Node, Python, Redis.
Always Warning.
Cross-File Checker
CROSS_FILE_CONFLICTDetects contradictions across different scaffold files, such as version conflicts ("React 18" vs "React 17") and package manager conflicts.
Error for version mismatch, Warning for package manager conflict.
Script Coverage Checker
UNDOCUMENTED_SCRIPTChecks the reverse direction: whether every script in package.json is mentioned somewhere in the scaffold. Excludes lifecycle hooks (pretest, postinstall) and automatically skipped sub-scripts (dev:debug ignored if dev is documented).
Always Warning.
3Scoring
The drift score starts at 100 and deducts points per issue. The score is clamped between 0 and 100. A perfect score means the scaffold is fully in sync with the codebase.
| Severity | Points deducted |
|---|---|
| ✗ Error | -10 |
| ⚠ Warning | -3 |
| ℹ Info | -1 |
For Contributors
The drift engine lives in src/drift/. Key files:
| File | Purpose |
|---|---|
| index.ts | Orchestrator — finds scaffold files, runs all checkers, assembles report. |
| claims.ts | Markdown parser that extracts path, command, dependency, and version claims. |
| frontmatter.ts | Reads YAML frontmatter from scaffold files. |
| scoring.ts | Computes the 0-100 score from issue severities. |
| checkers/*.ts | One file per checker — each exports a function that returns DriftIssue[]. |
Adding a new checkerCreate a new file in checkers/, export a function matching the signature of existing checkers, and wire it into index.ts. The function receives either claims or file paths and returns an array of DriftIssue objects with a code, severity, file, line, and message.
Ready to build? Check out the Contributing Guide for good first issues and PR guidelines.
5. Sync
What Sync Does
Sync is the repair mechanism. When mex check finds drift, sync builds targeted prompts that tell AI exactly what's broken and gives it the context to fix it — the current file content, the specific issues, what actually exists on disk, and recent git changes. The AI fixes only what's broken, not the entire scaffold.
There are two ways to run sync: the CLI command (mex sync) and the interactive shell script (bash .mex/sync.sh). The shell script wraps the CLI with an additional full resync option.
CLI Sync (mex sync)
The Sync Loop
Mode selection (first cycle only)
- 1. Interactive (default)Launches a live Claude Code session. The combined brief is passed as the prompt. Claude fixes all broken files while you watch. Requires Claude Code CLI installed.
- 2. Show promptsPrints the combined brief to stdout. You copy and paste it into whatever AI tool you're using.
- 3. ExitStop and come back later.
After the AI makes fixes, sync automatically re-runs mex check and shows the score change:Drift score: 72 → 95/100 (+23)
If errors remain, it asks whether to run another cycle. This continues until all errors are resolved or you choose to stop. If only warnings remain (and --warnings wasn't passed), it stops and tells you how many warnings are left.
How Briefs Are Built
The brief builder constructs a precise, targeted prompt for each broken file. When multiple files have issues, they're combined into a single prompt with numbered sections. For each broken file, the brief includes:
01 File path
Which scaffold file needs fixing.
02 Issues found
Every issue with severity and code.
[error] MISSING_PATH: Referenced path does not exist: src/old/auth.ts03 Current file content
The full markdown content of the scaffold file, so the AI can see what needs changing.
04 Filesystem context
For MISSING_PATH issues, lists what actually exists in the expected directory. If fewer than 20 files match the extension, lists all files with that extension. Gives AI enough context to find the correct current path.
05 Recent git changes
For paths referenced by the broken file, includes the git diff from the last 5 commits (HEAD~5..HEAD). This reveals renamed, moved, or deleted files to the AI.
The AI is instructed to: fix only what's necessary, not rewrite correct sections. When a referenced path no longer exists, find the correct current path from the filesystem context and update the reference.
Interactive Shell Script (bash .mex/sync.sh)
The shell script provides a menu with four options:
- 1Targeted sync (recommended)Runs
mex syncunder the hood. AI fixes only the flagged files. - 2Full resync Shell onlyAI re-reads the entire codebase and updates all scaffold files. Used when drift is so extensive that targeted fixes aren't enough.
- 3Show me the promptsRuns
mex sync --dry-runand prints the targeted prompts for manual pasting. - 4ExitFix it yourself.
Inside a Full Resync
Full resync is a separate mode not available through the CLI directly. It sends a comprehensive prompt that instructs the AI to:
- Read all context files to understand current state
- Explore what has changed since each file's
last_updateddate - Compare scaffold content to codebase file by file
- Make surgical, targeted edits — not rewrites
- Preserve YAML frontmatter structure
- Update
last_updatedin frontmatter - Update
ROUTER.md"Current Project State" - In
context/decisions.md: never delete existing decisions. If changed, mark old as superseded and add new above it.
If Claude Code CLI is installed, the full resync runs in the background with a spinner. Otherwise, it prints the prompt for manual pasting. The shell script supports --dry-run to show what needs fixing without executing anything.
Filtering Logic
By default, sync only targets files that have at least one error. If a file has errors, all of its issues (errors and warnings) are included in the brief — this gives the AI full context about everything wrong with that file. Files with only warnings are skipped.
Use --warnings to include warning-only files in the sync.
For Contributors
The sync engine lives in src/sync/. Key files:
| File | Purpose |
|---|---|
| index.ts | The sync loop — drift check, mode selection, Claude invocation, verify, repeat. |
| brief-builder.ts | Constructs targeted prompts with file content, issues, filesystem context, and git diffs. |
# Git Operations
The brief builder uses src/git.ts and the simple-git library:
getGitDiff(paths, cwd)Gets the diff for specific paths over the last 5 commits.
# Claude Invocation
The Claude Code session is launched via:
spawnSync("claude", [brief])With stdio: "inherit" (so the user sees the agent working) and a 5-minute timeout.
Ready to build? Check out the Contributing Guide for good first issues and PR guidelines.
6. Shell Scripts
mex includes four shell scripts that run from your project root. All are bash scripts requiring a bash-compatible shell (native on macOS/Linux, WSL or Git Bash on Windows). All support --help.
bash .mex/setup.sh
The entry point for new projects. Runs a 6-step process:
Step 1: Build CLI
Checks for Node.js and builds the CLI engine (npm install + npm run build inside .mex/). If the mex command is already available globally, it skips the build. If Node.js isn't installed, it continues without the CLI — the scaffold still works, you just won't have drift detection or sync commands.
Step 2: Detect project state
Scans for source files (supports 25+ languages) to determine which mode to use:
| State | Condition | Mode |
|---|---|---|
| existing | More than 3 source files found | Populate scaffold from code analysis |
| fresh | 3 or fewer source files | Populate scaffold from user intent (asks questions) |
| partial | Source files exist and scaffold is already partially filled | Populate empty slots, skip what's already filled |
Step 3: Tool config
Asks which AI tool you use and copies the appropriate config file to your project root. Supports selecting multiple tools at once. Config files are identical — they all point the agent to .mex/ROUTER.md. If a config file already exists, it asks before overwriting.
CLAUDE.md.cursorrules.windsurfrules.github/copilot-instructions.mdStep 4: Pre-analyze codebase
For existing/partial projects with the CLI available, runs mex init --json with a loading spinner. The scanner brief (~5-8k tokens) replaces the need for the AI to explore the filesystem (~50k tokens). If the scanner fails, the AI falls back to direct filesystem exploration.
Step 5: Build the setup prompt
- Existing projects (with brief): instructs the AI to reason from the scanner brief, populate all context files, generate 3-5 starter patterns, and wire frontmatter edges
- Existing projects (without brief): same, but the AI explores the filesystem directly
- Fresh projects: asks the user 7 questions one at a time (what does it do, hard rules, tech stack, stack rationale, component flow, day-one patterns, deliberate exclusions), then populates the scaffold from the answers
All prompts run 3 passes: populate context files → generate patterns → wire edges across all files.
Step 6: Run or print
If Claude Code was selected and the CLI is installed, launches an interactive Claude session directly. Otherwise, prints the prompt between copy markers for manual pasting. After completion, shows available commands and a tip to npm link for the mex shorthand.
--dry-run — shows what would happen without making any changes.bash .mex/sync.sh
A wrapper around mex sync that adds a full resync option. Auto-builds the CLI if it hasn't been built yet.
Flow
- 1Runs
mex check --quietfor the summary, thenmex check --jsonto count issues, then the full check for the detailed report. - 2If no issues, exits with a success message.
- 3Presents four options:
Full resync rules (enforced)
- • Surgical, targeted edits — not full file rewrites
- • Preserve YAML frontmatter structure — edit individual fields, never delete the whole block
- • In
decisions.md: never delete existing decisions. Superseded decisions get marked as such, and the new decision is added above - • Update
last_updatedin frontmatter for every changed file - • Update
ROUTER.md"Current Project State" after all updates
If the CLI isn't available, the script falls back to printing the full resync prompt for manual use.
--dry-run — shows what needs fixing without executing.bash .mex/update.sh
Updates mex infrastructure files from GitHub without touching your populated content.
What gets updated (safe to overwrite)
- Shell scripts:
setup.sh, update.sh, sync.sh, visualize.sh - Documentation:
SETUP.md, SYNC.md, LICENSE, patterns/README.md - Build config:
package.json, tsconfig.json, tsup.config.ts - Full directories:
.tool-configs/, src/, test/
What is NEVER touched
- Core routing:
AGENTS.md, ROUTER.md - All context: Everything in
context/ - Patterns:
patterns/INDEX.mdand user-created pattern files
Process
- Clones the latest mex from GitHub into a temp directory (shallow clone)
- Compares each infrastructure file — copies only files that changed or are new
- Checks if upstream added new context file templates — if so, copies them (new template files won't overwrite existing populated files)
- Detects if
ROUTER.mdorAGENTS.mdhave new sections upstream and warns you - If any CLI source files changed, automatically rebuilds the CLI (
npm install + npm run build) - Saves the latest commit hash to
.mex-versionfor future reference - Prints a summary of what was updated, added, and unchanged
bash .mex/visualize.sh
Launches a local web server (port 4444) with an interactive graph visualization of your scaffold. Shows all scaffold files as nodes and their frontmatter edges as connections.
Parses YAML frontmatter from all scaffold files, detects their completion status (populated, empty, partial), and renders an interactive force-directed graph in the browser. Auto-opens the browser on launch.
7. Multi-Tool Setup
mex works with any AI coding tool that can read files from the project directory. The scaffold itself is tool-agnostic — it's just markdown files. What differs is how each tool discovers the entry point.
How It Works
Each AI tool has a specific config file it auto-loads at the start of every session. mex uses this to bootstrap the navigation chain: the config file tells the agent to read .mex/ROUTER.md, which contains the routing table, project state, and behavioural contract.
All config files contain identical content — the same anchor text from .mex/AGENTS.md: project identity, non-negotiables, commands, and the instruction to read ROUTER.md before doing anything.
Supported Tools
| Tool | Config file | Location |
|---|---|---|
| Claude Code | CLAUDE.md | Project root |
| Cursor | .cursorrules | Project root |
| Windsurf | .windsurfrules | Project root |
| GitHub Copilot | copilot-instructions.md | .github/ directory in project root |
Automatic Setup
During bash .mex/setup.sh, you're asked which tool you use:
Selecting option 5 lets you enter multiple tool numbers (e.g., 1 2 4 for Claude Code + Cursor + Copilot). The script copies the correct config file for each selection to the right location. If a config file already exists at the destination, it asks before overwriting.
Manual Setup
If you skipped tool config during setup or want to add another tool later, copy the file manually:
cp .mex/.tool-configs/CLAUDE.md ./CLAUDE.mdcp .mex/.tool-configs/.cursorrules ./.cursorrulescp .mex/.tool-configs/.windsurfrules ./.windsurfrulesmkdir -p .github && cp .mex/.tool-configs/copilot-instructions.md ./.github/copilot-instructions.mdUsing a Tool Not Listed
For any AI tool not listed above, there are two options:
- 1Has a config file / custom instructions supportAdd the instruction
"Read .mex/ROUTER.md before starting any task"to it. - 2No config file supportPaste that instruction at the start of each session, or point the agent to
.mex/AGENTS.mddirectly.
The scaffold works identically regardless of which tool you use. The config file is just the entry point.
Keeping Config Files in Sync
.mex/AGENTS.md is the source of truth. The tool config files in your project root are copies. If you update AGENTS.md (project name, non-negotiables, commands), update your root config file too so they stay in sync.
The mex check drift detection includes tool config files in its scan — it checks paths, commands, and other claims in CLAUDE.md, .cursorrules, and .windsurfrules the same way it checks scaffold files.
8. Scaffold Structure
The scaffold lives inside a .mex/ directory in your project root. It's a structured set of markdown files that give AI agents persistent project knowledge. Each file has a specific role, YAML frontmatter for metadata and navigation, and annotation comments that guide what content belongs there.
YAML Frontmatter
Every scaffold file has YAML frontmatter at the top between --- delimiters. This is what makes the scaffold navigable rather than just a flat pile of files.
| Field | Purpose |
|---|---|
| name | Identifier for the file |
| description | One-line summary — used by the agent to decide if this file is relevant |
| triggers | Keywords that indicate this file should be loaded. The agent matches the current task against these |
| edges | Pointers to related files with conditions. Creates a navigable web — "if you're here and need X, go there" |
| last_updated | When the file was last modified. Used by the staleness checker to prioritize updates |
Edges are what connect the scaffold into a graph rather than isolated documents. Every context file should have at least 2 edges, every pattern at least 1. Edges are bidirectional where it makes sense.
AGENTS.md — Project Anchor
The identity file. Loaded every session. Kept deliberately small (target: under 150 tokens) so it never costs meaningful context.
| Section | What goes here |
|---|---|
| What This Is | One sentence. Factual description of what the software does. Not a tagline |
| Non-Negotiables | 3-7 hard rules the agent must never violate. Things that cause real damage if broken. Not preferences — rules |
| Commands | Exact commands to dev, test, lint, build. The actual commands from this codebase, not placeholders |
| Scaffold Growth | Instruction to update the scaffold after every task — create patterns, update context files |
| Navigation | Points the agent to ROUTER.md |
ROUTER.md — Session Bootstrap
The navigation hub. Read at the start of every session before any task.
1. Current Project State
Three subsections: Working, Not Yet Built, Known Issues. 3-7 items each. This is the primary drift prevention mechanism. It re-grounds the agent every session so it knows what actually exists right now.
2. Routing Table
Maps task types to the right context file:
| Task type | Load |
|---|---|
| Understanding how the system works | context/architecture.md |
| Working with a specific technology | context/stack.md |
| Writing or reviewing code | context/conventions.md |
| Making a design decision | context/decisions.md |
| Setting up or running the project | context/setup.md |
| Any specific task | Check patterns/INDEX.md |
When domain-specific context files are created (e.g., context/auth.md, context/payments.md), they get added as additional rows in this table.
3. Behavioural Contract
The 5-step CONTEXT → BUILD → VERIFY → DEBUG → GROW loop that the agent follows for every task. See the "How It Works" section for the full breakdown.
Context Files
Five core files covering different dimensions of the project. Each has annotation comments (<!-- HTML comments -->) that explain exactly what content belongs in each section, with minimum item counts and examples.
context/architecture.md
How the major pieces connect and flow. Focus is on flow, not technology — how does a request or action move through the system?
| Section | Content | Guidance |
|---|---|---|
| System Overview | How components connect. Text flow diagram or short prose | 5-15 lines, readable in 30s |
| Key Components | Major modules/services — name, what it does, what it depends on | Min 3, 1-2 lines each |
| External Dependencies | Third-party services, APIs, databases — what it is, what it's used for, constraints | Min 3, 1-2 lines each |
| What Does NOT Exist Here | Explicit boundaries — what is deliberately outside this system | Min 2, prevents agent from building things that belong elsewhere |
context/stack.md
Technology choices and the reasoning behind them.
| Section | Content | Guidance |
|---|---|---|
| Core Technologies | Primary language, framework, runtime with versions | Min 3, 3-7 items |
| Key Libraries | Libraries central to how the project works. Include reason over alternatives | Min 3, 3-10 items |
| What We Deliberately Do NOT Use | Technologies or patterns explicitly avoided, and why | Min 2, prevents unwanted dependencies |
| Version Constraints | Important version-specific things to know | Only fill if meaningful constraints exist |
context/conventions.md
How code is written in this project. The most frequently loaded context file — the agent checks it during the VERIFY step of every task.
| Section | Content | Guidance |
|---|---|---|
| Naming | How files, functions, variables, classes, database columns are named | Min 3, only conventions actually enforced |
| Structure | How code is organized within files and across the codebase | Min 3, focus on what the agent is most likely to get wrong |
| Patterns | Recurring code patterns with concrete before/after examples | Min 2 patterns with examples |
| Verify Checklist | Checklist the agent runs against any code it writes | Min 4 items, project-specific things most likely to go wrong |
context/decisions.md
Append-only decision log. The event clock of the project.
Format for each entry:
Key rules:
- Never delete existing decisions
- When a decision changes, mark the old entry as "Superseded by [new title]" and add the new decision above it
- Only document decisions where "why" matters — non-obvious choices, important constraints, or reasoning that prevents future mistakes
- Minimum 3 entries during initial population
context/setup.md
Everything needed to go from clone to running.
| Section | Content | Guidance |
|---|---|---|
| Prerequisites | What must be installed first, with versions if they matter | Min 2 |
| First-time Setup | Exact steps from clone to running, in order | Min 3 steps, actual commands not placeholders |
| Environment Variables | Required env vars and what they do. No actual values — this file is committed | List all required, then conditional, then optional |
| Common Commands | Daily-use commands with more detail than AGENTS.md | Min 4 |
| Common Issues | Things that actually go wrong and how to fix them | Min 2, not hypothetical problems |
Domain-Specific Context Files
If a project has domains complex enough that cramming them into architecture.md would make it too long or too shallow, additional context files are created in context/.
- context/auth.md — complex auth systems
- context/ingestion.md — data pipeline projects
- context/payments.md — Stripe or payment integrations
These use the same YAML frontmatter format (name, description, triggers, edges, last_updated) and get added as rows in ROUTER.md's routing table. Only created for domains that have real depth — not for simple integrations that fit in a few lines of architecture.md.
Patterns
Patterns are task-specific guides — the accumulated wisdom of working on this project. They live in patterns/ and are indexed by patterns/INDEX.md.
Pattern Format — Single Task
Pattern Categories
- 1 Common task patterns — the repeatable tasks developers do most often. Derived from architecture and conventions.
- 2 Integration patterns — how to work with external dependencies that have non-obvious gotchas. Every external dependency deserves one.
- 3 Debug/diagnosis patterns — when something breaks at a component boundary, where to look.
- 4 Deploy/release patterns — only if deployment is non-trivial. Staging, rollbacks, migrations.
How Patterns Grow
Setup seeds 3-5 starter patterns. The rest come from real work through the GROW step:
- New task type → Agent creates pattern
- Existing pattern wrong → Agent updates it
- New gotcha revealed → Agent adds it
Infrastructure Files
These files are owned by mex, not by your project content. They get updated by update.sh.
| File/Directory | Purpose |
|---|---|
| src/ | CLI source code (TypeScript) |
| test/ | Test suite |
| .tool-configs/ | Config file templates for each AI tool |
| setup.sh, sync.sh... | Shell scripts |
| package.json... | Build configuration |
| SETUP.md, SYNC.md | Internal documentation for prompts |
| patterns/README.md | Pattern format spec |
Content vs. Infrastructure
The distinction matters for update.sh:
Content files (never overwritten)
- • AGENTS.md, ROUTER.md
- • Everything in context/
- • patterns/INDEX.md and user patterns
Infrastructure files (safe to overwrite)
- • Shell scripts, CLI source, build config
- • test suite, tool config templates
- • patterns/README.md