# Generate and verify documentation with Cursor's agent

URL: https://developertoolkit.ai/en/cursor-ide/build/documentation/
Description: Have Cursor's agent write TSDoc, guides, Mermaid diagrams and migration notes from your code, then prove them in CI instead of proofreading.

Cursor's agent writes documentation by reading the code that the documentation describes: TSDoc for every public export, a getting-started guide lifted from passing tests, Mermaid architecture diagrams, and a migration guide built from `git diff`. The agent does the extraction. Mechanical gates — TypeDoc validation, compiled examples, rendered diagrams, and link checks — prove the result, so humans edit only the "why".

This page is for developers and tech leads who own a library or service whose documentation lags the code. Version 2.0 ships next week with 40 breaking changes, the README still shows a v1 example, and the architecture lives in one senior engineer's head. You cannot write four documents by hand before the release, and you cannot proofread four generated ones line by line either.

## What this workflow gives you

- A read-only audit prompt that ranks undocumented exports by how often your own code imports them.
- Prompts for TSDoc, a getting-started guide, an architecture overview, and a migration guide, each tied to a source of truth the agent must read.
- A CI job that fails when an export loses its documentation, an example stops compiling, or a link breaks.
- A one-line check that proves a "documentation-only" change touched no code.
- The failure modes of generated docs and how to recover from each.

## Which documentation should the agent write, and from what?

Generated documentation is only as trustworthy as the source it was generated from. Before you prompt, decide which artifact is the source of truth for each document and which gate proves the document still matches it.

| Document | Source of truth the agent reads | Gate that proves it | What a human still writes |
| --- | --- | --- | --- |
| TSDoc on public exports | Implementation and its tests | TypeDoc `--validation.notDocumented` | Intent: when to use it, and when not to |
| Getting-started guide | Passing tests | Extracted examples type-check | The order of concepts for a newcomer |
| Architecture overview | Import graph and entry points | Diagrams render; every claim cites a file | Design decisions and rejected options |
| Migration guide | `git diff` between release tags | The v1 test suite run against v2; each failure is a documented break | Behaviour changes with an unchanged signature |

The last column is where your review time goes. The agent cannot know why a module exists or why you rejected the obvious design, so do not ask it to guess. Ask it to leave a marked gap instead, and fill the gap yourself.

## Generate documentation with Cursor's agent, step by step

Work on a branch, one document per agent conversation. A fresh conversation per document keeps the context small and makes each diff reviewable on its own.

### Audit documentation gaps before you generate anything

Start in **Plan Mode**, which Cursor describes as creating "detailed implementation plans before writing any code" (Cursor docs, checked 2026-08-28). The audit reads and reports without changing code, so a wrong assumption costs you a re-run rather than a revert.

**Copy-paste prompt: documentation gap audit**

```text
Audit the documentation of this package. Do not edit any file.

1. List every symbol exported from src/index.ts (follow re-exports).
2. For each export, report: has a TSDoc summary (yes/no), documents every
   parameter (yes/no), has an @example (yes/no).
3. Count how many files in src/ and tests/ import each export, and sort the
   undocumented ones by that count, highest first.
4. Check README.md and docs/ for: installation, a first working example,
   an architecture overview, and a migration guide. Report which are missing
   and which reference symbols that no longer exist.

Output a table, then a prioritized list of the 10 exports to document first.
Cite a file path for every claim. If you cannot find evidence, say so
instead of guessing.
```

The import count is a proxy for user impact that the agent can compute from the code. The "cite a file path" rule makes every finding checkable: open the cited file, and the claim is either there or it is not.

### Set a documentation rule so every conversation follows the same standard

Before the generation passes, capture your conventions as a project rule, so that the second and tenth conversation write the same way the first one did. See [project rules in Cursor](/en/cursor-ide/quick-start/project-rules/) for where rules live and how they are applied, and [custom rules and templates](/en/cursor-ide/automate/custom-rules-templates/) for team-wide versions.

```markdown
# Documentation standard

- Document exported symbols only. Never document private helpers.
- One-sentence summary in the present tense, then @param, @returns, @throws.
- Every @example imports from the package name, not from a relative path,
  and must compile as written.
- Never change executable code while documenting. If the code looks wrong,
  add a line to docs/doc-questions.md and move on.
- Where intent cannot be read from code, write TODO(docs-why) instead of guessing.
```

Save it as a project rule from Cursor's rules settings; the [project rules](/en/cursor-ide/quick-start/project-rules/) page gives the file location.

The last two lines matter most. The first stops "documentation" commits from hiding behaviour changes. The second turns the agent's blind spot into a searchable list for the human pass.

### Generate TSDoc for the public API

Switch to the agent for the write pass, and give it the prioritized list from the audit.

**Copy-paste prompt: TSDoc for the top 10 exports**

```text
Add TSDoc to the 10 exports listed below, following the documentation rule.

For each export:
- Read the implementation and every test that calls it before writing.
- Document each @throws by naming the exact error class the code throws.
- Write one @example that imports from the package name and would compile.
- Note non-obvious behaviour explicitly: mutation of arguments, default
  values, coercion, and async ordering.

Do not modify any executable line. When you finish, run:
npx typedoc --emit none --validation.notDocumented --treatValidationWarningsAsErrors src/index.ts
and fix every warning it reports for these 10 exports.

Exports: <paste the list from the audit>
```

TypeDoc 0.28 (checked 2026-09-26) warns on each undocumented export when you pass `--validation.notDocumented`, and `--treatValidationWarningsAsErrors` turns those warnings into a non-zero exit code. `--emit none` skips writing the HTML site, so the command works as a gate.

Then check that the pass changed only comments. Run this in the terminal on the agent's branch, after it commits:

```bash
git diff -U0 main...HEAD -- src | grep -E '^[+-][^+-]' | grep -vE '^[+-][[:space:]]*(\*|/\*\*|\*/|//)' || echo "comments only"
```

Any line it prints is a changed line of code inside a "documentation" commit. Revert that hunk, or move it to its own reviewed change. The check is a quick filter, not proof: it skips changed lines that start with `+` or `-` (such as `++i;`), so still skim the diff.

### Turn passing tests into a getting-started guide

Your test suite already contains working calls with realistic inputs. That makes it a better source for tutorial examples than the agent's imagination.

**Copy-paste prompt: getting-started guide from tests**

```text
Write docs/getting-started.md for a developer who knows TypeScript but has
never used this package. Build it only from code that runs today:

1. Installation with npm, pnpm, and yarn.
2. A first example: find the simplest passing test in tests/ that exercises
   the main entry point, and turn it into a runnable script with imports.
3. The five most common usage patterns across tests/, one section each.
4. Configuration: every option with its default, read from the source,
   not from the existing README.
5. Error handling: each error class the public API throws, and how to catch it.

Put every code sample in a Markdown code fence tagged ts. Under each sample, add an HTML
comment naming the test file it came from, for example
<!-- source: tests/parse.test.ts -->. Keep the guide under 1,200 words.
```

The source comment gives the reviewer a way to check a sample without reading it: open the named test and confirm the call matches. The code-fence rule is what the CI example check in the next section extracts.

### Generate an architecture overview that cites its evidence

Architecture documents go stale faster than any other kind, because no single code change looks like it touches them. Generate the overview so that you can regenerate it cheaply, and keep it short enough that people read it.

**Copy-paste prompt: architecture overview with Mermaid**

```text
Write docs/architecture.md, at most 900 words, for an engineer joining the team.

1. A Mermaid flowchart of the top-level modules in src/ and their import
   relationships. Show at most 12 nodes; group the rest into subgraphs.
2. A Mermaid sequence diagram of one typical request, from the public entry
   point to the returned value.
3. The five most important types or interfaces, one paragraph each.
4. Extension points: every place a user can plug in behaviour.
5. Design decisions: for each, cite the files that show the pattern. Where
   the reason is not visible in code, write TODO(docs-why) instead of a
   plausible explanation.

After each factual sentence, cite the file path in parentheses.
```

Render the diagrams before you commit them. The Mermaid CLI treats a Markdown input file as a set of diagrams and renders each fenced `mermaid` block (`@mermaid-js/mermaid-cli` 12.0.0, checked 2026-09-26). It drives a headless Chrome through Puppeteer, so run it on a machine or CI image that has one:

```bash
npx -p @mermaid-js/mermaid-cli mmdc -i docs/architecture.md -o /tmp/architecture-rendered.md
```

A diagram that fails to render here is broken for most readers, and you find out before they do. For deeper architecture work, including decision records, see [architecture planning with Cursor](/en/cursor-ide/plan/architecture/).

### Build the migration guide from the release diff

Run this in the agent, not in Plan Mode, because the prompt writes docs/migration-v2.md. Replace the two tags with your release tags.

**Copy-paste prompt: v1 to v2 migration guide**

```text
Write docs/migration-v2.md.

1. Run: git diff v1.9.0..HEAD --stat -- src
   then read the full diff for every file that changes an exported symbol.
2. List every breaking change: renamed or removed exports, changed parameter
   order or types, new required parameters, changed return types, changed
   defaults.
3. For each, show a v1 snippet, the v2 equivalent, and one line on what the
   user must do. Order by how many call sites in tests/ the change affects.
4. Add a "Search and replace" table for purely mechanical renames.
5. Add a "Behaviour changes" section listing any exported function whose
   body changed but whose signature did not. For each, write
   TODO(docs-why) and name the commit that changed it.

Do not describe a change you did not see in the diff.
```

Section 5 is the one that saves you. Diffs expose signature changes reliably; a function that keeps its signature and returns something different is exactly what a generated guide misses, so the prompt makes the agent list the candidates for you to judge. For large upgrades of your own dependencies rather than your users', see [framework and library migrations with Cursor](/en/cursor-ide/build/migration/).

## How do you verify generated docs without reading every line?

Review the generated text where judgment is needed, and let machines check everything else. Put these gates in CI so they run on every pull request, not only on the day you generated the docs.

1. **Coverage.** TypeDoc validation fails the build when a new export lands without documentation.
2. **Examples compile.** A small script extracts every code fence tagged `ts` from `docs/` and `README.md` and type-checks it against the package source (the package name resolves to `src/index.ts`).
3. **Links resolve.** `markdown-link-check` fails on a dead link, including links to files and anchors you renamed.
4. **Diagrams render.** `mmdc` renders every Mermaid block (see the architecture-overview section).
5. **Human sign-off.** The owner of the module reviews only the `TODO(docs-why)` gaps, the "Behaviour changes" section, and the audit's list of symbols that no longer exist. That is a short, scoped review, not a read of every generated page.

Ask the agent to write the example extractor, because it is ordinary code with a clear contract:

**Copy-paste prompt: documentation checks for CI**

```text
Create scripts/check-doc-examples.ts, runnable with `npx tsx`:

- Find every Markdown code fence tagged ts in README.md and docs/**/*.md.
- Write each one to its own file in a temporary directory, keeping the
  source file and line number in the file name.
- Type-check all of them with the TypeScript compiler API against this
  package's tsconfig, resolving the package name to src/index.ts.
- Print each failure as <markdown file>:<line>: <compiler message>,
  and exit with code 1 if there is any failure.

Then run it and fix the documentation (not the code) until it passes.
Add a test for the extractor in tests/scripts/ with one valid and one
invalid fence.
```

Then wire the gates into a workflow. This job reads the repository only, holds no secrets, and runs no agent:

```yaml
# .github/workflows/docs-check.yml
name: docs-check
on: pull_request
permissions:
  contents: read
jobs:
  docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 22
      - run: npm ci
      - run: npx typedoc --emit none --validation.notDocumented --treatValidationWarningsAsErrors src/index.ts
      - run: npx tsx scripts/check-doc-examples.ts
      - run: npx markdown-link-check -q -c .markdown-link-check.json README.md
      - run: find docs -name "*.md" -print0 | xargs -0 -n1 npx markdown-link-check -q -c .markdown-link-check.json
```

`markdown-link-check` (3.15.0) also requests external URLs by default, which makes a pull-request gate flaky. Give it a `.markdown-link-check.json` with an `ignorePatterns` entry for `^https?://`, so this gate checks only local files and anchors, and check external links in a separate, non-blocking scheduled job.

The job above leaves out the Mermaid gate; add the `mmdc` command from the architecture-overview section as its own step once Puppeteer's Chrome runs on your runner. For review on the pull request itself, [Bugbot](/en/cursor-ide/ship/bugbot/) reviews the diff like any other change. It adds to the gates above; it does not replace them.

**What the gates cannot catch**

A TSDoc comment that is present, compiles, and describes the old behaviour passes every check above. The only defence is to tie examples to tests: when a behaviour change breaks a test, regenerate the TSDoc and guide sections that cite that test.

## When agent-generated documentation goes wrong

**The agent documents behaviour the code does not have.** It inferred a parameter's meaning from its name, or it described a retry that does not exist. Recovery: require a cited file path per claim, as the prompts above do, and spot-check three citations per document. If one is wrong, discard the section and regenerate it with the implementation file named explicitly in the prompt.

**Examples look right but do not compile.** Missing imports, relative paths, or a setup step the test had in `beforeEach`. Recovery: the example checker names the file and line; paste its output back into the agent with "fix the documentation, not the code".

**A documentation commit changed code.** The agent "fixed" a bug it noticed while reading. Recovery: the comments-only check above prints the offending lines. Revert them, and move the suspected bug to `docs/doc-questions.md` for a separate, tested change.

**The architecture diagram is an unreadable hairball.** A full import graph of a large codebase has hundreds of edges. Recovery: cap the node count in the prompt, as above, and draw one diagram per subsystem rather than one for everything.

**The migration guide misses a behaviour change.** The signature stayed the same, so the diff looked harmless. Recovery: run the v1 test suite against the v2 build; every failure that is not a documented break belongs in "Behaviour changes".

**Generated docs are long and nobody reads them.** Agents write to fill space unless you stop them. Recovery: set a word limit in every prompt, and cut any section a reader would skip before you merge.

**The docs drift again three months later.** Recovery: keep the CI gates on, and regenerate on a schedule. A Cursor [Automation](/en/cursor-ide/automate/cloud-agents-automations/) with a Scheduled trigger can rerun the audit prompt weekly; run the TSDoc prompt on what it flags, and send the result through the same gates as a normal pull request.

## Where to go next with documentation in Cursor

If your guide covers integrations with third-party libraries, a documentation MCP server gives the agent their current docs instead of what the model remembers.

- [Documentation as agent context](/en/workflows/context/documentation-as-context/) — Write docs that also make the agent better at your codebase, not just readers.
- [Project rules in Cursor](/en/cursor-ide/quick-start/project-rules/) — Store the documentation standard where every agent conversation applies it.
- [CI/CD with Cursor](/en/cursor-ide/ship/ci-cd/) — Extend the docs-check job into the rest of your pipeline.
- [Documentation and writing skills](/en/ecosystem/skills/document-and-writing-skills/) — Agent Skills that add documentation workflows to Cursor, Claude Code and Codex.
- [Documentation MCP servers](/en/ecosystem/mcp/context7/) — Give the agent current third-party library docs when your guide covers integrations.
- [Documentation with Claude Code](/en/claude-code/build/documentation/) — The same job from the terminal, with hooks and headless runs.
- [Documentation with Codex](/en/codex/build/documentation/) — The same job with Codex and AGENTS.md.
