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,238 @@
1
+ """The record form for the agent and the list of form errors."""
2
+
3
+ import json
4
+
5
+ from ..model.form import FORM, Field
6
+
7
+ # What each kind is for.
8
+ KIND_MEANINGS = {
9
+ "rule": "what is required or forbidden",
10
+ "recommendation": "what is advisable; deviating needs a reason",
11
+ "decision": "a decision that was made, not an architectural one (that is adr)",
12
+ "adr": "an architecture decision with its context, options and consequences",
13
+ "fact": "what is true about the project",
14
+ "risk": "what can go wrong and what to know in advance",
15
+ "procedure": "how to do something, step by step",
16
+ "question": "what is not known yet and what to do until it is answered",
17
+ "profile": "one identifiable project entity with its parameters, access method "
18
+ "and operating restrictions: a person, resource, server, environment, service, "
19
+ "site or database connection",
20
+ }
21
+
22
+ # What each top-level field means; nested fields are described with their parent.
23
+ MEANINGS = {
24
+ "title": "the knowledge itself in a few words, with its key value: indexes "
25
+ "show only the title",
26
+ "statement": "one requirement or one piece of knowledge, one paragraph, saying "
27
+ "only what the user stated or confirmed; several requirements are several "
28
+ "records; for an ADR the decision, for a question the question",
29
+ "scopes": '"./" for the whole project, a folder ending with "/", a file, '
30
+ 'or a .gitignore pattern such as "**/docs/"; no "!"; a folder applies to '
31
+ "everything inside it",
32
+ "exclusions": "paths or patterns where it does not apply",
33
+ "areas": "topic labels for search; they do not change where it applies",
34
+ "additions": "examples, explanations, code; shown only by get_record",
35
+ "effective_from": "applies from this date (for a fact: true from)",
36
+ "effective_until": "applies until this date (for a fact: true until)",
37
+ "question_id": "the id of the question this record answers; the question "
38
+ "becomes closed",
39
+ "related": "ids of closely related records",
40
+ "type": "required or forbidden; for forbidden the statement names the "
41
+ 'forbidden action, and the agent sees "Forbidden: <statement>"',
42
+ "when": "when it applies; without it, always within its scopes",
43
+ "why": "the reason; ask the user, do not invent it",
44
+ "how_to_verify": "how to check that it is followed",
45
+ "when_to_deviate": "when it is fine not to follow it",
46
+ "decided_by": "who decided, if not the author",
47
+ "context": "the context and the problem",
48
+ "decision_drivers": "what the choice depended on",
49
+ "options": "the options considered: [{name, pros: [...], cons: [...]}]",
50
+ "no_alternatives_because": "why there were no alternatives",
51
+ "chosen_option": "the option chosen",
52
+ "rationale": "why it was chosen",
53
+ "consequences": "{positive: [...], negative: [...]}",
54
+ "known_how": "how it is known: verified (read in a file or measured), "
55
+ "user-stated, agent-inferred or assumption",
56
+ "observed_at": "when it was checked or measured",
57
+ "key": "a key such as python.version; facts with one key and different values "
58
+ "are marked as conflicting",
59
+ "value": "the value for the key",
60
+ "likelihood": "how likely",
61
+ "impact": "how bad",
62
+ "mitigation": "how to reduce it",
63
+ "trigger": "when to run it",
64
+ "steps": "the steps, in order",
65
+ "expected_result": "what the result should be",
66
+ "preconditions": "what must hold before",
67
+ "abort_when": "when to stop",
68
+ "must_not": "what must not be done",
69
+ "rollback": "how to undo it",
70
+ "until_answered": "what to do until it is answered",
71
+ "resolution_criteria": "what counts as an answer",
72
+ "ask": "whom to ask",
73
+ "entity_type": "the kind of entity, lowercase",
74
+ "entity_name": "the name of the entity",
75
+ "properties": "a non-empty JSON object; choose keys and nested structure for the "
76
+ "entity. Keep numbers, booleans, nulls, arrays and objects as JSON values, not "
77
+ "encoded strings. Separate measurements from dates and caveats; never secrets",
78
+ }
79
+
80
+ KIND_RULES = {
81
+ "adr": "Set exactly one of options (2 or more, each with non-empty pros and "
82
+ "cons) and no_alternatives_because. consequences need at least one positive "
83
+ "and one negative.",
84
+ "fact": "observed_at is required when known_how is verified.",
85
+ "profile": "Search for the same entity before creating a profile. To extend "
86
+ "an existing entity, read its current record with get_record, then propose "
87
+ "edit_record. A supplied properties object replaces the whole object: preserve "
88
+ "unchanged properties. Include the entity name or alias in the title because "
89
+ "the start index shows titles only. Store access instructions, never passwords "
90
+ "or tokens.\n"
91
+ "Base entity types: person (role, responsibility, work contacts), "
92
+ "server (address, OS, access), environment (dev/stage/prod and specifics), "
93
+ "service (an OpenSearch cluster, a database, a queue: address, how to work "
94
+ "with it; for a database connection: engine, environment, database, address, "
95
+ "existing connection name, access method and restrictions), site (a dev site, "
96
+ "Swagger: address, how to log in). Another type is allowed.",
97
+ }
98
+
99
+ EXAMPLES: dict[str, dict[str, object]] = {
100
+ "rule": {
101
+ "kind": "rule",
102
+ "type": "required",
103
+ "title": "Run tests with make test",
104
+ "statement": "Run the tests with make test.",
105
+ "scopes": ["./"],
106
+ },
107
+ "recommendation": {
108
+ "kind": "recommendation",
109
+ "title": "Small pull requests",
110
+ "statement": "Keep pull requests under 400 changed lines.",
111
+ "when_to_deviate": "Generated code.",
112
+ "scopes": ["./"],
113
+ },
114
+ "decision": {
115
+ "kind": "decision",
116
+ "title": "Catalog cache TTL",
117
+ "statement": "The catalog cache keeps entries for 10 minutes.",
118
+ "scopes": ["services/catalog/"],
119
+ },
120
+ "adr": {
121
+ "kind": "adr",
122
+ "title": "Search on OpenSearch",
123
+ "statement": "Organization search runs on OpenSearch.",
124
+ "context": "Search over 40 million organizations.",
125
+ "decision_drivers": ["Reindex without downtime"],
126
+ "options": [
127
+ {"name": "Postgres", "pros": ["One store"], "cons": ["Reindex locks"]},
128
+ {"name": "OpenSearch", "pros": ["Scales"], "cons": ["Second store"]},
129
+ ],
130
+ "chosen_option": "OpenSearch",
131
+ "rationale": "Reindexes without downtime.",
132
+ "consequences": {"positive": ["No downtime"], "negative": ["Second store"]},
133
+ "scopes": ["app/search/"],
134
+ },
135
+ "fact": {
136
+ "kind": "fact",
137
+ "title": "Runs on Python 3.12",
138
+ "statement": "The project runs on Python 3.12.",
139
+ "known_how": "verified",
140
+ "observed_at": "2026-09-26",
141
+ "key": "python.version",
142
+ "value": "3.12",
143
+ "scopes": ["./"],
144
+ },
145
+ "risk": {
146
+ "kind": "risk",
147
+ "title": "Empty results after alias switch",
148
+ "statement": "Switching the alias before warm-up returns empty results.",
149
+ "likelihood": "medium",
150
+ "impact": "high",
151
+ "mitigation": "Warm up the new index first.",
152
+ "scopes": ["app/search/"],
153
+ },
154
+ "procedure": {
155
+ "kind": "procedure",
156
+ "title": "Reindex geonames",
157
+ "statement": "Build a new index and switch the alias.",
158
+ "trigger": "GeoNames needs an update.",
159
+ "steps": ["Build the new index.", "Warm it up.", "Switch the alias."],
160
+ "expected_result": "The alias points to the new index.",
161
+ "scopes": ["app/search/"],
162
+ },
163
+ "question": {
164
+ "kind": "question",
165
+ "title": "Replace the country by address?",
166
+ "statement": "May the pipeline replace an existing country by the address?",
167
+ "until_answered": "Keep the existing country.",
168
+ "scopes": ["app/geo/"],
169
+ },
170
+ "profile": {
171
+ "kind": "profile",
172
+ "title": "Development server dev-1",
173
+ "statement": "The development server.",
174
+ "entity_type": "server",
175
+ "entity_name": "dev-1",
176
+ "properties": {
177
+ "address": "dev-1.example.com",
178
+ "environment": "dev",
179
+ "access": {"method": "ssh", "alias": "dev-1"},
180
+ "cpu": {"cores": 48},
181
+ "memory": {"bytes": 134721630208},
182
+ "restrictions": ["Development workloads only."],
183
+ },
184
+ "scopes": ["./"],
185
+ },
186
+ }
187
+
188
+
189
+ def form_text(kinds: list[str], language: str | None) -> str:
190
+ """The fields of each kind, its rules and an example."""
191
+ blocks = []
192
+ for kind in kinds:
193
+ lines = [f"kind: {kind} — {KIND_MEANINGS[kind]}."]
194
+ lines += [_field_line(field) for field in FORM[kind]]
195
+ if kind in KIND_RULES:
196
+ lines.append(KIND_RULES[kind])
197
+ lines.append("Example: " + json.dumps(EXAMPLES[kind], ensure_ascii=False))
198
+ blocks.append("\n".join(lines))
199
+ blocks.append("effective_from must not be later than effective_until.")
200
+ if language:
201
+ blocks.append(f"Write records in {language}.")
202
+ return "\n\n".join(blocks) + "\n"
203
+
204
+
205
+ def errors_text(errors: list[str]) -> str:
206
+ """`N errors. Fix and call again.` and one line per error."""
207
+ count = f"{len(errors)} errors"
208
+ if len(errors) == 1:
209
+ count = "1 error"
210
+ return "\n".join([f"{count}. Fix and call again.", *errors]) + "\n"
211
+
212
+
213
+ def _field_line(field: Field) -> str:
214
+ line = f"- {field.name} ({_facts(field)}): {MEANINGS[field.name]}."
215
+ if field.fields:
216
+ nested = "; ".join(f"{inner.name} ({_facts(inner)})" for inner in field.fields)
217
+ line += f" Fields: {nested}."
218
+ return line
219
+
220
+
221
+ def _facts(field: Field) -> str:
222
+ """Required or not, allowed values and limits, from the model table."""
223
+ facts = ["required" if field.required else "optional"]
224
+ if field.values:
225
+ facts.append("one of: " + ", ".join(field.values))
226
+ if field.type in ("text", "line"):
227
+ facts.append(f"up to {field.limit} chars")
228
+ if field.type in ("texts", "paths"):
229
+ facts.append(f"up to {field.limit} chars each")
230
+ if field.type == "line":
231
+ facts.append("one line")
232
+ if field.type == "date":
233
+ facts.append("YYYY-MM-DD")
234
+ if field.max_items is not None:
235
+ facts.append(f"{field.min_items}–{field.max_items} items")
236
+ if field.max_items is None and field.min_items:
237
+ facts.append(f"at least {field.min_items}")
238
+ return ", ".join(facts)
@@ -0,0 +1,85 @@
1
+ """A whole record for get_record."""
2
+
3
+ import json
4
+
5
+ from ..delivery import record_marks
6
+ from ..knowledge import Lifecycle
7
+ from ..model.form import FORM, Record
8
+ from ..model.scope import PATH_FIELDS, shown_scope
9
+
10
+ DETAILS = (
11
+ "author",
12
+ "created_at",
13
+ "confirmation",
14
+ "producer",
15
+ "state",
16
+ "marks",
17
+ )
18
+
19
+
20
+ def record_text(
21
+ record: Record,
22
+ lifecycle: Lifecycle,
23
+ details: bool,
24
+ history: bool,
25
+ ) -> str:
26
+ """`field: value` lines: all the knowledge; `details` adds who, when and how;
27
+ `history` adds the versions. State is resolved at the lifecycle's date."""
28
+ by_id = lifecycle.by_id
29
+ lines = [f"[{record['id']}] {record['kind']}", *record_marks(record, lifecycle)]
30
+ for field in FORM[record["kind"]]:
31
+ value = record.get(field.name)
32
+ if not value:
33
+ continue
34
+ # A link to a missing record is not shown; a problem line says so.
35
+ if field.name == "question_id" and value not in by_id:
36
+ continue
37
+ if field.name == "related":
38
+ known = [other for other in value if other in by_id]
39
+ value = [f"{other} {by_id[other]['title']}" for other in known]
40
+ if field.name in PATH_FIELDS:
41
+ value = [shown_scope(path) for path in value]
42
+ lines.append(f"{field.name}: {_value(value)}")
43
+ if details:
44
+ for name in DETAILS:
45
+ if name == "state":
46
+ lines.append(f"state: {lifecycle.states[record['id']]}")
47
+ continue
48
+ if record.get(name):
49
+ lines.append(f"{name}: {_value(record[name])}")
50
+ if history:
51
+ lines.append("history:")
52
+ for version in _versions(record, by_id):
53
+ lines.append(
54
+ f"- {version['created_at'][:10]} {version['author']['name']} "
55
+ f"[{version['id']}] {lifecycle.states[version['id']]}: "
56
+ f"{version['statement']}"
57
+ )
58
+ lines.extend(f" {mark}" for mark in record_marks(version, lifecycle))
59
+ return "\n".join(lines) + "\n"
60
+
61
+
62
+ def _value(value: object) -> str:
63
+ if isinstance(value, str):
64
+ return value
65
+ if isinstance(value, list) and all(isinstance(item, str) for item in value):
66
+ return "; ".join(value)
67
+ return json.dumps(value, ensure_ascii=False)
68
+
69
+
70
+ def _versions(record: Record, by_id: dict[str, Record]) -> list[Record]:
71
+ """All earlier versions through replaces (a merge replaces several), the record,
72
+ then later ones through replaced_by; oldest first. A version that is not a
73
+ project record (earlier versions kept personal records) is left out."""
74
+ found = {record["id"]: record}
75
+ waiting = [record]
76
+ while waiting:
77
+ current = waiting.pop()
78
+ linked = list(current.get("replaces") or [])
79
+ if current.get("replaced_by"):
80
+ linked.append(current["replaced_by"])
81
+ for other in linked:
82
+ if other in by_id and other not in found:
83
+ found[other] = by_id[other]
84
+ waiting.append(by_id[other])
85
+ return sorted(found.values(), key=lambda version: version["created_at"])
@@ -0,0 +1,106 @@
1
+ """search_records: records by words, kind and state."""
2
+
3
+ import math
4
+ import re
5
+ import unicodedata
6
+ from collections import Counter
7
+ from collections.abc import Iterator
8
+
9
+ from ..delivery import open_question_marks, record_marks, scoped_line
10
+ from ..knowledge import Lifecycle, open_questions
11
+ from ..model.form import FORM, Record
12
+
13
+ LIMIT = 50
14
+
15
+
16
+ def search_text(
17
+ lifecycle: Lifecycle,
18
+ query: str,
19
+ kinds: list[str],
20
+ states: list[str],
21
+ ) -> str:
22
+ """Rank whole normalized word matches across the selected kinds and states.
23
+ Empty queries browse newest first. Expired records remain searchable, marked
24
+ as not delivered. Scope delivery does not use this ranking or its limit."""
25
+ words = set(_words(query))
26
+ if query.strip() and not words:
27
+ return "No records match.\n"
28
+ candidates = [
29
+ record
30
+ for record in lifecycle.records
31
+ if (not kinds or record["kind"] in kinds)
32
+ and lifecycle.states[record["id"]] in (states or ["active"])
33
+ ]
34
+ found = _rank(candidates, words) if words else candidates
35
+ if not found:
36
+ return "No records match.\n"
37
+ if not words:
38
+ found.sort(
39
+ key=lambda record: (record["created_at"], record["id"]), reverse=True
40
+ )
41
+ shown = found[:LIMIT]
42
+ doubts = open_questions(lifecycle)
43
+ lines = []
44
+ for record in shown:
45
+ marks = record_marks(record, lifecycle)
46
+ marks += open_question_marks(doubts.get(record["id"], []))
47
+ lines.append(scoped_line(record, marks))
48
+ if len(found) > LIMIT:
49
+ lines.append(f"{len(found) - LIMIT} more match. Narrow the query.")
50
+ return "\n".join(lines) + "\n"
51
+
52
+
53
+ def _words(text: str) -> list[str]:
54
+ return re.findall(r"[^\W_]+", unicodedata.normalize("NFKC", text).casefold())
55
+
56
+
57
+ def _rank(records: list[Record], words: set[str]) -> list[Record]:
58
+ """BM25 with k1=1.2 and b=0.75: rare matches outweigh common words and
59
+ long records do not win merely by repeating a term."""
60
+ if not records:
61
+ return []
62
+ documents = [Counter(_words(" ".join(_strings(record)))) for record in records]
63
+ lengths = [sum(document.values()) for document in documents]
64
+ average = sum(lengths) / len(records)
65
+ if not average:
66
+ return []
67
+ frequencies = Counter(
68
+ word for document in documents for word in words & document.keys()
69
+ )
70
+ weights = {
71
+ word: math.log1p((len(records) - count + 0.5) / (count + 0.5))
72
+ for word, count in frequencies.items()
73
+ }
74
+ scored = []
75
+ for record, document, length in zip(records, documents, lengths, strict=True):
76
+ score = sum(
77
+ weights[word]
78
+ * (document[word] * 2.2)
79
+ / (document[word] + 1.2 * (0.25 + 0.75 * length / average))
80
+ for word in sorted(words & document.keys())
81
+ )
82
+ if score:
83
+ scored.append((score, record))
84
+ scored.sort(
85
+ key=lambda match: (match[0], match[1]["created_at"], match[1]["id"]),
86
+ reverse=True,
87
+ )
88
+ return [record for _, record in scored]
89
+
90
+
91
+ def _strings(record: Record) -> Iterator[str]:
92
+ """The text of the form fields: profile name and properties, areas and
93
+ scopes included; service fields are not text a user searches."""
94
+ for field in FORM[record["kind"]]:
95
+ yield from _texts(record.get(field.name))
96
+
97
+
98
+ def _texts(value: object) -> Iterator[str]:
99
+ if isinstance(value, str):
100
+ yield value
101
+ if isinstance(value, list):
102
+ for item in value:
103
+ yield from _texts(item)
104
+ if isinstance(value, dict):
105
+ for item in value.values():
106
+ yield from _texts(item)
@@ -0,0 +1,67 @@
1
+ """A record as the user reads it: words, not JSON."""
2
+
3
+ import json
4
+
5
+ from ..model.form import FORM, Record
6
+ from ..model.scope import scopes_text
7
+
8
+ # Shown in lines of their own.
9
+ OWN_LINES = frozenset(
10
+ {"title", "statement", "scopes", "exclusions", "areas", "question_id"}
11
+ )
12
+
13
+
14
+ def noun(kind: str) -> str:
15
+ if kind == "adr":
16
+ return "ADR"
17
+ return kind
18
+
19
+
20
+ def head_lines(record: Record) -> list[str]:
21
+ """What it is, where it applies and its essence on one line each: Claude Code
22
+ shows only the first 3 lines of a window."""
23
+ return [
24
+ f"{noun(record['kind'])}: {record['title']}",
25
+ f"Applies to: {scopes_text(record['scopes'], record.get('exclusions'))}",
26
+ " ".join(record["statement"].split()),
27
+ ]
28
+
29
+
30
+ def card(record: Record) -> str:
31
+ """The whole record: the head, the other fields named in words and the tags."""
32
+ lines = [
33
+ f"{noun(record['kind'])}: {record['title']}",
34
+ f"Applies to: {scopes_text(record['scopes'], record.get('exclusions'))}",
35
+ record["statement"],
36
+ ]
37
+ for field in FORM[record["kind"]]:
38
+ value = record.get(field.name)
39
+ if value is None or value == "" or value == [] or field.name in OWN_LINES:
40
+ continue
41
+ shown = (
42
+ json.dumps(value, ensure_ascii=False, indent=2)
43
+ if field.name == "properties"
44
+ else value_text(value)
45
+ )
46
+ lines.append(f"{field_label(field.name)}: {shown}")
47
+ if record.get("question_id"):
48
+ lines.append(f"Answers the question {record['question_id']}.")
49
+ if record.get("areas"):
50
+ lines.append(f"Tags (for search): {', '.join(record['areas'])}")
51
+ return "\n".join(lines)
52
+
53
+
54
+ def field_label(name: str) -> str:
55
+ return name.replace("_", " ").capitalize()
56
+
57
+
58
+ def value_text(value: object) -> str:
59
+ """Lists by semicolons, objects as `name: value`; a profile property as
60
+ `address: dev-1`."""
61
+ if isinstance(value, list):
62
+ return "; ".join(value_text(item) for item in value)
63
+ if isinstance(value, dict) and set(value) == {"name", "value"}:
64
+ return f"{value['name']}: {value_text(value['value'])}"
65
+ if isinstance(value, dict):
66
+ return ", ".join(f"{name}: {value_text(item)}" for name, item in value.items())
67
+ return str(value)