reasonledger-core 0.3.0a6__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.
- reasonledger_core/__init__.py +26 -0
- reasonledger_core/consent.py +216 -0
- reasonledger_core/decisions/__init__.py +41 -0
- reasonledger_core/decisions/fingerprint.py +113 -0
- reasonledger_core/decisions/format.py +99 -0
- reasonledger_core/decisions/identity_check.py +85 -0
- reasonledger_core/decisions/ids.py +49 -0
- reasonledger_core/decisions/lifecycle.py +113 -0
- reasonledger_core/decisions/service.py +231 -0
- reasonledger_core/harvest/__init__.py +15 -0
- reasonledger_core/harvest/batch.py +77 -0
- reasonledger_core/harvest/deterministic.py +108 -0
- reasonledger_core/harvest/llm_replay.py +28 -0
- reasonledger_core/importer/__init__.py +60 -0
- reasonledger_core/importer/adapters.py +91 -0
- reasonledger_core/importer/agent_route.py +207 -0
- reasonledger_core/importer/config.py +134 -0
- reasonledger_core/importer/endpoint.py +64 -0
- reasonledger_core/importer/extractor.py +59 -0
- reasonledger_core/importer/llm.py +306 -0
- reasonledger_core/importer/outgoing.py +86 -0
- reasonledger_core/importer/probe.py +90 -0
- reasonledger_core/importer/prompt.py +53 -0
- reasonledger_core/importer/propose.py +242 -0
- reasonledger_core/importer/scan.py +206 -0
- reasonledger_core/importer/service.py +77 -0
- reasonledger_core/ingest/classify.py +75 -0
- reasonledger_core/ingest/contributors.py +14 -0
- reasonledger_core/ingest/github_types.py +54 -0
- reasonledger_core/ingest/normalize.py +69 -0
- reasonledger_core/metrics.py +172 -0
- reasonledger_core/models/decision.py +261 -0
- reasonledger_core/models/oversight.py +29 -0
- reasonledger_core/models/policy.py +82 -0
- reasonledger_core/models/provenance.py +51 -0
- reasonledger_core/models/reasoning.py +143 -0
- reasonledger_core/modules/__init__.py +35 -0
- reasonledger_core/modules/agent_route.py +155 -0
- reasonledger_core/modules/buckets.py +61 -0
- reasonledger_core/modules/config.py +374 -0
- reasonledger_core/modules/decision_suggest.py +108 -0
- reasonledger_core/modules/digest.py +136 -0
- reasonledger_core/modules/drift.py +143 -0
- reasonledger_core/modules/editing.py +189 -0
- reasonledger_core/modules/files.py +84 -0
- reasonledger_core/modules/fold.py +133 -0
- reasonledger_core/modules/globs.py +127 -0
- reasonledger_core/modules/hand_placement.py +102 -0
- reasonledger_core/modules/labels.py +55 -0
- reasonledger_core/modules/llm_mapper.py +239 -0
- reasonledger_core/modules/manifest.py +156 -0
- reasonledger_core/modules/mapper_check.py +128 -0
- reasonledger_core/modules/mapping.py +260 -0
- reasonledger_core/modules/models.py +156 -0
- reasonledger_core/modules/organize.py +267 -0
- reasonledger_core/modules/placement.py +87 -0
- reasonledger_core/modules/quick_map.py +47 -0
- reasonledger_core/modules/resolve.py +274 -0
- reasonledger_core/modules/review.py +23 -0
- reasonledger_core/modules/scan.py +126 -0
- reasonledger_core/modules/signals/__init__.py +1 -0
- reasonledger_core/modules/signals/cochange.py +112 -0
- reasonledger_core/modules/signals/codeowners.py +76 -0
- reasonledger_core/modules/signals/convention.py +96 -0
- reasonledger_core/modules/signals/layout.py +130 -0
- reasonledger_core/modules/signals/specs.py +96 -0
- reasonledger_core/modules/signals/tooling.py +25 -0
- reasonledger_core/modules/signals/workspace.py +126 -0
- reasonledger_core/modules/suggest.py +240 -0
- reasonledger_core/modules/tier_split.py +135 -0
- reasonledger_core/modules/tiers.py +53 -0
- reasonledger_core/oversight/classify.py +29 -0
- reasonledger_core/paths/critical.py +13 -0
- reasonledger_core/policy/__init__.py +19 -0
- reasonledger_core/policy/evaluate.py +118 -0
- reasonledger_core/policy/parse.py +75 -0
- reasonledger_core/privacy/data_minimization.py +22 -0
- reasonledger_core/privacy/pii_linter.py +134 -0
- reasonledger_core/provenance/classify.py +41 -0
- reasonledger_core/provenance/detectors.py +197 -0
- reasonledger_core/py.typed +0 -0
- reasonledger_core/reasoning/__init__.py +148 -0
- reasonledger_core/reasoning/agent_judge.py +164 -0
- reasonledger_core/reasoning/anchors.py +74 -0
- reasonledger_core/reasoning/cache.py +75 -0
- reasonledger_core/reasoning/config.py +82 -0
- reasonledger_core/reasoning/conflict_config.py +172 -0
- reasonledger_core/reasoning/conflicts.py +197 -0
- reasonledger_core/reasoning/conflicts_replay.py +56 -0
- reasonledger_core/reasoning/dismissals.py +218 -0
- reasonledger_core/reasoning/embeddings.py +142 -0
- reasonledger_core/reasoning/judge.py +292 -0
- reasonledger_core/reasoning/pr_opener.py +33 -0
- reasonledger_core/reasoning/related.py +201 -0
- reasonledger_core/reasoning/retrieval.py +87 -0
- reasonledger_core/reasoning/symbols.py +116 -0
- reasonledger_core/reasoning/ts_symbols.py +323 -0
- reasonledger_core/reasoning/verdicts.py +162 -0
- reasonledger_core/reasoning/watchers.py +120 -0
- reasonledger_core/reasoning/why.py +230 -0
- reasonledger_core/reasoning/why_nearby.py +139 -0
- reasonledger_core/repo_files.py +42 -0
- reasonledger_core/settings.py +21 -0
- reasonledger_core/sync/__init__.py +39 -0
- reasonledger_core/sync/repo.py +305 -0
- reasonledger_core/sync/state.py +62 -0
- reasonledger_core/views/__init__.py +33 -0
- reasonledger_core/views/cache.py +84 -0
- reasonledger_core/views/homeless.py +99 -0
- reasonledger_core/views/inbox.py +208 -0
- reasonledger_core/views/ledger.py +383 -0
- reasonledger_core/views/map_models.py +90 -0
- reasonledger_core/views/map_view.py +265 -0
- reasonledger_core/views/organize_files.py +113 -0
- reasonledger_core/views/related_view.py +121 -0
- reasonledger_core/views/stats.py +80 -0
- reasonledger_core-0.3.0a6.dist-info/METADATA +75 -0
- reasonledger_core-0.3.0a6.dist-info/RECORD +121 -0
- reasonledger_core-0.3.0a6.dist-info/WHEEL +4 -0
- reasonledger_core-0.3.0a6.dist-info/licenses/LICENSE +201 -0
- reasonledger_core-0.3.0a6.dist-info/licenses/NOTICE +4 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Framework-free domain logic for ReasonLedger."""
|
|
2
|
+
|
|
3
|
+
from reasonledger_core.models.oversight import OversightClassification
|
|
4
|
+
from reasonledger_core.models.policy import CheckOutcome, PolicyEvaluationResult
|
|
5
|
+
from reasonledger_core.models.provenance import (
|
|
6
|
+
ProvenanceFinding,
|
|
7
|
+
ProvenanceStatus,
|
|
8
|
+
SignalConfidence,
|
|
9
|
+
)
|
|
10
|
+
from reasonledger_core.oversight.classify import classify_oversight
|
|
11
|
+
from reasonledger_core.policy import evaluate_policy
|
|
12
|
+
from reasonledger_core.provenance.classify import classify_provenance
|
|
13
|
+
from reasonledger_core.provenance.detectors import detect_provenance_signals
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"CheckOutcome",
|
|
17
|
+
"OversightClassification",
|
|
18
|
+
"PolicyEvaluationResult",
|
|
19
|
+
"ProvenanceFinding",
|
|
20
|
+
"ProvenanceStatus",
|
|
21
|
+
"SignalConfidence",
|
|
22
|
+
"classify_oversight",
|
|
23
|
+
"classify_provenance",
|
|
24
|
+
"detect_provenance_signals",
|
|
25
|
+
"evaluate_policy",
|
|
26
|
+
]
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Consent to send repo data to a model that is not on this machine.
|
|
2
|
+
|
|
3
|
+
Nothing leaves the machine until a person says so, per repo, per kind of data, and for the
|
|
4
|
+
destination they saw. A model on this machine (a loopback address) needs no consent. The
|
|
5
|
+
record lives in the user's own config directory, never in the repo and never committed, so a
|
|
6
|
+
clone or a CI run starts with nothing granted and fails closed.
|
|
7
|
+
|
|
8
|
+
Three kinds of data can be sent, and each is its own grant:
|
|
9
|
+
|
|
10
|
+
* ``decision_text``: each decision's context and choice (``judge``).
|
|
11
|
+
* ``paths``: file paths and route paths, never file contents (``map``).
|
|
12
|
+
* ``repo_text``: text of your docs and your commit messages, subject and body (``import``,
|
|
13
|
+
``catchup``). Before it is sent, a doc or commit that matches the PII/secret patterns is held
|
|
14
|
+
back whole and reported (``importer.outgoing``).
|
|
15
|
+
|
|
16
|
+
A grant is bound to the destination origin (scheme, host and port) it was given for. Point the
|
|
17
|
+
repo at a different provider, or the same host over another scheme or port, and it asks again;
|
|
18
|
+
so does a new kind of data. Grants recorded before origins were used named a bare host, match
|
|
19
|
+
no origin, and so are asked for again.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import contextlib
|
|
25
|
+
import os
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
from datetime import UTC, datetime
|
|
29
|
+
from enum import StrEnum
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
import yaml
|
|
34
|
+
|
|
35
|
+
from reasonledger_core.importer.config import ExtractorConfig, ExtractorProvider
|
|
36
|
+
from reasonledger_core.importer.endpoint import is_loopback, origin
|
|
37
|
+
from reasonledger_core.importer.llm import ANTHROPIC_DEFAULT_BASE_URL
|
|
38
|
+
|
|
39
|
+
CONSENT_DIR_ENV = "RL_CONSENT_DIR"
|
|
40
|
+
CONSENT_FILE = "consent.yml"
|
|
41
|
+
CONSENT_VERSION = "1"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class DataClass(StrEnum):
|
|
45
|
+
DECISION_TEXT = "decision_text"
|
|
46
|
+
PATHS = "paths"
|
|
47
|
+
REPO_TEXT = "repo_text"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
LABELS: dict[DataClass, str] = {
|
|
51
|
+
DataClass.DECISION_TEXT: "Decision text",
|
|
52
|
+
DataClass.PATHS: "File and route paths",
|
|
53
|
+
DataClass.REPO_TEXT: "Docs and commit messages",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
DESCRIPTIONS: dict[DataClass, str] = {
|
|
57
|
+
DataClass.DECISION_TEXT: (
|
|
58
|
+
"the context and choice of your recorded decisions, to judge which related ones conflict"
|
|
59
|
+
),
|
|
60
|
+
DataClass.PATHS: (
|
|
61
|
+
"file paths and HTTP route paths, to propose your module map; never file contents"
|
|
62
|
+
),
|
|
63
|
+
DataClass.REPO_TEXT: (
|
|
64
|
+
"the text of your docs and of your commit messages (subject and body), to extract "
|
|
65
|
+
"decisions from them; a doc or commit matching the PII/secret check is held back; "
|
|
66
|
+
"never diffs or author names"
|
|
67
|
+
),
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ConsentError(ValueError):
|
|
72
|
+
"""Raised for a request that cannot be a grant (an unknown class, a local model)."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_classes(names: list[str]) -> list[DataClass]:
|
|
76
|
+
"""Class names as typed on the command line or sent by the UI."""
|
|
77
|
+
parsed: list[DataClass] = []
|
|
78
|
+
for name in names:
|
|
79
|
+
try:
|
|
80
|
+
parsed.append(DataClass(name))
|
|
81
|
+
except ValueError as exc:
|
|
82
|
+
valid = ", ".join(item.value for item in DataClass)
|
|
83
|
+
raise ConsentError(f"unknown data class {name!r} (choose from {valid})") from exc
|
|
84
|
+
return parsed
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def destination(config: ExtractorConfig) -> str | None:
|
|
88
|
+
"""The origin a prompt goes to, or ``None`` when it never leaves this machine.
|
|
89
|
+
|
|
90
|
+
A disabled provider sends nothing. Anthropic is always off the machine; any other
|
|
91
|
+
provider is local only when its base URL is a loopback address.
|
|
92
|
+
"""
|
|
93
|
+
if config.provider is ExtractorProvider.DISABLED:
|
|
94
|
+
return None
|
|
95
|
+
if config.provider is ExtractorProvider.ANTHROPIC:
|
|
96
|
+
return origin(config.base_url or ANTHROPIC_DEFAULT_BASE_URL)
|
|
97
|
+
if is_loopback(config.base_url):
|
|
98
|
+
return None
|
|
99
|
+
return origin(config.base_url) if config.base_url else "(no base_url set)"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def consent_dir() -> Path:
|
|
103
|
+
"""User-scope config directory: outside every repo, so it can never be committed."""
|
|
104
|
+
override = os.environ.get(CONSENT_DIR_ENV)
|
|
105
|
+
if override:
|
|
106
|
+
return Path(override)
|
|
107
|
+
if sys.platform == "win32":
|
|
108
|
+
base = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
|
|
109
|
+
return Path(base) / "reasonledger"
|
|
110
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
111
|
+
return Path(base) / "reasonledger"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def repo_key(root: Path) -> str:
|
|
115
|
+
"""The repo's first commit hash (stable across clones), else its resolved path."""
|
|
116
|
+
resolved = root.resolve()
|
|
117
|
+
try:
|
|
118
|
+
out = subprocess.run( # noqa: S603
|
|
119
|
+
["git", "-C", str(resolved), "rev-list", "--max-parents=0", "HEAD"], # noqa: S607
|
|
120
|
+
capture_output=True,
|
|
121
|
+
text=True,
|
|
122
|
+
timeout=10,
|
|
123
|
+
check=False,
|
|
124
|
+
)
|
|
125
|
+
except (OSError, subprocess.SubprocessError):
|
|
126
|
+
return str(resolved)
|
|
127
|
+
first = out.stdout.split()
|
|
128
|
+
return first[0] if out.returncode == 0 and first else str(resolved)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _load() -> dict[str, Any]:
|
|
132
|
+
path = consent_dir() / CONSENT_FILE
|
|
133
|
+
try:
|
|
134
|
+
raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
135
|
+
except (OSError, yaml.YAMLError):
|
|
136
|
+
return {} # unreadable means nothing is granted: fail closed
|
|
137
|
+
repos = raw.get("repos") if isinstance(raw, dict) else None
|
|
138
|
+
return {"repos": repos} if isinstance(repos, dict) else {}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _save(repos: dict[str, Any]) -> None:
|
|
142
|
+
directory = consent_dir()
|
|
143
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
path = directory / CONSENT_FILE
|
|
145
|
+
payload = {"version": CONSENT_VERSION, "repos": repos}
|
|
146
|
+
path.write_text(yaml.safe_dump(payload, sort_keys=True), encoding="utf-8")
|
|
147
|
+
with contextlib.suppress(OSError): # best effort on filesystems without POSIX modes
|
|
148
|
+
path.chmod(0o600)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def granted_classes(root: Path, config: ExtractorConfig) -> set[DataClass]:
|
|
152
|
+
"""Classes granted for this repo to the destination the config points at now."""
|
|
153
|
+
host = destination(config)
|
|
154
|
+
if host is None:
|
|
155
|
+
return set()
|
|
156
|
+
entry = _load().get("repos", {}).get(repo_key(root), {})
|
|
157
|
+
granted = entry.get("granted", {}) if isinstance(entry, dict) else {}
|
|
158
|
+
found: set[DataClass] = set()
|
|
159
|
+
for name, record in granted.items() if isinstance(granted, dict) else []:
|
|
160
|
+
if isinstance(record, dict) and record.get("destination") == host:
|
|
161
|
+
try:
|
|
162
|
+
found.add(DataClass(name))
|
|
163
|
+
except ValueError:
|
|
164
|
+
continue
|
|
165
|
+
return found
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def missing_classes(
|
|
169
|
+
root: Path, config: ExtractorConfig, classes: list[DataClass]
|
|
170
|
+
) -> list[DataClass]:
|
|
171
|
+
"""Classes this call needs that nobody has allowed yet. Empty for a model on this machine."""
|
|
172
|
+
if destination(config) is None:
|
|
173
|
+
return []
|
|
174
|
+
have = granted_classes(root, config)
|
|
175
|
+
return [item for item in classes if item not in have]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def grant(
|
|
179
|
+
root: Path,
|
|
180
|
+
config: ExtractorConfig,
|
|
181
|
+
classes: list[DataClass],
|
|
182
|
+
*,
|
|
183
|
+
now: datetime | None = None,
|
|
184
|
+
) -> None:
|
|
185
|
+
"""Record that these classes may go to the configured destination for this repo."""
|
|
186
|
+
host = destination(config)
|
|
187
|
+
if host is None:
|
|
188
|
+
raise ConsentError("the configured model runs on this machine; nothing to allow")
|
|
189
|
+
repos = _load().get("repos", {})
|
|
190
|
+
entry = repos.setdefault(repo_key(root), {})
|
|
191
|
+
entry["path"] = str(root.resolve())
|
|
192
|
+
granted = entry.setdefault("granted", {})
|
|
193
|
+
stamp = (now or datetime.now(UTC)).isoformat()
|
|
194
|
+
for item in classes:
|
|
195
|
+
granted[item.value] = {"destination": host, "granted_at": stamp}
|
|
196
|
+
_save(repos)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def revoke(root: Path, classes: list[DataClass] | None = None) -> None:
|
|
200
|
+
"""Withdraw consent for these classes, or for everything when none are named."""
|
|
201
|
+
repos = _load().get("repos", {})
|
|
202
|
+
key = repo_key(root)
|
|
203
|
+
entry = repos.get(key)
|
|
204
|
+
if not isinstance(entry, dict):
|
|
205
|
+
return
|
|
206
|
+
granted = entry.get("granted", {})
|
|
207
|
+
if classes is None:
|
|
208
|
+
granted = {}
|
|
209
|
+
else:
|
|
210
|
+
for item in classes:
|
|
211
|
+
granted.pop(item.value, None)
|
|
212
|
+
if granted:
|
|
213
|
+
entry["granted"] = granted
|
|
214
|
+
else:
|
|
215
|
+
repos.pop(key, None)
|
|
216
|
+
_save(repos)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Decision capture — format, record, and query."""
|
|
2
|
+
|
|
3
|
+
from reasonledger_core.decisions.format import (
|
|
4
|
+
DECISIONS_DIR,
|
|
5
|
+
DecisionFormatError,
|
|
6
|
+
decision_filename,
|
|
7
|
+
parse_decision_markdown,
|
|
8
|
+
read_decision_file,
|
|
9
|
+
render_decision_markdown,
|
|
10
|
+
write_decision_file,
|
|
11
|
+
)
|
|
12
|
+
from reasonledger_core.decisions.ids import (
|
|
13
|
+
generate_decision_id,
|
|
14
|
+
harvest_decision_id,
|
|
15
|
+
import_decision_id,
|
|
16
|
+
)
|
|
17
|
+
from reasonledger_core.decisions.service import (
|
|
18
|
+
build_decision_record,
|
|
19
|
+
load_decisions_from_dir,
|
|
20
|
+
query_decisions,
|
|
21
|
+
record_decision_to_path,
|
|
22
|
+
superseded_by_map,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"DECISIONS_DIR",
|
|
27
|
+
"DecisionFormatError",
|
|
28
|
+
"build_decision_record",
|
|
29
|
+
"decision_filename",
|
|
30
|
+
"generate_decision_id",
|
|
31
|
+
"harvest_decision_id",
|
|
32
|
+
"import_decision_id",
|
|
33
|
+
"load_decisions_from_dir",
|
|
34
|
+
"parse_decision_markdown",
|
|
35
|
+
"query_decisions",
|
|
36
|
+
"read_decision_file",
|
|
37
|
+
"record_decision_to_path",
|
|
38
|
+
"render_decision_markdown",
|
|
39
|
+
"superseded_by_map",
|
|
40
|
+
"write_decision_file",
|
|
41
|
+
]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Anchors that survive edits: fingerprint the lines a decision explains, find them again later.
|
|
2
|
+
|
|
3
|
+
A ``path:START-END`` locus is a raw line range, and it drifts the moment lines are added above
|
|
4
|
+
it. At record time we store a truncated hash of the normalised lines (blank lines and trailing
|
|
5
|
+
whitespace ignored); at read time, if the stored range no longer hashes the same, a window of
|
|
6
|
+
the same number of non-blank lines is slid over the file. Exactly one match means the code
|
|
7
|
+
*moved*; none, or several, means the anchor is *lost* and the decision falls back to file level.
|
|
8
|
+
|
|
9
|
+
A truncated hash is not source code, so AGENTS §7 (never store source) still holds. Nothing here
|
|
10
|
+
writes a decision file: reading must never rewrite the ledger.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import re
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from enum import StrEnum
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from reasonledger_core.repo_files import read_repo_text
|
|
23
|
+
|
|
24
|
+
HASH_PREFIX = "sha256:"
|
|
25
|
+
HASH_HEX_CHARS = 16
|
|
26
|
+
# A longer block is not slid: the search is quadratic in block size, and a block this big is
|
|
27
|
+
# rarely moved intact. Its fingerprint still tells intact from changed.
|
|
28
|
+
MAX_SLIDE_LINES = 200
|
|
29
|
+
_LINE_LOCUS = re.compile(r"^(?P<path>.+):(?P<start>\d+)(?:-(?P<end>\d+))?$")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Drift(StrEnum):
|
|
33
|
+
INTACT = "intact"
|
|
34
|
+
MOVED = "moved"
|
|
35
|
+
LOST = "lost"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Resolution:
|
|
40
|
+
state: Drift
|
|
41
|
+
start: int
|
|
42
|
+
end: int
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def parse_line_locus(locus: str) -> tuple[str, int, int] | None:
|
|
46
|
+
"""``(path, start, end)`` for ``path:START-END`` or ``path:LINE``; None for any other locus."""
|
|
47
|
+
if "::" in locus:
|
|
48
|
+
return None
|
|
49
|
+
match = _LINE_LOCUS.match(locus)
|
|
50
|
+
if match is None:
|
|
51
|
+
return None
|
|
52
|
+
start = int(match["start"])
|
|
53
|
+
end = int(match["end"] or start)
|
|
54
|
+
return (match["path"], start, end) if 0 < start <= end else None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _normalise(lines: Sequence[str]) -> list[str]:
|
|
58
|
+
stripped = (line.rstrip() for line in lines)
|
|
59
|
+
return [line for line in stripped if line.strip()]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _digest(normalised: Sequence[str]) -> str:
|
|
63
|
+
joined = "\n".join(normalised).encode("utf-8")
|
|
64
|
+
return HASH_PREFIX + hashlib.sha256(joined).hexdigest()[:HASH_HEX_CHARS]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def fingerprint_range(lines: Sequence[str], start: int, end: int) -> str | None:
|
|
68
|
+
"""The fingerprint of 1-based inclusive ``start``-``end``; None when it holds no code."""
|
|
69
|
+
normalised = _normalise(lines[start - 1 : end])
|
|
70
|
+
return _digest(normalised) if normalised else None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_lines(root: Path, relative: str) -> list[str] | None:
|
|
74
|
+
"""The file's lines, or None when it is outside ``root``, missing or not text."""
|
|
75
|
+
text = read_repo_text(root, relative)
|
|
76
|
+
return text.splitlines() if text is not None else None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def fingerprint_loci(root: Path, loci: Sequence[str]) -> dict[str, str] | None:
|
|
80
|
+
"""Locus -> fingerprint for every line-range locus whose file can be read, else None."""
|
|
81
|
+
hashes: dict[str, str] = {}
|
|
82
|
+
cache: dict[str, list[str] | None] = {}
|
|
83
|
+
for locus in loci:
|
|
84
|
+
parsed = parse_line_locus(locus)
|
|
85
|
+
if parsed is None:
|
|
86
|
+
continue
|
|
87
|
+
path, start, end = parsed
|
|
88
|
+
if path not in cache:
|
|
89
|
+
cache[path] = read_lines(root, path)
|
|
90
|
+
lines = cache[path]
|
|
91
|
+
digest = fingerprint_range(lines, start, end) if lines is not None else None
|
|
92
|
+
if digest is not None:
|
|
93
|
+
hashes[locus] = digest
|
|
94
|
+
return hashes or None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def resolve_anchor(lines: Sequence[str], start: int, end: int, stored: str) -> Resolution:
|
|
98
|
+
"""Where the fingerprinted block is now: where it was, somewhere unique, or nowhere sure."""
|
|
99
|
+
if fingerprint_range(lines, start, end) == stored:
|
|
100
|
+
return Resolution(Drift.INTACT, start, end)
|
|
101
|
+
code = [
|
|
102
|
+
(number, text) for number, line in enumerate(lines, 1) if (text := line.rstrip()).strip()
|
|
103
|
+
]
|
|
104
|
+
found: set[tuple[int, int]] = set()
|
|
105
|
+
for size in range(min(end - start + 1, MAX_SLIDE_LINES), 0, -1):
|
|
106
|
+
for first in range(len(code) - size + 1):
|
|
107
|
+
window = code[first : first + size]
|
|
108
|
+
if _digest([text for _, text in window]) == stored:
|
|
109
|
+
found.add((window[0][0], window[-1][0]))
|
|
110
|
+
if len(found) == 1:
|
|
111
|
+
((new_start, new_end),) = found
|
|
112
|
+
return Resolution(Drift.MOVED, new_start, new_end)
|
|
113
|
+
return Resolution(Drift.LOST, start, end)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Serialize and parse `.reasonledger/decisions/*.md` records."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
from reasonledger_core.models.decision import (
|
|
12
|
+
DECISION_ID_PATTERN,
|
|
13
|
+
DecisionFrontmatter,
|
|
14
|
+
DecisionRecord,
|
|
15
|
+
)
|
|
16
|
+
from reasonledger_core.repo_files import RepoBoundaryError
|
|
17
|
+
|
|
18
|
+
DECISIONS_DIR = Path(".reasonledger/decisions")
|
|
19
|
+
# libyaml parses a decision several times faster than the pure-Python loader, which is
|
|
20
|
+
# what keeps a view of hundreds of records inside its time budget.
|
|
21
|
+
_YAML_LOADER = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
|
|
22
|
+
_FRONTMATTER_RE = re.compile(
|
|
23
|
+
r"\A---\s*\n(?P<yaml>.*?)\n---\s*\n?(?P<body>.*)\Z",
|
|
24
|
+
re.DOTALL,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DecisionFormatError(ValueError):
|
|
29
|
+
"""Raised when a decision markdown document is invalid."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def render_decision_markdown(record: DecisionRecord) -> str:
|
|
33
|
+
payload = record.frontmatter.model_dump(mode="json", exclude_none=True)
|
|
34
|
+
dumped = yaml.safe_dump(payload, sort_keys=False, allow_unicode=True).strip()
|
|
35
|
+
body = record.body.strip()
|
|
36
|
+
if body:
|
|
37
|
+
return f"---\n{dumped}\n---\n\n{body}\n"
|
|
38
|
+
return f"---\n{dumped}\n---\n"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parse_decision_markdown(raw: str) -> DecisionRecord:
|
|
42
|
+
match = _FRONTMATTER_RE.match(raw)
|
|
43
|
+
if match is None:
|
|
44
|
+
raise DecisionFormatError("decision markdown must start with YAML frontmatter")
|
|
45
|
+
try:
|
|
46
|
+
data = yaml.load(match.group("yaml"), Loader=_YAML_LOADER)
|
|
47
|
+
except yaml.YAMLError as exc:
|
|
48
|
+
raise DecisionFormatError(f"invalid frontmatter YAML: {exc}") from exc
|
|
49
|
+
if not isinstance(data, dict):
|
|
50
|
+
raise DecisionFormatError("frontmatter must be a mapping")
|
|
51
|
+
try:
|
|
52
|
+
frontmatter = DecisionFrontmatter.model_validate(data)
|
|
53
|
+
except Exception as exc:
|
|
54
|
+
raise DecisionFormatError(f"invalid decision frontmatter: {exc}") from exc
|
|
55
|
+
body = match.group("body").strip()
|
|
56
|
+
return DecisionRecord(frontmatter=frontmatter, body=body)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# O_NOFOLLOW makes the open itself refuse a symlink, closing the gap after the check below;
|
|
60
|
+
# where the platform has none (Windows), the check alone stands.
|
|
61
|
+
_NO_FOLLOW = getattr(os, "O_NOFOLLOW", 0)
|
|
62
|
+
_NEW_FILE_MODE = 0o666 # narrowed by the umask, as Path.write_text would
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def write_decision_file(path: Path, record: DecisionRecord) -> Path:
|
|
66
|
+
"""Write ``record`` to ``path``, never through a symlink: a committed link points anywhere.
|
|
67
|
+
|
|
68
|
+
The directory is the caller's to contain (``repo_files.contained_dir``); this refuses the
|
|
69
|
+
file itself being a link, including a broken one, which ``Path.exists`` reports as absent.
|
|
70
|
+
"""
|
|
71
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
if path.is_symlink():
|
|
73
|
+
raise RepoBoundaryError(
|
|
74
|
+
f"{path.name} is a symlink; refusing to write a decision through it"
|
|
75
|
+
)
|
|
76
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | _NO_FOLLOW, _NEW_FILE_MODE)
|
|
77
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
78
|
+
handle.write(render_decision_markdown(record))
|
|
79
|
+
return path
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def read_decision_file(path: Path) -> DecisionRecord:
|
|
83
|
+
return parse_decision_markdown(path.read_text(encoding="utf-8"))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_DECISION_ID_RE = re.compile(DECISION_ID_PATTERN)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class DecisionIdError(ValueError):
|
|
90
|
+
"""A decision id that cannot be used as a file name, or one already taken."""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def decision_filename(decision_id: str) -> str:
|
|
94
|
+
"""The file name for an id; refuses anything that is not a plain ``dec_`` id."""
|
|
95
|
+
if not _DECISION_ID_RE.fullmatch(decision_id):
|
|
96
|
+
raise DecisionIdError(
|
|
97
|
+
f"invalid decision id {decision_id!r}: expected dec_ then a-z, 0-9 or _"
|
|
98
|
+
)
|
|
99
|
+
return f"{decision_id}.md"
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Compare who a record says gave a verdict with who committed it. Git only, no network.
|
|
2
|
+
|
|
3
|
+
A name in a decision file is self-reported. When a verdict arrives in a diff, the author of the
|
|
4
|
+
commit that carried it is the independent witness; a mismatch is evidence worth a reviewer's
|
|
5
|
+
look, not proof of fraud (squash merges, bots and name variants all differ), so callers decide
|
|
6
|
+
whether it blocks.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from reasonledger_core.decisions.format import (
|
|
15
|
+
DECISIONS_DIR,
|
|
16
|
+
DecisionFormatError,
|
|
17
|
+
parse_decision_markdown,
|
|
18
|
+
read_decision_file,
|
|
19
|
+
)
|
|
20
|
+
from reasonledger_core.models.decision import DecisionFrontmatter
|
|
21
|
+
from reasonledger_core.sync.repo import (
|
|
22
|
+
decision_files_changed_since,
|
|
23
|
+
file_at_ref,
|
|
24
|
+
last_author_since,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# Frontmatter field naming the person, and the field whose change means that person acted.
|
|
28
|
+
_NAMED_FIELDS = (
|
|
29
|
+
("approved_by", ("oversight", "approved_by")),
|
|
30
|
+
("confirmed_by", ("confirmed_by",)),
|
|
31
|
+
("retired_by", ("retired_by",)),
|
|
32
|
+
("superseded_decided_by", ("superseded_decided_by",)),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class IdentityMismatch:
|
|
38
|
+
decision_id: str
|
|
39
|
+
field: str
|
|
40
|
+
recorded: str
|
|
41
|
+
committer: str
|
|
42
|
+
|
|
43
|
+
def describe(self) -> str:
|
|
44
|
+
return (
|
|
45
|
+
f"{self.decision_id}: {self.field} is {self.recorded!r} but the commit that added "
|
|
46
|
+
f"it was authored by {self.committer!r}"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _same_person(recorded: str, author: str) -> bool:
|
|
51
|
+
return recorded.strip().casefold() == author.strip().casefold()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _before(root: Path, base: str, filename: str) -> DecisionFrontmatter | None:
|
|
55
|
+
raw = file_at_ref(root, base, f"{DECISIONS_DIR.as_posix()}/{filename}")
|
|
56
|
+
if raw is None:
|
|
57
|
+
return None
|
|
58
|
+
try:
|
|
59
|
+
return parse_decision_markdown(raw).frontmatter
|
|
60
|
+
except DecisionFormatError:
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def identity_mismatches(root: Path, base: str) -> list[IdentityMismatch]:
|
|
65
|
+
"""Verdict names added or changed since ``base`` that differ from the committing author.
|
|
66
|
+
|
|
67
|
+
Records changed only in the working tree have no commit to compare and are skipped.
|
|
68
|
+
"""
|
|
69
|
+
changed = decision_files_changed_since(root, base, DECISIONS_DIR) or {}
|
|
70
|
+
found: list[IdentityMismatch] = []
|
|
71
|
+
for filename, status in sorted(changed.items()):
|
|
72
|
+
path = root / DECISIONS_DIR / filename
|
|
73
|
+
if status == "D" or not path.is_file():
|
|
74
|
+
continue
|
|
75
|
+
now = read_decision_file(path).frontmatter
|
|
76
|
+
before = _before(root, base, filename)
|
|
77
|
+
author = last_author_since(root, base, f"{DECISIONS_DIR.as_posix()}/{filename}")
|
|
78
|
+
if author is None:
|
|
79
|
+
continue
|
|
80
|
+
for name_field, watched in _NAMED_FIELDS:
|
|
81
|
+
recorded = getattr(now, name_field)
|
|
82
|
+
moved = before is None or any(getattr(now, f) != getattr(before, f) for f in watched)
|
|
83
|
+
if recorded and moved and not _same_person(recorded, author):
|
|
84
|
+
found.append(IdentityMismatch(now.id, name_field, recorded, author))
|
|
85
|
+
return found
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Stable decision id generation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import secrets
|
|
7
|
+
import string
|
|
8
|
+
|
|
9
|
+
DECISION_ID_PREFIX = "dec_"
|
|
10
|
+
DECISION_ID_SUFFIX_LEN = 6
|
|
11
|
+
CONTENT_ID_HASH_LEN = 12
|
|
12
|
+
_ALPHABET = string.ascii_lowercase + string.digits
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def generate_decision_id() -> str:
|
|
16
|
+
suffix = "".join(secrets.choice(_ALPHABET) for _ in range(DECISION_ID_SUFFIX_LEN))
|
|
17
|
+
return f"{DECISION_ID_PREFIX}{suffix}"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _content_decision_id(source_key: str) -> str:
|
|
21
|
+
"""Deterministic ``dec_<hash>`` from a stable source key.
|
|
22
|
+
|
|
23
|
+
Uses SHA-256 (not the salted builtin ``hash``) so ids are identical across
|
|
24
|
+
runs and processes — the property that makes re-harvest / re-import
|
|
25
|
+
idempotent.
|
|
26
|
+
"""
|
|
27
|
+
digest = hashlib.sha256(source_key.encode("utf-8")).hexdigest()[:CONTENT_ID_HASH_LEN]
|
|
28
|
+
return f"{DECISION_ID_PREFIX}{digest}"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def harvest_decision_id(source_key: str) -> str:
|
|
32
|
+
"""Deterministic id for a harvested PR so re-runs are idempotent."""
|
|
33
|
+
return _content_decision_id(source_key)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def import_decision_id(source_key: str) -> str:
|
|
37
|
+
"""Deterministic id for a doc-imported decision so re-imports are idempotent."""
|
|
38
|
+
return _content_decision_id(source_key)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def supersede_decision_id(source_key: str, content_key: str) -> str:
|
|
42
|
+
"""Deterministic id for a record that would supersede an earlier import.
|
|
43
|
+
|
|
44
|
+
Keyed on the content as well as the source, so a doc that changed under a
|
|
45
|
+
confirmed decision yields an id *distinct* from the record it replaces (both
|
|
46
|
+
must coexist in the ledger), while re-running the same import stays
|
|
47
|
+
idempotent.
|
|
48
|
+
"""
|
|
49
|
+
return _content_decision_id(f"{source_key}\x00{content_key}")
|