The morning after I first added a workflow that rewrote the README of my own Next.js repo, I opened the diff and it did look better. It also no longer had three lines I had added by hand after forgetting them more than once: re-running wrangler secret before deploying to Cloudflare Workers.
The generated prose was fine. What disappeared was the part you can't learn by reading the code — the caveats someone writes down after getting burned.
This piece shows how I now update README, CHANGELOG and API docs on every push while leaving the hand-written parts completely alone. Every script below was run on my machine before going into the article; where I couldn't verify something, I say so.
The Rule I Settled On: Generate Only Inside a Fence
After that morning I stopped replacing whole files. Instead, a pair of comment markers fences off a block, and the scripts only ever rewrite what sits between them.
# my-project
## Install
(Humans write this, including the deploy caveats.)
<!-- auto-docs:overview:start -->
(Only this part is regenerated.)
<!-- auto-docs:overview:end -->Outside the fence is human text; inside is machine text. CHANGELOG and the API reference work the same way.
The machine writes inside the fence; people own everything outside it. Since adopting that line, opening an auto-commit diff no longer makes my stomach tighten.
A side benefit: if the fenced content is identical to last time, the file isn't touched at all. The old "only update when the diff exceeds 30 lines" threshold simply isn't needed anymore.
Three Ways to Do This, and When Each Fits
Even inside CI there are three ways to have Claude write docs. I use the SDK-script approach in this article, but they suit quite different jobs.
| Approach | What runs | Input scope | Output shape | Cost predictability | Best when |
|---|---|---|---|---|---|
| Python SDK scripts (this article) | One Messages API call per document | Only the files the script selects | Always the same fenced block | High (input size is roughly constant) | Where and how to write is fixed: README overview, CHANGELOG, API list |
anthropics/claude-code-action@v1 | Claude Code reads the repo and edits files | The agent explores on its own | It decides which files to change | Low (depends on how much it explores) | You want judgment, e.g. fix every description this change made stale |
claude -p in a CI step | Headless Claude Code | Depends on CLAUDE.md and allowed tools | Depends on the prompt | In between | You want the same prompt and CLAUDE.md you use locally, in CI |
My rule of thumb: if the place and shape of the output are the same every time, use SDK scripts; if you want the model to decide which files need fixing, use claude-code-action. You can combine them, too — scripts on every push, claude-code-action only for a pre-release review.
Setup: One Policy File, Read by Both Claude Code and the Scripts
You only need Python 3.12 and the anthropic library (2.8.0 is the latest on PyPI as of November 2026; I checked).
pip install "anthropic>=2.8,<3"
export ANTHROPIC_API_KEY=YOUR_API_KEYI need to correct something the earlier version of this article said: that writing your policy into CLAUDE.md would shape what the scripts generate. It doesn't. CLAUDE.md is read by Claude Code. A script calling the Messages API directly never sees it.
So the policy lives in a single file, docs/DOC_POLICY.md. The scripts put it into the system prompt, and CLAUDE.md imports it for Claude Code.
<!-- docs/DOC_POLICY.md -->
# Documentation policy
- The generated part of README covers overview, key features and basic usage only. No install or deploy steps.
- docs/api.md is for developers. Copy types exactly as written; never guess.
- Code examples in TypeScript.
- Never describe settings or features that don't exist.<!-- CLAUDE.md (for Claude Code) -->
@docs/DOC_POLICY.mdNow a README edit you ask Claude Code for locally and one the CI script makes follow the same rules.
Shared Helpers: Never Write a Truncated Reply
These helpers are shared by all three scripts. They solve two problems: writing a reply that stopped at max_tokens straight into a file, and re-implementing the fence replacement three times.
# scripts/_docs_common.py — shared helpers for the three scripts
import os
from pathlib import Path
import anthropic
# Models can be swapped via env vars (defaults are Active as of November 2026)
SMALL_MODEL = os.environ.get("DOCS_MODEL_SMALL", "claude-haiku-4-5-20251001")
LARGE_MODEL = os.environ.get("DOCS_MODEL_LARGE", "claude-sonnet-4-6")
_client = None
def ask(model: str, system: str, user: str, max_tokens: int) -> str:
"""Call once and return the text. Never let a truncated reply reach a file."""
global _client
if _client is None:
_client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
res = _client.messages.create(
model=model,
max_tokens=max_tokens,
system=system,
messages=[{"role": "user", "content": user}],
)
if res.stop_reason == "max_tokens":
raise RuntimeError(f"Reply was cut off at max_tokens={max_tokens}. Narrow the input or raise the limit.")
text = "".join(b.text for b in res.content if b.type == "text").strip()
if not text:
raise RuntimeError("Reply was empty")
return text
def load_policy(repo: str = ".") -> str:
"""The writing policy. Claude Code reads the same file via @docs/DOC_POLICY.md."""
p = Path(repo) / "docs" / "DOC_POLICY.md"
return p.read_text(encoding="utf-8") if p.exists() else ""
def replace_block(path: str, name: str, body: str) -> bool:
"""Replace only what sits inside <!-- auto-docs:NAME:start/end -->. Hand-written text outside is left alone."""
start = f"<!-- auto-docs:{name}:start -->"
end = f"<!-- auto-docs:{name}:end -->"
p = Path(path)
src = p.read_text(encoding="utf-8") if p.exists() else ""
block = f"{start}\n{body.strip()}\n{end}"
if start in src and end in src:
head, rest = src.split(start, 1)
_, tail = rest.split(end, 1)
new = head + block + tail
else:
new = (src.rstrip() + "\n\n" if src.strip() else "") + block + "\n"
if new == src:
return False
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(new, encoding="utf-8")
return TrueI raise on stop_reason == "max_tokens" because the old API reference once ended mid-sentence on its last function and stayed that way for weeks. A truncated document, I've come to feel, is worse than none.
Model IDs can be overridden through environment variables. Both defaults, claude-haiku-4-5-20251001 and claude-sonnet-4-6, are listed as Active on the official deprecations page as of November 2026.
README: Pick Files by Last Commit, Not by mtime
The README fence gets an overview, key features and usage.
# scripts/generate_readme.py — update only the fenced block inside README
import subprocess
import sys
from pathlib import Path
from _docs_common import LARGE_MODEL, ask, load_policy, replace_block
EXTS = {".ts", ".tsx", ".py", ".js", ".go"}
EXCLUDE = {"node_modules", "dist", ".next", "__pycache__", ".git", "coverage"}
def recently_committed_files(repo: str, limit: int = 8) -> list[str]:
"""Order sources by last commit. In CI every mtime equals checkout time, so mtime is useless."""
out = subprocess.run(
["git", "-C", repo, "log", "--name-only", "--format=", "--no-renames"],
capture_output=True, text=True, check=True,
).stdout
picked: list[str] = []
for line in out.splitlines():
if not line or line in picked:
continue
p = Path(repo) / line
is_test = ".test." in p.name or ".spec." in p.name
if p.suffix in EXTS and p.exists() and not is_test and not EXCLUDE & set(p.parts):
picked.append(line)
if len(picked) >= limit:
break
return picked
def build_prompt(repo: str, files: list[str]) -> str:
parts = []
for rel in files:
text = (Path(repo) / rel).read_text(encoding="utf-8", errors="replace")[:2500]
parts.append(f"### {rel}\n```\n{text}\n```")
return "\n\n".join(parts)
def main() -> int:
repo = sys.argv[1] if len(sys.argv) > 1 else "."
dry = "--dry-run" in sys.argv
files = recently_committed_files(repo)
if not files:
print("No source files to read", file=sys.stderr)
return 1
system = (
"You write only the overview and usage part of a README. "
"Installation, deployment and caveats are written by humans, so never output them. "
"Do not describe features the code does not have.\n\n" + load_policy(repo)
)
user = (
"From the sources below, write an overview (3 sentences max), key features (5 items max) "
"and basic usage (one code example) in Markdown. Start headings at ##.\n\n"
+ build_prompt(repo, files)
)
body = ask(LARGE_MODEL, system, user, max_tokens=2048)
if dry:
print(body)
return 0
changed = replace_block(str(Path(repo) / "README.md"), "overview", body)
print("README: updated" if changed else "README: no change", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())The old version picked the eight files with the newest modification time. That works on a laptop, but on GitHub Actions every checked-out file has nearly the same mtime, so the ordering means nothing. Reading git log --name-only newest-first and taking the most recently committed files fixes that.
In a small test repo I pushed a file's mtime back to 2001 on purpose; the file I had just committed, src/c.ts, still came first.
['src/c.ts', 'scripts/_docs_common.py', ..., 'src/a.ts', 'src/b.ts']You may notice scripts/ itself shows up. If you'd rather keep the automation out of your README, add "scripts" to EXCLUDE.
CHANGELOG: Rebuild Unreleased Each Run, and Let Regex Handle Conventional Commits
The old CHANGELOG step had two bugs. It prepended a fresh ## [unreleased] section on every push, so identical headings piled up. And it printed "no new commits found" to stdout, which then got written into the CHANGELOG itself.
# scripts/generate_changelog.py — rebuild the Unreleased section every run (never stack it)
import json
import re
import subprocess
import sys
from _docs_common import SMALL_MODEL, ask, replace_block
SECTIONS = {"features": "Added", "fixes": "Fixed", "improvements": "Changed"}
CONVENTIONAL = re.compile(r"^(feat|fix|refactor|perf|docs|chore|test|ci|build|style)(\([^)]*\))?!?:\s*(.+)")
PREFIX_TO_SECTION = {"feat": "features", "fix": "fixes", "refactor": "improvements", "perf": "improvements"}
def commits_since_last_tag() -> list[str]:
tag = subprocess.run(["git", "describe", "--tags", "--abbrev=0"], capture_output=True, text=True)
rng = [f"{tag.stdout.strip()}..HEAD"] if tag.returncode == 0 else ["-50"]
out = subprocess.run(["git", "log", *rng, "--no-merges", "--format=%s"],
capture_output=True, text=True, check=True).stdout
# keep our own auto-commits out of the CHANGELOG
return [s for s in out.splitlines() if s and not s.startswith("docs: auto-update")]
def classify(subjects: list[str]) -> dict[str, list[str]]:
result = {k: [] for k in SECTIONS}
unknown = []
for s in subjects:
m = CONVENTIONAL.match(s)
if m: # conventional commits are sorted by regex (no API cost)
sec = PREFIX_TO_SECTION.get(m.group(1))
if sec:
result[sec].append(m.group(3))
else:
unknown.append(s)
if unknown: # only the non-conforming ones go to the small model
listing = "\n".join(f"{i}: {s}" for i, s in enumerate(unknown))
text = ask(
SMALL_MODEL,
"You classify commit subjects. Return JSON only.",
"Put each line into exactly one of features / fixes / improvements / other, "
'returned as {"0": "fixes", "1": "other"}.\n\n' + listing,
max_tokens=1024,
)
try:
labels = json.loads(text[text.find("{"): text.rfind("}") + 1])
except ValueError:
labels = {}
print(f"Warning: could not parse the classification; skipping {len(unknown)} commits", file=sys.stderr)
for i, s in enumerate(unknown):
sec = labels.get(str(i))
if sec in result:
result[sec].append(s)
return result
def render(classified: dict[str, list[str]]) -> str:
lines = ["## [Unreleased]"]
for key, title in SECTIONS.items():
if classified[key]:
lines += ["", f"### {title}", *[f"- {s}" for s in classified[key]]]
return "\n".join(lines) if len(lines) > 1 else "## [Unreleased]\n\n(Nothing worth recording yet.)"
def main() -> int:
subjects = commits_since_last_tag()
body = render(classify(subjects))
if "--dry-run" in sys.argv:
print(body)
return 0
changed = replace_block("CHANGELOG.md", "unreleased", body)
print("CHANGELOG: updated" if changed else "CHANGELOG: no change", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())You don't need a model to sort commits that start with feat: or fix: — a regex does it. Only subjects that don't follow the convention go to the model, so in a repo that sticks to Conventional Commits, the CHANGELOG costs nothing in API fees.
The old version classified with Haiku and then had Sonnet "polish" the result. But the output is just headings and bullets, which Python can lay out. Prose release notes are something I want when publishing a release, not on every push.
Run it twice and the second run reports no change; the file isn't rewritten.
$ python scripts/generate_changelog.py
CHANGELOG: updated
$ python scripts/generate_changelog.py
CHANGELOG: no change<!-- auto-docs:unreleased:start -->
## [Unreleased]
### Fixed
- handle null
- typo
### Changed
- split module
<!-- auto-docs:unreleased:end -->When I tag a release, I move the fenced content outside the fence by hand as ## [0.2.0] - date. Where a release begins is a call I want to make myself.
API Reference: Capture Each Export Until Its Parentheses Close
The old extractor grabbed only lines starting with export. A function whose parameters wrapped onto several lines was cut at export function add(, and the model filled in the rest by guessing. That is how parameters that don't exist ended up in the docs.
# scripts/generate_api_docs.py — build docs/api.md from exported definitions
import sys
from pathlib import Path
from _docs_common import LARGE_MODEL, ask, load_policy, replace_block
SKIP_SUFFIXES = (".d.ts", ".test.ts", ".spec.ts", ".test.tsx", ".spec.tsx")
def exported_signatures(text: str) -> list[str]:
"""Take each export line up to where its parentheses close, plus the JSDoc right above it."""
lines = text.splitlines()
out, i = [], 0
while i < len(lines):
if lines[i].lstrip().startswith("export"):
j = i - 1 # walk back over the preceding JSDoc
while j >= 0 and lines[j].strip().startswith(("*", "/**", "*/")):
j -= 1
chunk, depth = [], 0
for k in range(i, min(i + 40, len(lines))):
chunk.append(lines[k])
depth += lines[k].count("(") - lines[k].count(")")
if depth <= 0 and lines[k].rstrip().endswith(("{", ";", ">", "=")):
break
out.append("\n".join(lines[j + 1:i] + chunk))
i += len(chunk)
else:
i += 1
return out
def collect(src_dir: str, max_files: int = 20) -> str:
src = Path(src_dir)
if not src.is_dir():
raise FileNotFoundError(f"Directory not found: {src_dir}")
files = sorted(
f for f in [*src.rglob("*.ts"), *src.rglob("*.tsx")]
if "node_modules" not in f.parts and not f.name.endswith(SKIP_SUFFIXES)
)
blocks = []
for f in files[:max_files]:
sigs = exported_signatures(f.read_text(encoding="utf-8", errors="replace"))
if sigs:
blocks.append(f"### {f.as_posix()}\n```typescript\n" + "\n\n".join(sigs) + "\n```")
if not blocks:
raise ValueError("No exported definitions found")
return "\n\n".join(blocks)
def main() -> int:
src_dir = sys.argv[1] if len(sys.argv) > 1 else "src"
try:
signatures = collect(src_dir)
except (FileNotFoundError, ValueError) as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if "--show-input" in sys.argv: # check what would be sent, without calling the API
print(signatures)
return 0
system = (
"You write an API reference from TypeScript exports. "
"Copy parameter and return types exactly as written in the code; never fill gaps by guessing.\n\n"
+ load_policy(".")
)
body = ask(LARGE_MODEL, system,
"For each export, give a 1-2 sentence description, parameters, return value and an example, in Markdown.\n\n" + signatures,
max_tokens=8192)
changed = replace_block("docs/api.md", "api", "# API reference\n\n" + body)
print("docs/api.md: updated" if changed else "docs/api.md: no change", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())--show-input shows what would be sent without calling the API. Multi-line parameters now come through, along with the JSDoc above them.
### src/a.ts
```typescript
/**
* Adds two numbers
*/
export function add(
a: number,
b: number,
): number {
export type Id = string;
```This is a lightweight, almost regex-level extractor; it doesn't parse TypeScript. Overloads and heavy generics may slip through. If type accuracy matters, I think it's safer to let TypeDoc produce the types and have Claude write only the descriptions.
GitHub Actions: Catch Failures with ||
Here is the old version's biggest bug first.
# Before (old version — does not work)
run: |
python scripts/generate_readme.py . "${{ github.repository }}" > /tmp/readme_new.md
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
echo "::warning::README generation failed"
exit 0
fiWhen you don't set shell, a run step on Linux executes as bash -e {0} (documented in the official Workflow syntax reference). With -e, the step ends the moment Python fails; EXIT_CODE=$? never runs. The "keep going on failure" branch had never executed once. Reproducing it locally:
$ bash -e -c 'false > /tmp/x_out; EXIT_CODE=$?; echo "never printed $EXIT_CODE"'; echo "outer exit=$?"
outer exit=1
$ bash -e -c 'fail=0; false || { echo "warn caught"; fail=1; }; echo "fail=$fail"'
warn caught
fail=1There's a second trap: with > docs/api.md, the shell empties the file before Python even starts. If generation fails, you commit an empty reference. The current scripts write only after success, from inside Python.
# .github/workflows/auto-docs.yml
name: Auto docs
on:
push:
branches: [main]
paths:
- 'src/**'
- 'lib/**'
- '!**/*.test.ts'
- '!**/*.spec.ts'
# stop two back-to-back pushes from racing each other
concurrency:
group: auto-docs
cancel-in-progress: false
jobs:
docs:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0 # tags and history are needed
- uses: actions/setup-python@v7
with:
python-version: '3.12'
- run: pip install "anthropic>=2.8,<3"
- name: Generate
id: gen
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# The default shell is bash -e. Catch failures with || (checking $? afterwards never runs).
fail=0
python scripts/generate_readme.py . || { echo "::warning::README generation failed"; fail=1; }
python scripts/generate_changelog.py || { echo "::warning::CHANGELOG generation failed"; fail=1; }
python scripts/generate_api_docs.py src || { echo "::warning::API docs generation failed"; fail=1; }
echo "fail=$fail" >> "$GITHUB_OUTPUT"
- name: Commit
run: |
# git diff ignores untracked files; use status so a first-run CHANGELOG.md counts
if [ -z "$(git status --porcelain -- README.md CHANGELOG.md docs/)" ]; then
echo "No documentation changes"; exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
# git add is fatal on a missing path, so add only what exists
for f in README.md CHANGELOG.md docs; do
if [ -e "$f" ]; then git add -- "$f"; fi
done
git commit -m "docs: auto-update [skip ci]"
git pull --rebase origin main
git push
- name: Report partial failure
if: steps.gen.outputs.fail == '1'
run: exit 1 # keep what succeeded, but turn the run red so someone noticesThree notes on why it's written this way:
- Catch with
||, then fail at the end. What succeeded is still committed, but the run turns red so the failure gets noticed. Exiting 0 keeps everything green and nobody finds out. git status --porcelain. The oldgit diff --quietignores untracked files, so a first-runCHANGELOG.mdcould be judged "no change".concurrency. Two quick pushes otherwise race, and the second one's commit fails to push.
I confirmed on GitHub's release pages that the latest actions/checkout and actions/setup-python are in the v7 series as of November 2026.
When It Misbehaves: A Triage Table
Some of these I hit myself; the rest happen with the old code as written.
| Symptom | Likely cause | How to check | Fix |
|---|---|---|---|
A step failed but no ::warning:: ever appears | Default bash -e ends the step before $? is read | In the log, does the step end right after the failing python line? | Use command || { warn; fail=1; } |
docs/api.md committed empty | The > redirect truncates the file first | Look at the commit diff from the failed run | Write from inside the script, only after success |
Many ## [unreleased] headings in CHANGELOG | A new section is prepended each run | grep -c 'Unreleased' CHANGELOG.md | Rebuild the fenced block each run |
| CHANGELOG contains "no new commits found" | Status messages go to stdout | Run the script with > /dev/null and see what's left | Send messages to stderr (file=sys.stderr) |
| README is based on unrelated files | In CI, every mtime equals checkout time | ls -l --time-style=full-iso src inside the job | Order by git log --name-only |
| The reference ends mid-sentence | Hit max_tokens | Check the reply's stop_reason | Raise and don't write; narrow input or raise the limit |
| "No documentation changes" on the very first run | git diff ignores untracked files | Does git status --porcelain show ??? | Decide with git status --porcelain |
| 400 error after switching to Sonnet 5.5 / Haiku 5.5 | Sampling parameters such as temperature | Does the error name that parameter? | Remove temperature, top_p, top_k |
That last row concerns the old advice to set temperature=0.3 for steadier output. According to the official migration guides, Sonnet 5.5 and Haiku 5.5 reject sampling parameters with a 400. The current scripts don't set temperature; the fences and the policy file keep the output steady instead.
Three Common Misconceptions
"Without [skip ci], the auto-commit will loop forever."
GitHub's docs say pushes made with the repository's GITHUB_TOKEN don't create new workflow runs (with exceptions such as workflow_dispatch). So with the default token there's no loop even without [skip ci]. If you later switch to a personal access token or a GitHub App token, though, those pushes do trigger workflows — which is why I keep [skip ci] anyway.
"Policy in CLAUDE.md also applies to scripts that call the API."
As corrected above, it doesn't. CLAUDE.md is for Claude Code. Keep the policy in its own file, inject it into the system prompt from scripts, and import it into CLAUDE.md with @.
"Prompt caching cuts this pipeline's cost by up to 90%."
The old version said this, and it doesn't hold here. Only a sufficiently long prefix can be cached; the official minimums are 1,024 tokens for Sonnet 4.6 and 4,096 for Haiku 4.5. The system prompts here are a few hundred tokens, so nothing gets cached — and the part that changes every run is the source code. Caching starts paying off when you put a long policy document or glossary at the front in the same form every time.
Estimating Cost (November 2026, from the official pricing page)
The old version's claims — Haiku input at $0.08 per million tokens, "about a fifth of Sonnet", "65–70% savings" — were either wrong or unsupported, and I've withdrawn them. Current official prices:
| Model | Input (per 1M tokens) | Output (per 1M tokens) | Role here |
|---|---|---|---|
Claude Haiku 4.5 (claude-haiku-4-5-20251001) | $1 | $5 | Classifying non-conforming commits |
Claude Sonnet 4.6 (claude-sonnet-4-6) | $3 | $15 | README and API reference |
Claude Haiku 5.5 (claude-haiku-5-5, prompts up to 100K tokens) | $0.10 | $0.50 | Candidate via env var |
Claude Sonnet 5.5 (claude-sonnet-5-5) | $2 | $10 | Candidate via env var |
Per-run cost is input tokens × input price + output tokens × output price. With 8,000 input and 1,500 output tokens for the README on Sonnet 4.6, that's 8,000 × $3 / 1M + 1,500 × $15 / 1M, about $0.05. That's arithmetic, not a measurement from my repo. For yours, count the input first with the Messages API's count_tokens endpoint.
To move to the 5.5 models, add DOCS_MODEL_SMALL=claude-haiku-5-5 and DOCS_MODEL_LARGE=claude-sonnet-5-5 to the workflow env. Since no sampling parameters are set, the code should run unchanged — but I haven't run the 5.5 models in this CI yet, so I can't speak to output quality.
GitHub Actions minutes on standard runners are free for public repositories. Private repositories draw from your plan's included usage. The old "2,000 minutes a month" phrasing doesn't match the current billing model, which expresses included usage as a dollar amount, so check GitHub's Actions billing docs for the latest.
The Next Snag: When You Want PRs Instead of Direct Commits to main
After a while, someone on the team may say the README keeps changing under them. The next step is to turn the commit step into a branch push plus a pull request.
- name: Open PR
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
BRANCH="auto-docs/${{ github.sha }}"
git switch -c "$BRANCH"
git commit -am "docs: auto-update [skip ci]" || exit 0
git push origin "$BRANCH"
gh pr create --base main --head "$BRANCH" --title "docs: auto-update" --body "Generated from ${{ github.sha }}"For this you'll need pull-requests: write under permissions and the repository setting that allows GitHub Actions to create pull requests. GitHub's docs also note that CI on a PR created with GITHUB_TOKEN waits for approval. And since git commit -am skips untracked files, put the git add loop from the earlier workflow in front of it for the first run.
If you want the same checks running locally as you work, the detailed guide to automating with Claude Code Hooks is a good place to start. If you plan to put a long policy document up front to make caching work, the comparison of how cache-read discounts actually show up on the bill will help you avoid a bad estimate. And the fence idea carries over to CLAUDE.md: restoring headings after a large CLAUDE.md was overwritten is the same failure, prevented in a different place.
Where to Start
Try running generate_changelog.py locally with --dry-run. In a repo that follows Conventional Commits, the fenced content appears without a single API call. Seeing once what would land in your CHANGELOG, then widening to the README and API reference, was the order that went wrong least for me.
Those three lines that vanished that morning now sit safely outside the fence. However far I extend the automation, the place where people write down what they learned the hard way is one I don't hand over.