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.
    Windows Users: Use WSL, Git Bash, or any bash-compatible terminal.
  • 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:

git clone https://github.com/theDakshJaitly/mex.git .mex
bash .mex/setup.sh

The setup script does the following, in order:

  1. Builds the CLI
    Runs npm install and npm run build inside .mex/. If Node.js isn't available, it skips this step and continues (the scaffold still works, you just won't have CLI commands).
  2. Detects project state
    Scans for source files to determine if this is an existing codebase, a fresh project, or a partially populated scaffold.
  3. 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.md at the start of every session.
  4. Pre-scans the codebase
    If the CLI was built successfully and source files exist, runs mex init --json to 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).
  5. 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.
Setup supports the --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:

cd .mex && npm link && cd ..

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:

bash .mex/update.sh

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:

git clone https://github.com/theDakshJaitly/mex.git
cd mex
npm install
npm run build # one-time build
npm run dev # watch mode — rebuilds on save
npm test # run test suite
npm run typecheck # TypeScript type checking

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:

  1. A structured markdown scaffold — a set of navigable files that give AI agents persistent project knowledge
  2. 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 typeLoad
    Understanding how the system workscontext/architecture.md
    Working with a specific technologycontext/stack.md
    Writing or reviewing codecontext/conventions.md
    Making a design decisioncontext/decisions.md
    Setting up or running the projectcontext/setup.md
    Any specific taskCheck patterns/INDEX.md

context/ Knowledge Files

Five files covering different dimensions of the project:

FileWhat it contains
architecture.mdHow the major pieces connect — system flow, component boundaries, external dependencies
stack.mdTechnology choices and reasoning — language, framework, database, key libraries, and why each was chosen over alternatives
conventions.mdNaming conventions, code structure patterns, file organization rules
decisions.mdAppend-only decision log — architectural choices with context and reasoning
setup.mdHow 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 loaded
  • edges — pointers to related files
  • last_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:

  1. Common tasks (add endpoint, add component)
  2. Integration patterns (external dependencies with gotchas)
  3. Debug/diagnosis (when something breaks at a boundary)
  4. Deploy/release workflows

The Behavioural Contract

Every task follows a 5-step loop defined in ROUTER.md:

  1. CONTEXT
    Load the relevant context file(s) from the routing table. Check patterns/INDEX.md for a matching pattern. Narrate what's being loaded.
  2. BUILD
    Do the work. If a pattern exists, follow its steps. If deviating, state the deviation and why before writing code.
  3. VERIFY
    Load context/conventions.md and run the verify checklist item by item. Each item is stated explicitly with pass/fail — no summarizing.
  4. DEBUG
    If verification fails, check patterns/INDEX.md for a debug pattern. Follow it. Fix the issue and re-run VERIFY.
  5. 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:

edges:
- target: context/stack.md
condition: when specific technology details are needed
- target: context/decisions.md
condition: when understanding why the architecture is structured this way

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.

FlagWhat it does
--quietOne-line summary only. Example: mex: drift score 92/100 (1 warning)
--jsonFull drift report as JSON — every issue with file, line number, severity, code, and message. Useful for CI pipelines or programmatic consumption.
--fixRuns 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:

  1. Runs mex check internally to find all issues
  2. Groups issues by file and shows which files need attention (error & warning counts)
  3. 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.
  4. After the AI fixes files, re-runs the drift check automatically
  5. Shows the score change (e.g., Drift score: 72 → 95/100 (+23))
  6. 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.

FlagWhat it does
--dry-runShows the targeted prompt that would be sent to AI, without executing. Useful for reviewing what sync would do.
--warningsBy 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 moduleWhat it extracts
manifestDependencies, versions, scripts from package.json (or equivalent)
entry-pointsMain entry files (e.g., src/index.ts, app.py)
folder-treeDirectory structure, excluding node_modules, .git, dist, etc.
toolingBuild tools, linters, formatters, CI config
readmeExisting README content

Without --json, it wraps the brief in a prompt instructing the AI how to use it to populate the scaffold.

FlagWhat it does
--jsonOutputs 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-check comment

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.

Prints all commands with flags
& 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.

ScriptWhat it does
bash .mex/setup.shFirst-time setup — detects project state, copies tool config, scans codebase, launches AI to populate the scaffold. Supports --dry-run
bash .mex/sync.shInteractive menu — choose between check, sync, or exporting the sync prompt.
bash .mex/update.shPulls 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 typeExtracted fromExample
pathInline code containing / or a known file extensionsrc/routes/api.ts
commandInline code or code blocks starting with npm/yarn/pnpm/make/etc.npm run test
dependencyBold text (**Name**) inside sections with headers matching "dependencies", "stack", "key libraries", etc.**Express**
versionBold 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/bookmarks are skipped
  • Code snippets containing =, (), ; are skipped
  • Wildcard patterns like *_streaming_client.py are 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_PATH

Validates 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_EDGE

Validates 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_ENTRY

Cross-references patterns/INDEX.md with actual files to find unlisted patterns or orphaned references.

Always Warning.

Command Checker
DEAD_COMMAND

Validates 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_FILE

Uses 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.

MetricWarningError
Days since change> 30> 90
Commits since change> 50> 200
Dependency Checker
DEPENDENCY_MISSINGVERSION_MISMATCH

Checks 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_CONFLICT

Detects 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_SCRIPT

Checks 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.

SeverityPoints deducted
Error-10
Warning-3
Info-1
05080100
Needs SyncDriftingHealthy

For Contributors

The drift engine lives in src/drift/. Key files:

FilePurpose
index.tsOrchestrator — finds scaffold files, runs all checkers, assembles report.
claims.tsMarkdown parser that extracts path, command, dependency, and version claims.
frontmatter.tsReads YAML frontmatter from scaffold files.
scoring.tsComputes the 0-100 score from issue severities.
checkers/*.tsOne 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

Run drift check
Group issues by file → show which files need attention
Ask user: Interactive / Show prompts / Exit
Build combined brief for all broken files
Launch Claude Code session (or print prompt)
Re-run drift check → show score delta
If issues remain → ask to run another cycle

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.ts

03 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:

  1. 1
    Targeted sync (recommended)Runs mex sync under the hood. AI fixes only the flagged files.
  2. 2
    Full 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.
  3. 3
    Show me the promptsRuns mex sync --dry-run and prints the targeted prompts for manual pasting.
  4. 4
    ExitFix 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_updated date
  • Compare scaffold content to codebase file by file
  • Make surgical, targeted edits — not rewrites
  • Preserve YAML frontmatter structure
  • Update last_updated in 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:

FilePurpose
index.tsThe sync loop — drift check, mode selection, Claude invocation, verify, repeat.
brief-builder.tsConstructs 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:

StateConditionMode
existingMore than 3 source files foundPopulate scaffold from code analysis
fresh3 or fewer source filesPopulate scaffold from user intent (asks questions)
partialSource files exist and scaffold is already partially filledPopulate 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 Code
CLAUDE.md
Cursor
.cursorrules
Windsurf
.windsurfrules
GitHub Copilot
.github/copilot-instructions.md

Step 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.

Flags: --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

  1. 1
    Runs mex check --quiet for the summary, then mex check --json to count issues, then the full check for the detailed report.
  2. 2
    If no issues, exits with a success message.
  3. 3
    Presents four options:
Targeted sync (default)Runs mex sync — AI fixes only the flagged files
Full resyncSends a comprehensive prompt to re-read and update the entire scaffold
Show me the promptsRuns mex sync --dry-run for manual pasting
ExitStop, fix it yourself

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_updated in 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.

Flags: --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.md and user-created pattern files

Process

  1. Clones the latest mex from GitHub into a temp directory (shallow clone)
  2. Compares each infrastructure file — copies only files that changed or are new
  3. Checks if upstream added new context file templates — if so, copies them (new template files won't overwrite existing populated files)
  4. Detects if ROUTER.md or AGENTS.md have new sections upstream and warns you
  5. If any CLI source files changed, automatically rebuilds the CLI (npm install + npm run build)
  6. Saves the latest commit hash to .mex-version for future reference
  7. 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.

Zero dependencies — uses embedded Python HTTP server
Local Graph UI

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

ToolConfig fileLocation
Claude CodeCLAUDE.mdProject root
Cursor.cursorrulesProject root
Windsurf.windsurfrulesProject root
GitHub Copilotcopilot-instructions.md.github/ directory in project root

Automatic Setup

During bash .mex/setup.sh, you're asked which tool you use:

setup.sh
? Which AI tool do you use?
1) Claude Code
2) Cursor
3) Windsurf
4) GitHub Copilot
5) Multiple (select next) ◄ selected
6) None / other (skip)

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:

Claude Code
cp .mex/.tool-configs/CLAUDE.md ./CLAUDE.md
Cursor
cp .mex/.tool-configs/.cursorrules ./.cursorrules
Windsurf
cp .mex/.tool-configs/.windsurfrules ./.windsurfrules
GitHub Copilot
mkdir -p .github && cp .mex/.tool-configs/copilot-instructions.md ./.github/copilot-instructions.md

Using a Tool Not Listed

For any AI tool not listed above, there are two options:

  1. 1
    Has a config file / custom instructions supportAdd the instruction "Read .mex/ROUTER.md before starting any task" to it.
  2. 2
    No config file supportPaste that instruction at the start of each session, or point the agent to .mex/AGENTS.md directly.

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.

.mex/AGENTS.md
Source
CLAUDE.md.cursorrules
Monitored by Drift Check

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.

your-project/
├── CLAUDE.md← tool config (auto-loaded, points to .mex/)
├── .mex/
│ ├── AGENTS.md← project identity, non-negotiables, commands
│ ├── ROUTER.md← session bootstrap, routing table, behavioural contract
│ ├── context/
│ │ ├── architecture.md← how components connect and flow
│ │ ├── stack.md← technology choices and reasoning
│ │ ├── conventions.md← naming, structure, code patterns, verify checklist
│ │ ├── decisions.md← append-only decision log
│ │ └── setup.md← environment setup, commands, common issues
│ ├── patterns/
│ │ ├── README.md← pattern format spec and category guide
│ │ ├── INDEX.md← lookup table for all patterns
│ │ └── *.md← task-specific guides (created during setup and GROW)
│ ├── .tool-configs/← config file templates for each AI tool
│ ├── src/← CLI source code (TypeScript)
│ ├── test/← test suite
│ ├── setup.sh← first-time setup
│ ├── sync.sh← interactive sync menu
│ ├── update.sh← pull latest infrastructure
│ └── visualize.sh← scaffold graph visualization

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.

---
name: architecture
description: How the major pieces...
triggers:
- "architecture"
- "system design"
- "how does X connect to Y"
edges:
- target: context/stack.md
condition: when specific...
- target: context/decisions.md
condition: when understanding why...
last_updated: 2025-03-15
---
FieldPurpose
nameIdentifier for the file
descriptionOne-line summary — used by the agent to decide if this file is relevant
triggersKeywords that indicate this file should be loaded. The agent matches the current task against these
edgesPointers to related files with conditions. Creates a navigable web — "if you're here and need X, go there"
last_updatedWhen 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.

SectionWhat goes here
What This IsOne sentence. Factual description of what the software does. Not a tagline
Non-Negotiables3-7 hard rules the agent must never violate. Things that cause real damage if broken. Not preferences — rules
CommandsExact commands to dev, test, lint, build. The actual commands from this codebase, not placeholders
Scaffold GrowthInstruction to update the scaffold after every task — create patterns, update context files
NavigationPoints 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 typeLoad
Understanding how the system workscontext/architecture.md
Working with a specific technologycontext/stack.md
Writing or reviewing codecontext/conventions.md
Making a design decisioncontext/decisions.md
Setting up or running the projectcontext/setup.md
Any specific taskCheck 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?

SectionContentGuidance
System OverviewHow components connect. Text flow diagram or short prose5-15 lines, readable in 30s
Key ComponentsMajor modules/services — name, what it does, what it depends onMin 3, 1-2 lines each
External DependenciesThird-party services, APIs, databases — what it is, what it's used for, constraintsMin 3, 1-2 lines each
What Does NOT Exist HereExplicit boundaries — what is deliberately outside this systemMin 2, prevents agent from building things that belong elsewhere

context/stack.md

Technology choices and the reasoning behind them.

SectionContentGuidance
Core TechnologiesPrimary language, framework, runtime with versionsMin 3, 3-7 items
Key LibrariesLibraries central to how the project works. Include reason over alternativesMin 3, 3-10 items
What We Deliberately Do NOT UseTechnologies or patterns explicitly avoided, and whyMin 2, prevents unwanted dependencies
Version ConstraintsImportant version-specific things to knowOnly 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.

SectionContentGuidance
NamingHow files, functions, variables, classes, database columns are namedMin 3, only conventions actually enforced
StructureHow code is organized within files and across the codebaseMin 3, focus on what the agent is most likely to get wrong
PatternsRecurring code patterns with concrete before/after examplesMin 2 patterns with examples
Verify ChecklistChecklist the agent runs against any code it writesMin 4 items, project-specific things most likely to go wrong
The Verify Checklist is critical — it's what the agent runs item-by-item during the VERIFY step. Each item should be a concrete, checkable assertion about the code, not a vague principle.

context/decisions.md

Append-only decision log. The event clock of the project.

Format for each entry:
### [Decision Title]
**Date:** YYYY-MM-DD
**Status:** Active | Superseded by [title]
**Decision:** What was decided, one sentence
**Reasoning:** Why this was chosen
**Alternatives considered:** What else...
**Consequences:** What this means...
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.

SectionContentGuidance
PrerequisitesWhat must be installed first, with versions if they matterMin 2
First-time SetupExact steps from clone to running, in orderMin 3 steps, actual commands not placeholders
Environment VariablesRequired env vars and what they do. No actual values — this file is committedList all required, then conditional, then optional
Common CommandsDaily-use commands with more detail than AGENTS.mdMin 4
Common IssuesThings that actually go wrong and how to fix themMin 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

--- name: add-endpoint description: How to add a new API endpoint... ... ---# Add Endpoint## ContextWhat to load or know before starting this task.## StepsThe workflow — what to do, in what order.## GotchasThings that go wrong. What to watch out for.## VerifyChecklist to run after completing this task.## DebugWhat to check when this task type breaks.## Update Scaffold- [ ] Update ROUTER.md "Current Project State"... - [ ] Update any context files...

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/DirectoryPurpose
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.mdInternal documentation for prompts
patterns/README.mdPattern 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