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
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
"""The nine record kinds, their fields and the form check.
|
|
2
|
+
|
|
3
|
+
FORM is the table of fields that both the form check and get_record_form
|
|
4
|
+
read. Rules spanning several fields (ADR options, fact observed_at, profile
|
|
5
|
+
entity_type, date order) are not in the table: see _kind_errors.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import difflib
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Callable, Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import date, datetime
|
|
13
|
+
from pathlib import PurePosixPath, PureWindowsPath
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .json import json_value
|
|
17
|
+
from .profile import profile_properties
|
|
18
|
+
from .scope import WHOLE_PROJECT
|
|
19
|
+
|
|
20
|
+
# A saved record: form fields plus the fields RatifyPoint sets.
|
|
21
|
+
Record = Mapping[str, Any]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Field:
|
|
26
|
+
"""One field of a record.
|
|
27
|
+
|
|
28
|
+
`type` is one of: text, line (one-line text), date, enum, texts, paths,
|
|
29
|
+
object, objects, json_object. `limit` is in chars, per item for lists.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
name: str
|
|
33
|
+
type: str
|
|
34
|
+
required: bool = False
|
|
35
|
+
limit: int = 1000
|
|
36
|
+
values: tuple[str, ...] = ()
|
|
37
|
+
min_items: int = 0
|
|
38
|
+
max_items: int | None = None
|
|
39
|
+
fields: tuple["Field", ...] = ()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
LEVELS = ("low", "medium", "high")
|
|
43
|
+
# The states of a record; "closed" is computed for questions.
|
|
44
|
+
STATES = ("active", "outdated", "replaced", "closed")
|
|
45
|
+
MAX_RELATED = 10
|
|
46
|
+
FORMAT_VERSION = 3
|
|
47
|
+
|
|
48
|
+
# Set by RatifyPoint, in file order; the agent never
|
|
49
|
+
# sends them.
|
|
50
|
+
SERVICE_ORDER = (
|
|
51
|
+
"author",
|
|
52
|
+
"producer",
|
|
53
|
+
"confirmation",
|
|
54
|
+
"created_at",
|
|
55
|
+
"state",
|
|
56
|
+
"replaced_by",
|
|
57
|
+
"replaces",
|
|
58
|
+
"answered_by",
|
|
59
|
+
"marks",
|
|
60
|
+
"state_changed",
|
|
61
|
+
"knowledge_hash",
|
|
62
|
+
"format_version",
|
|
63
|
+
)
|
|
64
|
+
SERVICE_FIELDS = frozenset({"id", *SERVICE_ORDER})
|
|
65
|
+
# Fields of records saved by earlier versions: kept as they are, never read.
|
|
66
|
+
LEGACY_FIELDS = ("source",)
|
|
67
|
+
|
|
68
|
+
HEAD = (
|
|
69
|
+
Field("title", "line", required=True, limit=120),
|
|
70
|
+
Field("statement", "text", required=True),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
TAIL = (
|
|
74
|
+
Field("scopes", "paths", required=True, min_items=1, max_items=32),
|
|
75
|
+
Field("exclusions", "paths", max_items=32),
|
|
76
|
+
Field("areas", "texts", max_items=5),
|
|
77
|
+
Field("additions", "text", limit=20000),
|
|
78
|
+
Field("effective_from", "date"),
|
|
79
|
+
Field("effective_until", "date"),
|
|
80
|
+
Field("question_id", "text"),
|
|
81
|
+
Field("related", "texts", max_items=MAX_RELATED),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
KIND_FIELDS: dict[str, tuple[Field, ...]] = {
|
|
85
|
+
"rule": (
|
|
86
|
+
Field("type", "enum", required=True, values=("required", "forbidden")),
|
|
87
|
+
Field("when", "text"),
|
|
88
|
+
Field("why", "text"),
|
|
89
|
+
Field("how_to_verify", "text"),
|
|
90
|
+
),
|
|
91
|
+
"recommendation": (
|
|
92
|
+
Field("when", "text"),
|
|
93
|
+
Field("why", "text"),
|
|
94
|
+
Field("when_to_deviate", "text"),
|
|
95
|
+
),
|
|
96
|
+
"decision": (Field("decided_by", "text"),),
|
|
97
|
+
"adr": (
|
|
98
|
+
Field("context", "text", required=True),
|
|
99
|
+
Field("decision_drivers", "texts", required=True, min_items=1),
|
|
100
|
+
# Exactly one of options (2+) and no_alternatives_because: checked below.
|
|
101
|
+
Field(
|
|
102
|
+
"options",
|
|
103
|
+
"objects",
|
|
104
|
+
fields=(
|
|
105
|
+
Field("name", "text", required=True),
|
|
106
|
+
Field("pros", "texts", required=True, min_items=1),
|
|
107
|
+
Field("cons", "texts", required=True, min_items=1),
|
|
108
|
+
),
|
|
109
|
+
),
|
|
110
|
+
Field("no_alternatives_because", "text"),
|
|
111
|
+
Field("chosen_option", "text", required=True),
|
|
112
|
+
Field("rationale", "text", required=True),
|
|
113
|
+
Field(
|
|
114
|
+
"consequences",
|
|
115
|
+
"object",
|
|
116
|
+
required=True,
|
|
117
|
+
fields=(
|
|
118
|
+
Field("positive", "texts", required=True, min_items=1),
|
|
119
|
+
Field("negative", "texts", required=True, min_items=1),
|
|
120
|
+
),
|
|
121
|
+
),
|
|
122
|
+
Field("decided_by", "text"),
|
|
123
|
+
),
|
|
124
|
+
"fact": (
|
|
125
|
+
Field(
|
|
126
|
+
"known_how",
|
|
127
|
+
"enum",
|
|
128
|
+
required=True,
|
|
129
|
+
values=("verified", "user-stated", "agent-inferred", "assumption"),
|
|
130
|
+
),
|
|
131
|
+
Field("observed_at", "date"),
|
|
132
|
+
Field("key", "text"),
|
|
133
|
+
Field("value", "text"),
|
|
134
|
+
),
|
|
135
|
+
"risk": (
|
|
136
|
+
Field("likelihood", "enum", required=True, values=LEVELS),
|
|
137
|
+
Field("impact", "enum", required=True, values=LEVELS),
|
|
138
|
+
Field("mitigation", "text"),
|
|
139
|
+
),
|
|
140
|
+
"procedure": (
|
|
141
|
+
Field("trigger", "text", required=True),
|
|
142
|
+
Field("steps", "texts", required=True, limit=500, min_items=1, max_items=50),
|
|
143
|
+
Field("expected_result", "text", required=True),
|
|
144
|
+
Field("preconditions", "text"),
|
|
145
|
+
Field("abort_when", "text"),
|
|
146
|
+
Field("must_not", "text"),
|
|
147
|
+
Field("rollback", "text"),
|
|
148
|
+
),
|
|
149
|
+
"question": (
|
|
150
|
+
Field("until_answered", "text", required=True),
|
|
151
|
+
Field("resolution_criteria", "text"),
|
|
152
|
+
Field("ask", "text"),
|
|
153
|
+
),
|
|
154
|
+
"profile": (
|
|
155
|
+
Field("entity_type", "text", required=True),
|
|
156
|
+
Field("entity_name", "text", required=True),
|
|
157
|
+
Field(
|
|
158
|
+
"properties",
|
|
159
|
+
"json_object",
|
|
160
|
+
required=True,
|
|
161
|
+
min_items=1,
|
|
162
|
+
),
|
|
163
|
+
),
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
KINDS = tuple(KIND_FIELDS)
|
|
167
|
+
|
|
168
|
+
FORM: dict[str, tuple[Field, ...]] = {
|
|
169
|
+
kind: HEAD + KIND_FIELDS[kind] + TAIL for kind in KINDS
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def form_errors(record: Mapping[str, object]) -> list[str]:
|
|
174
|
+
"""All form errors of one record, as `<field>: <problem>. Fix: <what to do>.`"""
|
|
175
|
+
kind = record.get("kind")
|
|
176
|
+
if kind is None:
|
|
177
|
+
return [f"kind: required field is missing. Fix: add kind ({_or(KINDS)})."]
|
|
178
|
+
if not isinstance(kind, str) or kind not in FORM:
|
|
179
|
+
return [f'kind: "{kind}" is not allowed. Fix: use {_or(KINDS)}.']
|
|
180
|
+
fields = {name: value for name, value in record.items() if name != "kind"}
|
|
181
|
+
return _object_errors(fields, FORM[kind], "", kind) + _kind_errors(kind, record)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def normalized(record: Mapping[str, object]) -> dict[str, object]:
|
|
185
|
+
"""The record in form order, empty values as null. Only for a valid record."""
|
|
186
|
+
kind = str(record["kind"])
|
|
187
|
+
result: dict[str, object] = {"kind": kind}
|
|
188
|
+
for field in FORM[kind]:
|
|
189
|
+
value = record.get(field.name)
|
|
190
|
+
if value == "" or value == []:
|
|
191
|
+
value = None
|
|
192
|
+
result[field.name] = value
|
|
193
|
+
return result
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def stored_errors(record: Mapping[str, object]) -> list[str]:
|
|
197
|
+
"""Validate stored knowledge and service fields without changing fingerprints."""
|
|
198
|
+
knowledge = {
|
|
199
|
+
name: value
|
|
200
|
+
for name, value in record.items()
|
|
201
|
+
if name not in SERVICE_FIELDS and name not in LEGACY_FIELDS
|
|
202
|
+
}
|
|
203
|
+
if record.get("kind") == "profile":
|
|
204
|
+
try:
|
|
205
|
+
knowledge["properties"] = profile_properties(record.get("properties"))
|
|
206
|
+
except ValueError as error:
|
|
207
|
+
return [str(error)]
|
|
208
|
+
errors = form_errors(knowledge)
|
|
209
|
+
author_fields = (
|
|
210
|
+
Field("name", "text", required=True),
|
|
211
|
+
Field("email", "text"),
|
|
212
|
+
)
|
|
213
|
+
service = {name: record[name] for name in SERVICE_ORDER if name in record}
|
|
214
|
+
service["id"] = record.get("id")
|
|
215
|
+
service.pop("format_version", None)
|
|
216
|
+
errors += _object_errors(
|
|
217
|
+
service,
|
|
218
|
+
(
|
|
219
|
+
Field("id", "text", required=True),
|
|
220
|
+
Field("author", "object", required=True, fields=author_fields),
|
|
221
|
+
Field("producer", "text"),
|
|
222
|
+
Field(
|
|
223
|
+
"confirmation", "enum", required=True, values=("agent", "elicitation")
|
|
224
|
+
),
|
|
225
|
+
Field("created_at", "timestamp", required=True),
|
|
226
|
+
Field(
|
|
227
|
+
"state",
|
|
228
|
+
"enum",
|
|
229
|
+
required=True,
|
|
230
|
+
values=("active", "replaced", "outdated"),
|
|
231
|
+
),
|
|
232
|
+
Field("replaced_by", "text"),
|
|
233
|
+
Field("replaces", "texts"),
|
|
234
|
+
Field("answered_by", "text"),
|
|
235
|
+
Field("knowledge_hash", "text", required=True),
|
|
236
|
+
Field(
|
|
237
|
+
"marks",
|
|
238
|
+
"object",
|
|
239
|
+
fields=(
|
|
240
|
+
Field("checked", "timestamp"),
|
|
241
|
+
Field("not_conflict", "texts"),
|
|
242
|
+
Field("related_review", "json_object"),
|
|
243
|
+
),
|
|
244
|
+
),
|
|
245
|
+
Field(
|
|
246
|
+
"state_changed",
|
|
247
|
+
"object",
|
|
248
|
+
fields=(
|
|
249
|
+
Field("by", "object", required=True, fields=author_fields),
|
|
250
|
+
Field("at", "timestamp", required=True),
|
|
251
|
+
Field(
|
|
252
|
+
"confirmation",
|
|
253
|
+
"enum",
|
|
254
|
+
required=True,
|
|
255
|
+
values=("agent", "elicitation"),
|
|
256
|
+
),
|
|
257
|
+
),
|
|
258
|
+
),
|
|
259
|
+
),
|
|
260
|
+
"",
|
|
261
|
+
"stored record",
|
|
262
|
+
)
|
|
263
|
+
version = record.get("format_version")
|
|
264
|
+
if type(version) is not int or not 1 <= version <= FORMAT_VERSION:
|
|
265
|
+
errors.append(
|
|
266
|
+
f"format_version: expected an integer from 1 to {FORMAT_VERSION}."
|
|
267
|
+
)
|
|
268
|
+
if record.get("state") == "replaced" and not record.get("replaced_by"):
|
|
269
|
+
errors.append("replaced_by: a replaced record must name its successor.")
|
|
270
|
+
return errors
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _object_errors(
|
|
274
|
+
value: Mapping[str, object], fields: tuple[Field, ...], prefix: str, owner: str
|
|
275
|
+
) -> list[str]:
|
|
276
|
+
names = [field.name for field in fields]
|
|
277
|
+
errors = []
|
|
278
|
+
for key in value:
|
|
279
|
+
if key in names:
|
|
280
|
+
continue
|
|
281
|
+
if key in SERVICE_FIELDS:
|
|
282
|
+
errors.append(f"{prefix}{key}: set by RatifyPoint. Fix: remove this field.")
|
|
283
|
+
continue
|
|
284
|
+
close = difflib.get_close_matches(key, names, n=1)
|
|
285
|
+
hint = f" or use {close[0]}" if close else ""
|
|
286
|
+
errors.append(
|
|
287
|
+
f"{prefix}{key}: unknown field for {owner}. Fix: remove it{hint}."
|
|
288
|
+
)
|
|
289
|
+
for field in fields:
|
|
290
|
+
errors += _value_errors(field, value.get(field.name), prefix + field.name)
|
|
291
|
+
return errors
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _value_errors(field: Field, value: object, name: str) -> list[str]:
|
|
295
|
+
if value is None or value == "":
|
|
296
|
+
if not field.required:
|
|
297
|
+
return []
|
|
298
|
+
hint = f" ({_or(field.values)})" if field.values else ""
|
|
299
|
+
return [f"{name}: required field is missing. Fix: add {field.name}{hint}."]
|
|
300
|
+
return _CHECKS[field.type](field, value, name)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _text(field: Field, value: object, name: str) -> list[str]:
|
|
304
|
+
if not isinstance(value, str):
|
|
305
|
+
return [_type_error(field, name, "a string")]
|
|
306
|
+
if len(value) > field.limit:
|
|
307
|
+
return [
|
|
308
|
+
f"{name}: {len(value)} chars, limit {field.limit}. "
|
|
309
|
+
f"Fix: shorten to {field.limit} chars or less."
|
|
310
|
+
]
|
|
311
|
+
return []
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _line(field: Field, value: object, name: str) -> list[str]:
|
|
315
|
+
errors = _text(field, value, name)
|
|
316
|
+
if isinstance(value, str) and "\n" in value:
|
|
317
|
+
errors.append(f"{name}: must be one line. Fix: remove the line breaks.")
|
|
318
|
+
return errors
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _date(field: Field, value: object, name: str) -> list[str]:
|
|
322
|
+
if _parse_date(value) is None:
|
|
323
|
+
return [f'{name}: "{value}" is not a date. Fix: use YYYY-MM-DD.']
|
|
324
|
+
return []
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _timestamp(field: Field, value: object, name: str) -> list[str]:
|
|
328
|
+
if isinstance(value, str):
|
|
329
|
+
try:
|
|
330
|
+
datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
|
|
331
|
+
except ValueError:
|
|
332
|
+
pass
|
|
333
|
+
else:
|
|
334
|
+
return []
|
|
335
|
+
return [f"{name}: expected a UTC timestamp YYYY-MM-DDTHH:MM:SSZ."]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _enum(field: Field, value: object, name: str) -> list[str]:
|
|
339
|
+
if value not in field.values:
|
|
340
|
+
return [f'{name}: "{value}" is not allowed. Fix: use {_or(field.values)}.']
|
|
341
|
+
return []
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _texts(field: Field, value: object, name: str) -> list[str]:
|
|
345
|
+
return _string_list(field, value, name, _text)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _paths(field: Field, value: object, name: str) -> list[str]:
|
|
349
|
+
return _string_list(field, value, name, _scope_path)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _scope_path(field: Field, value: str, name: str) -> list[str]:
|
|
353
|
+
errors = _text(field, value, name)
|
|
354
|
+
if _outside_project(value):
|
|
355
|
+
errors.append(
|
|
356
|
+
f'{name}: path "{value}" is outside the project. '
|
|
357
|
+
"Fix: use a path from the project root."
|
|
358
|
+
)
|
|
359
|
+
# Negation would hide where a record does not apply; exclusions say it.
|
|
360
|
+
if value.startswith("!"):
|
|
361
|
+
errors.append(f'{name}: "!" is not allowed. Fix: use exclusions instead.')
|
|
362
|
+
# The scope "./" is stored as "project" before this check; a path kept with
|
|
363
|
+
# "./" or "." would match no file.
|
|
364
|
+
if value == "." or value.startswith(WHOLE_PROJECT):
|
|
365
|
+
errors.append(
|
|
366
|
+
f'{name}: "{value}" is not a path from the project root. Fix: write '
|
|
367
|
+
'it without "./".'
|
|
368
|
+
)
|
|
369
|
+
return errors
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _string_list(
|
|
373
|
+
field: Field,
|
|
374
|
+
value: object,
|
|
375
|
+
name: str,
|
|
376
|
+
check: Callable[[Field, str, str], list[str]],
|
|
377
|
+
) -> list[str]:
|
|
378
|
+
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
|
379
|
+
return [_type_error(field, name, "a list of strings")]
|
|
380
|
+
errors = _count_errors(field, len(value), name)
|
|
381
|
+
for number, item in enumerate(value, start=1):
|
|
382
|
+
errors += check(field, item, f"{name}[{number}]")
|
|
383
|
+
return errors
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _outside_project(path: str) -> bool:
|
|
387
|
+
"""True for an absolute path (POSIX or Windows) or a path climbing out with ..."""
|
|
388
|
+
return (
|
|
389
|
+
PurePosixPath(path).is_absolute()
|
|
390
|
+
or PureWindowsPath(path).is_absolute()
|
|
391
|
+
or ".." in PurePosixPath(path).parts
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _object(field: Field, value: object, name: str) -> list[str]:
|
|
396
|
+
if not isinstance(value, dict):
|
|
397
|
+
return [_type_error(field, name, "an object")]
|
|
398
|
+
return _object_errors(value, field.fields, f"{name}.", field.name)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _objects(field: Field, value: object, name: str) -> list[str]:
|
|
402
|
+
if not isinstance(value, list):
|
|
403
|
+
return [_type_error(field, name, "a list of objects")]
|
|
404
|
+
errors = _count_errors(field, len(value), name)
|
|
405
|
+
for number, item in enumerate(value, start=1):
|
|
406
|
+
errors += _object(field, item, f"{name}[{number}]")
|
|
407
|
+
return errors
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _json_object(field: Field, value: object, name: str) -> list[str]:
|
|
411
|
+
if not isinstance(value, dict):
|
|
412
|
+
return [
|
|
413
|
+
_type_error(field, name, "a JSON object with keys chosen for this entity")
|
|
414
|
+
]
|
|
415
|
+
try:
|
|
416
|
+
json_value(value, name)
|
|
417
|
+
except ValueError as error:
|
|
418
|
+
return [str(error)]
|
|
419
|
+
return _count_errors(field, len(value), name)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
_CHECKS: dict[str, Callable[[Field, object, str], list[str]]] = {
|
|
423
|
+
"text": _text,
|
|
424
|
+
"line": _line,
|
|
425
|
+
"date": _date,
|
|
426
|
+
"timestamp": _timestamp,
|
|
427
|
+
"enum": _enum,
|
|
428
|
+
"texts": _texts,
|
|
429
|
+
"paths": _paths,
|
|
430
|
+
"object": _object,
|
|
431
|
+
"objects": _objects,
|
|
432
|
+
"json_object": _json_object,
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _kind_errors(kind: str, record: Mapping[str, object]) -> list[str]:
|
|
437
|
+
"""Rules that span several fields."""
|
|
438
|
+
errors = []
|
|
439
|
+
start = _parse_date(record.get("effective_from"))
|
|
440
|
+
end = _parse_date(record.get("effective_until"))
|
|
441
|
+
if start and end and start > end:
|
|
442
|
+
errors.append(
|
|
443
|
+
"effective_from: later than effective_until. Fix: correct the dates."
|
|
444
|
+
)
|
|
445
|
+
if kind == "adr":
|
|
446
|
+
errors += _adr_errors(record)
|
|
447
|
+
if kind == "fact" and record.get("known_how") == "verified":
|
|
448
|
+
if not record.get("observed_at"):
|
|
449
|
+
errors.append(
|
|
450
|
+
"observed_at: required when known_how is verified. "
|
|
451
|
+
"Fix: add the date it was checked."
|
|
452
|
+
)
|
|
453
|
+
entity_type = record.get("entity_type")
|
|
454
|
+
if kind == "profile" and isinstance(entity_type, str):
|
|
455
|
+
if entity_type != entity_type.lower():
|
|
456
|
+
errors.append(
|
|
457
|
+
f'entity_type: must be lowercase. Fix: use "{entity_type.lower()}".'
|
|
458
|
+
)
|
|
459
|
+
return errors
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _adr_errors(record: Mapping[str, object]) -> list[str]:
|
|
463
|
+
options = record.get("options")
|
|
464
|
+
no_alternatives = record.get("no_alternatives_because")
|
|
465
|
+
if options and no_alternatives:
|
|
466
|
+
return [
|
|
467
|
+
"options: set together with no_alternatives_because. "
|
|
468
|
+
"Fix: keep only one of them."
|
|
469
|
+
]
|
|
470
|
+
if not options and not no_alternatives:
|
|
471
|
+
return [
|
|
472
|
+
"options: required field is missing. "
|
|
473
|
+
"Fix: add the options considered, or set no_alternatives_because."
|
|
474
|
+
]
|
|
475
|
+
if isinstance(options, list) and len(options) < 2:
|
|
476
|
+
return [
|
|
477
|
+
f"options: {len(options)} option, at least 2 needed. "
|
|
478
|
+
"Fix: add the options considered, or set no_alternatives_because."
|
|
479
|
+
]
|
|
480
|
+
return []
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _count_errors(field: Field, count: int, name: str) -> list[str]:
|
|
484
|
+
if count < field.min_items:
|
|
485
|
+
return [f"{name}: at least {field.min_items} needed. Fix: add {field.name}."]
|
|
486
|
+
if field.max_items is not None and count > field.max_items:
|
|
487
|
+
return [
|
|
488
|
+
f"{name}: {count} items, limit {field.max_items}. "
|
|
489
|
+
f"Fix: keep {field.max_items} or fewer."
|
|
490
|
+
]
|
|
491
|
+
return []
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _type_error(field: Field, name: str, expected: str) -> str:
|
|
495
|
+
return f"{name}: must be {expected}. Fix: send {field.name} as {expected}."
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _parse_date(value: object) -> date | None:
|
|
499
|
+
if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
|
|
500
|
+
return None
|
|
501
|
+
try:
|
|
502
|
+
return date.fromisoformat(value)
|
|
503
|
+
except ValueError:
|
|
504
|
+
return None
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _or(values: tuple[str, ...]) -> str:
|
|
508
|
+
return ", ".join(values[:-1]) + " or " + values[-1]
|
ratifypoint/model/ids.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Record ids: `<kind>-<slug>-<4>`, or `<kind>-<6>` when the title has no latin."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import secrets
|
|
5
|
+
import string
|
|
6
|
+
from collections.abc import Container
|
|
7
|
+
|
|
8
|
+
ALPHABET = string.digits + string.ascii_lowercase
|
|
9
|
+
SLUG_WORDS = 5
|
|
10
|
+
SLUG_LIMIT = 40
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def new_id(kind: str, title: str, taken: Container[str]) -> str:
|
|
14
|
+
"""A new id that is not in `taken`."""
|
|
15
|
+
words = " ".join(title.lower().split()[:SLUG_WORDS])
|
|
16
|
+
slug = re.sub(r"[^a-z0-9]+", "-", words).strip("-")[:SLUG_LIMIT].rstrip("-")
|
|
17
|
+
if slug:
|
|
18
|
+
prefix = f"{kind}-{slug}"
|
|
19
|
+
length = 4
|
|
20
|
+
else:
|
|
21
|
+
prefix = kind
|
|
22
|
+
length = 6
|
|
23
|
+
while True:
|
|
24
|
+
suffix = "".join(secrets.choice(ALPHABET) for _ in range(length))
|
|
25
|
+
record_id = f"{prefix}-{suffix}"
|
|
26
|
+
if record_id not in taken:
|
|
27
|
+
return record_id
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""JSON values and field selection without losing scalar types."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from typing import TypeAlias
|
|
6
|
+
|
|
7
|
+
JSONValue: TypeAlias = (
|
|
8
|
+
str | int | float | bool | None | list["JSONValue"] | dict[str, "JSONValue"]
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def json_value(value: object, path: str) -> JSONValue:
|
|
13
|
+
"""Validate an external value as JSON; errors identify the offending path."""
|
|
14
|
+
if value is None or isinstance(value, (str, bool, int)):
|
|
15
|
+
return value
|
|
16
|
+
if isinstance(value, float) and math.isfinite(value):
|
|
17
|
+
return value
|
|
18
|
+
if isinstance(value, list):
|
|
19
|
+
return [
|
|
20
|
+
json_value(child, f"{path}/{index}") for index, child in enumerate(value)
|
|
21
|
+
]
|
|
22
|
+
if isinstance(value, dict):
|
|
23
|
+
validated: dict[str, JSONValue] = {}
|
|
24
|
+
for key, child in value.items():
|
|
25
|
+
if not isinstance(key, str):
|
|
26
|
+
raise ValueError(f"{path}: JSON object keys must be strings.")
|
|
27
|
+
validated[key] = json_value(child, f"{path}/{key}")
|
|
28
|
+
return validated
|
|
29
|
+
raise ValueError(f"{path}: expected a JSON value with finite numbers.")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def at_pointer(document: object, pointer: str) -> JSONValue:
|
|
33
|
+
"""Read one RFC 6901 JSON Pointer, including array indexes and escaped keys."""
|
|
34
|
+
if pointer == "":
|
|
35
|
+
return json_value(document, pointer)
|
|
36
|
+
if not pointer.startswith("/") or re.search(r"~(?![01])", pointer):
|
|
37
|
+
raise ValueError(f"{pointer!r}: invalid JSON Pointer; use /field/subfield.")
|
|
38
|
+
current = document
|
|
39
|
+
for part in pointer[1:].split("/"):
|
|
40
|
+
key = part.replace("~1", "/").replace("~0", "~")
|
|
41
|
+
if isinstance(current, dict) and key in current:
|
|
42
|
+
current = current[key]
|
|
43
|
+
elif (
|
|
44
|
+
isinstance(current, list)
|
|
45
|
+
and re.fullmatch(r"0|[1-9][0-9]*", key)
|
|
46
|
+
and int(key) < len(current)
|
|
47
|
+
):
|
|
48
|
+
current = current[int(key)]
|
|
49
|
+
else:
|
|
50
|
+
raise ValueError(f"{pointer!r}: field does not exist.")
|
|
51
|
+
return json_value(current, pointer)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Profile properties, including the string pairs stored by RatifyPoint 1.x."""
|
|
2
|
+
|
|
3
|
+
from .json import JSONValue, json_value
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def profile_properties(stored: object) -> dict[str, JSONValue]:
|
|
7
|
+
"""Read properties without rewriting legacy records or their fingerprints."""
|
|
8
|
+
if isinstance(stored, dict):
|
|
9
|
+
properties = json_value(stored, "properties")
|
|
10
|
+
assert isinstance(properties, dict)
|
|
11
|
+
return properties
|
|
12
|
+
if not isinstance(stored, list):
|
|
13
|
+
raise ValueError(
|
|
14
|
+
"properties: expected a JSON object or legacy name/value pairs."
|
|
15
|
+
)
|
|
16
|
+
properties = {}
|
|
17
|
+
for entry in stored:
|
|
18
|
+
if not isinstance(entry, dict) or set(entry) != {"name", "value"}:
|
|
19
|
+
raise ValueError("properties: malformed legacy name/value pair.")
|
|
20
|
+
name, value = entry["name"], entry["value"]
|
|
21
|
+
if not isinstance(name, str) or not isinstance(value, str):
|
|
22
|
+
raise ValueError("properties: legacy names and values must be strings.")
|
|
23
|
+
if name in properties:
|
|
24
|
+
raise ValueError(f"properties: duplicate legacy name {name!r}.")
|
|
25
|
+
properties[name] = value
|
|
26
|
+
return properties
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Where a record applies: paths from the project root or .gitignore patterns."""
|
|
2
|
+
|
|
3
|
+
from pathspec import GitIgnoreSpec
|
|
4
|
+
|
|
5
|
+
PROJECT = "project"
|
|
6
|
+
# How the whole project is written and shown; it is stored as PROJECT.
|
|
7
|
+
WHOLE_PROJECT = "./"
|
|
8
|
+
PATH_FIELDS = ("scopes", "exclusions")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def applies(scopes: list[str], exclusions: list[str], path: str) -> bool:
|
|
12
|
+
"""True if the path or one of its folders is in a scope and in no exclusion."""
|
|
13
|
+
return _matches(scopes, path) and not _matches(exclusions, path)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _matches(entries: list[str], path: str) -> bool:
|
|
17
|
+
if PROJECT in entries:
|
|
18
|
+
return True
|
|
19
|
+
# A plain path is from the project root; without the leading "/" .gitignore
|
|
20
|
+
# would match "app/" at any depth. Patterns keep .gitignore rules.
|
|
21
|
+
lines = [entry if is_pattern(entry) else "/" + entry for entry in entries]
|
|
22
|
+
return GitIgnoreSpec.from_lines(lines).match_file(path)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_pattern(entry: str) -> bool:
|
|
26
|
+
"""A .gitignore pattern rather than a plain path."""
|
|
27
|
+
return any(char in entry for char in "*?[")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def shown_scope(scope: str) -> str:
|
|
31
|
+
if scope == PROJECT:
|
|
32
|
+
return WHOLE_PROJECT
|
|
33
|
+
return scope
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def scopes_text(scopes: list[str], exclusions: list[str] | None) -> str:
|
|
37
|
+
"""Where a record applies, as the user and the agent read it."""
|
|
38
|
+
text = ", ".join(shown_scope(scope) for scope in scopes)
|
|
39
|
+
if exclusions:
|
|
40
|
+
text += f"; not in {', '.join(exclusions)}"
|
|
41
|
+
return text
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def with_stored_paths(fields: dict[str, object]) -> dict[str, object]:
|
|
45
|
+
"""Fields from the agent with the scope "./" stored as PROJECT; a value that
|
|
46
|
+
is not a list stays for the form check to name."""
|
|
47
|
+
scopes = fields.get("scopes")
|
|
48
|
+
if not isinstance(scopes, list):
|
|
49
|
+
return dict(fields)
|
|
50
|
+
stored = [PROJECT if scope == WHOLE_PROJECT else scope for scope in scopes]
|
|
51
|
+
return {**fields, "scopes": stored}
|