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,81 @@
|
|
|
1
|
+
"""The plugin of Claude Code or Codex in a local marketplace of its own: the MCP
|
|
2
|
+
server and the hooks, in the layout and keys each client expects."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import shlex
|
|
6
|
+
import sysconfig
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .. import __version__
|
|
11
|
+
|
|
12
|
+
NAME = "ratifypoint"
|
|
13
|
+
MARKETPLACE = "ratifypoint-local"
|
|
14
|
+
DESCRIPTION = (
|
|
15
|
+
"User-confirmed project knowledge for AI agents: rules, decisions, facts, "
|
|
16
|
+
"procedures and profiles of resources, servers, services, environments "
|
|
17
|
+
"and database connections."
|
|
18
|
+
)
|
|
19
|
+
PLUGIN = f"plugins/{NAME}"
|
|
20
|
+
AUTHOR = {"name": "RatifyPoint"}
|
|
21
|
+
EXECUTABLE = Path(sysconfig.get_path("scripts")) / NAME
|
|
22
|
+
SERVER = {"command": str(EXECUTABLE), "args": ["mcp", "serve"]}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def plugin_files(client: str) -> dict[str, str]:
|
|
26
|
+
"""The marketplace folder of `client` (claude-code or codex): relative path →
|
|
27
|
+
content. Launch the CLI belonging to this Python environment by absolute path."""
|
|
28
|
+
manifest = {
|
|
29
|
+
"name": NAME,
|
|
30
|
+
"version": __version__,
|
|
31
|
+
"description": DESCRIPTION,
|
|
32
|
+
"author": AUTHOR,
|
|
33
|
+
"mcpServers": "./.mcp.json",
|
|
34
|
+
}
|
|
35
|
+
hooks = {
|
|
36
|
+
"SessionStart": [_hook("session-start", client)],
|
|
37
|
+
"SubagentStart": [_hook("session-start", client)],
|
|
38
|
+
}
|
|
39
|
+
files: dict[str, Any] = {f"{PLUGIN}/hooks/hooks.json": {"hooks": hooks}}
|
|
40
|
+
if client == "claude-code":
|
|
41
|
+
files[".claude-plugin/marketplace.json"] = {
|
|
42
|
+
"name": MARKETPLACE,
|
|
43
|
+
"owner": AUTHOR,
|
|
44
|
+
"description": DESCRIPTION,
|
|
45
|
+
"plugins": [{"name": NAME, "source": f"./{PLUGIN}"}],
|
|
46
|
+
}
|
|
47
|
+
files[f"{PLUGIN}/.claude-plugin/plugin.json"] = manifest
|
|
48
|
+
files[f"{PLUGIN}/.mcp.json"] = {"mcpServers": {NAME: SERVER}}
|
|
49
|
+
if client == "codex":
|
|
50
|
+
files[".agents/plugins/marketplace.json"] = {
|
|
51
|
+
"name": MARKETPLACE,
|
|
52
|
+
"interface": {"displayName": "RatifyPoint Local"},
|
|
53
|
+
"plugins": [
|
|
54
|
+
{
|
|
55
|
+
"name": NAME,
|
|
56
|
+
"source": {"source": "local", "path": f"./{PLUGIN}"},
|
|
57
|
+
"policy": {
|
|
58
|
+
"installation": "AVAILABLE",
|
|
59
|
+
"authentication": "ON_INSTALL",
|
|
60
|
+
},
|
|
61
|
+
"category": "Productivity",
|
|
62
|
+
}
|
|
63
|
+
],
|
|
64
|
+
}
|
|
65
|
+
files[f"{PLUGIN}/.codex-plugin/plugin.json"] = {
|
|
66
|
+
**manifest,
|
|
67
|
+
"interface": {"displayName": "RatifyPoint"},
|
|
68
|
+
}
|
|
69
|
+
files[f"{PLUGIN}/.mcp.json"] = {"mcpServers": {NAME: SERVER}}
|
|
70
|
+
return {path: json.dumps(data, indent=2) + "\n" for path, data in files.items()}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _hook(command: str, client: str) -> dict[str, Any]:
|
|
74
|
+
handler: dict[str, Any] = {
|
|
75
|
+
"type": "command",
|
|
76
|
+
"command": shlex.join([str(EXECUTABLE), "hook", command, client]),
|
|
77
|
+
}
|
|
78
|
+
if client == "codex":
|
|
79
|
+
# Codex keeps about 2,500 tokens of hook text by default; 0 gives it all.
|
|
80
|
+
handler["additionalContextLimit"] = 0
|
|
81
|
+
return {"hooks": [handler]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Rules over several records: duplicates, conflicts, questions, hand edits,
|
|
2
|
+
secrets."""
|
|
3
|
+
|
|
4
|
+
from .conflicts import broken_links, conflicts, open_questions
|
|
5
|
+
from .duplicates import Duplicate, duplicate_of
|
|
6
|
+
from .integrity import edited, knowledge_hash, secrets_in
|
|
7
|
+
from .lifecycle import Lifecycle
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Duplicate",
|
|
11
|
+
"Lifecycle",
|
|
12
|
+
"broken_links",
|
|
13
|
+
"conflicts",
|
|
14
|
+
"duplicate_of",
|
|
15
|
+
"edited",
|
|
16
|
+
"knowledge_hash",
|
|
17
|
+
"open_questions",
|
|
18
|
+
"secrets_in",
|
|
19
|
+
]
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Mechanical conflicts, closed questions and broken links."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from itertools import combinations
|
|
5
|
+
|
|
6
|
+
from ..model.form import Record
|
|
7
|
+
from .duplicates import normalize_text, properties, same_entity
|
|
8
|
+
from .lifecycle import Lifecycle
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def conflicts(lifecycle: Lifecycle) -> dict[str, set[str]]:
|
|
12
|
+
"""Active records marked as conflicting, each with the ids it conflicts with."""
|
|
13
|
+
active = [
|
|
14
|
+
record for record in lifecycle.records if record["id"] in lifecycle.in_effect
|
|
15
|
+
]
|
|
16
|
+
found: dict[str, set[str]] = {}
|
|
17
|
+
for a, b in combinations(active, 2):
|
|
18
|
+
if not _conflict(a, b):
|
|
19
|
+
continue
|
|
20
|
+
if _cleared(a, b):
|
|
21
|
+
continue
|
|
22
|
+
found.setdefault(a["id"], set()).add(b["id"])
|
|
23
|
+
found.setdefault(b["id"], set()).add(a["id"])
|
|
24
|
+
return found
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def open_questions(lifecycle: Lifecycle) -> dict[str, list[str]]:
|
|
28
|
+
"""For each record, the open questions linked to it by related, either way:
|
|
29
|
+
a doubt about it that the user has not resolved yet."""
|
|
30
|
+
records = lifecycle.records
|
|
31
|
+
questions = set()
|
|
32
|
+
for record in records:
|
|
33
|
+
if record["kind"] != "question" or record["id"] not in lifecycle.in_effect:
|
|
34
|
+
continue
|
|
35
|
+
questions.add(record["id"])
|
|
36
|
+
found: dict[str, set[str]] = {}
|
|
37
|
+
for record in records:
|
|
38
|
+
for other in record.get("related") or []:
|
|
39
|
+
if record["id"] in questions:
|
|
40
|
+
found.setdefault(other, set()).add(record["id"])
|
|
41
|
+
if other in questions:
|
|
42
|
+
found.setdefault(record["id"], set()).add(other)
|
|
43
|
+
return {record_id: sorted(ids) for record_id, ids in found.items()}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def broken_links(checked: Iterable[Record], everything: Iterable[Record]) -> list[str]:
|
|
47
|
+
"""Links of active `checked` records to records not in `everything`."""
|
|
48
|
+
known = {record["id"] for record in everything}
|
|
49
|
+
problems = []
|
|
50
|
+
for record in checked:
|
|
51
|
+
for other in [*(record.get("replaces") or []), record.get("replaced_by")]:
|
|
52
|
+
if other and other not in known:
|
|
53
|
+
problems.append(
|
|
54
|
+
f"{record['id']} has a missing version {other}. "
|
|
55
|
+
"Fix: restore the missing record from your backup or Git."
|
|
56
|
+
)
|
|
57
|
+
if record.get("state") != "active":
|
|
58
|
+
continue
|
|
59
|
+
links = [("question_id", record.get("question_id"))]
|
|
60
|
+
links += [("related", other) for other in record.get("related") or []]
|
|
61
|
+
for field, other in links:
|
|
62
|
+
if other is None or other in known:
|
|
63
|
+
continue
|
|
64
|
+
problems.append(
|
|
65
|
+
f"{record['id']} links to {other}, which does not exist. Fix: "
|
|
66
|
+
"restore that record, or remove the link with edit_record replace "
|
|
67
|
+
f'and clear: ["{field}"].'
|
|
68
|
+
)
|
|
69
|
+
return problems
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _conflict(a: Record, b: Record) -> bool:
|
|
73
|
+
# Two new versions of one record: whichever way their scopes lie.
|
|
74
|
+
if set(a.get("replaces") or []) & set(b.get("replaces") or []):
|
|
75
|
+
return True
|
|
76
|
+
# A deeper scope overrides a broader one, so only a shared scope conflicts.
|
|
77
|
+
if not set(a["scopes"]) & set(b["scopes"]):
|
|
78
|
+
return False
|
|
79
|
+
if a["kind"] == "fact" and b["kind"] == "fact":
|
|
80
|
+
return _facts_differ(a, b)
|
|
81
|
+
if same_entity(a, b):
|
|
82
|
+
return _properties_differ(a, b)
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _facts_differ(a: Record, b: Record) -> bool:
|
|
87
|
+
if not a.get("key") or not b.get("key"):
|
|
88
|
+
return False
|
|
89
|
+
if normalize_text(a["key"]) != normalize_text(b["key"]):
|
|
90
|
+
return False
|
|
91
|
+
return normalize_text(a.get("value") or "") != normalize_text(b.get("value") or "")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _properties_differ(a: Record, b: Record) -> bool:
|
|
95
|
+
b_properties = properties(b)
|
|
96
|
+
for name, value in properties(a).items():
|
|
97
|
+
if name in b_properties and b_properties[name] != value:
|
|
98
|
+
return True
|
|
99
|
+
return False
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _cleared(a: Record, b: Record) -> bool:
|
|
103
|
+
"""The user said the pair does not conflict, on either record."""
|
|
104
|
+
a_cleared = (a.get("marks") or {}).get("not_conflict", [])
|
|
105
|
+
b_cleared = (b.get("marks") or {}).get("not_conflict", [])
|
|
106
|
+
return b["id"] in a_cleared or a["id"] in b_cleared
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Duplicates: the same essence in the same place, whatever the kind."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from ..model.form import LEGACY_FIELDS, SERVICE_FIELDS, Record
|
|
8
|
+
from ..model.profile import profile_properties
|
|
9
|
+
from .lifecycle import Lifecycle
|
|
10
|
+
|
|
11
|
+
# Strongest first: of two duplicates the stronger kind stays.
|
|
12
|
+
WEIGHT = (
|
|
13
|
+
"rule",
|
|
14
|
+
"adr",
|
|
15
|
+
"decision",
|
|
16
|
+
"recommendation",
|
|
17
|
+
"procedure",
|
|
18
|
+
"fact",
|
|
19
|
+
"risk",
|
|
20
|
+
"question",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
# Not details: set by RatifyPoint, kept from earlier versions, or not knowledge
|
|
24
|
+
# (the title).
|
|
25
|
+
NOT_DETAILS = SERVICE_FIELDS | set(LEGACY_FIELDS) | {"kind", "title"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Duplicate:
|
|
30
|
+
"""The saved record a new one repeats, the kind to keep, and whether the new
|
|
31
|
+
record adds anything."""
|
|
32
|
+
|
|
33
|
+
record: Record
|
|
34
|
+
kind: str
|
|
35
|
+
news: bool
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def duplicate_of(
|
|
39
|
+
new: Record, records: Iterable[Record], today: str
|
|
40
|
+
) -> Duplicate | None:
|
|
41
|
+
"""The active record that `new` duplicates, from the same storage."""
|
|
42
|
+
lifecycle = Lifecycle(records, today)
|
|
43
|
+
for record in lifecycle.records:
|
|
44
|
+
if lifecycle.states[record["id"]] != "active":
|
|
45
|
+
continue
|
|
46
|
+
if not _same_place(new, record):
|
|
47
|
+
continue
|
|
48
|
+
if not _periods_overlap(new, record):
|
|
49
|
+
continue
|
|
50
|
+
if new["kind"] == "profile" or record["kind"] == "profile":
|
|
51
|
+
if not same_entity(new, record):
|
|
52
|
+
continue
|
|
53
|
+
return Duplicate(record, "profile", _new_properties(new, record))
|
|
54
|
+
if not _same_essence(new, record):
|
|
55
|
+
continue
|
|
56
|
+
kind = min(new["kind"], record["kind"], key=WEIGHT.index)
|
|
57
|
+
return Duplicate(record, kind, _has_details(new, record))
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def normalize_text(text: str) -> str:
|
|
62
|
+
"""Case, spacing, line breaks and a final dot do not matter."""
|
|
63
|
+
return " ".join(text.lower().split()).removesuffix(".")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def same_entity(a: Record, b: Record) -> bool:
|
|
67
|
+
"""Two profiles of one entity: same type and name."""
|
|
68
|
+
if a["kind"] != "profile" or b["kind"] != "profile":
|
|
69
|
+
return False
|
|
70
|
+
same_type = normalize_text(a["entity_type"]) == normalize_text(b["entity_type"])
|
|
71
|
+
same_name = normalize_text(a["entity_name"]) == normalize_text(b["entity_name"])
|
|
72
|
+
return same_type and same_name
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def properties(record: Record) -> dict[str, str]:
|
|
76
|
+
"""Canonical JSON values: keys, scalar types and nested structure matter."""
|
|
77
|
+
return {
|
|
78
|
+
name: json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)
|
|
79
|
+
for name, value in profile_properties(record["properties"]).items()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _same_place(a: Record, b: Record) -> bool:
|
|
84
|
+
same_scopes = set(a["scopes"]) == set(b["scopes"])
|
|
85
|
+
same_exclusions = set(a.get("exclusions") or []) == set(b.get("exclusions") or [])
|
|
86
|
+
return same_scopes and same_exclusions
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _periods_overlap(a: Record, b: Record) -> bool:
|
|
90
|
+
# ISO dates compare as strings; a missing bound is open.
|
|
91
|
+
a_from = a.get("effective_from") or ""
|
|
92
|
+
b_from = b.get("effective_from") or ""
|
|
93
|
+
a_until = a.get("effective_until") or "9999-12-31"
|
|
94
|
+
b_until = b.get("effective_until") or "9999-12-31"
|
|
95
|
+
return a_from <= b_until and b_from <= a_until
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _same_essence(a: Record, b: Record) -> bool:
|
|
99
|
+
return normalize_text(a["statement"]) == normalize_text(b["statement"])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _has_details(new: Record, saved: Record) -> bool:
|
|
103
|
+
"""True if `new` has a filled field that `saved` lacks or states differently."""
|
|
104
|
+
for name, value in new.items():
|
|
105
|
+
if name in NOT_DETAILS:
|
|
106
|
+
continue
|
|
107
|
+
if value in (None, "", []):
|
|
108
|
+
continue
|
|
109
|
+
if not _same_value(value, saved.get(name)):
|
|
110
|
+
return True
|
|
111
|
+
return False
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _same_value(a: object, b: object) -> bool:
|
|
115
|
+
if isinstance(a, str) and isinstance(b, str):
|
|
116
|
+
return normalize_text(a) == normalize_text(b)
|
|
117
|
+
if isinstance(a, list) and isinstance(b, list):
|
|
118
|
+
if all(isinstance(item, str) for item in a + b):
|
|
119
|
+
return {normalize_text(x) for x in a} == {normalize_text(x) for x in b}
|
|
120
|
+
return a == b
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _new_properties(new: Record, saved: Record) -> bool:
|
|
124
|
+
saved_properties = properties(saved)
|
|
125
|
+
for name, value in properties(new).items():
|
|
126
|
+
if saved_properties.get(name) != value:
|
|
127
|
+
return True
|
|
128
|
+
return False
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Hand-edit fingerprint and secrets in a record."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
|
|
8
|
+
from ..model.form import Record
|
|
9
|
+
|
|
10
|
+
# Changed in place by RatifyPoint, so not part of the fingerprint.
|
|
11
|
+
NOT_HASHED = frozenset(
|
|
12
|
+
{
|
|
13
|
+
"state",
|
|
14
|
+
"replaced_by",
|
|
15
|
+
"replaces",
|
|
16
|
+
"answered_by",
|
|
17
|
+
"marks",
|
|
18
|
+
"state_changed",
|
|
19
|
+
"knowledge_hash",
|
|
20
|
+
"format_version",
|
|
21
|
+
"areas",
|
|
22
|
+
"related",
|
|
23
|
+
}
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# Known formats only: hashes, ids and random strings are not secrets.
|
|
27
|
+
SECRET_PATTERNS = (
|
|
28
|
+
("AWS access key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
|
|
29
|
+
("private key", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
|
|
30
|
+
("GitHub token", re.compile(r"\bghp_[A-Za-z0-9]{36}\b|\bgithub_pat_\w{22,}")),
|
|
31
|
+
("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")),
|
|
32
|
+
("password or token", re.compile(r"(?i)\b(password|secret|token)\s*[=:]\s*\S")),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def knowledge_hash(record: Record) -> str:
|
|
37
|
+
"""sha256 of everything written once at save, as canonical JSON."""
|
|
38
|
+
payload = {key: value for key, value in record.items() if key not in NOT_HASHED}
|
|
39
|
+
text = json.dumps(
|
|
40
|
+
payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")
|
|
41
|
+
)
|
|
42
|
+
return hashlib.sha256(text.encode()).hexdigest()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def edited(record: Record) -> bool:
|
|
46
|
+
"""True when the knowledge was changed by hand outside RatifyPoint."""
|
|
47
|
+
return bool(record["knowledge_hash"] != knowledge_hash(record))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def secrets_in(record: Record) -> list[str]:
|
|
51
|
+
"""Form errors for fields that hold a secret."""
|
|
52
|
+
errors = []
|
|
53
|
+
for name, text in _strings(record, ""):
|
|
54
|
+
for kind, pattern in SECRET_PATTERNS:
|
|
55
|
+
if pattern.search(text):
|
|
56
|
+
errors.append(
|
|
57
|
+
f"{name}: looks like a secret ({kind}). "
|
|
58
|
+
"Fix: remove it and write where to get access instead."
|
|
59
|
+
)
|
|
60
|
+
break
|
|
61
|
+
return errors
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _strings(value: object, name: str) -> Iterator[tuple[str, str]]:
|
|
65
|
+
if isinstance(value, str):
|
|
66
|
+
yield name, value
|
|
67
|
+
if isinstance(value, dict):
|
|
68
|
+
for key, item in value.items():
|
|
69
|
+
if name:
|
|
70
|
+
yield from _strings(item, f"{name}.{key}")
|
|
71
|
+
else:
|
|
72
|
+
yield from _strings(item, key)
|
|
73
|
+
if isinstance(value, list):
|
|
74
|
+
for number, item in enumerate(value, start=1):
|
|
75
|
+
yield from _strings(item, f"{name}[{number}]")
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""The effective state of each record at a date, including scheduled replacements."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
|
|
6
|
+
from ..model.form import Record
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Lifecycle:
|
|
10
|
+
"""One dated view of stored records; reading it never changes their history.
|
|
11
|
+
|
|
12
|
+
A replacement retires its predecessors when it starts, never before it was
|
|
13
|
+
recorded. Future versions remain visible as future knowledge. Deleting a
|
|
14
|
+
replacement does not restore its predecessors; restoration is explicit.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, records: Iterable[Record], today: str) -> None:
|
|
18
|
+
self.records = list(records)
|
|
19
|
+
self.by_id: dict[str, Record] = {
|
|
20
|
+
record["id"]: record for record in self.records
|
|
21
|
+
}
|
|
22
|
+
self.today = today
|
|
23
|
+
self.replacement_dates: dict[str, str] = {}
|
|
24
|
+
self.states: dict[str, str] = {}
|
|
25
|
+
for record in self.records:
|
|
26
|
+
identity = record["id"]
|
|
27
|
+
state = str(record["state"])
|
|
28
|
+
if state == "replaced":
|
|
29
|
+
successors = self.successors(record)
|
|
30
|
+
if successors:
|
|
31
|
+
starts = min(
|
|
32
|
+
max(
|
|
33
|
+
datetime.fromisoformat(version["created_at"])
|
|
34
|
+
.astimezone()
|
|
35
|
+
.date()
|
|
36
|
+
.isoformat(),
|
|
37
|
+
version.get("effective_from") or "",
|
|
38
|
+
)
|
|
39
|
+
for version in successors
|
|
40
|
+
)
|
|
41
|
+
self.replacement_dates[identity] = starts
|
|
42
|
+
if starts > today:
|
|
43
|
+
state = "active"
|
|
44
|
+
self.states[identity] = state
|
|
45
|
+
self.in_effect: set[str] = {
|
|
46
|
+
record["id"]
|
|
47
|
+
for record in self.records
|
|
48
|
+
if self.states[record["id"]] == "active"
|
|
49
|
+
and (not record.get("effective_from") or record["effective_from"] <= today)
|
|
50
|
+
and (
|
|
51
|
+
not record.get("effective_until") or record["effective_until"] >= today
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
closed = set()
|
|
55
|
+
for record in self.records:
|
|
56
|
+
if record["id"] in self.in_effect and record.get("question_id"):
|
|
57
|
+
closed.add(record["question_id"])
|
|
58
|
+
if record.get("answered_by") in self.in_effect:
|
|
59
|
+
closed.add(record["id"])
|
|
60
|
+
self.closed: set[str] = closed
|
|
61
|
+
for identity in closed:
|
|
62
|
+
if self.states.get(identity) == "active":
|
|
63
|
+
self.states[identity] = "closed"
|
|
64
|
+
self.in_effect -= closed
|
|
65
|
+
self.delivered = [
|
|
66
|
+
record
|
|
67
|
+
for record in self.records
|
|
68
|
+
if self.states[record["id"]] == "active"
|
|
69
|
+
and (
|
|
70
|
+
not record.get("effective_until") or record["effective_until"] >= today
|
|
71
|
+
)
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
def successors(self, record: Record) -> list[Record]:
|
|
75
|
+
"""Later versions in order; missing links are reported separately."""
|
|
76
|
+
versions = []
|
|
77
|
+
seen = {record["id"]}
|
|
78
|
+
current = record
|
|
79
|
+
while current.get("replaced_by"):
|
|
80
|
+
identity = current["replaced_by"]
|
|
81
|
+
if identity in seen:
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"Replacement history of {record['id']} cycles through {identity}."
|
|
84
|
+
)
|
|
85
|
+
seen.add(identity)
|
|
86
|
+
if identity not in self.by_id:
|
|
87
|
+
break
|
|
88
|
+
current = self.by_id[identity]
|
|
89
|
+
versions.append(current)
|
|
90
|
+
return versions
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Review the versions named by related without treating them as dependencies."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from ..model.form import Record
|
|
7
|
+
from .integrity import knowledge_hash
|
|
8
|
+
from .lifecycle import Lifecycle
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def related_snapshot(record: Record, lifecycle: Lifecycle) -> dict[str, str]:
|
|
12
|
+
"""Fingerprint linked knowledge and its successors, excluding review metadata.
|
|
13
|
+
|
|
14
|
+
Confirming either record must not cause another review by itself. Knowledge,
|
|
15
|
+
replacement and validity changes do; links keep their original version IDs.
|
|
16
|
+
"""
|
|
17
|
+
snapshot = {}
|
|
18
|
+
for identity in record.get("related") or []:
|
|
19
|
+
target = lifecycle.by_id.get(identity)
|
|
20
|
+
versions = [] if target is None else [target, *lifecycle.successors(target)]
|
|
21
|
+
contents = [
|
|
22
|
+
{
|
|
23
|
+
"id": version["id"],
|
|
24
|
+
"knowledge": knowledge_hash(version),
|
|
25
|
+
"state": lifecycle.states[version["id"]],
|
|
26
|
+
"in_effect": version["id"] in lifecycle.in_effect,
|
|
27
|
+
}
|
|
28
|
+
for version in versions
|
|
29
|
+
]
|
|
30
|
+
text = json.dumps(contents, sort_keys=True, separators=(",", ":"))
|
|
31
|
+
snapshot[identity] = hashlib.sha256(text.encode()).hexdigest()
|
|
32
|
+
return snapshot
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def related_changes(record: Record, lifecycle: Lifecycle) -> list[str]:
|
|
36
|
+
"""Linked IDs needing a review, never a verdict that this record is invalid."""
|
|
37
|
+
previous = (record.get("marks") or {}).get("related_review")
|
|
38
|
+
if previous is not None and (
|
|
39
|
+
not isinstance(previous, dict)
|
|
40
|
+
or not all(
|
|
41
|
+
isinstance(key, str) and isinstance(value, str)
|
|
42
|
+
for key, value in previous.items()
|
|
43
|
+
)
|
|
44
|
+
):
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"{record['id']}: marks.related_review must map IDs to fingerprints."
|
|
47
|
+
)
|
|
48
|
+
changed = []
|
|
49
|
+
for identity, digest in related_snapshot(record, lifecycle).items():
|
|
50
|
+
# Migrated links need an initial review: the originally reviewed
|
|
51
|
+
# contents were not recorded.
|
|
52
|
+
if previous is None or previous.get(identity) != digest:
|
|
53
|
+
changed.append(identity)
|
|
54
|
+
return changed
|