"""Read-only checks of use-case-driven Markdown conventions; no dependencies.""" from __future__ import annotations import argparse import re import unicodedata from pathlib import Path from urllib.parse import unquote SECTIONS = ( "Участники", "Предусловия", "Основной поток", "Альтернативы и ошибки", "Результат", "Коды завершения", ) CODE = re.compile(r"\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b") LINK = re.compile(r"\[([^\]]+)\]\(#([^)]+)\)") HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$") LEGACY_REQUIREMENT_ID_PATTERN = r"[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+" QUALIFIED_REQUIREMENT_ID_PATTERN = r"[A-Z][A-Z0-9]*(?:\.[A-Z][A-Z0-9]*)+-\d{2,}" REQUIREMENT_ID_PATTERN = rf"(?:{QUALIFIED_REQUIREMENT_ID_PATTERN}|{LEGACY_REQUIREMENT_ID_PATTERN})" REQUIREMENT_ID = re.compile(rf"^\*\*ID:\*\* `({REQUIREMENT_ID_PATTERN})`$", re.MULTILINE) FR_ID_PATTERN = rf"(?:{QUALIFIED_REQUIREMENT_ID_PATTERN}\.)?FR-\d{{2,}}" FR_ID = re.compile(rf"^(?:(?P{QUALIFIED_REQUIREMENT_ID_PATTERN})\.)?(?PFR-\d{{2,}})$") FR_HEADING = re.compile(rf"^##### ({FR_ID_PATTERN})(?: \[(DB|API|UI)\])?: (.+)$", re.MULTILINE) HTML_ANCHOR = re.compile(r"]*\bid\s*=", re.IGNORECASE) DB_TABLE_COLUMNS = ("Поле", "Тип", "Ограничения и значение по умолчанию", "Назначение") CONTRACT_COLUMNS = ("Поле", "Тип", "Обязательность", "Ограничения и значение по умолчанию", "Назначение") RESPONSE_CONTRACT_COLUMNS = (*CONTRACT_COLUMNS, "Формирование значения") def plain_text(value: str) -> str: value = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", value) return re.sub(r"^[\d.\-\s]+|[`*_]", "", value).strip() def heading_slug(title: str) -> str: """Build the heading fragment used by GitHub-style Markdown renderers.""" title = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", title) title = re.sub(r"[`*_~]", "", title).lower() slug: list[str] = [] for char in title: category = unicodedata.category(char)[0] if char.isspace(): if slug and slug[-1] != "-": slug.append("-") elif char in {"-", "_"} or category in {"L", "M", "N"}: slug.append(char) return "".join(slug).strip("-") def parse_fr_reference(label: str) -> tuple[str | None, str] | None: """Return an optional requirement ID and the local FR number from a link label.""" label = label.strip() match = FR_ID.fullmatch(label) if match: return match.group("requirement"), match.group("number") match = re.fullmatch( rf"({LEGACY_REQUIREMENT_ID_PATTERN})\s*/\s*(FR-\d{{2,}})", label ) if match: return match.group(1), match.group(2) return None def openspec_root_for(path: Path) -> Path: """Find the OpenSpec root containing a master or change spec.""" resolved = path.resolve() for parent in (resolved, *resolved.parents): if parent.name == "openspec": return parent return (Path.cwd() / "openspec").resolve() def load_capability_prefixes(openspec_root: Path) -> tuple[dict[str, str], list[str]]: """Read the active path-to-prefix mapping from master specs.""" specs_root = openspec_root / "specs" spec_paths = set(specs_root.rglob("spec.md")) prefixes_by_capability: dict[str, set[str]] = {} errors: list[str] = [] for spec_path in sorted(spec_paths): capability_path = spec_path.parent.relative_to(specs_root).as_posix() try: ids = REQUIREMENT_ID.findall(spec_path.read_text(encoding="utf-8")) except OSError as error: errors.append(f"не удалось прочитать спецификацию {spec_path}: {error}") continue prefixes = { requirement_id.rsplit("-", 1)[0] for requirement_id in ids if "." in requirement_id } if prefixes: prefixes_by_capability.setdefault(capability_path, set()).update(prefixes) prefix_owners: dict[str, set[str]] = {} mappings: dict[str, str] = {} for capability_path, prefixes in prefixes_by_capability.items(): if len(prefixes) != 1: errors.append( f"capability {capability_path} использует несколько префиксов: " f"{', '.join(sorted(prefixes))}" ) continue prefix = next(iter(prefixes)) mappings[capability_path] = prefix prefix_owners.setdefault(prefix, set()).add(capability_path) for prefix, owners in prefix_owners.items(): if len(owners) > 1: errors.append( f"префикс {prefix} используется несколькими capabilities: " f"{', '.join(sorted(owners))}" ) return mappings, errors def load_active_change_prefixes( openspec_root: Path, exclude_path: Path, ) -> dict[str, set[str]]: """Read prefixes declared by other in-flight changes.""" changes_root = openspec_root / "changes" excluded = exclude_path.resolve() prefixes_by_capability: dict[str, set[str]] = {} if not changes_root.is_dir(): return prefixes_by_capability for change_dir in changes_root.iterdir(): if not change_dir.is_dir() or change_dir.name == "archive": continue for spec_path in change_dir.rglob("spec.md"): if spec_path.resolve() == excluded: continue capability_path = spec_capability_path(spec_path) if not capability_path: continue try: ids = REQUIREMENT_ID.findall(spec_path.read_text(encoding="utf-8")) except OSError: continue prefixes = { requirement_id.rsplit("-", 1)[0] for requirement_id in ids if "." in requirement_id } if prefixes: prefixes_by_capability.setdefault(capability_path, set()).update(prefixes) return prefixes_by_capability def check_capability_ids( path: Path, requirement_ids: list[str], known_prefixes: dict[str, str], base: Path | None = None, ) -> list[str]: """Check that a spec uses one stable, project-unique capability prefix.""" prefixes = { requirement_id.rsplit("-", 1)[0] for requirement_id in requirement_ids if "." in requirement_id } if not prefixes: return [] capability_path = spec_capability_path(path) if not capability_path: return ["по пути файла не удалось определить capability для составного Requirement ID"] errors: list[str] = [] if len(prefixes) > 1: errors.append( f"capability {capability_path} использует несколько префиксов: " f"{', '.join(sorted(prefixes))}" ) base_capability_path = spec_capability_path(base) if base else None owners_by_prefix: dict[str, set[str]] = {} for known_path, known_prefix in known_prefixes.items(): owners_by_prefix.setdefault(known_prefix, set()).add(known_path) expected_prefix = known_prefixes.get(capability_path) if expected_prefix is None and base_capability_path: expected_prefix = known_prefixes.get(base_capability_path) active_change_prefixes: dict[str, set[str]] = {} if is_change_spec(path): active_change_prefixes = load_active_change_prefixes( openspec_root_for(path), path ) for prefix in prefixes: if expected_prefix and prefix != expected_prefix: errors.append( f"ID использует префикс {prefix}, но для capability {capability_path} " f"уже назначен {expected_prefix}" ) owners = owners_by_prefix.get(prefix, set()) if owners and capability_path not in owners and base_capability_path not in owners: errors.append( f"префикс {prefix} уже используется capability " f"{', '.join(sorted(owners))}" ) for active_path, active_prefixes in active_change_prefixes.items(): if active_path == capability_path and len(active_prefixes) > 1: errors.append( f"активные changes для capability {capability_path} используют " f"несколько префиксов: {', '.join(sorted(active_prefixes))}" ) if active_path == capability_path and prefix not in active_prefixes: errors.append( f"change для capability {capability_path} использует другой префикс: " f"{', '.join(sorted(active_prefixes))}" ) elif ( prefix in active_prefixes and active_path != capability_path and active_path != base_capability_path ): errors.append( f"префикс {prefix} уже используется активным change " f"для capability {active_path}" ) return errors def spec_capability_path(path: Path) -> str | None: parts = path.parts indexes = [index for index, part in enumerate(parts) if part == "specs"] if not indexes: return None capability_parts = parts[indexes[-1] + 1:-1] return "/".join(capability_parts) if capability_parts else None def is_change_spec(path: Path) -> bool: parts = path.parts changes_indexes = [index for index, part in enumerate(parts) if part == "changes"] specs_indexes = [index for index, part in enumerate(parts) if part == "specs"] return bool(changes_indexes and specs_indexes and specs_indexes[-1] > changes_indexes[-1]) def heading_targets(text: str) -> tuple[set[str], dict[str, tuple[str, str]]]: """Return generated heading fragments and fragments that target FR headings.""" targets: set[str] = set() fr_targets: dict[str, tuple[str, str]] = {} duplicates: dict[str, int] = {} requirement_id = "" for line in text.splitlines(): if line.startswith("### Requirement:"): requirement_id = "" id_match = REQUIREMENT_ID.match(line) if id_match: requirement_id = id_match.group(1) match = HEADING.match(line) if not match: continue slug = heading_slug(match.group(2)) if not slug: continue duplicate_index = duplicates.get(slug, 0) duplicates[slug] = duplicate_index + 1 target = slug if duplicate_index == 0 else f"{slug}-{duplicate_index}" targets.add(target) fr_match = FR_HEADING.match(line) if fr_match and requirement_id: fr_id = FR_ID.fullmatch(fr_match.group(1)) if fr_id: fr_targets[target] = (requirement_id, fr_id.group("number")) return targets, fr_targets def requirement_blocks(text: str): heading = re.compile(r"^## .*|^### Requirement: (.+)$", re.MULTILINE) headings = list(heading.finditer(text)) operation = "" for index, match in enumerate(headings): if not match.group(1): operation = match.group().removeprefix("## ") continue if operation in {"REMOVED Requirements", "RENAMED Requirements"}: continue end = headings[index + 1].start() if index + 1 < len(headings) else len(text) yield match.group(1), text[match.end():end] def check_database_table_pattern(content: str) -> list[str]: errors: list[str] = [] tables: list[list[str]] = [] current: list[str] = [] for line in content.splitlines(): if line.strip().startswith("|"): current.append(line.strip()) elif current: tables.append(current) current = [] if current: tables.append(current) if len(tables) != 1: return ["паттерн таблицы БД требует ровно одну Markdown-таблицу"] rows = [[cell.strip() for cell in row.strip("|").split("|")] for row in tables[0]] if len(rows) < 3 or tuple(rows[0]) != DB_TABLE_COLUMNS: return ["таблица БД должна иметь заголовки Поле, Тип, Ограничения и значение по умолчанию, Назначение"] if len(rows[1]) != len(DB_TABLE_COLUMNS) or any(not re.fullmatch(r":?-{3,}:?", cell) for cell in rows[1]): errors.append("в таблице БД некорректная строка разделителя") field_names: set[str] = set() for row in rows[2:]: if len(row) != len(DB_TABLE_COLUMNS) or any(not cell for cell in row): errors.append("каждая строка таблицы БД должна содержать четыре непустые ячейки") continue field_name = row[0].strip("`") if field_name in field_names: errors.append(f"поле `{field_name}` повторяется в таблице БД") field_names.add(field_name) return errors def check_message_contract_pattern(content: str, direction: str | None = None) -> list[str]: errors: list[str] = [] contract_type_match = re.search(r"(?m)^Тип контракта: (request|response)$", content) if direction is None and not contract_type_match: errors.append("контракт должен явно указывать Тип контракта: request или response") selected_direction = direction or (contract_type_match.group(1) if contract_type_match else "") columns = ( RESPONSE_CONTRACT_COLUMNS if selected_direction == "response" else CONTRACT_COLUMNS ) tables: list[list[str]] = [] current: list[str] = [] for line in content.splitlines(): if line.strip().startswith("|"): current.append(line.strip()) elif current: tables.append(current) current = [] if current: tables.append(current) if len(tables) != 1: return errors + ["паттерн контракта требует ровно одну Markdown-таблицу"] rows = [[cell.strip() for cell in row.strip("|").split("|")] for row in tables[0]] if len(rows) < 3 or tuple(rows[0]) != columns: required_columns = ", ".join(columns) return errors + [f"таблица контракта должна содержать колонки: {required_columns}"] if len(rows[1]) != len(columns) or any(not re.fullmatch(r":?-{3,}:?", cell) for cell in rows[1]): errors.append("в таблице контракта некорректная строка разделителя") field_names: set[str] = set() for row in rows[2:]: if len(row) != len(columns) or any(not cell for cell in row): errors.append("каждая строка таблицы контракта должна содержать нужное число непустых ячеек") continue field_name = row[0].strip(chr(96)) if field_name in field_names: errors.append(f"поле контракта {field_name} повторяется") field_names.add(field_name) if row[2] not in {"Обязательное", "Опциональное"}: errors.append(f"поле контракта {field_name} должно явно задавать обязательность") return errors def check_http_endpoint_contract(content: str) -> list[str]: errors: list[str] = [] headings = re.findall(r"^##### (.+)$", content, re.MULTILINE) if headings != ["Request", "Response"]: return ["CONTRACT должен содержать только подразделы Request и Response в этом порядке"] request, response = re.split(r"^##### (?:Request|Response)\s*$", content, maxsplit=2, flags=re.MULTILINE)[1:] if len(re.findall(r"(?m)^Метод: \x60?(?:GET|POST|PUT|PATCH|DELETE)\x60?; путь: \x60?/\S+", request)) != 1: errors.append("в Request укажи один HTTP-метод и путь endpoint") request_tables = sum(line.strip().startswith("|") for line in request.splitlines()) if request_tables: errors.extend(check_message_contract_pattern(request, "request")) elif not re.search(r"Тело запроса(?: и query-параметры)? отсутств(?:ует|уют)", request): errors.append("в Request укажи таблицу тела запроса или явно отметь его отсутствие") if not re.search(r"(?m)^HTTP status:", response): errors.append("в Response укажи HTTP status") errors.extend(check_message_contract_pattern(response, "response")) return errors def check_requirement( name: str, block: str, targets: set[str], fr_targets: dict[str, tuple[str, str]], require_qualified_ids: bool = False, ) -> list[str]: errors: list[str] = [] ids = REQUIREMENT_ID.findall(block) if len(ids) != 1: return [f"{name}: нужен один стабильный **ID:** с префиксом capability и номером Requirement"] requirement_id = ids[0] is_qualified = "." in requirement_id if require_qualified_ids and not is_qualified: errors.append("новый или изменённый Requirement должен иметь составной ID capability, например AREA.CAP-01") level_four = re.findall(r"^#### (.+)$", block, re.MULTILINE) has_contract = len(level_four) == 3 and level_four[2] == "CONTRACT" expected_level_four = ["Функциональные требования", "CONTRACT"] if has_contract else ["Функциональные требования"] if ( len(level_four) != len(expected_level_four) + 1 or not level_four[0].startswith("Scenario: ") or level_four[1:] != expected_level_four ): return [f"{name}: нужны один Scenario, Функциональные требования и опциональный завершающий CONTRACT"] scenario_heading = level_four[0].removeprefix("Scenario: ") is_short_use_case = scenario_heading.startswith("Сокращенный use case:") scenario, details = block.split("#### Функциональные требования", 1) scenario = scenario.split("#### Scenario:", 1)[1].split("\n", 1)[1] if has_contract: if is_short_use_case: errors.append("Requirement с HTTP CONTRACT должен использовать полный Use case") details, contract_content = details.split("#### CONTRACT", 1) errors.extend(check_http_endpoint_contract(contract_content)) sections = re.findall(r"^##### (.+)$", scenario, re.MULTILINE) narrative = "" outcomes = "" short_use_case_flow_lines: list[str] = [] if is_short_use_case: if sections != ["Основной поток"]: errors.append("сокращенный use case должен содержать только Основной поток") before_flow, separator, flow = scenario.partition("##### Основной поток") if not separator or before_flow.strip(): errors.append("сокращенный use case содержит только раздел Основной поток") short_use_case_flow_lines = [line.strip() for line in flow.splitlines() if line.strip()] if any(not re.match(r"^\d+\. .+", line) for line in short_use_case_flow_lines): errors.append("основной поток сокращенного use case содержит только нумерованные шаги") if any(len(plain_text(line)) > 240 for line in short_use_case_flow_lines): errors.append("шаг сокращенного use case длиннее 240 знаков; детали должны быть в FR") else: required = [section for section in sections if section != "Назначение"] if required != list(SECTIONS) or sections.count("Назначение") > 1: errors.append("разделы Scenario не соответствуют шаблону") if "Назначение" in sections and sections[0] != "Назначение": errors.append("опциональное Назначение должно предшествовать Участники") for section in sections: content = re.split(r"^##### ", scenario.split(f"##### {section}\n", 1)[1], maxsplit=1, flags=re.MULTILINE)[0] if not content.strip(): errors.append(f"пустой раздел Scenario: {section}") narrative, separator, outcomes = scenario.partition("##### Коды завершения") if not separator: errors.append("нет списка кодов завершения") if re.search(r"^\s*\|", narrative, re.MULTILINE): errors.append("техническая таблица должна находиться в FR") for paragraph in re.split(r"\n\s*\n", narrative): lines = [line for line in paragraph.splitlines() if line.strip() and not line.startswith("#")] chunks = lines if all(re.match(r"^(?:\d+\.|-) ", line) for line in lines) else [" ".join(lines)] if any(len(plain_text(chunk)) > 240 for chunk in chunks): errors.append("абзац или шаг Scenario длиннее 240 знаков; перенеси детали в FR") if re.search(r"(?im)^\s*(?:[-*]\s*)?(?:\*\*)?(?:GIVEN|WHEN|THEN|AND|BUT)\b", scenario): errors.append("Scenario содержит Gherkin") if "```" in scenario or "~~~" in scenario: errors.append("блок кода должен находиться в FR") flow = scenario.partition("##### Основной поток")[2] if not is_short_use_case: flow = flow.partition("##### Альтернативы и ошибки")[0] steps = [int(number) for number in re.findall(r"^(\d+)\. ", flow, re.MULTILINE)] if not steps or steps != list(range(1, len(steps) + 1)): errors.append("основной поток должен содержать последовательные нумерованные шаги") raw_definitions = list(FR_HEADING.finditer(details)) if len(raw_definitions) != len(re.findall(r"^##### ", details, re.MULTILINE)): errors.append("подразделы Функциональных требований должны иметь заголовки с ID вида .FR-NN") definitions: list[tuple[re.Match[str], re.Match[str]]] = [] for match in raw_definitions: fr_id_match = FR_ID.fullmatch(match.group(1)) if not fr_id_match: errors.append(f"некорректный ID FR в заголовке: {match.group(1)}") continue definitions.append((match, fr_id_match)) numbers = [int(fr_id_match.group("number").removeprefix("FR-")) for _, fr_id_match in definitions] if not numbers or numbers[0] != 1 or numbers != sorted(set(numbers)): errors.append("FR должны начинаться с FR-01 и иметь уникальные возрастающие номера") fr_contents: dict[str, str] = {} for index, (match, fr_id_match) in enumerate(definitions): fr_id = fr_id_match.group("number") expected_fr_id = f"{requirement_id}.{fr_id}" if is_qualified else fr_id if match.group(1) != expected_fr_id: errors.append(f"заголовок FR должен использовать полный ID {expected_fr_id}") target = heading_slug(match.group(0).removeprefix("##### ")) if fr_targets.get(target) != (requirement_id, fr_id): errors.append(f"заголовок {match.group(1)} не создаёт ожидаемый Markdown-якорь") next_definition = definitions[index + 1][0] if index + 1 < len(definitions) else None end = next_definition.start() if next_definition else len(details) fr_contents[fr_id] = details[match.end():end] format_type = match.group(2) title = match.group(3) if format_type == "DB" or title.lower().startswith("таблица хранения "): errors.extend(check_database_table_pattern(fr_contents[fr_id])) if format_type == "API" and re.match(r"контракт (?:сообщения|запроса|ответа)\b", title, re.IGNORECASE): errors.extend(check_message_contract_pattern(fr_contents[fr_id])) if has_contract and format_type == "API": errors.append("HTTP request/response-контракт описывается в CONTRACT, не в FR [API]") for label, raw_target in LINK.findall(block): target = unquote(raw_target) if target not in targets: errors.append(f"ссылка {label} ведёт на отсутствующий Markdown-заголовок #{target}") continue linked_fr = parse_fr_reference(label) if "FR-" in label and not linked_fr: errors.append(f"ссылка {label} должна содержать полный ID FR") if linked_fr: target_fr = fr_targets.get(target) linked_requirement, linked_number = linked_fr if target_fr is None or target_fr[1] != linked_number: errors.append(f"ссылка {label} должна вести на заголовок соответствующего FR") if linked_requirement and target_fr and target_fr[0] != linked_requirement: errors.append(f"ссылка {label} ведёт на FR другого Requirement") if target_fr and "." in target_fr[0] and label != f"{target_fr[0]}.{target_fr[1]}": errors.append(f"ссылка {label} должна использовать полный ID {target_fr[0]}.{target_fr[1]}") if is_short_use_case: for step in short_use_case_flow_lines: has_local_fr = False for label, raw_target in LINK.findall(step): linked_fr = parse_fr_reference(label) target_fr = fr_targets.get(unquote(raw_target)) expected_label = f"{requirement_id}.FR-{linked_fr[1].removeprefix('FR-')}" if linked_fr and is_qualified else (linked_fr[1] if linked_fr else "") if linked_fr and target_fr == (requirement_id, linked_fr[1]) and label == expected_label: has_local_fr = True break if not has_local_fr: errors.append("каждый шаг сокращенного use case должен ссылаться на локальный FR") else: rows = [line for line in outcomes.splitlines() if line.startswith("|")] if not rows or rows[0] != "| Код | Смысл | Связанные FR |": errors.append("таблица завершения должна иметь колонки Код, Смысл, Связанные FR") codes = [] for row in rows[2:]: cells = [cell.strip() for cell in row.strip("|").split("|")] if len(cells) != 3 or not re.fullmatch(r"`[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+`", cells[0]): errors.append("некорректная строка таблицы кодов завершения") continue code = cells[0].strip("`") codes.append(code) references = [ fr_targets[target][1] for _, raw_target in LINK.findall(cells[2]) if (target := unquote(raw_target)) in fr_targets and fr_targets[target][0] == requirement_id ] if not cells[1] or not references or not any(code in fr_contents[fr_id] for fr_id in references if fr_id in fr_contents): errors.append(f"{code}: нужны смысл и ссылка на локальный FR, описывающий этот код") if not codes or len(codes) != len(set(codes)): errors.append("список кодов завершения пуст или содержит дубликаты") if set(CODE.findall(narrative)) != set(codes): errors.append("коды в потоке/альтернативах должны совпадать со списком завершения") return [f"{requirement_id}: {error}" for error in errors] def validate( path: Path, base: Path | None = None, require_qualified_ids: bool = False, capability_prefixes: dict[str, str] | None = None, capability_inventory_errors: list[str] | None = None, ) -> list[str]: text = path.read_text(encoding="utf-8") if HTML_ANCHOR.search(text): return ["HTML-якоря запрещены; используйте автоматически сгенерированные Markdown-якоря заголовков"] targets, fr_targets = heading_targets(text) if base: base_targets, base_fr_targets = heading_targets(base.read_text(encoding="utf-8")) targets.update(base_targets) fr_targets.update(base_fr_targets) errors = list(capability_inventory_errors or []) if capability_prefixes is None: capability_prefixes, inventory_errors = load_capability_prefixes( openspec_root_for(path) ) errors.extend(inventory_errors) blocks = list(requirement_blocks(text)) ids = REQUIREMENT_ID.findall(text) if len(ids) != len(set(ids)): errors.append("повторяющиеся ID Requirements") errors.extend(check_capability_ids(path, ids, capability_prefixes, base)) if not blocks and not re.search(r"^## (REMOVED|RENAMED) Requirements$", text, re.MULTILINE): errors.append("нет Requirements") for name, block in blocks: errors.extend(check_requirement(name, block, targets, fr_targets, require_qualified_ids)) return errors def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("paths", nargs="*", type=Path, default=[Path("openspec/specs")]) parser.add_argument("--base", type=Path, help="master spec referenced from a delta") parser.add_argument( "--require-qualified-ids", action="store_true", help="требовать составные ID у Requirements в новых или изменённых specs", ) args = parser.parse_args() paths = sorted({file for path in args.paths for file in (path.rglob("spec.md") if path.is_dir() else [path])}) if not paths: parser.error("не найдены spec.md") prefix_cache: dict[Path, tuple[dict[str, str], list[str]]] = {} reported_roots: set[Path] = set() failed = False for path in paths: try: openspec_root = openspec_root_for(path) if openspec_root not in prefix_cache: prefix_cache[openspec_root] = load_capability_prefixes(openspec_root) capability_prefixes, inventory_errors = prefix_cache[openspec_root] reported_inventory_errors = ( inventory_errors if openspec_root not in reported_roots else [] ) errors = validate( path, args.base, args.require_qualified_ids, capability_prefixes, reported_inventory_errors, ) if reported_inventory_errors: reported_roots.add(openspec_root) except OSError as error: errors = [str(error)] for error in errors: print(f"ERROR {path}: {error}") if not errors: print(f"OK {path}") failed |= bool(errors) return int(failed) if __name__ == "__main__": raise SystemExit(main())