remgu 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
remgu/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ from .experiment import Experiment
4
+ from .models import Motivation
5
+ from .run import Run
6
+
7
+
8
+
9
+ __all__ = ["Experiment", "Motivation", "Run"]
10
+
11
+
12
+ from remgu.example.example_provider import ExampleProvider
13
+ from remgu.example.example_selector import ExampleSelector, TopKSelector
14
+
15
+ __all__ += ["ExampleProvider", "ExampleSelector", "TopKSelector"]
@@ -0,0 +1,9 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Read-only research-record consistency checks."""
4
+
5
+ from .consistency_issue import ConsistencyIssue
6
+ from .consistency_report import ConsistencyReport
7
+ from .research_checker import ResearchChecker
8
+
9
+ __all__ = ["ConsistencyIssue", "ConsistencyReport", "ResearchChecker"]
@@ -0,0 +1,22 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Compatibility facade for the src consistency service."""
4
+ from .consistency_report import ConsistencyReport
5
+ from remgu.consistency.research_checker import ResearchChecker
6
+
7
+
8
+ class Consistency:
9
+ """Compatibility facade exposing the consistency service as an object."""
10
+
11
+ def __init__(self, checker: ResearchChecker) -> None:
12
+ """Create a consistency facade.
13
+
14
+ Args:
15
+ checker: Read-only checker that performs the actual analysis.
16
+ """
17
+ self.checker = checker
18
+ """Underlying src consistency checker."""
19
+
20
+ def check(self) -> ConsistencyReport:
21
+ """Run consistency analysis and return its report."""
22
+ return self.checker.check()
@@ -0,0 +1,23 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """One issue reported by src consistency analysis."""
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class ConsistencyIssue:
11
+ """Describe one consistency problem in persisted src data."""
12
+
13
+ run_id: str
14
+ """Run identifier where the problem was detected."""
15
+
16
+ code: str
17
+ """Stable machine-readable issue code."""
18
+
19
+ message: str
20
+ """Human-readable explanation of the issue."""
21
+
22
+ severity: str = "warning"
23
+ """Issue severity, normally ``warning`` or ``error``."""
@@ -0,0 +1,27 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Consistency-analysis report model."""
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass, field
7
+
8
+ from .consistency_issue import ConsistencyIssue
9
+
10
+
11
+ @dataclass
12
+ class ConsistencyReport:
13
+ """Aggregate completed runs, hypotheses and detected consistency issues."""
14
+
15
+ completed_runs: list[str] = field(default_factory=list)
16
+ """Identifiers of runs whose execution status is ``completed``."""
17
+
18
+ runs_with_hypotheses: list[str] = field(default_factory=list)
19
+ """Identifiers of runs containing a non-empty hypothesis."""
20
+
21
+ issues: list[ConsistencyIssue] = field(default_factory=list)
22
+ """Consistency problems discovered while scanning persisted runs."""
23
+
24
+ @property
25
+ def ok(self) -> bool:
26
+ """Return whether the report contains no consistency issues."""
27
+ return not self.issues
@@ -0,0 +1,124 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Read-only consistency analysis service."""
4
+ from __future__ import annotations
5
+
6
+ from typing import Any
7
+
8
+ from remgu.consistency.consistency_issue import ConsistencyIssue
9
+ from remgu.consistency.consistency_report import ConsistencyReport
10
+ from remgu.file_storage import FileStorage
11
+
12
+
13
+ class ResearchChecker:
14
+ """Analyze persisted runs without modifying research state."""
15
+
16
+ def __init__(self, storage: FileStorage) -> None:
17
+ """Create a checker bound to a src storage service.
18
+
19
+ Args:
20
+ storage: File-backed src storage to inspect.
21
+ """
22
+ self.storage = storage
23
+ """Storage service whose run files are inspected."""
24
+
25
+ def check(self) -> ConsistencyReport:
26
+ """Scan all persisted runs and return a consistency report."""
27
+ report = ConsistencyReport()
28
+ run_ids = self.storage.list_run_ids()
29
+ known_ids = set(run_ids)
30
+ for run_id in run_ids:
31
+ self._check_run(run_id, known_ids, report)
32
+ return report
33
+
34
+ def _check_run(self, run_id: str, known_ids: set[str], report: ConsistencyReport) -> None:
35
+ """Analyze one run and append findings to an existing report.
36
+
37
+ Args:
38
+ run_id: Identifier of the run being checked.
39
+ known_ids: All known run identifiers used to validate references.
40
+ report: Mutable report receiving the findings.
41
+ """
42
+ path = self.storage.run_path(run_id) / "run.yaml"
43
+ try:
44
+ data = self.storage.read_yaml_file(path)
45
+ except Exception as exc:
46
+ report.issues.append(ConsistencyIssue(run_id, "invalid_yaml", f"cannot read run.yaml: {exc}", "error"))
47
+ return
48
+ if not isinstance(data, dict):
49
+ report.issues.append(ConsistencyIssue(run_id, "invalid_structure", "run.yaml must contain a mapping", "error"))
50
+ return
51
+ research = self._section(data, "research", run_id, report)
52
+ execution = self._section(data, "execution", run_id, report)
53
+ review = self._section(data, "review", run_id, report)
54
+ self._check_hypothesis(run_id, research, report)
55
+ self._check_motivation(run_id, research, known_ids, report)
56
+ self._check_execution(run_id, execution, review, report)
57
+ self._check_review(run_id, execution, review, report)
58
+
59
+ def _section(self, data: dict[str, Any], name: str, run_id: str, report: ConsistencyReport) -> dict[str, Any]:
60
+ """Read a required top-level mapping and report malformed sections.
61
+
62
+ Args:
63
+ data: Parsed run YAML mapping.
64
+ name: Section name expected in the run YAML document.
65
+ run_id: Identifier of the run being checked.
66
+ report: Report receiving a malformed-section issue when needed.
67
+ """
68
+ section = data.get(name)
69
+ if not isinstance(section, dict):
70
+ report.issues.append(ConsistencyIssue(run_id, f"missing_{name}", f"{name} section is missing or invalid", "error"))
71
+ return {}
72
+ return section
73
+
74
+ def _check_hypothesis(self, run_id: str, research: dict[str, Any], report: ConsistencyReport) -> None:
75
+ """Validate and count the run hypothesis."""
76
+ hypothesis = research.get("hypothesis")
77
+ if self._nonempty_text(hypothesis):
78
+ report.runs_with_hypotheses.append(run_id)
79
+ else:
80
+ report.issues.append(ConsistencyIssue(run_id, "missing_hypothesis", "hypothesis is empty or missing"))
81
+
82
+ def _check_motivation(self, run_id: str, research: dict[str, Any], known_ids: set[str], report: ConsistencyReport) -> None:
83
+ """Validate motivation structure and previous-run references."""
84
+ motivation = research.get("motivation")
85
+ if not isinstance(motivation, dict):
86
+ report.issues.append(ConsistencyIssue(run_id, "missing_motivation", "motivation is missing or invalid"))
87
+ return
88
+ motivation_type = motivation.get("type")
89
+ reference = motivation.get("reference")
90
+ if not self._nonempty_text(motivation_type):
91
+ report.issues.append(ConsistencyIssue(run_id, "weak_motivation", "motivation type is empty"))
92
+ elif motivation_type == "previous_run" and not self._nonempty_text(reference):
93
+ report.issues.append(ConsistencyIssue(run_id, "weak_motivation", "previous_run motivation has no reference"))
94
+ elif self._nonempty_text(reference) and reference not in known_ids:
95
+ report.issues.append(ConsistencyIssue(run_id, "broken_motivation_reference", f"motivation references unknown run {reference}"))
96
+
97
+ def _check_execution(self, run_id: str, execution: dict[str, Any], review: dict[str, Any], report: ConsistencyReport) -> None:
98
+ """Validate execution status and require conclusions for completed runs."""
99
+ status = execution.get("status")
100
+ if status == "completed":
101
+ report.completed_runs.append(run_id)
102
+ if not self._nonempty_text(review.get("conclusion")):
103
+ report.issues.append(ConsistencyIssue(run_id, "missing_conclusion", "completed run has no conclusion"))
104
+ elif status not in {"running", "failed", "aborted", None}:
105
+ report.issues.append(ConsistencyIssue(run_id, "invalid_execution_status", f"unknown execution status: {status}", "error"))
106
+
107
+ def _check_review(self, run_id: str, execution: dict[str, Any], review: dict[str, Any], report: ConsistencyReport) -> None:
108
+ """Validate review status and its relationship with execution."""
109
+ status = review.get("status", "needs_review")
110
+ if status not in {"needs_review", "reviewed"}:
111
+ report.issues.append(ConsistencyIssue(run_id, "invalid_review_status", f"unknown review status: {status}", "error"))
112
+ if status == "reviewed" and execution.get("status") != "completed":
113
+ report.issues.append(ConsistencyIssue(run_id, "reviewed_noncompleted_run", "run is marked reviewed but execution is not completed"))
114
+ if status == "reviewed" and not self._nonempty_text(review.get("next_step")):
115
+ report.issues.append(ConsistencyIssue(run_id, "missing_next_step", "reviewed run has no next_step"))
116
+
117
+ @staticmethod
118
+ def _nonempty_text(value: Any) -> bool:
119
+ """Return whether a value is a non-empty string.
120
+
121
+ Args:
122
+ value: Value being checked.
123
+ """
124
+ return isinstance(value, str) and bool(value.strip())
@@ -0,0 +1,9 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Diagnostic example selection and lookup interfaces."""
4
+
5
+ from .example_provider import ExampleProvider
6
+ from .example_selector import ExampleSelector
7
+ from .top_k_selector import TopKSelector
8
+
9
+ __all__ = ["ExampleProvider", "ExampleSelector", "TopKSelector"]
@@ -0,0 +1,21 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Internal candidate model used by example selection."""
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Candidate:
12
+ """Represent one record retained by a top-k selector's heap."""
13
+
14
+ score: float
15
+ """Numeric diagnostic score used for ranking the record."""
16
+
17
+ order: int
18
+ """Insertion order used to make equal-score selection deterministic."""
19
+
20
+ record: dict[str, Any]
21
+ """Copy of the selected record."""
@@ -0,0 +1,26 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Interface for resolving compact src example identifiers."""
4
+ from __future__ import annotations
5
+
6
+ from typing import Any, Protocol
7
+
8
+
9
+ class ExampleProvider(Protocol):
10
+ """Define the read-only interface used to resolve diagnostic example IDs."""
11
+
12
+ def get(self, example_id: str) -> Any:
13
+ """Load the original example or its lightweight context.
14
+
15
+ Args:
16
+ example_id: Compact identifier of the requested example.
17
+ """
18
+ ...
19
+
20
+ def describe(self, example_id: str) -> str:
21
+ """Return a cheap human-readable description of an example.
22
+
23
+ Args:
24
+ example_id: Compact identifier of the requested example.
25
+ """
26
+ ...
@@ -0,0 +1,57 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Combine several named example-selection criteria."""
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Mapping
7
+ from typing import Any
8
+
9
+ from .top_k_selector import TopKSelector
10
+
11
+
12
+ class ExampleSelector:
13
+ """Run several named top-k criteria over the same candidate stream."""
14
+
15
+ def __init__(self, selectors: list[TopKSelector]) -> None:
16
+ """Create a multi-criterion selector.
17
+
18
+ Args:
19
+ selectors: Named top-k selectors evaluated over the same records.
20
+ """
21
+ if not selectors:
22
+ raise ValueError("at least one selector is required")
23
+ if any(selector.name is None for selector in selectors):
24
+ raise ValueError("every selector must have a name")
25
+ self.selectors = selectors
26
+ """Ordered selectors whose outputs will be merged."""
27
+
28
+ def consider(self, record: Mapping[str, Any]) -> None:
29
+ """Pass one record to every configured selector.
30
+
31
+ Args:
32
+ record: Candidate diagnostic record shared by all selectors.
33
+ """
34
+ for selector in self.selectors:
35
+ selector.consider(record)
36
+
37
+ def records(self) -> list[dict[str, Any]]:
38
+ """Return unique selected records with reasons and scores attached."""
39
+ merged: dict[Any, dict[str, Any]] = {}
40
+ for selector in self.selectors:
41
+ for record in selector.records():
42
+ example_id = record.get("example_id")
43
+ if example_id is None:
44
+ raise ValueError("multi-selector records require example_id")
45
+ item = merged.setdefault(example_id, dict(record))
46
+ selection = item.setdefault("selection", {})
47
+ reasons = selection.setdefault("reasons", [])
48
+ if selector.name not in reasons:
49
+ reasons.append(selector.name)
50
+ scores = selection.setdefault("scores", {})
51
+ if selector.key is not None:
52
+ scores[selector.name] = float(selector.key(record))
53
+ return list(merged.values())
54
+
55
+ def __repr__(self) -> str:
56
+ """Return a concise representation of the configured selectors."""
57
+ return f"{self.selectors}"
@@ -0,0 +1,88 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Domain-agnostic top-k example selector."""
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Callable, Mapping
7
+ from heapq import heappush, heappushpop
8
+ from typing import Any
9
+
10
+ from remgu.example.candidate import Candidate
11
+
12
+ ScoreFunction = Callable[[Mapping[str, Any]], float]
13
+ """Callable that extracts a numeric selection score from a record."""
14
+
15
+
16
+ class TopKSelector:
17
+ """Keep the k records with the largest or smallest diagnostic score."""
18
+
19
+ def __init__(self, k: int, *, key: ScoreFunction | None = None,
20
+ largest: bool = True, name: str | None = None) -> None:
21
+ """Create an incremental top-k selector.
22
+
23
+ Args:
24
+ k: Maximum number of records retained.
25
+ key: Optional score function applied to each record.
26
+ largest: Whether larger scores are considered better.
27
+ name: Optional stable selector name used by ``ExampleSelector``.
28
+ """
29
+ if k <= 0:
30
+ raise ValueError("k must be positive")
31
+ if key is not None and not callable(key):
32
+ raise TypeError("key must be callable")
33
+ self.k = k
34
+ """Maximum number of candidates retained."""
35
+ self.key = key
36
+ """Optional score function."""
37
+ self.largest = largest
38
+ """Whether higher scores are preferred."""
39
+ self.name = name
40
+ """Optional selector name used in merged diagnostics."""
41
+ self._heap: list[tuple[float, int, Candidate]] = []
42
+ """Heap containing the currently retained candidates."""
43
+ self._counter = 0
44
+ """Monotonic insertion counter used for deterministic ties."""
45
+
46
+ def consider(self, record: Mapping[str, Any], priority: float | None = None,
47
+ *, score: float | None = None) -> None:
48
+ """Consider one record for retention.
49
+
50
+ Args:
51
+ record: Candidate diagnostic record.
52
+ priority: Backwards-compatible explicit score argument.
53
+ score: Preferred explicit score argument when no score function is configured.
54
+ """
55
+ if not isinstance(record, Mapping):
56
+ raise TypeError("record must be a mapping")
57
+ if priority is not None and score is not None:
58
+ raise TypeError("use either priority or score, not both")
59
+ if priority is not None:
60
+ value = priority
61
+ elif score is not None:
62
+ value = score
63
+ elif self.key is not None:
64
+ value = self.key(record)
65
+ else:
66
+ raise TypeError("provide priority, score, or a key")
67
+ try:
68
+ value = float(value)
69
+ except (TypeError, ValueError) as exc:
70
+ raise TypeError("selection score must be numeric") from exc
71
+ candidate = Candidate(value, self._counter, dict(record))
72
+ self._counter += 1
73
+ heap_score = value if self.largest else -value
74
+ item = (heap_score, candidate.order, candidate)
75
+ if len(self._heap) < self.k:
76
+ heappush(self._heap, item)
77
+ elif item[:2] > self._heap[0][:2]:
78
+ heappushpop(self._heap, item)
79
+
80
+ def records(self) -> list[dict[str, Any]]:
81
+ """Return retained records in best-first order."""
82
+ candidates = [item[2] for item in self._heap]
83
+ candidates.sort(key=lambda item: (item.score, item.order), reverse=self.largest)
84
+ return [item.record for item in candidates]
85
+
86
+ def __len__(self) -> int:
87
+ """Return the number of records currently retained."""
88
+ return len(self._heap)
remgu/experiment.py ADDED
@@ -0,0 +1,139 @@
1
+ # Copyright 2026 Mstislav Maslennikov
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """High-level facade for creating and resuming research runs."""
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Mapping
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from remgu.models.execution import Execution
12
+ from remgu.models.motivation import Motivation
13
+ from remgu.models.research_metadata import ResearchMetadata
14
+ from remgu.models.review import Review
15
+ from .run import Run
16
+ from .file_storage import FileStorage
17
+
18
+
19
+ class Experiment:
20
+ """Provide the student-facing API for persistent src execution."""
21
+
22
+ def __init__(self, experiment_id: str, base_path: str | Path = ".research") -> None:
23
+ """Create an experiment facade over a file-backed research store.
24
+
25
+ Args:
26
+ experiment_id: Human-readable identifier of the experiment or project.
27
+ base_path: Root directory used for persistent research state.
28
+ """
29
+ self.experiment_id = experiment_id
30
+ """Human-readable experiment identifier."""
31
+ self.storage = FileStorage(base_path)
32
+ """Persistence service used to create and resume runs."""
33
+ self.storage.initialize()
34
+
35
+ def run(self, hypothesis: str | None = None,
36
+ motivation: Mapping[str, Any] | Motivation | None = None) -> Run:
37
+ """Resume the active run or create a new programmatic run.
38
+
39
+ Args:
40
+ hypothesis: Hypothesis for a new run; omit it when resuming an active run.
41
+ motivation: Motivation for a new run; omit it when resuming an active run.
42
+ """
43
+ if hypothesis is None and motivation is None:
44
+ return self._active_run()
45
+ if hypothesis is None or motivation is None:
46
+ raise ValueError("hypothesis and motivation must be provided together, or both omitted to continue the active run")
47
+ return self._create_run(hypothesis, motivation)
48
+
49
+ def _active_run(self) -> Run:
50
+ """Load and validate the run referenced by the active pointer."""
51
+ run_id = self.storage.get_active()
52
+ if run_id is None:
53
+ raise RuntimeError("No active research run. Run `src new` first.")
54
+ run = self._load_run(run_id)
55
+ if run.execution.status != "running":
56
+ self.storage.clear_active(run_id)
57
+ raise RuntimeError(f"Active research run is not running: {run_id} ({run.execution.status})")
58
+ return run
59
+
60
+ def _create_run(self, hypothesis: str,
61
+ motivation: Mapping[str, Any] | Motivation) -> Run:
62
+ """Create, activate and persist a new running execution.
63
+
64
+ Args:
65
+ hypothesis: Research hypothesis associated with the new run.
66
+ motivation: Motivation object or mapping describing why it was created.
67
+ """
68
+ active = self.storage.get_active()
69
+ if active is not None:
70
+ raise RuntimeError(f"Another run is already active: {active}")
71
+ motivation_model = self._make_motivation(motivation)
72
+ run_id = self.storage.next_run_id()
73
+ run = Run(run_id=run_id,
74
+ research=ResearchMetadata(hypothesis=hypothesis, motivation=motivation_model),
75
+ storage=self.storage, path=self.storage.run_path(run_id),
76
+ execution=Execution(status="running"), review=Review())
77
+ self.storage.set_active(run_id)
78
+ try:
79
+ run.start()
80
+ except Exception:
81
+ self.storage.clear_active(run_id)
82
+ raise
83
+ return run
84
+
85
+ def _load_run(self, run_id: str) -> Run:
86
+ """Deserialize one persisted run into its domain object.
87
+
88
+ Args:
89
+ run_id: Identifier of the run to load.
90
+ """
91
+ data = self.storage.read_run(run_id)
92
+ if not data:
93
+ raise RuntimeError(f"Active run not found: {run_id}")
94
+ try:
95
+ research_data = data["research"]
96
+ motivation_data = research_data["motivation"]
97
+ execution_data = data["execution"]
98
+ review_data = data["review"]
99
+ motivation = Motivation(type=str(motivation_data["type"]),
100
+ reference=str(motivation_data["reference"]) if motivation_data.get("reference") is not None else None)
101
+ execution = Execution(status=str(execution_data["status"]),
102
+ started_at=self._parse_time(execution_data.get("started_at")),
103
+ finished_at=self._parse_time(execution_data.get("finished_at")),
104
+ error=execution_data.get("error"))
105
+ review = Review(status=str(review_data.get("status", "needs_review")),
106
+ conclusion=review_data.get("conclusion"), next_step=review_data.get("next_step"))
107
+ except (KeyError, TypeError, ValueError) as exc:
108
+ raise RuntimeError(f"Invalid run.yaml for {run_id}: {exc}") from exc
109
+ return Run(run_id=run_id,
110
+ research=ResearchMetadata(hypothesis=str(research_data["hypothesis"]), motivation=motivation),
111
+ storage=self.storage, path=self.storage.run_path(run_id),
112
+ execution=execution, review=review)
113
+
114
+ @staticmethod
115
+ def _parse_time(value: Any) -> datetime | None:
116
+ """Convert persisted time data to a timezone-aware datetime.
117
+
118
+ Args:
119
+ value: YAML value representing an ISO timestamp or ``None``.
120
+ """
121
+ if value is None:
122
+ return None
123
+ if isinstance(value, datetime):
124
+ return value
125
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
126
+
127
+ @staticmethod
128
+ def _make_motivation(motivation: Mapping[str, Any] | Motivation) -> Motivation:
129
+ """Normalize a motivation mapping or object into ``Motivation``.
130
+
131
+ Args:
132
+ motivation: Motivation value object or mapping containing ``type`` and optional ``reference``.
133
+ """
134
+ if isinstance(motivation, Motivation):
135
+ return motivation
136
+ if "type" not in motivation:
137
+ raise ValueError("motivation must contain 'type'")
138
+ return Motivation(type=str(motivation["type"]),
139
+ reference=str(motivation["reference"]) if motivation.get("reference") is not None else None)