Coverage for docs_facts.py: 100%

186 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Numbers the docs quote, kept true by reading them from their source. 

2 

3A doc writes `<!--fact:universe.total-->104<!--/fact-->`, which renders as plain "104". `aq docs sync` rewrites each value 

4from `compute_facts`, `aq docs sync --check` reports drift (`tests/test_docs_facts.py` runs it, so CI fails on a stale number), 

5and a full `aq test` syncs too. Facts read tracked files only, so a clean checkout computes the same values. 

6 

7A generated block is the multi-line twin: `<!-- AQ:NAME_START -->...<!-- AQ:NAME_END -->` is rewritten whole from `compute_blocks` 

8(`DOCS_SITE`, the README's map of the documentation site, read from `mkdocs.yml`'s nav; `CHANGELOG_LATEST`, the site's list 

9of the latest phases, read from `development/Changelog.md`).""" 

10 

11from __future__ import annotations 

12 

13import gzip 

14import json 

15import re 

16import subprocess 

17from collections import Counter 

18from collections.abc import Iterable 

19from pathlib import Path 

20 

21ROOT = Path(__file__).resolve().parent 

22FACT_RE = re.compile(r"<!--fact:([a-z0-9_.]+)-->(.*?)<!--/fact-->") 

23EXCLUDED_PREFIXES = ("Aether-quant-Obsidian-Vault/", "development/backups/", "backtests/", "webui/node_modules/") 

24_PROBLEM_HEADING_RE = re.compile(r"^### ([0-9]+[a-z]?)\. ", re.MULTILINE) 

25_STATUS_MARKERS = {"fixed": "🟢", "partial": "🟡", "closed": "🔴"} 

26_NAV_SECTION_RE = re.compile(r"^ - ([^:]+):\s*(\S+)?\s*$") 

27_NAV_PAGE_RE = re.compile(r"^ - ([^:]+):\s*(\S+)\s*$") 

28SITE_URL = "https://leon1706-lol.github.io/Aether-quant/" 

29 

30 

31def universe_facts(config: dict) -> dict[str, str]: 

32 assets = config["phase1"]["universe"]["assets"] 

33 counts = Counter(str(asset.get("asset_class") or asset.get("security_type")) for asset in assets) 

34 facts = {"universe.total": str(len(assets))} 

35 facts.update({f"universe.{kind}": str(count) for kind, count in counts.items()}) 

36 for kind in counts: 

37 tickers = (str(asset["ticker"]) for asset in assets if str(asset.get("asset_class") or asset.get("security_type")) == kind) 

38 facts[f"universe.list.{kind}"] = ", ".join(sorted(tickers)) 

39 return facts 

40 

41 

42def window_facts(config: dict) -> dict[str, str]: 

43 windows = config["phase1"]["windows"] 

44 return {f"windows.{name}": f"{window['start']} to {window['end']}" for name, window in windows.items() if isinstance(window, dict) and "start" in window} 

45 

46 

47def _status_line(entry: str) -> str: 

48 return next((line.strip() for line in entry.splitlines()[1:] if line.strip()), "") 

49 

50 

51def problem_facts(text: str) -> dict[str, str]: 

52 """Entry count, highest number and how many entries carry each status marker.""" 

53 numbers = _PROBLEM_HEADING_RE.findall(text) 

54 highest = max((int(re.match(r"\d+", number).group()) for number in numbers), default=0) 

55 facts = {"problems.total": str(len(numbers)), "problems.last": str(highest)} 

56 entries = re.split(r"^### ", text, flags=re.MULTILINE)[1:] 

57 for name, marker in _STATUS_MARKERS.items(): 

58 facts[f"problems.{name}"] = str(sum(1 for entry in entries if _status_line(entry).startswith(marker))) 

59 return facts 

60 

61 

62def changelog_facts(text: str) -> dict[str, str]: 

63 phases = re.findall(r"^## Phase (\S+)", text, flags=re.MULTILINE) 

64 return {"changelog.latest": phases[-1]} if phases else {} 

65 

66 

67def research_facts(problems: str) -> dict[str, str]: 

68 """The deflated-Sharpe N: the last "The deflated-Sharpe N is now X." in Problems.md (`RESEARCH_TRIALS` is pinned to it).""" 

69 counts = re.findall(r"The deflated-Sharpe N is now (\d+)\.", problems) 

70 return {"research.trials": counts[-1]} if counts else {} 

71 

72 

73def sample_facts(path: Path) -> dict[str, str]: 

74 """The bundled sample's window, from its own rows (`date` first, ISO dates).""" 

75 with gzip.open(path, "rt", encoding="utf-8") as handle: 

76 dates = [line.split(",", 1)[0] for line in handle.read().splitlines()[1:] if line] 

77 if not dates: 

78 return {} 

79 first, last = min(dates), max(dates) 

80 return {"sample.first": first, "sample.last": last, "sample.months": f"{first[:7]} to {last[:7]}"} 

81 

82 

83def hello_facts(path: Path) -> dict[str, str]: 

84 """`aq hello --offline`'s headline figures, from the summary tests/test_hello_world.py checks against a real run.""" 

85 if not path.exists(): 

86 return {} 

87 return {f"hello.{key}": str(value) for key, value in json.loads(path.read_text(encoding="utf-8")).items()} 

88 

89 

90def lean_pin_facts(readme: str) -> dict[str, str]: 

91 """The pinned Lean run, from the line the README's generated Backtest Statistics write ("_Lean run `<id>`, ...").""" 

92 run = re.search(r"^_Lean run `([0-9_-]+)`", readme, re.MULTILINE) 

93 return {"lean.pin_run": run.group(1)} if run else {} 

94 

95 

96def python_facts(pyproject: str, ci_workflow: str) -> dict[str, str]: 

97 facts = {} 

98 requires = re.search(r'^requires-python\s*=\s*"([^"]+)"', pyproject, re.MULTILINE) 

99 if requires: 

100 facts["python.requires"] = requires.group(1) 

101 versions = re.findall(r'python-version:\s*"?([0-9.]+)"?', ci_workflow) 

102 if versions: 

103 facts["python.ci"] = Counter(versions).most_common(1)[0][0] 

104 return facts 

105 

106 

107def _option_structures() -> dict[str, str]: 

108 from portfolio.options_strategy import MULTI_LEG_STRATEGY_REGISTRY 

109 

110 return {"options.structures": str(len(MULTI_LEG_STRATEGY_REGISTRY))} 

111 

112 

113def _aq_commands() -> dict[str, str]: 

114 from aq_cli import build_parser 

115 

116 parser = build_parser() 

117 commands = next(action.choices for action in parser._actions if isinstance(getattr(action, "choices", None), dict)) 

118 return {"aq.commands": str(len(commands))} 

119 

120 

121def compute_facts(root: Path = ROOT) -> dict[str, str]: 

122 root = Path(root) 

123 config = json.loads((root / "config.json").read_text(encoding="utf-8")) 

124 facts = {**universe_facts(config), **window_facts(config)} 

125 problems = (root / "development" / "Problems.md").read_text(encoding="utf-8") 

126 facts.update(problem_facts(problems)) 

127 facts.update(research_facts(problems)) 

128 facts.update(sample_facts(root / "aether_quant" / "_sample" / "coinbase_daily.csv.gz")) 

129 facts.update(hello_facts(root / "tests" / "data" / "hello_offline_summary.json")) 

130 facts.update(lean_pin_facts((root / "README.md").read_text(encoding="utf-8"))) 

131 facts.update(changelog_facts((root / "development" / "Changelog.md").read_text(encoding="utf-8"))) 

132 facts.update(python_facts((root / "pyproject.toml").read_text(encoding="utf-8"), (root / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8"))) 

133 api = json.loads((root / "tests" / "data" / "aether_quant_api.json").read_text(encoding="utf-8")) 

134 facts["library.modules"] = str(len(api)) 

135 facts["library.names"] = str(sum(len(names) for names in api.values())) 

136 engine = re.search(r"^ARG LEAN_BASE_IMAGE=(\S+)", (root / "Dockerfile.lean").read_text(encoding="utf-8"), re.MULTILINE) 

137 if engine: 

138 facts["lean.engine"] = engine.group(1).split("@", 1)[0] # the tag; the digest pin is Dockerfile.lean's 

139 jobs = re.search(r"^jobs:\n(.*)", (root / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8"), re.MULTILINE | re.DOTALL) 

140 if jobs: 

141 facts["ci.jobs"] = str(len(re.findall(r"^ [a-z0-9-]+:$", jobs.group(1), re.MULTILINE))) 

142 facts["formal.specs"] = str(sum(1 for _ in (root / "formal" / "AetherFormal").glob("*.lean"))) 

143 facts.update(_option_structures()) 

144 facts.update(_aq_commands()) 

145 return facts 

146 

147 

148def apply_facts(text: str, facts: dict[str, str]) -> tuple[str, list[str], list[str]]: 

149 """(new text, keys with no known value, keys whose value changed).""" 

150 unknown: list[str] = [] 

151 changed: list[str] = [] 

152 

153 def replace(match: re.Match) -> str: 

154 key, value = match.group(1), match.group(2) 

155 if key not in facts: 

156 unknown.append(key) 

157 return match.group(0) 

158 if facts[key] != value: 

159 changed.append(key) 

160 return f"<!--fact:{key}-->{facts[key]}<!--/fact-->" 

161 

162 return FACT_RE.sub(replace, text), unknown, changed 

163 

164 

165def docs_site_nav(root: Path = ROOT) -> list[tuple[str, list[tuple[str, str]]]]: 

166 """`mkdocs.yml`'s nav as [(section, [(title, docs-relative path)])], read line by line (no YAML dependency).""" 

167 sections: list[tuple[str, list[tuple[str, str]]]] = [] 

168 in_nav = False 

169 for line in (Path(root) / "mkdocs.yml").read_text(encoding="utf-8").splitlines(): 

170 if line.startswith("nav:"): 

171 in_nav = True 

172 continue 

173 if in_nav and line and not line.startswith(" "): 

174 break 

175 if not in_nav or line.strip().startswith("#"): 

176 continue 

177 section, page = _NAV_SECTION_RE.match(line), _NAV_PAGE_RE.match(line) 

178 if section: 

179 sections.append((section.group(1).strip(), [("", section.group(2))] if section.group(2) else [])) 

180 elif page and sections: 

181 sections[-1][1].append((page.group(1).strip(), page.group(2))) 

182 return sections 

183 

184 

185def _site_link(title: str, page: str) -> str: 

186 # tutorials are copied into docs/ at build time (gitignored there); the README links their tracked source 

187 target = f"notebooks/{Path(page).name}" if page.startswith("tutorials/") else f"docs/{page}" 

188 return f"[{title}]({target})" 

189 

190 

191def docs_site_block(root: Path = ROOT) -> str: 

192 """The README's table of the documentation site: one row per nav section; the API reference collapses to one link.""" 

193 rows = ["| Section | Pages |", "|---|---|"] 

194 for section, pages in docs_site_nav(root): 

195 if section == "API reference": 

196 modules = [page for title, page in pages if title.startswith("aether_quant.")] 

197 cell = f"[Overview](docs/reference/index.md), one page per facade ({len(modules)}), generated by `scripts/build_docs.py`" 

198 elif len(pages) == 1 and not pages[0][0]: 

199 cell = _site_link(section, pages[0][1]) 

200 else: 

201 cell = " · ".join(_site_link(title, page) for title, page in pages) 

202 rows.append(f"| {section} | {cell} |") 

203 return "\n".join(rows) 

204 

205 

206def changelog_latest_block(root: Path = ROOT, count: int = 3) -> str: 

207 """The last `count` phases of `development/Changelog.md`, newest first, each linked to its heading on GitHub.""" 

208 text = (Path(root) / "development" / "Changelog.md").read_text(encoding="utf-8") 

209 headings = re.findall(r"^## (Phase .+?)\s*$", text, flags=re.MULTILINE)[-count:] 

210 base = "https://github.com/leon1706-lol/Aether-quant/blob/main/development/Changelog.md" 

211 return "\n".join(f"- [{heading}]({base}#{_anchor(heading)})" for heading in reversed(headings)) 

212 

213 

214def _anchor(heading: str) -> str: 

215 """GitHub's heading anchor: lowercase, punctuation dropped, spaces to hyphens.""" 

216 return re.sub(r"[^\w\- ]", "", heading.lower()).replace(" ", "-") 

217 

218 

219def cli_reference_block() -> str: 

220 """Every `aq` command, subcommand and flag (docs/reference/cli.md), rendered from the parser itself.""" 

221 from aq_cli import build_parser 

222 from aq_devtools import render_cli_markdown 

223 

224 return render_cli_markdown(build_parser()).rstrip() 

225 

226 

227def compute_blocks(root: Path = ROOT) -> dict[str, str]: 

228 """Every generated block a living doc may hold, by name.""" 

229 return {"DOCS_SITE": docs_site_block(root), "CHANGELOG_LATEST": changelog_latest_block(root), "CLI_REFERENCE": cli_reference_block()} 

230 

231 

232def apply_blocks(text: str, blocks: dict[str, str]) -> tuple[str, list[str]]: 

233 """`text` with each `<!-- AQ:NAME_START -->...<!-- AQ:NAME_END -->` it holds rewritten from `blocks`; also the names that moved.""" 

234 changed = [] 

235 for name, body in blocks.items(): 

236 start, end = f"<!-- AQ:{name}_START -->", f"<!-- AQ:{name}_END -->" 

237 if start not in text or end not in text: 

238 continue 

239 head, rest = text.split(start, 1) 

240 old, tail = rest.split(end, 1) 

241 new = f"\n{body}\n" 

242 if old != new: 

243 changed.append(name) 

244 text = f"{head}{start}{new}{end}{tail}" 

245 return text, changed 

246 

247 

248def tracked_docs(root: Path = ROOT) -> list[Path]: 

249 output = subprocess.run(["git", "ls-files", "*.md"], cwd=root, capture_output=True, text=True, check=True, timeout=30).stdout 

250 paths = [Path(root) / line for line in output.splitlines() if line and not line.startswith(EXCLUDED_PREFIXES)] 

251 return [path for path in paths if path.exists()] 

252 

253 

254def sync_docs(paths: Iterable[Path], facts: dict[str, str], *, check: bool = False, blocks: dict[str, str] | None = None) -> dict[str, list[str]]: 

255 """{"changed": ["file: key"], "unknown": ["file: key"]}. Writes only the files whose text moved, and nothing with `check`. 

256 `blocks` (from `compute_blocks`) also rewrites the generated blocks a doc holds.""" 

257 report: dict[str, list[str]] = {"changed": [], "unknown": []} 

258 for path in paths: 

259 text = path.read_text(encoding="utf-8") 

260 updated, unknown, changed = apply_facts(text, facts) 

261 if blocks: 

262 updated, moved = apply_blocks(updated, blocks) 

263 changed = [*changed, *(f"block {name}" for name in moved)] 

264 report["changed"] += [f"{path.name}: {key}" for key in changed] 

265 report["unknown"] += [f"{path.name}: {key}" for key in unknown] 

266 if updated != text and not check: 

267 path.write_text(updated, encoding="utf-8", newline="\n") 

268 return report