Guideline Rules for writing, maintaining, and automating high-quality documentation for code libraries using a docs-as-code workflow.
Stop writing documentation that gets outdated the moment you push to main. If you're tired of maintaining separate wikis, wrestling with broken examples, or watching your README become a graveyard of stale information, these Cursor Rules will change how you think about library documentation forever.
Every developer has lived this nightmare: You ship a brilliant library, write decent initial docs, then watch helplessly as they rot. Contributors skip documentation updates. Examples break silently. Your README becomes a monument to good intentions. Users file issues about confusing docs, but fixing them feels like archaeology.
The core problem? Documentation lives separate from code. Different repositories, different workflows, different review processes. When your docs aren't part of your development DNA, they become technical debt instead of technical assets.
These Cursor Rules implement a battle-tested docs-as-code workflow that treats documentation like the first-class code it should be. Every doc lives in your repo. Every example runs in CI. Every API change requires matching documentation. No exceptions.
Here's what changes immediately:
### Before: Traditional Documentation
- Separate wiki or documentation site
- Manual example updates (when you remember)
- README that's either empty or overwhelming
- Zero validation of code snippets
- Documentation updates as afterthoughts
### After: DocuMaster Workflow
- All docs versioned with source code
- Executable examples that break the build if outdated
- Living README as single source of truth
- Automated API reference generation
- Documentation PRs block merges until complete
Before these rules, API changes meant playing documentation roulette. Would you remember to update all the examples? Would users discover breaking changes through trial and error?
Now your workflow becomes bulletproof:
# You change a function signature
export function authenticate(config: AuthConfig): Promise<AuthResult>
# CI immediately catches outdated examples
❌ docs/examples/quick-start.js:12 - Property 'apiKey' missing
❌ README.md code block fails compilation
❌ JSDoc examples don't match actual parameters
# Build fails until documentation matches reality
These rules transform your README from a dumping ground into a navigation hub:
# Your Library Name
## What it does (one clear sentence)
## Quick Start (30-second success)
```js
import { createClient } from 'your-lib';
const client = createClient({ apiKey: 'test' });
await client.authenticate(); // ✅ This runs in CI
Auto-generated from JSDoc comments → Full API Docs
### Code Examples That Never Lie
Every code snippet becomes executable and validated:
```javascript
// This comment becomes testable documentation
/**
* Authenticates a user with the service
*
* @example
* ```js
* const result = await auth.login('[email protected]', 'password');
* console.log(result.token); // "eyJhbGciOiJIUzI1NiIs..."
* ```
*
* @param {string} email - User email address
* @param {string} password - User password
* @returns {Promise<AuthResult>} Authentication result
*/
CI automatically extracts and runs these examples. If your API changes break an example, the build fails. No more discovering broken documentation in production.
⚡ 60% Faster Onboarding: New team members find working examples immediately, not archaeological expeditions through outdated wikis.
🔒 Zero Stale Examples: Every code snippet runs in CI. Broken examples break builds. Your documentation stays honest.
📝 Automatic API Docs: JSDoc/Sphinx/Doxygen integration means your API reference updates itself. Write comments once, get beautiful documentation everywhere.
🚀 Documentation-Driven Development: Writing docs first clarifies your API design. Better APIs ship faster.
⚙️ One-Command Publishing: npm run docs:deploy builds, tests, and publishes versioned documentation. No more manual upload ceremonies.
Copy the provided rules into your Cursor settings. These configure intelligent assistance for documentation workflows across Markdown, JSDoc, Sphinx, and MkDocs.
# Create the recommended directory structure
mkdir -p docs/{getting-started,reference,examples}
mkdir -p examples scripts
# Initialize your documentation toolchain
npm install --save-dev markdown-lint jsdoc mkdocs-material
Add to your package.json:
{
"scripts": {
"docs:build": "jsdoc -c jsdoc.conf.json && mkdocs build",
"docs:test": "markdown-lint docs/ && npm run test:examples",
"docs:deploy": "npm run docs:build && gh-pages -d site",
"test:examples": "node scripts/test-examples.js"
}
}
Create scripts/test-examples.js:
// Automatically extract and test code blocks from documentation
const fs = require('fs');
const path = require('path');
function extractCodeBlocks(markdown) {
const regex = /```javascript\n([\s\S]*?)\n```/g;
const blocks = [];
let match;
while ((match = regex.exec(markdown)) !== null) {
blocks.push(match[1]);
}
return blocks;
}
// Test all examples in docs/
// Exit with error if any fail
Add to your GitHub Actions:
name: Documentation
on: [push, pull_request]
jobs:
docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm install
- run: npm run docs:test
- run: npm run docs:build
- name: Deploy to GitHub Pages
if: github.ref == 'refs/heads/main'
run: npm run docs:deploy
Week 1: Your examples stop breaking silently. Contributors can't merge without updating docs.
Month 1: New users report faster onboarding. Support tickets about confusing documentation drop by 70%.
Month 3: Your library's documentation becomes a competitive advantage. Other teams start asking how you keep everything so up-to-date.
Long-term: Documentation becomes a development accelerator, not a maintenance burden. You ship features faster because writing docs clarifies design decisions upfront.
These rules don't just organize your documentation—they make documentation a force multiplier for your entire development process. Your future self (and your users) will thank you for making this investment today.
Ready to stop playing documentation roulette? Add these rules to Cursor and watch your library documentation transform from liability to asset.
You are an expert in Documentation-as-Code workflows, Markdown, reStructuredText, AsciiDoc, Sphinx, MkDocs, Doxygen, JSDoc, CI/CD automation, and AI-assisted documentation.
Key Principles
- Treat documentation as first-class code; store every doc file in the same VCS as the source code.
- Write for the least-experienced reader: use simple, inclusive language and avoid jargon.
- Keep the README the single source of truth for purpose, quick start, and common tasks.
- Prefer living, executable examples over static snippets; verify them in CI.
- Any public API surface must ship with usage, parameter tables, return values, and error/exception detail.
- Enforce consistency with a style guide (e.g., Microsoft Writing Style Guide) and an automated linter.
- Every new feature or change = matching documentation PR; no green build without updated docs.
- Build, test, and deploy docs on every commit; publish versioned output.
Markdown
- Use ATX # headings; never skip a level (e.g., `###` cannot follow `#`).
- Limit line length to 100 chars for diff readability.
- Fenced code blocks ```language``` with explicit language identifiers; enable syntax highlighting.
- Place one blank line before and after code blocks, lists, and tables.
- Use relative links (`./path/file.md`) inside the repo; external links must include protocol.
- Capitalize first word in list items if they form complete sentences; otherwise lower-case.
- Prefer tables for argument/parameter matrices; generate via `npm run docs:tables` helper.
- Example snippet:
```markdown
### Installation
```bash
npm install my-lib --save
```
### Quick Example
```js
import { add } from 'my-lib';
console.log(add(2, 3)); // 5
```
- Avoid HTML tags unless Markdown lacks the needed construct (e.g., `<details>` for collapsibles).
Error Handling and Validation
- Document every thrown exception or error response in the same order they may occur.
- Use “Error reference” pages grouping errors by domain, code, and remediation.
- Provide copy-pastable curl examples for HTTP error reproductions.
- Validate documentation during CI with:
- `markdown-lint` for style & broken links.
- `doctest` / `pytest --doctest-globs="*.md"` to execute code blocks.
- Spell checking (`codespell`).
- Fail the pipeline if any documentation check fails.
Sphinx (Python / C++)
- Configure `conf.py` with `numpydoc`, `autodoc`, `autosummary`, `intersphinx`.
- Source in `docs/` folder; output to `docs/_build/html`.
- Enable `sphinx.ext.coverage` to track undocumented APIs; coverage < 90% blocks merge.
- Use `.. code-block:: python` instead of Markdown in reST files for consistency.
- Theme: `furo` with dark/light switch.
MkDocs (General, lightweight)
- YAML config lives at project root: `mkdocs.yml`.
- Enable plugins: `awesome-pages`, `mkdocs-material`, `mkdocs-macros`, `mkdocs-gen-files`.
- Auto-generate API reference via `mkdocstrings` and tie into `docs/reference/`.
- Versioning handled by `mike`; latest → `/`, older versions under `/vX.Y/`.
JSDoc (JavaScript)
- JSDoc comments mandatory for every exported symbol; template: `/**\n * Summary.\n * \n * @param {number} x – first number\n * @returns {number} sum\n */`.
- Run `npm run docs:js` (wrapper around `jsdoc`) on pre-publish.
- Output lives in `site/api/js` and is linked in main sidebar.
Doxygen (C/C++)
- Use `///` triple-slash comments.
- Generate call graphs and include `.dot` outputs in HTML build.
- Turn on `EXTRACT_ALL = NO` and `WARN_IF_UNDOCUMENTED = YES` to keep noise low but strict.
Additional Sections
Testing
- All code samples must compile/run under CI; use `examples/` folder with mirrors of snippet files.
- Attach unit tests validating snippet output; failing snippet blocks merge.
Performance
- Track documentation build time; warn if build > 90th percentile of last 30 builds.
- Cache heavy steps (Sphinx HTML) with CI artifacts keyed by `docs/**` hash.
Security
- Secrets scanning enabled for every doc commit; fail build on accidental key disclosure.
- Strip private URLs and internal IPs via pre-commit hook.
Accessibility
- Use aria-labels in custom HTML.
- Provide alt text for all images; lint via `img-alt-checker`.
- Ensure color contrast meets WCAG AA; theme CI test with `pa11y`.
Collaboration & Review
- Documentation PR template requires:
- Purpose summary
- Screenshots of rendered output
- Checklist: spellcheck, linkcheck, snippet test pass
- Docs reviewers listed in `CODEOWNERS` under `/docs/`.
- Encourage community edits via “Edit this page” links pointing to Git HEAD.
Directory Layout
```
/README.md ← landing page
/docs/
index.md ← primary nav entry
getting-started.md
reference/
api.md
/examples/ ← runnable samples used in docs
/scripts/
lint-docs.sh ← wraps all lint & test tools
/tags/ ← generated tag assets
```
Commit Message Conventions (docs scope)
- `docs: add authentication guide`
- `docs(fix): correct typo in API params`
- `docs(build): bump mkdocs-material 9.x`
CI Targets
- `docs:build` – build HTML/PDF
- `docs:test` – execute doctests & lint
- `docs:deploy` – push to `gh-pages` with version tagging
With these rules your team can produce, test, and ship professional-grade, continuously-validated documentation that evolves alongside the codebase.