Просмотр исходного кода

Improve CPLD ch1 ch2 teaching layout

Codex 5 месяцев назад
Родитель
Сommit
d315cbb711

Разница между файлами не показана из-за своего большого размера
+ 20 - 1
docs/cpld-html-teaching-requirements.zh-CN.md


Разница между файлами не показана из-за своего большого размера
+ 294 - 3
scripts/generate_cpld_teaching_html.py


+ 115 - 16
scripts/validate_cpld_teaching_html.py

@@ -74,6 +74,27 @@ GENERIC_NARRATION_MARKERS = [
 ]
 
 
+VISIBLE_HTML_FRAGMENT_PATTERNS = [
+    re.compile(r'\b[a-z][a-z0-9_-]{1,40}">[A-Za-z0-9\u4e00-\u9fff]', re.I),
+    re.compile(r'\b(?:button|article|section|header|aside|div|span|a)\s+class="[^"]+"', re.I),
+    re.compile(r'\bdata-term="[^"]+"', re.I),
+]
+
+RAW_HTML_CORRUPTION_PATTERNS = [
+    re.compile(r'<meta\s+charset="utf-<', re.I),
+    re.compile(r'\b[a-z_:][\w:.-]*="[^"]*<[^"]*"', re.I),
+    re.compile(r'(?<!<)\b(?:button|article|section|header|aside|div|span|a)\s+(?:class|id|type|data-[\w-]+)=', re.I),
+    re.compile(r'\b(?:class|id|href|data-target|type|aria-label)="[^"]*<[^"]*"', re.I),
+    re.compile(r'cpld-tooltip-enhance-v\d+', re.I),
+    re.compile(r'cpld-visual-teach-v\d+', re.I),
+    re.compile(r'\bvisual-body\b', re.I),
+    re.compile(r'\bteach-(?:takeaway|split|matrix|cell|figure|table|flow|step|pitfall)\b', re.I),
+    re.compile(r'<button\b[^>]*>(?:(?!</button>).)*<(?:a|button)\b', re.I | re.S),
+]
+
+BALANCED_TAGS = ["button"]
+
+
 @dataclass
 class Finding:
     level: str
@@ -110,13 +131,94 @@ def repeated_paragraphs(plain: str) -> list[str]:
     return [sentence for sentence, count in counts.items() if count >= 4]
 
 
+def clipped(text: str, start: int, size: int = 80) -> str:
+    return text[max(0, start - 24) : start + size].replace("\n", " ")
+
+
+def tag_counts(markup: str, tag: str) -> tuple[int, int]:
+    opens = len(re.findall(fr"<{tag}\b", markup, flags=re.I))
+    closes = len(re.findall(fr"</{tag}\s*>", markup, flags=re.I))
+    return opens, closes
+
+
+def validate_integrated_section(block: str, block_plain: str, index: int, name: str) -> list[Finding]:
+    findings: list[Finding] = []
+    if han_count(block_plain) < 800:
+        findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars"))
+    for marker in [
+        'class="integrated-section"',
+        'class="scene-lead"',
+        'class="visual-explain-grid"',
+        'class="integrated-mechanism"',
+        'class="visual-figure-block"',
+        'class="integrated-proof-table"',
+        'class="verify-table"',
+    ]:
+        if marker not in block:
+            findings.append(Finding("error", name, f"section {index} missing integrated marker {marker}"))
+    for forbidden in ['class="term-strip"', 'class="section-story"', 'class="evidence-panel"', 'class="explanation-flow"']:
+        if forbidden in block:
+            findings.append(Finding("error", name, f"section {index} still uses legacy marker {forbidden}"))
+    for forbidden_text in ["工程讲解", "证据与操作", "完整讲解"]:
+        if forbidden_text in block_plain:
+            findings.append(Finding("error", name, f"section {index} still exposes legacy heading {forbidden_text}"))
+    for required_text in ["先看现场", "结构图", "工程锚点表", "机制拆解", "验证与排障"]:
+        if required_text not in block_plain:
+            findings.append(Finding("error", name, f"section {index} missing integrated text {required_text}"))
+    if "<svg" not in block:
+        findings.append(Finding("error", name, f"section {index} missing integrated SVG diagram"))
+    if block.count("<table") < 2:
+        findings.append(Finding("error", name, f"section {index} missing integrated proof/verify tables"))
+    if block.count('class="term"') < 2:
+        findings.append(Finding("error", name, f"section {index} missing inline clickable terms"))
+    return findings
+
+
+def validate_legacy_section(block: str, block_plain: str, index: int, name: str) -> list[Finding]:
+    findings: list[Finding] = []
+    if han_count(block_plain) < 900:
+        findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars"))
+    if 'class="explanation-flow"' not in block:
+        findings.append(Finding("error", name, f"section {index} missing natural explanation flow"))
+    if 'class="evidence-panel"' not in block:
+        findings.append(Finding("error", name, f"section {index} missing evidence panel"))
+    if 'class="section-story"' not in block:
+        findings.append(Finding("error", name, f"section {index} missing section-specific story"))
+    if 'class="progressive-note"' not in block:
+        findings.append(Finding("error", name, f"section {index} missing progressive note"))
+    if 'class="section-thread"' in block:
+        findings.append(Finding("error", name, f"section {index} still uses generic section thread"))
+    for required_text in ["工程讲解", "证据与操作", "验证", "Runbook", "完整讲解"]:
+        if required_text not in block_plain:
+            findings.append(Finding("error", name, f"section {index} missing required text {required_text}"))
+    return findings
+
+
 def validate_file(path: Path, chapter: dict[str, Any], glossary: dict[str, Any]) -> list[Finding]:
     findings: list[Finding] = []
     html = path.read_text(encoding="utf-8")
     plain = strip_tags(html)
     name = path.name
 
-    if han_count(plain) < 9000:
+    if '<meta charset="utf-8">' not in html:
+        findings.append(Finding("error", name, "html fragment leak: missing exact utf-8 meta tag"))
+    if '<meta name="viewport" content="width=device-width, initial-scale=1">' not in html:
+        findings.append(Finding("error", name, "html fragment leak: missing exact viewport meta tag"))
+    for pattern in RAW_HTML_CORRUPTION_PATTERNS:
+        match = pattern.search(html)
+        if match:
+            findings.append(Finding("error", name, f"html fragment leak in markup: {clipped(html, match.start())}"))
+    for tag in BALANCED_TAGS:
+        opens, closes = tag_counts(html, tag)
+        if opens != closes:
+            findings.append(Finding("error", name, f"html fragment leak: unbalanced <{tag}> tags ({opens} open, {closes} close)"))
+    for pattern in VISIBLE_HTML_FRAGMENT_PATTERNS:
+        match = pattern.search(plain)
+        if match:
+            findings.append(Finding("error", name, f"html fragment leak in visible text: {clipped(plain, match.start())}"))
+
+    min_han = 8200 if chapter["id"] in {1, 2} else 9000
+    if han_count(plain) < min_han:
         findings.append(Finding("error", name, f"content depth too shallow: {han_count(plain)} Han chars"))
 
     sections = section_blocks(html)
@@ -126,21 +228,10 @@ def validate_file(path: Path, chapter: dict[str, Any], glossary: dict[str, Any])
 
     for index, block in enumerate(sections, start=1):
         block_plain = strip_tags(block)
-        if han_count(block_plain) < 900:
-            findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars"))
-        if 'class="explanation-flow"' not in block:
-            findings.append(Finding("error", name, f"section {index} missing natural explanation flow"))
-        if 'class="evidence-panel"' not in block:
-            findings.append(Finding("error", name, f"section {index} missing evidence panel"))
-        if 'class="section-story"' not in block:
-            findings.append(Finding("error", name, f"section {index} missing section-specific story"))
-        if 'class="progressive-note"' not in block:
-            findings.append(Finding("error", name, f"section {index} missing progressive note"))
-        if 'class="section-thread"' in block:
-            findings.append(Finding("error", name, f"section {index} still uses generic section thread"))
-        for required_text in ["工程讲解", "证据与操作", "验证", "Runbook", "完整讲解"]:
-            if required_text not in block_plain:
-                findings.append(Finding("error", name, f"section {index} missing required text {required_text}"))
+        if chapter["id"] in {1, 2}:
+            findings.extend(validate_integrated_section(block, block_plain, index, name))
+        else:
+            findings.extend(validate_legacy_section(block, block_plain, index, name))
 
     if "learning-ladder" not in html or "从浅到深的学习阶梯" not in plain:
         findings.append(Finding("error", name, "missing progressive learning ladder"))
@@ -234,6 +325,12 @@ def validate(directory: Path, content: Path) -> dict[str, Any]:
         or "generic section thread" in f.message
         or "generic narration marker" in f.message
     ]
+    integrated_section_errors = [
+        f
+        for f in errors
+        if "integrated" in f.message or "legacy marker" in f.message or "legacy heading" in f.message
+    ]
+    html_integrity_errors = [f for f in errors if "html fragment leak" in f.message]
 
     return {
         "summary": {
@@ -251,6 +348,8 @@ def validate(directory: Path, content: Path) -> dict[str, Any]:
             "learning_progression": {"passed": not learning_progression_errors, "errors": len(learning_progression_errors)},
             "knowledge_system": {"passed": not knowledge_system_errors, "errors": len(knowledge_system_errors)},
             "natural_section_story": {"passed": not natural_section_story_errors, "errors": len(natural_section_story_errors)},
+            "integrated_sections": {"passed": not integrated_section_errors, "errors": len(integrated_section_errors)},
+            "html_integrity": {"passed": not html_integrity_errors, "errors": len(html_integrity_errors)},
         },
         "findings": [f.__dict__ for f in all_findings],
     }

+ 94 - 0
tests/test_cpld_teaching_pipeline.py

@@ -1,4 +1,5 @@
 import json
+import re
 import subprocess
 import sys
 from pathlib import Path
@@ -37,6 +38,10 @@ def run_cmd(*args: str) -> subprocess.CompletedProcess[str]:
     )
 
 
+def depth_sections(html: str) -> list[str]:
+    return re.findall(r'<section class="section depth-section"[\s\S]*?</section>', html, flags=re.I)
+
+
 def test_generator_creates_all_thirteen_single_file_reports(tmp_path: Path) -> None:
     result = run_cmd(str(GENERATOR), "--content", str(CONTENT), "--output-dir", str(tmp_path))
     assert result.returncode == 0, result.stderr + result.stdout
@@ -102,6 +107,46 @@ def test_generator_creates_all_thirteen_single_file_reports(tmp_path: Path) -> N
             assert marker not in text
 
 
+def test_ch1_ch2_use_integrated_visual_sections_with_inline_terms(tmp_path: Path) -> None:
+    result = run_cmd(str(GENERATOR), "--content", str(CONTENT), "--output-dir", str(tmp_path))
+    assert result.returncode == 0, result.stderr + result.stdout
+
+    for file_name in [
+        "cpld_ch1_env_board_learning_report_v1.html",
+        "cpld_ch2_verilog_fpga_basics_learning_report_v1.html",
+    ]:
+        html = (tmp_path / file_name).read_text(encoding="utf-8")
+        sections = depth_sections(html)
+
+        assert 'class="term-strip"' not in html
+        assert "工程讲解" not in html
+        assert "完整讲解" not in html
+        assert 'class="integrated-section"' in html
+        assert html.count('class="integrated-section"') == len(sections)
+        assert html.count('class="integrated-proof-table"') >= len(sections)
+        assert html.count('class="verify-table"') >= len(sections)
+
+        for section in sections:
+            assert 'class="integrated-section"' in section
+            assert 'class="term"' in section
+            assert "<svg" in section
+            assert 'class="integrated-proof-table"' in section
+            assert 'class="verify-table"' in section
+            assert 'class="section-story"' not in section
+            assert 'class="evidence-panel"' not in section
+            assert "先看现场" in section
+            assert "结构图" in section
+            assert "工程锚点表" in section
+            assert "机制拆解" in section
+            assert "验证与排障" in section
+
+    ch3 = (tmp_path / "cpld_ch3_td_flow_learning_report_v1.html").read_text(encoding="utf-8")
+    assert 'class="term-strip"' in ch3
+    assert "工程讲解" in ch3
+    assert "完整讲解" in ch3
+    assert 'class="integrated-section"' not in ch3
+
+
 def test_validator_accepts_generated_reports_and_writes_json_receipt(tmp_path: Path) -> None:
     generated = run_cmd(str(GENERATOR), "--content", str(CONTENT), "--output-dir", str(tmp_path))
     assert generated.returncode == 0, generated.stderr + generated.stdout
@@ -122,6 +167,55 @@ def test_validator_accepts_generated_reports_and_writes_json_receipt(tmp_path: P
     assert payload["checks"]["learning_progression"]["passed"] is True
     assert payload["checks"]["knowledge_system"]["passed"] is True
     assert payload["checks"]["natural_section_story"]["passed"] is True
+    assert payload["checks"]["integrated_sections"]["passed"] is True
+    assert payload["checks"]["html_integrity"]["passed"] is True
+
+
+def test_validator_rejects_visible_html_fragment_leaks(tmp_path: Path) -> None:
+    generated = run_cmd(str(GENERATOR), "--content", str(CONTENT), "--output-dir", str(tmp_path))
+    assert generated.returncode == 0, generated.stderr + generated.stdout
+
+    target = tmp_path / "cpld_ch1_env_board_learning_report_v1.html"
+    html = target.read_text(encoding="utf-8")
+    html = html.replace(
+        "<main>",
+        '<main><p class="leak-probe">学习“td">TD 工程文件”时会看到 cpld">CPLD 这种残片。</p>',
+        1,
+    )
+    html = html.replace('class="system-node"', 'class="system-<h3>', 1)
+    target.write_text(html, encoding="utf-8")
+
+    result = run_cmd(str(VALIDATOR), "--dir", str(tmp_path), "--json")
+
+    assert result.returncode != 0
+    assert "html fragment leak" in (result.stderr + result.stdout).lower()
+
+
+def test_validator_rejects_corrupt_term_injection_and_unbalanced_buttons(tmp_path: Path) -> None:
+    generated = run_cmd(str(GENERATOR), "--content", str(CONTENT), "--output-dir", str(tmp_path))
+    assert generated.returncode == 0, generated.stderr + generated.stdout
+
+    target = tmp_path / "cpld_ch1_env_board_learning_report_v1.html"
+    html = target.read_text(encoding="utf-8")
+    html = html.replace(
+        "data-section-title=\"",
+        'data-section-title="学习“<button class="term" type="button" data-term="td">TD</button> ',
+        1,
+    )
+    html = html.replace("</style>", "/* cpld-visual-teach-v1 */\n.visual-body{display:grid}\n</style>", 1)
+    html = html.replace(
+        '<button class="pill" id="tocBtn" type="button">目录</button><a class="pill"',
+        '<button class="pill" id="tocBtn" type="button">目录<a class="pill"',
+        1,
+    )
+    target.write_text(html, encoding="utf-8")
+
+    result = run_cmd(str(VALIDATOR), "--dir", str(tmp_path), "--json")
+
+    assert result.returncode != 0
+    output = (result.stderr + result.stdout).lower()
+    assert "html fragment leak" in output
+    assert "html_integrity" in output
 
 
 def test_content_source_models_section_specific_progressive_learning_and_system_context() -> None: