"""Compile a deterministic TestPointSet from a Skill runtime state machine.""" from __future__ import annotations import re from .models import SkillBundle, TestPoint, TestPointSet COMPILER_VERSION = "runtime-state-machine-v2" STATE_MACHINE_HEADING = re.compile(r"^##\s+Runtime State Machine\s*$", re.MULTILINE) NEXT_HEADING = re.compile(r"^##\s+", re.MULTILINE) STATE_ITEM_PATTERN = re.compile(r"^\s*(\d+)\.\s+`([^`\n]+)`\s*$", re.MULTILINE) STAGE_LABEL_PATTERN = re.compile(r"^Stage\s+(\d+)\s*:", re.IGNORECASE) def _state_machine_section(content: str, skill_id: str) -> str: heading = STATE_MACHINE_HEADING.search(content) if heading is None: raise ValueError(f"Skill {skill_id} has no ## Runtime State Machine section") next_heading = NEXT_HEADING.search(content, heading.end()) return content[heading.end():next_heading.start() if next_heading else len(content)] def _testpoint_id(label: str) -> str: # A colon is a convenient separator for a human-readable description, not # a semantic requirement. For ``Stage 3: ...`` this yields ``stage-3``; # arbitrary labels such as ``Handoff: ...`` or ``Review`` work identically. name = label.split(":", 1)[0].strip() stage = STAGE_LABEL_PATTERN.match(label) if stage: # Preserve the established ID spelling for numbered stages (including # normalizing ``Stage 01`` to ``stage-1``) while keeping the compiler # fully generic for every other label. return f"stage-{int(stage.group(1))}" slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") if not slug: raise ValueError(f"runtime state item has no stable identifier: {label!r}") return slug def compile_test_points(skill: SkillBundle) -> list[TestPoint]: section = _state_machine_section(skill.content, skill.skill_id) matches = list(STATE_ITEM_PATTERN.finditer(section)) if not matches: raise ValueError(f"Skill {skill.skill_id} Runtime State Machine has no numbered code items") list_numbers = [int(match.group(1)) for match in matches] expected_numbers = list(range(1, len(matches) + 1)) if list_numbers != expected_numbers: raise ValueError( f"Skill {skill.skill_id} Runtime State Machine numbering must be contiguous from 1" ) points: list[TestPoint] = [] seen: set[str] = set() for ordinal, match in enumerate(matches, start=1): name = match.group(2).strip() testpoint_id = _testpoint_id(name) if testpoint_id in seen: raise ValueError(f"Skill {skill.skill_id} has duplicate TestPoint id {testpoint_id!r}") seen.add(testpoint_id) points.append(TestPoint( test_point_id=testpoint_id, kind="runtime_state", ordinal=ordinal, name=name, previous_test_point_id=points[-1].test_point_id if points else None, requirement=f"Runtime state {ordinal} ({name}) must be completed.", )) return points def compile_testpoint_set(skill: SkillBundle) -> TestPointSet: return TestPointSet( skill_id=skill.skill_id, skill_version=skill.version, skill_bundle_hash=skill.bundle_hash, compiler_version=COMPILER_VERSION, test_points=compile_test_points(skill), )