"""Learner-map contracts: provenance, aggregation, and repeatable generation."""
import json
from pathlib import Path
import shutil
import pytest
import yaml
from core.concept_graph import ConceptGraphError, build, load_graph, refresh
@pytest.fixture
def curriculum(tmp_path):
root = tmp_path
for volume in ("vol1", "vol2"):
folder = root / "books" / volume / "01_intro"
folder.mkdir(parents=True)
(folder / "01_intro.qmd").write_text(
'---\n---\n# Introduction {#sec-intro}\n\n## Queueing {#sec-queue}\n\nWaiting increases as utilization rises.\n\n::: {#dfn-admission .callout-definition title="Admission control"}\nAdmission limits arrivals.\n:::\n'
)
graph = dict(
schema_version=1,
concepts=[
dict(
id=f"{volume}.queue",
label="Queueing delay",
teaches="Queueing",
summary="Waiting for service.",
section="sec-queue",
),
dict(
id=f"{volume}.utilization",
label="Utilization",
teaches="Queueing",
summary="Busy fraction.",
section="sec-queue",
),
],
relationships=[
dict(
id=f"{volume}.relation",
source=f"{volume}.queue",
target=f"{volume}.utilization",
predicate="increases with",
explanation="Near saturation, waits increase.",
conditions="Fixed service process.",
status="draft",
evidence=dict(
section="sec-queue",
quote="Waiting increases as utilization rises.",
),
)
],
maps=[
dict(
id=f"{volume}.queue-map",
focus_question="Why do requests wait?",
description="Queueing map.",
concepts=[f"{volume}.queue", f"{volume}.utilization"],
relationships=[f"{volume}.relation"],
)
],
)
contract = dict(
schema_version=2,
source="01_intro.qmd",
primary_concepts=["Queueing"],
secondary_concepts=[],
claims={"Queueing": "Capacity and arrivals govern waiting."},
learner_graph=graph,
)
(folder / "intro_concepts.yml").write_text(
yaml.safe_dump({"concept_map": contract})
)
site = root / "taxonomy"
(site / "vendor").mkdir(parents=True)
(site / "index.qmd").write_text("---\n---\n```{=html}\n
Viewer
\n```\n")
for name in (
"explorer.js",
"explorer.css",
"atlas.js",
"vendor/cytoscape.min.js",
"vendor/LICENSE.cytoscape",
):
(site / name).write_text("fixture")
return root
def edit_contract(root, change):
path = root / "books/vol1/01_intro/intro_concepts.yml"
value = yaml.safe_load(path.read_text())
change(value["concept_map"])
path.write_text(yaml.safe_dump(value))
def test_chapter_viewers_use_volume_template_when_explorer_has_its_own_page(curriculum):
site = curriculum / "taxonomy"
(site / "index.qmd").write_text('```{=html}\nField explorer
\n```\n')
(site / "volume-maps.qmd").write_text('```{=html}\nVolume viewer
\n```\n')
build(curriculum)
atlas = (site / "atlas.html").read_text()
assert 'id="concept-map"' in atlas
assert 'id="study-root"' not in atlas
embedded = (curriculum / "books/vol1/01_intro/concepts-generated/index.html").read_text()
assert 'id="concept-map"' in embedded
def test_field_explorer_cannot_silently_become_chapter_viewer(curriculum):
(curriculum / "taxonomy/index.qmd").write_text('```{=html}\nField explorer
\n```\n')
with pytest.raises(ConceptGraphError, match="volume-map template"):
build(curriculum)
def test_section_provenance_cannot_be_missing_or_replaced(curriculum):
source = curriculum / "books/vol1/01_intro/01_intro.qmd"
source.write_text(
source.read_text().replace(
"Waiting increases as utilization rises.", "A different statement."
)
)
with pytest.raises(ConceptGraphError, match="evidence quote changed"):
load_graph(curriculum)
def test_learner_concept_must_belong_to_teaching_owner(curriculum):
edit_contract(
curriculum,
lambda c: c["learner_graph"]["concepts"][0].update(teaches="Not owned"),
)
with pytest.raises(ConceptGraphError, match="owned concept"):
load_graph(curriculum)
def test_map_cannot_publish_an_edge_with_hidden_endpoint(curriculum):
edit_contract(curriculum, lambda c: c["learner_graph"]["maps"][0]["concepts"].pop())
with pytest.raises(ConceptGraphError, match="endpoint outside map"):
load_graph(curriculum)
def test_cross_chapter_references_resolve_without_duplicate_definitions(curriculum):
path = curriculum / "books/vol1/02_reuse"
path.mkdir()
(path / "02_reuse.qmd").write_text("# Reuse {#sec-reuse}\n")
contract = dict(
schema_version=2,
source="02_reuse.qmd",
primary_concepts=[],
secondary_concepts=[],
claims={},
learner_graph=dict(
schema_version=1,
maps=[
dict(
id="vol1.reuse",
focus_question="Where is queueing reused?",
description="Reuse.",
concepts=["vol1.queue", "vol1.utilization"],
relationships=["vol1.relation"],
)
],
),
)
(path / "reuse_concepts.yml").write_text(yaml.safe_dump({"concept_map": contract}))
graph = load_graph(curriculum)
assert len(graph["nodes"]) == 4
assert graph["maps"]["vol1.reuse"]["concepts"][0] == "vol1.queue"
def test_refresh_only_proposes_definitions_and_tracks_source_changes(curriculum):
contract = curriculum / "books/vol1/01_intro/intro_concepts.yml"
authored = contract.read_bytes()
initial = refresh(curriculum, ("vol1",))
assert initial["candidates"][0]["label"] == "Admission control"
assert not initial["changed_evidence"]
source = curriculum / "books/vol1/01_intro/01_intro.qmd"
source.write_text(source.read_text() + "\nAdditional explanation.\n")
changed = refresh(curriculum, ("vol1",))
assert changed["changed_evidence"] == ["vol1.relation"]
assert refresh(curriculum, ("vol1",))["changed_evidence"] == ["vol1.relation"]
assert contract.read_bytes() == authored
@pytest.mark.skipif(not shutil.which("dot"), reason="Graphviz is needed for rendering")
def test_rerun_is_stable_and_authoring_propagates_to_all_views(curriculum):
build(curriculum)
assert build(curriculum, check=True)["stale"] == []
catalog = json.loads((curriculum / "taxonomy/catalog.json").read_text())
assert [v["id"] for v in catalog["volumes"]] == ["vol1", "vol2"]
edit_contract(
curriculum,
lambda c: c["learner_graph"]["concepts"][0].update(
label="Request waiting time"
),
)
assert build(curriculum, check=True)["stale"]
build(curriculum, ("vol1",))
website = json.loads(
(curriculum / "taxonomy/maps/vol1.queue-map/graph.json").read_text()
)
chapter = json.loads(
(
curriculum
/ "books/vol1/01_intro/concepts-generated/maps/vol1.queue-map/graph.json"
).read_text()
)
assert website == chapter
assert website["nodes"][0]["label"] == "Request waiting time"
# A scoped chapter build must retain the full series catalog.
assert (
len(
json.loads((curriculum / "taxonomy/catalog.json").read_text())[
"volumes"
]
)
== 2
)
@pytest.mark.skipif(not shutil.which("dot"), reason="Graphviz is needed for rendering")
def test_bad_authoring_does_not_overwrite_published_assets(curriculum):
build(curriculum)
asset = curriculum / "taxonomy/maps/vol1.queue-map/graph.json"
original = asset.read_bytes()
edit_contract(
curriculum,
lambda c: c["learner_graph"]["relationships"][0].update(target="vol1.missing"),
)
with pytest.raises(ConceptGraphError, match="missing concept"):
build(curriculum)
assert asset.read_bytes() == original
def test_map_ids_cannot_escape_generated_directory(curriculum):
edit_contract(curriculum, lambda c: c["learner_graph"]["maps"][0].update(id=".."))
with pytest.raises(ConceptGraphError, match="invalid map ID"):
load_graph(curriculum)
def test_existing_concept_map_gate_catches_bad_learner_evidence(curriculum):
from checks.concept_maps import check_concept_maps
edit_contract(
curriculum,
lambda c: c["learner_graph"]["relationships"][0]["evidence"].update(
quote="Unsupported claim"
),
)
findings = check_concept_maps(curriculum / "books", curriculum)
assert any(
"learner_graph" in f.message and "evidence quote changed" in f.message
for f in findings
)
@pytest.mark.skipif(not shutil.which("dot"), reason="Graphviz is needed for rendering")
def test_chapter_viewer_embeds_graph_data_for_offline_use(curriculum):
import re
build(curriculum)
viewer = (
curriculum / "books/vol1/01_intro/concepts-generated/index.html"
).read_text()
payload = re.search(
r'',
viewer,
re.S,
)[1]
embedded = json.loads(payload)
assert embedded["maps"]["vol1.queue-map"]["graph"]["nodes"][0]["id"] == "vol1.queue"
assert "