Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Workflow recipe

Write code documentation from the source with an AI agent

A cited fact sheet first, docstrings with runnable examples, then proof that only docs changed and every example runs.

By Checked Intermediate1 h 10 min6 steps
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On this page

To generate documentation from code with AI, pin a commit, list the public names you want documented, and ask the agent for a read-only fact sheet in which every statement cites a file and line. Check the surprising facts yourself, then let the agent write docstrings with runnable examples, prove with a script and the doctests that only documentation changed, and publish an HTML reference with the open questions sent to the code’s owner.

Ask an agent to “add docs” and you get fluent text that describes what the function name suggests, not what the code does. The dangerous errors are the plausible ones: a default described from the parameter name, an exception that is never raised, rounding that “rounds up”. Splitting the work into facts first, prose second, and making every example executable turns those errors into failing doctests and a list of questions instead of wrong documentation. The recipe uses Python, but the order of work suits any language with doc comments.

TerminalAbout 5 min

1. Pin the commit and list the public API

Documentation describes one version of the code, so fix it, and decide which names are public before the agent starts. A package’s __all__ is the usual answer in Python.

git switch -c docs/public-api
git rev-parse --short HEAD
git grep -n "__all__"
uv run pytest -q

Our module exported five names (Parcel, quote, volumetric_weight, zone_for, format_label) and had 6 passed. Private helpers stay out of scope: documenting them makes the page longer and freezes things the owner may want to change.

Claude CodeAbout 10 min

2. Get a fact sheet with a citation on every fact

Start Claude Code read-only with claude --permission-mode plan and paste the prompt. Facts first, prose later: the fact sheet is short enough to check, and the docstrings in step 4 may only use what is in it.

Fact sheet for the public API · Claude Code
Document the public API of this package: [PUBLIC NAMES OR THE FILE THAT LISTS THEM]. Do not edit any file yet. For each name, write a fact sheet: - signature - each parameter: type, default, and what the code does with it - return value and type - every exception it can raise, and the exact condition - side effects - behaviour a caller could be surprised by: rounding, case handling, falsy values, limits, validation done elsewhere Rules: - Every fact ends with a citation in the form path/to/file:line from code you opened in this session. - Describe what the code does, not what the names suggest. If the code and a name or comment disagree, report the code and add a QUESTION. - Do not run anything that changes files. - End with a numbered list of QUESTIONS for the code owner: behaviour that looks unintended or undecided.

In plan mode Claude Code writes the full answer to a plan file under ~/.claude/plans/ and prints a summary; copy the file to FACTS.md outside the repository. Ours took two minutes and came back with five fact sheets, 15 questions and a list of surprises we had not planned: weight is rounded to the nearest 0.1 kg rather than up, the 30 kg limit is checked before that rounding, prices are rounded half-even (an express 1.1 kg parcel costs 6.28, not 6.29), express="no" still charges express, and a label line can pass the width check and come out longer once upper-cased.

TerminalAbout 15 min

3. Check the surprising facts by running them

Pick every fact the sheet lists under surprises, every exception and every default, and confirm each with a one-line call against the real code. Mark each in FACTS.md as confirmed or wrong.

uv run python -c "from shipping import Parcel, quote; print(quote(Parcel(1.2, 30, 20, 10), 'gb', insured_value=0))"
uv run python -c "from shipping import format_label; print(format_label('Ana Silva', '1 High St', 'Leeds', 'ls1 4ap', 'gb'))"
uv run python -c "from shipping import zone_for; zone_for('XX')"
uv run python -c "from shipping import Parcel, quote; print(quote(Parcel(1.1, 10, 10, 10), 'GB', express=True))"

Our four calls confirmed that an insured value of 0 adds no insurance charge at all (4.28, the same as no insurance), that the label upper-cases every line including the name, that an unknown country raises KeyError, not ValueError, and the half-even 6.28. Every fact we checked held, so we passed no corrections in step 4. A fact that fails its check is struck from the sheet and goes on the questions list.

Claude CodeAbout 15 min

4. Write docstrings with runnable examples

Switch Claude Code to accept edits (Shift+Tab until the status bar says so) and paste the second prompt in the same session. The examples are doctests, so step 5 can run them.

Docstrings from the fact sheet · Claude Code
Write docstrings for [PUBLIC NAMES] in [DOCSTRING STYLE] using only the fact sheet above, with any corrections I give here: [CORRECTIONS FROM YOUR CHECKS, OR NONE]. Rules: - Change docstrings only. Do not change code, comments, formatting, imports or names, and do not add files. - Each docstring has: one summary line, Args, Returns, Raises, and an Examples section written as doctests that run against the real code. - Write the example outputs from running them, not from memory. - Do not state anything that is not in the fact sheet. Where a QUESTION is open, describe the current behaviour plainly and do not guess the intent. - Keep each docstring under 25 lines. When you finish, run [DOCTEST AND TEST COMMAND] and report the result, the files you changed and any fact you could not express.

If Claude Code asks for approval to run commands, allow the test command, or the examples will be written without being run. Ours took two minutes, added 114 lines to two files and reported 11 passed: the six tests plus one doctest per name. It also listed the facts it could not fit in 25 lines, such as NaN weights returning Decimal('NaN'); add any you need by hand.

Read two or three docstrings in full before going on. Look for the surprises from step 3: a docstring that leaves them out is the agent smoothing over the code.

TerminalAbout 15 min

5. Prove only documentation changed and every example runs

This is the proof step. A script compares the syntax tree of each changed file with and without docstrings against the pinned commit, so any change to code fails it whatever the diff looks like. Save it outside the repository as ../tools/docs_only.py.

"""Fail if a change touched anything in Python files except docstrings and comments."""
import ast
import subprocess
import sys

base = sys.argv[1] if len(sys.argv) > 1 else "HEAD"


def strip_docstrings(source):
    tree = ast.parse(source)
    for node in ast.walk(tree):
        if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
            body = node.body
            if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) \
                    and isinstance(body[0].value.value, str):
                node.body = body[1:] or [ast.Pass()]
    return ast.dump(tree)


changed = subprocess.run(["git", "diff", "--name-only", base, "--", "*.py"],
                         capture_output=True, text=True, check=True).stdout.split()
failed = False
for path in changed:
    old = subprocess.run(["git", "show", f"{base}:{path}"], capture_output=True, text=True).stdout
    new = open(path, encoding="utf-8").read()
    if strip_docstrings(old) != strip_docstrings(new):
        print(f"CODE CHANGED: {path}")
        failed = True
    else:
        print(f"docs only:    {path}")
sys.exit(1 if failed else 0)

Then run it with the doctests and the test suite:

uv run python ../tools/docs_only.py
uv run pytest -q --doctest-modules shipping tests

Every changed file should print docs only:, and the test count should be your baseline plus one doctest per documented name. We saw docs only: for both files and 11 passed. Then read each Raises section against the fact sheet: a doctest proves an example, not a claim in prose. Our quote docstring said a non-numeric or NaN insured_value raises decimal.InvalidOperation; two one-line calls confirmed both.

TerminalAbout 10 min

6. Publish the reference and send the questions

Build the HTML reference with pdoc, which reads the docstrings and respects __all__, then open docs/api/index.html and read it as a user would.

uv run --with pdoc pdoc shipping -d google -o docs/api

Ours built index.html, shipping.html and a search index, with sections for exactly the five public names and their Args, Returns, Raises and Examples. Commit the docstrings, decide with the team whether the generated HTML belongs in the repository or in CI, and send the questions list from the fact sheet to the code’s owner. Questions about behaviour are the most useful thing this recipe produces after the docs themselves: each one is either a bug report or a sentence the docs can now state with confidence.

Check it worked

Verification checklist

0 of 7 done

When it goes wrong

If the agent says some example outputs were written before it could run them, its commands were probably blocked waiting for approval. In our run two examples were written that way; the doctest run in the same turn confirmed them, but outputs from memory are where Decimal and float formatting goes wrong. Allow the test command (with --allowedTools or when prompted) and ask the agent to run every example and paste the real output.

If the docs-only script prints CODE CHANGED, the agent touched code: a reformatted line, a type hint added on the way past, a default changed. We tested the script by changing one constant in a scratch copy and it failed as it should. Discard that file’s changes with git restore, repeat the rule that only docstrings may change, and run the prompt again for that file. If the script itself fails with python: command not found, run it through your project’s interpreter (uv run python), as the step shows.

If the docstrings read well but leave out the surprising behaviour, the agent smoothed it over or ran out of room. Ours hit the 25-line limit on quote and listed what it had left out (NaN handling, the tie-breaking on weight rounding). Compare each docstring with the surprises in the fact sheet and add a sentence for each one that matters to callers.

Variations

For TypeScript, ask for TSDoc comments in step 4, replace the docs-only script with a check that the emitted JavaScript is unchanged (build before and after and diff the output folder), and build the reference with a tool such as TypeDoc. The fact sheet and the questions list do not change.

With Codex or Cursor, use the read-only or ask mode for step 2 and agent mode for step 4, with the same prompts. In CI, run the docs-only script and the doctests on every pull request that only claims to change documentation.

For a README or a how-to guide rather than reference docs, keep steps 1 to 3, then ask for the guide with every code sample taken from the doctests, so the guide’s examples are already tested. To stop the agent reporting done before it has run the checks, the Verification before completion skill makes it show the command output first.

If you do not know the code yet, understand a codebase with AI first, with the same citation habit. When the questions list turns up untested behaviour, generate unit tests with AI for legacy code to pin it. New to the agent? The Claude Code tutorial covers the basics and the glossary explains plan mode. The AI-assisted software engineering path puts these recipes in order.

Outcome and tools

Outcome
Docstrings with runnable examples for a module's public API, proof that no code changed, an HTML reference page and a list of questions for the code owner.
For
Developers
Variants for
Claude Code

Check your understanding

Write code documentation from the source with an agent quiz

Pinning the public API, cited fact sheets, checking surprises by running them, doctest examples, the docs-only proof script and pdoc.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. Why does the recipe ask for a fact sheet before any docstrings are written?
  • Understand an unfamiliar codebase with an AI agent

    Get a read-only map where every claim cites a file and line, check the citations, trace one path and test what you learned.

    WorkflowBeginner1 h 5 min6 steps

  • Write unit tests for legacy code with a coding agent

    An agent writes characterisation tests, you check for weak assertions and prove them with mutation testing.

    WorkflowBeginner1 h6 steps

  • Your first session with Claude Code

    Install it, run it in a real repository, approve its first changes, commit a reviewed edit and learn the commands you will use daily.

    TutorialBeginner30 min

  • Plan mode

    An agent mode in which it reads and researches the code and proposes a plan, without editing any files until you approve the plan.

    Glossary

  • AI-assisted software engineering

    Learn AI-assisted software engineering on real repositories: set up coding agents, give them good instructions, review their diffs and run several in parallel.

    Learning pathIntermediate11 h14 steps

Back to top