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.
Files changed (50) hide show
  1. ratifypoint/__init__.py +3 -0
  2. ratifypoint/adapter/__init__.py +5 -0
  3. ratifypoint/adapter/server.py +413 -0
  4. ratifypoint/adapter/texts.py +108 -0
  5. ratifypoint/cli.py +75 -0
  6. ratifypoint/commands/__init__.py +19 -0
  7. ratifypoint/commands/checks.py +58 -0
  8. ratifypoint/commands/clean.py +368 -0
  9. ratifypoint/commands/edit.py +370 -0
  10. ratifypoint/commands/init.py +52 -0
  11. ratifypoint/commands/save.py +98 -0
  12. ratifypoint/commands/session.py +251 -0
  13. ratifypoint/commands/versions.py +100 -0
  14. ratifypoint/delivery/__init__.py +27 -0
  15. ratifypoint/delivery/context.py +322 -0
  16. ratifypoint/delivery/receipt.py +70 -0
  17. ratifypoint/hooks/__init__.py +5 -0
  18. ratifypoint/hooks/hooks.py +57 -0
  19. ratifypoint/integrations/__init__.py +21 -0
  20. ratifypoint/integrations/install.py +144 -0
  21. ratifypoint/integrations/plugin.py +81 -0
  22. ratifypoint/knowledge/__init__.py +19 -0
  23. ratifypoint/knowledge/conflicts.py +106 -0
  24. ratifypoint/knowledge/duplicates.py +128 -0
  25. ratifypoint/knowledge/integrity.py +75 -0
  26. ratifypoint/knowledge/lifecycle.py +90 -0
  27. ratifypoint/knowledge/related.py +54 -0
  28. ratifypoint/model/__init__.py +7 -0
  29. ratifypoint/model/form.py +508 -0
  30. ratifypoint/model/ids.py +27 -0
  31. ratifypoint/model/json.py +51 -0
  32. ratifypoint/model/profile.py +26 -0
  33. ratifypoint/model/scope.py +51 -0
  34. ratifypoint/presentation/__init__.py +7 -0
  35. ratifypoint/presentation/form.py +238 -0
  36. ratifypoint/presentation/record.py +85 -0
  37. ratifypoint/presentation/search.py +106 -0
  38. ratifypoint/presentation/window.py +67 -0
  39. ratifypoint/report.py +333 -0
  40. ratifypoint/show.py +29 -0
  41. ratifypoint/status.py +69 -0
  42. ratifypoint/storage/__init__.py +15 -0
  43. ratifypoint/storage/files.py +228 -0
  44. ratifypoint/storage/project.py +149 -0
  45. ratifypoint-3.0.4.dist-info/METADATA +136 -0
  46. ratifypoint-3.0.4.dist-info/RECORD +50 -0
  47. ratifypoint-3.0.4.dist-info/WHEEL +5 -0
  48. ratifypoint-3.0.4.dist-info/entry_points.txt +2 -0
  49. ratifypoint-3.0.4.dist-info/licenses/LICENSE +202 -0
  50. ratifypoint-3.0.4.dist-info/top_level.txt +1 -0
@@ -0,0 +1,58 @@
1
+ """Checks of a record before it is stored, shared by save_record and edit_record."""
2
+
3
+ from ..knowledge import secrets_in
4
+ from ..model.form import Record
5
+ from ..model.scope import PROJECT, is_pattern
6
+ from .session import Session
7
+ from .versions import author
8
+
9
+ NOT_SET_UP = (
10
+ "RatifyPoint is not set up in this project. Fix: call init_project(); it asks "
11
+ "the user where to keep records and in which language, then save again."
12
+ )
13
+
14
+
15
+ def author_problems(session: Session) -> list[str]:
16
+ """The author of new records and changes comes from Git."""
17
+ if all(author(session.project.root).values()):
18
+ return []
19
+ return [
20
+ "Git user.name and user.email are not set. Fix: ask the user to set them "
21
+ "with git config."
22
+ ]
23
+
24
+
25
+ def record_problems(
26
+ session: Session, record: Record, every: dict[str, Record]
27
+ ) -> list[str]:
28
+ """Secrets, the set-up, paths and links of a record valid in form."""
29
+ problems = secrets_in(record)
30
+ if not session.project.set_up:
31
+ problems.append(NOT_SET_UP)
32
+ for name in ("scopes", "exclusions"):
33
+ for number, path in enumerate(record.get(name) or [], start=1):
34
+ if path == PROJECT or is_pattern(path):
35
+ continue
36
+ if not session.file(path).exists():
37
+ problems.append(
38
+ f'{name}[{number}]: path "{path}" does not exist. '
39
+ "Fix: use an existing path or a path pattern."
40
+ )
41
+ return problems + link_problems(record, every)
42
+
43
+
44
+ def link_problems(record: Record, every: dict[str, Record]) -> list[str]:
45
+ problems = []
46
+ question = record.get("question_id")
47
+ if question and every.get(question, {}).get("kind") != "question":
48
+ problems.append(
49
+ f'question_id: "{question}" is not a question. '
50
+ "Fix: use the id of a question from search_records."
51
+ )
52
+ for number, other in enumerate(record.get("related") or [], start=1):
53
+ if other not in every:
54
+ problems.append(
55
+ f'related[{number}]: record "{other}" does not exist. '
56
+ "Fix: use an existing id."
57
+ )
58
+ return problems
@@ -0,0 +1,368 @@
1
+ """clean_memory: a cleanup run, portion by portion."""
2
+
3
+ import re
4
+ import subprocess
5
+ from dataclasses import dataclass
6
+ from datetime import date, datetime, timedelta
7
+ from itertools import combinations
8
+ from pathlib import Path
9
+
10
+ from ..delivery import EDITED, HEADINGS, record_line
11
+ from ..knowledge import Lifecycle, edited
12
+ from ..knowledge.related import related_changes
13
+ from ..model.form import Record
14
+ from ..model.scope import PROJECT, is_pattern, shown_scope
15
+ from .session import Session
16
+
17
+ # 8 thousand tokens, a token taken as 4 characters.
18
+ PORTION = 32000
19
+ # Share of significant words two records of one scope have in common to be
20
+ # shown as worded alike: a candidate duplicate, never a verdict.
21
+ SIMILAR = 0.5
22
+ # A rule is usually saved while its code is written; commits within this time
23
+ # after it was saved or confirmed are that work, not a change to doubt.
24
+ GRACE = timedelta(days=1)
25
+ FIRST = (
26
+ "Memory cleanup in 3 passes: 1 records to doubt, 2 duplicates and "
27
+ "contradictions, 3 open questions. Each item asks one question; answer with "
28
+ "edit_record actions."
29
+ )
30
+ TITLES = {
31
+ 1: "records to doubt",
32
+ 2: "duplicates and contradictions",
33
+ 3: "open questions",
34
+ }
35
+ ANSWERS = {
36
+ 1: (
37
+ "Answers: read the record and any changed files or related records. "
38
+ "A related change is a reason to review, not proof this record is wrong. "
39
+ 'Still correct: {"id": "<id>", "action": "confirm"}; it no longer '
40
+ "holds: ask the user; partly correct, or a new scope path or date: "
41
+ '{"id": "<id>", "action": "replace", <corrected fields>}; no longer true, '
42
+ 'or another record states it correctly: {"id": "<id>", "action": '
43
+ '"delete"}. Skip what you can\'t check now.'
44
+ ),
45
+ 2: (
46
+ "Which of these say the same thing, and which contradict each other? Does "
47
+ "any state several requirements?\n"
48
+ 'Answers: same thing: {"ids": ["<id>", "<id>"], "action": "replace", '
49
+ "<merged fields>}; contradiction: ask the user which one is right, then "
50
+ '{"id": "<wrong one>", "action": "delete"}; if the user can\'t decide now, '
51
+ "save a question with save_record whose related names both: it is shown "
52
+ "next to them until it is answered. A narrower scope that differs because "
53
+ 'of its folder is not a contradiction: {"id": "<id>", "action": '
54
+ '"not_conflict", "other_id": "<id>"}. Closely related: {"id": "<id>", '
55
+ '"action": "link", "other_id": "<id>"}. Several requirements: save each as '
56
+ 'its own record with save_record, then {"id": "<id>", "action": '
57
+ '"delete"}.'
58
+ ),
59
+ 3: (
60
+ 'Answers: answered by a record: {"id": "<question id>", "action": "close", '
61
+ '"answer_id": "<record id>"}; the user knows the answer: save it with '
62
+ 'save_record and "question_id": "<question id>". Skip questions with no '
63
+ "answer yet."
64
+ ),
65
+ }
66
+ NEXT = (
67
+ "This tool only reads records. Next: propose each change separately with "
68
+ "edit_record and each new record with save_record; skip this if there are "
69
+ "none. Each proposal requires direct MCP confirmation. After the user has "
70
+ "answered, call clean_memory() for the next portion."
71
+ )
72
+ END = (
73
+ "Cleanup complete; no more clean_memory calls are needed. Items found: {passes}. "
74
+ "Tell the user what was checked, what was found and what was changed (from the "
75
+ "edit_record and save_record results), even if nothing."
76
+ )
77
+ # Words too common to make two records related.
78
+ STOP_WORDS = frozenset(
79
+ {
80
+ "the",
81
+ "and",
82
+ "for",
83
+ "with",
84
+ "that",
85
+ "this",
86
+ "from",
87
+ "are",
88
+ "was",
89
+ "not",
90
+ "all",
91
+ "use",
92
+ "when",
93
+ "into",
94
+ "has",
95
+ "have",
96
+ "its",
97
+ "our",
98
+ "will",
99
+ "can",
100
+ "must",
101
+ }
102
+ )
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class Item:
107
+ """One question with its records; `key` says it was already shown."""
108
+
109
+ key: tuple[str, ...]
110
+ text: str
111
+
112
+
113
+ class Cleaner:
114
+ """The cleanup run, kept in the server process."""
115
+
116
+ def __init__(self, session: Session) -> None:
117
+ self.session = session
118
+ self.run: set[str] | None = None
119
+ self.shown: set[tuple[str, ...]] = set()
120
+ self.pass_number = 1
121
+ self.portion = 0
122
+ self.item_number = 0
123
+ # Items of each pass, for the report at the end; passes found empty since
124
+ # the last portion, for its first line.
125
+ self.found: dict[int, int] = {}
126
+ self.empty: list[int] = []
127
+
128
+ def clean(self) -> str:
129
+ if self.run is not None:
130
+ return self._next()
131
+ records, _ = self.session.records()
132
+ lifecycle = Lifecycle(records, date.today().isoformat())
133
+ self.run = {record["id"] for record in _active(lifecycle, None)}
134
+ self.shown = set()
135
+ self.pass_number = 1
136
+ self.portion = 0
137
+ self.item_number = 0
138
+ self.found = {number: 0 for number in TITLES}
139
+ self.empty = []
140
+ text = self._next()
141
+ # Nothing shown: every pass is empty, the answer is the end.
142
+ if not self.shown:
143
+ return text
144
+ return f"{FIRST}\n{text}"
145
+
146
+ def _next(self) -> str:
147
+ """The next portion; records no longer active are left out of it."""
148
+ records, _ = self.session.records()
149
+ lifecycle = Lifecycle(records, date.today().isoformat())
150
+ active = _active(lifecycle, self.run)
151
+ while self.pass_number <= len(TITLES):
152
+ items = [
153
+ item
154
+ for item in _items(self.session, self.pass_number, lifecycle, active)
155
+ if item.key not in self.shown
156
+ ]
157
+ if items:
158
+ return self._portion(items)
159
+ if self.portion == 0:
160
+ self.empty.append(self.pass_number)
161
+ self.pass_number += 1
162
+ self.portion = 0
163
+ self.item_number = 0
164
+ self.run = None
165
+ passes = [
166
+ f"pass {number} ({title}) {self.found[number]}"
167
+ for number, title in TITLES.items()
168
+ ]
169
+ return END.format(passes="; ".join(passes)) + "\n"
170
+
171
+ def _portion(self, items: list[Item]) -> str:
172
+ portions = _packed(items)
173
+ self.portion += 1
174
+ total = self.portion + len(portions) - 1
175
+ lines = []
176
+ if self.empty:
177
+ empty = ", ".join(f"{number} ({TITLES[number]})" for number in self.empty)
178
+ lines.append(f"Nothing found in passes {empty}.")
179
+ self.empty = []
180
+ lines.append(
181
+ f"Pass {self.pass_number} of {len(TITLES)}, portion {self.portion} of "
182
+ f"{total}: {TITLES[self.pass_number]}."
183
+ )
184
+ for item in portions[0]:
185
+ self.shown.add(item.key)
186
+ self.item_number += 1
187
+ self.found[self.pass_number] += 1
188
+ lines.append(f"Item {self.item_number}. {item.text}")
189
+ lines += [ANSWERS[self.pass_number], NEXT]
190
+ return "\n".join(lines) + "\n"
191
+
192
+
193
+ def _active(lifecycle: Lifecycle, run: set[str] | None) -> list[Record]:
194
+ """Active records; of the run only, once it has started."""
195
+ active = []
196
+ for record in lifecycle.records:
197
+ if lifecycle.states[record["id"]] not in ("active", "closed"):
198
+ continue
199
+ if run is not None and record["id"] not in run:
200
+ continue
201
+ active.append(record)
202
+ return active
203
+
204
+
205
+ def _items(
206
+ session: Session, pass_number: int, lifecycle: Lifecycle, active: list[Record]
207
+ ) -> list[Item]:
208
+ if pass_number == 1:
209
+ return _doubtful(session, active, lifecycle)
210
+ current = [record for record in active if record["id"] in lifecycle.in_effect]
211
+ if pass_number == 2:
212
+ return _groups(current)
213
+ return _questions(lifecycle.closed, current)
214
+
215
+
216
+ def _doubtful(
217
+ session: Session, active: list[Record], lifecycle: Lifecycle
218
+ ) -> list[Item]:
219
+ """Pass 1: a record and its mechanical reasons to doubt it."""
220
+ today = date.today().isoformat()
221
+ root = session.project.root
222
+ history = _has_commits(root)
223
+ items = []
224
+ for record in active:
225
+ reasons = []
226
+ if edited(record):
227
+ reasons.append(EDITED)
228
+ marks = record.get("marks") or {}
229
+ checked = max(record["created_at"], marks.get("checked", ""))
230
+ for path in record["scopes"]:
231
+ if path == PROJECT or is_pattern(path):
232
+ continue
233
+ if not session.file(path).exists():
234
+ reasons.append(f"Its scope path {path} no longer exists.")
235
+ continue
236
+ # A record about one file is about its code: a change may undo it.
237
+ if path.endswith("/") or not history:
238
+ continue
239
+ commits = _commits_after(root, path, checked)
240
+ if commits:
241
+ reasons.append(
242
+ f"{path} changed in Git after the record was saved or last "
243
+ f"confirmed on {checked[:10]} (commits: {commits})."
244
+ )
245
+ until = record.get("effective_until")
246
+ if until and until < today:
247
+ reasons.append(f"It was in effect until {until}.")
248
+ for identity in related_changes(record, lifecycle):
249
+ reasons.append(
250
+ f"Related record {identity} changed or needs review. "
251
+ "Check whether that affects this record."
252
+ )
253
+ if reasons:
254
+ reason = " ".join(reasons)
255
+ text = f"{record_line(record, [])} Reason: {reason} Is it still correct?"
256
+ items.append(Item((record["id"], "reason"), text))
257
+ return items
258
+
259
+
260
+ def _has_commits(root: Path) -> bool:
261
+ """A repository without commits has no history to compare with."""
262
+ done = subprocess.run(
263
+ ["git", "-C", str(root), "rev-parse", "--verify", "-q", "HEAD"],
264
+ capture_output=True,
265
+ )
266
+ return done.returncode == 0
267
+
268
+
269
+ def _commits_after(root: Path, path: str, checked: str) -> int:
270
+ """Commits that changed a file a day or more after a record was saved or
271
+ confirmed: the first day's commits are the work the record was saved with."""
272
+ moment = datetime.strptime(checked, "%Y-%m-%dT%H:%M:%SZ") + GRACE
273
+ since = moment.strftime("%Y-%m-%dT%H:%M:%SZ")
274
+ # --since alone stops at the first commit dated earlier; a filter does not.
275
+ done = subprocess.run(
276
+ ["git", "-C", str(root), "log", f"--since-as-filter={since}", "--format=%H"]
277
+ + ["--", path],
278
+ capture_output=True,
279
+ text=True,
280
+ check=True,
281
+ )
282
+ return len(done.stdout.split())
283
+
284
+
285
+ def _groups(records: list[Record]) -> list[Item]:
286
+ """Pass 2: every active record of one scope and heading, an item per scope,
287
+ with the pairs worded alike. A single record is an item too, for several
288
+ requirements; a scope whose records were already shown together is not."""
289
+ groups: dict[tuple[str, str], list[Record]] = {}
290
+ for record in records:
291
+ for heading, kinds in HEADINGS:
292
+ if record["kind"] not in kinds:
293
+ continue
294
+ for scope in record["scopes"]:
295
+ groups.setdefault((scope, heading), []).append(record)
296
+ items = []
297
+ shown: set[tuple[str, frozenset[str]]] = set()
298
+ for (scope, heading), members in groups.items():
299
+ same = (heading, frozenset(record["id"] for record in members))
300
+ if same in shown:
301
+ continue
302
+ shown.add(same)
303
+ lines = [f"Scope {shown_scope(scope)}, all {heading}:"]
304
+ lines += [record_line(record, []) for record in members]
305
+ for a, b in combinations(members, 2):
306
+ if _alike(a, b):
307
+ lines.append(f"Worded alike: [{a['id']}] and [{b['id']}].")
308
+ items.append(Item((scope, heading), "\n".join(lines)))
309
+ return items
310
+
311
+
312
+ def _alike(a: Record, b: Record) -> bool:
313
+ """Most of their significant words are the same."""
314
+ a_words = _words(a)
315
+ b_words = _words(b)
316
+ if not a_words or not b_words:
317
+ return False
318
+ shared = len(a_words & b_words) / len(a_words | b_words)
319
+ return shared >= SIMILAR
320
+
321
+
322
+ def _questions(closed: set[str], records: list[Record]) -> list[Item]:
323
+ """Pass 3: an open question and the records of its scope that share
324
+ significant words with it; a question is never an answer, and a question
325
+ without candidates is not an item."""
326
+ items = []
327
+ for question in records:
328
+ if question["kind"] != "question" or question["id"] in closed:
329
+ continue
330
+ words = _words(question)
331
+ candidates = []
332
+ for record in records:
333
+ if record["kind"] == "question":
334
+ continue
335
+ if not set(record["scopes"]) & set(question["scopes"]):
336
+ continue
337
+ if not _words(record) & words:
338
+ continue
339
+ candidates.append(record_line(record, []))
340
+ if not candidates:
341
+ continue
342
+ text = (
343
+ f"{record_line(question, [])} Candidates: {'; '.join(candidates)} "
344
+ "Does one of these answer it?"
345
+ )
346
+ items.append(Item((question["id"],), text))
347
+ return items
348
+
349
+
350
+ def _words(record: Record) -> set[str]:
351
+ """Words of 3+ letters or digits, without the common ones."""
352
+ text = f"{record['title']} {record['statement']}".lower()
353
+ words = set(re.findall(r"[^\W_]{3,}", text))
354
+ return words - STOP_WORDS
355
+
356
+
357
+ def _packed(items: list[Item]) -> list[list[Item]]:
358
+ """Items in portions of up to PORTION characters; an item is never split, a
359
+ larger one is a portion of its own."""
360
+ portions: list[list[Item]] = [[]]
361
+ size = 0
362
+ for item in items:
363
+ if portions[-1] and size + len(item.text) > PORTION:
364
+ portions.append([])
365
+ size = 0
366
+ portions[-1].append(item)
367
+ size += len(item.text)
368
+ return portions