ratifypoint 3.0.4__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.
- ratifypoint/__init__.py +3 -0
- ratifypoint/adapter/__init__.py +5 -0
- ratifypoint/adapter/server.py +413 -0
- ratifypoint/adapter/texts.py +108 -0
- ratifypoint/cli.py +75 -0
- ratifypoint/commands/__init__.py +19 -0
- ratifypoint/commands/checks.py +58 -0
- ratifypoint/commands/clean.py +368 -0
- ratifypoint/commands/edit.py +370 -0
- ratifypoint/commands/init.py +52 -0
- ratifypoint/commands/save.py +98 -0
- ratifypoint/commands/session.py +251 -0
- ratifypoint/commands/versions.py +100 -0
- ratifypoint/delivery/__init__.py +27 -0
- ratifypoint/delivery/context.py +322 -0
- ratifypoint/delivery/receipt.py +70 -0
- ratifypoint/hooks/__init__.py +5 -0
- ratifypoint/hooks/hooks.py +57 -0
- ratifypoint/integrations/__init__.py +21 -0
- ratifypoint/integrations/install.py +144 -0
- ratifypoint/integrations/plugin.py +81 -0
- ratifypoint/knowledge/__init__.py +19 -0
- ratifypoint/knowledge/conflicts.py +106 -0
- ratifypoint/knowledge/duplicates.py +128 -0
- ratifypoint/knowledge/integrity.py +75 -0
- ratifypoint/knowledge/lifecycle.py +90 -0
- ratifypoint/knowledge/related.py +54 -0
- ratifypoint/model/__init__.py +7 -0
- ratifypoint/model/form.py +508 -0
- ratifypoint/model/ids.py +27 -0
- ratifypoint/model/json.py +51 -0
- ratifypoint/model/profile.py +26 -0
- ratifypoint/model/scope.py +51 -0
- ratifypoint/presentation/__init__.py +7 -0
- ratifypoint/presentation/form.py +238 -0
- ratifypoint/presentation/record.py +85 -0
- ratifypoint/presentation/search.py +106 -0
- ratifypoint/presentation/window.py +67 -0
- ratifypoint/report.py +333 -0
- ratifypoint/show.py +29 -0
- ratifypoint/status.py +69 -0
- ratifypoint/storage/__init__.py +15 -0
- ratifypoint/storage/files.py +228 -0
- ratifypoint/storage/project.py +149 -0
- ratifypoint-3.0.4.dist-info/METADATA +136 -0
- ratifypoint-3.0.4.dist-info/RECORD +50 -0
- ratifypoint-3.0.4.dist-info/WHEEL +5 -0
- ratifypoint-3.0.4.dist-info/entry_points.txt +2 -0
- ratifypoint-3.0.4.dist-info/licenses/LICENSE +202 -0
- ratifypoint-3.0.4.dist-info/top_level.txt +1 -0
ratifypoint/report.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""Compare current scoped records with versions in successful logged responses.
|
|
2
|
+
Client logs are the only delivery history; requests alone are not evidence.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Iterator, Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from datetime import UTC, date, datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Literal
|
|
12
|
+
|
|
13
|
+
from .commands import Session
|
|
14
|
+
from .delivery.context import START, applies_to_paths
|
|
15
|
+
from .delivery.receipt import DeliveryReceipt, revision
|
|
16
|
+
from .knowledge import Lifecycle
|
|
17
|
+
from .model.form import Record
|
|
18
|
+
from .storage import NotInRepositoryError
|
|
19
|
+
|
|
20
|
+
CLAUDE_EDITS = {
|
|
21
|
+
"Edit": "file_path",
|
|
22
|
+
"Write": "file_path",
|
|
23
|
+
"MultiEdit": "file_path",
|
|
24
|
+
"NotebookEdit": "notebook_path",
|
|
25
|
+
}
|
|
26
|
+
TOOL = "get_project_context"
|
|
27
|
+
CLIENTS = ("Claude Code", "Codex")
|
|
28
|
+
CLAUDE_LINES = ('"tool_use"', '"tool_result"')
|
|
29
|
+
CODEX_LINES = ('"session_meta"', '"item_completed"')
|
|
30
|
+
NOTE = (
|
|
31
|
+
"Counted: sessions that got the start context of RatifyPoint 1.1 or later; "
|
|
32
|
+
"successful edits through the clients' file tools; successful "
|
|
33
|
+
"get_project_context responses with delivery receipts. Compared with current "
|
|
34
|
+
"active, unanswered, unexpired scoped records created before each edit. "
|
|
35
|
+
"This is not a reconstruction of historical rules or proof of compliance. "
|
|
36
|
+
"Shell writes and project-wide context are not assessed. Times are UTC."
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class Event:
|
|
42
|
+
"""A successful file edit or completed context response in a client log."""
|
|
43
|
+
|
|
44
|
+
time: datetime
|
|
45
|
+
paths: list[str]
|
|
46
|
+
kind: Literal["edit", "context"]
|
|
47
|
+
receipt: DeliveryReceipt | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class FirstEdit:
|
|
52
|
+
"""Coverage of current record versions before the first edit of a file."""
|
|
53
|
+
|
|
54
|
+
client: str
|
|
55
|
+
time: datetime
|
|
56
|
+
path: str
|
|
57
|
+
missing: list[str]
|
|
58
|
+
unverified: list[str]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def report(start: Path, home: Path, since: str) -> tuple[str, int]:
|
|
62
|
+
"""Read client logs; compare delivered versions with today's scoped records.
|
|
63
|
+
Exit 1 when the repository or complete, readable evidence is unavailable."""
|
|
64
|
+
try:
|
|
65
|
+
session = Session(start, home, None, lambda window: None)
|
|
66
|
+
except NotInRepositoryError:
|
|
67
|
+
return "Not in a Git repository: RatifyPoint has no project here.\n", 1
|
|
68
|
+
records, problems = session.records()
|
|
69
|
+
if problems:
|
|
70
|
+
return (
|
|
71
|
+
"Report unavailable: project records are incomplete.\n"
|
|
72
|
+
+ "\n".join(problems)
|
|
73
|
+
+ "\n",
|
|
74
|
+
1,
|
|
75
|
+
)
|
|
76
|
+
records = Lifecycle(records, date.today().isoformat()).delivered
|
|
77
|
+
sessions: dict[str, int] = {client: 0 for client in CLIENTS}
|
|
78
|
+
edits: list[FirstEdit] = []
|
|
79
|
+
try:
|
|
80
|
+
for client, events in _sessions(session, home, since):
|
|
81
|
+
sessions[client] += 1
|
|
82
|
+
edits += _first_edits(client, events, records, date.fromisoformat(since))
|
|
83
|
+
except ValueError as error:
|
|
84
|
+
return f"Report unavailable: {error}.\n", 1
|
|
85
|
+
return _text(since, sessions, edits), 0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _sessions(
|
|
89
|
+
session: Session, home: Path, since: str
|
|
90
|
+
) -> Iterator[tuple[str, list[Event]]]:
|
|
91
|
+
"""Sessions in this project that received start context, including subagents."""
|
|
92
|
+
root = session.project.root
|
|
93
|
+
folder = home / ".claude" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", str(root))
|
|
94
|
+
claude = sorted(folder.glob("*.jsonl")) + sorted(folder.glob("*/subagents/*.jsonl"))
|
|
95
|
+
for log in claude:
|
|
96
|
+
if _written_before(log, since):
|
|
97
|
+
continue
|
|
98
|
+
messages, started = _read(log, CLAUDE_LINES)
|
|
99
|
+
if started:
|
|
100
|
+
try:
|
|
101
|
+
yield "Claude Code", _claude_events(messages, session)
|
|
102
|
+
except ValueError as error:
|
|
103
|
+
raise ValueError(f"{log}: {error}") from error
|
|
104
|
+
for log in sorted((home / ".codex" / "sessions").glob("*/*/*/rollout-*.jsonl")):
|
|
105
|
+
if _written_before(log, since):
|
|
106
|
+
continue
|
|
107
|
+
messages, started = _read(log, CODEX_LINES)
|
|
108
|
+
if started and _in_project(messages, root):
|
|
109
|
+
try:
|
|
110
|
+
yield "Codex", _codex_events(messages, session)
|
|
111
|
+
except ValueError as error:
|
|
112
|
+
raise ValueError(f"{log}: {error}") from error
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _claude_events(messages: list[dict[str, Any]], session: Session) -> list[Event]:
|
|
116
|
+
"""Interpret Claude's untyped log boundary and pair calls with their results."""
|
|
117
|
+
events: list[Event] = []
|
|
118
|
+
pending: dict[str, Event] = {}
|
|
119
|
+
for message in messages:
|
|
120
|
+
if message.get("type") not in ("assistant", "user"):
|
|
121
|
+
continue
|
|
122
|
+
time = _time(message["timestamp"])
|
|
123
|
+
content = message.get("message", {}).get("content")
|
|
124
|
+
if not isinstance(content, list):
|
|
125
|
+
continue
|
|
126
|
+
for block in content:
|
|
127
|
+
if not isinstance(block, dict):
|
|
128
|
+
continue
|
|
129
|
+
if block.get("type") == "tool_use":
|
|
130
|
+
name = block["name"]
|
|
131
|
+
arguments = block["input"]
|
|
132
|
+
if name in CLAUDE_EDITS:
|
|
133
|
+
paths = _project_paths(session, [arguments.get(CLAUDE_EDITS[name])])
|
|
134
|
+
pending[block["id"]] = Event(time, paths, "edit")
|
|
135
|
+
elif name.endswith(TOOL) and arguments.get("paths"):
|
|
136
|
+
paths = _project_paths(session, arguments["paths"])
|
|
137
|
+
pending[block["id"]] = Event(time, paths, "context")
|
|
138
|
+
continue
|
|
139
|
+
if block.get("type") != "tool_result":
|
|
140
|
+
continue
|
|
141
|
+
request = pending.pop(block.get("tool_use_id", ""), None)
|
|
142
|
+
if request is None or block.get("is_error"):
|
|
143
|
+
continue
|
|
144
|
+
receipt = None
|
|
145
|
+
if request.kind == "context":
|
|
146
|
+
receipt = DeliveryReceipt.read(_content_text(block.get("content")))
|
|
147
|
+
events.append(Event(time, request.paths, request.kind, receipt))
|
|
148
|
+
return events
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _in_project(messages: list[dict[str, Any]], root: Path) -> bool:
|
|
152
|
+
for message in messages:
|
|
153
|
+
if message.get("type") == "session_meta":
|
|
154
|
+
return Path(message["payload"]["cwd"]).is_relative_to(root)
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _codex_events(messages: list[dict[str, Any]], session: Session) -> list[Event]:
|
|
159
|
+
"""Interpret Codex's untyped log boundary; failed calls give no evidence."""
|
|
160
|
+
events: list[Event] = []
|
|
161
|
+
for message in messages:
|
|
162
|
+
payload = message.get("payload")
|
|
163
|
+
if not isinstance(payload, dict) or payload.get("type") != "item_completed":
|
|
164
|
+
continue
|
|
165
|
+
item = payload["item"]
|
|
166
|
+
time = _time(message["timestamp"])
|
|
167
|
+
if item["type"] == "FileChange":
|
|
168
|
+
if item.get("status") == "failed":
|
|
169
|
+
continue
|
|
170
|
+
changed = _project_paths(session, list(item["changes"]))
|
|
171
|
+
events.append(Event(time, changed, "edit"))
|
|
172
|
+
continue
|
|
173
|
+
if item["type"] != "McpToolCall" or item.get("tool") != TOOL:
|
|
174
|
+
continue
|
|
175
|
+
if item.get("status") != "completed":
|
|
176
|
+
continue
|
|
177
|
+
response = item.get("result")
|
|
178
|
+
if (
|
|
179
|
+
not isinstance(response, dict)
|
|
180
|
+
or response.get("isError")
|
|
181
|
+
or response.get("is_error")
|
|
182
|
+
):
|
|
183
|
+
continue
|
|
184
|
+
requested = (item.get("arguments") or {}).get("paths")
|
|
185
|
+
if requested:
|
|
186
|
+
paths = _project_paths(session, requested)
|
|
187
|
+
receipt = DeliveryReceipt.read(_content_text(response.get("content")))
|
|
188
|
+
events.append(Event(time, paths, "context", receipt))
|
|
189
|
+
return events
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _content_text(content: object) -> str:
|
|
193
|
+
"""Client logs retain MCP text either directly or as content blocks."""
|
|
194
|
+
if isinstance(content, str):
|
|
195
|
+
return content
|
|
196
|
+
if isinstance(content, list):
|
|
197
|
+
return "\n".join(
|
|
198
|
+
block["text"]
|
|
199
|
+
for block in content
|
|
200
|
+
if isinstance(block, dict)
|
|
201
|
+
and block.get("type") == "text"
|
|
202
|
+
and isinstance(block.get("text"), str)
|
|
203
|
+
)
|
|
204
|
+
return ""
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _first_edits(
|
|
208
|
+
client: str, events: list[Event], records: list[Record], since: date
|
|
209
|
+
) -> list[FirstEdit]:
|
|
210
|
+
"""Legacy responses and in-place version differences leave coverage unknown."""
|
|
211
|
+
versions = {record["id"]: revision(record) for record in records}
|
|
212
|
+
given: dict[str, set[str]] = {}
|
|
213
|
+
unverified_paths: set[str] = set()
|
|
214
|
+
seen: set[str] = set()
|
|
215
|
+
found = []
|
|
216
|
+
for event in sorted(events, key=lambda event: event.time):
|
|
217
|
+
if event.kind == "context":
|
|
218
|
+
if event.receipt is None or not event.receipt.complete:
|
|
219
|
+
unverified_paths.update(event.paths)
|
|
220
|
+
if event.receipt is not None:
|
|
221
|
+
for identity, digest in event.receipt.records.items():
|
|
222
|
+
given.setdefault(identity, set()).add(digest)
|
|
223
|
+
continue
|
|
224
|
+
for path in event.paths:
|
|
225
|
+
if path in seen:
|
|
226
|
+
continue
|
|
227
|
+
seen.add(path)
|
|
228
|
+
if event.time.date() < since:
|
|
229
|
+
continue
|
|
230
|
+
needed = [
|
|
231
|
+
record
|
|
232
|
+
for record in records
|
|
233
|
+
if _time(record["created_at"]) <= event.time
|
|
234
|
+
and applies_to_paths(record, [path])
|
|
235
|
+
]
|
|
236
|
+
if not needed:
|
|
237
|
+
continue
|
|
238
|
+
missing: list[str] = []
|
|
239
|
+
unverified: list[str] = []
|
|
240
|
+
for record in needed:
|
|
241
|
+
identity = record["id"]
|
|
242
|
+
if versions[identity] in given.get(identity, set()):
|
|
243
|
+
continue
|
|
244
|
+
if identity in given or any(
|
|
245
|
+
applies_to_paths(record, [requested])
|
|
246
|
+
for requested in unverified_paths
|
|
247
|
+
):
|
|
248
|
+
unverified.append(identity)
|
|
249
|
+
else:
|
|
250
|
+
missing.append(identity)
|
|
251
|
+
found.append(FirstEdit(client, event.time, path, missing, unverified))
|
|
252
|
+
return found
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _text(since: str, sessions: dict[str, int], edits: list[FirstEdit]) -> str:
|
|
256
|
+
lines = [f"RatifyPoint report since {since}, from this project's session logs."]
|
|
257
|
+
for client in CLIENTS:
|
|
258
|
+
mine = [edit for edit in edits if edit.client == client]
|
|
259
|
+
had = sum(not edit.missing and not edit.unverified for edit in mine)
|
|
260
|
+
unknown = sum(bool(edit.unverified) for edit in mine)
|
|
261
|
+
lines.append(
|
|
262
|
+
f"{client}: {sessions[client]} sessions; files with records for folders "
|
|
263
|
+
f"and files changed: {len(mine)}; current versions received before "
|
|
264
|
+
f"the change: {had}; unverified: {unknown}."
|
|
265
|
+
)
|
|
266
|
+
lines.append(NOTE)
|
|
267
|
+
if not edits:
|
|
268
|
+
lines.append(
|
|
269
|
+
"No files with current records for folders and files were changed."
|
|
270
|
+
)
|
|
271
|
+
return "\n".join(lines) + "\n"
|
|
272
|
+
had = sum(not edit.missing and not edit.unverified for edit in edits)
|
|
273
|
+
share = round(100 * had / len(edits))
|
|
274
|
+
lines.append(f"Verified coverage: {had} of {len(edits)} ({share}%).")
|
|
275
|
+
missed = [edit for edit in edits if edit.missing or edit.unverified]
|
|
276
|
+
if missed:
|
|
277
|
+
lines.append("Edits without verified current context:")
|
|
278
|
+
for edit in sorted(missed, key=lambda edit: edit.time):
|
|
279
|
+
when = edit.time.strftime("%Y-%m-%d %H:%M")
|
|
280
|
+
lines.append(
|
|
281
|
+
f"- {when} {edit.client} {edit.path}: "
|
|
282
|
+
f"not received: {', '.join(edit.missing) or 'none'}; "
|
|
283
|
+
f"unverified: {', '.join(edit.unverified) or 'none'}"
|
|
284
|
+
)
|
|
285
|
+
return "\n".join(lines) + "\n"
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _project_paths(session: Session, paths: Sequence[object]) -> list[str]:
|
|
289
|
+
"""Normalize project paths; outside paths are irrelevant to this report."""
|
|
290
|
+
found = []
|
|
291
|
+
for path in paths:
|
|
292
|
+
if not isinstance(path, str) or not path:
|
|
293
|
+
continue
|
|
294
|
+
normal = session.normal_path(path)
|
|
295
|
+
if normal:
|
|
296
|
+
found.append(normal)
|
|
297
|
+
return found
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _written_before(log: Path, since: str) -> bool:
|
|
301
|
+
written = datetime.fromtimestamp(log.stat().st_mtime, UTC).date().isoformat()
|
|
302
|
+
return written < since
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _time(timestamp: str) -> datetime:
|
|
306
|
+
"""Normalize client offsets to UTC without losing subsecond event order."""
|
|
307
|
+
return datetime.fromisoformat(timestamp.replace("Z", "+00:00")).astimezone(UTC)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _read(log: Path, kinds: tuple[str, ...]) -> tuple[list[dict[str, Any]], bool]:
|
|
311
|
+
"""Read relevant external log objects only for sessions with start context."""
|
|
312
|
+
lines = []
|
|
313
|
+
started = False
|
|
314
|
+
with log.open(encoding="utf-8") as file:
|
|
315
|
+
for line in file:
|
|
316
|
+
if START in line:
|
|
317
|
+
started = True
|
|
318
|
+
if any(kind in line for kind in kinds):
|
|
319
|
+
lines.append(line)
|
|
320
|
+
if not started:
|
|
321
|
+
return [], False
|
|
322
|
+
messages = []
|
|
323
|
+
for line in lines:
|
|
324
|
+
try:
|
|
325
|
+
message = json.loads(line)
|
|
326
|
+
except json.JSONDecodeError as error:
|
|
327
|
+
# Only an unfinished final append may be incomplete during a session.
|
|
328
|
+
if not line.endswith("\n"):
|
|
329
|
+
continue
|
|
330
|
+
raise ValueError(f"{log}: invalid client log JSON: {error.msg}") from error
|
|
331
|
+
if isinstance(message, dict):
|
|
332
|
+
messages.append(message)
|
|
333
|
+
return messages, True
|
ratifypoint/show.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""`ratifypoint show`: the project's knowledge as the agent gets it, for a person.
|
|
2
|
+
Nothing is stored."""
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .commands import CommandError, Session
|
|
7
|
+
from .delivery import folder_records, start_context
|
|
8
|
+
from .storage import NotInRepositoryError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def show(start: Path, home: Path, paths: list[str]) -> tuple[str, int]:
|
|
12
|
+
"""Without paths: the start context and every record for folders and files.
|
|
13
|
+
With paths, from the current folder: what get_project_context gives for
|
|
14
|
+
them. The exit code is 1 on an error."""
|
|
15
|
+
try:
|
|
16
|
+
session = Session(start, home, None, lambda window: None)
|
|
17
|
+
except NotInRepositoryError:
|
|
18
|
+
return "Not in a Git repository: RatifyPoint has no project here.\n", 1
|
|
19
|
+
if paths:
|
|
20
|
+
absolute = [str((start / path).resolve()) for path in paths]
|
|
21
|
+
try:
|
|
22
|
+
return session.project_context(absolute), 0
|
|
23
|
+
except CommandError as error:
|
|
24
|
+
return str(error), 1
|
|
25
|
+
context = session.context()
|
|
26
|
+
listing = folder_records(context)
|
|
27
|
+
if not listing:
|
|
28
|
+
return start_context(context), 0
|
|
29
|
+
return f"{start_context(context)}\n{listing}", 0
|
ratifypoint/status.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""`ratifypoint status`: the project, the integrations and problems in the data,
|
|
2
|
+
for a person. Nothing is stored."""
|
|
3
|
+
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
from .commands import Session
|
|
9
|
+
from .delivery import start_context
|
|
10
|
+
from .hooks.hooks import CLAUDE_CODE_LIMIT
|
|
11
|
+
from .integrations import CLIENTS, files_version, up_to_date
|
|
12
|
+
from .model.form import Record
|
|
13
|
+
from .model.scope import PROJECT
|
|
14
|
+
from .storage import NotInRepositoryError, Project
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def status(start: Path, home: Path) -> tuple[str, int]:
|
|
18
|
+
"""The report and the exit code: 1 when the data has problems."""
|
|
19
|
+
try:
|
|
20
|
+
session = Session(start, home, None, lambda window: None)
|
|
21
|
+
except NotInRepositoryError:
|
|
22
|
+
lines = ["Project: not in a Git repository.", *_integrations(home)]
|
|
23
|
+
return "\n".join(lines) + "\n", 0
|
|
24
|
+
context = session.context()
|
|
25
|
+
lines = [_project(session.project, context.records), *_integrations(home)]
|
|
26
|
+
size = len(start_context(context))
|
|
27
|
+
line = f"Start context: {size:,} characters."
|
|
28
|
+
if size > CLAUDE_CODE_LIMIT:
|
|
29
|
+
line += " Claude Code gives a text this long to the agent as a file."
|
|
30
|
+
lines.append(line)
|
|
31
|
+
code = 0
|
|
32
|
+
if context.problems:
|
|
33
|
+
lines += ["Problems:", *(f"- {problem}" for problem in context.problems)]
|
|
34
|
+
code = 1
|
|
35
|
+
return "\n".join(lines) + "\n", code
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _project(project: Project, records: Sequence[Record]) -> str:
|
|
39
|
+
active = [record for record in records if record["state"] == "active"]
|
|
40
|
+
everywhere = [record for record in active if PROJECT in record["scopes"]]
|
|
41
|
+
counts = (
|
|
42
|
+
f"{len(active)} records: {len(everywhere)} for the whole project, "
|
|
43
|
+
f"{len(active) - len(everywhere)} for folders and files."
|
|
44
|
+
)
|
|
45
|
+
if not project.set_up:
|
|
46
|
+
return f"Project: not set up. {counts}"
|
|
47
|
+
return f"Project: set up, {project.mode} mode. {counts}"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _integrations(home: Path) -> list[str]:
|
|
51
|
+
lines = []
|
|
52
|
+
for client, known in CLIENTS.items():
|
|
53
|
+
current = up_to_date(client, home)
|
|
54
|
+
if current is None:
|
|
55
|
+
lines.append(
|
|
56
|
+
f"{known.title}: not installed. Run: ratifypoint install {client}"
|
|
57
|
+
)
|
|
58
|
+
continue
|
|
59
|
+
if not current:
|
|
60
|
+
# Both versions: a different ratifypoint earlier in PATH (a development
|
|
61
|
+
# venv) reads "out of date" while the installed one is current.
|
|
62
|
+
lines.append(
|
|
63
|
+
f"{known.title}: installed, plugin files out of date: they are from "
|
|
64
|
+
f"RatifyPoint {files_version(client, home)}, this ratifypoint is "
|
|
65
|
+
f"{__version__}. Run: ratifypoint install {client}"
|
|
66
|
+
)
|
|
67
|
+
continue
|
|
68
|
+
lines.append(f"{known.title}: installed, plugin files up to date.")
|
|
69
|
+
return lines
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Where records and settings are kept, and how files look."""
|
|
2
|
+
|
|
3
|
+
from .files import read_language, read_records, write_language, write_record
|
|
4
|
+
from .project import NotInRepositoryError, Project, open_project, set_mode
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"NotInRepositoryError",
|
|
8
|
+
"Project",
|
|
9
|
+
"open_project",
|
|
10
|
+
"read_language",
|
|
11
|
+
"read_records",
|
|
12
|
+
"set_mode",
|
|
13
|
+
"write_language",
|
|
14
|
+
"write_record",
|
|
15
|
+
]
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Record files and project settings."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from dataclasses import asdict
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from ..model.form import (
|
|
12
|
+
FORM,
|
|
13
|
+
FORMAT_VERSION,
|
|
14
|
+
LEGACY_FIELDS,
|
|
15
|
+
SERVICE_ORDER,
|
|
16
|
+
Record,
|
|
17
|
+
normalized,
|
|
18
|
+
stored_errors,
|
|
19
|
+
)
|
|
20
|
+
from ..model.json import JSONValue, json_value
|
|
21
|
+
from .project import Project
|
|
22
|
+
|
|
23
|
+
CONFLICT_MARKERS = ("<<<<<<< ", "=======", ">>>>>>> ")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RecoveryError(Exception):
|
|
27
|
+
"""An interrupted approved write needs the user's original checkout or files."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def write_record(folder: Path, record: Record) -> None:
|
|
31
|
+
"""Write `<folder>/<kind>/<id>.json`, replacing the file in one step:
|
|
32
|
+
id, form fields, legacy fields it has, then service fields; empty values as
|
|
33
|
+
null."""
|
|
34
|
+
_write_json(folder / record["kind"] / f"{record['id']}.json", _stored(record))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _stored(record: Record) -> dict[str, object]:
|
|
38
|
+
known = {"id", "kind", *(field.name for field in FORM[record["kind"]])}
|
|
39
|
+
unknown = set(record) - known - set(LEGACY_FIELDS) - set(SERVICE_ORDER)
|
|
40
|
+
if unknown:
|
|
41
|
+
raise ValueError(f"{record['id']}: unknown fields {sorted(unknown)}")
|
|
42
|
+
data = {"id": record["id"], **normalized(record)}
|
|
43
|
+
for name in LEGACY_FIELDS:
|
|
44
|
+
if name in record:
|
|
45
|
+
data[name] = record[name]
|
|
46
|
+
for name in SERVICE_ORDER:
|
|
47
|
+
data[name] = record.get(name)
|
|
48
|
+
data["format_version"] = record.get("format_version", FORMAT_VERSION)
|
|
49
|
+
return data
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def write_records(project: Project, records: Sequence[Record]) -> None:
|
|
53
|
+
"""Publish an approved batch under the session lock, resumable after a crash."""
|
|
54
|
+
journal = project.write_journal
|
|
55
|
+
if journal.exists():
|
|
56
|
+
raise RecoveryError(
|
|
57
|
+
f"Cannot start another record write: recover {journal} first."
|
|
58
|
+
)
|
|
59
|
+
changes = []
|
|
60
|
+
for record in records:
|
|
61
|
+
path = project.records / record["kind"] / f"{record['id']}.json"
|
|
62
|
+
changes.append({"before": _file_hash(path), "after": _stored(record)})
|
|
63
|
+
_write_json(
|
|
64
|
+
journal,
|
|
65
|
+
{
|
|
66
|
+
"base": str(project.base),
|
|
67
|
+
"checkout": asdict(project.checkout())
|
|
68
|
+
if project.mode == "shared"
|
|
69
|
+
else None,
|
|
70
|
+
"records": changes,
|
|
71
|
+
},
|
|
72
|
+
)
|
|
73
|
+
recover_records(project)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def recover_records(project: Project) -> None:
|
|
77
|
+
"""Finish an interrupted approved batch under the session lock.
|
|
78
|
+
|
|
79
|
+
A changed checkout or an external file edit blocks recovery rather than
|
|
80
|
+
overwriting the new state. The journal remains available for explicit repair.
|
|
81
|
+
"""
|
|
82
|
+
journal = project.write_journal
|
|
83
|
+
if not journal.exists():
|
|
84
|
+
return
|
|
85
|
+
pending, problem = _read_json(project, journal)
|
|
86
|
+
if problem:
|
|
87
|
+
raise RecoveryError(f"Cannot recover approved record write: {problem}")
|
|
88
|
+
assert pending is not None
|
|
89
|
+
checkout = asdict(project.checkout()) if project.mode == "shared" else None
|
|
90
|
+
if pending.get("base") != str(project.base) or pending.get("checkout") != checkout:
|
|
91
|
+
raise RecoveryError(
|
|
92
|
+
f"Cannot recover {journal}: the storage location, branch or commit "
|
|
93
|
+
"changed. Return to the original checkout before reading or writing."
|
|
94
|
+
)
|
|
95
|
+
changes = pending.get("records")
|
|
96
|
+
if not isinstance(changes, list) or not changes:
|
|
97
|
+
raise RecoveryError(
|
|
98
|
+
f"Cannot recover {journal}: records must be a non-empty list."
|
|
99
|
+
)
|
|
100
|
+
writes: list[tuple[Path, dict[str, JSONValue]]] = []
|
|
101
|
+
for change in changes:
|
|
102
|
+
if not isinstance(change, dict) or not isinstance(change.get("after"), dict):
|
|
103
|
+
raise RecoveryError(
|
|
104
|
+
f"Cannot recover {journal}: each change needs a record."
|
|
105
|
+
)
|
|
106
|
+
record = change["after"]
|
|
107
|
+
assert isinstance(record, dict)
|
|
108
|
+
errors = stored_errors(record)
|
|
109
|
+
identity = record.get("id")
|
|
110
|
+
kind = record.get("kind")
|
|
111
|
+
if errors or not isinstance(identity, str) or kind not in FORM:
|
|
112
|
+
raise RecoveryError(f"Cannot recover {journal}: invalid record: {errors}.")
|
|
113
|
+
assert isinstance(kind, str)
|
|
114
|
+
if identity in (".", "..") or "/" in identity or "\\" in identity:
|
|
115
|
+
raise RecoveryError(
|
|
116
|
+
f"Cannot recover {journal}: invalid record id {identity!r}."
|
|
117
|
+
)
|
|
118
|
+
path = project.records / kind / f"{identity}.json"
|
|
119
|
+
before = change.get("before")
|
|
120
|
+
if before is not None and not isinstance(before, str):
|
|
121
|
+
raise RecoveryError(f"Cannot recover {journal}: invalid prior file hash.")
|
|
122
|
+
current_hash = _file_hash(path)
|
|
123
|
+
if current_hash == before:
|
|
124
|
+
writes.append((path, record))
|
|
125
|
+
continue
|
|
126
|
+
current, error = _read_json(project, path) if path.exists() else (None, None)
|
|
127
|
+
if error or current != record:
|
|
128
|
+
raise RecoveryError(
|
|
129
|
+
f"Cannot recover {journal}: {path} changed outside the approved "
|
|
130
|
+
"write. Restore its original or approved contents before recovery."
|
|
131
|
+
)
|
|
132
|
+
for path, record in writes:
|
|
133
|
+
_write_json(path, record)
|
|
134
|
+
journal.unlink()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _file_hash(path: Path) -> str | None:
|
|
138
|
+
return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def read_records(project: Project, folder: Path) -> tuple[list[Record], list[str]]:
|
|
142
|
+
"""All readable records of a folder, and a line for each damaged file."""
|
|
143
|
+
records: list[Record] = []
|
|
144
|
+
problems = []
|
|
145
|
+
for path in sorted(folder.glob("*/*.json")):
|
|
146
|
+
data, problem = _read_json(project, path)
|
|
147
|
+
if problem:
|
|
148
|
+
problems.append(problem)
|
|
149
|
+
continue
|
|
150
|
+
assert data is not None
|
|
151
|
+
if "see_also" in data:
|
|
152
|
+
problems.append(
|
|
153
|
+
f"{project.shown(path)} uses the old see_also field. "
|
|
154
|
+
"Migrate this project's record files to related "
|
|
155
|
+
"before using RatifyPoint 3."
|
|
156
|
+
)
|
|
157
|
+
continue
|
|
158
|
+
violations = stored_errors(data)
|
|
159
|
+
if data.get("id") != path.stem or data.get("kind") != path.parent.name:
|
|
160
|
+
violations.append("Record id or kind does not match its file path.")
|
|
161
|
+
if violations:
|
|
162
|
+
problems.append(f"{project.shown(path)} is invalid: {' '.join(violations)}")
|
|
163
|
+
continue
|
|
164
|
+
records.append(data)
|
|
165
|
+
return records, problems
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def read_language(project: Project) -> tuple[str | None, list[str]]:
|
|
169
|
+
"""The records language; none while settings are missing or damaged."""
|
|
170
|
+
if not project.settings.exists():
|
|
171
|
+
return None, []
|
|
172
|
+
data, problem = _read_json(project, project.settings)
|
|
173
|
+
if problem:
|
|
174
|
+
return None, [problem]
|
|
175
|
+
assert data is not None
|
|
176
|
+
language = data.get("language")
|
|
177
|
+
if not isinstance(language, str) or not language.strip():
|
|
178
|
+
return None, [
|
|
179
|
+
f"{project.shown(project.settings)}: language must be non-empty text."
|
|
180
|
+
]
|
|
181
|
+
return language, []
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def write_language(project: Project, language: str) -> None:
|
|
185
|
+
_write_json(project.settings, {"language": language})
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _read_json(
|
|
189
|
+
project: Project, path: Path
|
|
190
|
+
) -> tuple[dict[str, JSONValue] | None, str | None]:
|
|
191
|
+
shown = project.shown(path)
|
|
192
|
+
try:
|
|
193
|
+
text = path.read_text(encoding="utf-8")
|
|
194
|
+
except UnicodeDecodeError as error:
|
|
195
|
+
return None, (
|
|
196
|
+
f"{shown} is not valid UTF-8 (byte {error.start}). "
|
|
197
|
+
"Fix: restore or correct the file."
|
|
198
|
+
)
|
|
199
|
+
if any(line.startswith(CONFLICT_MARKERS) for line in text.splitlines()):
|
|
200
|
+
return None, (
|
|
201
|
+
f"{shown} has Git merge conflict markers. "
|
|
202
|
+
"Fix: resolve the merge conflict in this file."
|
|
203
|
+
)
|
|
204
|
+
try:
|
|
205
|
+
data = json_value(json.loads(text), shown)
|
|
206
|
+
except json.JSONDecodeError as error:
|
|
207
|
+
fix = "correct the file"
|
|
208
|
+
if project.in_git(path):
|
|
209
|
+
fix = "correct the file or restore it from Git"
|
|
210
|
+
return None, f"{shown} is not valid JSON (line {error.lineno}). Fix: {fix}."
|
|
211
|
+
except ValueError as error:
|
|
212
|
+
return None, str(error)
|
|
213
|
+
if not isinstance(data, dict):
|
|
214
|
+
return (
|
|
215
|
+
None,
|
|
216
|
+
f"{shown} must contain a JSON object. Fix: restore or correct the file.",
|
|
217
|
+
)
|
|
218
|
+
return data, None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _write_json(path: Path, data: object) -> None:
|
|
222
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
223
|
+
with tempfile.NamedTemporaryFile(
|
|
224
|
+
"w", encoding="utf-8", dir=path.parent, suffix=".tmp", delete=False
|
|
225
|
+
) as file:
|
|
226
|
+
json.dump(data, file, ensure_ascii=False, indent=2)
|
|
227
|
+
file.write("\n")
|
|
228
|
+
os.replace(file.name, path)
|