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,370 @@
1
+ """edit_record: plan one change, confirm its contents, then persist it."""
2
+
3
+ import json
4
+ from dataclasses import dataclass, field
5
+ from datetime import date
6
+
7
+ from ..knowledge import Lifecycle, knowledge_hash
8
+ from ..knowledge.related import related_snapshot
9
+ from ..model import FORM, form_errors, normalized
10
+ from ..model.form import MAX_RELATED, Record
11
+ from ..model.profile import profile_properties
12
+ from ..model.scope import PATH_FIELDS, shown_scope, with_stored_paths
13
+ from ..presentation import errors_text
14
+ from ..presentation.window import card, field_label, value_text
15
+ from ..storage import write_record
16
+ from .checks import author_problems, record_problems
17
+ from .session import CommandError, Session, Window
18
+ from .versions import author, create, now, retire
19
+
20
+ ACTIONS = (
21
+ "replace",
22
+ "delete",
23
+ "restore",
24
+ "confirm",
25
+ "close",
26
+ "not_conflict",
27
+ "link",
28
+ "rename_area",
29
+ )
30
+
31
+
32
+ @dataclass
33
+ class Change:
34
+ """The exact source records and proposed contents covered by one confirmation."""
35
+
36
+ action: str
37
+ targets: list[Record]
38
+ fields: dict[str, str] = field(default_factory=dict)
39
+ replacement: dict[str, object] | None = None
40
+ related_review: dict[str, str] | None = None
41
+
42
+ @property
43
+ def unchanged(self) -> bool:
44
+ return (
45
+ self.action == "replace"
46
+ and len(self.targets) == 1
47
+ and self.replacement is not None
48
+ and normalized(self.replacement) == normalized(self.targets[0])
49
+ )
50
+
51
+
52
+ class Editor:
53
+ """One direct confirmation per edit, with no agent-supplied approval."""
54
+
55
+ def __init__(self, session: Session) -> None:
56
+ self.session = session
57
+
58
+ def edit(self, proposal: object) -> str:
59
+ errors = author_problems(self.session)
60
+ if errors:
61
+ raise CommandError(errors_text(errors))
62
+ records, _ = self.session.records()
63
+ change = _plan(
64
+ self.session, proposal, {record["id"]: record for record in records}
65
+ )
66
+ if change.unchanged:
67
+ return (
68
+ f"Unchanged: {change.targets[0]['id']}; "
69
+ "supplied fields already match.\n"
70
+ )
71
+ answer = self.session.ask(_window(change))
72
+ if answer.option == "cancel":
73
+ return f"Not changed: Skip selected for {change.action}.\n"
74
+ if answer.option != "approve":
75
+ raise CommandError(f"Edit {change.action}: no approval received.\n")
76
+ with self.session.writing(answer):
77
+ records, _ = self.session.records()
78
+ current = {record["id"]: record for record in records}
79
+ for target in change.targets:
80
+ if current.get(target["id"]) != target:
81
+ raise CommandError(
82
+ f"Not changed: {target['id']} changed "
83
+ "after confirmation began. "
84
+ "Read it again and propose a new edit.\n"
85
+ )
86
+ if change.related_review is not None:
87
+ snapshot = related_snapshot(
88
+ change.targets[0], Lifecycle(records, date.today().isoformat())
89
+ )
90
+ if snapshot != change.related_review:
91
+ raise CommandError(
92
+ "Not confirmed: related knowledge for "
93
+ f"{change.targets[0]['id']} "
94
+ "changed during confirmation. Review it and confirm again.\n"
95
+ )
96
+ return self._apply(change) + "\n"
97
+
98
+ def _apply(self, change: Change) -> str:
99
+ project = self.session.project
100
+ fields = change.fields
101
+ if change.action == "replace":
102
+ assert change.replacement is not None
103
+ ids = [record["id"] for record in change.targets]
104
+ new = create(
105
+ project,
106
+ change.replacement,
107
+ self.session.client,
108
+ "elicitation",
109
+ change.targets,
110
+ )
111
+ return f"Replaced: {', '.join(ids)} → {new['id']}."
112
+ if change.action == "rename_area":
113
+ for record in change.targets:
114
+ areas = [
115
+ fields["new_area"] if area == fields["area"] else area
116
+ for area in record["areas"]
117
+ ]
118
+ self._write(record, areas=list(dict.fromkeys(areas)))
119
+ return (
120
+ f"Renamed area {fields['area']!r} to {fields['new_area']!r} "
121
+ f"in {len(change.targets)} records."
122
+ )
123
+ target = change.targets[0]
124
+ if change.action == "delete":
125
+ retire(project, target, "outdated", "elicitation")
126
+ return f"Deleted: {target['id']} is outdated and no longer delivered."
127
+ if change.action == "restore":
128
+ retire(project, target, "active", "elicitation")
129
+ return f"Restored: {target['id']} is delivered again."
130
+ if change.action == "close":
131
+ self._write(target, answered_by=fields["answer_id"])
132
+ return f"Closed: {target['id']} is answered by {fields['answer_id']}."
133
+ if change.action == "not_conflict":
134
+ marks = dict(target.get("marks") or {})
135
+ marks["not_conflict"] = [*marks.get("not_conflict", []), fields["other_id"]]
136
+ self._write(target, marks=marks)
137
+ return f"Not conflicting: {target['id']} and {fields['other_id']}."
138
+ if change.action == "link":
139
+ linked = {
140
+ **target,
141
+ "related": [*(target.get("related") or []), fields["other_id"]],
142
+ }
143
+ records, _ = self.session.records()
144
+ snapshot = related_snapshot(
145
+ linked, Lifecycle(records, date.today().isoformat())
146
+ )
147
+ marks = dict(target.get("marks") or {})
148
+ marks["related_review"] = {
149
+ **(marks.get("related_review") or {}),
150
+ fields["other_id"]: snapshot[fields["other_id"]],
151
+ }
152
+ self._write(target, related=linked["related"], marks=marks)
153
+ return f"Linked: {target['id']} → {fields['other_id']}."
154
+ assert change.related_review is not None
155
+ marks = {
156
+ **(target.get("marks") or {}),
157
+ "checked": now(),
158
+ "related_review": change.related_review,
159
+ }
160
+ self._write(target, knowledge_hash=knowledge_hash(target), marks=marks)
161
+ return f"Confirmed: {target['id']} is correct as it is."
162
+
163
+ def _write(self, record: Record, **changes: object) -> None:
164
+ """Audit service-field changes while preserving the record's knowledge."""
165
+ write_record(
166
+ self.session.project.records,
167
+ {
168
+ **record,
169
+ **changes,
170
+ "state_changed": {
171
+ "by": author(self.session.project.root),
172
+ "at": now(),
173
+ "confirmation": "elicitation",
174
+ },
175
+ },
176
+ )
177
+
178
+
179
+ def _plan(session: Session, proposal: object, every: dict[str, Record]) -> Change:
180
+ if not isinstance(proposal, dict):
181
+ raise CommandError("edit: expected one edit object.\n")
182
+ action = proposal.get("action")
183
+ if not isinstance(action, str) or action not in ACTIONS:
184
+ raise CommandError(f"edit.action: expected one of {', '.join(ACTIONS)}.\n")
185
+ if action == "rename_area":
186
+ if set(proposal) - {"action", "area", "new_area"}:
187
+ raise CommandError("rename_area: use only action, area and new_area.\n")
188
+ old, new = proposal.get("area"), proposal.get("new_area")
189
+ if not isinstance(old, str) or not old or not isinstance(new, str) or not new:
190
+ raise CommandError(
191
+ "rename_area: area and new_area must be non-empty strings.\n"
192
+ )
193
+ targets = [
194
+ record for record in every.values() if old in (record.get("areas") or [])
195
+ ]
196
+ if not targets:
197
+ raise CommandError(f"rename_area: no record has area {old!r}.\n")
198
+ return Change(action, targets, {"area": old, "new_area": new})
199
+ if "ids" in proposal:
200
+ ids = proposal["ids"]
201
+ if action != "replace" or "id" in proposal:
202
+ raise CommandError(
203
+ "edit.ids: only replace can merge records; supply ids or id.\n"
204
+ )
205
+ if (
206
+ not isinstance(ids, list)
207
+ or len(ids) < 2
208
+ or not all(isinstance(key, str) for key in ids)
209
+ ):
210
+ raise CommandError(
211
+ "replace.ids: expected at least two distinct record ids.\n"
212
+ )
213
+ if len(set(ids)) != len(ids):
214
+ raise CommandError("replace.ids: record ids must be distinct.\n")
215
+ else:
216
+ identity = proposal.get("id")
217
+ if not isinstance(identity, str):
218
+ raise CommandError("edit.id: expected a record id.\n")
219
+ ids = [identity]
220
+ missing = [key for key in ids if key not in every]
221
+ if missing:
222
+ raise CommandError(f"edit.id: records do not exist: {', '.join(missing)}.\n")
223
+ targets = [every[key] for key in ids]
224
+ for target in targets:
225
+ allowed = ("outdated", "replaced") if action == "restore" else ("active",)
226
+ state = target["state"]
227
+ if action not in ("restore", "replace"):
228
+ lifecycle = Lifecycle(every.values(), date.today().isoformat())
229
+ if lifecycle.states[target["id"]] == "active":
230
+ state = "active"
231
+ if state not in allowed:
232
+ raise CommandError(
233
+ f"{action}: {target['id']} is {target['state']}; "
234
+ f"expected {', '.join(allowed)}.\n"
235
+ )
236
+ if action == "replace":
237
+ return _replacement(session, proposal, targets, every)
238
+ allowed_fields = {"id", "action"}
239
+ if action == "close":
240
+ allowed_fields.add("answer_id")
241
+ if action in ("link", "not_conflict"):
242
+ allowed_fields.add("other_id")
243
+ unknown = set(proposal) - allowed_fields
244
+ if unknown:
245
+ raise CommandError(f"{action}: unknown fields: {', '.join(sorted(unknown))}.\n")
246
+ target = targets[0]
247
+ fields: dict[str, str] = {}
248
+ if action == "close":
249
+ answer = proposal.get("answer_id")
250
+ if target["kind"] != "question":
251
+ raise CommandError(f"close: {target['id']} is not a question.\n")
252
+ if not isinstance(answer, str) or answer not in every:
253
+ raise CommandError(
254
+ f"close.answer_id: {answer!r} is not an existing record.\n"
255
+ )
256
+ fields["answer_id"] = answer
257
+ if action in ("link", "not_conflict"):
258
+ other = proposal.get("other_id")
259
+ if not isinstance(other, str) or other not in every or other == target["id"]:
260
+ raise CommandError(
261
+ f"{action}.other_id: expected another existing record.\n"
262
+ )
263
+ if action == "link":
264
+ links = target.get("related") or []
265
+ if other in links or len(links) >= MAX_RELATED:
266
+ raise CommandError(
267
+ f"link: {target['id']} already links to {other} "
268
+ f"or has {MAX_RELATED} links.\n"
269
+ )
270
+ fields["other_id"] = other
271
+ review = None
272
+ if action == "confirm":
273
+ review = related_snapshot(
274
+ target, Lifecycle(every.values(), date.today().isoformat())
275
+ )
276
+ return Change(action, targets, fields, related_review=review)
277
+
278
+
279
+ def _replacement(
280
+ session: Session,
281
+ proposal: dict[str, object],
282
+ targets: list[Record],
283
+ every: dict[str, Record],
284
+ ) -> Change:
285
+ base = targets[0]
286
+ updates = with_stored_paths(
287
+ {
288
+ name: value
289
+ for name, value in proposal.items()
290
+ if name not in {"id", "ids", "action", "clear"}
291
+ }
292
+ )
293
+ clear = proposal.get("clear", [])
294
+ if not isinstance(clear, list) or not all(isinstance(name, str) for name in clear):
295
+ raise CommandError("replace.clear: expected a list of field names.\n")
296
+ if not updates and not clear and len(targets) == 1:
297
+ raise CommandError("replace: no changed fields supplied.\n")
298
+ kind = updates.get("kind", base["kind"])
299
+ if not isinstance(kind, str) or kind not in FORM:
300
+ raise CommandError(f"replace.kind: unknown kind {kind!r}.\n")
301
+ names = {"kind", *(field.name for field in FORM[kind])}
302
+ unknown = set(clear) - (names - {"kind"})
303
+ if unknown:
304
+ raise CommandError(
305
+ f"replace.clear: unknown fields: {', '.join(sorted(unknown))}.\n"
306
+ )
307
+ replacement = {name: value for name, value in base.items() if name in names}
308
+ if kind == "profile" and base["kind"] == "profile":
309
+ replacement["properties"] = profile_properties(base["properties"])
310
+ replacement.update(updates)
311
+ for name in clear:
312
+ replacement.pop(name, None)
313
+ errors = form_errors(replacement)
314
+ if not errors:
315
+ errors = record_problems(session, replacement, every)
316
+ if errors:
317
+ raise CommandError(errors_text(errors))
318
+ return Change("replace", targets, replacement=replacement)
319
+
320
+
321
+ def _window(change: Change) -> Window:
322
+ identities = ", ".join(record["id"] for record in change.targets)
323
+ if change.replacement is not None:
324
+ before = change.targets[0]
325
+ differences = []
326
+ fields = dict.fromkeys(
327
+ [
328
+ "kind",
329
+ *(field.name for field in FORM[before["kind"]]),
330
+ *(field.name for field in FORM[str(change.replacement["kind"])]),
331
+ ]
332
+ )
333
+ for name in fields:
334
+ old, new = _shown(name, before), _shown(name, change.replacement)
335
+ if old != new:
336
+ differences.append(f"{field_label(name)}: {old} → {new}")
337
+ details = "\n".join(differences)
338
+ if len(change.targets) > 1:
339
+ details += "\nMerged record:\n" + card(change.replacement)
340
+ start = change.replacement.get("effective_from")
341
+ if isinstance(start, str) and start > date.today().isoformat():
342
+ details += (
343
+ f"\nThe previous version remains current until {start}, "
344
+ "unless its own validity ends earlier."
345
+ )
346
+ else:
347
+ details = "\n\n".join(card(record) for record in change.targets)
348
+ if change.fields:
349
+ details += "\n" + value_text(change.fields)
350
+ if change.action == "delete":
351
+ details += (
352
+ "\nIt will no longer be delivered to agents; history is retained."
353
+ )
354
+ return Window(
355
+ f"{change.action}: {identities}",
356
+ ("approve", "cancel"),
357
+ question="Apply this change?",
358
+ details=details,
359
+ )
360
+
361
+
362
+ def _shown(name: str, record: Record) -> str:
363
+ value = record.get(name)
364
+ if value is None or value == "" or value == []:
365
+ return "(none)"
366
+ if name in PATH_FIELDS:
367
+ return ", ".join(shown_scope(path) for path in value)
368
+ if name == "properties":
369
+ return json.dumps(value, ensure_ascii=False, indent=2)
370
+ return value_text(value)
@@ -0,0 +1,52 @@
1
+ """init_project: ask the user for storage and language before writing settings."""
2
+
3
+ from dataclasses import replace
4
+
5
+ from ..storage import set_mode, write_language
6
+ from .session import CommandError, Session, Window
7
+
8
+ MODES = ("local", "shared")
9
+ HEAD = "Set up RatifyPoint in this project."
10
+ MODE_QUESTION = "Where should RatifyPoint keep this project's knowledge?"
11
+ MODE_DETAILS = (
12
+ "Local: only on this computer. Nothing goes to Git or to colleagues.\n"
13
+ "Shared: in the repository. Records go to Git with your commits."
14
+ )
15
+ LANGUAGE_QUESTION = "In which language should this project's records be written?"
16
+ LANGUAGE_DETAILS = "English, or choose Other and enter the language."
17
+
18
+
19
+ class Initializer:
20
+ """Setup has no agent-supplied answers or pending state."""
21
+
22
+ def __init__(self, session: Session) -> None:
23
+ self.session = session
24
+
25
+ def init(self) -> str:
26
+ mode = self.session.ask(
27
+ Window(HEAD, MODES, question=MODE_QUESTION, details=MODE_DETAILS)
28
+ )
29
+ language = self.session.ask(
30
+ Window(
31
+ HEAD,
32
+ ("english", "other"),
33
+ question=LANGUAGE_QUESTION,
34
+ details=LANGUAGE_DETAILS,
35
+ field="Language",
36
+ )
37
+ )
38
+ chosen_language = "English" if language.option == "english" else language.text
39
+ if not chosen_language.strip():
40
+ raise CommandError(
41
+ "Set up RatifyPoint: no language supplied; nothing saved.\n"
42
+ )
43
+ with self.session.writing(language):
44
+ project = self.session.project
45
+ set_mode(project, mode.option)
46
+ self.session.project = replace(project, mode=mode.option)
47
+ write_language(self.session.project, chosen_language)
48
+ return (
49
+ f"RatifyPoint is set up here in {mode.option} mode. "
50
+ f"Write records in {chosen_language}. "
51
+ "Use save_record to propose knowledge; each record is confirmed directly.\n"
52
+ )
@@ -0,0 +1,98 @@
1
+ """save_record: validate one record, ask the user, then store it."""
2
+
3
+ from datetime import date
4
+
5
+ from ..knowledge import Duplicate, duplicate_of
6
+ from ..model import form_errors
7
+ from ..model.form import Record
8
+ from ..model.scope import scopes_text, with_stored_paths
9
+ from ..presentation import errors_text
10
+ from ..presentation.window import card, head_lines, noun
11
+ from .checks import author_problems, record_problems
12
+ from .session import CommandError, Session, Window
13
+ from .versions import create
14
+
15
+
16
+ class Saver:
17
+ """Save one proposal only after its MCP confirmation has been accepted."""
18
+
19
+ def __init__(self, session: Session) -> None:
20
+ self.session = session
21
+
22
+ def save(self, proposal: object) -> str:
23
+ if not isinstance(proposal, dict):
24
+ raise CommandError("record: expected one record object.\n")
25
+ record = with_stored_paths(proposal)
26
+ errors = form_errors(record)
27
+ if errors:
28
+ raise CommandError(errors_text(errors))
29
+ saved, _ = self.session.records()
30
+ errors = author_problems(self.session) + record_problems(
31
+ self.session, record, {stored["id"]: stored for stored in saved}
32
+ )
33
+ if errors:
34
+ raise CommandError(errors_text(errors))
35
+ duplicate = duplicate_of(record, saved, date.today().isoformat())
36
+ if duplicate is not None:
37
+ return _repeat(record, duplicate)
38
+ answer = self.session.ask(
39
+ Window(
40
+ "\n".join(head_lines(record)),
41
+ ("approve", "cancel", "change"),
42
+ question=f"Save this {noun(str(record['kind']))}?",
43
+ details=card(record),
44
+ )
45
+ )
46
+ if answer.option == "cancel":
47
+ return f"Not saved: Skip selected for {record['title']!r}.\n"
48
+ if answer.option == "change":
49
+ correction = self.session.ask(
50
+ Window(
51
+ f"Change {record['title']!r}",
52
+ (),
53
+ question="What to change?",
54
+ field="Requested changes",
55
+ )
56
+ )
57
+ return (
58
+ f"Not saved: requested changes: {correction.text!r}. "
59
+ "Revise the record and call save_record again for confirmation.\n"
60
+ )
61
+ if answer.option != "approve":
62
+ raise CommandError(f"Save {record['title']!r}: no approval received.\n")
63
+ with self.session.writing(answer):
64
+ saved, _ = self.session.records()
65
+ problems = record_problems(
66
+ self.session, record, {stored["id"]: stored for stored in saved}
67
+ )
68
+ if problems:
69
+ raise CommandError(errors_text(problems))
70
+ duplicate = duplicate_of(record, saved, date.today().isoformat())
71
+ if duplicate is not None:
72
+ return _repeat(record, duplicate)
73
+ stored = create(
74
+ self.session.project, record, self.session.client, "elicitation"
75
+ )
76
+ return f"Saved as {stored['id']}.\n{card(stored)}\n"
77
+
78
+
79
+ def _repeat(record: Record, duplicate: Duplicate) -> str:
80
+ saved = duplicate.record
81
+ if duplicate.kind == record["kind"] == saved["kind"] and not duplicate.news:
82
+ return (
83
+ f"Already recorded: {saved['id']} {saved['title']!r}, applies to "
84
+ f"{scopes_text(saved['scopes'], saved.get('exclusions'))}.\n"
85
+ )
86
+ if duplicate.kind == "profile":
87
+ return (
88
+ f"Same entity as {saved['id']}. "
89
+ f'Read it with get_record(ids=["{saved["id"]}"]) before '
90
+ "proposing edit_record with action replace. Send the complete "
91
+ "properties object, preserving unchanged properties.\n"
92
+ )
93
+ return (
94
+ f"Same knowledge and scope as {saved['id']}. "
95
+ f'Read it with get_record(ids=["{saved["id"]}"]) before '
96
+ "proposing edit_record with action replace and "
97
+ f"kind {duplicate.kind!r} to combine the confirmed details.\n"
98
+ )