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,251 @@
1
+ """A server session: the project, its records and the read-only commands."""
2
+
3
+ from collections.abc import Callable, Iterator
4
+ from contextlib import contextmanager
5
+ from dataclasses import dataclass, replace
6
+ from datetime import date
7
+ from pathlib import Path, PurePosixPath, PureWindowsPath
8
+
9
+ from filelock import FileLock
10
+
11
+ from ..delivery import Context, path_context, record_marks, start_context
12
+ from ..knowledge import Lifecycle, broken_links
13
+ from ..model.form import KINDS, STATES, Record
14
+ from ..model.json import at_pointer
15
+ from ..presentation import errors_text, form_text, record_text, search_text
16
+ from ..storage import Project, open_project, read_language, read_records
17
+ from ..storage.files import RecoveryError, recover_records
18
+ from ..storage.project import Checkout
19
+
20
+
21
+ class CommandError(Exception):
22
+ """The agent's input is wrong; the text says what to fix."""
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Window:
27
+ """A short form header and complete details shown with its question.
28
+ `field` names a free-text input; no options means a text-only form."""
29
+
30
+ text: str
31
+ options: tuple[str, ...]
32
+ question: str
33
+ details: str = ""
34
+ field: str | None = None
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Answer:
39
+ """An MCP form reply; protocol rejection never grants write permission."""
40
+
41
+ option: str
42
+ text: str = ""
43
+ checkout: Checkout | None = None
44
+
45
+
46
+ # Shows a window and returns the answer; None when no window can be shown.
47
+ Ask = Callable[[Window], Answer | None]
48
+
49
+
50
+ class Session:
51
+ """One per server process: the project of the folder it started in."""
52
+
53
+ def __init__(self, start: Path, home: Path, client: str | None, ask: Ask) -> None:
54
+ self.project: Project = open_project(start, home)
55
+ self.lock = FileLock(self.project.lock_file)
56
+ self.client = client
57
+ self._ask = ask
58
+
59
+ def ask(self, window: Window) -> Answer:
60
+ """Require a valid direct client answer before any mutation."""
61
+ checkout = self.project.checkout()
62
+ answer = self._ask(window)
63
+ if answer is None:
64
+ reason = "the MCP client cannot show confirmation forms"
65
+ elif answer.option == "decline":
66
+ reason = (
67
+ "the MCP client declined the request; it may not have shown a window"
68
+ )
69
+ elif answer.option == "close":
70
+ reason = "the MCP client cancelled the confirmation request"
71
+ elif answer.option == "invalid":
72
+ reason = f"invalid confirmation response: {answer.text}"
73
+ elif answer.option not in (window.options or ("other",)):
74
+ reason = f"unexpected confirmation choice {answer.option!r}"
75
+ else:
76
+ return replace(answer, checkout=checkout)
77
+ raise CommandError(
78
+ f"Not applied: {window.text.splitlines()[0].rstrip('.')}. {reason}. "
79
+ "Direct user confirmation is required. Enable MCP elicitation in your "
80
+ "client; Codex must allow mcp_elicitations rather than use "
81
+ "approval_policy=never. "
82
+ "Do not retry unless the user asks.\n"
83
+ )
84
+
85
+ def file(self, path: str) -> Path:
86
+ return self.project.root / path
87
+
88
+ @contextmanager
89
+ def storage(self) -> Iterator[None]:
90
+ """Hold one process lock and finish any interrupted approved record write."""
91
+ with self.lock:
92
+ try:
93
+ recover_records(self.project)
94
+ except RecoveryError as error:
95
+ raise CommandError(str(error)) from error
96
+ yield
97
+
98
+ @contextmanager
99
+ def writing(self, answer: Answer) -> Iterator[None]:
100
+ """Serialize validation and writes after approval, never the user dialog."""
101
+ with self.storage():
102
+ if answer.checkout != self.project.checkout():
103
+ raise CommandError(
104
+ "Not applied: the Git branch or commit changed while awaiting "
105
+ "confirmation. Read the current context and propose again.\n"
106
+ )
107
+ yield
108
+
109
+ def records(self) -> tuple[list[Record], list[str]]:
110
+ """The project's records, and lines about damaged files and broken
111
+ links."""
112
+ with self.storage():
113
+ records, problems = read_records(self.project, self.project.records)
114
+ return records, problems + broken_links(records, records)
115
+
116
+ def context(self) -> Context:
117
+ records, problems = self.records()
118
+ _, damaged = read_language(self.project)
119
+ return Context(
120
+ records=records,
121
+ today=date.today().isoformat(),
122
+ problems=problems + damaged,
123
+ set_up=self.project.set_up,
124
+ )
125
+
126
+ def project_context(self, paths: list[str]) -> str:
127
+ errors = []
128
+ if len(paths) > 10:
129
+ errors.append(
130
+ f"paths: {len(paths)} items, limit 10. Fix: keep 10 or fewer."
131
+ )
132
+ normal = []
133
+ for number, path in enumerate(paths, start=1):
134
+ folder_or_file = self.normal_path(path)
135
+ if folder_or_file is None:
136
+ errors.append(
137
+ f'paths[{number}]: path "{path}" is outside the project. '
138
+ "Fix: use a path from the project root."
139
+ )
140
+ continue
141
+ # The project root is the start context.
142
+ if folder_or_file:
143
+ normal.append(folder_or_file)
144
+ if errors:
145
+ raise CommandError(errors_text(errors))
146
+ if not normal:
147
+ return start_context(self.context())
148
+ return path_context(self.context(), normal)
149
+
150
+ def normal_path(self, path: str) -> str | None:
151
+ """A path from the project root, a folder ending with "/", "" for the root;
152
+ None when it is outside the project."""
153
+ if PurePosixPath(path).is_absolute() or PureWindowsPath(path).is_absolute():
154
+ absolute = Path(path)
155
+ if not absolute.is_relative_to(self.project.root):
156
+ return None
157
+ path = absolute.relative_to(self.project.root).as_posix()
158
+ parts = PurePosixPath(path).parts
159
+ if ".." in parts:
160
+ return None
161
+ if not parts:
162
+ return ""
163
+ normal = "/".join(parts)
164
+ if (self.project.root / normal).is_dir() or path.endswith("/"):
165
+ normal += "/"
166
+ return normal
167
+
168
+ def record(
169
+ self, ids: list[str], details: bool, history: bool, fields: object = None
170
+ ) -> str | dict[str, object]:
171
+ records, problems = self.records()
172
+ by_id = {record["id"]: record for record in records}
173
+ errors = []
174
+ for number, record_id in enumerate(ids, start=1):
175
+ if record_id not in by_id:
176
+ errors.append(
177
+ f'ids[{number}]: record "{record_id}" does not exist. Fix: use '
178
+ "an id from get_project_context or search_records."
179
+ )
180
+ if not ids:
181
+ errors.append("ids: at least 1 needed. Fix: add ids.")
182
+ if len(ids) > 20:
183
+ errors.append(f"ids: {len(ids)} items, limit 20. Fix: keep 20 or fewer.")
184
+ if fields is not None and (
185
+ not isinstance(fields, list)
186
+ or not fields
187
+ or not all(isinstance(pointer, str) for pointer in fields)
188
+ ):
189
+ errors.append("fields: expected a non-empty list of JSON Pointer strings.")
190
+ if fields is not None and (details or history):
191
+ errors.append("fields: select fields or request details/history, not both.")
192
+ if errors:
193
+ raise CommandError(errors_text(errors))
194
+ lifecycle = Lifecycle(records, date.today().isoformat())
195
+ if isinstance(fields, list):
196
+ selected = []
197
+ for record_id in ids:
198
+ values = {}
199
+ for pointer in fields:
200
+ try:
201
+ values[pointer] = at_pointer(by_id[record_id], pointer)
202
+ except ValueError as error:
203
+ errors.append(f"{record_id}: {error}")
204
+ selected.append(
205
+ {
206
+ "id": record_id,
207
+ "fields": values,
208
+ "warnings": record_marks(by_id[record_id], lifecycle),
209
+ }
210
+ )
211
+ if errors:
212
+ raise CommandError(errors_text(errors))
213
+ return {"records": selected, "problems": problems}
214
+ texts = []
215
+ for record_id in ids:
216
+ record = by_id[record_id]
217
+ texts.append(record_text(record, lifecycle, details, history))
218
+ return "\n".join(texts) + _told(problems)
219
+
220
+ def search(self, query: str, kinds: list[str], states: list[str]) -> str:
221
+ errors = _unknown("kinds", kinds, KINDS) + _unknown("states", states, STATES)
222
+ if errors:
223
+ raise CommandError(errors_text(errors))
224
+ records, problems = self.records()
225
+ lifecycle = Lifecycle(records, date.today().isoformat())
226
+ found = search_text(lifecycle, query, kinds, states)
227
+ return found + _told(problems)
228
+
229
+ def form(self, kinds: list[str]) -> str:
230
+ errors = _unknown("kinds", kinds, KINDS)
231
+ if not kinds:
232
+ errors.append("kinds: at least 1 needed. Fix: add kinds.")
233
+ if errors:
234
+ raise CommandError(errors_text(errors))
235
+ return form_text(kinds, read_language(self.project)[0])
236
+
237
+
238
+ def _told(problems: list[str]) -> str:
239
+ """Problems in the data, in the answer where they were met."""
240
+ return "".join(f"Tell the user: {problem}\n" for problem in problems)
241
+
242
+
243
+ def _unknown(name: str, values: list[str], allowed: tuple[str, ...]) -> list[str]:
244
+ errors = []
245
+ for number, value in enumerate(values, start=1):
246
+ if value not in allowed:
247
+ errors.append(
248
+ f'{name}[{number}]: "{value}" is not allowed. '
249
+ f"Fix: use {', '.join(allowed)}."
250
+ )
251
+ return errors
@@ -0,0 +1,100 @@
1
+ """Writing records: a new record and a new version of one (shared by save and edit)."""
2
+
3
+ import subprocess
4
+ from datetime import UTC, date, datetime
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from ..knowledge import Lifecycle, knowledge_hash
9
+ from ..knowledge.related import related_snapshot
10
+ from ..model import new_id, normalized
11
+ from ..model.form import Record
12
+ from ..storage import Project, read_records, write_record
13
+ from ..storage.files import write_records
14
+
15
+
16
+ def now() -> str:
17
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
18
+
19
+
20
+ def author(root: Path) -> dict[str, str]:
21
+ """The author from the user's Git settings."""
22
+ return {"name": _config(root, "user.name"), "email": _config(root, "user.email")}
23
+
24
+
25
+ def create(
26
+ project: Project,
27
+ record: Record,
28
+ producer: str | None,
29
+ confirmation: str,
30
+ replaces: list[Record] | None = None,
31
+ ) -> dict[str, Any]:
32
+ """Store a new record: id, author, time and the fingerprint of the knowledge
33
+ are set here."""
34
+ records, _ = read_records(project, project.records)
35
+ taken = {saved["id"] for saved in records}
36
+ saved: dict[str, Any] = normalized(record)
37
+ saved["id"] = new_id(saved["kind"], saved["title"], taken)
38
+ saved["author"] = author(project.root)
39
+ saved["producer"] = producer
40
+ saved["confirmation"] = confirmation
41
+ saved["created_at"] = now()
42
+ saved["state"] = "active"
43
+ saved["replaces"] = [previous["id"] for previous in replaces] if replaces else None
44
+ saved["knowledge_hash"] = knowledge_hash(saved)
45
+ saved["marks"] = {
46
+ "related_review": related_snapshot(
47
+ saved, Lifecycle([*records, saved], date.today().isoformat())
48
+ )
49
+ }
50
+ if replaces:
51
+ retired = [
52
+ {
53
+ **previous,
54
+ "state": "replaced",
55
+ "replaced_by": saved["id"],
56
+ "answered_by": None,
57
+ "state_changed": {
58
+ "by": saved["author"],
59
+ "at": saved["created_at"],
60
+ "confirmation": confirmation,
61
+ },
62
+ }
63
+ for previous in replaces
64
+ ]
65
+ write_records(project, [saved, *retired])
66
+ else:
67
+ write_record(project.records, saved)
68
+ return saved
69
+
70
+
71
+ def retire(
72
+ project: Project,
73
+ old: Record,
74
+ state: str,
75
+ confirmation: str,
76
+ replaced_by: str | None = None,
77
+ answered_by: str | None = None,
78
+ ) -> None:
79
+ """Change the state of a record, with who, when and how."""
80
+ changed = {
81
+ **old,
82
+ "state": state,
83
+ "replaced_by": replaced_by,
84
+ "answered_by": answered_by,
85
+ "state_changed": {
86
+ "by": author(project.root),
87
+ "at": now(),
88
+ "confirmation": confirmation,
89
+ },
90
+ }
91
+ write_record(project.records, changed)
92
+
93
+
94
+ def _config(root: Path, key: str) -> str:
95
+ done = subprocess.run(
96
+ ["git", "-C", str(root), "config", "--get", key],
97
+ capture_output=True,
98
+ text=True,
99
+ )
100
+ return done.stdout.strip()
@@ -0,0 +1,27 @@
1
+ """What the agent gets: the start context and the answer by paths."""
2
+
3
+ from .context import (
4
+ EDITED,
5
+ HEADINGS,
6
+ Context,
7
+ folder_records,
8
+ open_question_marks,
9
+ path_context,
10
+ record_line,
11
+ record_marks,
12
+ scoped_line,
13
+ start_context,
14
+ )
15
+
16
+ __all__ = [
17
+ "EDITED",
18
+ "HEADINGS",
19
+ "Context",
20
+ "folder_records",
21
+ "open_question_marks",
22
+ "path_context",
23
+ "record_line",
24
+ "record_marks",
25
+ "scoped_line",
26
+ "start_context",
27
+ ]