"""Build the documentation site in docs-site/ (Mintlify) from the code and docs/ (decision 0011).
The site is a guided tour of the whole codebase that cannot go stale:
written by hand docs-site/index.mdx, docs-site/ask.mdx, the tour chapters docs-site/tour/*.mdx
(the story of each stage), and docs-site/reading_order.json (which files each
chapter covers, in reading order)
generated here one page per file under docs-site/reference/ (its docstring, what is inside, what
it uses and what uses it, and the full source), the data contracts, decisions,
diagrams, status and handoffs, the file list and diagrams inside each chapter
(between the GENERATED markers), and docs.json
Every tracked code, config and tooling file must be in reading_order.json, so new work always gets a
place in the tour. tests/test_docs_site.py runs `--check`, and the commit hook runs the tests, so a
commit whose docs are out of date is refused until you run this script.
python3 scripts/build_docs.py rebuild docs-site/
python3 scripts/build_docs.py --check list what is out of date; exit 1 if anything is
Look at the site locally with the Mintlify CLI (Node 20.17+): cd docs-site && npx mint dev
"""
from __future__ import annotations
import argparse
import ast
import json
import posixpath
import re
import subprocess
import sys
from pathlib import Path
from common.settings import CHECKPOINT_DIR, DATA_DIR, DOCS_DIR, DOCS_SITE_DIR, RAW_DIR, REPO_ROOT
ORDER_FILE = DOCS_SITE_DIR / "reading_order.json"
GENERATED_DIRS = ["reference", "decisions", "diagrams", "log", "images"] # rebuilt from scratch each time
GENERATED_FILES = ["docs.json", "contracts.mdx"]
HAND_WRITTEN = ["index", "ask"]
RESULTS = DOCS_DIR / "results" # scripts/export_results.py writes it
RUNNING = DOCS_DIR / "running.md" # every command, in order: the "Run it" page
AI_USAGE = DOCS_DIR / "ai-usage"
START = "{/* GENERATED: do not edit between these markers; run python3 scripts/build_docs.py */}"
END = "{/* END GENERATED */}"
# Files that must have a place in the tour: tracked code, config, tests and team tooling.
COVERED = re.compile(r"^(etl/.+\.py|src/.+\.py|scripts/.+\.(py|sh)|tests/.+\.py|config/.+\.csv|hosting/(space|cards|streamlit|workflows|live-stream)/[^/]+"
r"|\.claude/hooks/.+|\.claude/settings\.json|run_everything\.sh|requirements(-dev)?\.txt|pyproject\.toml"
r"|pyrightconfig\.json|\.gitignore|README\.md|AGENTS\.md|CLAUDE\.md)$")
LANG = {".py": "python", ".sh": "bash", ".csv": "csv", ".json": "json", ".toml": "toml", ".txt": "text",
".md": "markdown", ".html": "html", ".js": "javascript", ".css": "css", "": "text"}
SHELL_WORDS = ("python3 ", "python ", "spark-submit", "./", "streamlit ", "hf ", "cd ", "pip ", "git ", "npx ", "export ")
# ---------------------------------------------------------------- small helpers
SKIP_DIRS = {".git", ".venv", "venv", "node_modules", "__pycache__", ".pytest_cache",
RAW_DIR.name, DATA_DIR.name, CHECKPOINT_DIR.name}
def repo_url() -> str | None:
"""The repository's web address, from reading_order.json (the same on every machine)."""
return load_order().get("repository")
def tracked_files() -> list[str]:
"""The files git tracks. The commit hook tests a copy of the staged files with no .git
folder; there, every file on disk is a staged one."""
git = subprocess.run(["git", "ls-files"], cwd=REPO_ROOT, capture_output=True, text=True)
if git.returncode == 0:
return sorted(f for f in git.stdout.split("\n") if f and (REPO_ROOT / f).exists())
return sorted(p.relative_to(REPO_ROOT).as_posix() for p in REPO_ROOT.rglob("*")
if p.is_file() and not SKIP_DIRS & set(p.relative_to(REPO_ROOT).parts))
def page_of(path: str) -> str:
"""The site page of a source file, e.g. src/common/study.py -> reference/src/common/study."""
p = Path(path.lstrip("."))
name = p.stem if p.suffix == ".py" else p.name.replace(".", "-")
name = "init" if name == "__init__" else name
return "reference/" + (p.parent / name).as_posix().lstrip("./")
def escape(text: str) -> str:
"""Plain text made safe for MDX: braces and '<' would otherwise be read as code."""
text = re.sub(r"<!--.*?-->", "", text)
return text.replace("{", "\\{").replace("}", "\\}").replace("<", "<")
FENCE = re.compile(r"^\s*(`{3,}|~{3,})")
def mdx(markdown: str) -> str:
"""Markdown made safe for MDX: text outside code blocks and `code spans` is escaped."""
out, fence = [], None
for line in markdown.splitlines():
m = FENCE.match(line)
if fence:
out.append(line)
if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence):
fence = None
elif m:
fence = m.group(1)
out.append(line)
else:
parts = re.split(r"(`+[^`]*`+)", line)
out.append("".join(p if p.startswith("`") else escape(p) for p in parts))
return "\n".join(out)
def fence_for(code: str) -> str:
"""A code fence longer than any run of backticks in the code."""
longest = max((len(m) for m in re.findall(r"`+", code)), default=0)
return "`" * max(3, longest + 1)
def docstring_markdown(doc: str) -> str:
"""A docstring as Markdown: blocks indented under a line ending in ':' become code blocks."""
lines, out, i = doc.strip("\n").splitlines(), [], 0
while i < len(lines):
line = lines[i]
prev = out[-1].rstrip() if out else ""
if line.startswith(" ") and (prev.endswith(":") or prev == ""):
block = []
while i < len(lines) and (lines[i].startswith(" ") or not lines[i].strip()):
block.append(lines[i][4:] if lines[i].startswith(" ") else "")
i += 1
while block and not block[-1]:
block.pop()
lang = "bash" if all(b.strip().startswith(SHELL_WORDS) or not b.strip() for b in block) else "text"
out += ["", f"```{lang}", *block, "```", ""]
continue
out.append(line)
i += 1
return mdx("\n".join(out))
def first_paragraph(doc: str | None) -> str:
if not doc:
return ""
return " ".join(doc.strip().split("\n\n")[0].split())
def yaml_text(s: str) -> str:
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
def frontmatter(title: str, description: str = "", sidebar: str = "") -> str:
lines = ["---", f"title: {yaml_text(title)}"]
if sidebar:
lines.append(f"sidebarTitle: {yaml_text(sidebar)}")
if description:
lines.append(f"description: {yaml_text(description)}")
return "\n".join(lines + ["---", ""])
# ---------------------------------------------------------------- reading what a file is
def module_name(path: str) -> str | None:
"""The import name of a file under src/, e.g. src/common/study.py -> common.study."""
if not (path.startswith("src/") and path.endswith(".py")):
return None
parts = Path(path[4:-3]).parts
return ".".join(parts[:-1] if parts[-1] == "__init__" else parts)
def imports_of(tree: ast.AST, modules: dict[str, str]) -> list[str]:
"""Project files this file imports, in first-use order."""
found = []
for node in ast.walk(tree):
names = ([a.name for a in node.names] if isinstance(node, ast.Import)
else [node.module or ""] if isinstance(node, ast.ImportFrom) and node.level == 0 else [])
for name in names:
while name and name not in modules:
name = name.rpartition(".")[0]
if name and modules[name] not in found:
found.append(modules[name])
return found
def comment_header(text: str, suffix: str) -> str:
"""The leading comment block of a non-Python file, as plain text."""
lines = text.splitlines()
if suffix in (".js", ".css"):
m = re.match(r"\s*(?:\"use strict\";\s*)?/\*(.*?)\*/", text, re.S)
return " ".join(m.group(1).split()) if m else ""
if suffix == ".html":
m = re.search(r'<meta name="description" content="([^"]*)"', text)
return m.group(1) if m else ""
out = []
for line in lines[1:] if lines and lines[0].startswith("#!") else lines:
if line.startswith("#"):
out.append(line.lstrip("#").strip())
elif line.strip() or out:
break
return "\n".join(out).strip()
def describe(path: str, text: str, modules: dict[str, str]) -> dict:
"""What a reference page says about one file."""
suffix = Path(path).suffix
info = {"summary": "", "body": "", "inside": [], "checks": [], "uses": []}
if suffix == ".py":
tree = ast.parse(text)
doc = ast.get_docstring(tree) or ""
info["summary"] = first_paragraph(doc)
info["body"] = docstring_markdown(doc) if doc else ""
info["uses"] = imports_of(tree, modules)
source = text.splitlines()
for node in tree.body:
targets = node.targets if isinstance(node, ast.Assign) else [node.target] if isinstance(node, ast.AnnAssign) else []
names = [t.id for t in targets if isinstance(t, ast.Name)]
if names and all(n.isupper() for n in names): # a named setting
above, i = [], node.lineno - 2
while i >= 0 and source[i].strip().startswith("#"):
above.insert(0, source[i].strip().lstrip("#").strip())
i -= 1
inline = source[node.lineno - 1].split("#", 1)[1].strip() if " #" in source[node.lineno - 1] else ""
info["inside"].append((", ".join(names), node.lineno, " ".join(above) or inline))
continue
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
if node.name.startswith("test_"):
info["checks"].append((node.name[5:].replace("_", " "), node.lineno))
continue
args = "" if isinstance(node, ast.ClassDef) else ", ".join(a.arg for a in node.args.args)
info["inside"].append((f"{node.name}({args})", node.lineno, first_paragraph(ast.get_docstring(node))))
if isinstance(node, ast.ClassDef):
for sub in node.body:
if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef)) and not sub.name.startswith("_"):
sub_args = ", ".join(a.arg for a in sub.args.args)
info["inside"].append((f"{node.name}.{sub.name}({sub_args})", sub.lineno,
first_paragraph(ast.get_docstring(sub))))
elif suffix == ".csv":
rows = [r for r in text.splitlines() if r.strip()]
header = rows[0].split(",") if rows else []
info["summary"] = f"A registry with {len(rows) - 1} rows. Columns: " + ", ".join(f"`{h}`" for h in header) + "."
info["body"] = mdx(info["summary"]) + "\n\nIts columns are a contract: see [Data contracts](/contracts)."
elif suffix == ".md" and text.startswith("---"):
info["summary"] = "A Hugging Face card template: its {placeholders} are filled in by src/hosting/publish_hf.py."
info["body"] = mdx(info["summary"])
elif suffix == ".md":
heading = next((l.lstrip("# ").strip() for l in text.splitlines() if l.startswith("#")), "")
info["summary"] = heading
info["body"] = "The full text is below."
else:
info["summary"] = first_paragraph(comment_header(text, suffix))
info["body"] = mdx(comment_header(text, suffix))
return info
# ---------------------------------------------------------------- the pages
def reference_page(path: str, chapter: dict, number: int, info: dict, used_by: list[str], url: str | None) -> str:
text = (REPO_ROOT / path).read_text(encoding="utf-8")
lang = LANG.get(Path(path).suffix, "text")
n_lines = len(text.splitlines())
parts = [frontmatter(path, info["summary"][:300], Path(path).name),
f"`{path}` · chapter [{chapter['title']}](/tour/{chapter['id']}), file {number} · {n_lines} lines"
+ (f" · [open in the repository]({url}/blob/main/{path})" if url else ""), ""]
if info["body"]:
parts += ["## What it does", "", info["body"], ""]
if info["inside"]:
parts += ["## What is inside", ""]
for name, line, what in info["inside"]:
where = f"[line {line}]({url}/blob/main/{path}#L{line})" if url else f"line {line}"
parts.append(f"- **`{name}`** · {where}" + (f": {escape(what)}" if what else ""))
parts.append("")
if info["checks"]:
parts += ["## What it checks", ""]
parts += [f"- {escape(what)} (line {line})" for what, line in info["checks"]]
parts.append("")
if info["uses"] or used_by:
parts += ["## Connections", ""]
if info["uses"]:
parts.append("**Uses:** " + ", ".join(f"[`{u}`](/{page_of(u)})" for u in info["uses"]))
parts.append("")
if used_by:
parts.append("**Used by:** " + ", ".join(f"[`{u}`](/{page_of(u)})" for u in used_by))
parts.append("")
fence = fence_for(text)
parts += ["## Source", "", f'{fence}{lang} title="{path}" lines expandable', text.rstrip("\n"), fence, ""]
return "\n".join(parts)
def chapter_block(chapter: dict, infos: dict, diagrams: dict) -> str:
"""The generated part of a tour chapter: its diagrams and its files, in reading order."""
out = [START, ""]
for name in chapter["diagrams"]:
if name in diagrams:
out += [f"### The picture: {escape(diagrams[name]['title'])}", "",
"```mermaid", diagrams[name]["diagram"].rstrip("\n"), "```", "",
f"The [full diagram and its guide](/diagrams/{name}) explain every box.", ""]
out += ["### Read these files in this order", "", "<Steps>"]
for path in chapter["files"]:
summary = escape(infos[path]["summary"]) or "See the file."
out += [f' <Step title="{path}">', f" {summary} [Read it](/{page_of(path)})", " </Step>"]
out += ["</Steps>", "", END]
return "\n".join(out)
def markdown_page(md: str, fallback_title: str, base: str = "docs", images: str | None = None) -> str:
"""A Markdown file from `base` (a folder in the repo) as an MDX page: its first heading becomes
the title. With `images`, relative image links point to that folder of the site instead."""
lines = md.splitlines()
title = fallback_title
if lines and lines[0].startswith("# "):
title, lines = lines[0][2:].strip(), lines[1:]
body = mdx("\n".join(lines))
if images:
body = re.sub(r"!\[([^\]]*)\]\((?!https?://|/)[^)]*?([^/)]+\.png)\)", rf"", body)
body = re.sub(r"(?<!!)\]\((?!https?://|#|/)([^)]+)\)", lambda m: "](" + link_target(m.group(1), base) + ")", body)
return frontmatter(title) + "\n" + body.strip() + "\n"
def link_target(relative: str, base: str = "docs") -> str:
"""Where a relative link inside a Markdown file in `base` should point on the site."""
name = Path(relative.split("#")[0]).name
if name.endswith(".md") and re.match(r"\d{4}-", name):
return "/decisions/" + name[:-3]
if name == "data-contracts.md":
return "/contracts"
url = repo_url()
path = posixpath.normpath(posixpath.join(base, relative))
return f"{url}/{'tree' if relative.endswith('/') else 'blob'}/main/{path}" if url else relative
def diagram_pages() -> dict:
"""docs/architecture/*.mmd, paired with their guides: {name: {title, diagram, guide}}."""
folder = DOCS_DIR / "architecture"
found = {}
for mmd in sorted(folder.glob("*.mmd")):
if mmd.stem.endswith("-guide") and (folder / (mmd.stem[:-6] + ".mmd")).exists():
continue
text = mmd.read_text(encoding="utf-8")
first = text.splitlines()[0].lstrip("%").strip() if text else mmd.stem
parts = [x.strip() for x in first.split("·")][1:] or [mmd.stem] # drop "Calendar Effects"
if len(parts) > 1 and re.match(r"^(Guide )?\d+\w?( of \d+)?$", parts[0]):
parts = parts[1:] # drop "7 of 8", "Guide 11"
title = parts[0].split(". ")[0]
title = title[:1].upper() + title[1:]
guide = folder / (mmd.stem + "-guide.mmd")
found[mmd.stem] = {"title": title.rstrip("."), "diagram": text,
"guide": guide.read_text(encoding="utf-8") if guide.exists() else ""}
return found
def diagram_page(name: str, d: dict) -> str:
parts = [frontmatter(d["title"], f"docs/architecture/{name}.mmd"), "```mermaid", d["diagram"].rstrip("\n"), "```", ""]
if d["guide"]:
parts += ["## Guide", "", "```mermaid", d["guide"].rstrip("\n"), "```", ""]
return "\n".join(parts)
# ---------------------------------------------------------------- the whole site
def load_order() -> dict:
return json.loads(ORDER_FILE.read_text(encoding="utf-8"))
def coverage_problems(order: dict, tracked: list[str]) -> list[str]:
listed = [f for c in order["chapters"] for f in c["files"]]
problems = [f"{f} is listed twice in reading_order.json" for f in sorted({f for f in listed if listed.count(f) > 1})]
problems += [f"{f} is in reading_order.json but does not exist" for f in listed if not (REPO_ROOT / f).exists()]
problems += [f"{f} has no place in the tour: add it to a chapter in docs-site/reading_order.json"
for f in tracked if COVERED.match(f) and f not in listed]
return problems
def build() -> dict[str, str | bytes]:
"""Every generated file, as {path relative to docs-site/: content}."""
order = load_order()
files = [f for c in order["chapters"] for f in c["files"]]
modules = {m: f for f in files + [f for f in tracked_files() if f.startswith("src/")] if (m := module_name(f))}
url = repo_url()
infos = {f: describe(f, (REPO_ROOT / f).read_text(encoding="utf-8"), modules) for f in files}
used_by = {f: [g for g in files if f in infos[g]["uses"] and g != f] for f in files}
diagrams = diagram_pages()
out: dict[str, str | bytes] = {}
for chapter in order["chapters"]:
for n, f in enumerate(chapter["files"], 1):
out[page_of(f) + ".mdx"] = reference_page(f, chapter, n, infos[f], used_by[f], url)
page = DOCS_SITE_DIR / "tour" / f"{chapter['id']}.mdx"
written = page.read_text(encoding="utf-8") if page.exists() else (
frontmatter(chapter["title"], chapter["summary"]) + f"\n{START}\n{END}\n")
if START not in written or END not in written:
raise SystemExit(f"{page} has lost its GENERATED markers; put them back (see another chapter).")
head, rest = written.split(START, 1)
out[f"tour/{chapter['id']}.mdx"] = head + chapter_block(chapter, infos, diagrams) + rest.split(END, 1)[1]
out["contracts.mdx"] = markdown_page((DOCS_DIR / "data-contracts.md").read_text(encoding="utf-8"), "Data contracts")
decisions = sorted(p for p in (DOCS_DIR / "decisions").glob("[0-9][0-9][0-9][0-9]-*.md"))
for p in decisions:
out[f"decisions/{p.stem}.mdx"] = markdown_page(p.read_text(encoding="utf-8"), p.stem, "docs/decisions")
for name, d in diagrams.items():
out[f"diagrams/{name}.mdx"] = diagram_page(name, d)
out["log/status.mdx"] = markdown_page((DOCS_DIR / "STATUS.md").read_text(encoding="utf-8"), "Status")
handoffs = sorted((p for p in (DOCS_DIR / "handoffs").glob("20*.md")), reverse=True)
for p in handoffs:
out[f"log/{p.stem}.mdx"] = markdown_page(p.read_text(encoding="utf-8"), p.stem, "docs/handoffs")
logs = sorted(p for p in AI_USAGE.glob("*.md") if p.name != "README.md")
for p in logs:
out[f"log/ai-usage-{p.stem}.mdx"] = markdown_page(p.read_text(encoding="utf-8"), p.stem, "docs/ai-usage")
out["run.mdx"] = markdown_page(RUNNING.read_text(encoding="utf-8"), "Run it")
has_results = (RESULTS / "README.md").exists()
if has_results:
out["results.mdx"] = markdown_page((RESULTS / "README.md").read_text(encoding="utf-8"), "Results",
"docs/results", images="images/results")
for png in sorted((RESULTS / "charts").glob("*.png")):
out[f"images/results/{png.name}"] = png.read_bytes()
out["docs.json"] = json.dumps(docs_json(order, decisions, diagrams, handoffs, logs, has_results), indent=2) + "\n"
return out
def docs_json(order, decisions, diagrams, handoffs, logs=(), has_results=False) -> dict:
"""The site's settings and navigation (generated: edit this function, not docs.json)."""
return {
"$schema": "https://mintlify.com/docs.json",
"theme": "mint",
"name": "Calendar Effects",
"description": "A guided tour of the Calendar Effects codebase: Kafka, Spark Structured Streaming, "
"an event study and a Spark MLlib model, read from start to finish.",
"colors": {"primary": "#2a78d6", "light": "#3987e5", "dark": "#1c5cab"},
"navigation": {"tabs": [
{"tab": "Guide", "groups": [
{"group": "Start here", "pages": HAND_WRITTEN[:1] + ["run"] + (["results"] if has_results else [])
+ HAND_WRITTEN[1:]},
{"group": "The tour", "pages": [f"tour/{c['id']}" for c in order["chapters"]]}]},
{"tab": "Code", "groups": [
{"group": f"{i}. {c['title']}", "pages": [page_of(f) for f in c["files"]]}
for i, c in enumerate(order["chapters"], 1)]},
{"tab": "Data and decisions", "groups": [
{"group": "Data", "pages": ["contracts"]},
{"group": "Decisions", "pages": [f"decisions/{p.stem}" for p in decisions]},
{"group": "Diagrams", "pages": [f"diagrams/{n}" for n in diagrams]}]},
{"tab": "Project log", "groups": [
{"group": "Status", "pages": ["log/status"]},
{"group": "Handoffs, newest first", "pages": [f"log/{p.stem}" for p in handoffs]},
{"group": "AI usage, per member", "pages": [f"log/ai-usage-{p.stem}" for p in logs]}]},
]},
"contextual": {"options": ["copy", "view", "claude", "chatgpt", "cursor", "mcp"]},
}
def same(path: Path, content) -> bool:
if not path.exists():
return False
return path.read_bytes() == content if isinstance(content, bytes) else path.read_text(encoding="utf-8") == content
def stale(out: dict) -> list[str]:
"""Generated files that differ from what is on disk, are missing, or should be gone."""
problems = [p for p, content in out.items() if not same(DOCS_SITE_DIR / p, content)]
for d in GENERATED_DIRS:
for p in (f for f in (DOCS_SITE_DIR / d).rglob("*") if f.is_file()):
rel = p.relative_to(DOCS_SITE_DIR).as_posix()
if rel not in out:
problems.append(rel + " (no longer generated)")
return sorted(problems)
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--check", action="store_true", help="only report what is out of date")
args = parser.parse_args()
problems = coverage_problems(load_order(), tracked_files())
if problems:
print("The tour does not cover the codebase:\n " + "\n ".join(problems))
sys.exit(1)
out = build()
behind = stale(out)
if args.check:
if behind:
print("docs-site/ is out of date; run python3 scripts/build_docs.py. Files:\n " + "\n ".join(behind))
sys.exit(1)
print("docs-site/ is up to date.")
return
for d in GENERATED_DIRS:
for p in (f for f in (DOCS_SITE_DIR / d).rglob("*") if f.is_file()):
if p.relative_to(DOCS_SITE_DIR).as_posix() not in out:
p.unlink()
for rel, content in out.items():
path = DOCS_SITE_DIR / rel
path.parent.mkdir(parents=True, exist_ok=True)
if not same(path, content):
path.write_bytes(content) if isinstance(content, bytes) else path.write_text(content, encoding="utf-8")
print(f"docs-site/: {len(out)} files, {len(behind)} changed.")
if __name__ == "__main__":
main()