Skip to content

API

The reactive-research package provides the reference executable implementation of Reactive Research.

API documentation below is generated from the package source and docstrings.

For command-line usage, use:

uvx reactive-research --help
uvx reactive-research COMMAND --help

Models

reactive_research.models

Core data models for Reactive Research.

Diagnostic dataclass

One extraction or validation finding.

Source code in src/reactive_research/models.py
79
80
81
82
83
84
85
86
@dataclass(frozen=True)
class Diagnostic:
    """One extraction or validation finding."""

    code: str
    message: str
    severity: DiagnosticSeverity
    source: SourceLocation | None = None

DiagnosticSeverity

Bases: StrEnum

Severity of one Reactive Research diagnostic.

Source code in src/reactive_research/models.py
34
35
36
37
38
class DiagnosticSeverity(StrEnum):
    """Severity of one Reactive Research diagnostic."""

    ERROR = "error"
    WARNING = "warning"

ExtractionResult dataclass

Complete result of extracting one repository.

Source code in src/reactive_research/models.py
 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
@dataclass(frozen=True)
class ExtractionResult:
    """Complete result of extracting one repository."""

    repository: RepositoryContext
    declarations: tuple[ResearchDeclaration, ...] = field(default_factory=tuple)
    diagnostics: tuple[Diagnostic, ...] = field(default_factory=tuple)

    @property
    def defines(self) -> tuple[ResearchDeclaration, ...]:
        """Return all DEFINES declarations."""
        return tuple(
            declaration
            for declaration in self.declarations
            if declaration.relation is ResearchRelation.DEFINES
        )

    @property
    def implements(self) -> tuple[ResearchDeclaration, ...]:
        """Return all IMPLEMENTS declarations."""
        return tuple(
            declaration
            for declaration in self.declarations
            if declaration.relation is ResearchRelation.IMPLEMENTS
        )

    @property
    def valid(self) -> bool:
        """Return whether extraction produced no error diagnostics."""
        return not any(
            diagnostic.severity is DiagnosticSeverity.ERROR
            for diagnostic in self.diagnostics
        )

defines property

defines: tuple[ResearchDeclaration, ...]

Return all DEFINES declarations.

implements property

implements: tuple[ResearchDeclaration, ...]

Return all IMPLEMENTS declarations.

valid property

valid: bool

Return whether extraction produced no error diagnostics.

RepositoryContext dataclass

Identity and revision of the repository being examined.

Source code in src/reactive_research/models.py
69
70
71
72
73
74
75
76
@dataclass(frozen=True)
class RepositoryContext:
    """Identity and revision of the repository being examined."""

    root: Path
    organization: str | None
    name: str
    revision: str | None

ResearchDeclaration dataclass

One typed relationship to an addressable research object.

Source code in src/reactive_research/models.py
60
61
62
63
64
65
66
@dataclass(frozen=True)
class ResearchDeclaration:
    """One typed relationship to an addressable research object."""

    relation: ResearchRelation
    identifier: ResearchIdentifier
    source: SourceLocation

ResearchIdentifier dataclass

Stable identifier for one addressable research object.

Source code in src/reactive_research/models.py
41
42
43
44
45
46
47
48
49
@dataclass(frozen=True)
class ResearchIdentifier:
    """Stable identifier for one addressable research object."""

    value: str

    def __str__(self) -> str:
        """Return the canonical identifier string."""
        return self.value

__str__

__str__() -> str

Return the canonical identifier string.

Source code in src/reactive_research/models.py
47
48
49
def __str__(self) -> str:
    """Return the canonical identifier string."""
    return self.value

ResearchRelation

Bases: StrEnum

Supported relationships between repositories and research objects.

Source code in src/reactive_research/models.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class ResearchRelation(StrEnum):
    """Supported relationships between repositories and research objects."""

    DEFINES = "DEFINES"
    IMPLEMENTS = "IMPLEMENTS"
    DEPENDS = "DEPENDS"
    FORMALIZES = "FORMALIZES"
    SPECIFIES = "SPECIFIES"
    TESTS = "TESTS"
    PILOTS = "PILOTS"
    EVALUATES = "EVALUATES"
    CITES = "CITES"
    FREEZES = "FREEZES"
    DERIVES_FROM = "DERIVES_FROM"
    INFORMS = "INFORMS"
    REVISES = "REVISES"
    SUPERSEDES = "SUPERSEDES"
    CONTRIBUTES_TO = "CONTRIBUTES_TO"
    SHOULD_REVALIDATE = "SHOULD_REVALIDATE"
    EVIDENCES = "EVIDENCES"

SourceLocation dataclass

Location of one declaration in repository source.

Source code in src/reactive_research/models.py
52
53
54
55
56
57
@dataclass(frozen=True)
class SourceLocation:
    """Location of one declaration in repository source."""

    path: Path
    line: int

Identifiers

reactive_research.identifiers

Research-object identifier parsing and validation.

Examples: SE-210.Definition.2.4 SE-210.Definition.4.3 SE-210.Theorem.5.2 SE-210.Proposition.4.14 SE-210.Example.4.11 SE-210.Remark.4.16c

InvalidResearchIdentifierError

Bases: ValueError

Raised when a research-object identifier is malformed.

Source code in src/reactive_research/identifiers.py
26
27
class InvalidResearchIdentifierError(ValueError):
    """Raised when a research-object identifier is malformed."""

parse_research_identifier

parse_research_identifier(value: str) -> ResearchIdentifier

Parse and validate a research-object identifier.

Source code in src/reactive_research/identifiers.py
30
31
32
33
34
35
36
37
38
39
40
41
42
def parse_research_identifier(value: str) -> ResearchIdentifier:
    """Parse and validate a research-object identifier."""
    normalized = value.strip()

    if not normalized:
        raise InvalidResearchIdentifierError("Research identifier must not be empty.")

    if not _IDENTIFIER_PATTERN.fullmatch(normalized):
        raise InvalidResearchIdentifierError(
            f"Invalid research identifier: {normalized!r}"
        )

    return ResearchIdentifier(normalized)

Repository Discovery

reactive_research.repository

Repository discovery for Reactive Research.

discover_repository_context

discover_repository_context(
    path: Path,
) -> RepositoryContext

Discover repository identity and revision.

Source code in src/reactive_research/repository.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
def discover_repository_context(path: Path) -> RepositoryContext:
    """Discover repository identity and revision."""
    root = path.resolve()

    organization: str | None = None
    name = root.name

    manifest_path = _find_manifest(root)
    if manifest_path is not None:
        manifest = _load_toml(manifest_path)

        repository = manifest.get("repository")
        if isinstance(repository, dict):
            repository_name = repository.get("name")
            repository_organization = repository.get("organization")

            if isinstance(repository_name, str) and repository_name:
                name = repository_name

            if isinstance(repository_organization, str) and repository_organization:
                organization = repository_organization

        # Compatibility with older SE manifests.
        repo = manifest.get("repo")
        if isinstance(repo, dict):
            repository_name = repo.get("name")
            if isinstance(repository_name, str) and repository_name:
                name = repository_name

    return RepositoryContext(
        root=root,
        organization=organization,
        name=name,
        revision=_git_revision(root),
    )

Extraction

reactive_research.extract

Extract Reactive Research declarations.

Reactive Research annotations may be provided in any source file with an eligible suffix.

extract_repository

extract_repository(path: Path) -> ExtractionResult

Extract Reactive Research declarations from one repository.

Source code in src/reactive_research/extract.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def extract_repository(path: Path) -> ExtractionResult:
    """Extract Reactive Research declarations from one repository."""
    repository = discover_repository_context(path)

    declarations: list[ResearchDeclaration] = []
    diagnostics: list[Diagnostic] = []

    for source_path in _source_files(repository.root):
        source_declarations, source_diagnostics = _extract_file(
            source_path,
            root=repository.root,
        )
        declarations.extend(source_declarations)
        diagnostics.extend(source_diagnostics)

    diagnostics.extend(_duplicate_definition_diagnostics(declarations))

    return ExtractionResult(
        repository=repository,
        declarations=tuple(declarations),
        diagnostics=tuple(diagnostics),
    )

extract_research

extract_research(
    *, path: Path, check: bool = False
) -> dict[str, Any]

Extract declarations and return the normalized CLI representation.

Source code in src/reactive_research/extract.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def extract_research(
    *,
    path: Path,
    check: bool = False,
) -> dict[str, Any]:
    """Extract declarations and return the normalized CLI representation."""
    result = extract_repository(path)
    document = declaration_document(result)

    return {
        "command": "extract",
        "check": check,
        **document,
    }

extract_source_text

extract_source_text(
    text: str, *, path: Path
) -> tuple[list[ResearchDeclaration], list[Diagnostic]]

Apply existing annotation normalization to observed or historical text.

Source code in src/reactive_research/extract.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def extract_source_text(
    text: str,
    *,
    path: Path,
) -> tuple[list[ResearchDeclaration], list[Diagnostic]]:
    """Apply existing annotation normalization to observed or historical text."""
    declarations: list[ResearchDeclaration] = []
    diagnostics: list[Diagnostic] = []
    pattern = _ANNOTATION_PATTERNS.get(path.suffix.lower())
    if pattern is None:
        return declarations, diagnostics
    relative_path = path

    for line_number, line in enumerate(
        text.splitlines(),
        start=1,
    ):
        match = pattern.fullmatch(line)
        if match is None:
            continue

        location = SourceLocation(
            path=relative_path,
            line=line_number,
        )

        raw_relation = match.group("relation").upper().replace("-", "_")
        if raw_relation == "DEPENDS_ON":
            raw_relation = "DEPENDS"

        try:
            relation = ResearchRelation(raw_relation)
        except ValueError:
            diagnostics.append(
                Diagnostic(
                    code="RR.UNSUPPORTED_RELATION",
                    message=(
                        f"Unsupported Reactive Research relationship: {raw_relation!r}."
                    ),
                    severity=DiagnosticSeverity.ERROR,
                    source=location,
                )
            )
            continue

        raw_identifier = match.group("identifier").strip()

        try:
            identifier = parse_research_identifier(raw_identifier)
        except InvalidResearchIdentifierError as error:
            diagnostics.append(
                Diagnostic(
                    code="RR.INVALID_IDENTIFIER",
                    message=str(error),
                    severity=DiagnosticSeverity.ERROR,
                    source=location,
                )
            )
            continue

        declarations.append(
            ResearchDeclaration(
                relation=relation,
                identifier=identifier,
                source=location,
            )
        )

    return declarations, diagnostics

Validation

reactive_research.validate

Validate repository-local Reactive Research declarations.

validate_extraction

validate_extraction(
    extraction: ExtractionResult, *, strict: bool = False
) -> tuple[Diagnostic, ...]

Validate one previously extracted repository result.

Source code in src/reactive_research/validate.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
 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
def validate_extraction(
    extraction: ExtractionResult,
    *,
    strict: bool = False,
) -> tuple[Diagnostic, ...]:
    """Validate one previously extracted repository result."""
    del strict

    diagnostics = list(extraction.diagnostics)

    repository = extraction.repository

    if not repository.name.strip():
        diagnostics.append(
            Diagnostic(
                code="RR.MISSING_REPOSITORY_NAME",
                message="Repository name must not be empty.",
                severity=DiagnosticSeverity.ERROR,
            )
        )

    if extraction.declarations and repository.revision is None:
        diagnostics.append(
            Diagnostic(
                code="RR.MISSING_REVISION",
                message=(
                    "Repository contains Reactive Research declarations "
                    "but no Git revision could be determined."
                ),
                severity=DiagnosticSeverity.WARNING,
            )
        )

    for declaration in extraction.declarations:
        if declaration.source.path.is_absolute():
            diagnostics.append(
                Diagnostic(
                    code="RR.ABSOLUTE_SOURCE_PATH",
                    message=("Declaration source paths must be repository-relative."),
                    severity=DiagnosticSeverity.ERROR,
                    source=declaration.source,
                )
            )

        if declaration.source.line < 1:
            diagnostics.append(
                Diagnostic(
                    code="RR.INVALID_SOURCE_LINE",
                    message=("Declaration source line must be greater than zero."),
                    severity=DiagnosticSeverity.ERROR,
                    source=declaration.source,
                )
            )

        try:
            parse_research_identifier(str(declaration.identifier))
        except InvalidResearchIdentifierError as error:
            diagnostics.append(
                Diagnostic(
                    code="RR.INVALID_IDENTIFIER",
                    message=str(error),
                    severity=DiagnosticSeverity.ERROR,
                    source=declaration.source,
                )
            )

    return tuple(diagnostics)

validate_research

validate_research(
    *, path: Path, strict: bool = False
) -> dict[str, Any]

Validate repository-local Reactive Research declarations.

Source code in src/reactive_research/validate.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
def validate_research(
    *,
    path: Path,
    strict: bool = False,
) -> dict[str, Any]:
    """Validate repository-local Reactive Research declarations."""
    extraction = extract_repository(path)
    diagnostics = validate_extraction(
        extraction,
        strict=strict,
    )

    document = declaration_document(extraction)

    valid = _diagnostics_are_valid(
        diagnostics,
        strict=strict,
    )

    return {
        "command": "validate",
        "path": str(extraction.repository.root),
        "repository": extraction.repository.name,
        "organization": extraction.repository.organization,
        "revision": extraction.repository.revision,
        "strict": strict,
        "valid": valid,
        "declaration_count": len(extraction.declarations),
        "declarations": document["declarations"],
        "diagnostics": [diagnostic_record(diagnostic) for diagnostic in diagnostics],
    }

Declaration Export

reactive_research.declarations

Normalized declaration documents for Reactive Research.

declaration_document

declaration_document(
    result: ExtractionResult,
    *,
    extractor_version: str | None = None,
) -> dict[str, Any]

Return a normalized declaration document.

Source code in src/reactive_research/declarations.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
63
64
def declaration_document(
    result: ExtractionResult,
    *,
    extractor_version: str | None = None,
) -> dict[str, Any]:
    """Return a normalized declaration document."""
    current_version = extractor_version or package_version()
    repository = result.repository

    return {
        "format": _DECLARATION_FORMAT,
        "format_version": _DECLARATION_FORMAT_VERSION,
        "extractor_version": current_version,
        "path": str(repository.root),
        "repository": {
            "organization": repository.organization,
            "name": repository.name,
            "revision": repository.revision,
        },
        "valid": result.valid,
        "declarations": [
            declaration_record(
                declaration,
                organization=repository.organization,
                repository=repository.name,
                revision=repository.revision,
                extractor_version=current_version,
            )
            for declaration in result.declarations
        ],
        "diagnostics": [
            diagnostic_record(diagnostic) for diagnostic in result.diagnostics
        ],
    }

declaration_record

declaration_record(
    declaration: ResearchDeclaration,
    *,
    organization: str | None,
    repository: str,
    revision: str | None,
    extractor_version: str,
) -> dict[str, object]

Return one normalized research declaration.

Source code in src/reactive_research/declarations.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def declaration_record(
    declaration: ResearchDeclaration,
    *,
    organization: str | None,
    repository: str,
    revision: str | None,
    extractor_version: str,
) -> dict[str, object]:
    """Return one normalized research declaration."""
    source_path = declaration.source.path

    return {
        "identifier": str(declaration.identifier),
        "relation": declaration.relation.value,
        "organization": organization,
        "repository": repository,
        "revision": revision,
        "source_path": source_path.as_posix(),
        "source_line": declaration.source.line,
        "source_kind": _source_kind(source_path),
        "extractor_version": extractor_version,
    }

diagnostic_record

diagnostic_record(
    diagnostic: Diagnostic,
) -> dict[str, object]

Return one normalized diagnostic.

Source code in src/reactive_research/declarations.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def diagnostic_record(
    diagnostic: Diagnostic,
) -> dict[str, object]:
    """Return one normalized diagnostic."""
    source_path: str | None = None
    source_line: int | None = None

    if diagnostic.source is not None:
        source_path = diagnostic.source.path.as_posix()
        source_line = diagnostic.source.line

    return {
        "code": diagnostic.code,
        "severity": diagnostic.severity.value,
        "message": diagnostic.message,
        "source_path": source_path,
        "source_line": source_line,
    }

export_declarations

export_declarations(path: Path) -> dict[str, Any]

Extract and export normalized declarations for one repository.

Source code in src/reactive_research/declarations.py
21
22
23
24
25
26
27
28
def export_declarations(path: Path) -> dict[str, Any]:
    """Extract and export normalized declarations for one repository."""
    # WHY: Local import avoids a module cycle because extract.py uses
    # declaration_document() for its machine-readable result.
    from reactive_research.extract import extract_repository

    result = extract_repository(path)
    return declaration_document(result)

is_declaration_document

is_declaration_document(value: object) -> bool

Return whether a value has the normalized declaration-document shape.

Source code in src/reactive_research/declarations.py
111
112
113
114
115
116
117
118
119
120
def is_declaration_document(value: object) -> bool:
    """Return whether a value has the normalized declaration-document shape."""
    if not isinstance(value, dict):
        return False

    return (
        value.get("format") == _DECLARATION_FORMAT
        and value.get("format_version") == _DECLARATION_FORMAT_VERSION
        and isinstance(value.get("declarations"), list)
    )

Resolution

reactive_research.resolve

Resolve Reactive Research identifiers.

RegistryLoadError

Bases: ValueError

Raised when declaration registry input cannot be loaded.

Source code in src/reactive_research/resolve.py
24
25
class RegistryLoadError(ValueError):
    """Raised when declaration registry input cannot be loaded."""

resolve_research

resolve_research(
    *,
    path: Path,
    identifier: str | None,
    resolve_all: bool,
    registry: str | None,
    snapshot: str | None,
) -> dict[str, Any]

Resolve research-object references.

Source code in src/reactive_research/resolve.py
 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
 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def resolve_research(
    *,
    path: Path,
    identifier: str | None,
    resolve_all: bool,
    registry: str | None,
    snapshot: str | None,
) -> dict[str, Any]:
    """Resolve research-object references."""
    if snapshot is not None:
        from reactive_research.snapshot import load_snapshot

        graph = load_snapshot(snapshot, registry)
        if identifier is not None:
            try:
                identifier = str(parse_research_identifier(identifier))
            except InvalidResearchIdentifierError as error:
                return {
                    "command": "resolve",
                    "resolved": False,
                    "results": [],
                    "snapshot_id": graph["snapshot_id"],
                    "diagnostics": [
                        {
                            "code": "RR.INVALID_IDENTIFIER",
                            "severity": "error",
                            "message": str(error),
                        }
                    ],
                }
        definitions = {
            node["label"]: node.get("definitions", [])
            for node in graph["nodes"]
            if node["kind"] == "object"
        }
        targets = (
            [identifier]
            if identifier is not None
            else sorted(
                {
                    edge["target"].removeprefix("object:")
                    for edge in graph["edges"]
                    if resolve_all
                    and edge["relation"] == "implements"
                    and edge["target"].startswith("object:")
                }
            )
        )
        results = [
            _resolve_identifier(target, definitions=definitions) for target in targets
        ]
        return {
            "command": "resolve",
            "path": str(path.resolve()),
            "identifier": identifier,
            "resolve_all": resolve_all,
            "registry": registry,
            "snapshot": snapshot,
            "resolved": all(result["status"] == "resolved" for result in results),
            "results": results,
            "diagnostics": [],
            "snapshot_id": graph["snapshot_id"],
        }

    current_document = export_declarations(path)
    try:
        registry_documents = _load_registry_documents(
            registry,
            current_document=current_document,
        )
    except RegistryLoadError as error:
        return {
            "command": "resolve",
            "path": str(path.resolve()),
            "identifier": identifier,
            "resolve_all": resolve_all,
            "registry": registry,
            "snapshot": snapshot,
            "resolved": False,
            "results": [],
            "diagnostics": [
                {
                    "code": "RR.REGISTRY_LOAD_ERROR",
                    "severity": "error",
                    "message": str(error),
                }
            ],
        }

    targets, target_error = _resolution_targets(
        current_document=current_document,
        identifier=identifier,
        resolve_all=resolve_all,
    )

    if target_error is not None:
        return {
            "command": "resolve",
            "path": str(path.resolve()),
            "identifier": identifier,
            "resolve_all": resolve_all,
            "registry": registry,
            "snapshot": snapshot,
            "resolved": False,
            "results": [],
            "diagnostics": [target_error],
        }

    declarations = _registry_declarations(registry_documents)

    definitions = _definitions_by_identifier(declarations)

    results = [
        _resolve_identifier(
            target,
            definitions=definitions,
        )
        for target in targets
    ]

    resolved = all(result["status"] == "resolved" for result in results)

    return {
        "command": "resolve",
        "path": str(path.resolve()),
        "identifier": identifier,
        "resolve_all": resolve_all,
        "registry": registry,
        "snapshot": snapshot,
        "resolved": resolved,
        "results": results,
        "diagnostics": [],
    }

Graph

reactive_research.graph

Build and query Reactive Research graphs.

build_research_graph

build_research_graph(
    *,
    path: Path,
    target: str | None,
    view: GraphView,
    registry: str | None,
    snapshot: str | None,
) -> dict[str, Any]

Build or inspect a typed Reactive Research graph.

Source code in src/reactive_research/graph.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def build_research_graph(
    *,
    path: Path,
    target: str | None,
    view: GraphView,
    registry: str | None,
    snapshot: str | None,
) -> dict[str, Any]:
    """Build or inspect a typed Reactive Research graph."""
    graph = (
        load_snapshot(snapshot, registry)
        if snapshot
        else observe_workspace(path, registry=registry)
    )
    return graph_projection(graph, view=view, target=target)

graph_projection

graph_projection(
    graph: dict[str, Any],
    *,
    view: GraphView = "objects",
    target: str | None = None,
) -> dict[str, Any]

Derive an object graph or repository projection without new declarations.

Source code in src/reactive_research/graph.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
53
54
55
56
57
58
59
60
61
62
63
64
65
def graph_projection(
    graph: dict[str, Any], *, view: GraphView = "objects", target: str | None = None
) -> dict[str, Any]:
    """Derive an object graph or repository projection without new declarations."""
    nodes = {n["id"]: n for n in graph["nodes"]}
    edges = graph["edges"]
    if view == "repositories":

        def owner(identifier: str) -> str:
            node = nodes[identifier]
            if node.get("lifecycle") in {"frozen", "frozen-record", "protected"}:
                return identifier
            definitions = node.get("definitions", [])
            if len(definitions) == 1 and definitions[0].get("project") in nodes:
                return definitions[0]["project"]
            return node.get("project", identifier)

        edges = [
            {
                **e,
                "source": owner(e["source"]),
                "target": owner(e["target"]),
                "observed_source": e["source"],
                "observed_target": e["target"],
            }
            for e in edges
            if owner(e["source"]) != owner(e["target"])
        ]
        used = {e[k] for e in edges for k in ("source", "target")}
        nodes = {
            k: n for k, n in nodes.items() if n["kind"] == "repository" or k in used
        }
    if target is not None:
        selected = select_node({"nodes": list(nodes.values())}, target)["id"]
        adjacent = {selected}
        adjacent.update(
            e[k]
            for e in edges
            if selected in (e["source"], e["target"])
            for k in ("source", "target")
        )
        nodes = {k: n for k, n in nodes.items() if k in adjacent}
        edges = [e for e in edges if e["source"] in nodes and e["target"] in nodes]
    return {
        "command": "graph",
        "snapshot_id": graph["snapshot_id"],
        "view": view,
        "nodes": sorted(nodes.values(), key=lambda n: n["id"]),
        "edges": edges,
    }

mermaid_graph

mermaid_graph(
    graph: dict[str, Any], *, category: str = "propagation"
) -> str

Render deterministic Mermaid directly from the shared JSON graph boundary.

Source code in src/reactive_research/graph.py
 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
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
139
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
166
167
168
169
170
171
172
173
174
def mermaid_graph(graph: dict[str, Any], *, category: str = "propagation") -> str:
    """Render deterministic Mermaid directly from the shared JSON graph boundary."""
    if category not in {"evolution", "propagation", "impact"}:
        raise ValueError(f"Unknown graph category: {category}")
    evolution = CONTEXT | {"formalizes", "implements", "pilots", "evaluates", "freezes"}
    allowed = evolution if category == "evolution" else PROPAGATING | {"freezes"}
    edges = [
        e for e in graph["edges"] if category == "impact" or e["relation"] in allowed
    ]
    used = {e[k] for e in edges for k in ("source", "target")}
    if category == "impact":
        used.update(n["id"] for n in graph["nodes"])
    nodes = sorted(
        (n for n in graph["nodes"] if n["id"] in used), key=lambda n: n["id"]
    )
    names = {n["id"]: f"n{i}" for i, n in enumerate(nodes)}

    def escape(value: object) -> str:
        return (
            str(value)
            .replace("&", "&amp;")
            .replace('"', "&quot;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("|", "&#124;")
            .replace("\n", " ")
        )

    lines = [
        "flowchart LR",
        "  %% Typed arrows read source --relation--> target. Dependency impact follows reverse arrows; influence/protection follows forward arrows.",
    ]
    dispositions: dict[str, set[str]] = {}
    for obligation in graph.get("obligations", []):
        dispositions.setdefault(obligation["consumer"]["id"], set()).add(
            obligation["disposition"]
        )
    for node in nodes:
        state = node.get("state", {})
        revision = (state.get("source_revision") or "")[:8]
        label = f"{node['label']} [{state.get('mode', node.get('resolution', 'observed'))} {revision}]"
        if node.get("declared_version"):
            label += f" / declared {node['declared_version']}"
        if state.get("commit_time"):
            label += " / commit " + state["commit_time"][:10]
        lines.append(f'  {names[node["id"]]}["{escape(label)}"]')
        disposition = dispositions.get(node["id"], set())
        if disposition:
            lines[-1] = (
                f'  {names[node["id"]]}["{escape(label + " / " + ", ".join(sorted(disposition)))}"]'
            )
        style = "ordinary"
        if node.get("lifecycle") in {"frozen", "frozen-record", "protected"}:
            style = "protected"
        elif node["id"] == graph.get("identifier"):
            style = "changed"
        elif "mechanical candidate" in disposition:
            style = "mechanical"
        elif "semantic review" in disposition:
            style = "semantic"
        elif "verification required" in disposition:
            style = "verification"
        elif node["kind"] == "unresolved":
            style = "unresolved"
        lines.append(f"  class {names[node['id']]} {style}")
    groups: dict[tuple[str, ...], list[dict[str, Any]]] = {}
    for edge in edges:
        constraint = edge.get("constraint", {})
        key = (
            edge["source"],
            edge["target"],
            edge["relation"],
            edge["kind"],
            str(
                constraint.get("requested_revision") or constraint.get("version") or ""
            ),
            edge.get("resolution", "unresolved"),
        )
        groups.setdefault(key, []).append(edge)
    for key in sorted(groups):
        matches = groups[key]
        edge = matches[0]
        label = f"{edge['relation']} / {edge['kind']}"
        constraint = edge.get("constraint", {})
        pin = constraint.get("requested_revision") or constraint.get("version")
        if pin:
            label += f" / {pin}"
        if edge.get("resolution") != "resolved":
            label += f" / {edge.get('resolution')}"
        if len(matches) > 1:
            label += f" / {len(matches)} evidence edges"
        arrow = "-.->" if edge["relation"] in CONTEXT else "-->"
        lines.append(
            f'  {names[edge["source"]]} {arrow}|"{escape(label)}"| {names[edge["target"]]}'
        )
    lines.extend(
        [
            "  classDef changed fill:#fde68a,stroke:#92400e,stroke-width:3px",
            "  classDef protected fill:#fecaca,stroke:#991b1b,stroke-width:3px",
            "  classDef mechanical fill:#bfdbfe,stroke:#1d4ed8",
            "  classDef semantic fill:#e9d5ff,stroke:#7e22ce",
            "  classDef verification fill:#bbf7d0,stroke:#166534",
            "  classDef unresolved fill:#e5e7eb,stroke:#4b5563,stroke-dasharray:5 5",
            "  classDef ordinary fill:#f8fafc,stroke:#64748b",
        ]
    )
    return "\n".join(lines)

Impact Analysis

reactive_research.impact

Analyze downstream Reactive Research impact.

analyze_impact

analyze_impact(
    *,
    path: Path,
    identifier: str,
    depth: ImpactDepth,
    registry: str | None,
    snapshot: str | None,
    from_snapshot: str | None,
    to_snapshot: str | None,
    relations: set[str] | None = None,
) -> dict[str, Any]

Identify downstream objects potentially affected by a change.

Source code in src/reactive_research/impact.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def analyze_impact(
    *,
    path: Path,
    identifier: str,
    depth: ImpactDepth,
    registry: str | None,
    snapshot: str | None,
    from_snapshot: str | None,
    to_snapshot: str | None,
    relations: set[str] | None = None,
) -> dict[str, Any]:
    """Identify downstream objects potentially affected by a change."""
    selected = to_snapshot or snapshot
    graph = (
        load_snapshot(selected, registry)
        if selected
        else observe_workspace(path, registry=registry)
    )
    previous = load_snapshot(from_snapshot, registry) if from_snapshot else None
    return impact_obligations(
        graph, identifier, previous=previous, depth=depth, relations=relations
    )

impact_obligations

impact_obligations(
    graph: dict[str, Any],
    identifier: str,
    *,
    previous: dict[str, Any] | None = None,
    depth: ImpactDepth = "transitive",
    relations: set[str] | None = None,
) -> dict[str, Any]

Calculate bounded typed obligations without proposing or applying edits.

Source code in src/reactive_research/impact.py
 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
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
139
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
166
167
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def impact_obligations(
    graph: dict[str, Any],
    identifier: str,
    *,
    previous: dict[str, Any] | None = None,
    depth: ImpactDepth = "transitive",
    relations: set[str] | None = None,
) -> dict[str, Any]:
    """Calculate bounded typed obligations without proposing or applying edits."""
    selected = PROPAGATING if relations is None else frozenset(relations)
    unknown = selected - PROPAGATING - CONTEXT - {"freezes"}
    if unknown:
        raise ValueError(f"Unsupported impact relationships: {sorted(unknown)}")
    nodes = {n["id"]: n for n in graph["nodes"]}
    source = select_node(graph, identifier)
    old_source = next(
        (n for n in (previous or {}).get("nodes", []) if n["id"] == source["id"]), None
    )
    changed = old_source != source if previous is not None else None
    obligations: list[dict[str, Any]] = []
    queue = deque([(source["id"], [], 0)])
    visited = {source["id"]}
    reached = {source["id"]}
    traversed: dict[str, dict[str, Any]] = {}

    def add(
        consumer: dict[str, Any],
        edge: dict[str, Any],
        chain: list[str],
        level: int,
        disposition: str,
        reason: str,
        reach: str = "impact",
    ) -> None:
        record = {
            "changed_source": source,
            "previous_source": old_source,
            "consumer": consumer,
            "relationship": edge["relation"],
            "edge": edge,
            "evidence": edge["evidence"],
            "constraints": edge["constraint"],
            "path": chain,
            "distance": level,
            "reach": reach,
            "disposition": disposition,
            "reason": reason,
            "lifecycle_constraints": {
                "source": source.get("lifecycle"),
                "consumer": consumer.get("lifecycle"),
                "protection": consumer.get("protection"),
                "authority": "Human review determines scientific validity and reconciliation.",
            },
        }
        obligations.append({"id": "obligation:" + digest(record), **record})

    if changed is not False:
        while queue:
            current, chain, level = queue.popleft()
            for edge in graph["edges"]:
                if edge["relation"] not in selected:
                    continue
                if edge["relation"] in FORWARD:
                    if edge["source"] != current:
                        continue
                    consumer_id = edge["target"]
                else:
                    if edge["target"] != current:
                        continue
                    consumer_id = edge["source"]
                if consumer_id == source["id"]:
                    continue
                consumer = nodes[consumer_id]
                new_chain = chain + [edge["id"]]
                reached.add(consumer_id)
                traversed[edge["id"]] = edge
                protected = consumer.get("lifecycle") in {
                    "frozen",
                    "frozen-record",
                    "protected",
                }
                if protected:
                    disposition = "frozen/protected — do not modify"
                    reason = "DO NOT MODIFY FROZEN EVIDENCE. Assess successor work under a new explicit freeze."
                elif (
                    edge["resolution"] != "resolved" or consumer["kind"] == "unresolved"
                ):
                    disposition = "unresolved"
                    reason = "Resolve the identity or ambiguous definition before interpreting impact."
                elif edge["kind"] == "build":
                    disposition = "verification required"
                    reason = "Recheck the selected dependency revision, imports and consumer verification; no automatic update."
                elif edge["relation"] in {
                    "tests",
                    "evaluates",
                    "pilots",
                    "should-revalidate",
                }:
                    disposition = "verification required"
                    reason = "Review whether verification must be rerun under the changed source state."
                else:
                    disposition = "semantic review"
                    reason = "Review the declared research relationship; matching terminology does not establish equivalence."
                    if edge["relation"] in CONTEXT:
                        reason = "Context/provenance notice only. Historical citation remains valid provenance; no build or update requirement."
                add(consumer, edge, new_chain, level + 1, disposition, reason)
                if (
                    edge["kind"] == "build"
                    and not protected
                    and disposition != "unresolved"
                ):
                    target = nodes[edge["target"]]
                    pinned = edge["constraint"].get("resolved_revision")
                    head = target.get("state", {}).get("source_revision")
                    if pinned and head and pinned != head:
                        add(
                            consumer,
                            edge,
                            new_chain,
                            level + 1,
                            "mechanical candidate",
                            "PENDING MECHANICAL PROPAGATION: lock selects a different committed revision. Review intentional pinning before proposing a successor pin.",
                        )
                    add(
                        consumer,
                        edge,
                        new_chain,
                        level + 1,
                        "semantic review",
                        "PENDING SEMANTIC REVIEW: determine whether the dependency change affects definitions actually used; build success cannot settle this.",
                    )
                if (
                    depth == "transitive"
                    and not protected
                    and disposition != "unresolved"
                    and edge["relation"] not in CONTEXT
                    and consumer_id not in visited
                ):
                    visited.add(consumer_id)
                    queue.append((consumer_id, new_chain, level + 1))

        # Protect scoped frozen members when their owner is reached. These are
        # guard notices, not invented semantic/build dependencies or propagation.
        owner_ids = reached | {nodes[n].get("project") for n in reached}
        for edge in graph["edges"]:
            if (
                edge["relation"] == "freezes"
                and nodes[edge["target"]].get("project") in owner_ids
            ):
                member = nodes[edge["target"]]
                if not any(
                    o["consumer"]["id"] == member["id"]
                    and o["disposition"].startswith("frozen/")
                    for o in obligations
                ):
                    add(
                        member,
                        edge,
                        [],
                        0,
                        "frozen/protected — do not modify",
                        "DO NOT MODIFY FROZEN EVIDENCE. Owner context is under review; this hash-committed member remains protected.",
                        "protection-boundary",
                    )
                    traversed[edge["id"]] = edge
                    reached.update((edge["source"], edge["target"]))
        for diagnostic in graph["diagnostics"]:
            if (
                diagnostic.get("code") == "RR.TECHNICAL_EDGE_NOT_IN_MANIFEST"
                and diagnostic.get("project") in reached
            ):
                consumer = nodes[diagnostic["project"]]
                edge = next(
                    (
                        e
                        for e in graph["edges"]
                        if e["source"] == consumer["id"]
                        and e.get("declared_target") == diagnostic["target"]
                        and e["kind"] == "build"
                    ),
                    None,
                )
                if edge and edge["target"] in reached:
                    add(
                        consumer,
                        edge,
                        [edge["id"]],
                        1,
                        "mechanical candidate",
                        "PENDING MECHANICAL PROPAGATION: existing Lake edge is missing from SE manifest graph visibility; review declaration alignment, without changing theory.",
                    )
    return {
        "command": "impact",
        "format_version": 1,
        "snapshot_id": graph["snapshot_id"],
        "previous_snapshot_id": previous.get("snapshot_id") if previous else None,
        "identifier": source["id"],
        "source": source,
        "change_detected": changed,
        "change_basis": "snapshot comparison"
        if previous
        else "caller-selected change scenario; not evidence of a newly observed change",
        "selected_relations": sorted(selected),
        "depth": depth,
        "obligations": sorted(
            {o["id"]: o for o in obligations}.values(), key=canonical
        ),
        "nodes": sorted((nodes[n] for n in reached), key=lambda n: n["id"]),
        "edges": sorted(traversed.values(), key=lambda e: e["id"]),
    }

select_node

select_node(
    graph: dict[str, Any], identifier: str
) -> dict[str, Any]

Resolve a node ID or an unambiguous observed label.

Source code in src/reactive_research/impact.py
39
40
41
42
43
44
45
46
47
48
def select_node(graph: dict[str, Any], identifier: str) -> dict[str, Any]:
    """Resolve a node ID or an unambiguous observed label."""
    matches = [
        n for n in graph["nodes"] if n["id"] == identifier or n["label"] == identifier
    ]
    if len(matches) != 1:
        raise ValueError(
            f"Expected one observed node for {identifier!r}; found {len(matches)}. Use a node ID."
        )
    return matches[0]

Snapshots

reactive_research.snapshot

Deterministic, content-addressed observations of existing research surfaces.

load_snapshot

load_snapshot(
    reference: str, registry: str | None = None
) -> dict[str, Any]

Load and integrity-check a snapshot file or registry content-addressed ID.

Source code in src/reactive_research/snapshot.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def load_snapshot(reference: str, registry: str | None = None) -> dict[str, Any]:
    """Load and integrity-check a snapshot file or registry content-addressed ID."""
    path = Path(reference)
    if reference.startswith("sha256:"):
        if registry is None:
            raise ValueError("Resolving a snapshot ID requires --registry DIR.")
        path = Path(registry) / (reference.removeprefix("sha256:") + ".json")
    value = json.loads(path.read_text(encoding="utf-8"))
    if (
        not isinstance(value, dict)
        or value.get("format") != FORMAT
        or value.get("format_version") != FORMAT_VERSION
    ):
        raise ValueError("Not a supported Reactive Research observation snapshot.")
    payload = {k: v for k, v in value.items() if k != "snapshot_id"}
    if value.get("snapshot_id") != "sha256:" + digest(payload):
        raise ValueError(
            "Snapshot content does not match its content-addressed identifier."
        )
    return value

observe_workspace

observe_workspace(
    path: Path,
    *,
    revisions: dict[str, str] | None = None,
    registry: str | None = None,
) -> dict[str, Any]

Observe discovered projects, optionally substituting named committed trees.

Source code in src/reactive_research/snapshot.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
 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
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
139
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
166
167
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def observe_workspace(
    path: Path, *, revisions: dict[str, str] | None = None, registry: str | None = None
) -> dict[str, Any]:
    """Observe discovered projects, optionally substituting named committed trees."""
    root = path.resolve()
    nodes: dict[str, dict[str, Any]] = {}
    edges: list[dict[str, Any]] = []
    declarations: list[dict[str, Any]] = []
    diagnostics: list[dict[str, Any]] = []
    aliases: dict[str, set[str]] = {}
    discovered = discover_projects(root)
    unknown = set(revisions or {}) - {
        p.relative_to(root).as_posix() for p in discovered
    }
    if unknown:
        raise ValueError(
            f"Revision selections do not identify discovered roots: {sorted(unknown)}"
        )
    for project_root in discovered:
        relative = project_root.relative_to(root).as_posix()
        pid = "repo:" + relative
        data, state = read_project(project_root, (revisions or {}).get(relative))
        manifest_name = next(
            (
                n
                for n in ("SE_MANIFEST.toml", "MANIFEST.toml", "se-manifest.toml")
                if n in data
            ),
            None,
        )
        manifest = toml(data, manifest_name, diagnostics) if manifest_name else {}
        identity = manifest.get("repository", manifest.get("repo", {}))
        if not isinstance(identity, dict):
            identity = {}
        lake = toml(data, "lakefile.toml", diagnostics)
        python = toml(data, "pyproject.toml", diagnostics).get("project", {})
        name = identity.get("name") or project_root.name
        node = {
            "id": pid,
            "kind": "repository",
            "label": name,
            "name": name,
            "path": relative,
            "organization": identity.get("organization"),
            "class": identity.get("class"),
            "lifecycle": identity.get("status", "unspecified"),
            "state": state,
            "manifest": manifest_name,
            "declared_version": identity.get(
                "version", lake.get("version", python.get("version"))
            ),
        }
        nodes[pid] = node
        for alias in (name, project_root.name, lake.get("name"), python.get("name")):
            if isinstance(alias, str):
                aliases.setdefault(alias, set()).add(pid)
        found, relationships, records, errors = observe_surfaces(node, data)
        for candidate in found:
            nid = candidate["id"]
            if nid in nodes and candidate["kind"] == "object":
                nodes[nid]["definitions"].extend(candidate["definitions"])
            else:
                nodes[nid] = candidate
        edges.extend(relationships)
        declarations.extend(records)
        diagnostics.extend(errors)

    if registry is not None:
        # Reuse repository-published declarations rather than a master list.
        from reactive_research.resolve import _load_declaration_file

        location = Path(registry)
        files = [location] if location.is_file() else sorted(location.glob("*.json"))
        if not files:
            raise ValueError(f"No declaration documents found at {registry}")
        for file in files:
            document = _load_declaration_file(file)
            for record in document["declarations"]:
                if record.get("relation") != "DEFINES":
                    diagnostics.append(
                        {"code": "RR.REGISTRY_RELATION_NOT_OBSERVED", "record": record}
                    )
                    continue
                if any(
                    all(
                        d.get(k) == record.get(k)
                        for k in (
                            "identifier",
                            "repository",
                            "revision",
                            "source_path",
                            "source_line",
                        )
                    )
                    for d in declarations
                ):
                    continue
                oid = "object:" + record["identifier"]
                nodes.setdefault(
                    oid,
                    {
                        "id": oid,
                        "label": record["identifier"],
                        "kind": "object",
                        "definitions": [],
                    },
                )["definitions"].append(
                    {
                        **record,
                        "state": "registry-declaration",
                        "adapter": "normalized-declarations",
                    }
                )
                declarations.append(record)

    resolved_edges: list[dict[str, Any]] = []
    for original in edges:
        edge = dict(original)
        for endpoint in ("source", "target"):
            raw = edge[endpoint]
            if not raw.startswith("alias:"):
                continue
            alias = raw.removeprefix("alias:")
            matches = sorted(aliases.get(alias, set()))
            edge["declared_" + endpoint] = alias
            edge[endpoint + "_candidates"] = matches
            edge[endpoint] = matches[0] if len(matches) == 1 else "unresolved:" + alias
            if endpoint == "target":
                edge["candidates"] = matches
            if len(matches) != 1:
                edge["resolution"] = "ambiguous" if matches else "unresolved"
            if edge[endpoint] not in nodes:
                nodes[edge[endpoint]] = {
                    "id": edge[endpoint],
                    "label": alias,
                    "kind": "unresolved",
                    "lifecycle": "unresolved",
                }
        target = edge["target"]
        if "resolution" not in edge:
            edge["resolution"] = (
                "resolved"
                if target in nodes and nodes[target]["kind"] != "unresolved"
                else "unresolved"
            )
        if target not in nodes:
            nodes[target] = {
                "id": target,
                "label": target.split(":", 1)[-1],
                "kind": "unresolved",
                "lifecycle": "unresolved",
            }
        if edge["resolution"] != "resolved":
            diagnostics.append(
                {
                    "code": "RR.UNRESOLVED_EDGE",
                    "source": edge["source"],
                    "target": target,
                    "resolution": edge["resolution"],
                    "evidence": edge["evidence"],
                }
            )
        resolved_edges.append(edge)
    for node in nodes.values():
        if node["kind"] == "object":
            definitions = sorted(node["definitions"], key=canonical)
            node["definitions"] = definitions
            node["resolution"] = (
                "resolved" if len(definitions) == 1 else "duplicate-definition"
            )
            node["content_digest"] = digest(definitions)
            if len(definitions) > 1:
                diagnostics.append(
                    {
                        "code": "RR.DUPLICATE_DEFINITION",
                        "identifier": node["label"],
                        "definitions": definitions,
                    }
                )
    for edge in resolved_edges:
        if nodes[edge["target"]].get("resolution") == "duplicate-definition":
            edge["resolution"] = "duplicate-definition"
        edge["id"] = "edge:" + digest({k: v for k, v in edge.items() if k != "id"})
    payload = {
        "format": FORMAT,
        "format_version": FORMAT_VERSION,
        "observer_version": 1,
        "scope": "Discovered Git/project roots; excludes caches, build outputs and symlinks. No scientific validation inferred.",
        "nodes": sorted(nodes.values(), key=lambda n: n["id"]),
        "edges": sorted(
            {e["id"]: e for e in resolved_edges}.values(), key=lambda e: e["id"]
        ),
        "declarations": sorted(declarations, key=canonical),
        "diagnostics": sorted(diagnostics, key=canonical),
    }
    return {**payload, "snapshot_id": "sha256:" + digest(payload)}

snapshot_research_graph

snapshot_research_graph(
    *,
    path: Path,
    registry: str | None,
    base_snapshot: str | None,
    show: str | None,
    revisions: dict[str, str] | None = None,
) -> dict[str, Any]

Create or inspect a reproducible observation; output storage is explicit.

Source code in src/reactive_research/snapshot.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def snapshot_research_graph(
    *,
    path: Path,
    registry: str | None,
    base_snapshot: str | None,
    show: str | None,
    revisions: dict[str, str] | None = None,
) -> dict[str, Any]:
    """Create or inspect a reproducible observation; output storage is explicit."""
    if show is not None:
        return load_snapshot(show, registry)
    if base_snapshot is not None:
        load_snapshot(base_snapshot, registry)
    return observe_workspace(path, revisions=revisions, registry=registry)

Inspection

reactive_research.inspect

Inspect Reactive Research objects and repositories.

inspect_research_object

inspect_research_object(
    *,
    path: Path,
    target: str,
    registry: str | None,
    snapshot: str | None,
) -> dict[str, Any]

Explain one research object or repository.

Source code in src/reactive_research/inspect.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def inspect_research_object(
    *,
    path: Path,
    target: str,
    registry: str | None,
    snapshot: str | None,
) -> dict[str, Any]:
    """Explain one research object or repository."""
    return {
        "command": "inspect",
        "status": "scaffolded",
        "path": str(path.resolve()),
        "target": target,
        "registry": registry,
        "snapshot": snapshot,
        "defined_by": None,
        "implements": [],
        "implemented_by": [],
        "depends_on": [],
        "depended_on_by": [],
        "revalidation_required": False,
    }