Skip to content

API Reference

The API reference is rendered from Python source.

Package

se_theory_reference_kit

se_theory_reference_kit package.

base

base/init.py - Shared base utilities for theory-reference tooling.

ArtifactLoadError

Bases: ReferenceKitError

Raised when a reference artifact cannot be loaded.

Source code in src/se_theory_reference_kit/base/errors.py
16
17
class ArtifactLoadError(ReferenceKitError):
    """Raised when a reference artifact cannot be loaded."""

CheckResult dataclass

One validation finding emitted by one check.

Attributes:

Name Type Description
check_id str

Stable id of the check that emitted the finding.

status CheckStatus

Check status.

severity CheckSeverity

Finding severity.

message str

Human-readable finding message.

artifact_id str | None

Optional artifact id associated with the finding.

path Path | None

Optional path associated with the finding.

detail JsonDetail

Optional structured detail for reports or downstream tooling.

Source code in src/se_theory_reference_kit/base/results.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass(frozen=True, slots=True)
class CheckResult:
    """One validation finding emitted by one check.

    Attributes:
        check_id: Stable id of the check that emitted the finding.
        status: Check status.
        severity: Finding severity.
        message: Human-readable finding message.
        artifact_id: Optional artifact id associated with the finding.
        path: Optional path associated with the finding.
        detail: Optional structured detail for reports or downstream tooling.
    """

    check_id: str
    status: CheckStatus
    severity: CheckSeverity
    message: str
    artifact_id: str | None = None
    path: Path | None = None
    detail: JsonDetail = field(default_factory=empty_detail)

CheckSeverity

Bases: StrEnum

Severity vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
38
39
40
41
42
43
class CheckSeverity(StrEnum):
    """Severity vocabulary for one validation finding."""

    INFO = "info"
    WARNING = "warning"
    ERROR = "error"

CheckStatus

Bases: StrEnum

Status vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
29
30
31
32
33
34
35
class CheckStatus(StrEnum):
    """Status vocabulary for one validation finding."""

    OK = "ok"
    PARTIAL = "partial"
    FAIL = "fail"
    CANNOT_VERIFY = "cannot-verify"

ConfigurationError

Bases: ReferenceKitError

Raised when repo-provided reference configuration is invalid.

Source code in src/se_theory_reference_kit/base/errors.py
12
13
class ConfigurationError(ReferenceKitError):
    """Raised when repo-provided reference configuration is invalid."""

ReferenceKitError

Bases: Exception

Base exception for theory-reference-kit failures.

Source code in src/se_theory_reference_kit/base/errors.py
4
5
class ReferenceKitError(Exception):
    """Base exception for theory-reference-kit failures."""

RepositoryRootError

Bases: ReferenceKitError

Raised when a repository root cannot be resolved.

Source code in src/se_theory_reference_kit/base/errors.py
8
9
class RepositoryRootError(ReferenceKitError):
    """Raised when a repository root cannot be resolved."""

cannot_verify

cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a cannot-verify result.

Source code in src/se_theory_reference_kit/base/results.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a cannot-verify result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.CANNOT_VERIFY,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

failure

failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an error failure result.

Source code in src/se_theory_reference_kit/base/results.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an error failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

find_repository_root

find_repository_root(start: Path | None = None) -> Path

Find the nearest repository root from a starting path.

Parameters:

Name Type Description Default
start Path | None

Starting path. Defaults to the current working directory.

None

Returns:

Type Description
Path

Resolved repository root path.

Raises:

Type Description
RepositoryRootError

If no repository root marker is found.

Source code in src/se_theory_reference_kit/base/paths.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def find_repository_root(start: Path | None = None) -> Path:
    """Find the nearest repository root from a starting path.

    Args:
        start: Starting path. Defaults to the current working directory.

    Returns:
        Resolved repository root path.

    Raises:
        RepositoryRootError: If no repository root marker is found.
    """
    current = (start or Path.cwd()).resolve()

    if current.is_file():
        current = current.parent

    for candidate in (current, *current.parents):
        if any((candidate / marker).exists() for marker in ROOT_MARKERS):
            return candidate

    msg = f"Could not resolve repository root from {current}"
    raise RepositoryRootError(msg)

lean_module_to_path

lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path

Resolve a Lean module name to its repository source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required
root Path | None

Repository root.

None
lean_public_root str

Expected public Lean root for the owning repository.

required

Returns:

Type Description
Path

Repository-contained Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, path-like, malformed, or outside the declared public Lean root.

Source code in src/se_theory_reference_kit/base/paths.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path:
    """Resolve a Lean module name to its repository source path.

    Args:
        module: Lean module name.
        root: Repository root.
        lean_public_root: Expected public Lean root for the owning repository.

    Returns:
        Repository-contained Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, path-like, malformed,
            or outside the declared public Lean root.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    if module_name != lean_public_root and not module_name.startswith(
        f"{lean_public_root}."
    ):
        msg = f"Expected Lean module under {lean_public_root}, got: {module_name}"
        raise PathResolutionError(msg)

    relative_path = Path(*parts).with_suffix(".lean")
    return resolve_repo_path(relative_path, root=root)

ok

ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an ok result.

Source code in src/se_theory_reference_kit/base/results.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an ok result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.OK,
        severity=CheckSeverity.INFO,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

partial

partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a partial result.

Source code in src/se_theory_reference_kit/base/results.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a partial result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.PARTIAL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

reference_artifact_path

reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Resolve a declared reference artifact path.

The declared path must be repository-relative and under the reference directory.

Parameters:

Name Type Description Default
path str | Path

Declared repository-relative artifact path.

required
root Path | None

Repository root.

None
reference_dir_name str

Name of the reference artifact directory.

'reference'

Returns:

Type Description
Path

Resolved reference artifact path.

Raises:

Type Description
PathResolutionError

If the path is outside the reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Resolve a declared reference artifact path.

    The declared path must be repository-relative and under the reference
    directory.

    Args:
        path: Declared repository-relative artifact path.
        root: Repository root.
        reference_dir_name: Name of the reference artifact directory.

    Returns:
        Resolved reference artifact path.

    Raises:
        PathResolutionError: If the path is outside the reference directory.
    """
    resolved = resolve_repo_path(path, root=root)
    reference_root = reference_dir(
        root=root,
        reference_dir_name=reference_dir_name,
    ).resolve()

    try:
        resolved.relative_to(reference_root)
    except ValueError as exc:
        msg = f"Reference artifact path is not under {reference_dir_name}/: {path}"
        raise PathResolutionError(msg) from exc

    return resolved

reference_dir

reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Return the repository reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
63
64
65
66
67
68
69
def reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Return the repository reference directory."""
    return resolve_repo_path(reference_dir_name, root=root)

resolve_repo_path

resolve_repo_path(
    path: str | Path, *, root: Path | None = None
) -> Path

Resolve a path as repository-relative and contained within the repository.

Parameters:

Name Type Description Default
path str | Path

Repository-relative path.

required
root Path | None

Repository root. Defaults to nearest detected repository root.

None

Returns:

Type Description
Path

Resolved absolute path.

Raises:

Type Description
PathResolutionError

If the path escapes the repository root.

Source code in src/se_theory_reference_kit/base/paths.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def resolve_repo_path(path: str | Path, *, root: Path | None = None) -> Path:
    """Resolve a path as repository-relative and contained within the repository.

    Args:
        path: Repository-relative path.
        root: Repository root. Defaults to nearest detected repository root.

    Returns:
        Resolved absolute path.

    Raises:
        PathResolutionError: If the path escapes the repository root.
    """
    repo_root = find_repository_root(root)
    resolved = (repo_root / path).resolve()

    try:
        resolved.relative_to(repo_root)
    except ValueError as exc:
        msg = f"Path escapes repository root: {path}"
        raise PathResolutionError(msg) from exc

    return resolved

warning

warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a warning failure result.

Source code in src/se_theory_reference_kit/base/results.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a warning failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

worst_status

worst_status(results: Iterable[CheckResult]) -> CheckStatus

Return the worst status across validation results.

Source code in src/se_theory_reference_kit/base/results.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def worst_status(results: Iterable[CheckResult]) -> CheckStatus:
    """Return the worst status across validation results."""
    rank = {
        CheckStatus.OK: 0,
        CheckStatus.PARTIAL: 1,
        CheckStatus.FAIL: 2,
        CheckStatus.CANNOT_VERIFY: 3,
    }

    worst = CheckStatus.OK
    for result in results:
        if rank[result.status] > rank[worst]:
            worst = result.status

    return worst

errors

base/errors.py - Exception types for theory-reference tooling.

ArtifactLoadError

Bases: ReferenceKitError

Raised when a reference artifact cannot be loaded.

Source code in src/se_theory_reference_kit/base/errors.py
16
17
class ArtifactLoadError(ReferenceKitError):
    """Raised when a reference artifact cannot be loaded."""
ArtifactWriteError

Bases: ReferenceKitError

Raised when a reference artifact cannot be written.

Source code in src/se_theory_reference_kit/base/errors.py
20
21
class ArtifactWriteError(ReferenceKitError):
    """Raised when a reference artifact cannot be written."""
ConfigurationError

Bases: ReferenceKitError

Raised when repo-provided reference configuration is invalid.

Source code in src/se_theory_reference_kit/base/errors.py
12
13
class ConfigurationError(ReferenceKitError):
    """Raised when repo-provided reference configuration is invalid."""
PathResolutionError

Bases: ReferenceKitError

Raised when a repository-relative path is invalid.

Source code in src/se_theory_reference_kit/base/errors.py
24
25
class PathResolutionError(ReferenceKitError):
    """Raised when a repository-relative path is invalid."""
ReferenceKitError

Bases: Exception

Base exception for theory-reference-kit failures.

Source code in src/se_theory_reference_kit/base/errors.py
4
5
class ReferenceKitError(Exception):
    """Base exception for theory-reference-kit failures."""
RepositoryRootError

Bases: ReferenceKitError

Raised when a repository root cannot be resolved.

Source code in src/se_theory_reference_kit/base/errors.py
8
9
class RepositoryRootError(ReferenceKitError):
    """Raised when a repository root cannot be resolved."""

io

base/io.py - UTF-8 text and TOML loading helpers.

load_toml
load_toml(path: Path) -> TomlDocument

Load a TOML file.

Parameters:

Name Type Description Default
path Path

TOML file path.

required

Returns:

Type Description
TomlDocument

Parsed TOML document.

Raises:

Type Description
ArtifactLoadError

If the file cannot be read or parsed.

Source code in src/se_theory_reference_kit/base/io.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def load_toml(path: Path) -> TomlDocument:
    """Load a TOML file.

    Args:
        path: TOML file path.

    Returns:
        Parsed TOML document.

    Raises:
        ArtifactLoadError: If the file cannot be read or parsed.
    """
    try:
        with path.open("rb") as file_obj:
            data = tomllib.load(file_obj)
    except (OSError, tomllib.TOMLDecodeError) as exc:
        msg = f"Unable to read TOML file: {path}"
        raise ArtifactLoadError(msg) from exc

    return data
read_text
read_text(path: Path) -> str

Read a UTF-8 text file.

Parameters:

Name Type Description Default
path Path

File path.

required

Returns:

Type Description
str

File contents.

Raises:

Type Description
ArtifactLoadError

If the file cannot be read.

Source code in src/se_theory_reference_kit/base/io.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def read_text(path: Path) -> str:
    """Read a UTF-8 text file.

    Args:
        path: File path.

    Returns:
        File contents.

    Raises:
        ArtifactLoadError: If the file cannot be read.
    """
    try:
        return path.read_text(encoding="utf-8")
    except OSError as exc:
        msg = f"Unable to read text file: {path}"
        raise ArtifactLoadError(msg) from exc
write_text
write_text(path: Path, content: str) -> None

Write a UTF-8 text file, creating parent directories if needed.

Parameters:

Name Type Description Default
path Path

Output path.

required
content str

Text content.

required

Raises:

Type Description
ArtifactWriteError

If the file cannot be written.

Source code in src/se_theory_reference_kit/base/io.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def write_text(path: Path, content: str) -> None:
    """Write a UTF-8 text file, creating parent directories if needed.

    Args:
        path: Output path.
        content: Text content.

    Raises:
        ArtifactWriteError: If the file cannot be written.
    """
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content, encoding="utf-8")
    except OSError as exc:
        msg = f"Unable to write text file: {path}"
        raise ArtifactWriteError(msg) from exc

json_utils

base/json_utils.py - Deterministic JSON helpers.

encode_json
encode_json(payload: JsonObject) -> str

Encode a JSON payload deterministically.

The payload builder owns ordering. This encoder preserves insertion order rather than sorting keys.

Parameters:

Name Type Description Default
payload JsonObject

JSON-compatible object.

required

Returns:

Type Description
str

Encoded JSON text ending with a newline.

Source code in src/se_theory_reference_kit/base/json_utils.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def encode_json(payload: JsonObject) -> str:
    """Encode a JSON payload deterministically.

    The payload builder owns ordering. This encoder preserves insertion order
    rather than sorting keys.

    Args:
        payload: JSON-compatible object.

    Returns:
        Encoded JSON text ending with a newline.
    """
    return (
        json.dumps(
            payload,
            indent=2,
            sort_keys=False,
            ensure_ascii=True,
        )
        + "\n"
    )
write_or_check_json
write_or_check_json(
    path: Path, payload: JsonObject, *, check: bool
) -> bool

Write a JSON payload or check whether the file is current.

Parameters:

Name Type Description Default
path Path

Output path.

required
payload JsonObject

JSON payload.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
bool

True when current or written, otherwise false.

Source code in src/se_theory_reference_kit/base/json_utils.py
67
68
69
70
71
72
73
74
75
76
77
78
def write_or_check_json(path: Path, payload: JsonObject, *, check: bool) -> bool:
    """Write a JSON payload or check whether the file is current.

    Args:
        path: Output path.
        payload: JSON payload.
        check: If true, check freshness without writing.

    Returns:
        True when current or written, otherwise false.
    """
    return write_or_check_text(path, encode_json(payload), check=check)
write_or_check_text
write_or_check_text(
    path: Path, content: str, *, check: bool
) -> bool

Write a file or check whether it is current.

Returns true when the file is current or was written. Returns false when check mode finds stale content.

Parameters:

Name Type Description Default
path Path

Output path.

required
content str

Expected file content.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
bool

True when current or written, otherwise false.

Source code in src/se_theory_reference_kit/base/json_utils.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def write_or_check_text(path: Path, content: str, *, check: bool) -> bool:
    """Write a file or check whether it is current.

    Returns true when the file is current or was written.
    Returns false when check mode finds stale content.

    Args:
        path: Output path.
        content: Expected file content.
        check: If true, check freshness without writing.

    Returns:
        True when current or written, otherwise false.
    """
    if check:
        if not path.exists():
            print(f"[stale] {path.as_posix()} is missing")
            return False

        current = path.read_text(encoding="utf-8")
        if current != content:
            print(f"[stale] {path.as_posix()} is out of date")
            return False

        print(f"[ok   ] {path.as_posix()}")
        return True

    write_text(path, content)
    print(f"[write] {path.as_posix()}")
    return True

paths

base/paths.py - Repository-relative path helpers.

find_repository_root
find_repository_root(start: Path | None = None) -> Path

Find the nearest repository root from a starting path.

Parameters:

Name Type Description Default
start Path | None

Starting path. Defaults to the current working directory.

None

Returns:

Type Description
Path

Resolved repository root path.

Raises:

Type Description
RepositoryRootError

If no repository root marker is found.

Source code in src/se_theory_reference_kit/base/paths.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def find_repository_root(start: Path | None = None) -> Path:
    """Find the nearest repository root from a starting path.

    Args:
        start: Starting path. Defaults to the current working directory.

    Returns:
        Resolved repository root path.

    Raises:
        RepositoryRootError: If no repository root marker is found.
    """
    current = (start or Path.cwd()).resolve()

    if current.is_file():
        current = current.parent

    for candidate in (current, *current.parents):
        if any((candidate / marker).exists() for marker in ROOT_MARKERS):
            return candidate

    msg = f"Could not resolve repository root from {current}"
    raise RepositoryRootError(msg)
lean_module_to_path
lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path

Resolve a Lean module name to its repository source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required
root Path | None

Repository root.

None
lean_public_root str

Expected public Lean root for the owning repository.

required

Returns:

Type Description
Path

Repository-contained Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, path-like, malformed, or outside the declared public Lean root.

Source code in src/se_theory_reference_kit/base/paths.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path:
    """Resolve a Lean module name to its repository source path.

    Args:
        module: Lean module name.
        root: Repository root.
        lean_public_root: Expected public Lean root for the owning repository.

    Returns:
        Repository-contained Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, path-like, malformed,
            or outside the declared public Lean root.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    if module_name != lean_public_root and not module_name.startswith(
        f"{lean_public_root}."
    ):
        msg = f"Expected Lean module under {lean_public_root}, got: {module_name}"
        raise PathResolutionError(msg)

    relative_path = Path(*parts).with_suffix(".lean")
    return resolve_repo_path(relative_path, root=root)
reference_artifact_path
reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Resolve a declared reference artifact path.

The declared path must be repository-relative and under the reference directory.

Parameters:

Name Type Description Default
path str | Path

Declared repository-relative artifact path.

required
root Path | None

Repository root.

None
reference_dir_name str

Name of the reference artifact directory.

'reference'

Returns:

Type Description
Path

Resolved reference artifact path.

Raises:

Type Description
PathResolutionError

If the path is outside the reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Resolve a declared reference artifact path.

    The declared path must be repository-relative and under the reference
    directory.

    Args:
        path: Declared repository-relative artifact path.
        root: Repository root.
        reference_dir_name: Name of the reference artifact directory.

    Returns:
        Resolved reference artifact path.

    Raises:
        PathResolutionError: If the path is outside the reference directory.
    """
    resolved = resolve_repo_path(path, root=root)
    reference_root = reference_dir(
        root=root,
        reference_dir_name=reference_dir_name,
    ).resolve()

    try:
        resolved.relative_to(reference_root)
    except ValueError as exc:
        msg = f"Reference artifact path is not under {reference_dir_name}/: {path}"
        raise PathResolutionError(msg) from exc

    return resolved
reference_dir
reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Return the repository reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
63
64
65
66
67
68
69
def reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Return the repository reference directory."""
    return resolve_repo_path(reference_dir_name, root=root)
repo_relative_path
repo_relative_path(path: Path, repo_root: Path) -> str

Return a repository-relative POSIX path.

Source code in src/se_theory_reference_kit/base/paths.py
155
156
157
def repo_relative_path(path: Path, repo_root: Path) -> str:
    """Return a repository-relative POSIX path."""
    return path.resolve().relative_to(repo_root.resolve()).as_posix()
resolve_repo_path
resolve_repo_path(
    path: str | Path, *, root: Path | None = None
) -> Path

Resolve a path as repository-relative and contained within the repository.

Parameters:

Name Type Description Default
path str | Path

Repository-relative path.

required
root Path | None

Repository root. Defaults to nearest detected repository root.

None

Returns:

Type Description
Path

Resolved absolute path.

Raises:

Type Description
PathResolutionError

If the path escapes the repository root.

Source code in src/se_theory_reference_kit/base/paths.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def resolve_repo_path(path: str | Path, *, root: Path | None = None) -> Path:
    """Resolve a path as repository-relative and contained within the repository.

    Args:
        path: Repository-relative path.
        root: Repository root. Defaults to nearest detected repository root.

    Returns:
        Resolved absolute path.

    Raises:
        PathResolutionError: If the path escapes the repository root.
    """
    repo_root = find_repository_root(root)
    resolved = (repo_root / path).resolve()

    try:
        resolved.relative_to(repo_root)
    except ValueError as exc:
        msg = f"Path escapes repository root: {path}"
        raise PathResolutionError(msg) from exc

    return resolved

results

validation/results.py - Result vocabulary for theory-reference checks.

CheckResult dataclass

One validation finding emitted by one check.

Attributes:

Name Type Description
check_id str

Stable id of the check that emitted the finding.

status CheckStatus

Check status.

severity CheckSeverity

Finding severity.

message str

Human-readable finding message.

artifact_id str | None

Optional artifact id associated with the finding.

path Path | None

Optional path associated with the finding.

detail JsonDetail

Optional structured detail for reports or downstream tooling.

Source code in src/se_theory_reference_kit/base/results.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass(frozen=True, slots=True)
class CheckResult:
    """One validation finding emitted by one check.

    Attributes:
        check_id: Stable id of the check that emitted the finding.
        status: Check status.
        severity: Finding severity.
        message: Human-readable finding message.
        artifact_id: Optional artifact id associated with the finding.
        path: Optional path associated with the finding.
        detail: Optional structured detail for reports or downstream tooling.
    """

    check_id: str
    status: CheckStatus
    severity: CheckSeverity
    message: str
    artifact_id: str | None = None
    path: Path | None = None
    detail: JsonDetail = field(default_factory=empty_detail)
CheckSeverity

Bases: StrEnum

Severity vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
38
39
40
41
42
43
class CheckSeverity(StrEnum):
    """Severity vocabulary for one validation finding."""

    INFO = "info"
    WARNING = "warning"
    ERROR = "error"
CheckStatus

Bases: StrEnum

Status vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
29
30
31
32
33
34
35
class CheckStatus(StrEnum):
    """Status vocabulary for one validation finding."""

    OK = "ok"
    PARTIAL = "partial"
    FAIL = "fail"
    CANNOT_VERIFY = "cannot-verify"
cannot_verify
cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a cannot-verify result.

Source code in src/se_theory_reference_kit/base/results.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a cannot-verify result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.CANNOT_VERIFY,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )
empty_detail
empty_detail() -> JsonDetail

Return an empty result detail dictionary.

Source code in src/se_theory_reference_kit/base/results.py
24
25
26
def empty_detail() -> JsonDetail:
    """Return an empty result detail dictionary."""
    return {}
failure
failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an error failure result.

Source code in src/se_theory_reference_kit/base/results.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an error failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )
ok
ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an ok result.

Source code in src/se_theory_reference_kit/base/results.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an ok result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.OK,
        severity=CheckSeverity.INFO,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )
partial
partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a partial result.

Source code in src/se_theory_reference_kit/base/results.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a partial result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.PARTIAL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )
warning
warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a warning failure result.

Source code in src/se_theory_reference_kit/base/results.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a warning failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )
worst_status
worst_status(results: Iterable[CheckResult]) -> CheckStatus

Return the worst status across validation results.

Source code in src/se_theory_reference_kit/base/results.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def worst_status(results: Iterable[CheckResult]) -> CheckStatus:
    """Return the worst status across validation results."""
    rank = {
        CheckStatus.OK: 0,
        CheckStatus.PARTIAL: 1,
        CheckStatus.FAIL: 2,
        CheckStatus.CANNOT_VERIFY: 3,
    }

    worst = CheckStatus.OK
    for result in results:
        if rank[result.status] > rank[worst]:
            worst = result.status

    return worst

cli

cli.py - Console entry point for se-theory-reference.

main

main(argv: Sequence[str] | None = None) -> int

Run the combined command-line interface.

Source code in src/se_theory_reference_kit/commands/root.py
38
39
40
41
42
43
44
45
46
47
48
def main(argv: Sequence[str] | None = None) -> int:
    """Run the combined command-line interface."""
    parser = build_parser()
    args = parser.parse_args(argv)

    handler = getattr(args, "handler", None)
    if handler is None:
        parser.print_help()
        return 2

    return int(handler(args))

commands

Command implementations for cli.

catalog

commands/catalog.py - Reference catalog command.

configure_catalog_parser
configure_catalog_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the catalog subcommand.

Source code in src/se_theory_reference_kit/commands/catalog.py
13
14
15
16
17
18
19
20
21
22
23
24
def configure_catalog_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the catalog subcommand."""
    parser = subparsers.add_parser(
        "catalog",
        help="Build the generated reference catalog.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Check whether the generated catalog is current without writing.",
    )
    parser.set_defaults(handler=run_catalog_command)
run_catalog_command
run_catalog_command(args: Namespace) -> int

Run generated catalog export or freshness check.

Source code in src/se_theory_reference_kit/commands/catalog.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def run_catalog_command(args: Namespace) -> int:
    """Run generated catalog export or freshness check."""
    root = None if args.root is None else Path(args.root)
    command_context = resolve_command_context(root=root)
    config = command_context.config

    if config.catalog_artifact_name is None:
        msg = (
            "theory-reference.toml must declare [export_map].catalog for catalog export"
        )
        raise RuntimeError(msg)
    if config.catalog_schema is None:
        msg = "theory-reference.toml must resolve a catalog schema for catalog export"
        raise RuntimeError(msg)

    namespace = (
        config.reference_namespace or f"se.{config.artifact_slug.replace('-', '_')}"
    )

    registry = build_registry_from_config(command_context.repo_root, config)

    payload = build_reference_catalog(
        registry=registry,
        schema=config.catalog_schema,
        repo_root=command_context.repo_root,
        source=config.repo_slug,
        namespace=namespace,
        artifact=config.catalog_artifact_name,
    )

    output_path = (
        command_context.repo_root
        / config.generated_data_dir
        / f"{config.catalog_artifact_name}.json"
    )

    current = write_or_check_text(
        output_path,
        encode_json(payload),
        check=bool(args.check),
    )

    if current:
        print(
            "Reference catalog is current."
            if args.check
            else "Reference catalog completed."
        )
        return 0

    print("Reference catalog is stale.")
    return 1

export

commands/export.py - Generated export command.

configure_export_parser
configure_export_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the export subcommand.

Source code in src/se_theory_reference_kit/commands/export.py
12
13
14
15
16
17
18
19
20
21
22
23
def configure_export_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the export subcommand."""
    parser = subparsers.add_parser(
        "export",
        help="Export generated data artifacts from reference artifacts.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Check whether generated artifacts are current without writing.",
    )
    parser.set_defaults(handler=run_export_command)
run_export_command
run_export_command(args: Namespace) -> int

Run generated export or export freshness check.

Source code in src/se_theory_reference_kit/commands/export.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def run_export_command(args: Namespace) -> int:
    """Run generated export or export freshness check."""
    raw_root = getattr(args, "root", None)
    root = None if raw_root is None else Path(raw_root)

    command_context = resolve_command_context(root=root)

    registry = build_registry_from_config(
        command_context.repo_root,
        command_context.config,
    )

    namespace = _reference_namespace(command_context.config)

    reference_root = (
        command_context.repo_root / command_context.config.reference_dir_name
    )
    output_root = command_context.repo_root / command_context.config.generated_data_dir

    results = export_registries(
        specs=command_context.export_specs,
        registry=registry,
        repo_root=command_context.repo_root,
        reference_root=reference_root,
        output_root=output_root,
        repo_slug=command_context.config.repo_slug,
        reference_namespace=namespace,
        check=bool(args.check),
    )

    if all(result.current for result in results):
        if args.check:
            print("Reference exports are current.")
        else:
            print("Reference export completed.")
        return 0

    print("Reference exports are stale.")
    return 1

inspect

commands/inspect.py - Inspect resolved theory-reference declarations.

configure_inspect_parser
configure_inspect_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the inspect subcommand.

Source code in src/se_theory_reference_kit/commands/inspect.py
11
12
13
14
15
16
17
def configure_inspect_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the inspect subcommand."""
    parser = subparsers.add_parser(
        "inspect",
        help="Inspect resolved theory-reference declarations.",
    )
    parser.set_defaults(handler=run_inspect_command)
run_inspect_command
run_inspect_command(args: Namespace) -> int

Inspect the resolved command context.

Source code in src/se_theory_reference_kit/commands/inspect.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def run_inspect_command(args: Namespace) -> int:
    """Inspect the resolved command context."""
    raw_root = getattr(args, "root", None)
    root = None if raw_root is None else Path(raw_root)

    command_context = resolve_command_context(root=root)
    config = command_context.config

    print(f"repo_root: {command_context.repo_root.as_posix()}")
    print(f"repo_slug: {config.repo_slug}")
    print(f"artifact_slug: {config.artifact_slug}")
    print(f"lean_public_root: {config.lean_public_root}")
    print(f"reference_dir: {config.reference_dir_name}")
    print(f"generated_data_dir: {config.generated_data_dir}")

    print("surface_kind_sources:")
    for kind, source in sorted(config.surface_kind_sources.items()):
        print(f"  {kind}: {source}")

    registry = build_registry_from_config(
        command_context.repo_root,
        config,
    )
    print(f"loaded_artifacts: {len(registry.artifacts)}")

    print("surface_symbols:")
    for kind, symbols in sorted(command_context.surface.by_kind.items()):
        print(f"  {kind}: {len(symbols)}")

    print(f"export_specs: {len(command_context.export_specs)}")
    for spec in command_context.export_specs:
        print(f"  {spec.source_name} -> {spec.output_name}")

    return 0

root

commands/root.py - Root command dispatcher for se-theory-reference.

build_parser
build_parser() -> ArgumentParser

Build the root argument parser.

Source code in src/se_theory_reference_kit/commands/root.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def build_parser() -> ArgumentParser:
    """Build the root argument parser."""
    parser = ArgumentParser(
        prog="se-theory-reference",
        description="Reference tooling for Structural Explainability theory repos.",
    )
    parser.add_argument(
        "--root",
        default=None,
        help="Repository root or path inside the target repository.",
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    configure_validate_parser(subparsers)
    configure_scaffold_parser(subparsers)
    configure_export_parser(subparsers)
    configure_catalog_parser(subparsers)
    configure_inspect_parser(subparsers)

    return parser
main
main(argv: Sequence[str] | None = None) -> int

Run the combined command-line interface.

Source code in src/se_theory_reference_kit/commands/root.py
38
39
40
41
42
43
44
45
46
47
48
def main(argv: Sequence[str] | None = None) -> int:
    """Run the combined command-line interface."""
    parser = build_parser()
    args = parser.parse_args(argv)

    handler = getattr(args, "handler", None)
    if handler is None:
        parser.print_help()
        return 2

    return int(handler(args))

scaffold

commands/scaffold.py - Reference scaffold command.

configure_scaffold_parser
configure_scaffold_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the scaffold subcommand.

Source code in src/se_theory_reference_kit/commands/scaffold.py
10
11
12
13
14
15
16
17
18
def configure_scaffold_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the scaffold subcommand."""
    parser = subparsers.add_parser(
        "scaffold",
        help="Scaffold missing reference entries from Lean source.",
    )
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--overwrite", action="store_true")
    parser.set_defaults(handler=run_scaffold_command)
run_scaffold_command
run_scaffold_command(args: Namespace) -> int

Run reference scaffolding.

Source code in src/se_theory_reference_kit/commands/scaffold.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def run_scaffold_command(args: Namespace) -> int:
    """Run reference scaffolding."""
    root = None if args.root is None else Path(args.root)
    command_context = resolve_command_context(root=root)

    print(f"repo_root: {command_context.repo_root.as_posix()}")
    print("Reference scaffolding command is wired.")
    print("Scaffold engine extraction is required before entries can be written.")

    if args.dry_run:
        print("mode: dry-run")
    if args.overwrite:
        print("mode: overwrite")

    return 0

validate

commands/validate.py - Validation command.

configure_validate_parser
configure_validate_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the validate subcommand.

Source code in src/se_theory_reference_kit/commands/validate.py
13
14
15
16
17
18
19
20
21
22
23
24
def configure_validate_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the validate subcommand."""
    parser = subparsers.add_parser(
        "validate",
        help="Validate reference artifacts against declared Lean public surface.",
    )
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Run strict validation checks.",
    )
    parser.set_defaults(handler=run_validate_command)
run_validate_command
run_validate_command(args: Namespace) -> int

Run validation checks.

Source code in src/se_theory_reference_kit/commands/validate.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def run_validate_command(args: Namespace) -> int:
    """Run validation checks."""
    raw_root = getattr(args, "root", None)
    root = None if raw_root is None else Path(raw_root)

    command_context = resolve_command_context(root=root)

    context = ReferenceRunContext(
        repo_root=command_context.repo_root,
        config=command_context.config,
        surface=command_context.surface,
        export_specs=command_context.export_specs,
    )

    registry = default_registry()
    report = run_checks(
        registry=registry,
        context=context,
        strict=bool(args.strict),
    )

    for result in report.results:
        print(f"[{result.check_id}] {result.status.value}  {result.message}")

    return report.exit_code

declarations

declarations/init.py - Typed declarations consumed by the generic engine.

ExportSpec dataclass

A generated JSON artifact export specification.

Source code in src/se_theory_reference_kit/declarations/export_spec.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class ExportSpec:
    """A generated JSON artifact export specification."""

    source_name: str
    source_table: str
    output_name: str
    schema: str
    payload_key: str

    @classmethod
    def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
        """Build export specs by joining [surface_kinds] and [export_map].

        Kit-owned convention for each non-catalog kind present in both maps:
            source_table = kind
            payload_key  = kind
            schema       = f"se-theory-{artifact_slug}-{kind}-registry"
        """
        repository = _section(data, "repository")
        surface_kinds = _string_mapping(data, "surface_kinds")
        export_map = _string_mapping(data, "export_map")

        slug = repository.get("theory")
        if not isinstance(slug, str) or not slug:
            return ()

        specs: list[Self] = []

        for kind, source in surface_kinds.items():
            output = export_map.get(kind)
            if output is None:
                continue

            specs.append(
                cls(
                    source_name=Path(source).name,
                    source_table=kind,
                    output_name=Path(output).name,
                    schema=f"se-theory-{slug}-{kind}-registry",
                    payload_key=kind,
                )
            )

        return tuple(specs)
specs_from_toml classmethod
specs_from_toml(
    data: Mapping[str, object],
) -> tuple[Self, ...]

Build export specs by joining [surface_kinds] and [export_map].

Kit-owned convention for each non-catalog kind present in both maps

source_table = kind payload_key = kind schema = f"se-theory-{artifact_slug}-{kind}-registry"

Source code in src/se_theory_reference_kit/declarations/export_spec.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
    """Build export specs by joining [surface_kinds] and [export_map].

    Kit-owned convention for each non-catalog kind present in both maps:
        source_table = kind
        payload_key  = kind
        schema       = f"se-theory-{artifact_slug}-{kind}-registry"
    """
    repository = _section(data, "repository")
    surface_kinds = _string_mapping(data, "surface_kinds")
    export_map = _string_mapping(data, "export_map")

    slug = repository.get("theory")
    if not isinstance(slug, str) or not slug:
        return ()

    specs: list[Self] = []

    for kind, source in surface_kinds.items():
        output = export_map.get(kind)
        if output is None:
            continue

        specs.append(
            cls(
                source_name=Path(source).name,
                source_table=kind,
                output_name=Path(output).name,
                schema=f"se-theory-{slug}-{kind}-registry",
                payload_key=kind,
            )
        )

    return tuple(specs)

SurfaceSymbols dataclass

Kinded public Lean surface symbols for one theory repository.

Source code in src/se_theory_reference_kit/declarations/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class SurfaceSymbols:
    """Kinded public Lean surface symbols for one theory repository."""

    by_kind: Mapping[str, frozenset[str]] = field(
        default_factory=lambda: EMPTY_SURFACE_MAP
    )

    def symbols_for_kind(self, kind: str) -> frozenset[str]:
        """Return public symbols for one surface kind."""
        return self.by_kind.get(kind, EMPTY_STRING_SET)

    @property
    def all_symbols(self) -> frozenset[str]:
        """Return all declared public surface symbols."""
        return frozenset(
            symbol for symbols in self.by_kind.values() for symbol in symbols
        )

    @classmethod
    def from_optional_kinds(
        cls,
        *,
        types: frozenset[str] = EMPTY_STRING_SET,
        predicates: frozenset[str] = EMPTY_STRING_SET,
        axioms: frozenset[str] = EMPTY_STRING_SET,
        theorems: frozenset[str] = EMPTY_STRING_SET,
        requirements: frozenset[str] = EMPTY_STRING_SET,
        vocabulary: frozenset[str] = EMPTY_STRING_SET,
        witnesses: frozenset[str] = EMPTY_STRING_SET,
    ) -> Self:
        """Build a surface declaration from common optional surface kinds."""
        return cls(
            by_kind={
                "type": types,
                "predicate": predicates,
                "axiom": axioms,
                "theorem": theorems,
                "requirement": requirements,
                "vocabulary": vocabulary,
                "witness": witnesses,
            }
        )
all_symbols property
all_symbols: frozenset[str]

Return all declared public surface symbols.

from_optional_kinds classmethod
from_optional_kinds(
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self

Build a surface declaration from common optional surface kinds.

Source code in src/se_theory_reference_kit/declarations/surface.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def from_optional_kinds(
    cls,
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self:
    """Build a surface declaration from common optional surface kinds."""
    return cls(
        by_kind={
            "type": types,
            "predicate": predicates,
            "axiom": axioms,
            "theorem": theorems,
            "requirement": requirements,
            "vocabulary": vocabulary,
            "witness": witnesses,
        }
    )
symbols_for_kind
symbols_for_kind(kind: str) -> frozenset[str]

Return public symbols for one surface kind.

Source code in src/se_theory_reference_kit/declarations/surface.py
19
20
21
def symbols_for_kind(self, kind: str) -> frozenset[str]:
    """Return public symbols for one surface kind."""
    return self.by_kind.get(kind, EMPTY_STRING_SET)

TheoryReferenceConfig dataclass

Repository-specific configuration consumed by the generic engine.

Source code in src/se_theory_reference_kit/declarations/config.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass(frozen=True, slots=True)
class TheoryReferenceConfig:
    """Repository-specific configuration consumed by the generic engine."""

    repo_slug: str
    artifact_slug: str
    lean_public_root: str
    reference_dir_name: str = "reference"
    generated_data_dir: Path | str = "data"
    reference_namespace: str | None = None
    catalog_artifact_name: str | None = None
    catalog_schema: str | None = None
    surface_kind_sources: Mapping[str, str] = field(
        default_factory=lambda: EMPTY_SOURCE_MAP
    )
    strict_warning_exemptions: frozenset[str] = field(
        default_factory=lambda: EMPTY_STRING_SET
    )

    @classmethod
    def from_toml(cls, data: Mapping[str, object]) -> Self:
        """Build configuration from a parsed theory-reference.toml mapping."""
        repository = _section(data, "repository")
        lean = _section(data, "lean")
        reference = _section(data, "reference")
        export = _section(data, "export")
        export_map = _string_mapping(data, "export_map")
        surface_kinds = _string_mapping(data, "surface_kinds")
        strict = _section(data, "strict")

        artifact_slug = _require_str(repository, "theory", "repository.theory")
        catalog_path = export_map.get("catalog")
        catalog_artifact = Path(catalog_path).stem if catalog_path else None
        catalog_schema = _opt_str(export.get("catalog_schema")) or (
            f"se-theory-{artifact_slug}-catalog"
        )

        return cls(
            repo_slug=_require_str(repository, "name", "repository.name"),
            artifact_slug=artifact_slug,
            lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
            reference_dir_name=_str(reference.get("root"), "reference"),
            generated_data_dir=_str(export.get("root"), "data"),
            reference_namespace=_opt_str(lean.get("namespace")),
            catalog_artifact_name=catalog_artifact,
            catalog_schema=catalog_schema,
            surface_kind_sources=surface_kinds,
            strict_warning_exemptions=frozenset(
                _string_list(strict, "warning_exemptions")
            ),
        )
from_toml classmethod
from_toml(data: Mapping[str, object]) -> Self

Build configuration from a parsed theory-reference.toml mapping.

Source code in src/se_theory_reference_kit/declarations/config.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@classmethod
def from_toml(cls, data: Mapping[str, object]) -> Self:
    """Build configuration from a parsed theory-reference.toml mapping."""
    repository = _section(data, "repository")
    lean = _section(data, "lean")
    reference = _section(data, "reference")
    export = _section(data, "export")
    export_map = _string_mapping(data, "export_map")
    surface_kinds = _string_mapping(data, "surface_kinds")
    strict = _section(data, "strict")

    artifact_slug = _require_str(repository, "theory", "repository.theory")
    catalog_path = export_map.get("catalog")
    catalog_artifact = Path(catalog_path).stem if catalog_path else None
    catalog_schema = _opt_str(export.get("catalog_schema")) or (
        f"se-theory-{artifact_slug}-catalog"
    )

    return cls(
        repo_slug=_require_str(repository, "name", "repository.name"),
        artifact_slug=artifact_slug,
        lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
        reference_dir_name=_str(reference.get("root"), "reference"),
        generated_data_dir=_str(export.get("root"), "data"),
        reference_namespace=_opt_str(lean.get("namespace")),
        catalog_artifact_name=catalog_artifact,
        catalog_schema=catalog_schema,
        surface_kind_sources=surface_kinds,
        strict_warning_exemptions=frozenset(
            _string_list(strict, "warning_exemptions")
        ),
    )

config

declarations/config.py - Repository-specific configuration model.

TheoryReferenceConfig dataclass

Repository-specific configuration consumed by the generic engine.

Source code in src/se_theory_reference_kit/declarations/config.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass(frozen=True, slots=True)
class TheoryReferenceConfig:
    """Repository-specific configuration consumed by the generic engine."""

    repo_slug: str
    artifact_slug: str
    lean_public_root: str
    reference_dir_name: str = "reference"
    generated_data_dir: Path | str = "data"
    reference_namespace: str | None = None
    catalog_artifact_name: str | None = None
    catalog_schema: str | None = None
    surface_kind_sources: Mapping[str, str] = field(
        default_factory=lambda: EMPTY_SOURCE_MAP
    )
    strict_warning_exemptions: frozenset[str] = field(
        default_factory=lambda: EMPTY_STRING_SET
    )

    @classmethod
    def from_toml(cls, data: Mapping[str, object]) -> Self:
        """Build configuration from a parsed theory-reference.toml mapping."""
        repository = _section(data, "repository")
        lean = _section(data, "lean")
        reference = _section(data, "reference")
        export = _section(data, "export")
        export_map = _string_mapping(data, "export_map")
        surface_kinds = _string_mapping(data, "surface_kinds")
        strict = _section(data, "strict")

        artifact_slug = _require_str(repository, "theory", "repository.theory")
        catalog_path = export_map.get("catalog")
        catalog_artifact = Path(catalog_path).stem if catalog_path else None
        catalog_schema = _opt_str(export.get("catalog_schema")) or (
            f"se-theory-{artifact_slug}-catalog"
        )

        return cls(
            repo_slug=_require_str(repository, "name", "repository.name"),
            artifact_slug=artifact_slug,
            lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
            reference_dir_name=_str(reference.get("root"), "reference"),
            generated_data_dir=_str(export.get("root"), "data"),
            reference_namespace=_opt_str(lean.get("namespace")),
            catalog_artifact_name=catalog_artifact,
            catalog_schema=catalog_schema,
            surface_kind_sources=surface_kinds,
            strict_warning_exemptions=frozenset(
                _string_list(strict, "warning_exemptions")
            ),
        )
from_toml classmethod
from_toml(data: Mapping[str, object]) -> Self

Build configuration from a parsed theory-reference.toml mapping.

Source code in src/se_theory_reference_kit/declarations/config.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@classmethod
def from_toml(cls, data: Mapping[str, object]) -> Self:
    """Build configuration from a parsed theory-reference.toml mapping."""
    repository = _section(data, "repository")
    lean = _section(data, "lean")
    reference = _section(data, "reference")
    export = _section(data, "export")
    export_map = _string_mapping(data, "export_map")
    surface_kinds = _string_mapping(data, "surface_kinds")
    strict = _section(data, "strict")

    artifact_slug = _require_str(repository, "theory", "repository.theory")
    catalog_path = export_map.get("catalog")
    catalog_artifact = Path(catalog_path).stem if catalog_path else None
    catalog_schema = _opt_str(export.get("catalog_schema")) or (
        f"se-theory-{artifact_slug}-catalog"
    )

    return cls(
        repo_slug=_require_str(repository, "name", "repository.name"),
        artifact_slug=artifact_slug,
        lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
        reference_dir_name=_str(reference.get("root"), "reference"),
        generated_data_dir=_str(export.get("root"), "data"),
        reference_namespace=_opt_str(lean.get("namespace")),
        catalog_artifact_name=catalog_artifact,
        catalog_schema=catalog_schema,
        surface_kind_sources=surface_kinds,
        strict_warning_exemptions=frozenset(
            _string_list(strict, "warning_exemptions")
        ),
    )

export_spec

declarations/export_spec.py - Repo-owned generated export specification shape.

ExportSpec dataclass

A generated JSON artifact export specification.

Source code in src/se_theory_reference_kit/declarations/export_spec.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class ExportSpec:
    """A generated JSON artifact export specification."""

    source_name: str
    source_table: str
    output_name: str
    schema: str
    payload_key: str

    @classmethod
    def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
        """Build export specs by joining [surface_kinds] and [export_map].

        Kit-owned convention for each non-catalog kind present in both maps:
            source_table = kind
            payload_key  = kind
            schema       = f"se-theory-{artifact_slug}-{kind}-registry"
        """
        repository = _section(data, "repository")
        surface_kinds = _string_mapping(data, "surface_kinds")
        export_map = _string_mapping(data, "export_map")

        slug = repository.get("theory")
        if not isinstance(slug, str) or not slug:
            return ()

        specs: list[Self] = []

        for kind, source in surface_kinds.items():
            output = export_map.get(kind)
            if output is None:
                continue

            specs.append(
                cls(
                    source_name=Path(source).name,
                    source_table=kind,
                    output_name=Path(output).name,
                    schema=f"se-theory-{slug}-{kind}-registry",
                    payload_key=kind,
                )
            )

        return tuple(specs)
specs_from_toml classmethod
specs_from_toml(
    data: Mapping[str, object],
) -> tuple[Self, ...]

Build export specs by joining [surface_kinds] and [export_map].

Kit-owned convention for each non-catalog kind present in both maps

source_table = kind payload_key = kind schema = f"se-theory-{artifact_slug}-{kind}-registry"

Source code in src/se_theory_reference_kit/declarations/export_spec.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
    """Build export specs by joining [surface_kinds] and [export_map].

    Kit-owned convention for each non-catalog kind present in both maps:
        source_table = kind
        payload_key  = kind
        schema       = f"se-theory-{artifact_slug}-{kind}-registry"
    """
    repository = _section(data, "repository")
    surface_kinds = _string_mapping(data, "surface_kinds")
    export_map = _string_mapping(data, "export_map")

    slug = repository.get("theory")
    if not isinstance(slug, str) or not slug:
        return ()

    specs: list[Self] = []

    for kind, source in surface_kinds.items():
        output = export_map.get(kind)
        if output is None:
            continue

        specs.append(
            cls(
                source_name=Path(source).name,
                source_table=kind,
                output_name=Path(output).name,
                schema=f"se-theory-{slug}-{kind}-registry",
                payload_key=kind,
            )
        )

    return tuple(specs)

surface

declarations/surface.py - Repo-owned Lean public surface declaration shape.

SurfaceSymbols dataclass

Kinded public Lean surface symbols for one theory repository.

Source code in src/se_theory_reference_kit/declarations/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class SurfaceSymbols:
    """Kinded public Lean surface symbols for one theory repository."""

    by_kind: Mapping[str, frozenset[str]] = field(
        default_factory=lambda: EMPTY_SURFACE_MAP
    )

    def symbols_for_kind(self, kind: str) -> frozenset[str]:
        """Return public symbols for one surface kind."""
        return self.by_kind.get(kind, EMPTY_STRING_SET)

    @property
    def all_symbols(self) -> frozenset[str]:
        """Return all declared public surface symbols."""
        return frozenset(
            symbol for symbols in self.by_kind.values() for symbol in symbols
        )

    @classmethod
    def from_optional_kinds(
        cls,
        *,
        types: frozenset[str] = EMPTY_STRING_SET,
        predicates: frozenset[str] = EMPTY_STRING_SET,
        axioms: frozenset[str] = EMPTY_STRING_SET,
        theorems: frozenset[str] = EMPTY_STRING_SET,
        requirements: frozenset[str] = EMPTY_STRING_SET,
        vocabulary: frozenset[str] = EMPTY_STRING_SET,
        witnesses: frozenset[str] = EMPTY_STRING_SET,
    ) -> Self:
        """Build a surface declaration from common optional surface kinds."""
        return cls(
            by_kind={
                "type": types,
                "predicate": predicates,
                "axiom": axioms,
                "theorem": theorems,
                "requirement": requirements,
                "vocabulary": vocabulary,
                "witness": witnesses,
            }
        )
all_symbols property
all_symbols: frozenset[str]

Return all declared public surface symbols.

from_optional_kinds classmethod
from_optional_kinds(
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self

Build a surface declaration from common optional surface kinds.

Source code in src/se_theory_reference_kit/declarations/surface.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def from_optional_kinds(
    cls,
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self:
    """Build a surface declaration from common optional surface kinds."""
    return cls(
        by_kind={
            "type": types,
            "predicate": predicates,
            "axiom": axioms,
            "theorem": theorems,
            "requirement": requirements,
            "vocabulary": vocabulary,
            "witness": witnesses,
        }
    )
symbols_for_kind
symbols_for_kind(kind: str) -> frozenset[str]

Return public symbols for one surface kind.

Source code in src/se_theory_reference_kit/declarations/surface.py
19
20
21
def symbols_for_kind(self, kind: str) -> frozenset[str]:
    """Return public symbols for one surface kind."""
    return self.by_kind.get(kind, EMPTY_STRING_SET)

export

export/init.py - Generic generated export helpers.

CatalogEntry dataclass

Generic catalog entry for one loaded reference artifact.

Source code in src/se_theory_reference_kit/export/catalog.py
13
14
15
16
17
18
19
@dataclass(frozen=True, slots=True)
class CatalogEntry:
    """Generic catalog entry for one loaded reference artifact."""

    artifact_id: str
    kind: str
    path: str

ExportResult dataclass

Result of one generated export operation.

Attributes:

Name Type Description
output_path Path

Generated output path.

current bool

True when output is current or was written.

wrote bool

True when output was written.

checked bool

True when the operation ran in check mode.

Source code in src/se_theory_reference_kit/export/engine.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@dataclass(frozen=True, slots=True)
class ExportResult:
    """Result of one generated export operation.

    Attributes:
        output_path: Generated output path.
        current: True when output is current or was written.
        wrote: True when output was written.
        checked: True when the operation ran in check mode.
    """

    output_path: Path
    current: bool
    wrote: bool
    checked: bool

build_reference_catalog

build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject

Build a generic reference catalog from loaded reference artifacts.

This function builds the common catalog envelope and reference path list. Repo-specific catalog payload sections remain owned by the theory repo.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
schema str

Catalog schema id.

required
source str

Owning repository slug.

required
namespace str

Reference namespace.

required
artifact str

Catalog artifact name.

required

Returns:

Type Description
JsonObject

JSON-compatible catalog payload.

Source code in src/se_theory_reference_kit/export/catalog.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject:
    """Build a generic reference catalog from loaded reference artifacts.

    This function builds the common catalog envelope and reference path list.
    Repo-specific catalog payload sections remain owned by the theory repo.

    Args:
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        schema: Catalog schema id.
        source: Owning repository slug.
        namespace: Reference namespace.
        artifact: Catalog artifact name.

    Returns:
        JSON-compatible catalog payload.
    """
    entries = [
        CatalogEntry(
            artifact_id=item.artifact_id,
            kind=item.kind,
            path=repo_relative_path(item.path, repo_root),
        )
        for item in registry.artifacts
    ]

    return {
        "schema": schema,
        "source": source,
        "namespace": namespace,
        "artifact": artifact,
        "reference_paths": [entry.path for entry in entries],
        "reference_artifacts": [
            {
                "id": entry.artifact_id,
                "kind": entry.kind,
                "path": entry.path,
            }
            for entry in entries
        ],
    }

build_registry_payload

build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject

Build one generated registry payload from one reference artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
document ReferenceDocument

Parsed reference artifact.

required
source_path Path

Source reference artifact path.

required
repo_root Path

Repository root used to produce portable relative paths.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace for generated payloads.

required

Returns:

Type Description
JsonObject

JSON-compatible generated registry payload.

Source code in src/se_theory_reference_kit/export/engine.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject:
    """Build one generated registry payload from one reference artifact.

    Args:
        spec: Repo-owned export specification.
        document: Parsed reference artifact.
        source_path: Source reference artifact path.
        repo_root: Repository root used to produce portable relative paths.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace for generated payloads.

    Returns:
        JSON-compatible generated registry payload.
    """
    meta = reference_artifact_meta(document)
    entries = ordered_table_values(document, spec.source_table)

    return {
        "schema": spec.schema,
        "source": meta.get("source", repo_slug),
        "namespace": meta.get("namespace", reference_namespace),
        "artifact": spec.output_name.removesuffix(".json"),
        "reference_artifact": meta.get(
            "artifact",
            spec.source_name.removesuffix(".toml"),
        ),
        "reference_path": repo_relative_path(source_path, repo_root),
        spec.payload_key: entries,
    }

export_registries

export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]

Export generated registry JSON artifacts.

Parameters:

Name Type Description Default
specs tuple[ExportSpec, ...]

Repo-owned export specifications.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
tuple[ExportResult, ...]

Export results.

Source code in src/se_theory_reference_kit/export/engine.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]:
    """Export generated registry JSON artifacts.

    Args:
        specs: Repo-owned export specifications.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export results.
    """
    return tuple(
        export_registry(
            spec=spec,
            registry=registry,
            repo_root=repo_root,
            reference_root=reference_root,
            output_root=output_root,
            repo_slug=repo_slug,
            reference_namespace=reference_namespace,
            check=check,
        )
        for spec in specs
    )

export_registry

export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult

Export one registry JSON artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root used to locate source artifacts.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
ExportResult

Export result.

Raises:

Type Description
FileNotFoundError

If the source artifact is not loaded in the registry.

Source code in src/se_theory_reference_kit/export/engine.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult:
    """Export one registry JSON artifact.

    Args:
        spec: Repo-owned export specification.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root used to locate source artifacts.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export result.

    Raises:
        FileNotFoundError: If the source artifact is not loaded in the registry.
    """
    source_path = reference_root / spec.source_name

    source_artifact = next(
        (
            artifact
            for artifact in registry.artifacts
            if artifact.path.resolve() == source_path.resolve()
        ),
        None,
    )

    if source_artifact is None:
        msg = f"export source artifact not loaded: {source_path}"
        raise FileNotFoundError(msg)

    payload = build_registry_payload(
        spec=spec,
        document=source_artifact.data,
        source_path=source_path,
        repo_root=repo_root,
        repo_slug=repo_slug,
        reference_namespace=reference_namespace,
    )

    output_path = output_root / spec.output_name
    content = encode_json(payload)
    current = write_or_check_text(output_path, content, check=check)

    return ExportResult(
        output_path=output_path,
        current=current,
        wrote=current and not check,
        checked=check,
    )

catalog

export/catalog.py - Generic reference catalog construction.

CatalogEntry dataclass

Generic catalog entry for one loaded reference artifact.

Source code in src/se_theory_reference_kit/export/catalog.py
13
14
15
16
17
18
19
@dataclass(frozen=True, slots=True)
class CatalogEntry:
    """Generic catalog entry for one loaded reference artifact."""

    artifact_id: str
    kind: str
    path: str
build_reference_catalog
build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject

Build a generic reference catalog from loaded reference artifacts.

This function builds the common catalog envelope and reference path list. Repo-specific catalog payload sections remain owned by the theory repo.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
schema str

Catalog schema id.

required
source str

Owning repository slug.

required
namespace str

Reference namespace.

required
artifact str

Catalog artifact name.

required

Returns:

Type Description
JsonObject

JSON-compatible catalog payload.

Source code in src/se_theory_reference_kit/export/catalog.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject:
    """Build a generic reference catalog from loaded reference artifacts.

    This function builds the common catalog envelope and reference path list.
    Repo-specific catalog payload sections remain owned by the theory repo.

    Args:
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        schema: Catalog schema id.
        source: Owning repository slug.
        namespace: Reference namespace.
        artifact: Catalog artifact name.

    Returns:
        JSON-compatible catalog payload.
    """
    entries = [
        CatalogEntry(
            artifact_id=item.artifact_id,
            kind=item.kind,
            path=repo_relative_path(item.path, repo_root),
        )
        for item in registry.artifacts
    ]

    return {
        "schema": schema,
        "source": source,
        "namespace": namespace,
        "artifact": artifact,
        "reference_paths": [entry.path for entry in entries],
        "reference_artifacts": [
            {
                "id": entry.artifact_id,
                "kind": entry.kind,
                "path": entry.path,
            }
            for entry in entries
        ],
    }

engine

export/engine.py - Generic generated JSON export engine.

ExportResult dataclass

Result of one generated export operation.

Attributes:

Name Type Description
output_path Path

Generated output path.

current bool

True when output is current or was written.

wrote bool

True when output was written.

checked bool

True when the operation ran in check mode.

Source code in src/se_theory_reference_kit/export/engine.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@dataclass(frozen=True, slots=True)
class ExportResult:
    """Result of one generated export operation.

    Attributes:
        output_path: Generated output path.
        current: True when output is current or was written.
        wrote: True when output was written.
        checked: True when the operation ran in check mode.
    """

    output_path: Path
    current: bool
    wrote: bool
    checked: bool
build_registry_payload
build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject

Build one generated registry payload from one reference artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
document ReferenceDocument

Parsed reference artifact.

required
source_path Path

Source reference artifact path.

required
repo_root Path

Repository root used to produce portable relative paths.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace for generated payloads.

required

Returns:

Type Description
JsonObject

JSON-compatible generated registry payload.

Source code in src/se_theory_reference_kit/export/engine.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject:
    """Build one generated registry payload from one reference artifact.

    Args:
        spec: Repo-owned export specification.
        document: Parsed reference artifact.
        source_path: Source reference artifact path.
        repo_root: Repository root used to produce portable relative paths.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace for generated payloads.

    Returns:
        JSON-compatible generated registry payload.
    """
    meta = reference_artifact_meta(document)
    entries = ordered_table_values(document, spec.source_table)

    return {
        "schema": spec.schema,
        "source": meta.get("source", repo_slug),
        "namespace": meta.get("namespace", reference_namespace),
        "artifact": spec.output_name.removesuffix(".json"),
        "reference_artifact": meta.get(
            "artifact",
            spec.source_name.removesuffix(".toml"),
        ),
        "reference_path": repo_relative_path(source_path, repo_root),
        spec.payload_key: entries,
    }
export_registries
export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]

Export generated registry JSON artifacts.

Parameters:

Name Type Description Default
specs tuple[ExportSpec, ...]

Repo-owned export specifications.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
tuple[ExportResult, ...]

Export results.

Source code in src/se_theory_reference_kit/export/engine.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]:
    """Export generated registry JSON artifacts.

    Args:
        specs: Repo-owned export specifications.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export results.
    """
    return tuple(
        export_registry(
            spec=spec,
            registry=registry,
            repo_root=repo_root,
            reference_root=reference_root,
            output_root=output_root,
            repo_slug=repo_slug,
            reference_namespace=reference_namespace,
            check=check,
        )
        for spec in specs
    )
export_registry
export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult

Export one registry JSON artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root used to locate source artifacts.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
ExportResult

Export result.

Raises:

Type Description
FileNotFoundError

If the source artifact is not loaded in the registry.

Source code in src/se_theory_reference_kit/export/engine.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult:
    """Export one registry JSON artifact.

    Args:
        spec: Repo-owned export specification.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root used to locate source artifacts.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export result.

    Raises:
        FileNotFoundError: If the source artifact is not loaded in the registry.
    """
    source_path = reference_root / spec.source_name

    source_artifact = next(
        (
            artifact
            for artifact in registry.artifacts
            if artifact.path.resolve() == source_path.resolve()
        ),
        None,
    )

    if source_artifact is None:
        msg = f"export source artifact not loaded: {source_path}"
        raise FileNotFoundError(msg)

    payload = build_registry_payload(
        spec=spec,
        document=source_artifact.data,
        source_path=source_path,
        repo_root=repo_root,
        repo_slug=repo_slug,
        reference_namespace=reference_namespace,
    )

    output_path = output_root / spec.output_name
    content = encode_json(payload)
    current = write_or_check_text(output_path, content, check=check)

    return ExportResult(
        output_path=output_path,
        current=current,
        wrote=current and not check,
        checked=check,
    )

lean

lean/init.py - Generic Lean source inspection helpers.

LeanDecl dataclass

Lean declaration with name, kind, and reference section.

Source code in src/se_theory_reference_kit/lean/declarations.py
53
54
55
56
57
58
59
@dataclass(frozen=True, slots=True)
class LeanDecl:
    """Lean declaration with name, kind, and reference section."""

    name: str
    kind: str
    section: str

expected_symbols_for_kind

expected_symbols_for_kind(
    surface: SurfaceSymbols, kind: str
) -> frozenset[str]

Return expected public Lean symbols for a surface kind.

Missing kinds return an empty set. The owning theory repository supplies the surface symbols; the kit only reads the generic shape.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
kind str

Surface kind.

required

Returns:

Type Description
frozenset[str]

Expected symbols for that kind.

Source code in src/se_theory_reference_kit/lean/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def expected_symbols_for_kind(surface: SurfaceSymbols, kind: str) -> frozenset[str]:
    """Return expected public Lean symbols for a surface kind.

    Missing kinds return an empty set. The owning theory repository supplies the
    surface symbols; the kit only reads the generic shape.

    Args:
        surface: Repo-owned public surface declaration.
        kind: Surface kind.

    Returns:
        Expected symbols for that kind.
    """
    return surface.symbols_for_kind(kind)

extract_decls

extract_decls(lean_file: Path) -> list[LeanDecl]

Extract top-level Lean declarations from a Lean file.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required

Returns:

Type Description
list[LeanDecl]

Extracted declarations. Missing files return an empty list.

Source code in src/se_theory_reference_kit/lean/declarations.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def extract_decls(lean_file: Path) -> list[LeanDecl]:
    """Extract top-level Lean declarations from a Lean file.

    Args:
        lean_file: Lean source file.

    Returns:
        Extracted declarations. Missing files return an empty list.
    """
    if not lean_file.exists():
        return []

    text = read_text(lean_file)
    return [
        LeanDecl(
            name=match.group("name"),
            kind=match.group("kind"),
            section=LEAN_DECL_TO_SECTION.get(match.group("kind"), "unknown"),
        )
        for match in DECL_RE.finditer(text)
    ]

extract_for_section

extract_for_section(
    lean_file: Path, target_section: str
) -> list[LeanDecl]

Extract Lean declarations matching a reference section.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required
target_section str

Reference section name.

required

Returns:

Type Description
list[LeanDecl]

Declarations whose Lean kind belongs to the requested section.

Source code in src/se_theory_reference_kit/lean/declarations.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def extract_for_section(lean_file: Path, target_section: str) -> list[LeanDecl]:
    """Extract Lean declarations matching a reference section.

    Args:
        lean_file: Lean source file.
        target_section: Reference section name.

    Returns:
        Declarations whose Lean kind belongs to the requested section.
    """
    wanted = SECTION_LEAN_KINDS.get(target_section)
    if wanted is None:
        return []

    return [decl for decl in extract_decls(lean_file) if decl.kind in wanted]

extract_spec_ids

extract_spec_ids(spec_file: Path) -> set[str]

Extract stable citation ids from a Lean Spec file.

Parameters:

Name Type Description Default
spec_file Path

Lean Spec source file.

required

Returns:

Type Description
set[str]

Citation id string values. Missing files return an empty set.

Source code in src/se_theory_reference_kit/lean/spec.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def extract_spec_ids(spec_file: Path) -> set[str]:
    """Extract stable citation ids from a Lean Spec file.

    Args:
        spec_file: Lean Spec source file.

    Returns:
        Citation id string values. Missing files return an empty set.
    """
    if not spec_file.exists():
        return set()

    text = read_text(spec_file)
    return {match.group("value") for match in SPEC_STRING_RE.finditer(text)}

infer_core_modules

infer_core_modules(
    surface_module: str, lean_root: Path
) -> list[str]

Infer Core modules under a public Surface module namespace.

Parameters:

Name Type Description Default
surface_module str

Public surface module, typically ending in ".Surface".

required
lean_root Path

Lean source root.

required

Returns:

Type Description
list[str]

Inferred Core module names. Returns an empty list when the surface module

list[str]

does not follow the expected Surface naming pattern or no Core files are

list[str]

found.

Source code in src/se_theory_reference_kit/lean/modules.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def infer_core_modules(surface_module: str, lean_root: Path) -> list[str]:
    """Infer Core modules under a public Surface module namespace.

    Args:
        surface_module: Public surface module, typically ending in ".Surface".
        lean_root: Lean source root.

    Returns:
        Inferred Core module names. Returns an empty list when the surface module
        does not follow the expected Surface naming pattern or no Core files are
        found.
    """
    if not surface_module.endswith(".Surface"):
        return []

    root_module = surface_module.removesuffix(".Surface")
    root_dir = lean_root.joinpath(*root_module.split("."))

    if not root_dir.exists():
        return []

    core_files = sorted(root_dir.rglob("Core.lean"))

    root_core = root_dir / "Core.lean"
    if root_core in core_files:
        core_files.remove(root_core)
        core_files.insert(0, root_core)

    return [path_to_module(path, lean_root) for path in core_files]

infer_spec_module

infer_spec_module(surface_module: str) -> str

Infer the Spec module from the public surface module.

Parameters:

Name Type Description Default
surface_module str

Public surface module.

required

Returns:

Type Description
str

Inferred Spec module name.

Source code in src/se_theory_reference_kit/lean/spec.py
40
41
42
43
44
45
46
47
48
49
50
51
52
def infer_spec_module(surface_module: str) -> str:
    """Infer the Spec module from the public surface module.

    Args:
        surface_module: Public surface module.

    Returns:
        Inferred Spec module name.
    """
    if surface_module.endswith(".Surface"):
        return surface_module.removesuffix(".Surface") + ".Spec"

    return surface_module + ".Spec"

lean_module_to_relative_path

lean_module_to_relative_path(module: str) -> Path

Convert a Lean module name to a relative Lean source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required

Returns:

Type Description
Path

Relative Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, malformed, or path-like.

Source code in src/se_theory_reference_kit/lean/modules.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def lean_module_to_relative_path(module: str) -> Path:
    """Convert a Lean module name to a relative Lean source path.

    Args:
        module: Lean module name.

    Returns:
        Relative Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, malformed, or
            path-like.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    return Path(*parts).with_suffix(".lean")

missing_expected_surface_symbols

missing_expected_surface_symbols(
    *, surface: SurfaceSymbols, registered: set[str]
) -> set[str]

Return expected public-surface symbols missing from reference registries.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
registered set[str]

Lean symbols already registered in reference artifacts.

required

Returns:

Type Description
set[str]

Expected symbols not present in registered symbols.

Source code in src/se_theory_reference_kit/lean/surface.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def missing_expected_surface_symbols(
    *,
    surface: SurfaceSymbols,
    registered: set[str],
) -> set[str]:
    """Return expected public-surface symbols missing from reference registries.

    Args:
        surface: Repo-owned public surface declaration.
        registered: Lean symbols already registered in reference artifacts.

    Returns:
        Expected symbols not present in registered symbols.
    """
    return set(surface.all_symbols) - registered

path_to_module

path_to_module(path: Path, lean_root: Path) -> str

Convert a Lean file path to a Lean module name.

Parameters:

Name Type Description Default
path Path

Lean source file.

required
lean_root Path

Root directory used for module-relative path conversion.

required

Returns:

Type Description
str

Dotted Lean module name.

Source code in src/se_theory_reference_kit/lean/modules.py
46
47
48
49
50
51
52
53
54
55
56
57
def path_to_module(path: Path, lean_root: Path) -> str:
    """Convert a Lean file path to a Lean module name.

    Args:
        path: Lean source file.
        lean_root: Root directory used for module-relative path conversion.

    Returns:
        Dotted Lean module name.
    """
    relative = path.relative_to(lean_root).with_suffix("")
    return ".".join(relative.parts)

declarations

lean/declarations.py - Extract generic Lean declarations from source files.

LeanDecl dataclass

Lean declaration with name, kind, and reference section.

Source code in src/se_theory_reference_kit/lean/declarations.py
53
54
55
56
57
58
59
@dataclass(frozen=True, slots=True)
class LeanDecl:
    """Lean declaration with name, kind, and reference section."""

    name: str
    kind: str
    section: str
extract_decls
extract_decls(lean_file: Path) -> list[LeanDecl]

Extract top-level Lean declarations from a Lean file.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required

Returns:

Type Description
list[LeanDecl]

Extracted declarations. Missing files return an empty list.

Source code in src/se_theory_reference_kit/lean/declarations.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def extract_decls(lean_file: Path) -> list[LeanDecl]:
    """Extract top-level Lean declarations from a Lean file.

    Args:
        lean_file: Lean source file.

    Returns:
        Extracted declarations. Missing files return an empty list.
    """
    if not lean_file.exists():
        return []

    text = read_text(lean_file)
    return [
        LeanDecl(
            name=match.group("name"),
            kind=match.group("kind"),
            section=LEAN_DECL_TO_SECTION.get(match.group("kind"), "unknown"),
        )
        for match in DECL_RE.finditer(text)
    ]
extract_for_section
extract_for_section(
    lean_file: Path, target_section: str
) -> list[LeanDecl]

Extract Lean declarations matching a reference section.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required
target_section str

Reference section name.

required

Returns:

Type Description
list[LeanDecl]

Declarations whose Lean kind belongs to the requested section.

Source code in src/se_theory_reference_kit/lean/declarations.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def extract_for_section(lean_file: Path, target_section: str) -> list[LeanDecl]:
    """Extract Lean declarations matching a reference section.

    Args:
        lean_file: Lean source file.
        target_section: Reference section name.

    Returns:
        Declarations whose Lean kind belongs to the requested section.
    """
    wanted = SECTION_LEAN_KINDS.get(target_section)
    if wanted is None:
        return []

    return [decl for decl in extract_decls(lean_file) if decl.kind in wanted]

modules

lean/modules.py - Convert between Lean module names and source paths.

infer_core_modules
infer_core_modules(
    surface_module: str, lean_root: Path
) -> list[str]

Infer Core modules under a public Surface module namespace.

Parameters:

Name Type Description Default
surface_module str

Public surface module, typically ending in ".Surface".

required
lean_root Path

Lean source root.

required

Returns:

Type Description
list[str]

Inferred Core module names. Returns an empty list when the surface module

list[str]

does not follow the expected Surface naming pattern or no Core files are

list[str]

found.

Source code in src/se_theory_reference_kit/lean/modules.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def infer_core_modules(surface_module: str, lean_root: Path) -> list[str]:
    """Infer Core modules under a public Surface module namespace.

    Args:
        surface_module: Public surface module, typically ending in ".Surface".
        lean_root: Lean source root.

    Returns:
        Inferred Core module names. Returns an empty list when the surface module
        does not follow the expected Surface naming pattern or no Core files are
        found.
    """
    if not surface_module.endswith(".Surface"):
        return []

    root_module = surface_module.removesuffix(".Surface")
    root_dir = lean_root.joinpath(*root_module.split("."))

    if not root_dir.exists():
        return []

    core_files = sorted(root_dir.rglob("Core.lean"))

    root_core = root_dir / "Core.lean"
    if root_core in core_files:
        core_files.remove(root_core)
        core_files.insert(0, root_core)

    return [path_to_module(path, lean_root) for path in core_files]
lean_module_to_relative_path
lean_module_to_relative_path(module: str) -> Path

Convert a Lean module name to a relative Lean source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required

Returns:

Type Description
Path

Relative Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, malformed, or path-like.

Source code in src/se_theory_reference_kit/lean/modules.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def lean_module_to_relative_path(module: str) -> Path:
    """Convert a Lean module name to a relative Lean source path.

    Args:
        module: Lean module name.

    Returns:
        Relative Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, malformed, or
            path-like.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    return Path(*parts).with_suffix(".lean")
path_to_module
path_to_module(path: Path, lean_root: Path) -> str

Convert a Lean file path to a Lean module name.

Parameters:

Name Type Description Default
path Path

Lean source file.

required
lean_root Path

Root directory used for module-relative path conversion.

required

Returns:

Type Description
str

Dotted Lean module name.

Source code in src/se_theory_reference_kit/lean/modules.py
46
47
48
49
50
51
52
53
54
55
56
57
def path_to_module(path: Path, lean_root: Path) -> str:
    """Convert a Lean file path to a Lean module name.

    Args:
        path: Lean source file.
        lean_root: Root directory used for module-relative path conversion.

    Returns:
        Dotted Lean module name.
    """
    relative = path.relative_to(lean_root).with_suffix("")
    return ".".join(relative.parts)

spec

lean/spec.py - Extract stable citation identifiers from Lean spec files.

extract_spec_ids
extract_spec_ids(spec_file: Path) -> set[str]

Extract stable citation ids from a Lean Spec file.

Parameters:

Name Type Description Default
spec_file Path

Lean Spec source file.

required

Returns:

Type Description
set[str]

Citation id string values. Missing files return an empty set.

Source code in src/se_theory_reference_kit/lean/spec.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def extract_spec_ids(spec_file: Path) -> set[str]:
    """Extract stable citation ids from a Lean Spec file.

    Args:
        spec_file: Lean Spec source file.

    Returns:
        Citation id string values. Missing files return an empty set.
    """
    if not spec_file.exists():
        return set()

    text = read_text(spec_file)
    return {match.group("value") for match in SPEC_STRING_RE.finditer(text)}
infer_spec_module
infer_spec_module(surface_module: str) -> str

Infer the Spec module from the public surface module.

Parameters:

Name Type Description Default
surface_module str

Public surface module.

required

Returns:

Type Description
str

Inferred Spec module name.

Source code in src/se_theory_reference_kit/lean/spec.py
40
41
42
43
44
45
46
47
48
49
50
51
52
def infer_spec_module(surface_module: str) -> str:
    """Infer the Spec module from the public surface module.

    Args:
        surface_module: Public surface module.

    Returns:
        Inferred Spec module name.
    """
    if surface_module.endswith(".Surface"):
        return surface_module.removesuffix(".Surface") + ".Spec"

    return surface_module + ".Spec"

surface

lean/surface.py - Compare repo-owned public surface declarations.

expected_symbols_for_kind
expected_symbols_for_kind(
    surface: SurfaceSymbols, kind: str
) -> frozenset[str]

Return expected public Lean symbols for a surface kind.

Missing kinds return an empty set. The owning theory repository supplies the surface symbols; the kit only reads the generic shape.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
kind str

Surface kind.

required

Returns:

Type Description
frozenset[str]

Expected symbols for that kind.

Source code in src/se_theory_reference_kit/lean/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def expected_symbols_for_kind(surface: SurfaceSymbols, kind: str) -> frozenset[str]:
    """Return expected public Lean symbols for a surface kind.

    Missing kinds return an empty set. The owning theory repository supplies the
    surface symbols; the kit only reads the generic shape.

    Args:
        surface: Repo-owned public surface declaration.
        kind: Surface kind.

    Returns:
        Expected symbols for that kind.
    """
    return surface.symbols_for_kind(kind)
missing_expected_surface_symbols
missing_expected_surface_symbols(
    *, surface: SurfaceSymbols, registered: set[str]
) -> set[str]

Return expected public-surface symbols missing from reference registries.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
registered set[str]

Lean symbols already registered in reference artifacts.

required

Returns:

Type Description
set[str]

Expected symbols not present in registered symbols.

Source code in src/se_theory_reference_kit/lean/surface.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def missing_expected_surface_symbols(
    *,
    surface: SurfaceSymbols,
    registered: set[str],
) -> set[str]:
    """Return expected public-surface symbols missing from reference registries.

    Args:
        surface: Repo-owned public surface declaration.
        registered: Lean symbols already registered in reference artifacts.

    Returns:
        Expected symbols not present in registered symbols.
    """
    return set(surface.all_symbols) - registered

reference

reference/init.py - Generic reference artifact tooling.

LoadedReferenceArtifact dataclass

Loaded reference artifact.

Attributes:

Name Type Description
artifact_id str

Stable artifact id from the reference index.

path Path

Resolved artifact path.

kind str

Artifact kind declared by the owning repository.

data ReferenceDocument

Parsed TOML data.

Source code in src/se_theory_reference_kit/reference/artifacts.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@dataclass(frozen=True, slots=True)
class LoadedReferenceArtifact:
    """Loaded reference artifact.

    Attributes:
        artifact_id: Stable artifact id from the reference index.
        path: Resolved artifact path.
        kind: Artifact kind declared by the owning repository.
        data: Parsed TOML data.
    """

    artifact_id: str
    path: Path
    kind: str
    data: ReferenceDocument

ReferenceRegistry dataclass

Loaded reference artifact registry.

Attributes:

Name Type Description
artifacts tuple[LoadedReferenceArtifact, ...]

Loaded reference artifacts in index order.

Source code in src/se_theory_reference_kit/reference/registry.py
25
26
27
28
29
30
31
32
33
34
35
36
37
@dataclass(frozen=True, slots=True)
class ReferenceRegistry:
    """Loaded reference artifact registry.

    Attributes:
        artifacts: Loaded reference artifacts in index order.
    """

    artifacts: tuple[LoadedReferenceArtifact, ...]

    def by_id(self) -> dict[str, LoadedReferenceArtifact]:
        """Return loaded artifacts keyed by artifact id."""
        return {artifact.artifact_id: artifact for artifact in self.artifacts}
by_id
by_id() -> dict[str, LoadedReferenceArtifact]

Return loaded artifacts keyed by artifact id.

Source code in src/se_theory_reference_kit/reference/registry.py
35
36
37
def by_id(self) -> dict[str, LoadedReferenceArtifact]:
    """Return loaded artifacts keyed by artifact id."""
    return {artifact.artifact_id: artifact for artifact in self.artifacts}

build_reference_registry

build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry

Build a registry from artifact declarations.

Parameters:

Name Type Description Default
artifact_declarations list[ArtifactDeclaration]

Artifact declarations from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
ReferenceRegistry

Loaded reference registry.

Source code in src/se_theory_reference_kit/reference/registry.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry:
    """Build a registry from artifact declarations.

    Args:
        artifact_declarations: Artifact declarations from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference registry.
    """
    loaded = tuple(
        load_reference_artifact(
            artifact,
            root=root,
            reference_dir_name=reference_dir_name,
        )
        for artifact in artifact_declarations
    )

    return ReferenceRegistry(artifacts=loaded)

discover_reference_artifacts

discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]

Discover TOML reference artifacts under the reference directory.

Parameters:

Name Type Description Default
root Path | None

Repository root.

None
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
tuple[Path, ...]

Sorted reference TOML paths.

Source code in src/se_theory_reference_kit/reference/artifacts.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]:
    """Discover TOML reference artifacts under the reference directory.

    Args:
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Sorted reference TOML paths.
    """
    root_dir = reference_dir(root=root, reference_dir_name=reference_dir_name)

    if not root_dir.exists():
        return ()

    return tuple(
        sorted(
            path
            for path in root_dir.rglob("*.toml")
            if path.is_file() and path.name != "index.toml"
        )
    )

load_reference_artifact

load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact

Load one reference artifact declared in the reference index.

Parameters:

Name Type Description Default
artifact ArtifactDeclaration

Artifact declaration from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
LoadedReferenceArtifact

Loaded reference artifact.

Raises:

Type Description
ValueError

If the declaration lacks a valid path.

Source code in src/se_theory_reference_kit/reference/artifacts.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact:
    """Load one reference artifact declared in the reference index.

    Args:
        artifact: Artifact declaration from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference artifact.

    Raises:
        ValueError: If the declaration lacks a valid path.
    """
    artifact_id = str(artifact.get("id", "<unnamed>"))
    kind = str(artifact.get("kind", ""))

    rel_path = artifact.get("path", "")
    if not isinstance(rel_path, str) or not rel_path:
        msg = f"artifact {artifact_id!r} path must be a nonempty string"
        raise ValueError(msg)

    path = reference_artifact_path(
        rel_path,
        root=root,
        reference_dir_name=reference_dir_name,
    )

    return LoadedReferenceArtifact(
        artifact_id=artifact_id,
        path=path,
        kind=kind,
        data=load_toml(path),
    )

make_stub

make_stub(
    declaration: LeanDecl, source_module: str
) -> ReferenceEntry

Create a generic reference entry stub for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required
source_module str

Source module for the declaration.

required

Returns:

Type Description
ReferenceEntry

Reference entry stub.

Source code in src/se_theory_reference_kit/reference/stubs.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def make_stub(
    declaration: LeanDecl,
    source_module: str,
) -> ReferenceEntry:
    """Create a generic reference entry stub for a Lean declaration.

    Args:
        declaration: Lean declaration.
        source_module: Source module for the declaration.

    Returns:
        Reference entry stub.
    """
    return {
        "lean_symbol": declaration.name,
        "lean_kind": declaration.kind,
        "source_module": source_module,
    }

merge_entry

merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry

Merge an existing hand-authored entry with generated fields.

Parameters:

Name Type Description Default
existing ReferenceEntry

Existing entry.

required
generated ReferenceEntry

Generated stub fields.

required
overwrite bool

If true, generated values replace existing values.

required

Returns:

Type Description
ReferenceEntry

Merged entry.

Source code in src/se_theory_reference_kit/reference/stubs.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry:
    """Merge an existing hand-authored entry with generated fields.

    Args:
        existing: Existing entry.
        generated: Generated stub fields.
        overwrite: If true, generated values replace existing values.

    Returns:
        Merged entry.
    """
    if overwrite:
        return {**existing, **generated}

    merged = dict(generated)
    merged.update(existing)
    return merged

ordered_table_values

ordered_table_values(
    document: ReferenceDocument, table_name: str
) -> list[dict[str, object]]

Return nested table values sorted by order, then id/key.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required
table_name str

Top-level table name.

required

Returns:

Type Description
list[dict[str, object]]

Ordered table entries. Each entry receives an id if missing.

Raises:

Type Description
TypeError

If the table or entries are not tables.

Source code in src/se_theory_reference_kit/reference/artifacts.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def ordered_table_values(
    document: ReferenceDocument,
    table_name: str,
) -> list[dict[str, object]]:
    """Return nested table values sorted by order, then id/key.

    Args:
        document: Parsed reference artifact.
        table_name: Top-level table name.

    Returns:
        Ordered table entries. Each entry receives an id if missing.

    Raises:
        TypeError: If the table or entries are not tables.
    """
    table = document.get(table_name, {})
    if not isinstance(table, dict):
        msg = f"Expected [{table_name}.<id>] tables"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert before iterating.
    table_map = cast("dict[str, object]", table)
    entries: list[dict[str, object]] = []

    for key, value in table_map.items():
        if not isinstance(value, dict):
            msg = f"Expected table entry for {table_name}.{key}"
            raise TypeError(msg)

        entry = dict(cast("dict[str, object]", value))
        entry.setdefault("id", str(key))
        entries.append(entry)

    return sorted(
        entries,
        key=lambda item: (
            item.get("order", 999_999),
            str(item.get("id", "")),
        ),
    )

reference_artifact_meta

reference_artifact_meta(
    document: ReferenceDocument,
) -> dict[str, object]

Return normalized metadata from a reference artifact.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
dict[str, object]

Copy of the [meta] table, or an empty dictionary when absent.

Raises:

Type Description
TypeError

If [meta] is present but not a table.

Source code in src/se_theory_reference_kit/reference/artifacts.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def reference_artifact_meta(document: ReferenceDocument) -> dict[str, object]:
    """Return normalized metadata from a reference artifact.

    Args:
        document: Parsed reference artifact.

    Returns:
        Copy of the [meta] table, or an empty dictionary when absent.

    Raises:
        TypeError: If [meta] is present but not a table.
    """
    meta = document.get("meta", {})
    if not isinstance(meta, dict):
        msg = "Expected [meta] table"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert them for the copy.
    return dict(cast("dict[str, object]", meta))

reference_stub_key

reference_stub_key(declaration: LeanDecl) -> str

Return the default reference stub key for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required

Returns:

Type Description
str

Stub key.

Source code in src/se_theory_reference_kit/reference/stubs.py
10
11
12
13
14
15
16
17
18
19
def reference_stub_key(declaration: LeanDecl) -> str:
    """Return the default reference stub key for a Lean declaration.

    Args:
        declaration: Lean declaration.

    Returns:
        Stub key.
    """
    return declaration.name

registered_lean_symbols

registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]

Return Lean symbols registered in reference artifacts.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
sections frozenset[str] | None

Optional section filter.

None

Returns:

Type Description
set[str]

Registered Lean symbol names.

Source code in src/se_theory_reference_kit/reference/registry.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]:
    """Return Lean symbols registered in reference artifacts.

    Args:
        registry: Loaded reference registry.
        sections: Optional section filter.

    Returns:
        Registered Lean symbol names.
    """
    symbols: set[str] = set()

    for artifact in registry.artifacts:
        section_names = sections if sections is not None else frozenset(artifact.data)

        for section in section_names:
            for entry in section_entries(artifact.data, section).values():
                symbol = entry.get("lean_symbol")
                if isinstance(symbol, str) and symbol:
                    symbols.add(symbol)

    return symbols

section_entries

section_entries(
    data: ReferenceDocument, section: str
) -> SectionEntries

Return table entries for a reference section.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required
section str

Section name.

required

Returns:

Type Description
SectionEntries

Section entries keyed by entry id.

Source code in src/se_theory_reference_kit/reference/registry.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def section_entries(
    data: ReferenceDocument,
    section: str,
) -> SectionEntries:
    """Return table entries for a reference section.

    Args:
        data: Parsed reference artifact.
        section: Section name.

    Returns:
        Section entries keyed by entry id.
    """
    raw_section = data.get(section, {})

    if not isinstance(raw_section, dict):
        return {}

    # WHY: isinstance narrowing collapses the value to dict[Unknown, Unknown],
    # so re-assert the parameters that pyright strict otherwise reports unknown.
    section_map = cast("dict[str, object]", raw_section)

    entries: SectionEntries = {}

    for key, value in section_map.items():
        if isinstance(value, dict):
            entries[key] = cast("dict[str, Any]", value)

    return entries

source_modules_in_registry

source_modules_in_registry(
    data: ReferenceDocument,
) -> list[str]

Return source modules declared inside a reference artifact.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
list[str]

Source module names in first-seen order.

Source code in src/se_theory_reference_kit/reference/registry.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def source_modules_in_registry(data: ReferenceDocument) -> list[str]:
    """Return source modules declared inside a reference artifact.

    Args:
        data: Parsed reference artifact.

    Returns:
        Source module names in first-seen order.
    """
    modules: list[str] = []
    seen: set[str] = set()

    top_level = data.get("source_module")
    if isinstance(top_level, str) and top_level and top_level not in seen:
        modules.append(top_level)
        seen.add(top_level)

    for value in data.values():
        if not isinstance(value, dict):
            continue

        # WHY: re-assert parameters lost by isinstance narrowing before iterating.
        section_map = cast("dict[str, object]", value)

        extract_unique_source_modules(modules, seen, section_map)

    return modules

validate_reference_artifact_shape

validate_reference_artifact_shape(
    *, check_id: str, artifact: LoadedReferenceArtifact
) -> tuple[CheckResult, ...]

Validate generic reference artifact shape.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def validate_reference_artifact_shape(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
) -> tuple[CheckResult, ...]:
    """Validate generic reference artifact shape.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.

    Returns:
        Validation findings.
    """
    if not artifact.kind:
        return (
            failure(
                check_id,
                "reference artifact declaration has no kind",
                artifact_id=artifact.artifact_id,
                path=artifact.path,
            ),
        )

    return (
        ok(
            check_id,
            "reference artifact has generic TOML shape",
            artifact_id=artifact.artifact_id,
            path=artifact.path,
        ),
    )

validate_required_fields

validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]

Validate required fields for all entries in one reference section.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required
section str

Section name.

required
required_fields Iterable[str]

Required field names.

REQUIRED_ENTRY_FIELDS

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]:
    """Validate required fields for all entries in one reference section.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.
        section: Section name.
        required_fields: Required field names.

    Returns:
        Validation findings.
    """
    findings: list[CheckResult] = []
    required = tuple(required_fields)

    for entry_id, entry in section_entries(artifact.data, section).items():
        for field_name in required:
            value = entry.get(field_name)
            if not isinstance(value, str) or not value:
                findings.append(
                    failure(
                        check_id,
                        f"{section}.{entry_id} missing required field {field_name!r}",
                        artifact_id=artifact.artifact_id,
                        path=artifact.path,
                        detail={"section": section, "entry_id": entry_id},
                    )
                )

    return tuple(findings)

artifacts

reference/artifacts.py - Reference artifact discovery and loading.

LoadedReferenceArtifact dataclass

Loaded reference artifact.

Attributes:

Name Type Description
artifact_id str

Stable artifact id from the reference index.

path Path

Resolved artifact path.

kind str

Artifact kind declared by the owning repository.

data ReferenceDocument

Parsed TOML data.

Source code in src/se_theory_reference_kit/reference/artifacts.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@dataclass(frozen=True, slots=True)
class LoadedReferenceArtifact:
    """Loaded reference artifact.

    Attributes:
        artifact_id: Stable artifact id from the reference index.
        path: Resolved artifact path.
        kind: Artifact kind declared by the owning repository.
        data: Parsed TOML data.
    """

    artifact_id: str
    path: Path
    kind: str
    data: ReferenceDocument
discover_reference_artifacts
discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]

Discover TOML reference artifacts under the reference directory.

Parameters:

Name Type Description Default
root Path | None

Repository root.

None
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
tuple[Path, ...]

Sorted reference TOML paths.

Source code in src/se_theory_reference_kit/reference/artifacts.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]:
    """Discover TOML reference artifacts under the reference directory.

    Args:
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Sorted reference TOML paths.
    """
    root_dir = reference_dir(root=root, reference_dir_name=reference_dir_name)

    if not root_dir.exists():
        return ()

    return tuple(
        sorted(
            path
            for path in root_dir.rglob("*.toml")
            if path.is_file() and path.name != "index.toml"
        )
    )
load_reference_artifact
load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact

Load one reference artifact declared in the reference index.

Parameters:

Name Type Description Default
artifact ArtifactDeclaration

Artifact declaration from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
LoadedReferenceArtifact

Loaded reference artifact.

Raises:

Type Description
ValueError

If the declaration lacks a valid path.

Source code in src/se_theory_reference_kit/reference/artifacts.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact:
    """Load one reference artifact declared in the reference index.

    Args:
        artifact: Artifact declaration from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference artifact.

    Raises:
        ValueError: If the declaration lacks a valid path.
    """
    artifact_id = str(artifact.get("id", "<unnamed>"))
    kind = str(artifact.get("kind", ""))

    rel_path = artifact.get("path", "")
    if not isinstance(rel_path, str) or not rel_path:
        msg = f"artifact {artifact_id!r} path must be a nonempty string"
        raise ValueError(msg)

    path = reference_artifact_path(
        rel_path,
        root=root,
        reference_dir_name=reference_dir_name,
    )

    return LoadedReferenceArtifact(
        artifact_id=artifact_id,
        path=path,
        kind=kind,
        data=load_toml(path),
    )
ordered_table_values
ordered_table_values(
    document: ReferenceDocument, table_name: str
) -> list[dict[str, object]]

Return nested table values sorted by order, then id/key.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required
table_name str

Top-level table name.

required

Returns:

Type Description
list[dict[str, object]]

Ordered table entries. Each entry receives an id if missing.

Raises:

Type Description
TypeError

If the table or entries are not tables.

Source code in src/se_theory_reference_kit/reference/artifacts.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def ordered_table_values(
    document: ReferenceDocument,
    table_name: str,
) -> list[dict[str, object]]:
    """Return nested table values sorted by order, then id/key.

    Args:
        document: Parsed reference artifact.
        table_name: Top-level table name.

    Returns:
        Ordered table entries. Each entry receives an id if missing.

    Raises:
        TypeError: If the table or entries are not tables.
    """
    table = document.get(table_name, {})
    if not isinstance(table, dict):
        msg = f"Expected [{table_name}.<id>] tables"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert before iterating.
    table_map = cast("dict[str, object]", table)
    entries: list[dict[str, object]] = []

    for key, value in table_map.items():
        if not isinstance(value, dict):
            msg = f"Expected table entry for {table_name}.{key}"
            raise TypeError(msg)

        entry = dict(cast("dict[str, object]", value))
        entry.setdefault("id", str(key))
        entries.append(entry)

    return sorted(
        entries,
        key=lambda item: (
            item.get("order", 999_999),
            str(item.get("id", "")),
        ),
    )
reference_artifact_meta
reference_artifact_meta(
    document: ReferenceDocument,
) -> dict[str, object]

Return normalized metadata from a reference artifact.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
dict[str, object]

Copy of the [meta] table, or an empty dictionary when absent.

Raises:

Type Description
TypeError

If [meta] is present but not a table.

Source code in src/se_theory_reference_kit/reference/artifacts.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def reference_artifact_meta(document: ReferenceDocument) -> dict[str, object]:
    """Return normalized metadata from a reference artifact.

    Args:
        document: Parsed reference artifact.

    Returns:
        Copy of the [meta] table, or an empty dictionary when absent.

    Raises:
        TypeError: If [meta] is present but not a table.
    """
    meta = document.get("meta", {})
    if not isinstance(meta, dict):
        msg = "Expected [meta] table"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert them for the copy.
    return dict(cast("dict[str, object]", meta))

registry

reference/registry.py - Reference artifact registry helpers.

ReferenceRegistry dataclass

Loaded reference artifact registry.

Attributes:

Name Type Description
artifacts tuple[LoadedReferenceArtifact, ...]

Loaded reference artifacts in index order.

Source code in src/se_theory_reference_kit/reference/registry.py
25
26
27
28
29
30
31
32
33
34
35
36
37
@dataclass(frozen=True, slots=True)
class ReferenceRegistry:
    """Loaded reference artifact registry.

    Attributes:
        artifacts: Loaded reference artifacts in index order.
    """

    artifacts: tuple[LoadedReferenceArtifact, ...]

    def by_id(self) -> dict[str, LoadedReferenceArtifact]:
        """Return loaded artifacts keyed by artifact id."""
        return {artifact.artifact_id: artifact for artifact in self.artifacts}
by_id
by_id() -> dict[str, LoadedReferenceArtifact]

Return loaded artifacts keyed by artifact id.

Source code in src/se_theory_reference_kit/reference/registry.py
35
36
37
def by_id(self) -> dict[str, LoadedReferenceArtifact]:
    """Return loaded artifacts keyed by artifact id."""
    return {artifact.artifact_id: artifact for artifact in self.artifacts}
build_reference_registry
build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry

Build a registry from artifact declarations.

Parameters:

Name Type Description Default
artifact_declarations list[ArtifactDeclaration]

Artifact declarations from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
ReferenceRegistry

Loaded reference registry.

Source code in src/se_theory_reference_kit/reference/registry.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry:
    """Build a registry from artifact declarations.

    Args:
        artifact_declarations: Artifact declarations from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference registry.
    """
    loaded = tuple(
        load_reference_artifact(
            artifact,
            root=root,
            reference_dir_name=reference_dir_name,
        )
        for artifact in artifact_declarations
    )

    return ReferenceRegistry(artifacts=loaded)
build_registry_from_config
build_registry_from_config(
    repo_root: Path, config: TheoryReferenceConfig
) -> ReferenceRegistry

Build the full reference registry from the config artifact sources.

Source code in src/se_theory_reference_kit/reference/registry.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def build_registry_from_config(
    repo_root: Path, config: TheoryReferenceConfig
) -> ReferenceRegistry:
    """Build the full reference registry from the config artifact sources."""
    declarations: list[ArtifactDeclaration] = [
        {
            "id": kind,
            "kind": kind,
            "path": source,
        }
        for kind, source in config.surface_kind_sources.items()
    ]

    return build_reference_registry(
        declarations,
        root=repo_root,
        reference_dir_name=config.reference_dir_name,
    )
build_surface_symbols
build_surface_symbols(
    repo_root: Path, config: TheoryReferenceConfig
) -> SurfaceSymbols

Derive the public surface from the mapped reference artifacts.

Source code in src/se_theory_reference_kit/reference/registry.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def build_surface_symbols(
    repo_root: Path, config: TheoryReferenceConfig
) -> SurfaceSymbols:
    """Derive the public surface from the mapped reference artifacts."""
    by_kind: dict[str, frozenset[str]] = {}

    for kind, source in config.surface_kind_sources.items():
        if kind not in SURFACE_KINDS:
            continue

        artifact_path = reference_artifact_path(
            source,
            root=repo_root,
            reference_dir_name=config.reference_dir_name,
        )
        artifact = load_toml(artifact_path)
        by_kind[kind] = frozenset(_symbol_names(artifact, kind))

    return SurfaceSymbols(by_kind=by_kind)
extract_unique_source_modules
extract_unique_source_modules(
    modules: list[str],
    seen: set[str],
    section_map: dict[str, object],
) -> None

Extract unique source modules from a section map.

Source code in src/se_theory_reference_kit/reference/registry.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def extract_unique_source_modules(
    modules: list[str], seen: set[str], section_map: dict[str, object]
) -> None:
    """Extract unique source modules from a section map."""
    for entry in section_map.values():
        if not isinstance(entry, dict):
            continue

        entry_map = cast("dict[str, object]", entry)
        source_module = entry_map.get("source_module")
        if (
            isinstance(source_module, str)
            and source_module
            and source_module not in seen
        ):
            modules.append(source_module)
            seen.add(source_module)
registered_lean_symbols
registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]

Return Lean symbols registered in reference artifacts.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
sections frozenset[str] | None

Optional section filter.

None

Returns:

Type Description
set[str]

Registered Lean symbol names.

Source code in src/se_theory_reference_kit/reference/registry.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]:
    """Return Lean symbols registered in reference artifacts.

    Args:
        registry: Loaded reference registry.
        sections: Optional section filter.

    Returns:
        Registered Lean symbol names.
    """
    symbols: set[str] = set()

    for artifact in registry.artifacts:
        section_names = sections if sections is not None else frozenset(artifact.data)

        for section in section_names:
            for entry in section_entries(artifact.data, section).values():
                symbol = entry.get("lean_symbol")
                if isinstance(symbol, str) and symbol:
                    symbols.add(symbol)

    return symbols
section_entries
section_entries(
    data: ReferenceDocument, section: str
) -> SectionEntries

Return table entries for a reference section.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required
section str

Section name.

required

Returns:

Type Description
SectionEntries

Section entries keyed by entry id.

Source code in src/se_theory_reference_kit/reference/registry.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def section_entries(
    data: ReferenceDocument,
    section: str,
) -> SectionEntries:
    """Return table entries for a reference section.

    Args:
        data: Parsed reference artifact.
        section: Section name.

    Returns:
        Section entries keyed by entry id.
    """
    raw_section = data.get(section, {})

    if not isinstance(raw_section, dict):
        return {}

    # WHY: isinstance narrowing collapses the value to dict[Unknown, Unknown],
    # so re-assert the parameters that pyright strict otherwise reports unknown.
    section_map = cast("dict[str, object]", raw_section)

    entries: SectionEntries = {}

    for key, value in section_map.items():
        if isinstance(value, dict):
            entries[key] = cast("dict[str, Any]", value)

    return entries
source_modules_in_registry
source_modules_in_registry(
    data: ReferenceDocument,
) -> list[str]

Return source modules declared inside a reference artifact.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
list[str]

Source module names in first-seen order.

Source code in src/se_theory_reference_kit/reference/registry.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def source_modules_in_registry(data: ReferenceDocument) -> list[str]:
    """Return source modules declared inside a reference artifact.

    Args:
        data: Parsed reference artifact.

    Returns:
        Source module names in first-seen order.
    """
    modules: list[str] = []
    seen: set[str] = set()

    top_level = data.get("source_module")
    if isinstance(top_level, str) and top_level and top_level not in seen:
        modules.append(top_level)
        seen.add(top_level)

    for value in data.values():
        if not isinstance(value, dict):
            continue

        # WHY: re-assert parameters lost by isinstance narrowing before iterating.
        section_map = cast("dict[str, object]", value)

        extract_unique_source_modules(modules, seen, section_map)

    return modules

stubs

reference/stubs.py - Generic reference stub construction.

make_stub
make_stub(
    declaration: LeanDecl, source_module: str
) -> ReferenceEntry

Create a generic reference entry stub for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required
source_module str

Source module for the declaration.

required

Returns:

Type Description
ReferenceEntry

Reference entry stub.

Source code in src/se_theory_reference_kit/reference/stubs.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def make_stub(
    declaration: LeanDecl,
    source_module: str,
) -> ReferenceEntry:
    """Create a generic reference entry stub for a Lean declaration.

    Args:
        declaration: Lean declaration.
        source_module: Source module for the declaration.

    Returns:
        Reference entry stub.
    """
    return {
        "lean_symbol": declaration.name,
        "lean_kind": declaration.kind,
        "source_module": source_module,
    }
merge_entry
merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry

Merge an existing hand-authored entry with generated fields.

Parameters:

Name Type Description Default
existing ReferenceEntry

Existing entry.

required
generated ReferenceEntry

Generated stub fields.

required
overwrite bool

If true, generated values replace existing values.

required

Returns:

Type Description
ReferenceEntry

Merged entry.

Source code in src/se_theory_reference_kit/reference/stubs.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry:
    """Merge an existing hand-authored entry with generated fields.

    Args:
        existing: Existing entry.
        generated: Generated stub fields.
        overwrite: If true, generated values replace existing values.

    Returns:
        Merged entry.
    """
    if overwrite:
        return {**existing, **generated}

    merged = dict(generated)
    merged.update(existing)
    return merged
reference_stub_key
reference_stub_key(declaration: LeanDecl) -> str

Return the default reference stub key for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required

Returns:

Type Description
str

Stub key.

Source code in src/se_theory_reference_kit/reference/stubs.py
10
11
12
13
14
15
16
17
18
19
def reference_stub_key(declaration: LeanDecl) -> str:
    """Return the default reference stub key for a Lean declaration.

    Args:
        declaration: Lean declaration.

    Returns:
        Stub key.
    """
    return declaration.name

validation

reference/validation.py - Generic reference artifact shape validation.

validate_reference_artifact_shape
validate_reference_artifact_shape(
    *, check_id: str, artifact: LoadedReferenceArtifact
) -> tuple[CheckResult, ...]

Validate generic reference artifact shape.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def validate_reference_artifact_shape(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
) -> tuple[CheckResult, ...]:
    """Validate generic reference artifact shape.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.

    Returns:
        Validation findings.
    """
    if not artifact.kind:
        return (
            failure(
                check_id,
                "reference artifact declaration has no kind",
                artifact_id=artifact.artifact_id,
                path=artifact.path,
            ),
        )

    return (
        ok(
            check_id,
            "reference artifact has generic TOML shape",
            artifact_id=artifact.artifact_id,
            path=artifact.path,
        ),
    )
validate_required_fields
validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]

Validate required fields for all entries in one reference section.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required
section str

Section name.

required
required_fields Iterable[str]

Required field names.

REQUIRED_ENTRY_FIELDS

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]:
    """Validate required fields for all entries in one reference section.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.
        section: Section name.
        required_fields: Required field names.

    Returns:
        Validation findings.
    """
    findings: list[CheckResult] = []
    required = tuple(required_fields)

    for entry_id, entry in section_entries(artifact.data, section).items():
        for field_name in required:
            value = entry.get(field_name)
            if not isinstance(value, str) or not value:
                findings.append(
                    failure(
                        check_id,
                        f"{section}.{entry_id} missing required field {field_name!r}",
                        artifact_id=artifact.artifact_id,
                        path=artifact.path,
                        detail={"section": section, "entry_id": entry_id},
                    )
                )

    return tuple(findings)

validation

validation/init.py - Checks, registry, runner, and default check set.

Public surface
  • Check, CheckRegistry the check contract and its catalogue
  • CheckResult, CheckStatus, ... the result vocabulary
  • RunReport, run_checks execution with crash isolation
  • default_registry, DEFAULT_CHECKS the kit's fixed generic check set

Check dataclass

A registered check: a function plus its catalogue metadata.

Attributes:

Name Type Description
check_id str

Stable, unique id.

title str

Short human-readable description for logs and reports.

run CheckFunc

The check function.

strict_only bool

When true, the check runs only in strict mode.

Source code in src/se_theory_reference_kit/validation/registry.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@dataclass(frozen=True, slots=True)
class Check:
    """A registered check: a function plus its catalogue metadata.

    Attributes:
        check_id: Stable, unique id.
        title: Short human-readable description for logs and reports.
        run: The check function.
        strict_only: When true, the check runs only in strict mode.
    """

    check_id: str
    title: str
    run: CheckFunc
    strict_only: bool = False

CheckRegistry dataclass

An immutable, ordered collection of checks.

Order is preserved so runs are deterministic and the default generic checks always precede consumer-appended checks. Ids must be unique across the registry.

Source code in src/se_theory_reference_kit/validation/registry.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@dataclass(frozen=True, slots=True)
class CheckRegistry:
    """An immutable, ordered collection of checks.

    Order is preserved so runs are deterministic and the default generic checks
    always precede consumer-appended checks. Ids must be unique across the
    registry.
    """

    checks: tuple[Check, ...] = ()

    def __post_init__(self) -> None:
        """Reject duplicate check ids at construction time."""
        seen: set[str] = set()
        duplicates: list[str] = []

        for check in self.checks:
            if check.check_id in seen:
                duplicates.append(check.check_id)
            seen.add(check.check_id)

        if duplicates:
            joined = ", ".join(sorted(set(duplicates)))
            msg = f"duplicate check ids in registry: {joined}"
            raise ValueError(msg)

    def extend(self, *checks: Check) -> Self:
        """Return a new registry with the given checks appended.

        The kit's defaults are never mutated; a consumer extends them. The
        returned registry preserves order and re-validates id uniqueness, so a
        consumer cannot shadow a default id.
        """
        return type(self)(checks=(*self.checks, *checks))

    def extended_with(self, checks: Iterable[Check]) -> Self:
        """Return a new registry appending an iterable of checks."""
        return self.extend(*tuple(checks))

    def ids(self) -> tuple[str, ...]:
        """Return the check ids in order."""
        return tuple(check.check_id for check in self.checks)

    def select(self, *, strict: bool) -> Sequence[Check]:
        """Return the checks that should run for the given mode.

        In non-strict mode, strict-only checks are skipped. In strict mode, all
        checks run.
        """
        if strict:
            return self.checks

        return tuple(check for check in self.checks if not check.strict_only)
__post_init__
__post_init__() -> None

Reject duplicate check ids at construction time.

Source code in src/se_theory_reference_kit/validation/registry.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __post_init__(self) -> None:
    """Reject duplicate check ids at construction time."""
    seen: set[str] = set()
    duplicates: list[str] = []

    for check in self.checks:
        if check.check_id in seen:
            duplicates.append(check.check_id)
        seen.add(check.check_id)

    if duplicates:
        joined = ", ".join(sorted(set(duplicates)))
        msg = f"duplicate check ids in registry: {joined}"
        raise ValueError(msg)
extend
extend(*checks: Check) -> Self

Return a new registry with the given checks appended.

The kit's defaults are never mutated; a consumer extends them. The returned registry preserves order and re-validates id uniqueness, so a consumer cannot shadow a default id.

Source code in src/se_theory_reference_kit/validation/registry.py
75
76
77
78
79
80
81
82
def extend(self, *checks: Check) -> Self:
    """Return a new registry with the given checks appended.

    The kit's defaults are never mutated; a consumer extends them. The
    returned registry preserves order and re-validates id uniqueness, so a
    consumer cannot shadow a default id.
    """
    return type(self)(checks=(*self.checks, *checks))
extended_with
extended_with(checks: Iterable[Check]) -> Self

Return a new registry appending an iterable of checks.

Source code in src/se_theory_reference_kit/validation/registry.py
84
85
86
def extended_with(self, checks: Iterable[Check]) -> Self:
    """Return a new registry appending an iterable of checks."""
    return self.extend(*tuple(checks))
ids
ids() -> tuple[str, ...]

Return the check ids in order.

Source code in src/se_theory_reference_kit/validation/registry.py
88
89
90
def ids(self) -> tuple[str, ...]:
    """Return the check ids in order."""
    return tuple(check.check_id for check in self.checks)
select
select(*, strict: bool) -> Sequence[Check]

Return the checks that should run for the given mode.

In non-strict mode, strict-only checks are skipped. In strict mode, all checks run.

Source code in src/se_theory_reference_kit/validation/registry.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def select(self, *, strict: bool) -> Sequence[Check]:
    """Return the checks that should run for the given mode.

    In non-strict mode, strict-only checks are skipped. In strict mode, all
    checks run.
    """
    if strict:
        return self.checks

    return tuple(check for check in self.checks if not check.strict_only)

CheckResult dataclass

One validation finding emitted by one check.

Attributes:

Name Type Description
check_id str

Stable id of the check that emitted the finding.

status CheckStatus

Check status.

severity CheckSeverity

Finding severity.

message str

Human-readable finding message.

artifact_id str | None

Optional artifact id associated with the finding.

path Path | None

Optional path associated with the finding.

detail JsonDetail

Optional structured detail for reports or downstream tooling.

Source code in src/se_theory_reference_kit/base/results.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass(frozen=True, slots=True)
class CheckResult:
    """One validation finding emitted by one check.

    Attributes:
        check_id: Stable id of the check that emitted the finding.
        status: Check status.
        severity: Finding severity.
        message: Human-readable finding message.
        artifact_id: Optional artifact id associated with the finding.
        path: Optional path associated with the finding.
        detail: Optional structured detail for reports or downstream tooling.
    """

    check_id: str
    status: CheckStatus
    severity: CheckSeverity
    message: str
    artifact_id: str | None = None
    path: Path | None = None
    detail: JsonDetail = field(default_factory=empty_detail)

CheckSeverity

Bases: StrEnum

Severity vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
38
39
40
41
42
43
class CheckSeverity(StrEnum):
    """Severity vocabulary for one validation finding."""

    INFO = "info"
    WARNING = "warning"
    ERROR = "error"

CheckStatus

Bases: StrEnum

Status vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
29
30
31
32
33
34
35
class CheckStatus(StrEnum):
    """Status vocabulary for one validation finding."""

    OK = "ok"
    PARTIAL = "partial"
    FAIL = "fail"
    CANNOT_VERIFY = "cannot-verify"

ReferenceRunContext dataclass

Resolved read-only context for theory-reference validation.

Source code in src/se_theory_reference_kit/validation/context.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@dataclass(frozen=True, slots=True)
class ReferenceRunContext:
    """Resolved read-only context for theory-reference validation."""

    repo_root: Path
    config: TheoryReferenceConfig
    surface: SurfaceSymbols
    export_specs: tuple[ExportSpec, ...] = ()

    @property
    def reference_root(self) -> Path:
        """Return the reference artifact directory."""
        return self.repo_root / self.config.reference_dir_name

    @property
    def generated_root(self) -> Path:
        """Return the generated data directory."""
        return self.repo_root / self.config.generated_data_dir
generated_root property
generated_root: Path

Return the generated data directory.

reference_root property
reference_root: Path

Return the reference artifact directory.

RunReport dataclass

The outcome of running a registry against a context.

Attributes:

Name Type Description
results tuple[CheckResult, ...]

Every finding from every check, in check order.

strict bool

Whether the run was executed in strict mode.

overall_status CheckStatus

Worst status across all results.

Source code in src/se_theory_reference_kit/validation/runner.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@dataclass(frozen=True, slots=True)
class RunReport:
    """The outcome of running a registry against a context.

    Attributes:
        results: Every finding from every check, in check order.
        strict: Whether the run was executed in strict mode.
        overall_status: Worst status across all results.
    """

    results: tuple[CheckResult, ...]
    strict: bool
    overall_status: CheckStatus

    @property
    def failures(self) -> tuple[CheckResult, ...]:
        """Return results that count as failures for this run's mode.

        Error-severity findings always count. Warning-severity findings count
        only under strict mode. Cannot-verify always counts.
        """
        counted: list[CheckResult] = []

        for result in self.results:
            if result.status == CheckStatus.CANNOT_VERIFY:
                counted.append(result)
                continue

            if result.status == CheckStatus.FAIL and (
                result.severity == CheckSeverity.ERROR or self.strict
            ):
                counted.append(result)

        return tuple(counted)

    @property
    def passed(self) -> bool:
        """Return true when no findings count as failures for this mode."""
        return len(self.failures) == 0

    @property
    def exit_code(self) -> int:
        """Return the process exit code: 0 when passed, 1 otherwise."""
        return EXIT_OK if self.passed else EXIT_FAILED
exit_code property
exit_code: int

Return the process exit code: 0 when passed, 1 otherwise.

failures property
failures: tuple[CheckResult, ...]

Return results that count as failures for this run's mode.

Error-severity findings always count. Warning-severity findings count only under strict mode. Cannot-verify always counts.

passed property
passed: bool

Return true when no findings count as failures for this mode.

default_registry

default_registry() -> CheckRegistry

Return the kit's default registry of generic checks.

Returns a fresh CheckRegistry each call. Consumers extend it to add repo-specific checks; the kit's defaults are never mutated.

Source code in src/se_theory_reference_kit/validation/defaults.py
54
55
56
57
58
59
60
def default_registry() -> CheckRegistry:
    """Return the kit's default registry of generic checks.

    Returns a fresh CheckRegistry each call. Consumers extend it to add
    repo-specific checks; the kit's defaults are never mutated.
    """
    return CheckRegistry(checks=DEFAULT_CHECKS)

run_checks

run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport

Run selected checks against the context with crash isolation.

Each check is executed independently. If a check raises ReferenceKitError, it is recorded as a cannot-verify result and the run continues. One broken check never hides the results of the others.

Source code in src/se_theory_reference_kit/validation/runner.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport:
    """Run selected checks against the context with crash isolation.

    Each check is executed independently. If a check raises ReferenceKitError,
    it is recorded as a cannot-verify result and the run continues. One broken
    check never hides the results of the others.
    """
    collected: list[CheckResult] = []

    for check in registry.select(strict=strict):
        try:
            collected.extend(check.run(context))
        except ReferenceKitError as exc:
            collected.append(
                cannot_verify(
                    check.check_id,
                    f"check could not run: {exc}",
                )
            )

    return RunReport(
        results=tuple(collected),
        strict=strict,
        overall_status=worst_status(collected),
    )

checks

validation/checks/init.py - Generic theory-reference validation checks.

export

validation/checks/export.py - Validate generated export freshness.

check_exports_current
check_exports_current(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify generated export artifacts are current.

Source code in src/se_theory_reference_kit/validation/checks/export.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def check_exports_current(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify generated export artifacts are current."""
    if not context.export_specs:
        return [partial(CHECK_ID, "no export specs declared")]

    registry = build_registry_from_config(context.repo_root, context.config)
    namespace = _reference_namespace(context)

    results = export_registries(
        specs=context.export_specs,
        registry=registry,
        repo_root=context.repo_root,
        reference_root=context.repo_root / context.config.reference_dir_name,
        output_root=context.repo_root / context.config.generated_data_dir,
        repo_slug=context.config.repo_slug,
        reference_namespace=namespace,
        check=True,
    )

    findings: list[CheckResult] = []
    for result in results:
        if not result.current:
            artifact_id = result.output_path.name

            findings.append(
                failure(
                    CHECK_ID,
                    "generated export artifact is stale",
                    artifact_id=artifact_id,
                    path=result.output_path,
                )
            )

    if findings:
        return findings

    return [ok(CHECK_ID, "generated export artifacts are current")]
lean_surface

validation/checks/lean_surface.py - Validate reference coverage of Lean surface.

check_lean_surface
check_lean_surface(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify expected public Lean symbols appear in reference artifacts.

Source code in src/se_theory_reference_kit/validation/checks/lean_surface.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def check_lean_surface(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify expected public Lean symbols appear in reference artifacts."""
    expected = context.surface.all_symbols
    if not expected:
        return [partial(CHECK_ID, "no public surface symbols declared")]

    registry = build_registry_from_config(context.repo_root, context.config)
    registered = registered_lean_symbols(registry)
    missing = missing_expected_surface_symbols(
        surface=context.surface,
        registered=registered,
    )

    if missing:
        return [
            failure(
                CHECK_ID,
                f"expected public Lean symbol is not registered: {symbol}",
                detail={"lean_symbol": symbol},
            )
            for symbol in sorted(missing)
        ]

    return [
        ok(
            CHECK_ID,
            f"all {len(expected)} expected public Lean symbols are registered",
        )
    ]
reference_artifacts

validation/checks/reference_artifacts.py - Validate declared reference artifacts.

check_reference_artifacts
check_reference_artifacts(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify declared reference artifacts exist, parse, and have generic shape.

Source code in src/se_theory_reference_kit/validation/checks/reference_artifacts.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def check_reference_artifacts(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify declared reference artifacts exist, parse, and have generic shape."""
    declarations = _artifact_declarations_from_context(context)
    if not declarations:
        return [partial(CHECK_ID, "no reference artifacts declared")]

    findings: list[CheckResult] = []

    for declaration in declarations:
        raw_rel_path = declaration.get("path")
        raw_artifact_id = declaration.get("id")

        artifact_id = raw_artifact_id if isinstance(raw_artifact_id, str) else None

        if not isinstance(raw_rel_path, str) or not raw_rel_path:
            findings.append(
                failure(
                    CHECK_ID,
                    "artifact declaration path must be a nonempty string",
                    artifact_id=artifact_id,
                )
            )
            continue

        path = reference_artifact_path(
            raw_rel_path,
            root=context.repo_root,
            reference_dir_name=context.config.reference_dir_name,
        )
        if not path.is_file():
            findings.append(
                failure(
                    CHECK_ID,
                    "declared reference artifact does not exist",
                    artifact_id=artifact_id,
                    path=path,
                )
            )

    if findings:
        return findings

    registry = build_reference_registry(
        declarations,
        root=context.repo_root,
        reference_dir_name=context.config.reference_dir_name,
    )

    for artifact in registry.artifacts:
        findings.extend(
            validate_reference_artifact_shape(
                check_id=CHECK_ID,
                artifact=artifact,
            )
        )

    if not findings:
        findings.append(ok(CHECK_ID, "all declared reference artifacts load"))

    return findings
strict

validation/checks/strict.py - Strict-only unfinished-work marker check.

check_strict_no_todo
check_strict_no_todo(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify reference artifacts contain no unfinished-work markers.

Source code in src/se_theory_reference_kit/validation/checks/strict.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def check_strict_no_todo(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify reference artifacts contain no unfinished-work markers."""
    findings: list[CheckResult] = []

    for artifact_id, rel_path in _configured_artifact_paths(context):
        path = reference_artifact_path(
            rel_path,
            root=context.repo_root,
            reference_dir_name=context.config.reference_dir_name,
        )
        if path.suffix.lower() not in CHECKED_SUFFIXES:
            continue

        if not path.is_file():
            continue

        markers = _markers_in_text(read_text(path))
        if markers:
            findings.append(
                failure(
                    CHECK_ID,
                    "reference artifact contains unfinished-work marker(s): "
                    + ", ".join(sorted(set(markers))),
                    artifact_id=artifact_id,
                    path=path,
                )
            )

    if not findings:
        findings.append(
            ok(CHECK_ID, "no unfinished-work markers in reference artifacts")
        )

    return findings

context

validation/context.py - Context object for theory-reference validation checks.

ReferenceRunContext dataclass

Resolved read-only context for theory-reference validation.

Source code in src/se_theory_reference_kit/validation/context.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@dataclass(frozen=True, slots=True)
class ReferenceRunContext:
    """Resolved read-only context for theory-reference validation."""

    repo_root: Path
    config: TheoryReferenceConfig
    surface: SurfaceSymbols
    export_specs: tuple[ExportSpec, ...] = ()

    @property
    def reference_root(self) -> Path:
        """Return the reference artifact directory."""
        return self.repo_root / self.config.reference_dir_name

    @property
    def generated_root(self) -> Path:
        """Return the generated data directory."""
        return self.repo_root / self.config.generated_data_dir
generated_root property
generated_root: Path

Return the generated data directory.

reference_root property
reference_root: Path

Return the reference artifact directory.

defaults

validation/defaults.py - The kit's fixed set of generic checks.

This is the single place that knows which checks the kit ships. registry.py is pure machinery and imports nothing from checks; individual checks import Check from registry. defaults.py sits above both, importing the machinery and checks to assemble the default registry. The dependency arrow is one-way:

registry  <-  checks  <-  defaults

so there is no cycle, and registry/checks can be reasoned about without knowing the default set.

Consuming repos build their own registry by extending this one:

from se_theory_reference_kit.validation.defaults import default_registry

registry = default_registry().extend(repo_specific_check)

The defaults are never edited by a consumer; extend() returns a new registry.

Default order
  1. reference.index reference/index.toml exists and parses
  2. reference.artifacts declared reference artifacts exist and parse
  3. lean.surface declared public surface is covered
  4. exports.current generated exports are current
  5. structural.strict.no-todo no unfinished-work markers (strict-only)
default_registry
default_registry() -> CheckRegistry

Return the kit's default registry of generic checks.

Returns a fresh CheckRegistry each call. Consumers extend it to add repo-specific checks; the kit's defaults are never mutated.

Source code in src/se_theory_reference_kit/validation/defaults.py
54
55
56
57
58
59
60
def default_registry() -> CheckRegistry:
    """Return the kit's default registry of generic checks.

    Returns a fresh CheckRegistry each call. Consumers extend it to add
    repo-specific checks; the kit's defaults are never mutated.
    """
    return CheckRegistry(checks=DEFAULT_CHECKS)

registry

validation/registry.py - Check registry and consumer extension hook.

The kit provides a fixed set of default generic checks. Consuming theory repositories append repo-specific checks to that set without modifying the kit. The kit's defaults are never edited by a consumer; they are extended.

This is the seam that lets one shared engine serve every theory repository without forking. Immutability enforces it: extend() returns a new registry with the added checks appended, so a consumer cannot mutate the kit's defaults in place.

Check dataclass

A registered check: a function plus its catalogue metadata.

Attributes:

Name Type Description
check_id str

Stable, unique id.

title str

Short human-readable description for logs and reports.

run CheckFunc

The check function.

strict_only bool

When true, the check runs only in strict mode.

Source code in src/se_theory_reference_kit/validation/registry.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@dataclass(frozen=True, slots=True)
class Check:
    """A registered check: a function plus its catalogue metadata.

    Attributes:
        check_id: Stable, unique id.
        title: Short human-readable description for logs and reports.
        run: The check function.
        strict_only: When true, the check runs only in strict mode.
    """

    check_id: str
    title: str
    run: CheckFunc
    strict_only: bool = False
CheckRegistry dataclass

An immutable, ordered collection of checks.

Order is preserved so runs are deterministic and the default generic checks always precede consumer-appended checks. Ids must be unique across the registry.

Source code in src/se_theory_reference_kit/validation/registry.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@dataclass(frozen=True, slots=True)
class CheckRegistry:
    """An immutable, ordered collection of checks.

    Order is preserved so runs are deterministic and the default generic checks
    always precede consumer-appended checks. Ids must be unique across the
    registry.
    """

    checks: tuple[Check, ...] = ()

    def __post_init__(self) -> None:
        """Reject duplicate check ids at construction time."""
        seen: set[str] = set()
        duplicates: list[str] = []

        for check in self.checks:
            if check.check_id in seen:
                duplicates.append(check.check_id)
            seen.add(check.check_id)

        if duplicates:
            joined = ", ".join(sorted(set(duplicates)))
            msg = f"duplicate check ids in registry: {joined}"
            raise ValueError(msg)

    def extend(self, *checks: Check) -> Self:
        """Return a new registry with the given checks appended.

        The kit's defaults are never mutated; a consumer extends them. The
        returned registry preserves order and re-validates id uniqueness, so a
        consumer cannot shadow a default id.
        """
        return type(self)(checks=(*self.checks, *checks))

    def extended_with(self, checks: Iterable[Check]) -> Self:
        """Return a new registry appending an iterable of checks."""
        return self.extend(*tuple(checks))

    def ids(self) -> tuple[str, ...]:
        """Return the check ids in order."""
        return tuple(check.check_id for check in self.checks)

    def select(self, *, strict: bool) -> Sequence[Check]:
        """Return the checks that should run for the given mode.

        In non-strict mode, strict-only checks are skipped. In strict mode, all
        checks run.
        """
        if strict:
            return self.checks

        return tuple(check for check in self.checks if not check.strict_only)
__post_init__
__post_init__() -> None

Reject duplicate check ids at construction time.

Source code in src/se_theory_reference_kit/validation/registry.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __post_init__(self) -> None:
    """Reject duplicate check ids at construction time."""
    seen: set[str] = set()
    duplicates: list[str] = []

    for check in self.checks:
        if check.check_id in seen:
            duplicates.append(check.check_id)
        seen.add(check.check_id)

    if duplicates:
        joined = ", ".join(sorted(set(duplicates)))
        msg = f"duplicate check ids in registry: {joined}"
        raise ValueError(msg)
extend
extend(*checks: Check) -> Self

Return a new registry with the given checks appended.

The kit's defaults are never mutated; a consumer extends them. The returned registry preserves order and re-validates id uniqueness, so a consumer cannot shadow a default id.

Source code in src/se_theory_reference_kit/validation/registry.py
75
76
77
78
79
80
81
82
def extend(self, *checks: Check) -> Self:
    """Return a new registry with the given checks appended.

    The kit's defaults are never mutated; a consumer extends them. The
    returned registry preserves order and re-validates id uniqueness, so a
    consumer cannot shadow a default id.
    """
    return type(self)(checks=(*self.checks, *checks))
extended_with
extended_with(checks: Iterable[Check]) -> Self

Return a new registry appending an iterable of checks.

Source code in src/se_theory_reference_kit/validation/registry.py
84
85
86
def extended_with(self, checks: Iterable[Check]) -> Self:
    """Return a new registry appending an iterable of checks."""
    return self.extend(*tuple(checks))
ids
ids() -> tuple[str, ...]

Return the check ids in order.

Source code in src/se_theory_reference_kit/validation/registry.py
88
89
90
def ids(self) -> tuple[str, ...]:
    """Return the check ids in order."""
    return tuple(check.check_id for check in self.checks)
select
select(*, strict: bool) -> Sequence[Check]

Return the checks that should run for the given mode.

In non-strict mode, strict-only checks are skipped. In strict mode, all checks run.

Source code in src/se_theory_reference_kit/validation/registry.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def select(self, *, strict: bool) -> Sequence[Check]:
    """Return the checks that should run for the given mode.

    In non-strict mode, strict-only checks are skipped. In strict mode, all
    checks run.
    """
    if strict:
        return self.checks

    return tuple(check for check in self.checks if not check.strict_only)

runner

validation/runner.py - Execute a registry with crash isolation.

The runner is the only place that knows about strict mode and overall outcome. It runs each selected check, isolates crashes, collects all results, and computes an exit code.

Strict mode is applied here, not in checks: checks report severity, and the runner decides whether warning-severity findings fail the run.

RunReport dataclass

The outcome of running a registry against a context.

Attributes:

Name Type Description
results tuple[CheckResult, ...]

Every finding from every check, in check order.

strict bool

Whether the run was executed in strict mode.

overall_status CheckStatus

Worst status across all results.

Source code in src/se_theory_reference_kit/validation/runner.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@dataclass(frozen=True, slots=True)
class RunReport:
    """The outcome of running a registry against a context.

    Attributes:
        results: Every finding from every check, in check order.
        strict: Whether the run was executed in strict mode.
        overall_status: Worst status across all results.
    """

    results: tuple[CheckResult, ...]
    strict: bool
    overall_status: CheckStatus

    @property
    def failures(self) -> tuple[CheckResult, ...]:
        """Return results that count as failures for this run's mode.

        Error-severity findings always count. Warning-severity findings count
        only under strict mode. Cannot-verify always counts.
        """
        counted: list[CheckResult] = []

        for result in self.results:
            if result.status == CheckStatus.CANNOT_VERIFY:
                counted.append(result)
                continue

            if result.status == CheckStatus.FAIL and (
                result.severity == CheckSeverity.ERROR or self.strict
            ):
                counted.append(result)

        return tuple(counted)

    @property
    def passed(self) -> bool:
        """Return true when no findings count as failures for this mode."""
        return len(self.failures) == 0

    @property
    def exit_code(self) -> int:
        """Return the process exit code: 0 when passed, 1 otherwise."""
        return EXIT_OK if self.passed else EXIT_FAILED
exit_code property
exit_code: int

Return the process exit code: 0 when passed, 1 otherwise.

failures property
failures: tuple[CheckResult, ...]

Return results that count as failures for this run's mode.

Error-severity findings always count. Warning-severity findings count only under strict mode. Cannot-verify always counts.

passed property
passed: bool

Return true when no findings count as failures for this mode.

run_checks
run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport

Run selected checks against the context with crash isolation.

Each check is executed independently. If a check raises ReferenceKitError, it is recorded as a cannot-verify result and the run continues. One broken check never hides the results of the others.

Source code in src/se_theory_reference_kit/validation/runner.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport:
    """Run selected checks against the context with crash isolation.

    Each check is executed independently. If a check raises ReferenceKitError,
    it is recorded as a cannot-verify result and the run continues. One broken
    check never hides the results of the others.
    """
    collected: list[CheckResult] = []

    for check in registry.select(strict=strict):
        try:
            collected.extend(check.run(context))
        except ReferenceKitError as exc:
            collected.append(
                cannot_verify(
                    check.check_id,
                    f"check could not run: {exc}",
                )
            )

    return RunReport(
        results=tuple(collected),
        strict=strict,
        overall_status=worst_status(collected),
    )

Base

se_theory_reference_kit.base

base/init.py - Shared base utilities for theory-reference tooling.

ArtifactLoadError

Bases: ReferenceKitError

Raised when a reference artifact cannot be loaded.

Source code in src/se_theory_reference_kit/base/errors.py
16
17
class ArtifactLoadError(ReferenceKitError):
    """Raised when a reference artifact cannot be loaded."""

CheckResult dataclass

One validation finding emitted by one check.

Attributes:

Name Type Description
check_id str

Stable id of the check that emitted the finding.

status CheckStatus

Check status.

severity CheckSeverity

Finding severity.

message str

Human-readable finding message.

artifact_id str | None

Optional artifact id associated with the finding.

path Path | None

Optional path associated with the finding.

detail JsonDetail

Optional structured detail for reports or downstream tooling.

Source code in src/se_theory_reference_kit/base/results.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass(frozen=True, slots=True)
class CheckResult:
    """One validation finding emitted by one check.

    Attributes:
        check_id: Stable id of the check that emitted the finding.
        status: Check status.
        severity: Finding severity.
        message: Human-readable finding message.
        artifact_id: Optional artifact id associated with the finding.
        path: Optional path associated with the finding.
        detail: Optional structured detail for reports or downstream tooling.
    """

    check_id: str
    status: CheckStatus
    severity: CheckSeverity
    message: str
    artifact_id: str | None = None
    path: Path | None = None
    detail: JsonDetail = field(default_factory=empty_detail)

CheckSeverity

Bases: StrEnum

Severity vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
38
39
40
41
42
43
class CheckSeverity(StrEnum):
    """Severity vocabulary for one validation finding."""

    INFO = "info"
    WARNING = "warning"
    ERROR = "error"

CheckStatus

Bases: StrEnum

Status vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
29
30
31
32
33
34
35
class CheckStatus(StrEnum):
    """Status vocabulary for one validation finding."""

    OK = "ok"
    PARTIAL = "partial"
    FAIL = "fail"
    CANNOT_VERIFY = "cannot-verify"

ConfigurationError

Bases: ReferenceKitError

Raised when repo-provided reference configuration is invalid.

Source code in src/se_theory_reference_kit/base/errors.py
12
13
class ConfigurationError(ReferenceKitError):
    """Raised when repo-provided reference configuration is invalid."""

ReferenceKitError

Bases: Exception

Base exception for theory-reference-kit failures.

Source code in src/se_theory_reference_kit/base/errors.py
4
5
class ReferenceKitError(Exception):
    """Base exception for theory-reference-kit failures."""

RepositoryRootError

Bases: ReferenceKitError

Raised when a repository root cannot be resolved.

Source code in src/se_theory_reference_kit/base/errors.py
8
9
class RepositoryRootError(ReferenceKitError):
    """Raised when a repository root cannot be resolved."""

cannot_verify

cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a cannot-verify result.

Source code in src/se_theory_reference_kit/base/results.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a cannot-verify result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.CANNOT_VERIFY,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

failure

failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an error failure result.

Source code in src/se_theory_reference_kit/base/results.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an error failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

find_repository_root

find_repository_root(start: Path | None = None) -> Path

Find the nearest repository root from a starting path.

Parameters:

Name Type Description Default
start Path | None

Starting path. Defaults to the current working directory.

None

Returns:

Type Description
Path

Resolved repository root path.

Raises:

Type Description
RepositoryRootError

If no repository root marker is found.

Source code in src/se_theory_reference_kit/base/paths.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def find_repository_root(start: Path | None = None) -> Path:
    """Find the nearest repository root from a starting path.

    Args:
        start: Starting path. Defaults to the current working directory.

    Returns:
        Resolved repository root path.

    Raises:
        RepositoryRootError: If no repository root marker is found.
    """
    current = (start or Path.cwd()).resolve()

    if current.is_file():
        current = current.parent

    for candidate in (current, *current.parents):
        if any((candidate / marker).exists() for marker in ROOT_MARKERS):
            return candidate

    msg = f"Could not resolve repository root from {current}"
    raise RepositoryRootError(msg)

lean_module_to_path

lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path

Resolve a Lean module name to its repository source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required
root Path | None

Repository root.

None
lean_public_root str

Expected public Lean root for the owning repository.

required

Returns:

Type Description
Path

Repository-contained Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, path-like, malformed, or outside the declared public Lean root.

Source code in src/se_theory_reference_kit/base/paths.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path:
    """Resolve a Lean module name to its repository source path.

    Args:
        module: Lean module name.
        root: Repository root.
        lean_public_root: Expected public Lean root for the owning repository.

    Returns:
        Repository-contained Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, path-like, malformed,
            or outside the declared public Lean root.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    if module_name != lean_public_root and not module_name.startswith(
        f"{lean_public_root}."
    ):
        msg = f"Expected Lean module under {lean_public_root}, got: {module_name}"
        raise PathResolutionError(msg)

    relative_path = Path(*parts).with_suffix(".lean")
    return resolve_repo_path(relative_path, root=root)

ok

ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an ok result.

Source code in src/se_theory_reference_kit/base/results.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an ok result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.OK,
        severity=CheckSeverity.INFO,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

partial

partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a partial result.

Source code in src/se_theory_reference_kit/base/results.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a partial result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.PARTIAL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

reference_artifact_path

reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Resolve a declared reference artifact path.

The declared path must be repository-relative and under the reference directory.

Parameters:

Name Type Description Default
path str | Path

Declared repository-relative artifact path.

required
root Path | None

Repository root.

None
reference_dir_name str

Name of the reference artifact directory.

'reference'

Returns:

Type Description
Path

Resolved reference artifact path.

Raises:

Type Description
PathResolutionError

If the path is outside the reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Resolve a declared reference artifact path.

    The declared path must be repository-relative and under the reference
    directory.

    Args:
        path: Declared repository-relative artifact path.
        root: Repository root.
        reference_dir_name: Name of the reference artifact directory.

    Returns:
        Resolved reference artifact path.

    Raises:
        PathResolutionError: If the path is outside the reference directory.
    """
    resolved = resolve_repo_path(path, root=root)
    reference_root = reference_dir(
        root=root,
        reference_dir_name=reference_dir_name,
    ).resolve()

    try:
        resolved.relative_to(reference_root)
    except ValueError as exc:
        msg = f"Reference artifact path is not under {reference_dir_name}/: {path}"
        raise PathResolutionError(msg) from exc

    return resolved

reference_dir

reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Return the repository reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
63
64
65
66
67
68
69
def reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Return the repository reference directory."""
    return resolve_repo_path(reference_dir_name, root=root)

resolve_repo_path

resolve_repo_path(
    path: str | Path, *, root: Path | None = None
) -> Path

Resolve a path as repository-relative and contained within the repository.

Parameters:

Name Type Description Default
path str | Path

Repository-relative path.

required
root Path | None

Repository root. Defaults to nearest detected repository root.

None

Returns:

Type Description
Path

Resolved absolute path.

Raises:

Type Description
PathResolutionError

If the path escapes the repository root.

Source code in src/se_theory_reference_kit/base/paths.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def resolve_repo_path(path: str | Path, *, root: Path | None = None) -> Path:
    """Resolve a path as repository-relative and contained within the repository.

    Args:
        path: Repository-relative path.
        root: Repository root. Defaults to nearest detected repository root.

    Returns:
        Resolved absolute path.

    Raises:
        PathResolutionError: If the path escapes the repository root.
    """
    repo_root = find_repository_root(root)
    resolved = (repo_root / path).resolve()

    try:
        resolved.relative_to(repo_root)
    except ValueError as exc:
        msg = f"Path escapes repository root: {path}"
        raise PathResolutionError(msg) from exc

    return resolved

warning

warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a warning failure result.

Source code in src/se_theory_reference_kit/base/results.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a warning failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

worst_status

worst_status(results: Iterable[CheckResult]) -> CheckStatus

Return the worst status across validation results.

Source code in src/se_theory_reference_kit/base/results.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def worst_status(results: Iterable[CheckResult]) -> CheckStatus:
    """Return the worst status across validation results."""
    rank = {
        CheckStatus.OK: 0,
        CheckStatus.PARTIAL: 1,
        CheckStatus.FAIL: 2,
        CheckStatus.CANNOT_VERIFY: 3,
    }

    worst = CheckStatus.OK
    for result in results:
        if rank[result.status] > rank[worst]:
            worst = result.status

    return worst

errors

base/errors.py - Exception types for theory-reference tooling.

ArtifactLoadError

Bases: ReferenceKitError

Raised when a reference artifact cannot be loaded.

Source code in src/se_theory_reference_kit/base/errors.py
16
17
class ArtifactLoadError(ReferenceKitError):
    """Raised when a reference artifact cannot be loaded."""

ArtifactWriteError

Bases: ReferenceKitError

Raised when a reference artifact cannot be written.

Source code in src/se_theory_reference_kit/base/errors.py
20
21
class ArtifactWriteError(ReferenceKitError):
    """Raised when a reference artifact cannot be written."""

ConfigurationError

Bases: ReferenceKitError

Raised when repo-provided reference configuration is invalid.

Source code in src/se_theory_reference_kit/base/errors.py
12
13
class ConfigurationError(ReferenceKitError):
    """Raised when repo-provided reference configuration is invalid."""

PathResolutionError

Bases: ReferenceKitError

Raised when a repository-relative path is invalid.

Source code in src/se_theory_reference_kit/base/errors.py
24
25
class PathResolutionError(ReferenceKitError):
    """Raised when a repository-relative path is invalid."""

ReferenceKitError

Bases: Exception

Base exception for theory-reference-kit failures.

Source code in src/se_theory_reference_kit/base/errors.py
4
5
class ReferenceKitError(Exception):
    """Base exception for theory-reference-kit failures."""

RepositoryRootError

Bases: ReferenceKitError

Raised when a repository root cannot be resolved.

Source code in src/se_theory_reference_kit/base/errors.py
8
9
class RepositoryRootError(ReferenceKitError):
    """Raised when a repository root cannot be resolved."""

io

base/io.py - UTF-8 text and TOML loading helpers.

load_toml

load_toml(path: Path) -> TomlDocument

Load a TOML file.

Parameters:

Name Type Description Default
path Path

TOML file path.

required

Returns:

Type Description
TomlDocument

Parsed TOML document.

Raises:

Type Description
ArtifactLoadError

If the file cannot be read or parsed.

Source code in src/se_theory_reference_kit/base/io.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def load_toml(path: Path) -> TomlDocument:
    """Load a TOML file.

    Args:
        path: TOML file path.

    Returns:
        Parsed TOML document.

    Raises:
        ArtifactLoadError: If the file cannot be read or parsed.
    """
    try:
        with path.open("rb") as file_obj:
            data = tomllib.load(file_obj)
    except (OSError, tomllib.TOMLDecodeError) as exc:
        msg = f"Unable to read TOML file: {path}"
        raise ArtifactLoadError(msg) from exc

    return data

read_text

read_text(path: Path) -> str

Read a UTF-8 text file.

Parameters:

Name Type Description Default
path Path

File path.

required

Returns:

Type Description
str

File contents.

Raises:

Type Description
ArtifactLoadError

If the file cannot be read.

Source code in src/se_theory_reference_kit/base/io.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def read_text(path: Path) -> str:
    """Read a UTF-8 text file.

    Args:
        path: File path.

    Returns:
        File contents.

    Raises:
        ArtifactLoadError: If the file cannot be read.
    """
    try:
        return path.read_text(encoding="utf-8")
    except OSError as exc:
        msg = f"Unable to read text file: {path}"
        raise ArtifactLoadError(msg) from exc

write_text

write_text(path: Path, content: str) -> None

Write a UTF-8 text file, creating parent directories if needed.

Parameters:

Name Type Description Default
path Path

Output path.

required
content str

Text content.

required

Raises:

Type Description
ArtifactWriteError

If the file cannot be written.

Source code in src/se_theory_reference_kit/base/io.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def write_text(path: Path, content: str) -> None:
    """Write a UTF-8 text file, creating parent directories if needed.

    Args:
        path: Output path.
        content: Text content.

    Raises:
        ArtifactWriteError: If the file cannot be written.
    """
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content, encoding="utf-8")
    except OSError as exc:
        msg = f"Unable to write text file: {path}"
        raise ArtifactWriteError(msg) from exc

json_utils

base/json_utils.py - Deterministic JSON helpers.

encode_json

encode_json(payload: JsonObject) -> str

Encode a JSON payload deterministically.

The payload builder owns ordering. This encoder preserves insertion order rather than sorting keys.

Parameters:

Name Type Description Default
payload JsonObject

JSON-compatible object.

required

Returns:

Type Description
str

Encoded JSON text ending with a newline.

Source code in src/se_theory_reference_kit/base/json_utils.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def encode_json(payload: JsonObject) -> str:
    """Encode a JSON payload deterministically.

    The payload builder owns ordering. This encoder preserves insertion order
    rather than sorting keys.

    Args:
        payload: JSON-compatible object.

    Returns:
        Encoded JSON text ending with a newline.
    """
    return (
        json.dumps(
            payload,
            indent=2,
            sort_keys=False,
            ensure_ascii=True,
        )
        + "\n"
    )

write_or_check_json

write_or_check_json(
    path: Path, payload: JsonObject, *, check: bool
) -> bool

Write a JSON payload or check whether the file is current.

Parameters:

Name Type Description Default
path Path

Output path.

required
payload JsonObject

JSON payload.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
bool

True when current or written, otherwise false.

Source code in src/se_theory_reference_kit/base/json_utils.py
67
68
69
70
71
72
73
74
75
76
77
78
def write_or_check_json(path: Path, payload: JsonObject, *, check: bool) -> bool:
    """Write a JSON payload or check whether the file is current.

    Args:
        path: Output path.
        payload: JSON payload.
        check: If true, check freshness without writing.

    Returns:
        True when current or written, otherwise false.
    """
    return write_or_check_text(path, encode_json(payload), check=check)

write_or_check_text

write_or_check_text(
    path: Path, content: str, *, check: bool
) -> bool

Write a file or check whether it is current.

Returns true when the file is current or was written. Returns false when check mode finds stale content.

Parameters:

Name Type Description Default
path Path

Output path.

required
content str

Expected file content.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
bool

True when current or written, otherwise false.

Source code in src/se_theory_reference_kit/base/json_utils.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def write_or_check_text(path: Path, content: str, *, check: bool) -> bool:
    """Write a file or check whether it is current.

    Returns true when the file is current or was written.
    Returns false when check mode finds stale content.

    Args:
        path: Output path.
        content: Expected file content.
        check: If true, check freshness without writing.

    Returns:
        True when current or written, otherwise false.
    """
    if check:
        if not path.exists():
            print(f"[stale] {path.as_posix()} is missing")
            return False

        current = path.read_text(encoding="utf-8")
        if current != content:
            print(f"[stale] {path.as_posix()} is out of date")
            return False

        print(f"[ok   ] {path.as_posix()}")
        return True

    write_text(path, content)
    print(f"[write] {path.as_posix()}")
    return True

paths

base/paths.py - Repository-relative path helpers.

find_repository_root

find_repository_root(start: Path | None = None) -> Path

Find the nearest repository root from a starting path.

Parameters:

Name Type Description Default
start Path | None

Starting path. Defaults to the current working directory.

None

Returns:

Type Description
Path

Resolved repository root path.

Raises:

Type Description
RepositoryRootError

If no repository root marker is found.

Source code in src/se_theory_reference_kit/base/paths.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def find_repository_root(start: Path | None = None) -> Path:
    """Find the nearest repository root from a starting path.

    Args:
        start: Starting path. Defaults to the current working directory.

    Returns:
        Resolved repository root path.

    Raises:
        RepositoryRootError: If no repository root marker is found.
    """
    current = (start or Path.cwd()).resolve()

    if current.is_file():
        current = current.parent

    for candidate in (current, *current.parents):
        if any((candidate / marker).exists() for marker in ROOT_MARKERS):
            return candidate

    msg = f"Could not resolve repository root from {current}"
    raise RepositoryRootError(msg)

lean_module_to_path

lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path

Resolve a Lean module name to its repository source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required
root Path | None

Repository root.

None
lean_public_root str

Expected public Lean root for the owning repository.

required

Returns:

Type Description
Path

Repository-contained Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, path-like, malformed, or outside the declared public Lean root.

Source code in src/se_theory_reference_kit/base/paths.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def lean_module_to_path(
    module: str,
    *,
    root: Path | None = None,
    lean_public_root: str,
) -> Path:
    """Resolve a Lean module name to its repository source path.

    Args:
        module: Lean module name.
        root: Repository root.
        lean_public_root: Expected public Lean root for the owning repository.

    Returns:
        Repository-contained Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, path-like, malformed,
            or outside the declared public Lean root.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    if module_name != lean_public_root and not module_name.startswith(
        f"{lean_public_root}."
    ):
        msg = f"Expected Lean module under {lean_public_root}, got: {module_name}"
        raise PathResolutionError(msg)

    relative_path = Path(*parts).with_suffix(".lean")
    return resolve_repo_path(relative_path, root=root)

reference_artifact_path

reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Resolve a declared reference artifact path.

The declared path must be repository-relative and under the reference directory.

Parameters:

Name Type Description Default
path str | Path

Declared repository-relative artifact path.

required
root Path | None

Repository root.

None
reference_dir_name str

Name of the reference artifact directory.

'reference'

Returns:

Type Description
Path

Resolved reference artifact path.

Raises:

Type Description
PathResolutionError

If the path is outside the reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def reference_artifact_path(
    path: str | Path,
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Resolve a declared reference artifact path.

    The declared path must be repository-relative and under the reference
    directory.

    Args:
        path: Declared repository-relative artifact path.
        root: Repository root.
        reference_dir_name: Name of the reference artifact directory.

    Returns:
        Resolved reference artifact path.

    Raises:
        PathResolutionError: If the path is outside the reference directory.
    """
    resolved = resolve_repo_path(path, root=root)
    reference_root = reference_dir(
        root=root,
        reference_dir_name=reference_dir_name,
    ).resolve()

    try:
        resolved.relative_to(reference_root)
    except ValueError as exc:
        msg = f"Reference artifact path is not under {reference_dir_name}/: {path}"
        raise PathResolutionError(msg) from exc

    return resolved

reference_dir

reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path

Return the repository reference directory.

Source code in src/se_theory_reference_kit/base/paths.py
63
64
65
66
67
68
69
def reference_dir(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> Path:
    """Return the repository reference directory."""
    return resolve_repo_path(reference_dir_name, root=root)

repo_relative_path

repo_relative_path(path: Path, repo_root: Path) -> str

Return a repository-relative POSIX path.

Source code in src/se_theory_reference_kit/base/paths.py
155
156
157
def repo_relative_path(path: Path, repo_root: Path) -> str:
    """Return a repository-relative POSIX path."""
    return path.resolve().relative_to(repo_root.resolve()).as_posix()

resolve_repo_path

resolve_repo_path(
    path: str | Path, *, root: Path | None = None
) -> Path

Resolve a path as repository-relative and contained within the repository.

Parameters:

Name Type Description Default
path str | Path

Repository-relative path.

required
root Path | None

Repository root. Defaults to nearest detected repository root.

None

Returns:

Type Description
Path

Resolved absolute path.

Raises:

Type Description
PathResolutionError

If the path escapes the repository root.

Source code in src/se_theory_reference_kit/base/paths.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def resolve_repo_path(path: str | Path, *, root: Path | None = None) -> Path:
    """Resolve a path as repository-relative and contained within the repository.

    Args:
        path: Repository-relative path.
        root: Repository root. Defaults to nearest detected repository root.

    Returns:
        Resolved absolute path.

    Raises:
        PathResolutionError: If the path escapes the repository root.
    """
    repo_root = find_repository_root(root)
    resolved = (repo_root / path).resolve()

    try:
        resolved.relative_to(repo_root)
    except ValueError as exc:
        msg = f"Path escapes repository root: {path}"
        raise PathResolutionError(msg) from exc

    return resolved

results

validation/results.py - Result vocabulary for theory-reference checks.

CheckResult dataclass

One validation finding emitted by one check.

Attributes:

Name Type Description
check_id str

Stable id of the check that emitted the finding.

status CheckStatus

Check status.

severity CheckSeverity

Finding severity.

message str

Human-readable finding message.

artifact_id str | None

Optional artifact id associated with the finding.

path Path | None

Optional path associated with the finding.

detail JsonDetail

Optional structured detail for reports or downstream tooling.

Source code in src/se_theory_reference_kit/base/results.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass(frozen=True, slots=True)
class CheckResult:
    """One validation finding emitted by one check.

    Attributes:
        check_id: Stable id of the check that emitted the finding.
        status: Check status.
        severity: Finding severity.
        message: Human-readable finding message.
        artifact_id: Optional artifact id associated with the finding.
        path: Optional path associated with the finding.
        detail: Optional structured detail for reports or downstream tooling.
    """

    check_id: str
    status: CheckStatus
    severity: CheckSeverity
    message: str
    artifact_id: str | None = None
    path: Path | None = None
    detail: JsonDetail = field(default_factory=empty_detail)

CheckSeverity

Bases: StrEnum

Severity vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
38
39
40
41
42
43
class CheckSeverity(StrEnum):
    """Severity vocabulary for one validation finding."""

    INFO = "info"
    WARNING = "warning"
    ERROR = "error"

CheckStatus

Bases: StrEnum

Status vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
29
30
31
32
33
34
35
class CheckStatus(StrEnum):
    """Status vocabulary for one validation finding."""

    OK = "ok"
    PARTIAL = "partial"
    FAIL = "fail"
    CANNOT_VERIFY = "cannot-verify"

cannot_verify

cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a cannot-verify result.

Source code in src/se_theory_reference_kit/base/results.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def cannot_verify(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a cannot-verify result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.CANNOT_VERIFY,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

empty_detail

empty_detail() -> JsonDetail

Return an empty result detail dictionary.

Source code in src/se_theory_reference_kit/base/results.py
24
25
26
def empty_detail() -> JsonDetail:
    """Return an empty result detail dictionary."""
    return {}

failure

failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an error failure result.

Source code in src/se_theory_reference_kit/base/results.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def failure(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an error failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.ERROR,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

ok

ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create an ok result.

Source code in src/se_theory_reference_kit/base/results.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def ok(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create an ok result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.OK,
        severity=CheckSeverity.INFO,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

partial

partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a partial result.

Source code in src/se_theory_reference_kit/base/results.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def partial(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a partial result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.PARTIAL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

warning

warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult

Create a warning failure result.

Source code in src/se_theory_reference_kit/base/results.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def warning(
    check_id: str,
    message: str,
    *,
    artifact_id: str | None = None,
    path: Path | None = None,
    detail: JsonDetail | None = None,
) -> CheckResult:
    """Create a warning failure result."""
    return CheckResult(
        check_id=check_id,
        status=CheckStatus.FAIL,
        severity=CheckSeverity.WARNING,
        message=message,
        artifact_id=artifact_id,
        path=path,
        detail={} if detail is None else detail,
    )

worst_status

worst_status(results: Iterable[CheckResult]) -> CheckStatus

Return the worst status across validation results.

Source code in src/se_theory_reference_kit/base/results.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def worst_status(results: Iterable[CheckResult]) -> CheckStatus:
    """Return the worst status across validation results."""
    rank = {
        CheckStatus.OK: 0,
        CheckStatus.PARTIAL: 1,
        CheckStatus.FAIL: 2,
        CheckStatus.CANNOT_VERIFY: 3,
    }

    worst = CheckStatus.OK
    for result in results:
        if rank[result.status] > rank[worst]:
            worst = result.status

    return worst

Declarations

se_theory_reference_kit.declarations

declarations/init.py - Typed declarations consumed by the generic engine.

ExportSpec dataclass

A generated JSON artifact export specification.

Source code in src/se_theory_reference_kit/declarations/export_spec.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class ExportSpec:
    """A generated JSON artifact export specification."""

    source_name: str
    source_table: str
    output_name: str
    schema: str
    payload_key: str

    @classmethod
    def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
        """Build export specs by joining [surface_kinds] and [export_map].

        Kit-owned convention for each non-catalog kind present in both maps:
            source_table = kind
            payload_key  = kind
            schema       = f"se-theory-{artifact_slug}-{kind}-registry"
        """
        repository = _section(data, "repository")
        surface_kinds = _string_mapping(data, "surface_kinds")
        export_map = _string_mapping(data, "export_map")

        slug = repository.get("theory")
        if not isinstance(slug, str) or not slug:
            return ()

        specs: list[Self] = []

        for kind, source in surface_kinds.items():
            output = export_map.get(kind)
            if output is None:
                continue

            specs.append(
                cls(
                    source_name=Path(source).name,
                    source_table=kind,
                    output_name=Path(output).name,
                    schema=f"se-theory-{slug}-{kind}-registry",
                    payload_key=kind,
                )
            )

        return tuple(specs)

specs_from_toml classmethod

specs_from_toml(
    data: Mapping[str, object],
) -> tuple[Self, ...]

Build export specs by joining [surface_kinds] and [export_map].

Kit-owned convention for each non-catalog kind present in both maps

source_table = kind payload_key = kind schema = f"se-theory-{artifact_slug}-{kind}-registry"

Source code in src/se_theory_reference_kit/declarations/export_spec.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
    """Build export specs by joining [surface_kinds] and [export_map].

    Kit-owned convention for each non-catalog kind present in both maps:
        source_table = kind
        payload_key  = kind
        schema       = f"se-theory-{artifact_slug}-{kind}-registry"
    """
    repository = _section(data, "repository")
    surface_kinds = _string_mapping(data, "surface_kinds")
    export_map = _string_mapping(data, "export_map")

    slug = repository.get("theory")
    if not isinstance(slug, str) or not slug:
        return ()

    specs: list[Self] = []

    for kind, source in surface_kinds.items():
        output = export_map.get(kind)
        if output is None:
            continue

        specs.append(
            cls(
                source_name=Path(source).name,
                source_table=kind,
                output_name=Path(output).name,
                schema=f"se-theory-{slug}-{kind}-registry",
                payload_key=kind,
            )
        )

    return tuple(specs)

SurfaceSymbols dataclass

Kinded public Lean surface symbols for one theory repository.

Source code in src/se_theory_reference_kit/declarations/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class SurfaceSymbols:
    """Kinded public Lean surface symbols for one theory repository."""

    by_kind: Mapping[str, frozenset[str]] = field(
        default_factory=lambda: EMPTY_SURFACE_MAP
    )

    def symbols_for_kind(self, kind: str) -> frozenset[str]:
        """Return public symbols for one surface kind."""
        return self.by_kind.get(kind, EMPTY_STRING_SET)

    @property
    def all_symbols(self) -> frozenset[str]:
        """Return all declared public surface symbols."""
        return frozenset(
            symbol for symbols in self.by_kind.values() for symbol in symbols
        )

    @classmethod
    def from_optional_kinds(
        cls,
        *,
        types: frozenset[str] = EMPTY_STRING_SET,
        predicates: frozenset[str] = EMPTY_STRING_SET,
        axioms: frozenset[str] = EMPTY_STRING_SET,
        theorems: frozenset[str] = EMPTY_STRING_SET,
        requirements: frozenset[str] = EMPTY_STRING_SET,
        vocabulary: frozenset[str] = EMPTY_STRING_SET,
        witnesses: frozenset[str] = EMPTY_STRING_SET,
    ) -> Self:
        """Build a surface declaration from common optional surface kinds."""
        return cls(
            by_kind={
                "type": types,
                "predicate": predicates,
                "axiom": axioms,
                "theorem": theorems,
                "requirement": requirements,
                "vocabulary": vocabulary,
                "witness": witnesses,
            }
        )

all_symbols property

all_symbols: frozenset[str]

Return all declared public surface symbols.

from_optional_kinds classmethod

from_optional_kinds(
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self

Build a surface declaration from common optional surface kinds.

Source code in src/se_theory_reference_kit/declarations/surface.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def from_optional_kinds(
    cls,
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self:
    """Build a surface declaration from common optional surface kinds."""
    return cls(
        by_kind={
            "type": types,
            "predicate": predicates,
            "axiom": axioms,
            "theorem": theorems,
            "requirement": requirements,
            "vocabulary": vocabulary,
            "witness": witnesses,
        }
    )

symbols_for_kind

symbols_for_kind(kind: str) -> frozenset[str]

Return public symbols for one surface kind.

Source code in src/se_theory_reference_kit/declarations/surface.py
19
20
21
def symbols_for_kind(self, kind: str) -> frozenset[str]:
    """Return public symbols for one surface kind."""
    return self.by_kind.get(kind, EMPTY_STRING_SET)

TheoryReferenceConfig dataclass

Repository-specific configuration consumed by the generic engine.

Source code in src/se_theory_reference_kit/declarations/config.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass(frozen=True, slots=True)
class TheoryReferenceConfig:
    """Repository-specific configuration consumed by the generic engine."""

    repo_slug: str
    artifact_slug: str
    lean_public_root: str
    reference_dir_name: str = "reference"
    generated_data_dir: Path | str = "data"
    reference_namespace: str | None = None
    catalog_artifact_name: str | None = None
    catalog_schema: str | None = None
    surface_kind_sources: Mapping[str, str] = field(
        default_factory=lambda: EMPTY_SOURCE_MAP
    )
    strict_warning_exemptions: frozenset[str] = field(
        default_factory=lambda: EMPTY_STRING_SET
    )

    @classmethod
    def from_toml(cls, data: Mapping[str, object]) -> Self:
        """Build configuration from a parsed theory-reference.toml mapping."""
        repository = _section(data, "repository")
        lean = _section(data, "lean")
        reference = _section(data, "reference")
        export = _section(data, "export")
        export_map = _string_mapping(data, "export_map")
        surface_kinds = _string_mapping(data, "surface_kinds")
        strict = _section(data, "strict")

        artifact_slug = _require_str(repository, "theory", "repository.theory")
        catalog_path = export_map.get("catalog")
        catalog_artifact = Path(catalog_path).stem if catalog_path else None
        catalog_schema = _opt_str(export.get("catalog_schema")) or (
            f"se-theory-{artifact_slug}-catalog"
        )

        return cls(
            repo_slug=_require_str(repository, "name", "repository.name"),
            artifact_slug=artifact_slug,
            lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
            reference_dir_name=_str(reference.get("root"), "reference"),
            generated_data_dir=_str(export.get("root"), "data"),
            reference_namespace=_opt_str(lean.get("namespace")),
            catalog_artifact_name=catalog_artifact,
            catalog_schema=catalog_schema,
            surface_kind_sources=surface_kinds,
            strict_warning_exemptions=frozenset(
                _string_list(strict, "warning_exemptions")
            ),
        )

from_toml classmethod

from_toml(data: Mapping[str, object]) -> Self

Build configuration from a parsed theory-reference.toml mapping.

Source code in src/se_theory_reference_kit/declarations/config.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@classmethod
def from_toml(cls, data: Mapping[str, object]) -> Self:
    """Build configuration from a parsed theory-reference.toml mapping."""
    repository = _section(data, "repository")
    lean = _section(data, "lean")
    reference = _section(data, "reference")
    export = _section(data, "export")
    export_map = _string_mapping(data, "export_map")
    surface_kinds = _string_mapping(data, "surface_kinds")
    strict = _section(data, "strict")

    artifact_slug = _require_str(repository, "theory", "repository.theory")
    catalog_path = export_map.get("catalog")
    catalog_artifact = Path(catalog_path).stem if catalog_path else None
    catalog_schema = _opt_str(export.get("catalog_schema")) or (
        f"se-theory-{artifact_slug}-catalog"
    )

    return cls(
        repo_slug=_require_str(repository, "name", "repository.name"),
        artifact_slug=artifact_slug,
        lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
        reference_dir_name=_str(reference.get("root"), "reference"),
        generated_data_dir=_str(export.get("root"), "data"),
        reference_namespace=_opt_str(lean.get("namespace")),
        catalog_artifact_name=catalog_artifact,
        catalog_schema=catalog_schema,
        surface_kind_sources=surface_kinds,
        strict_warning_exemptions=frozenset(
            _string_list(strict, "warning_exemptions")
        ),
    )

config

declarations/config.py - Repository-specific configuration model.

TheoryReferenceConfig dataclass

Repository-specific configuration consumed by the generic engine.

Source code in src/se_theory_reference_kit/declarations/config.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@dataclass(frozen=True, slots=True)
class TheoryReferenceConfig:
    """Repository-specific configuration consumed by the generic engine."""

    repo_slug: str
    artifact_slug: str
    lean_public_root: str
    reference_dir_name: str = "reference"
    generated_data_dir: Path | str = "data"
    reference_namespace: str | None = None
    catalog_artifact_name: str | None = None
    catalog_schema: str | None = None
    surface_kind_sources: Mapping[str, str] = field(
        default_factory=lambda: EMPTY_SOURCE_MAP
    )
    strict_warning_exemptions: frozenset[str] = field(
        default_factory=lambda: EMPTY_STRING_SET
    )

    @classmethod
    def from_toml(cls, data: Mapping[str, object]) -> Self:
        """Build configuration from a parsed theory-reference.toml mapping."""
        repository = _section(data, "repository")
        lean = _section(data, "lean")
        reference = _section(data, "reference")
        export = _section(data, "export")
        export_map = _string_mapping(data, "export_map")
        surface_kinds = _string_mapping(data, "surface_kinds")
        strict = _section(data, "strict")

        artifact_slug = _require_str(repository, "theory", "repository.theory")
        catalog_path = export_map.get("catalog")
        catalog_artifact = Path(catalog_path).stem if catalog_path else None
        catalog_schema = _opt_str(export.get("catalog_schema")) or (
            f"se-theory-{artifact_slug}-catalog"
        )

        return cls(
            repo_slug=_require_str(repository, "name", "repository.name"),
            artifact_slug=artifact_slug,
            lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
            reference_dir_name=_str(reference.get("root"), "reference"),
            generated_data_dir=_str(export.get("root"), "data"),
            reference_namespace=_opt_str(lean.get("namespace")),
            catalog_artifact_name=catalog_artifact,
            catalog_schema=catalog_schema,
            surface_kind_sources=surface_kinds,
            strict_warning_exemptions=frozenset(
                _string_list(strict, "warning_exemptions")
            ),
        )
from_toml classmethod
from_toml(data: Mapping[str, object]) -> Self

Build configuration from a parsed theory-reference.toml mapping.

Source code in src/se_theory_reference_kit/declarations/config.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@classmethod
def from_toml(cls, data: Mapping[str, object]) -> Self:
    """Build configuration from a parsed theory-reference.toml mapping."""
    repository = _section(data, "repository")
    lean = _section(data, "lean")
    reference = _section(data, "reference")
    export = _section(data, "export")
    export_map = _string_mapping(data, "export_map")
    surface_kinds = _string_mapping(data, "surface_kinds")
    strict = _section(data, "strict")

    artifact_slug = _require_str(repository, "theory", "repository.theory")
    catalog_path = export_map.get("catalog")
    catalog_artifact = Path(catalog_path).stem if catalog_path else None
    catalog_schema = _opt_str(export.get("catalog_schema")) or (
        f"se-theory-{artifact_slug}-catalog"
    )

    return cls(
        repo_slug=_require_str(repository, "name", "repository.name"),
        artifact_slug=artifact_slug,
        lean_public_root=_require_str(lean, "root_module", "lean.root_module"),
        reference_dir_name=_str(reference.get("root"), "reference"),
        generated_data_dir=_str(export.get("root"), "data"),
        reference_namespace=_opt_str(lean.get("namespace")),
        catalog_artifact_name=catalog_artifact,
        catalog_schema=catalog_schema,
        surface_kind_sources=surface_kinds,
        strict_warning_exemptions=frozenset(
            _string_list(strict, "warning_exemptions")
        ),
    )

export_spec

declarations/export_spec.py - Repo-owned generated export specification shape.

ExportSpec dataclass

A generated JSON artifact export specification.

Source code in src/se_theory_reference_kit/declarations/export_spec.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class ExportSpec:
    """A generated JSON artifact export specification."""

    source_name: str
    source_table: str
    output_name: str
    schema: str
    payload_key: str

    @classmethod
    def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
        """Build export specs by joining [surface_kinds] and [export_map].

        Kit-owned convention for each non-catalog kind present in both maps:
            source_table = kind
            payload_key  = kind
            schema       = f"se-theory-{artifact_slug}-{kind}-registry"
        """
        repository = _section(data, "repository")
        surface_kinds = _string_mapping(data, "surface_kinds")
        export_map = _string_mapping(data, "export_map")

        slug = repository.get("theory")
        if not isinstance(slug, str) or not slug:
            return ()

        specs: list[Self] = []

        for kind, source in surface_kinds.items():
            output = export_map.get(kind)
            if output is None:
                continue

            specs.append(
                cls(
                    source_name=Path(source).name,
                    source_table=kind,
                    output_name=Path(output).name,
                    schema=f"se-theory-{slug}-{kind}-registry",
                    payload_key=kind,
                )
            )

        return tuple(specs)
specs_from_toml classmethod
specs_from_toml(
    data: Mapping[str, object],
) -> tuple[Self, ...]

Build export specs by joining [surface_kinds] and [export_map].

Kit-owned convention for each non-catalog kind present in both maps

source_table = kind payload_key = kind schema = f"se-theory-{artifact_slug}-{kind}-registry"

Source code in src/se_theory_reference_kit/declarations/export_spec.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def specs_from_toml(cls, data: Mapping[str, object]) -> tuple[Self, ...]:
    """Build export specs by joining [surface_kinds] and [export_map].

    Kit-owned convention for each non-catalog kind present in both maps:
        source_table = kind
        payload_key  = kind
        schema       = f"se-theory-{artifact_slug}-{kind}-registry"
    """
    repository = _section(data, "repository")
    surface_kinds = _string_mapping(data, "surface_kinds")
    export_map = _string_mapping(data, "export_map")

    slug = repository.get("theory")
    if not isinstance(slug, str) or not slug:
        return ()

    specs: list[Self] = []

    for kind, source in surface_kinds.items():
        output = export_map.get(kind)
        if output is None:
            continue

        specs.append(
            cls(
                source_name=Path(source).name,
                source_table=kind,
                output_name=Path(output).name,
                schema=f"se-theory-{slug}-{kind}-registry",
                payload_key=kind,
            )
        )

    return tuple(specs)

surface

declarations/surface.py - Repo-owned Lean public surface declaration shape.

SurfaceSymbols dataclass

Kinded public Lean surface symbols for one theory repository.

Source code in src/se_theory_reference_kit/declarations/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass(frozen=True, slots=True)
class SurfaceSymbols:
    """Kinded public Lean surface symbols for one theory repository."""

    by_kind: Mapping[str, frozenset[str]] = field(
        default_factory=lambda: EMPTY_SURFACE_MAP
    )

    def symbols_for_kind(self, kind: str) -> frozenset[str]:
        """Return public symbols for one surface kind."""
        return self.by_kind.get(kind, EMPTY_STRING_SET)

    @property
    def all_symbols(self) -> frozenset[str]:
        """Return all declared public surface symbols."""
        return frozenset(
            symbol for symbols in self.by_kind.values() for symbol in symbols
        )

    @classmethod
    def from_optional_kinds(
        cls,
        *,
        types: frozenset[str] = EMPTY_STRING_SET,
        predicates: frozenset[str] = EMPTY_STRING_SET,
        axioms: frozenset[str] = EMPTY_STRING_SET,
        theorems: frozenset[str] = EMPTY_STRING_SET,
        requirements: frozenset[str] = EMPTY_STRING_SET,
        vocabulary: frozenset[str] = EMPTY_STRING_SET,
        witnesses: frozenset[str] = EMPTY_STRING_SET,
    ) -> Self:
        """Build a surface declaration from common optional surface kinds."""
        return cls(
            by_kind={
                "type": types,
                "predicate": predicates,
                "axiom": axioms,
                "theorem": theorems,
                "requirement": requirements,
                "vocabulary": vocabulary,
                "witness": witnesses,
            }
        )
all_symbols property
all_symbols: frozenset[str]

Return all declared public surface symbols.

from_optional_kinds classmethod
from_optional_kinds(
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self

Build a surface declaration from common optional surface kinds.

Source code in src/se_theory_reference_kit/declarations/surface.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@classmethod
def from_optional_kinds(
    cls,
    *,
    types: frozenset[str] = EMPTY_STRING_SET,
    predicates: frozenset[str] = EMPTY_STRING_SET,
    axioms: frozenset[str] = EMPTY_STRING_SET,
    theorems: frozenset[str] = EMPTY_STRING_SET,
    requirements: frozenset[str] = EMPTY_STRING_SET,
    vocabulary: frozenset[str] = EMPTY_STRING_SET,
    witnesses: frozenset[str] = EMPTY_STRING_SET,
) -> Self:
    """Build a surface declaration from common optional surface kinds."""
    return cls(
        by_kind={
            "type": types,
            "predicate": predicates,
            "axiom": axioms,
            "theorem": theorems,
            "requirement": requirements,
            "vocabulary": vocabulary,
            "witness": witnesses,
        }
    )
symbols_for_kind
symbols_for_kind(kind: str) -> frozenset[str]

Return public symbols for one surface kind.

Source code in src/se_theory_reference_kit/declarations/surface.py
19
20
21
def symbols_for_kind(self, kind: str) -> frozenset[str]:
    """Return public symbols for one surface kind."""
    return self.by_kind.get(kind, EMPTY_STRING_SET)

Lean

se_theory_reference_kit.lean

lean/init.py - Generic Lean source inspection helpers.

LeanDecl dataclass

Lean declaration with name, kind, and reference section.

Source code in src/se_theory_reference_kit/lean/declarations.py
53
54
55
56
57
58
59
@dataclass(frozen=True, slots=True)
class LeanDecl:
    """Lean declaration with name, kind, and reference section."""

    name: str
    kind: str
    section: str

expected_symbols_for_kind

expected_symbols_for_kind(
    surface: SurfaceSymbols, kind: str
) -> frozenset[str]

Return expected public Lean symbols for a surface kind.

Missing kinds return an empty set. The owning theory repository supplies the surface symbols; the kit only reads the generic shape.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
kind str

Surface kind.

required

Returns:

Type Description
frozenset[str]

Expected symbols for that kind.

Source code in src/se_theory_reference_kit/lean/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def expected_symbols_for_kind(surface: SurfaceSymbols, kind: str) -> frozenset[str]:
    """Return expected public Lean symbols for a surface kind.

    Missing kinds return an empty set. The owning theory repository supplies the
    surface symbols; the kit only reads the generic shape.

    Args:
        surface: Repo-owned public surface declaration.
        kind: Surface kind.

    Returns:
        Expected symbols for that kind.
    """
    return surface.symbols_for_kind(kind)

extract_decls

extract_decls(lean_file: Path) -> list[LeanDecl]

Extract top-level Lean declarations from a Lean file.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required

Returns:

Type Description
list[LeanDecl]

Extracted declarations. Missing files return an empty list.

Source code in src/se_theory_reference_kit/lean/declarations.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def extract_decls(lean_file: Path) -> list[LeanDecl]:
    """Extract top-level Lean declarations from a Lean file.

    Args:
        lean_file: Lean source file.

    Returns:
        Extracted declarations. Missing files return an empty list.
    """
    if not lean_file.exists():
        return []

    text = read_text(lean_file)
    return [
        LeanDecl(
            name=match.group("name"),
            kind=match.group("kind"),
            section=LEAN_DECL_TO_SECTION.get(match.group("kind"), "unknown"),
        )
        for match in DECL_RE.finditer(text)
    ]

extract_for_section

extract_for_section(
    lean_file: Path, target_section: str
) -> list[LeanDecl]

Extract Lean declarations matching a reference section.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required
target_section str

Reference section name.

required

Returns:

Type Description
list[LeanDecl]

Declarations whose Lean kind belongs to the requested section.

Source code in src/se_theory_reference_kit/lean/declarations.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def extract_for_section(lean_file: Path, target_section: str) -> list[LeanDecl]:
    """Extract Lean declarations matching a reference section.

    Args:
        lean_file: Lean source file.
        target_section: Reference section name.

    Returns:
        Declarations whose Lean kind belongs to the requested section.
    """
    wanted = SECTION_LEAN_KINDS.get(target_section)
    if wanted is None:
        return []

    return [decl for decl in extract_decls(lean_file) if decl.kind in wanted]

extract_spec_ids

extract_spec_ids(spec_file: Path) -> set[str]

Extract stable citation ids from a Lean Spec file.

Parameters:

Name Type Description Default
spec_file Path

Lean Spec source file.

required

Returns:

Type Description
set[str]

Citation id string values. Missing files return an empty set.

Source code in src/se_theory_reference_kit/lean/spec.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def extract_spec_ids(spec_file: Path) -> set[str]:
    """Extract stable citation ids from a Lean Spec file.

    Args:
        spec_file: Lean Spec source file.

    Returns:
        Citation id string values. Missing files return an empty set.
    """
    if not spec_file.exists():
        return set()

    text = read_text(spec_file)
    return {match.group("value") for match in SPEC_STRING_RE.finditer(text)}

infer_core_modules

infer_core_modules(
    surface_module: str, lean_root: Path
) -> list[str]

Infer Core modules under a public Surface module namespace.

Parameters:

Name Type Description Default
surface_module str

Public surface module, typically ending in ".Surface".

required
lean_root Path

Lean source root.

required

Returns:

Type Description
list[str]

Inferred Core module names. Returns an empty list when the surface module

list[str]

does not follow the expected Surface naming pattern or no Core files are

list[str]

found.

Source code in src/se_theory_reference_kit/lean/modules.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def infer_core_modules(surface_module: str, lean_root: Path) -> list[str]:
    """Infer Core modules under a public Surface module namespace.

    Args:
        surface_module: Public surface module, typically ending in ".Surface".
        lean_root: Lean source root.

    Returns:
        Inferred Core module names. Returns an empty list when the surface module
        does not follow the expected Surface naming pattern or no Core files are
        found.
    """
    if not surface_module.endswith(".Surface"):
        return []

    root_module = surface_module.removesuffix(".Surface")
    root_dir = lean_root.joinpath(*root_module.split("."))

    if not root_dir.exists():
        return []

    core_files = sorted(root_dir.rglob("Core.lean"))

    root_core = root_dir / "Core.lean"
    if root_core in core_files:
        core_files.remove(root_core)
        core_files.insert(0, root_core)

    return [path_to_module(path, lean_root) for path in core_files]

infer_spec_module

infer_spec_module(surface_module: str) -> str

Infer the Spec module from the public surface module.

Parameters:

Name Type Description Default
surface_module str

Public surface module.

required

Returns:

Type Description
str

Inferred Spec module name.

Source code in src/se_theory_reference_kit/lean/spec.py
40
41
42
43
44
45
46
47
48
49
50
51
52
def infer_spec_module(surface_module: str) -> str:
    """Infer the Spec module from the public surface module.

    Args:
        surface_module: Public surface module.

    Returns:
        Inferred Spec module name.
    """
    if surface_module.endswith(".Surface"):
        return surface_module.removesuffix(".Surface") + ".Spec"

    return surface_module + ".Spec"

lean_module_to_relative_path

lean_module_to_relative_path(module: str) -> Path

Convert a Lean module name to a relative Lean source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required

Returns:

Type Description
Path

Relative Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, malformed, or path-like.

Source code in src/se_theory_reference_kit/lean/modules.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def lean_module_to_relative_path(module: str) -> Path:
    """Convert a Lean module name to a relative Lean source path.

    Args:
        module: Lean module name.

    Returns:
        Relative Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, malformed, or
            path-like.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    return Path(*parts).with_suffix(".lean")

missing_expected_surface_symbols

missing_expected_surface_symbols(
    *, surface: SurfaceSymbols, registered: set[str]
) -> set[str]

Return expected public-surface symbols missing from reference registries.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
registered set[str]

Lean symbols already registered in reference artifacts.

required

Returns:

Type Description
set[str]

Expected symbols not present in registered symbols.

Source code in src/se_theory_reference_kit/lean/surface.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def missing_expected_surface_symbols(
    *,
    surface: SurfaceSymbols,
    registered: set[str],
) -> set[str]:
    """Return expected public-surface symbols missing from reference registries.

    Args:
        surface: Repo-owned public surface declaration.
        registered: Lean symbols already registered in reference artifacts.

    Returns:
        Expected symbols not present in registered symbols.
    """
    return set(surface.all_symbols) - registered

path_to_module

path_to_module(path: Path, lean_root: Path) -> str

Convert a Lean file path to a Lean module name.

Parameters:

Name Type Description Default
path Path

Lean source file.

required
lean_root Path

Root directory used for module-relative path conversion.

required

Returns:

Type Description
str

Dotted Lean module name.

Source code in src/se_theory_reference_kit/lean/modules.py
46
47
48
49
50
51
52
53
54
55
56
57
def path_to_module(path: Path, lean_root: Path) -> str:
    """Convert a Lean file path to a Lean module name.

    Args:
        path: Lean source file.
        lean_root: Root directory used for module-relative path conversion.

    Returns:
        Dotted Lean module name.
    """
    relative = path.relative_to(lean_root).with_suffix("")
    return ".".join(relative.parts)

declarations

lean/declarations.py - Extract generic Lean declarations from source files.

LeanDecl dataclass

Lean declaration with name, kind, and reference section.

Source code in src/se_theory_reference_kit/lean/declarations.py
53
54
55
56
57
58
59
@dataclass(frozen=True, slots=True)
class LeanDecl:
    """Lean declaration with name, kind, and reference section."""

    name: str
    kind: str
    section: str

extract_decls

extract_decls(lean_file: Path) -> list[LeanDecl]

Extract top-level Lean declarations from a Lean file.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required

Returns:

Type Description
list[LeanDecl]

Extracted declarations. Missing files return an empty list.

Source code in src/se_theory_reference_kit/lean/declarations.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def extract_decls(lean_file: Path) -> list[LeanDecl]:
    """Extract top-level Lean declarations from a Lean file.

    Args:
        lean_file: Lean source file.

    Returns:
        Extracted declarations. Missing files return an empty list.
    """
    if not lean_file.exists():
        return []

    text = read_text(lean_file)
    return [
        LeanDecl(
            name=match.group("name"),
            kind=match.group("kind"),
            section=LEAN_DECL_TO_SECTION.get(match.group("kind"), "unknown"),
        )
        for match in DECL_RE.finditer(text)
    ]

extract_for_section

extract_for_section(
    lean_file: Path, target_section: str
) -> list[LeanDecl]

Extract Lean declarations matching a reference section.

Parameters:

Name Type Description Default
lean_file Path

Lean source file.

required
target_section str

Reference section name.

required

Returns:

Type Description
list[LeanDecl]

Declarations whose Lean kind belongs to the requested section.

Source code in src/se_theory_reference_kit/lean/declarations.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def extract_for_section(lean_file: Path, target_section: str) -> list[LeanDecl]:
    """Extract Lean declarations matching a reference section.

    Args:
        lean_file: Lean source file.
        target_section: Reference section name.

    Returns:
        Declarations whose Lean kind belongs to the requested section.
    """
    wanted = SECTION_LEAN_KINDS.get(target_section)
    if wanted is None:
        return []

    return [decl for decl in extract_decls(lean_file) if decl.kind in wanted]

modules

lean/modules.py - Convert between Lean module names and source paths.

infer_core_modules

infer_core_modules(
    surface_module: str, lean_root: Path
) -> list[str]

Infer Core modules under a public Surface module namespace.

Parameters:

Name Type Description Default
surface_module str

Public surface module, typically ending in ".Surface".

required
lean_root Path

Lean source root.

required

Returns:

Type Description
list[str]

Inferred Core module names. Returns an empty list when the surface module

list[str]

does not follow the expected Surface naming pattern or no Core files are

list[str]

found.

Source code in src/se_theory_reference_kit/lean/modules.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def infer_core_modules(surface_module: str, lean_root: Path) -> list[str]:
    """Infer Core modules under a public Surface module namespace.

    Args:
        surface_module: Public surface module, typically ending in ".Surface".
        lean_root: Lean source root.

    Returns:
        Inferred Core module names. Returns an empty list when the surface module
        does not follow the expected Surface naming pattern or no Core files are
        found.
    """
    if not surface_module.endswith(".Surface"):
        return []

    root_module = surface_module.removesuffix(".Surface")
    root_dir = lean_root.joinpath(*root_module.split("."))

    if not root_dir.exists():
        return []

    core_files = sorted(root_dir.rglob("Core.lean"))

    root_core = root_dir / "Core.lean"
    if root_core in core_files:
        core_files.remove(root_core)
        core_files.insert(0, root_core)

    return [path_to_module(path, lean_root) for path in core_files]

lean_module_to_relative_path

lean_module_to_relative_path(module: str) -> Path

Convert a Lean module name to a relative Lean source path.

Parameters:

Name Type Description Default
module str

Lean module name.

required

Returns:

Type Description
Path

Relative Lean source path.

Raises:

Type Description
PathResolutionError

If the module name is empty, malformed, or path-like.

Source code in src/se_theory_reference_kit/lean/modules.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def lean_module_to_relative_path(module: str) -> Path:
    """Convert a Lean module name to a relative Lean source path.

    Args:
        module: Lean module name.

    Returns:
        Relative Lean source path.

    Raises:
        PathResolutionError: If the module name is empty, malformed, or
            path-like.
    """
    module_name = module.strip()

    if not module_name:
        msg = "Lean module name must be nonempty."
        raise PathResolutionError(msg)

    if "/" in module_name or "\\" in module_name:
        msg = f"Expected Lean module name, got path-like value: {module}"
        raise PathResolutionError(msg)

    parts = module_name.split(".")

    if any(not part for part in parts):
        msg = f"Malformed Lean module name: {module}"
        raise PathResolutionError(msg)

    return Path(*parts).with_suffix(".lean")

path_to_module

path_to_module(path: Path, lean_root: Path) -> str

Convert a Lean file path to a Lean module name.

Parameters:

Name Type Description Default
path Path

Lean source file.

required
lean_root Path

Root directory used for module-relative path conversion.

required

Returns:

Type Description
str

Dotted Lean module name.

Source code in src/se_theory_reference_kit/lean/modules.py
46
47
48
49
50
51
52
53
54
55
56
57
def path_to_module(path: Path, lean_root: Path) -> str:
    """Convert a Lean file path to a Lean module name.

    Args:
        path: Lean source file.
        lean_root: Root directory used for module-relative path conversion.

    Returns:
        Dotted Lean module name.
    """
    relative = path.relative_to(lean_root).with_suffix("")
    return ".".join(relative.parts)

spec

lean/spec.py - Extract stable citation identifiers from Lean spec files.

extract_spec_ids

extract_spec_ids(spec_file: Path) -> set[str]

Extract stable citation ids from a Lean Spec file.

Parameters:

Name Type Description Default
spec_file Path

Lean Spec source file.

required

Returns:

Type Description
set[str]

Citation id string values. Missing files return an empty set.

Source code in src/se_theory_reference_kit/lean/spec.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def extract_spec_ids(spec_file: Path) -> set[str]:
    """Extract stable citation ids from a Lean Spec file.

    Args:
        spec_file: Lean Spec source file.

    Returns:
        Citation id string values. Missing files return an empty set.
    """
    if not spec_file.exists():
        return set()

    text = read_text(spec_file)
    return {match.group("value") for match in SPEC_STRING_RE.finditer(text)}

infer_spec_module

infer_spec_module(surface_module: str) -> str

Infer the Spec module from the public surface module.

Parameters:

Name Type Description Default
surface_module str

Public surface module.

required

Returns:

Type Description
str

Inferred Spec module name.

Source code in src/se_theory_reference_kit/lean/spec.py
40
41
42
43
44
45
46
47
48
49
50
51
52
def infer_spec_module(surface_module: str) -> str:
    """Infer the Spec module from the public surface module.

    Args:
        surface_module: Public surface module.

    Returns:
        Inferred Spec module name.
    """
    if surface_module.endswith(".Surface"):
        return surface_module.removesuffix(".Surface") + ".Spec"

    return surface_module + ".Spec"

surface

lean/surface.py - Compare repo-owned public surface declarations.

expected_symbols_for_kind

expected_symbols_for_kind(
    surface: SurfaceSymbols, kind: str
) -> frozenset[str]

Return expected public Lean symbols for a surface kind.

Missing kinds return an empty set. The owning theory repository supplies the surface symbols; the kit only reads the generic shape.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
kind str

Surface kind.

required

Returns:

Type Description
frozenset[str]

Expected symbols for that kind.

Source code in src/se_theory_reference_kit/lean/surface.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def expected_symbols_for_kind(surface: SurfaceSymbols, kind: str) -> frozenset[str]:
    """Return expected public Lean symbols for a surface kind.

    Missing kinds return an empty set. The owning theory repository supplies the
    surface symbols; the kit only reads the generic shape.

    Args:
        surface: Repo-owned public surface declaration.
        kind: Surface kind.

    Returns:
        Expected symbols for that kind.
    """
    return surface.symbols_for_kind(kind)

missing_expected_surface_symbols

missing_expected_surface_symbols(
    *, surface: SurfaceSymbols, registered: set[str]
) -> set[str]

Return expected public-surface symbols missing from reference registries.

Parameters:

Name Type Description Default
surface SurfaceSymbols

Repo-owned public surface declaration.

required
registered set[str]

Lean symbols already registered in reference artifacts.

required

Returns:

Type Description
set[str]

Expected symbols not present in registered symbols.

Source code in src/se_theory_reference_kit/lean/surface.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def missing_expected_surface_symbols(
    *,
    surface: SurfaceSymbols,
    registered: set[str],
) -> set[str]:
    """Return expected public-surface symbols missing from reference registries.

    Args:
        surface: Repo-owned public surface declaration.
        registered: Lean symbols already registered in reference artifacts.

    Returns:
        Expected symbols not present in registered symbols.
    """
    return set(surface.all_symbols) - registered

Reference

se_theory_reference_kit.reference

reference/init.py - Generic reference artifact tooling.

LoadedReferenceArtifact dataclass

Loaded reference artifact.

Attributes:

Name Type Description
artifact_id str

Stable artifact id from the reference index.

path Path

Resolved artifact path.

kind str

Artifact kind declared by the owning repository.

data ReferenceDocument

Parsed TOML data.

Source code in src/se_theory_reference_kit/reference/artifacts.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@dataclass(frozen=True, slots=True)
class LoadedReferenceArtifact:
    """Loaded reference artifact.

    Attributes:
        artifact_id: Stable artifact id from the reference index.
        path: Resolved artifact path.
        kind: Artifact kind declared by the owning repository.
        data: Parsed TOML data.
    """

    artifact_id: str
    path: Path
    kind: str
    data: ReferenceDocument

ReferenceRegistry dataclass

Loaded reference artifact registry.

Attributes:

Name Type Description
artifacts tuple[LoadedReferenceArtifact, ...]

Loaded reference artifacts in index order.

Source code in src/se_theory_reference_kit/reference/registry.py
25
26
27
28
29
30
31
32
33
34
35
36
37
@dataclass(frozen=True, slots=True)
class ReferenceRegistry:
    """Loaded reference artifact registry.

    Attributes:
        artifacts: Loaded reference artifacts in index order.
    """

    artifacts: tuple[LoadedReferenceArtifact, ...]

    def by_id(self) -> dict[str, LoadedReferenceArtifact]:
        """Return loaded artifacts keyed by artifact id."""
        return {artifact.artifact_id: artifact for artifact in self.artifacts}

by_id

by_id() -> dict[str, LoadedReferenceArtifact]

Return loaded artifacts keyed by artifact id.

Source code in src/se_theory_reference_kit/reference/registry.py
35
36
37
def by_id(self) -> dict[str, LoadedReferenceArtifact]:
    """Return loaded artifacts keyed by artifact id."""
    return {artifact.artifact_id: artifact for artifact in self.artifacts}

build_reference_registry

build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry

Build a registry from artifact declarations.

Parameters:

Name Type Description Default
artifact_declarations list[ArtifactDeclaration]

Artifact declarations from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
ReferenceRegistry

Loaded reference registry.

Source code in src/se_theory_reference_kit/reference/registry.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry:
    """Build a registry from artifact declarations.

    Args:
        artifact_declarations: Artifact declarations from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference registry.
    """
    loaded = tuple(
        load_reference_artifact(
            artifact,
            root=root,
            reference_dir_name=reference_dir_name,
        )
        for artifact in artifact_declarations
    )

    return ReferenceRegistry(artifacts=loaded)

discover_reference_artifacts

discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]

Discover TOML reference artifacts under the reference directory.

Parameters:

Name Type Description Default
root Path | None

Repository root.

None
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
tuple[Path, ...]

Sorted reference TOML paths.

Source code in src/se_theory_reference_kit/reference/artifacts.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]:
    """Discover TOML reference artifacts under the reference directory.

    Args:
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Sorted reference TOML paths.
    """
    root_dir = reference_dir(root=root, reference_dir_name=reference_dir_name)

    if not root_dir.exists():
        return ()

    return tuple(
        sorted(
            path
            for path in root_dir.rglob("*.toml")
            if path.is_file() and path.name != "index.toml"
        )
    )

load_reference_artifact

load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact

Load one reference artifact declared in the reference index.

Parameters:

Name Type Description Default
artifact ArtifactDeclaration

Artifact declaration from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
LoadedReferenceArtifact

Loaded reference artifact.

Raises:

Type Description
ValueError

If the declaration lacks a valid path.

Source code in src/se_theory_reference_kit/reference/artifacts.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact:
    """Load one reference artifact declared in the reference index.

    Args:
        artifact: Artifact declaration from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference artifact.

    Raises:
        ValueError: If the declaration lacks a valid path.
    """
    artifact_id = str(artifact.get("id", "<unnamed>"))
    kind = str(artifact.get("kind", ""))

    rel_path = artifact.get("path", "")
    if not isinstance(rel_path, str) or not rel_path:
        msg = f"artifact {artifact_id!r} path must be a nonempty string"
        raise ValueError(msg)

    path = reference_artifact_path(
        rel_path,
        root=root,
        reference_dir_name=reference_dir_name,
    )

    return LoadedReferenceArtifact(
        artifact_id=artifact_id,
        path=path,
        kind=kind,
        data=load_toml(path),
    )

make_stub

make_stub(
    declaration: LeanDecl, source_module: str
) -> ReferenceEntry

Create a generic reference entry stub for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required
source_module str

Source module for the declaration.

required

Returns:

Type Description
ReferenceEntry

Reference entry stub.

Source code in src/se_theory_reference_kit/reference/stubs.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def make_stub(
    declaration: LeanDecl,
    source_module: str,
) -> ReferenceEntry:
    """Create a generic reference entry stub for a Lean declaration.

    Args:
        declaration: Lean declaration.
        source_module: Source module for the declaration.

    Returns:
        Reference entry stub.
    """
    return {
        "lean_symbol": declaration.name,
        "lean_kind": declaration.kind,
        "source_module": source_module,
    }

merge_entry

merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry

Merge an existing hand-authored entry with generated fields.

Parameters:

Name Type Description Default
existing ReferenceEntry

Existing entry.

required
generated ReferenceEntry

Generated stub fields.

required
overwrite bool

If true, generated values replace existing values.

required

Returns:

Type Description
ReferenceEntry

Merged entry.

Source code in src/se_theory_reference_kit/reference/stubs.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry:
    """Merge an existing hand-authored entry with generated fields.

    Args:
        existing: Existing entry.
        generated: Generated stub fields.
        overwrite: If true, generated values replace existing values.

    Returns:
        Merged entry.
    """
    if overwrite:
        return {**existing, **generated}

    merged = dict(generated)
    merged.update(existing)
    return merged

ordered_table_values

ordered_table_values(
    document: ReferenceDocument, table_name: str
) -> list[dict[str, object]]

Return nested table values sorted by order, then id/key.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required
table_name str

Top-level table name.

required

Returns:

Type Description
list[dict[str, object]]

Ordered table entries. Each entry receives an id if missing.

Raises:

Type Description
TypeError

If the table or entries are not tables.

Source code in src/se_theory_reference_kit/reference/artifacts.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def ordered_table_values(
    document: ReferenceDocument,
    table_name: str,
) -> list[dict[str, object]]:
    """Return nested table values sorted by order, then id/key.

    Args:
        document: Parsed reference artifact.
        table_name: Top-level table name.

    Returns:
        Ordered table entries. Each entry receives an id if missing.

    Raises:
        TypeError: If the table or entries are not tables.
    """
    table = document.get(table_name, {})
    if not isinstance(table, dict):
        msg = f"Expected [{table_name}.<id>] tables"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert before iterating.
    table_map = cast("dict[str, object]", table)
    entries: list[dict[str, object]] = []

    for key, value in table_map.items():
        if not isinstance(value, dict):
            msg = f"Expected table entry for {table_name}.{key}"
            raise TypeError(msg)

        entry = dict(cast("dict[str, object]", value))
        entry.setdefault("id", str(key))
        entries.append(entry)

    return sorted(
        entries,
        key=lambda item: (
            item.get("order", 999_999),
            str(item.get("id", "")),
        ),
    )

reference_artifact_meta

reference_artifact_meta(
    document: ReferenceDocument,
) -> dict[str, object]

Return normalized metadata from a reference artifact.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
dict[str, object]

Copy of the [meta] table, or an empty dictionary when absent.

Raises:

Type Description
TypeError

If [meta] is present but not a table.

Source code in src/se_theory_reference_kit/reference/artifacts.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def reference_artifact_meta(document: ReferenceDocument) -> dict[str, object]:
    """Return normalized metadata from a reference artifact.

    Args:
        document: Parsed reference artifact.

    Returns:
        Copy of the [meta] table, or an empty dictionary when absent.

    Raises:
        TypeError: If [meta] is present but not a table.
    """
    meta = document.get("meta", {})
    if not isinstance(meta, dict):
        msg = "Expected [meta] table"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert them for the copy.
    return dict(cast("dict[str, object]", meta))

reference_stub_key

reference_stub_key(declaration: LeanDecl) -> str

Return the default reference stub key for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required

Returns:

Type Description
str

Stub key.

Source code in src/se_theory_reference_kit/reference/stubs.py
10
11
12
13
14
15
16
17
18
19
def reference_stub_key(declaration: LeanDecl) -> str:
    """Return the default reference stub key for a Lean declaration.

    Args:
        declaration: Lean declaration.

    Returns:
        Stub key.
    """
    return declaration.name

registered_lean_symbols

registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]

Return Lean symbols registered in reference artifacts.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
sections frozenset[str] | None

Optional section filter.

None

Returns:

Type Description
set[str]

Registered Lean symbol names.

Source code in src/se_theory_reference_kit/reference/registry.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]:
    """Return Lean symbols registered in reference artifacts.

    Args:
        registry: Loaded reference registry.
        sections: Optional section filter.

    Returns:
        Registered Lean symbol names.
    """
    symbols: set[str] = set()

    for artifact in registry.artifacts:
        section_names = sections if sections is not None else frozenset(artifact.data)

        for section in section_names:
            for entry in section_entries(artifact.data, section).values():
                symbol = entry.get("lean_symbol")
                if isinstance(symbol, str) and symbol:
                    symbols.add(symbol)

    return symbols

section_entries

section_entries(
    data: ReferenceDocument, section: str
) -> SectionEntries

Return table entries for a reference section.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required
section str

Section name.

required

Returns:

Type Description
SectionEntries

Section entries keyed by entry id.

Source code in src/se_theory_reference_kit/reference/registry.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def section_entries(
    data: ReferenceDocument,
    section: str,
) -> SectionEntries:
    """Return table entries for a reference section.

    Args:
        data: Parsed reference artifact.
        section: Section name.

    Returns:
        Section entries keyed by entry id.
    """
    raw_section = data.get(section, {})

    if not isinstance(raw_section, dict):
        return {}

    # WHY: isinstance narrowing collapses the value to dict[Unknown, Unknown],
    # so re-assert the parameters that pyright strict otherwise reports unknown.
    section_map = cast("dict[str, object]", raw_section)

    entries: SectionEntries = {}

    for key, value in section_map.items():
        if isinstance(value, dict):
            entries[key] = cast("dict[str, Any]", value)

    return entries

source_modules_in_registry

source_modules_in_registry(
    data: ReferenceDocument,
) -> list[str]

Return source modules declared inside a reference artifact.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
list[str]

Source module names in first-seen order.

Source code in src/se_theory_reference_kit/reference/registry.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def source_modules_in_registry(data: ReferenceDocument) -> list[str]:
    """Return source modules declared inside a reference artifact.

    Args:
        data: Parsed reference artifact.

    Returns:
        Source module names in first-seen order.
    """
    modules: list[str] = []
    seen: set[str] = set()

    top_level = data.get("source_module")
    if isinstance(top_level, str) and top_level and top_level not in seen:
        modules.append(top_level)
        seen.add(top_level)

    for value in data.values():
        if not isinstance(value, dict):
            continue

        # WHY: re-assert parameters lost by isinstance narrowing before iterating.
        section_map = cast("dict[str, object]", value)

        extract_unique_source_modules(modules, seen, section_map)

    return modules

validate_reference_artifact_shape

validate_reference_artifact_shape(
    *, check_id: str, artifact: LoadedReferenceArtifact
) -> tuple[CheckResult, ...]

Validate generic reference artifact shape.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def validate_reference_artifact_shape(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
) -> tuple[CheckResult, ...]:
    """Validate generic reference artifact shape.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.

    Returns:
        Validation findings.
    """
    if not artifact.kind:
        return (
            failure(
                check_id,
                "reference artifact declaration has no kind",
                artifact_id=artifact.artifact_id,
                path=artifact.path,
            ),
        )

    return (
        ok(
            check_id,
            "reference artifact has generic TOML shape",
            artifact_id=artifact.artifact_id,
            path=artifact.path,
        ),
    )

validate_required_fields

validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]

Validate required fields for all entries in one reference section.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required
section str

Section name.

required
required_fields Iterable[str]

Required field names.

REQUIRED_ENTRY_FIELDS

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]:
    """Validate required fields for all entries in one reference section.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.
        section: Section name.
        required_fields: Required field names.

    Returns:
        Validation findings.
    """
    findings: list[CheckResult] = []
    required = tuple(required_fields)

    for entry_id, entry in section_entries(artifact.data, section).items():
        for field_name in required:
            value = entry.get(field_name)
            if not isinstance(value, str) or not value:
                findings.append(
                    failure(
                        check_id,
                        f"{section}.{entry_id} missing required field {field_name!r}",
                        artifact_id=artifact.artifact_id,
                        path=artifact.path,
                        detail={"section": section, "entry_id": entry_id},
                    )
                )

    return tuple(findings)

artifacts

reference/artifacts.py - Reference artifact discovery and loading.

LoadedReferenceArtifact dataclass

Loaded reference artifact.

Attributes:

Name Type Description
artifact_id str

Stable artifact id from the reference index.

path Path

Resolved artifact path.

kind str

Artifact kind declared by the owning repository.

data ReferenceDocument

Parsed TOML data.

Source code in src/se_theory_reference_kit/reference/artifacts.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@dataclass(frozen=True, slots=True)
class LoadedReferenceArtifact:
    """Loaded reference artifact.

    Attributes:
        artifact_id: Stable artifact id from the reference index.
        path: Resolved artifact path.
        kind: Artifact kind declared by the owning repository.
        data: Parsed TOML data.
    """

    artifact_id: str
    path: Path
    kind: str
    data: ReferenceDocument

discover_reference_artifacts

discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]

Discover TOML reference artifacts under the reference directory.

Parameters:

Name Type Description Default
root Path | None

Repository root.

None
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
tuple[Path, ...]

Sorted reference TOML paths.

Source code in src/se_theory_reference_kit/reference/artifacts.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def discover_reference_artifacts(
    *,
    root: Path | None = None,
    reference_dir_name: str = "reference",
) -> tuple[Path, ...]:
    """Discover TOML reference artifacts under the reference directory.

    Args:
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Sorted reference TOML paths.
    """
    root_dir = reference_dir(root=root, reference_dir_name=reference_dir_name)

    if not root_dir.exists():
        return ()

    return tuple(
        sorted(
            path
            for path in root_dir.rglob("*.toml")
            if path.is_file() and path.name != "index.toml"
        )
    )

load_reference_artifact

load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact

Load one reference artifact declared in the reference index.

Parameters:

Name Type Description Default
artifact ArtifactDeclaration

Artifact declaration from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
LoadedReferenceArtifact

Loaded reference artifact.

Raises:

Type Description
ValueError

If the declaration lacks a valid path.

Source code in src/se_theory_reference_kit/reference/artifacts.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def load_reference_artifact(
    artifact: ArtifactDeclaration,
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> LoadedReferenceArtifact:
    """Load one reference artifact declared in the reference index.

    Args:
        artifact: Artifact declaration from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference artifact.

    Raises:
        ValueError: If the declaration lacks a valid path.
    """
    artifact_id = str(artifact.get("id", "<unnamed>"))
    kind = str(artifact.get("kind", ""))

    rel_path = artifact.get("path", "")
    if not isinstance(rel_path, str) or not rel_path:
        msg = f"artifact {artifact_id!r} path must be a nonempty string"
        raise ValueError(msg)

    path = reference_artifact_path(
        rel_path,
        root=root,
        reference_dir_name=reference_dir_name,
    )

    return LoadedReferenceArtifact(
        artifact_id=artifact_id,
        path=path,
        kind=kind,
        data=load_toml(path),
    )

ordered_table_values

ordered_table_values(
    document: ReferenceDocument, table_name: str
) -> list[dict[str, object]]

Return nested table values sorted by order, then id/key.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required
table_name str

Top-level table name.

required

Returns:

Type Description
list[dict[str, object]]

Ordered table entries. Each entry receives an id if missing.

Raises:

Type Description
TypeError

If the table or entries are not tables.

Source code in src/se_theory_reference_kit/reference/artifacts.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def ordered_table_values(
    document: ReferenceDocument,
    table_name: str,
) -> list[dict[str, object]]:
    """Return nested table values sorted by order, then id/key.

    Args:
        document: Parsed reference artifact.
        table_name: Top-level table name.

    Returns:
        Ordered table entries. Each entry receives an id if missing.

    Raises:
        TypeError: If the table or entries are not tables.
    """
    table = document.get(table_name, {})
    if not isinstance(table, dict):
        msg = f"Expected [{table_name}.<id>] tables"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert before iterating.
    table_map = cast("dict[str, object]", table)
    entries: list[dict[str, object]] = []

    for key, value in table_map.items():
        if not isinstance(value, dict):
            msg = f"Expected table entry for {table_name}.{key}"
            raise TypeError(msg)

        entry = dict(cast("dict[str, object]", value))
        entry.setdefault("id", str(key))
        entries.append(entry)

    return sorted(
        entries,
        key=lambda item: (
            item.get("order", 999_999),
            str(item.get("id", "")),
        ),
    )

reference_artifact_meta

reference_artifact_meta(
    document: ReferenceDocument,
) -> dict[str, object]

Return normalized metadata from a reference artifact.

Parameters:

Name Type Description Default
document ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
dict[str, object]

Copy of the [meta] table, or an empty dictionary when absent.

Raises:

Type Description
TypeError

If [meta] is present but not a table.

Source code in src/se_theory_reference_kit/reference/artifacts.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def reference_artifact_meta(document: ReferenceDocument) -> dict[str, object]:
    """Return normalized metadata from a reference artifact.

    Args:
        document: Parsed reference artifact.

    Returns:
        Copy of the [meta] table, or an empty dictionary when absent.

    Raises:
        TypeError: If [meta] is present but not a table.
    """
    meta = document.get("meta", {})
    if not isinstance(meta, dict):
        msg = "Expected [meta] table"
        raise TypeError(msg)

    # WHY: isinstance narrowing drops the parameters; re-assert them for the copy.
    return dict(cast("dict[str, object]", meta))

registry

reference/registry.py - Reference artifact registry helpers.

ReferenceRegistry dataclass

Loaded reference artifact registry.

Attributes:

Name Type Description
artifacts tuple[LoadedReferenceArtifact, ...]

Loaded reference artifacts in index order.

Source code in src/se_theory_reference_kit/reference/registry.py
25
26
27
28
29
30
31
32
33
34
35
36
37
@dataclass(frozen=True, slots=True)
class ReferenceRegistry:
    """Loaded reference artifact registry.

    Attributes:
        artifacts: Loaded reference artifacts in index order.
    """

    artifacts: tuple[LoadedReferenceArtifact, ...]

    def by_id(self) -> dict[str, LoadedReferenceArtifact]:
        """Return loaded artifacts keyed by artifact id."""
        return {artifact.artifact_id: artifact for artifact in self.artifacts}
by_id
by_id() -> dict[str, LoadedReferenceArtifact]

Return loaded artifacts keyed by artifact id.

Source code in src/se_theory_reference_kit/reference/registry.py
35
36
37
def by_id(self) -> dict[str, LoadedReferenceArtifact]:
    """Return loaded artifacts keyed by artifact id."""
    return {artifact.artifact_id: artifact for artifact in self.artifacts}

build_reference_registry

build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry

Build a registry from artifact declarations.

Parameters:

Name Type Description Default
artifact_declarations list[ArtifactDeclaration]

Artifact declarations from reference/index.toml.

required
root Path

Repository root.

required
reference_dir_name str

Reference directory name.

'reference'

Returns:

Type Description
ReferenceRegistry

Loaded reference registry.

Source code in src/se_theory_reference_kit/reference/registry.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def build_reference_registry(
    artifact_declarations: list[ArtifactDeclaration],
    *,
    root: Path,
    reference_dir_name: str = "reference",
) -> ReferenceRegistry:
    """Build a registry from artifact declarations.

    Args:
        artifact_declarations: Artifact declarations from reference/index.toml.
        root: Repository root.
        reference_dir_name: Reference directory name.

    Returns:
        Loaded reference registry.
    """
    loaded = tuple(
        load_reference_artifact(
            artifact,
            root=root,
            reference_dir_name=reference_dir_name,
        )
        for artifact in artifact_declarations
    )

    return ReferenceRegistry(artifacts=loaded)

build_registry_from_config

build_registry_from_config(
    repo_root: Path, config: TheoryReferenceConfig
) -> ReferenceRegistry

Build the full reference registry from the config artifact sources.

Source code in src/se_theory_reference_kit/reference/registry.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def build_registry_from_config(
    repo_root: Path, config: TheoryReferenceConfig
) -> ReferenceRegistry:
    """Build the full reference registry from the config artifact sources."""
    declarations: list[ArtifactDeclaration] = [
        {
            "id": kind,
            "kind": kind,
            "path": source,
        }
        for kind, source in config.surface_kind_sources.items()
    ]

    return build_reference_registry(
        declarations,
        root=repo_root,
        reference_dir_name=config.reference_dir_name,
    )

build_surface_symbols

build_surface_symbols(
    repo_root: Path, config: TheoryReferenceConfig
) -> SurfaceSymbols

Derive the public surface from the mapped reference artifacts.

Source code in src/se_theory_reference_kit/reference/registry.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def build_surface_symbols(
    repo_root: Path, config: TheoryReferenceConfig
) -> SurfaceSymbols:
    """Derive the public surface from the mapped reference artifacts."""
    by_kind: dict[str, frozenset[str]] = {}

    for kind, source in config.surface_kind_sources.items():
        if kind not in SURFACE_KINDS:
            continue

        artifact_path = reference_artifact_path(
            source,
            root=repo_root,
            reference_dir_name=config.reference_dir_name,
        )
        artifact = load_toml(artifact_path)
        by_kind[kind] = frozenset(_symbol_names(artifact, kind))

    return SurfaceSymbols(by_kind=by_kind)

extract_unique_source_modules

extract_unique_source_modules(
    modules: list[str],
    seen: set[str],
    section_map: dict[str, object],
) -> None

Extract unique source modules from a section map.

Source code in src/se_theory_reference_kit/reference/registry.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def extract_unique_source_modules(
    modules: list[str], seen: set[str], section_map: dict[str, object]
) -> None:
    """Extract unique source modules from a section map."""
    for entry in section_map.values():
        if not isinstance(entry, dict):
            continue

        entry_map = cast("dict[str, object]", entry)
        source_module = entry_map.get("source_module")
        if (
            isinstance(source_module, str)
            and source_module
            and source_module not in seen
        ):
            modules.append(source_module)
            seen.add(source_module)

registered_lean_symbols

registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]

Return Lean symbols registered in reference artifacts.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
sections frozenset[str] | None

Optional section filter.

None

Returns:

Type Description
set[str]

Registered Lean symbol names.

Source code in src/se_theory_reference_kit/reference/registry.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def registered_lean_symbols(
    registry: ReferenceRegistry,
    *,
    sections: frozenset[str] | None = None,
) -> set[str]:
    """Return Lean symbols registered in reference artifacts.

    Args:
        registry: Loaded reference registry.
        sections: Optional section filter.

    Returns:
        Registered Lean symbol names.
    """
    symbols: set[str] = set()

    for artifact in registry.artifacts:
        section_names = sections if sections is not None else frozenset(artifact.data)

        for section in section_names:
            for entry in section_entries(artifact.data, section).values():
                symbol = entry.get("lean_symbol")
                if isinstance(symbol, str) and symbol:
                    symbols.add(symbol)

    return symbols

section_entries

section_entries(
    data: ReferenceDocument, section: str
) -> SectionEntries

Return table entries for a reference section.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required
section str

Section name.

required

Returns:

Type Description
SectionEntries

Section entries keyed by entry id.

Source code in src/se_theory_reference_kit/reference/registry.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def section_entries(
    data: ReferenceDocument,
    section: str,
) -> SectionEntries:
    """Return table entries for a reference section.

    Args:
        data: Parsed reference artifact.
        section: Section name.

    Returns:
        Section entries keyed by entry id.
    """
    raw_section = data.get(section, {})

    if not isinstance(raw_section, dict):
        return {}

    # WHY: isinstance narrowing collapses the value to dict[Unknown, Unknown],
    # so re-assert the parameters that pyright strict otherwise reports unknown.
    section_map = cast("dict[str, object]", raw_section)

    entries: SectionEntries = {}

    for key, value in section_map.items():
        if isinstance(value, dict):
            entries[key] = cast("dict[str, Any]", value)

    return entries

source_modules_in_registry

source_modules_in_registry(
    data: ReferenceDocument,
) -> list[str]

Return source modules declared inside a reference artifact.

Parameters:

Name Type Description Default
data ReferenceDocument

Parsed reference artifact.

required

Returns:

Type Description
list[str]

Source module names in first-seen order.

Source code in src/se_theory_reference_kit/reference/registry.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def source_modules_in_registry(data: ReferenceDocument) -> list[str]:
    """Return source modules declared inside a reference artifact.

    Args:
        data: Parsed reference artifact.

    Returns:
        Source module names in first-seen order.
    """
    modules: list[str] = []
    seen: set[str] = set()

    top_level = data.get("source_module")
    if isinstance(top_level, str) and top_level and top_level not in seen:
        modules.append(top_level)
        seen.add(top_level)

    for value in data.values():
        if not isinstance(value, dict):
            continue

        # WHY: re-assert parameters lost by isinstance narrowing before iterating.
        section_map = cast("dict[str, object]", value)

        extract_unique_source_modules(modules, seen, section_map)

    return modules

stubs

reference/stubs.py - Generic reference stub construction.

make_stub

make_stub(
    declaration: LeanDecl, source_module: str
) -> ReferenceEntry

Create a generic reference entry stub for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required
source_module str

Source module for the declaration.

required

Returns:

Type Description
ReferenceEntry

Reference entry stub.

Source code in src/se_theory_reference_kit/reference/stubs.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def make_stub(
    declaration: LeanDecl,
    source_module: str,
) -> ReferenceEntry:
    """Create a generic reference entry stub for a Lean declaration.

    Args:
        declaration: Lean declaration.
        source_module: Source module for the declaration.

    Returns:
        Reference entry stub.
    """
    return {
        "lean_symbol": declaration.name,
        "lean_kind": declaration.kind,
        "source_module": source_module,
    }

merge_entry

merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry

Merge an existing hand-authored entry with generated fields.

Parameters:

Name Type Description Default
existing ReferenceEntry

Existing entry.

required
generated ReferenceEntry

Generated stub fields.

required
overwrite bool

If true, generated values replace existing values.

required

Returns:

Type Description
ReferenceEntry

Merged entry.

Source code in src/se_theory_reference_kit/reference/stubs.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def merge_entry(
    existing: ReferenceEntry,
    generated: ReferenceEntry,
    *,
    overwrite: bool,
) -> ReferenceEntry:
    """Merge an existing hand-authored entry with generated fields.

    Args:
        existing: Existing entry.
        generated: Generated stub fields.
        overwrite: If true, generated values replace existing values.

    Returns:
        Merged entry.
    """
    if overwrite:
        return {**existing, **generated}

    merged = dict(generated)
    merged.update(existing)
    return merged

reference_stub_key

reference_stub_key(declaration: LeanDecl) -> str

Return the default reference stub key for a Lean declaration.

Parameters:

Name Type Description Default
declaration LeanDecl

Lean declaration.

required

Returns:

Type Description
str

Stub key.

Source code in src/se_theory_reference_kit/reference/stubs.py
10
11
12
13
14
15
16
17
18
19
def reference_stub_key(declaration: LeanDecl) -> str:
    """Return the default reference stub key for a Lean declaration.

    Args:
        declaration: Lean declaration.

    Returns:
        Stub key.
    """
    return declaration.name

validation

reference/validation.py - Generic reference artifact shape validation.

validate_reference_artifact_shape

validate_reference_artifact_shape(
    *, check_id: str, artifact: LoadedReferenceArtifact
) -> tuple[CheckResult, ...]

Validate generic reference artifact shape.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def validate_reference_artifact_shape(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
) -> tuple[CheckResult, ...]:
    """Validate generic reference artifact shape.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.

    Returns:
        Validation findings.
    """
    if not artifact.kind:
        return (
            failure(
                check_id,
                "reference artifact declaration has no kind",
                artifact_id=artifact.artifact_id,
                path=artifact.path,
            ),
        )

    return (
        ok(
            check_id,
            "reference artifact has generic TOML shape",
            artifact_id=artifact.artifact_id,
            path=artifact.path,
        ),
    )

validate_required_fields

validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]

Validate required fields for all entries in one reference section.

Parameters:

Name Type Description Default
check_id str

Validation check id.

required
artifact LoadedReferenceArtifact

Loaded reference artifact.

required
section str

Section name.

required
required_fields Iterable[str]

Required field names.

REQUIRED_ENTRY_FIELDS

Returns:

Type Description
tuple[CheckResult, ...]

Validation findings.

Source code in src/se_theory_reference_kit/reference/validation.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def validate_required_fields(
    *,
    check_id: str,
    artifact: LoadedReferenceArtifact,
    section: str,
    required_fields: Iterable[str] = REQUIRED_ENTRY_FIELDS,
) -> tuple[CheckResult, ...]:
    """Validate required fields for all entries in one reference section.

    Args:
        check_id: Validation check id.
        artifact: Loaded reference artifact.
        section: Section name.
        required_fields: Required field names.

    Returns:
        Validation findings.
    """
    findings: list[CheckResult] = []
    required = tuple(required_fields)

    for entry_id, entry in section_entries(artifact.data, section).items():
        for field_name in required:
            value = entry.get(field_name)
            if not isinstance(value, str) or not value:
                findings.append(
                    failure(
                        check_id,
                        f"{section}.{entry_id} missing required field {field_name!r}",
                        artifact_id=artifact.artifact_id,
                        path=artifact.path,
                        detail={"section": section, "entry_id": entry_id},
                    )
                )

    return tuple(findings)

Export

se_theory_reference_kit.export

export/init.py - Generic generated export helpers.

CatalogEntry dataclass

Generic catalog entry for one loaded reference artifact.

Source code in src/se_theory_reference_kit/export/catalog.py
13
14
15
16
17
18
19
@dataclass(frozen=True, slots=True)
class CatalogEntry:
    """Generic catalog entry for one loaded reference artifact."""

    artifact_id: str
    kind: str
    path: str

ExportResult dataclass

Result of one generated export operation.

Attributes:

Name Type Description
output_path Path

Generated output path.

current bool

True when output is current or was written.

wrote bool

True when output was written.

checked bool

True when the operation ran in check mode.

Source code in src/se_theory_reference_kit/export/engine.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@dataclass(frozen=True, slots=True)
class ExportResult:
    """Result of one generated export operation.

    Attributes:
        output_path: Generated output path.
        current: True when output is current or was written.
        wrote: True when output was written.
        checked: True when the operation ran in check mode.
    """

    output_path: Path
    current: bool
    wrote: bool
    checked: bool

build_reference_catalog

build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject

Build a generic reference catalog from loaded reference artifacts.

This function builds the common catalog envelope and reference path list. Repo-specific catalog payload sections remain owned by the theory repo.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
schema str

Catalog schema id.

required
source str

Owning repository slug.

required
namespace str

Reference namespace.

required
artifact str

Catalog artifact name.

required

Returns:

Type Description
JsonObject

JSON-compatible catalog payload.

Source code in src/se_theory_reference_kit/export/catalog.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject:
    """Build a generic reference catalog from loaded reference artifacts.

    This function builds the common catalog envelope and reference path list.
    Repo-specific catalog payload sections remain owned by the theory repo.

    Args:
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        schema: Catalog schema id.
        source: Owning repository slug.
        namespace: Reference namespace.
        artifact: Catalog artifact name.

    Returns:
        JSON-compatible catalog payload.
    """
    entries = [
        CatalogEntry(
            artifact_id=item.artifact_id,
            kind=item.kind,
            path=repo_relative_path(item.path, repo_root),
        )
        for item in registry.artifacts
    ]

    return {
        "schema": schema,
        "source": source,
        "namespace": namespace,
        "artifact": artifact,
        "reference_paths": [entry.path for entry in entries],
        "reference_artifacts": [
            {
                "id": entry.artifact_id,
                "kind": entry.kind,
                "path": entry.path,
            }
            for entry in entries
        ],
    }

build_registry_payload

build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject

Build one generated registry payload from one reference artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
document ReferenceDocument

Parsed reference artifact.

required
source_path Path

Source reference artifact path.

required
repo_root Path

Repository root used to produce portable relative paths.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace for generated payloads.

required

Returns:

Type Description
JsonObject

JSON-compatible generated registry payload.

Source code in src/se_theory_reference_kit/export/engine.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject:
    """Build one generated registry payload from one reference artifact.

    Args:
        spec: Repo-owned export specification.
        document: Parsed reference artifact.
        source_path: Source reference artifact path.
        repo_root: Repository root used to produce portable relative paths.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace for generated payloads.

    Returns:
        JSON-compatible generated registry payload.
    """
    meta = reference_artifact_meta(document)
    entries = ordered_table_values(document, spec.source_table)

    return {
        "schema": spec.schema,
        "source": meta.get("source", repo_slug),
        "namespace": meta.get("namespace", reference_namespace),
        "artifact": spec.output_name.removesuffix(".json"),
        "reference_artifact": meta.get(
            "artifact",
            spec.source_name.removesuffix(".toml"),
        ),
        "reference_path": repo_relative_path(source_path, repo_root),
        spec.payload_key: entries,
    }

export_registries

export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]

Export generated registry JSON artifacts.

Parameters:

Name Type Description Default
specs tuple[ExportSpec, ...]

Repo-owned export specifications.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
tuple[ExportResult, ...]

Export results.

Source code in src/se_theory_reference_kit/export/engine.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]:
    """Export generated registry JSON artifacts.

    Args:
        specs: Repo-owned export specifications.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export results.
    """
    return tuple(
        export_registry(
            spec=spec,
            registry=registry,
            repo_root=repo_root,
            reference_root=reference_root,
            output_root=output_root,
            repo_slug=repo_slug,
            reference_namespace=reference_namespace,
            check=check,
        )
        for spec in specs
    )

export_registry

export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult

Export one registry JSON artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root used to locate source artifacts.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
ExportResult

Export result.

Raises:

Type Description
FileNotFoundError

If the source artifact is not loaded in the registry.

Source code in src/se_theory_reference_kit/export/engine.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult:
    """Export one registry JSON artifact.

    Args:
        spec: Repo-owned export specification.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root used to locate source artifacts.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export result.

    Raises:
        FileNotFoundError: If the source artifact is not loaded in the registry.
    """
    source_path = reference_root / spec.source_name

    source_artifact = next(
        (
            artifact
            for artifact in registry.artifacts
            if artifact.path.resolve() == source_path.resolve()
        ),
        None,
    )

    if source_artifact is None:
        msg = f"export source artifact not loaded: {source_path}"
        raise FileNotFoundError(msg)

    payload = build_registry_payload(
        spec=spec,
        document=source_artifact.data,
        source_path=source_path,
        repo_root=repo_root,
        repo_slug=repo_slug,
        reference_namespace=reference_namespace,
    )

    output_path = output_root / spec.output_name
    content = encode_json(payload)
    current = write_or_check_text(output_path, content, check=check)

    return ExportResult(
        output_path=output_path,
        current=current,
        wrote=current and not check,
        checked=check,
    )

catalog

export/catalog.py - Generic reference catalog construction.

CatalogEntry dataclass

Generic catalog entry for one loaded reference artifact.

Source code in src/se_theory_reference_kit/export/catalog.py
13
14
15
16
17
18
19
@dataclass(frozen=True, slots=True)
class CatalogEntry:
    """Generic catalog entry for one loaded reference artifact."""

    artifact_id: str
    kind: str
    path: str

build_reference_catalog

build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject

Build a generic reference catalog from loaded reference artifacts.

This function builds the common catalog envelope and reference path list. Repo-specific catalog payload sections remain owned by the theory repo.

Parameters:

Name Type Description Default
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
schema str

Catalog schema id.

required
source str

Owning repository slug.

required
namespace str

Reference namespace.

required
artifact str

Catalog artifact name.

required

Returns:

Type Description
JsonObject

JSON-compatible catalog payload.

Source code in src/se_theory_reference_kit/export/catalog.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def build_reference_catalog(
    *,
    registry: ReferenceRegistry,
    repo_root: Path,
    schema: str,
    source: str,
    namespace: str,
    artifact: str,
) -> JsonObject:
    """Build a generic reference catalog from loaded reference artifacts.

    This function builds the common catalog envelope and reference path list.
    Repo-specific catalog payload sections remain owned by the theory repo.

    Args:
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        schema: Catalog schema id.
        source: Owning repository slug.
        namespace: Reference namespace.
        artifact: Catalog artifact name.

    Returns:
        JSON-compatible catalog payload.
    """
    entries = [
        CatalogEntry(
            artifact_id=item.artifact_id,
            kind=item.kind,
            path=repo_relative_path(item.path, repo_root),
        )
        for item in registry.artifacts
    ]

    return {
        "schema": schema,
        "source": source,
        "namespace": namespace,
        "artifact": artifact,
        "reference_paths": [entry.path for entry in entries],
        "reference_artifacts": [
            {
                "id": entry.artifact_id,
                "kind": entry.kind,
                "path": entry.path,
            }
            for entry in entries
        ],
    }

engine

export/engine.py - Generic generated JSON export engine.

ExportResult dataclass

Result of one generated export operation.

Attributes:

Name Type Description
output_path Path

Generated output path.

current bool

True when output is current or was written.

wrote bool

True when output was written.

checked bool

True when the operation ran in check mode.

Source code in src/se_theory_reference_kit/export/engine.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@dataclass(frozen=True, slots=True)
class ExportResult:
    """Result of one generated export operation.

    Attributes:
        output_path: Generated output path.
        current: True when output is current or was written.
        wrote: True when output was written.
        checked: True when the operation ran in check mode.
    """

    output_path: Path
    current: bool
    wrote: bool
    checked: bool

build_registry_payload

build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject

Build one generated registry payload from one reference artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
document ReferenceDocument

Parsed reference artifact.

required
source_path Path

Source reference artifact path.

required
repo_root Path

Repository root used to produce portable relative paths.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace for generated payloads.

required

Returns:

Type Description
JsonObject

JSON-compatible generated registry payload.

Source code in src/se_theory_reference_kit/export/engine.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def build_registry_payload(
    *,
    spec: ExportSpec,
    document: ReferenceDocument,
    source_path: Path,
    repo_root: Path,
    repo_slug: str,
    reference_namespace: str,
) -> JsonObject:
    """Build one generated registry payload from one reference artifact.

    Args:
        spec: Repo-owned export specification.
        document: Parsed reference artifact.
        source_path: Source reference artifact path.
        repo_root: Repository root used to produce portable relative paths.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace for generated payloads.

    Returns:
        JSON-compatible generated registry payload.
    """
    meta = reference_artifact_meta(document)
    entries = ordered_table_values(document, spec.source_table)

    return {
        "schema": spec.schema,
        "source": meta.get("source", repo_slug),
        "namespace": meta.get("namespace", reference_namespace),
        "artifact": spec.output_name.removesuffix(".json"),
        "reference_artifact": meta.get(
            "artifact",
            spec.source_name.removesuffix(".toml"),
        ),
        "reference_path": repo_relative_path(source_path, repo_root),
        spec.payload_key: entries,
    }

export_registries

export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]

Export generated registry JSON artifacts.

Parameters:

Name Type Description Default
specs tuple[ExportSpec, ...]

Repo-owned export specifications.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
tuple[ExportResult, ...]

Export results.

Source code in src/se_theory_reference_kit/export/engine.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def export_registries(
    *,
    specs: tuple[ExportSpec, ...],
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> tuple[ExportResult, ...]:
    """Export generated registry JSON artifacts.

    Args:
        specs: Repo-owned export specifications.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export results.
    """
    return tuple(
        export_registry(
            spec=spec,
            registry=registry,
            repo_root=repo_root,
            reference_root=reference_root,
            output_root=output_root,
            repo_slug=repo_slug,
            reference_namespace=reference_namespace,
            check=check,
        )
        for spec in specs
    )

export_registry

export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult

Export one registry JSON artifact.

Parameters:

Name Type Description Default
spec ExportSpec

Repo-owned export specification.

required
registry ReferenceRegistry

Loaded reference registry.

required
repo_root Path

Repository root used to produce portable relative paths.

required
reference_root Path

Reference artifact root used to locate source artifacts.

required
output_root Path

Generated output root.

required
repo_slug str

Owning repository slug.

required
reference_namespace str

Reference namespace.

required
check bool

If true, check freshness without writing.

required

Returns:

Type Description
ExportResult

Export result.

Raises:

Type Description
FileNotFoundError

If the source artifact is not loaded in the registry.

Source code in src/se_theory_reference_kit/export/engine.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def export_registry(
    *,
    spec: ExportSpec,
    registry: ReferenceRegistry,
    repo_root: Path,
    reference_root: Path,
    output_root: Path,
    repo_slug: str,
    reference_namespace: str,
    check: bool,
) -> ExportResult:
    """Export one registry JSON artifact.

    Args:
        spec: Repo-owned export specification.
        registry: Loaded reference registry.
        repo_root: Repository root used to produce portable relative paths.
        reference_root: Reference artifact root used to locate source artifacts.
        output_root: Generated output root.
        repo_slug: Owning repository slug.
        reference_namespace: Reference namespace.
        check: If true, check freshness without writing.

    Returns:
        Export result.

    Raises:
        FileNotFoundError: If the source artifact is not loaded in the registry.
    """
    source_path = reference_root / spec.source_name

    source_artifact = next(
        (
            artifact
            for artifact in registry.artifacts
            if artifact.path.resolve() == source_path.resolve()
        ),
        None,
    )

    if source_artifact is None:
        msg = f"export source artifact not loaded: {source_path}"
        raise FileNotFoundError(msg)

    payload = build_registry_payload(
        spec=spec,
        document=source_artifact.data,
        source_path=source_path,
        repo_root=repo_root,
        repo_slug=repo_slug,
        reference_namespace=reference_namespace,
    )

    output_path = output_root / spec.output_name
    content = encode_json(payload)
    current = write_or_check_text(output_path, content, check=check)

    return ExportResult(
        output_path=output_path,
        current=current,
        wrote=current and not check,
        checked=check,
    )

Validation

se_theory_reference_kit.validation

validation/init.py - Checks, registry, runner, and default check set.

Public surface
  • Check, CheckRegistry the check contract and its catalogue
  • CheckResult, CheckStatus, ... the result vocabulary
  • RunReport, run_checks execution with crash isolation
  • default_registry, DEFAULT_CHECKS the kit's fixed generic check set

Check dataclass

A registered check: a function plus its catalogue metadata.

Attributes:

Name Type Description
check_id str

Stable, unique id.

title str

Short human-readable description for logs and reports.

run CheckFunc

The check function.

strict_only bool

When true, the check runs only in strict mode.

Source code in src/se_theory_reference_kit/validation/registry.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@dataclass(frozen=True, slots=True)
class Check:
    """A registered check: a function plus its catalogue metadata.

    Attributes:
        check_id: Stable, unique id.
        title: Short human-readable description for logs and reports.
        run: The check function.
        strict_only: When true, the check runs only in strict mode.
    """

    check_id: str
    title: str
    run: CheckFunc
    strict_only: bool = False

CheckRegistry dataclass

An immutable, ordered collection of checks.

Order is preserved so runs are deterministic and the default generic checks always precede consumer-appended checks. Ids must be unique across the registry.

Source code in src/se_theory_reference_kit/validation/registry.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@dataclass(frozen=True, slots=True)
class CheckRegistry:
    """An immutable, ordered collection of checks.

    Order is preserved so runs are deterministic and the default generic checks
    always precede consumer-appended checks. Ids must be unique across the
    registry.
    """

    checks: tuple[Check, ...] = ()

    def __post_init__(self) -> None:
        """Reject duplicate check ids at construction time."""
        seen: set[str] = set()
        duplicates: list[str] = []

        for check in self.checks:
            if check.check_id in seen:
                duplicates.append(check.check_id)
            seen.add(check.check_id)

        if duplicates:
            joined = ", ".join(sorted(set(duplicates)))
            msg = f"duplicate check ids in registry: {joined}"
            raise ValueError(msg)

    def extend(self, *checks: Check) -> Self:
        """Return a new registry with the given checks appended.

        The kit's defaults are never mutated; a consumer extends them. The
        returned registry preserves order and re-validates id uniqueness, so a
        consumer cannot shadow a default id.
        """
        return type(self)(checks=(*self.checks, *checks))

    def extended_with(self, checks: Iterable[Check]) -> Self:
        """Return a new registry appending an iterable of checks."""
        return self.extend(*tuple(checks))

    def ids(self) -> tuple[str, ...]:
        """Return the check ids in order."""
        return tuple(check.check_id for check in self.checks)

    def select(self, *, strict: bool) -> Sequence[Check]:
        """Return the checks that should run for the given mode.

        In non-strict mode, strict-only checks are skipped. In strict mode, all
        checks run.
        """
        if strict:
            return self.checks

        return tuple(check for check in self.checks if not check.strict_only)

__post_init__

__post_init__() -> None

Reject duplicate check ids at construction time.

Source code in src/se_theory_reference_kit/validation/registry.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __post_init__(self) -> None:
    """Reject duplicate check ids at construction time."""
    seen: set[str] = set()
    duplicates: list[str] = []

    for check in self.checks:
        if check.check_id in seen:
            duplicates.append(check.check_id)
        seen.add(check.check_id)

    if duplicates:
        joined = ", ".join(sorted(set(duplicates)))
        msg = f"duplicate check ids in registry: {joined}"
        raise ValueError(msg)

extend

extend(*checks: Check) -> Self

Return a new registry with the given checks appended.

The kit's defaults are never mutated; a consumer extends them. The returned registry preserves order and re-validates id uniqueness, so a consumer cannot shadow a default id.

Source code in src/se_theory_reference_kit/validation/registry.py
75
76
77
78
79
80
81
82
def extend(self, *checks: Check) -> Self:
    """Return a new registry with the given checks appended.

    The kit's defaults are never mutated; a consumer extends them. The
    returned registry preserves order and re-validates id uniqueness, so a
    consumer cannot shadow a default id.
    """
    return type(self)(checks=(*self.checks, *checks))

extended_with

extended_with(checks: Iterable[Check]) -> Self

Return a new registry appending an iterable of checks.

Source code in src/se_theory_reference_kit/validation/registry.py
84
85
86
def extended_with(self, checks: Iterable[Check]) -> Self:
    """Return a new registry appending an iterable of checks."""
    return self.extend(*tuple(checks))

ids

ids() -> tuple[str, ...]

Return the check ids in order.

Source code in src/se_theory_reference_kit/validation/registry.py
88
89
90
def ids(self) -> tuple[str, ...]:
    """Return the check ids in order."""
    return tuple(check.check_id for check in self.checks)

select

select(*, strict: bool) -> Sequence[Check]

Return the checks that should run for the given mode.

In non-strict mode, strict-only checks are skipped. In strict mode, all checks run.

Source code in src/se_theory_reference_kit/validation/registry.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def select(self, *, strict: bool) -> Sequence[Check]:
    """Return the checks that should run for the given mode.

    In non-strict mode, strict-only checks are skipped. In strict mode, all
    checks run.
    """
    if strict:
        return self.checks

    return tuple(check for check in self.checks if not check.strict_only)

CheckResult dataclass

One validation finding emitted by one check.

Attributes:

Name Type Description
check_id str

Stable id of the check that emitted the finding.

status CheckStatus

Check status.

severity CheckSeverity

Finding severity.

message str

Human-readable finding message.

artifact_id str | None

Optional artifact id associated with the finding.

path Path | None

Optional path associated with the finding.

detail JsonDetail

Optional structured detail for reports or downstream tooling.

Source code in src/se_theory_reference_kit/base/results.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass(frozen=True, slots=True)
class CheckResult:
    """One validation finding emitted by one check.

    Attributes:
        check_id: Stable id of the check that emitted the finding.
        status: Check status.
        severity: Finding severity.
        message: Human-readable finding message.
        artifact_id: Optional artifact id associated with the finding.
        path: Optional path associated with the finding.
        detail: Optional structured detail for reports or downstream tooling.
    """

    check_id: str
    status: CheckStatus
    severity: CheckSeverity
    message: str
    artifact_id: str | None = None
    path: Path | None = None
    detail: JsonDetail = field(default_factory=empty_detail)

CheckSeverity

Bases: StrEnum

Severity vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
38
39
40
41
42
43
class CheckSeverity(StrEnum):
    """Severity vocabulary for one validation finding."""

    INFO = "info"
    WARNING = "warning"
    ERROR = "error"

CheckStatus

Bases: StrEnum

Status vocabulary for one validation finding.

Source code in src/se_theory_reference_kit/base/results.py
29
30
31
32
33
34
35
class CheckStatus(StrEnum):
    """Status vocabulary for one validation finding."""

    OK = "ok"
    PARTIAL = "partial"
    FAIL = "fail"
    CANNOT_VERIFY = "cannot-verify"

ReferenceRunContext dataclass

Resolved read-only context for theory-reference validation.

Source code in src/se_theory_reference_kit/validation/context.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@dataclass(frozen=True, slots=True)
class ReferenceRunContext:
    """Resolved read-only context for theory-reference validation."""

    repo_root: Path
    config: TheoryReferenceConfig
    surface: SurfaceSymbols
    export_specs: tuple[ExportSpec, ...] = ()

    @property
    def reference_root(self) -> Path:
        """Return the reference artifact directory."""
        return self.repo_root / self.config.reference_dir_name

    @property
    def generated_root(self) -> Path:
        """Return the generated data directory."""
        return self.repo_root / self.config.generated_data_dir

generated_root property

generated_root: Path

Return the generated data directory.

reference_root property

reference_root: Path

Return the reference artifact directory.

RunReport dataclass

The outcome of running a registry against a context.

Attributes:

Name Type Description
results tuple[CheckResult, ...]

Every finding from every check, in check order.

strict bool

Whether the run was executed in strict mode.

overall_status CheckStatus

Worst status across all results.

Source code in src/se_theory_reference_kit/validation/runner.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@dataclass(frozen=True, slots=True)
class RunReport:
    """The outcome of running a registry against a context.

    Attributes:
        results: Every finding from every check, in check order.
        strict: Whether the run was executed in strict mode.
        overall_status: Worst status across all results.
    """

    results: tuple[CheckResult, ...]
    strict: bool
    overall_status: CheckStatus

    @property
    def failures(self) -> tuple[CheckResult, ...]:
        """Return results that count as failures for this run's mode.

        Error-severity findings always count. Warning-severity findings count
        only under strict mode. Cannot-verify always counts.
        """
        counted: list[CheckResult] = []

        for result in self.results:
            if result.status == CheckStatus.CANNOT_VERIFY:
                counted.append(result)
                continue

            if result.status == CheckStatus.FAIL and (
                result.severity == CheckSeverity.ERROR or self.strict
            ):
                counted.append(result)

        return tuple(counted)

    @property
    def passed(self) -> bool:
        """Return true when no findings count as failures for this mode."""
        return len(self.failures) == 0

    @property
    def exit_code(self) -> int:
        """Return the process exit code: 0 when passed, 1 otherwise."""
        return EXIT_OK if self.passed else EXIT_FAILED

exit_code property

exit_code: int

Return the process exit code: 0 when passed, 1 otherwise.

failures property

failures: tuple[CheckResult, ...]

Return results that count as failures for this run's mode.

Error-severity findings always count. Warning-severity findings count only under strict mode. Cannot-verify always counts.

passed property

passed: bool

Return true when no findings count as failures for this mode.

default_registry

default_registry() -> CheckRegistry

Return the kit's default registry of generic checks.

Returns a fresh CheckRegistry each call. Consumers extend it to add repo-specific checks; the kit's defaults are never mutated.

Source code in src/se_theory_reference_kit/validation/defaults.py
54
55
56
57
58
59
60
def default_registry() -> CheckRegistry:
    """Return the kit's default registry of generic checks.

    Returns a fresh CheckRegistry each call. Consumers extend it to add
    repo-specific checks; the kit's defaults are never mutated.
    """
    return CheckRegistry(checks=DEFAULT_CHECKS)

run_checks

run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport

Run selected checks against the context with crash isolation.

Each check is executed independently. If a check raises ReferenceKitError, it is recorded as a cannot-verify result and the run continues. One broken check never hides the results of the others.

Source code in src/se_theory_reference_kit/validation/runner.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport:
    """Run selected checks against the context with crash isolation.

    Each check is executed independently. If a check raises ReferenceKitError,
    it is recorded as a cannot-verify result and the run continues. One broken
    check never hides the results of the others.
    """
    collected: list[CheckResult] = []

    for check in registry.select(strict=strict):
        try:
            collected.extend(check.run(context))
        except ReferenceKitError as exc:
            collected.append(
                cannot_verify(
                    check.check_id,
                    f"check could not run: {exc}",
                )
            )

    return RunReport(
        results=tuple(collected),
        strict=strict,
        overall_status=worst_status(collected),
    )

checks

validation/checks/init.py - Generic theory-reference validation checks.

export

validation/checks/export.py - Validate generated export freshness.

check_exports_current
check_exports_current(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify generated export artifacts are current.

Source code in src/se_theory_reference_kit/validation/checks/export.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def check_exports_current(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify generated export artifacts are current."""
    if not context.export_specs:
        return [partial(CHECK_ID, "no export specs declared")]

    registry = build_registry_from_config(context.repo_root, context.config)
    namespace = _reference_namespace(context)

    results = export_registries(
        specs=context.export_specs,
        registry=registry,
        repo_root=context.repo_root,
        reference_root=context.repo_root / context.config.reference_dir_name,
        output_root=context.repo_root / context.config.generated_data_dir,
        repo_slug=context.config.repo_slug,
        reference_namespace=namespace,
        check=True,
    )

    findings: list[CheckResult] = []
    for result in results:
        if not result.current:
            artifact_id = result.output_path.name

            findings.append(
                failure(
                    CHECK_ID,
                    "generated export artifact is stale",
                    artifact_id=artifact_id,
                    path=result.output_path,
                )
            )

    if findings:
        return findings

    return [ok(CHECK_ID, "generated export artifacts are current")]

lean_surface

validation/checks/lean_surface.py - Validate reference coverage of Lean surface.

check_lean_surface
check_lean_surface(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify expected public Lean symbols appear in reference artifacts.

Source code in src/se_theory_reference_kit/validation/checks/lean_surface.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def check_lean_surface(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify expected public Lean symbols appear in reference artifacts."""
    expected = context.surface.all_symbols
    if not expected:
        return [partial(CHECK_ID, "no public surface symbols declared")]

    registry = build_registry_from_config(context.repo_root, context.config)
    registered = registered_lean_symbols(registry)
    missing = missing_expected_surface_symbols(
        surface=context.surface,
        registered=registered,
    )

    if missing:
        return [
            failure(
                CHECK_ID,
                f"expected public Lean symbol is not registered: {symbol}",
                detail={"lean_symbol": symbol},
            )
            for symbol in sorted(missing)
        ]

    return [
        ok(
            CHECK_ID,
            f"all {len(expected)} expected public Lean symbols are registered",
        )
    ]

reference_artifacts

validation/checks/reference_artifacts.py - Validate declared reference artifacts.

check_reference_artifacts
check_reference_artifacts(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify declared reference artifacts exist, parse, and have generic shape.

Source code in src/se_theory_reference_kit/validation/checks/reference_artifacts.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def check_reference_artifacts(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify declared reference artifacts exist, parse, and have generic shape."""
    declarations = _artifact_declarations_from_context(context)
    if not declarations:
        return [partial(CHECK_ID, "no reference artifacts declared")]

    findings: list[CheckResult] = []

    for declaration in declarations:
        raw_rel_path = declaration.get("path")
        raw_artifact_id = declaration.get("id")

        artifact_id = raw_artifact_id if isinstance(raw_artifact_id, str) else None

        if not isinstance(raw_rel_path, str) or not raw_rel_path:
            findings.append(
                failure(
                    CHECK_ID,
                    "artifact declaration path must be a nonempty string",
                    artifact_id=artifact_id,
                )
            )
            continue

        path = reference_artifact_path(
            raw_rel_path,
            root=context.repo_root,
            reference_dir_name=context.config.reference_dir_name,
        )
        if not path.is_file():
            findings.append(
                failure(
                    CHECK_ID,
                    "declared reference artifact does not exist",
                    artifact_id=artifact_id,
                    path=path,
                )
            )

    if findings:
        return findings

    registry = build_reference_registry(
        declarations,
        root=context.repo_root,
        reference_dir_name=context.config.reference_dir_name,
    )

    for artifact in registry.artifacts:
        findings.extend(
            validate_reference_artifact_shape(
                check_id=CHECK_ID,
                artifact=artifact,
            )
        )

    if not findings:
        findings.append(ok(CHECK_ID, "all declared reference artifacts load"))

    return findings

strict

validation/checks/strict.py - Strict-only unfinished-work marker check.

check_strict_no_todo
check_strict_no_todo(
    context: ReferenceRunContext,
) -> Iterable[CheckResult]

Verify reference artifacts contain no unfinished-work markers.

Source code in src/se_theory_reference_kit/validation/checks/strict.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def check_strict_no_todo(context: ReferenceRunContext) -> Iterable[CheckResult]:
    """Verify reference artifacts contain no unfinished-work markers."""
    findings: list[CheckResult] = []

    for artifact_id, rel_path in _configured_artifact_paths(context):
        path = reference_artifact_path(
            rel_path,
            root=context.repo_root,
            reference_dir_name=context.config.reference_dir_name,
        )
        if path.suffix.lower() not in CHECKED_SUFFIXES:
            continue

        if not path.is_file():
            continue

        markers = _markers_in_text(read_text(path))
        if markers:
            findings.append(
                failure(
                    CHECK_ID,
                    "reference artifact contains unfinished-work marker(s): "
                    + ", ".join(sorted(set(markers))),
                    artifact_id=artifact_id,
                    path=path,
                )
            )

    if not findings:
        findings.append(
            ok(CHECK_ID, "no unfinished-work markers in reference artifacts")
        )

    return findings

context

validation/context.py - Context object for theory-reference validation checks.

ReferenceRunContext dataclass

Resolved read-only context for theory-reference validation.

Source code in src/se_theory_reference_kit/validation/context.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@dataclass(frozen=True, slots=True)
class ReferenceRunContext:
    """Resolved read-only context for theory-reference validation."""

    repo_root: Path
    config: TheoryReferenceConfig
    surface: SurfaceSymbols
    export_specs: tuple[ExportSpec, ...] = ()

    @property
    def reference_root(self) -> Path:
        """Return the reference artifact directory."""
        return self.repo_root / self.config.reference_dir_name

    @property
    def generated_root(self) -> Path:
        """Return the generated data directory."""
        return self.repo_root / self.config.generated_data_dir
generated_root property
generated_root: Path

Return the generated data directory.

reference_root property
reference_root: Path

Return the reference artifact directory.

defaults

validation/defaults.py - The kit's fixed set of generic checks.

This is the single place that knows which checks the kit ships. registry.py is pure machinery and imports nothing from checks; individual checks import Check from registry. defaults.py sits above both, importing the machinery and checks to assemble the default registry. The dependency arrow is one-way:

registry  <-  checks  <-  defaults

so there is no cycle, and registry/checks can be reasoned about without knowing the default set.

Consuming repos build their own registry by extending this one:

from se_theory_reference_kit.validation.defaults import default_registry

registry = default_registry().extend(repo_specific_check)

The defaults are never edited by a consumer; extend() returns a new registry.

Default order
  1. reference.index reference/index.toml exists and parses
  2. reference.artifacts declared reference artifacts exist and parse
  3. lean.surface declared public surface is covered
  4. exports.current generated exports are current
  5. structural.strict.no-todo no unfinished-work markers (strict-only)

default_registry

default_registry() -> CheckRegistry

Return the kit's default registry of generic checks.

Returns a fresh CheckRegistry each call. Consumers extend it to add repo-specific checks; the kit's defaults are never mutated.

Source code in src/se_theory_reference_kit/validation/defaults.py
54
55
56
57
58
59
60
def default_registry() -> CheckRegistry:
    """Return the kit's default registry of generic checks.

    Returns a fresh CheckRegistry each call. Consumers extend it to add
    repo-specific checks; the kit's defaults are never mutated.
    """
    return CheckRegistry(checks=DEFAULT_CHECKS)

registry

validation/registry.py - Check registry and consumer extension hook.

The kit provides a fixed set of default generic checks. Consuming theory repositories append repo-specific checks to that set without modifying the kit. The kit's defaults are never edited by a consumer; they are extended.

This is the seam that lets one shared engine serve every theory repository without forking. Immutability enforces it: extend() returns a new registry with the added checks appended, so a consumer cannot mutate the kit's defaults in place.

Check dataclass

A registered check: a function plus its catalogue metadata.

Attributes:

Name Type Description
check_id str

Stable, unique id.

title str

Short human-readable description for logs and reports.

run CheckFunc

The check function.

strict_only bool

When true, the check runs only in strict mode.

Source code in src/se_theory_reference_kit/validation/registry.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@dataclass(frozen=True, slots=True)
class Check:
    """A registered check: a function plus its catalogue metadata.

    Attributes:
        check_id: Stable, unique id.
        title: Short human-readable description for logs and reports.
        run: The check function.
        strict_only: When true, the check runs only in strict mode.
    """

    check_id: str
    title: str
    run: CheckFunc
    strict_only: bool = False

CheckRegistry dataclass

An immutable, ordered collection of checks.

Order is preserved so runs are deterministic and the default generic checks always precede consumer-appended checks. Ids must be unique across the registry.

Source code in src/se_theory_reference_kit/validation/registry.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@dataclass(frozen=True, slots=True)
class CheckRegistry:
    """An immutable, ordered collection of checks.

    Order is preserved so runs are deterministic and the default generic checks
    always precede consumer-appended checks. Ids must be unique across the
    registry.
    """

    checks: tuple[Check, ...] = ()

    def __post_init__(self) -> None:
        """Reject duplicate check ids at construction time."""
        seen: set[str] = set()
        duplicates: list[str] = []

        for check in self.checks:
            if check.check_id in seen:
                duplicates.append(check.check_id)
            seen.add(check.check_id)

        if duplicates:
            joined = ", ".join(sorted(set(duplicates)))
            msg = f"duplicate check ids in registry: {joined}"
            raise ValueError(msg)

    def extend(self, *checks: Check) -> Self:
        """Return a new registry with the given checks appended.

        The kit's defaults are never mutated; a consumer extends them. The
        returned registry preserves order and re-validates id uniqueness, so a
        consumer cannot shadow a default id.
        """
        return type(self)(checks=(*self.checks, *checks))

    def extended_with(self, checks: Iterable[Check]) -> Self:
        """Return a new registry appending an iterable of checks."""
        return self.extend(*tuple(checks))

    def ids(self) -> tuple[str, ...]:
        """Return the check ids in order."""
        return tuple(check.check_id for check in self.checks)

    def select(self, *, strict: bool) -> Sequence[Check]:
        """Return the checks that should run for the given mode.

        In non-strict mode, strict-only checks are skipped. In strict mode, all
        checks run.
        """
        if strict:
            return self.checks

        return tuple(check for check in self.checks if not check.strict_only)
__post_init__
__post_init__() -> None

Reject duplicate check ids at construction time.

Source code in src/se_theory_reference_kit/validation/registry.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __post_init__(self) -> None:
    """Reject duplicate check ids at construction time."""
    seen: set[str] = set()
    duplicates: list[str] = []

    for check in self.checks:
        if check.check_id in seen:
            duplicates.append(check.check_id)
        seen.add(check.check_id)

    if duplicates:
        joined = ", ".join(sorted(set(duplicates)))
        msg = f"duplicate check ids in registry: {joined}"
        raise ValueError(msg)
extend
extend(*checks: Check) -> Self

Return a new registry with the given checks appended.

The kit's defaults are never mutated; a consumer extends them. The returned registry preserves order and re-validates id uniqueness, so a consumer cannot shadow a default id.

Source code in src/se_theory_reference_kit/validation/registry.py
75
76
77
78
79
80
81
82
def extend(self, *checks: Check) -> Self:
    """Return a new registry with the given checks appended.

    The kit's defaults are never mutated; a consumer extends them. The
    returned registry preserves order and re-validates id uniqueness, so a
    consumer cannot shadow a default id.
    """
    return type(self)(checks=(*self.checks, *checks))
extended_with
extended_with(checks: Iterable[Check]) -> Self

Return a new registry appending an iterable of checks.

Source code in src/se_theory_reference_kit/validation/registry.py
84
85
86
def extended_with(self, checks: Iterable[Check]) -> Self:
    """Return a new registry appending an iterable of checks."""
    return self.extend(*tuple(checks))
ids
ids() -> tuple[str, ...]

Return the check ids in order.

Source code in src/se_theory_reference_kit/validation/registry.py
88
89
90
def ids(self) -> tuple[str, ...]:
    """Return the check ids in order."""
    return tuple(check.check_id for check in self.checks)
select
select(*, strict: bool) -> Sequence[Check]

Return the checks that should run for the given mode.

In non-strict mode, strict-only checks are skipped. In strict mode, all checks run.

Source code in src/se_theory_reference_kit/validation/registry.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def select(self, *, strict: bool) -> Sequence[Check]:
    """Return the checks that should run for the given mode.

    In non-strict mode, strict-only checks are skipped. In strict mode, all
    checks run.
    """
    if strict:
        return self.checks

    return tuple(check for check in self.checks if not check.strict_only)

runner

validation/runner.py - Execute a registry with crash isolation.

The runner is the only place that knows about strict mode and overall outcome. It runs each selected check, isolates crashes, collects all results, and computes an exit code.

Strict mode is applied here, not in checks: checks report severity, and the runner decides whether warning-severity findings fail the run.

RunReport dataclass

The outcome of running a registry against a context.

Attributes:

Name Type Description
results tuple[CheckResult, ...]

Every finding from every check, in check order.

strict bool

Whether the run was executed in strict mode.

overall_status CheckStatus

Worst status across all results.

Source code in src/se_theory_reference_kit/validation/runner.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@dataclass(frozen=True, slots=True)
class RunReport:
    """The outcome of running a registry against a context.

    Attributes:
        results: Every finding from every check, in check order.
        strict: Whether the run was executed in strict mode.
        overall_status: Worst status across all results.
    """

    results: tuple[CheckResult, ...]
    strict: bool
    overall_status: CheckStatus

    @property
    def failures(self) -> tuple[CheckResult, ...]:
        """Return results that count as failures for this run's mode.

        Error-severity findings always count. Warning-severity findings count
        only under strict mode. Cannot-verify always counts.
        """
        counted: list[CheckResult] = []

        for result in self.results:
            if result.status == CheckStatus.CANNOT_VERIFY:
                counted.append(result)
                continue

            if result.status == CheckStatus.FAIL and (
                result.severity == CheckSeverity.ERROR or self.strict
            ):
                counted.append(result)

        return tuple(counted)

    @property
    def passed(self) -> bool:
        """Return true when no findings count as failures for this mode."""
        return len(self.failures) == 0

    @property
    def exit_code(self) -> int:
        """Return the process exit code: 0 when passed, 1 otherwise."""
        return EXIT_OK if self.passed else EXIT_FAILED
exit_code property
exit_code: int

Return the process exit code: 0 when passed, 1 otherwise.

failures property
failures: tuple[CheckResult, ...]

Return results that count as failures for this run's mode.

Error-severity findings always count. Warning-severity findings count only under strict mode. Cannot-verify always counts.

passed property
passed: bool

Return true when no findings count as failures for this mode.

run_checks

run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport

Run selected checks against the context with crash isolation.

Each check is executed independently. If a check raises ReferenceKitError, it is recorded as a cannot-verify result and the run continues. One broken check never hides the results of the others.

Source code in src/se_theory_reference_kit/validation/runner.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def run_checks(
    *,
    registry: CheckRegistry,
    context: ReferenceRunContext,
    strict: bool = False,
) -> RunReport:
    """Run selected checks against the context with crash isolation.

    Each check is executed independently. If a check raises ReferenceKitError,
    it is recorded as a cannot-verify result and the run continues. One broken
    check never hides the results of the others.
    """
    collected: list[CheckResult] = []

    for check in registry.select(strict=strict):
        try:
            collected.extend(check.run(context))
        except ReferenceKitError as exc:
            collected.append(
                cannot_verify(
                    check.check_id,
                    f"check could not run: {exc}",
                )
            )

    return RunReport(
        results=tuple(collected),
        strict=strict,
        overall_status=worst_status(collected),
    )

Commands

se_theory_reference_kit.commands

Command implementations for cli.

catalog

commands/catalog.py - Reference catalog command.

configure_catalog_parser

configure_catalog_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the catalog subcommand.

Source code in src/se_theory_reference_kit/commands/catalog.py
13
14
15
16
17
18
19
20
21
22
23
24
def configure_catalog_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the catalog subcommand."""
    parser = subparsers.add_parser(
        "catalog",
        help="Build the generated reference catalog.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Check whether the generated catalog is current without writing.",
    )
    parser.set_defaults(handler=run_catalog_command)

run_catalog_command

run_catalog_command(args: Namespace) -> int

Run generated catalog export or freshness check.

Source code in src/se_theory_reference_kit/commands/catalog.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def run_catalog_command(args: Namespace) -> int:
    """Run generated catalog export or freshness check."""
    root = None if args.root is None else Path(args.root)
    command_context = resolve_command_context(root=root)
    config = command_context.config

    if config.catalog_artifact_name is None:
        msg = (
            "theory-reference.toml must declare [export_map].catalog for catalog export"
        )
        raise RuntimeError(msg)
    if config.catalog_schema is None:
        msg = "theory-reference.toml must resolve a catalog schema for catalog export"
        raise RuntimeError(msg)

    namespace = (
        config.reference_namespace or f"se.{config.artifact_slug.replace('-', '_')}"
    )

    registry = build_registry_from_config(command_context.repo_root, config)

    payload = build_reference_catalog(
        registry=registry,
        schema=config.catalog_schema,
        repo_root=command_context.repo_root,
        source=config.repo_slug,
        namespace=namespace,
        artifact=config.catalog_artifact_name,
    )

    output_path = (
        command_context.repo_root
        / config.generated_data_dir
        / f"{config.catalog_artifact_name}.json"
    )

    current = write_or_check_text(
        output_path,
        encode_json(payload),
        check=bool(args.check),
    )

    if current:
        print(
            "Reference catalog is current."
            if args.check
            else "Reference catalog completed."
        )
        return 0

    print("Reference catalog is stale.")
    return 1

export

commands/export.py - Generated export command.

configure_export_parser

configure_export_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the export subcommand.

Source code in src/se_theory_reference_kit/commands/export.py
12
13
14
15
16
17
18
19
20
21
22
23
def configure_export_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the export subcommand."""
    parser = subparsers.add_parser(
        "export",
        help="Export generated data artifacts from reference artifacts.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Check whether generated artifacts are current without writing.",
    )
    parser.set_defaults(handler=run_export_command)

run_export_command

run_export_command(args: Namespace) -> int

Run generated export or export freshness check.

Source code in src/se_theory_reference_kit/commands/export.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def run_export_command(args: Namespace) -> int:
    """Run generated export or export freshness check."""
    raw_root = getattr(args, "root", None)
    root = None if raw_root is None else Path(raw_root)

    command_context = resolve_command_context(root=root)

    registry = build_registry_from_config(
        command_context.repo_root,
        command_context.config,
    )

    namespace = _reference_namespace(command_context.config)

    reference_root = (
        command_context.repo_root / command_context.config.reference_dir_name
    )
    output_root = command_context.repo_root / command_context.config.generated_data_dir

    results = export_registries(
        specs=command_context.export_specs,
        registry=registry,
        repo_root=command_context.repo_root,
        reference_root=reference_root,
        output_root=output_root,
        repo_slug=command_context.config.repo_slug,
        reference_namespace=namespace,
        check=bool(args.check),
    )

    if all(result.current for result in results):
        if args.check:
            print("Reference exports are current.")
        else:
            print("Reference export completed.")
        return 0

    print("Reference exports are stale.")
    return 1

inspect

commands/inspect.py - Inspect resolved theory-reference declarations.

configure_inspect_parser

configure_inspect_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the inspect subcommand.

Source code in src/se_theory_reference_kit/commands/inspect.py
11
12
13
14
15
16
17
def configure_inspect_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the inspect subcommand."""
    parser = subparsers.add_parser(
        "inspect",
        help="Inspect resolved theory-reference declarations.",
    )
    parser.set_defaults(handler=run_inspect_command)

run_inspect_command

run_inspect_command(args: Namespace) -> int

Inspect the resolved command context.

Source code in src/se_theory_reference_kit/commands/inspect.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def run_inspect_command(args: Namespace) -> int:
    """Inspect the resolved command context."""
    raw_root = getattr(args, "root", None)
    root = None if raw_root is None else Path(raw_root)

    command_context = resolve_command_context(root=root)
    config = command_context.config

    print(f"repo_root: {command_context.repo_root.as_posix()}")
    print(f"repo_slug: {config.repo_slug}")
    print(f"artifact_slug: {config.artifact_slug}")
    print(f"lean_public_root: {config.lean_public_root}")
    print(f"reference_dir: {config.reference_dir_name}")
    print(f"generated_data_dir: {config.generated_data_dir}")

    print("surface_kind_sources:")
    for kind, source in sorted(config.surface_kind_sources.items()):
        print(f"  {kind}: {source}")

    registry = build_registry_from_config(
        command_context.repo_root,
        config,
    )
    print(f"loaded_artifacts: {len(registry.artifacts)}")

    print("surface_symbols:")
    for kind, symbols in sorted(command_context.surface.by_kind.items()):
        print(f"  {kind}: {len(symbols)}")

    print(f"export_specs: {len(command_context.export_specs)}")
    for spec in command_context.export_specs:
        print(f"  {spec.source_name} -> {spec.output_name}")

    return 0

root

commands/root.py - Root command dispatcher for se-theory-reference.

build_parser

build_parser() -> ArgumentParser

Build the root argument parser.

Source code in src/se_theory_reference_kit/commands/root.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def build_parser() -> ArgumentParser:
    """Build the root argument parser."""
    parser = ArgumentParser(
        prog="se-theory-reference",
        description="Reference tooling for Structural Explainability theory repos.",
    )
    parser.add_argument(
        "--root",
        default=None,
        help="Repository root or path inside the target repository.",
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    configure_validate_parser(subparsers)
    configure_scaffold_parser(subparsers)
    configure_export_parser(subparsers)
    configure_catalog_parser(subparsers)
    configure_inspect_parser(subparsers)

    return parser

main

main(argv: Sequence[str] | None = None) -> int

Run the combined command-line interface.

Source code in src/se_theory_reference_kit/commands/root.py
38
39
40
41
42
43
44
45
46
47
48
def main(argv: Sequence[str] | None = None) -> int:
    """Run the combined command-line interface."""
    parser = build_parser()
    args = parser.parse_args(argv)

    handler = getattr(args, "handler", None)
    if handler is None:
        parser.print_help()
        return 2

    return int(handler(args))

scaffold

commands/scaffold.py - Reference scaffold command.

configure_scaffold_parser

configure_scaffold_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the scaffold subcommand.

Source code in src/se_theory_reference_kit/commands/scaffold.py
10
11
12
13
14
15
16
17
18
def configure_scaffold_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the scaffold subcommand."""
    parser = subparsers.add_parser(
        "scaffold",
        help="Scaffold missing reference entries from Lean source.",
    )
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--overwrite", action="store_true")
    parser.set_defaults(handler=run_scaffold_command)

run_scaffold_command

run_scaffold_command(args: Namespace) -> int

Run reference scaffolding.

Source code in src/se_theory_reference_kit/commands/scaffold.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def run_scaffold_command(args: Namespace) -> int:
    """Run reference scaffolding."""
    root = None if args.root is None else Path(args.root)
    command_context = resolve_command_context(root=root)

    print(f"repo_root: {command_context.repo_root.as_posix()}")
    print("Reference scaffolding command is wired.")
    print("Scaffold engine extraction is required before entries can be written.")

    if args.dry_run:
        print("mode: dry-run")
    if args.overwrite:
        print("mode: overwrite")

    return 0

validate

commands/validate.py - Validation command.

configure_validate_parser

configure_validate_parser(
    subparsers: _SubParsersAction[Any],
) -> None

Configure the validate subcommand.

Source code in src/se_theory_reference_kit/commands/validate.py
13
14
15
16
17
18
19
20
21
22
23
24
def configure_validate_parser(subparsers: _SubParsersAction[Any]) -> None:
    """Configure the validate subcommand."""
    parser = subparsers.add_parser(
        "validate",
        help="Validate reference artifacts against declared Lean public surface.",
    )
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Run strict validation checks.",
    )
    parser.set_defaults(handler=run_validate_command)

run_validate_command

run_validate_command(args: Namespace) -> int

Run validation checks.

Source code in src/se_theory_reference_kit/commands/validate.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def run_validate_command(args: Namespace) -> int:
    """Run validation checks."""
    raw_root = getattr(args, "root", None)
    root = None if raw_root is None else Path(raw_root)

    command_context = resolve_command_context(root=root)

    context = ReferenceRunContext(
        repo_root=command_context.repo_root,
        config=command_context.config,
        surface=command_context.surface,
        export_specs=command_context.export_specs,
    )

    registry = default_registry()
    report = run_checks(
        registry=registry,
        context=context,
        strict=bool(args.strict),
    )

    for result in report.results:
        print(f"[{result.check_id}] {result.status.value}  {result.message}")

    return report.exit_code