gabriel / musehub public
test_doc_land.py python
327 lines 16.9 KB
Raw
sha256:5bc6578bee044ce139e12989ae6d957b3da072f7952f3d03c243e9b517550c77 docs(security,landing): call-site pins and the fail-closed … Opus 5.5 patch 1 day ago
1 """DOC_LAND — the /muse landing page agrees with the registry and the engine (musehub#243).
2
3 DOC_LAND_01–04 from the ticket are enforced by the shared DOC_INF_02/03 checks in
4 ``test_doc_inf_registry.py``: the "doc sections" stat and card list
5 (``test_landing_cards_and_section_count``), reading-path label numbers
6 (``test_section_labels_match_registry[/muse]``), routes (``test_every_section_has_a_route…``)
7 and anchors (``test_internal_links_and_anchors_resolve[/muse]``). DOC_LAND_05 (URL scheme)
8 belongs to DOC_INF_04. This module covers what only the landing page claims.
9 """
10
11 from __future__ import annotations
12
13 import importlib
14 import inspect
15 import os
16 import pathlib
17 import re
18
19 import pytest
20 from muse.domain import MuseDomainPlugin
21
22 from musehub.api.routes.musehub import ui_docs
23 from musehub.api.routes.musehub.ui_docs import _PHASES
24 from tests.docs_contract import registry_check as rc
25
26 _BY_SLUG = {slug: (num, title) for slug, num, title, _ in _PHASES}
27
28
29 def _hero(html: str) -> str:
30 m = re.search(r'<div class="devdocs-index-intro">(.*?)<section class="cmap"', html, re.S)
31 assert m, "landing hero not found"
32 return m.group(1)
33
34
35 def _concept_map(html: str) -> str:
36 m = re.search(r'(<section class="cmap".*?</section>)\s*<div class="devdocs-phase-grid">', html, re.S)
37 assert m, "concept map not found between the hero and the section cards"
38 return m.group(1)
39
40
41 def _stat(html: str, label: str) -> str:
42 stats = dict(
43 (lbl, num)
44 for num, lbl in re.findall(
45 r'class="devdocs-stat-num">\s*([^<]*?)\s*</span>\s*<span class="devdocs-stat-label">\s*([^<]*?)\s*</span>',
46 html,
47 )
48 )
49 return stats[label]
50
51
52 # ── Reading paths (L-2, L-9) ────────────────────────────────────────────────
53
54
55 def test_doc_land_06_reading_paths_use_registered_sections() -> None:
56 unknown = [slug for _, _, slugs in ui_docs._READING_PATHS for slug in slugs if slug not in _BY_SLUG]
57 assert unknown == []
58 assert all(len(slugs) >= 2 for _, _, slugs in ui_docs._READING_PATHS)
59
60
61 def test_doc_land_07_every_section_is_on_a_reading_path() -> None:
62 on_a_path = {slug for _, _, slugs in ui_docs._READING_PATHS for slug in slugs}
63 assert [slug for slug in _BY_SLUG if slug not in on_a_path] == []
64
65
66 def test_doc_land_08_reading_path_table_is_rendered_from_the_registry(rendered: dict[str, str]) -> None:
67 html = rendered[rc.DOCS_ROOT]
68 steps = [a for a in rc.parse_page(html).anchors if "devdocs-reading-path__step" in a.classes]
69 want = [
70 (rc.phase_path(slug), f"{_BY_SLUG[slug][0]} {_BY_SLUG[slug][1]}")
71 for _, _, slugs in ui_docs._READING_PATHS
72 for slug in slugs
73 ]
74 assert [(a.href, a.text) for a in steps] == want
75 assert html.count('class="devdocs-reading-path"') == len(ui_docs._READING_PATHS)
76
77
78 # ── Hero claims (L-3, L-4, L-6, L-7) ────────────────────────────────────────
79
80
81 def test_doc_land_09_protocol_stat_matches_the_domain_protocol(rendered: dict[str, str]) -> None:
82 html = rendered[rc.DOCS_ROOT]
83 methods = sorted(n for n, v in vars(MuseDomainPlugin).items() if inspect.isfunction(v) and not n.startswith("_"))
84 assert _stat(html, "protocol methods") == str(len(methods))
85 hero = _hero(html)
86 assert [m for m in methods if f"<code>{m}</code>" not in hero] == []
87
88
89 def test_doc_land_10_hero_states_how_signing_is_enabled(rendered: dict[str, str]) -> None:
90 # Signing is opt-in (muse commit --sign, or commit.sign = true); the CLI flag itself is
91 # checked against the real parser by DOC_INF_01.
92 hero = _hero(rendered[rc.DOCS_ROOT])
93 assert "<code>muse commit --sign</code>" in hero
94 assert "<code>commit.sign = true</code>" in hero
95
96
97 @pytest.mark.parametrize(
98 "overclaim",
99 [
100 pytest.param("every commit is signed", id="L-3-signing-is-opt-in"),
101 pytest.param("every commit carries", id="L-4-provenance-fields-are-optional"),
102 pytest.param("can't be taught to resolve", id="L-6-harmony-escalates"),
103 pytest.param("escalates the rest to a human or a specialist agent", id="LAND-C16-no-escalation-routing"),
104 pytest.param("dependencies between them", id="LAND-C02-imports-not-call-graph"),
105 ],
106 )
107 def test_doc_land_11_retracted_hero_overclaims_stay_retracted(rendered: dict[str, str], overclaim: str) -> None:
108 text = " ".join(re.sub(r"<[^>]+>", " ", _hero(rendered[rc.DOCS_ROOT])).split()).lower()
109 assert overclaim not in text
110
111
112 # ── Architecture concept map (V1) ───────────────────────────────────────────
113
114 _NODES = {n.key: n for n in ui_docs._CONCEPT_NODES}
115 _LAYERS = [layer.key for layer in ui_docs._CONCEPT_LAYERS]
116 _REPO = pathlib.Path(__file__).resolve().parents[2]
117
118
119 def test_doc_land_12_concept_map_is_a_connected_graph_of_registered_sections() -> None:
120 assert len(_NODES) == len(ui_docs._CONCEPT_NODES), "duplicate node keys"
121 assert [n.key for n in _NODES.values() if n.section not in _BY_SLUG] == []
122 assert [n.key for n in _NODES.values() if n.layer not in _LAYERS] == []
123 assert [layer for layer in _LAYERS if not any(n.layer == layer for n in _NODES.values())] == []
124 assert [n.key for n in _NODES.values() if n.status not in ui_docs._CONCEPT_STATUS] == []
125 bad = [(a, b) for a, b, _ in ui_docs._CONCEPT_EDGES if a not in _NODES or b not in _NODES or a == b]
126 assert bad == []
127 linked = {k for a, b, _ in ui_docs._CONCEPT_EDGES for k in (a, b)}
128 assert [k for k in _NODES if k not in linked] == [], "every concept joins the map"
129
130
131 @pytest.mark.parametrize("node", ui_docs._CONCEPT_NODES, ids=lambda n: n.key)
132 def test_doc_land_13_every_node_names_real_code(node: ui_docs._ConceptNode) -> None:
133 module, _, symbol = node.implemented_by.partition(":")
134 obj = importlib.import_module(module)
135 for part in symbol.split("."):
136 obj = getattr(obj, part)
137
138
139 def test_doc_land_14_map_links_render_from_the_registry_in_reading_order(rendered: dict[str, str]) -> None:
140 cmap = _concept_map(rendered[rc.DOCS_ROOT])
141 links = [a for a in rc.parse_page(cmap).anchors if "cmap-node" in a.classes]
142 in_order = sorted(ui_docs._CONCEPT_NODES, key=lambda n: _LAYERS.index(n.layer))
143 assert [a.href for a in links] == [rc.phase_path(n.section) for n in in_order]
144 for n in in_order:
145 num, title = _BY_SLUG[n.section]
146 assert f'<span class="cmap-node__section">{num} {title}</span>' in cmap, n.key
147 uses = " ".join(b for a, b, _ in ui_docs._CONCEPT_EDGES if a == n.key)
148 assert f'data-node="{n.key}" data-uses="{uses}"' in cmap, n.key
149 assert re.search(r"\b\d{2}\b", re.sub(r"<[^>]+>|\{\{.*?\}\}", " ", _template_map())) is None, (
150 "section numbers in the concept map must come from _PHASES"
151 )
152
153
154 def _template_map() -> str:
155 src = (_REPO / "musehub/templates/musehub/pages/docs_muse.html").read_text()
156 m = re.search(r'<section class="cmap".*?</section>', src, re.S)
157 assert m
158 return m.group(0)
159
160
161 def test_doc_land_15_capability_labels_match_the_engine() -> None:
162 from muse.plugins import registry
163
164 registered = sorted(registry._REGISTRY)
165 if not os.environ.get("MUSE_ENABLE_MIDI"):
166 assert "midi" not in registered
167 assert _NODES["midi"].status == "opt-in"
168 assert _NODES["signing"].status == "opt-in"
169 assert _NODES["crdt"].status == "shipped" # pinned to the engine by DOC_LAND_18c (musehub#204, fixed)
170 assert _NODES["new-domain"].status == "not-built"
171 assert sorted(ui_docs._DEFAULT_DOMAINS) == sorted(d for d in registered if d != "midi")
172 assert "MUSE_ENABLE_MIDI" in _NODES["midi"].summary
173 assert "<code>muse commit --sign</code>" in _NODES["signing"].summary
174
175
176 def test_doc_land_16_map_is_accessible_without_hover_or_script(rendered: dict[str, str]) -> None:
177 cmap = _concept_map(rendered[rc.DOCS_ROOT])
178 labelled = re.search(r'<section class="cmap"[^>]*aria-labelledby="([^"]+)"', cmap)
179 assert labelled and f'id="{labelled.group(1)}"' in cmap
180 assert '<ol class="cmap-layers">' in cmap
181 ids = set(re.findall(r'\sid="([^"]+)"', cmap))
182 described = re.findall(r'<a class="cmap-node"[^>]*aria-describedby="([^"]+)"', cmap)
183 assert len(described) == len(_NODES)
184 assert [i for ref in described for i in ref.split() if i not in ids] == []
185 assert re.search(r'<svg class="cmap-wires"[^>]*aria-hidden="true"', cmap)
186 text = " ".join(re.sub(r"<[^>]+>", " ", cmap).split())
187 for n in _NODES.values():
188 assert ui_docs._CONCEPT_STATUS[n.status] in text, f"{n.key}: status must be visible text"
189 for a, b, verb in ui_docs._CONCEPT_EDGES:
190 assert f"{verb} {_NODES[b].label}" in text, f"relation {a}→{b} must be readable without hover"
191
192
193 def test_doc_land_17_styles_and_script_degrade_gracefully() -> None:
194 scss = (_REPO / "src/scss/components/_devdocs.scss").read_text()
195 block = scss[scss.index("// ── Architecture concept map") :]
196 assert "@media (prefers-reduced-motion: reduce)" in block
197 assert "@media (max-width:" in block
198 assert ":focus-visible" in block
199 assert "@media (forced-colors: active)" in block
200 ts = (_REPO / "src/ts/pages/docs.ts").read_text()
201 assert "initConceptMap();" in ts
202 assert "matchMedia('(prefers-reduced-motion: reduce)')" in ts or "prefers-reduced-motion" in scss
203
204
205 # ── QA contract v2 (#241): corrected claims stay tied to the engine ─────────
206 # Each pin fails when the engine changes, so the page is revisited instead of drifting: a known gap
207 # that gets fixed must drop its warning, and a formula that gains a field must be re-described.
208
209
210 def _text(html: str) -> str:
211 return " ".join(re.sub(r"<[^>]+>", " ", html).split())
212
213
214 def test_doc_land_18a_commit_id_inputs_are_all_named() -> None:
215 from muse.core.snapshot import compute_commit_id
216
217 words = {"parent_ids": "parents", "snapshot_id": "snapshot", "message": "message",
218 "committed_at_iso": "timestamp", "author": "author", "signer_public_key": "signer key"}
219 assert set(inspect.signature(compute_commit_id).parameters) == set(words), "commit ID formula changed"
220 assert [w for w in words.values() if w not in _NODES["commits"].summary] == []
221
222
223 def test_doc_land_18b_harmony_scope_matches_merge(rendered: dict[str, str]) -> None:
224 merge_src = inspect.getsource(importlib.import_module("muse.cli.commands.merge"))
225 assert "harmony_auto_apply" in merge_src # muse merge replays recorded resolutions …
226 assert "harmony.engine" not in merge_src, ( # … and does not run the full engine
227 "muse merge now runs the Harmony engine: update the hero and the harmony concept"
228 )
229 hero = _text(_hero(rendered[rc.DOCS_ROOT]))
230 for text in (hero, _NODES["harmony"].summary):
231 assert "muse merge" in text and "muse harmony engine" in text
232
233
234 def test_doc_land_18c_merge_routes_a_crdt_plugin_to_its_join() -> None:
235 """musehub#204 (fixed): run_merge — the engine behind ``muse merge`` — joins a plugin that implements CRDTPlugin and
236 declares merge_mode "crdt", and merges every other plugin three-way. The crdt concept says so."""
237 from muse.core.merge_engine import STRATEGY_MAP, run_merge, uses_crdt_join
238 from muse.plugins.scaffold.plugin import ScaffoldPlugin
239
240 joined: list[bool] = []
241
242 class _CrdtScaffold(ScaffoldPlugin):
243 def schema(self): # type: ignore[no-untyped-def]
244 return {**super().schema(), "merge_mode": "crdt"}
245
246 def join(self, a, b): # type: ignore[no-untyped-def]
247 joined.append(True)
248 return super().join(a, b)
249
250 assert uses_crdt_join(ScaffoldPlugin()) is False # implements CRDTPlugin but declares three_way
251 assert uses_crdt_join(_CrdtScaffold()) is True
252 result = run_merge({"a.txt": "sha256:" + "0" * 64}, {"a.txt": "sha256:" + "1" * 64}, {"a.txt": "sha256:" + "2" * 64},
253 STRATEGY_MAP["recursive"], plugin=_CrdtScaffold(), domain="scaffold")
254 assert joined and result.conflicts == [] and set(result.applied_strategies.values()) == {"crdt-join"}
255 assert _NODES["crdt"].status == "shipped" and "is merged by <code>join</code>" in _NODES["crdt"].summary
256 assert "never calls it" not in _NODES["crdt"].summary
257
258
259 def test_doc_land_18d_signing_needs_an_identity_and_fails_closed(rendered: dict[str, str]) -> None:
260 # every commit writer resolves its signer through one shared path since Muse 0.2.2rc6 (muse#126): it fails closed there
261 signer_src = inspect.getsource(importlib.import_module("muse.cli.signed_commit"))
262 assert "no signing identity resolves" in signer_src # fails closed (muse#124, #126)
263 hero = _hero(rendered[rc.DOCS_ROOT])
264 assert 'href="/muse/getting-started#identity"' in hero
265 assert "stops instead of writing an unsigned commit" in _text(hero)
266
267
268 def test_doc_land_18e_key_derivation_and_code_dimensions_match_the_engine(rendered: dict[str, str]) -> None:
269 from muse.cli import config
270 from muse.core import identity
271 from muse.plugins.code.plugin import CodePlugin
272
273 assert "MUSE_AGENT_KEY_FD" in inspect.getsource(config.get_signing_identity) # handed sub-seed
274 assert "mnemonic_to_seed" in inspect.getsource(identity.resolve_signing_identity) # one recovery seed
275 assert "recovery seed" in _NODES["identity"].summary and "sub-seed" in _NODES["identity"].summary
276 dims = {d["name"] for d in CodePlugin().schema()["dimensions"]}
277 assert {"symbols", "imports"} <= dims
278 assert "imports" in _NODES["code"].summary
279 assert "functions, classes and imports" in _text(_hero(rendered[rc.DOCS_ROOT]))
280
281
282 # ── Responsive layout and contrast (#241 D/E) ───────────────────────────────
283 # Browser evidence is in the #243 QA report; these static checks keep the causes from returning.
284
285
286 def test_doc_land_19_layout_cannot_widen_the_page_on_phones() -> None:
287 page = (_REPO / "musehub/templates/musehub/pages/docs_muse.html").read_text()
288 assert " style=" not in page, "no inline styles: they bypass the theme roles and the breakpoints"
289 assert re.search(r"#[0-9a-fA-F]{3,8}\b", re.sub(r"\{#.*?#\}", "", page, flags=re.S)) is None, "no hard-coded colours"
290 layout = (_REPO / "src/scss/pages/_muse-docs.scss").read_text()
291 index = layout[layout.index(".devdocs-index {") : layout.index("}", layout.index(".devdocs-index {"))]
292 assert "width: 100%" in index and "min-width: 0" in index # fills the column instead of fitting content
293 assert "grid-template-columns: minmax(0, 1fr) auto" in layout
294 scss = (_REPO / "src/scss/components/_devdocs.scss").read_text()
295 # A fixed minimum track wider than a phone's content box overflows; cap it with min(…, 100%).
296 landing_grids = layout[layout.index(".devdocs-phase-grid") :] + scss[scss.index("// ── Architecture concept map") : scss.index("// ── Shared docs figure")]
297 assert re.findall(r"minmax\(\s*\d+px", landing_grids) == []
298 paths = scss[scss.index("// ── Suggested reading paths") : scss.index("// ── Architecture concept map")]
299 assert "display: table" in paths and "white-space: nowrap" not in paths
300
301
302 def test_doc_land_19b_landing_text_uses_aa_colour_roles() -> None:
303 # Interim guard for the site-wide light-theme token defect (musehub#283): when #283 makes the
304 # tokens themselves AA-safe, delete the --land-* roles and this role list together.
305 scss = (_REPO / "src/scss/components/_devdocs.scss").read_text()
306 light = scss[scss.index('[data-theme="light"] .devdocs-index {') :]
307 light = light[: light.index("}")]
308 for role in ("--land-accent", "--land-link", "--land-success", "--land-warning", "--land-purple"):
309 assert f"{role}: color-mix(" in light, role
310 landing = scss[scss.index("// ── Suggested reading paths") : scss.index("// ── Shared docs figure")]
311 landing += scss[scss.index(".devdocs-eyebrow") : scss.index(".devdocs-tag")]
312 assert "--text-muted" not in landing, "--text-muted is below 4.5:1 for small text in both themes"
313 # Text colour only: borders, fills and wires may use the raw tokens (non-text, decorative).
314 raw = [v for v in re.findall(r"(?<![-\w])color:\s*([^;]+);", landing) if v.strip().startswith("var(--color-")]
315 assert raw == [], f"read accent/status text colours through the --land-* roles, not {raw}"
316
317
318 def test_doc_land_20_reading_paths_are_a_labelled_ordered_table(rendered: dict[str, str]) -> None:
319 html = rendered[rc.DOCS_ROOT]
320 m = re.search(r'<section class="devdocs-reading-paths" aria-labelledby="([^"]+)">(.*?)</section>', html, re.S)
321 assert m and f'id="{m.group(1)}"' in m.group(2)
322 rows = re.findall(r'<tr class="devdocs-reading-path">(.*?)</tr>', m.group(2), re.S)
323 assert len(rows) == len(ui_docs._READING_PATHS)
324 for row, (goal, _, slugs) in zip(rows, ui_docs._READING_PATHS):
325 assert re.search(rf'<th scope="row">.*?{re.escape(goal)}', row, re.S), goal
326 steps = re.search(r'<ol class="devdocs-reading-path__steps">(.*?)</ol>', row, re.S)
327 assert steps and steps.group(1).count("<li>") == len(slugs), goal
File History 10 commits
sha256:5bc6578bee044ce139e12989ae6d957b3da072f7952f3d03c243e9b517550c77 docs(security,landing): call-site pins and the fail-closed … Opus 5.5 patch 1 day ago
sha256:e1629e5f328982dbf6e535d3f253993c78ff225dfee4ebb0e0a15fc1db69046b merge: rc25 — docs and docs-contract tests match Muse batch… Opus 5.5 minor ⚠ 2 days ago
sha256:af59de7b8c8e9eaa86759e00caf5ee286439cf1dfc7730b6fb144cb29dd4a09f docs(domains,crdt,landing): .museattributes in every domain… Opus 5.5 minor ⚠ 2 days ago
sha256:a854c8a1d0741324c1efdd52a873f3447587724a66250c0eabe3906f5c505825 docs(landing): tie the interim light-theme colour roles to … Opus 5.5 9 days ago
sha256:d92f362b6c8aa3408e30fde1ad762a1e85c0f0fc054635d225c536d854470aba docs(landing): QA contract v2 — engine-pinned claim fixes, … Opus 5.5 minor ⚠ 9 days ago
sha256:f7413c1abec6d6a8e5bdabcd4cc7ad5fcd059ce6a6f50f566e2b0118a0a8b578 tests: make tests/docs_contract/ database-free by directory… Opus 5.5 10 days ago
sha256:597ccb67ee85981be2facd62d44c72e3484f2323c8ca876ca388d498e0c2a5a9 Merge task/243-docs-concept-map (#243 V1 concept map) into dev Opus 5.5 patch 10 days ago
sha256:13b886ba1f92343d568cf8cdf74846810609fc4c244e6edacee8451e1f15d22d docs(landing): interactive architecture concept map on /mus… Opus 5.5 patch 10 days ago
sha256:4414683727ea0547451795e9f87989be0031d71016b9595460967dcbb446ddc8 Merge dev (#243 landing) into task/244-docs-getting-started… Opus 5.5 patch 10 days ago
sha256:4a670eb4493ce4626bb9b9380af6057d90cb61ac4af2800d4b03f3ec61ee70dc docs(landing): derive /muse stats and reading paths from th… Opus 5.5 patch 10 days ago