protocolith 0.6.0__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 (57) hide show
  1. protocolith/__init__.py +38 -0
  2. protocolith/baseline_groups.py +294 -0
  3. protocolith/baselines.py +288 -0
  4. protocolith/card_svg_render.py +281 -0
  5. protocolith/card_svg_styles.py +178 -0
  6. protocolith/cli.py +796 -0
  7. protocolith/core/__init__.py +63 -0
  8. protocolith/core/_lock_posix.py +29 -0
  9. protocolith/core/_lock_windows.py +29 -0
  10. protocolith/core/atlas.py +406 -0
  11. protocolith/core/atlas_assets/atlas.css +86 -0
  12. protocolith/core/atlas_assets/atlas.html +84 -0
  13. protocolith/core/atlas_assets/atlas.js +370 -0
  14. protocolith/core/atlas_i18n/en.json +61 -0
  15. protocolith/core/canonical.py +124 -0
  16. protocolith/core/capture.py +68 -0
  17. protocolith/core/clock.py +25 -0
  18. protocolith/core/commands.py +356 -0
  19. protocolith/core/errors.py +116 -0
  20. protocolith/core/issue.py +98 -0
  21. protocolith/core/ledger.py +75 -0
  22. protocolith/core/mcp.py +371 -0
  23. protocolith/core/ops.py +183 -0
  24. protocolith/core/rules.py +352 -0
  25. protocolith/core/schema.py +137 -0
  26. protocolith/core/store.py +101 -0
  27. protocolith/core/views.py +136 -0
  28. protocolith/doctor.py +135 -0
  29. protocolith/evidence_card.py +354 -0
  30. protocolith/family_ledger.py +489 -0
  31. protocolith/generic_ohlcv_batch_pre_registration_meta.py +123 -0
  32. protocolith/inspect.py +48 -0
  33. protocolith/nasa_power.py +266 -0
  34. protocolith/nasa_power_fetch.py +64 -0
  35. protocolith/nasa_power_parser.py +133 -0
  36. protocolith/nasa_power_prereg_runner.py +383 -0
  37. protocolith/noaa_coops_fetch.py +188 -0
  38. protocolith/noaa_coops_parser.py +120 -0
  39. protocolith/noaa_coops_prereg_runner.py +341 -0
  40. protocolith/public_ai_protocol.py +176 -0
  41. protocolith/py.typed +0 -0
  42. protocolith/registry.py +139 -0
  43. protocolith/registry_view.py +302 -0
  44. protocolith/rerun_report.py +111 -0
  45. protocolith/run_root.py +243 -0
  46. protocolith/scaffold.py +565 -0
  47. protocolith/source_probe.py +230 -0
  48. protocolith/svg_a11y.py +100 -0
  49. protocolith/tree_overlay.py +343 -0
  50. protocolith/verify_packs.py +251 -0
  51. protocolith/workflows.py +233 -0
  52. protocolith-0.6.0.dist-info/METADATA +283 -0
  53. protocolith-0.6.0.dist-info/RECORD +57 -0
  54. protocolith-0.6.0.dist-info/WHEEL +4 -0
  55. protocolith-0.6.0.dist-info/entry_points.txt +3 -0
  56. protocolith-0.6.0.dist-info/licenses/LICENSE +201 -0
  57. protocolith-0.6.0.dist-info/licenses/NOTICE +13 -0
@@ -0,0 +1,75 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Ledger entry format: constants, hashing and serialization."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from collections.abc import Mapping
8
+ from datetime import datetime
9
+ from typing import Any
10
+
11
+ from .canonical import encode, sha256_hex
12
+ from .errors import InputError
13
+
14
+ FORMAT_VERSION = 1
15
+ ZERO_HASH = "0" * 64
16
+ MAX_ENTRY_BYTES = 1_048_576
17
+ ENTRY_TYPES = ("freeze", "record", "deviation", "issue")
18
+ ENTRY_KEYS = frozenset({"body", "hash", "prev", "seq", "ts", "type", "v"})
19
+ CARD_FORMAT = "evidence-card-json-svg"
20
+
21
+ # Same closed sets as protocolith.evidence_card; a test keeps them identical.
22
+ RESULT_STATUSES = frozenset(
23
+ {
24
+ "PASSED_UNDER_PROTOCOL",
25
+ "NEGATIVE_RESULT_UNDER_PROTOCOL",
26
+ "BLOCKED_SOURCE",
27
+ "INSUFFICIENT_COVERAGE",
28
+ "SOURCE_DRIFT",
29
+ "REPRODUCED_OUTCOME",
30
+ }
31
+ )
32
+
33
+ Entry = dict[str, Any]
34
+
35
+ _HASH_RE = re.compile(r"[0-9a-f]{64}")
36
+ _HEAD_REF_RE = re.compile(r"(0|[1-9][0-9]*):([0-9a-f]{64})")
37
+ _TS_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z")
38
+
39
+
40
+ def is_hash(value: object) -> bool:
41
+ return isinstance(value, str) and _HASH_RE.fullmatch(value) is not None
42
+
43
+
44
+ def parse_head_ref(value: object) -> tuple[int, str]:
45
+ """Parse ``SEQ:HASH`` (decimal seq without leading zeros, lowercase 64-hex hash)."""
46
+ found = _HEAD_REF_RE.fullmatch(value) if isinstance(value, str) else None
47
+ if found is None:
48
+ raise InputError("BAD_ENTRY", "expected head must look like SEQ:HASH (decimal seq, 64 lowercase hex characters)")
49
+ return int(found.group(1)), found.group(2)
50
+
51
+
52
+ def is_ts(value: object) -> bool:
53
+ if not (isinstance(value, str) and _TS_RE.fullmatch(value)):
54
+ return False
55
+ try:
56
+ datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
57
+ except ValueError:
58
+ return False
59
+ return True
60
+
61
+
62
+ def entry_hash(entry: Mapping[str, Any]) -> str:
63
+ """sha256 of the entry object without its ``hash`` field."""
64
+ return sha256_hex({key: value for key, value in entry.items() if key != "hash"})
65
+
66
+
67
+ def make_entry(*, seq: int, prev: str, ts: str, type: str, body: Mapping[str, Any]) -> Entry:
68
+ entry: Entry = {"body": body, "prev": prev, "seq": seq, "ts": ts, "type": type, "v": FORMAT_VERSION}
69
+ entry["hash"] = entry_hash(entry)
70
+ return entry
71
+
72
+
73
+ def serialize(entry: Mapping[str, Any]) -> bytes:
74
+ """One ledger line: PCJ-1 bytes plus a newline."""
75
+ return encode(entry) + b"\n"
@@ -0,0 +1,371 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Minimal MCP server over stdio: newline-delimited JSON-RPC 2.0, tools and read-only resources, no network."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from collections.abc import Callable, Iterable, Mapping
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any, BinaryIO
11
+
12
+ from . import ops
13
+ from .atlas import DEFAULT_OUT, DEFAULT_TITLE, build_atlas_result, confine, write_atlas
14
+ from .capture import capture
15
+ from .canonical import CanonError, decode, encode
16
+ from .clock import Clock
17
+ from .errors import InputError, ProtocolithError
18
+ from .schema import NAMES, all_schemas, schema_for
19
+ from .ledger import ENTRY_TYPES, RESULT_STATUSES
20
+ from .store import Store
21
+
22
+ PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
23
+ SERVER_NAME = "protocolith"
24
+ SERVER_VERSION = "0.6.0"
25
+
26
+ Handler = Callable[[Store, dict[str, Any], Clock | None], Any]
27
+
28
+
29
+ class RpcError(Exception):
30
+ def __init__(self, code: int, message: str) -> None:
31
+ super().__init__(message)
32
+ self.code = code
33
+ self.message = message
34
+
35
+
36
+ def _take(arguments: dict[str, Any], required: tuple[str, ...], optional: tuple[str, ...] = ()) -> dict[str, Any]:
37
+ missing = [key for key in required if key not in arguments]
38
+ if missing:
39
+ raise InputError("MISSING_FIELD", "missing arguments: " + ", ".join(missing))
40
+ extra = sorted(key for key in arguments if key not in required + optional)
41
+ if extra:
42
+ raise InputError("BAD_ENTRY", "unexpected arguments: " + ", ".join(extra))
43
+ return arguments
44
+
45
+
46
+ def _freeze(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
47
+ args = _take(arguments, ("protocol",), ("supersedes",))
48
+ return ops.freeze(store, args["protocol"], supersedes=args.get("supersedes"), clock=clock)
49
+
50
+
51
+ def _record(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
52
+ return ops.record(store, _take(arguments, ("body",))["body"], clock=clock)
53
+
54
+
55
+ def _deviation(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
56
+ return ops.deviation(store, _take(arguments, ("body",))["body"], clock=clock)
57
+
58
+
59
+ def _verify(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
60
+ args = _take(arguments, (), ("expect_head",))
61
+ return ops.verify(store, args.get("expect_head")).to_dict()
62
+
63
+
64
+ def _issue(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
65
+ return ops.issue(store, _take(arguments, ("seq",))["seq"], clock=clock)
66
+
67
+
68
+ def _log(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
69
+ args = _take(arguments, (), ("protocol", "type", "status", "tail"))
70
+ return {"entries": ops.log(store, **args), "head": ops.head(store)}
71
+
72
+
73
+ def _show(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
74
+ return ops.show(store, _take(arguments, ("seq",))["seq"])
75
+
76
+
77
+ def _summary(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
78
+ return ops.summary(store, _take(arguments, (), ("protocol",)).get("protocol"))
79
+
80
+
81
+ def _capture(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
82
+ args = _take(arguments, (), ("files", "env"))
83
+ files = args.get("files", [])
84
+ if not (isinstance(files, list) and all(isinstance(name, str) for name in files)):
85
+ raise InputError("BAD_ENTRY", "files must be a list of strings")
86
+ return capture(files, env=args.get("env") is True)
87
+
88
+
89
+ def _schema(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
90
+ name = _take(arguments, (), ("name",)).get("name", "all")
91
+ return all_schemas() if name == "all" else schema_for(name)
92
+
93
+
94
+ def _atlas(store: Store, arguments: dict[str, Any], clock: Clock | None) -> Any:
95
+ args = _take(arguments, (), ("out", "title", "cards", "i18n", "default_lang", "max_rows"))
96
+ cards = args.get("cards", [])
97
+ if not (isinstance(cards, list) and all(isinstance(name, str) for name in cards)):
98
+ raise InputError("BAD_ENTRY", "cards must be a list of strings")
99
+ folders = [confine(name) for name in cards]
100
+ i18n = confine(args["i18n"]) if "i18n" in args else None
101
+ out = confine(args.get("out", DEFAULT_OUT))
102
+ result = build_atlas_result(
103
+ store=None if folders else store,
104
+ cards=folders,
105
+ title=args.get("title", DEFAULT_TITLE),
106
+ i18n_dir=i18n,
107
+ default_lang=args.get("default_lang", "en"),
108
+ max_rows=args.get("max_rows"),
109
+ )
110
+ path = write_atlas(result.html, out)
111
+ return {**result.to_dict(), "path": path.relative_to(Path.cwd().resolve()).as_posix()}
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class Tool:
116
+ name: str
117
+ description: str
118
+ properties: Mapping[str, Any]
119
+ required: tuple[str, ...]
120
+ run: Handler
121
+
122
+ def listing(self) -> dict[str, Any]:
123
+ schema = {
124
+ "type": "object",
125
+ "properties": dict(self.properties),
126
+ "required": list(self.required),
127
+ "additionalProperties": False,
128
+ }
129
+ return {"name": self.name, "description": self.description, "inputSchema": schema}
130
+
131
+
132
+ _OBJECT = {"type": "object"}
133
+ TOOLS: dict[str, Tool] = {
134
+ tool.name: tool
135
+ for tool in (
136
+ Tool(
137
+ "protocolith_freeze",
138
+ "Freeze a protocol (an object with protocol_id and version) before a run.",
139
+ {
140
+ "protocol": _OBJECT,
141
+ "supersedes": {"type": ["string", "null"], "description": "sha256 of the old version"},
142
+ },
143
+ ("protocol",),
144
+ _freeze,
145
+ ),
146
+ Tool(
147
+ "protocolith_record",
148
+ "Record the outcome of a run against a frozen protocol.",
149
+ {"body": _OBJECT},
150
+ ("body",),
151
+ _record,
152
+ ),
153
+ Tool(
154
+ "protocolith_deviation",
155
+ "Record a deviation from a frozen protocol.",
156
+ {"body": _OBJECT},
157
+ ("body",),
158
+ _deviation,
159
+ ),
160
+ Tool(
161
+ "protocolith_verify",
162
+ "Verify the whole ledger; isError is true when it does not verify. "
163
+ "With expect_head (SEQ:HASH) the ledger must also contain that entry, else HEAD_MISMATCH.",
164
+ {"expect_head": {"type": "string", "description": "SEQ:HASH of a previously published head"}},
165
+ (),
166
+ _verify,
167
+ ),
168
+ Tool(
169
+ "protocolith_issue",
170
+ "Issue the evidence card (JSON and SVG, inside the store) for the record at seq.",
171
+ {"seq": {"type": "integer", "minimum": 0}},
172
+ ("seq",),
173
+ _issue,
174
+ ),
175
+ Tool(
176
+ "protocolith_log",
177
+ "List ledger entries (optionally filtered) and the current head.",
178
+ {
179
+ "protocol": {"type": "string", "description": "only entries of this protocol_id"},
180
+ "type": {"enum": list(ENTRY_TYPES)},
181
+ "status": {"enum": sorted(RESULT_STATUSES), "description": "only records with this status"},
182
+ "tail": {"type": "integer", "minimum": 1, "description": "keep the last N matches"},
183
+ },
184
+ (),
185
+ _log,
186
+ ),
187
+ Tool(
188
+ "protocolith_show",
189
+ "One entry with its protocol, the entries it points at and the entries that point at it.",
190
+ {"seq": {"type": "integer", "minimum": 0}},
191
+ ("seq",),
192
+ _show,
193
+ ),
194
+ Tool(
195
+ "protocolith_summary",
196
+ "What was done and which results are honest: verdict, head, counts by type and status, "
197
+ "a per-protocol table and the problems found. One fast call; start here.",
198
+ {"protocol": {"type": "string", "description": "only this protocol_id"}},
199
+ (),
200
+ _summary,
201
+ ),
202
+ Tool(
203
+ "protocolith_capture",
204
+ "Describe the environment (Python, platform, machine, protocolith version) and hash input files inside "
205
+ "the current directory. Returns a fragment for the outcome object of a record. Runs nothing; reads no "
206
+ "environment values.",
207
+ {
208
+ "files": {
209
+ "type": "array",
210
+ "items": {"type": "string"},
211
+ "description": "paths inside the working directory",
212
+ },
213
+ "env": {"type": "boolean", "description": "include the environment (default when no file is given)"},
214
+ },
215
+ (),
216
+ _capture,
217
+ ),
218
+ Tool(
219
+ "protocolith_atlas",
220
+ "Write a self-contained offline HTML atlas of the experiments (the ledger records, or the evidence card "
221
+ "directories named in cards) and return the path written, inside the working directory. "
222
+ "isError is true when the ledger fails verification; the atlas is still written, with a warning banner.",
223
+ {
224
+ "out": {"type": "string", "description": "output .html file or directory (default protocolith-atlas.html)"},
225
+ "title": {"type": "string"},
226
+ "cards": {"type": "array", "items": {"type": "string"}, "description": "card directories, used instead of the ledger"},
227
+ "i18n": {"type": "string", "description": "directory of <code>.json translation files"},
228
+ "default_lang": {"type": "string"},
229
+ "max_rows": {"type": "integer", "minimum": 1},
230
+ },
231
+ (),
232
+ _atlas,
233
+ ),
234
+ Tool(
235
+ "protocolith_schema",
236
+ "JSON Schema (draft 2020-12) of the inputs: freeze, record, deviation, issue, entry, or all.",
237
+ {"name": {"enum": [*NAMES, "all"]}},
238
+ (),
239
+ _schema,
240
+ ),
241
+ )
242
+ }
243
+
244
+
245
+ def _result(data: Any, *, is_error: bool) -> dict[str, Any]:
246
+ return {"content": [{"type": "text", "text": encode(data).decode("utf-8")}], "isError": is_error}
247
+
248
+
249
+ def _initialize(store: Store, params: dict[str, Any], clock: Clock | None) -> dict[str, Any]:
250
+ wanted = params.get("protocolVersion")
251
+ version = wanted if wanted in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
252
+ return {
253
+ "protocolVersion": version,
254
+ "capabilities": {"resources": {}, "tools": {}},
255
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
256
+ }
257
+
258
+
259
+ def _ping(store: Store, params: dict[str, Any], clock: Clock | None) -> dict[str, Any]:
260
+ return {}
261
+
262
+
263
+ def _resources_list(store: Store, params: dict[str, Any], clock: Clock | None) -> dict[str, Any]:
264
+ items = [("summary", "Ledger summary"), ("ledger", "All ledger entries and the head")]
265
+ items += [(f"schema/{name}", f"JSON Schema: {name}") for name in NAMES]
266
+ return {
267
+ "resources": [
268
+ {"uri": f"protocolith://{path}", "name": path, "description": text, "mimeType": "application/json"}
269
+ for path, text in items
270
+ ]
271
+ }
272
+
273
+
274
+ def _resource_data(store: Store, uri: Any) -> Any:
275
+ prefix = "protocolith://"
276
+ path = uri[len(prefix) :] if isinstance(uri, str) and uri.startswith(prefix) else ""
277
+ if path == "summary":
278
+ return ops.summary(store)
279
+ if path == "ledger":
280
+ return {"entries": ops.entries(store), "head": ops.head(store)}
281
+ if path.startswith("schema/") and path[7:] in NAMES:
282
+ return schema_for(path[7:])
283
+ raise RpcError(-32002, f"resource not found: {uri!r}")
284
+
285
+
286
+ def _resources_read(store: Store, params: dict[str, Any], clock: Clock | None) -> dict[str, Any]:
287
+ uri = params.get("uri")
288
+ try:
289
+ data = _resource_data(store, uri)
290
+ except ProtocolithError as exc:
291
+ raise RpcError(-32000, f"{exc.code}: {exc.message}") from None
292
+ return {"contents": [{"uri": uri, "mimeType": "application/json", "text": encode(data).decode("utf-8")}]}
293
+
294
+
295
+ def _tools_list(store: Store, params: dict[str, Any], clock: Clock | None) -> dict[str, Any]:
296
+ return {"tools": [tool.listing() for tool in TOOLS.values()]}
297
+
298
+
299
+ def _tools_call(store: Store, params: dict[str, Any], clock: Clock | None) -> dict[str, Any]:
300
+ name = params.get("name")
301
+ tool = TOOLS.get(name) if isinstance(name, str) else None
302
+ if tool is None:
303
+ raise RpcError(-32602, f"unknown tool: {name!r}")
304
+ arguments = params.get("arguments", {})
305
+ if not isinstance(arguments, dict):
306
+ raise RpcError(-32602, "arguments must be an object")
307
+ try:
308
+ data = tool.run(store, arguments, clock)
309
+ except ProtocolithError as exc:
310
+ return _result(exc.to_dict(), is_error=True)
311
+ return _result(data, is_error=isinstance(data, dict) and data.get("ok") is False)
312
+
313
+
314
+ METHODS: dict[str, Callable[[Store, dict[str, Any], Clock | None], dict[str, Any]]] = {
315
+ "initialize": _initialize,
316
+ "ping": _ping,
317
+ "resources/list": _resources_list,
318
+ "resources/read": _resources_read,
319
+ "tools/list": _tools_list,
320
+ "tools/call": _tools_call,
321
+ }
322
+
323
+
324
+ def _error(request_id: Any, code: int, message: str) -> dict[str, Any]:
325
+ return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
326
+
327
+
328
+ def handle_message(message: Any, store: Store, clock: Clock | None = None) -> dict[str, Any] | None:
329
+ """Answer one decoded JSON-RPC message; notifications get no answer."""
330
+ if not (isinstance(message, dict) and message.get("jsonrpc") == "2.0" and isinstance(message.get("method"), str)):
331
+ request_id = message.get("id") if isinstance(message, dict) else None
332
+ return _error(request_id, -32600, "invalid request")
333
+ is_request = "id" in message
334
+ request_id = message.get("id")
335
+ method = METHODS.get(message["method"])
336
+ params = message.get("params", {})
337
+ if not is_request:
338
+ return None
339
+ if method is None:
340
+ return _error(request_id, -32601, f"method not found: {message['method']}")
341
+ if not isinstance(params, dict):
342
+ return _error(request_id, -32602, "params must be an object")
343
+ try:
344
+ return {"jsonrpc": "2.0", "id": request_id, "result": method(store, params, clock)}
345
+ except RpcError as exc:
346
+ return _error(request_id, exc.code, exc.message)
347
+ except Exception as exc: # a bug must not kill the server or leak a traceback to stdout
348
+ return _error(request_id, -32603, f"internal error: {type(exc).__name__}")
349
+
350
+
351
+ def handle_line(raw: bytes, store: Store, clock: Clock | None = None) -> bytes | None:
352
+ try:
353
+ message = decode(raw)
354
+ except CanonError as exc:
355
+ reply: dict[str, Any] | None = _error(None, -32700, f"parse error: {exc.code}: {exc.message}")
356
+ else:
357
+ reply = handle_message(message, store, clock)
358
+ if reply is None:
359
+ return None
360
+ return json.dumps(reply, separators=(",", ":"), ensure_ascii=True).encode("ascii")
361
+
362
+
363
+ def serve(store: Store, stdin: Iterable[bytes], stdout: BinaryIO, clock: Clock | None = None) -> None:
364
+ """Read requests line by line until EOF. Nothing but JSON-RPC replies is written to ``stdout``."""
365
+ for raw in stdin:
366
+ if not raw.strip():
367
+ continue
368
+ reply = handle_line(raw, store, clock)
369
+ if reply is not None:
370
+ stdout.write(reply + b"\n")
371
+ stdout.flush()
@@ -0,0 +1,183 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The operations: freeze, record, deviation, verify, issue, log/head/show/summary, init and repair."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ from collections.abc import Iterator, Mapping
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .canonical import sha256_hex
13
+ from .clock import Clock, now_utc
14
+ from .errors import InputError, VerificationFailed, io_guard
15
+ from .issue import build_card, card_hash, write_card_files
16
+ from .ledger import CARD_FORMAT, Entry, make_entry, parse_head_ref, serialize
17
+ from .rules import Verdict, Verifier, apply_expected_head, scan
18
+ from .store import Store
19
+ from .views import select, show as _show, summarize
20
+
21
+ StoreLike = Store | str | os.PathLike[str]
22
+
23
+
24
+ def _as_store(store: StoreLike) -> Store:
25
+ return store if isinstance(store, Store) else Store(store)
26
+
27
+
28
+ @contextmanager
29
+ def _session(store: StoreLike, *, write: bool) -> Iterator[Store]:
30
+ real = _as_store(store)
31
+ with io_guard(), real.locked(write=write):
32
+ yield real
33
+
34
+
35
+ def _load(store: Store, *, missing_ok: bool) -> Verifier:
36
+ verdict, verifier = scan(store.read(missing_ok=missing_ok), card_hash)
37
+ if not verdict.ok:
38
+ raise VerificationFailed(verdict.violations)
39
+ return verifier
40
+
41
+
42
+ def _stage(verifier: Verifier, type: str, body: Mapping[str, Any], clock: Clock | None) -> tuple[Entry, bytes]:
43
+ """Build the next entry and check it against every rule before anything is written."""
44
+ entry = make_entry(seq=verifier.index, prev=verifier.tip_hash, ts=now_utc(clock), type=type, body=body)
45
+ line = serialize(entry)
46
+ found = verifier.feed(line[:-1])
47
+ if found:
48
+ raise InputError(found[0].code, "; ".join(v.message for v in found), found)
49
+ return entry, line
50
+
51
+
52
+ def _append(store: Store, type: str, body: Mapping[str, Any], clock: Clock | None) -> Entry:
53
+ entry, line = _stage(_load(store, missing_ok=True), type, body, clock)
54
+ store.append_line(line)
55
+ return entry
56
+
57
+
58
+ def freeze(store: StoreLike, protocol: Any, *, supersedes: str | None = None, clock: Clock | None = None) -> Entry:
59
+ """Freeze a protocol (an object with ``protocol_id`` and ``version``)."""
60
+ if not isinstance(protocol, dict):
61
+ raise InputError("BAD_ENTRY", "protocol must be an object")
62
+ body = {
63
+ "protocol_id": protocol.get("protocol_id", ""),
64
+ "protocol": protocol,
65
+ "protocol_sha256": sha256_hex(protocol),
66
+ "supersedes": supersedes,
67
+ "version": protocol.get("version", ""),
68
+ }
69
+ with _session(store, write=True) as real:
70
+ return _append(real, "freeze", body, clock)
71
+
72
+
73
+ def record(store: StoreLike, body: Any, *, clock: Clock | None = None) -> Entry:
74
+ return _typed(store, "record", body, clock)
75
+
76
+
77
+ def deviation(store: StoreLike, body: Any, *, clock: Clock | None = None) -> Entry:
78
+ return _typed(store, "deviation", body, clock)
79
+
80
+
81
+ def _typed(store: StoreLike, type: str, body: Any, clock: Clock | None) -> Entry:
82
+ if not isinstance(body, dict):
83
+ raise InputError("BAD_ENTRY", f"{type} body must be an object")
84
+ with _session(store, write=True) as real:
85
+ return _append(real, type, body, clock)
86
+
87
+
88
+ def verify(store: StoreLike, expect_head: str | None = None) -> Verdict:
89
+ """Verify the ledger; with ``expect_head="SEQ:HASH"`` also require that entry (HEAD_MISMATCH otherwise)."""
90
+ wanted = None if expect_head is None else parse_head_ref(expect_head)
91
+ with _session(store, write=False) as real:
92
+ verdict, verifier = scan(real.read(missing_ok=False), card_hash)
93
+ return verdict if wanted is None else apply_expected_head(verdict, verifier, *wanted)
94
+
95
+
96
+ def entries(store: StoreLike) -> list[Entry]:
97
+ with _session(store, write=False) as real:
98
+ verifier = _load(real, missing_ok=False)
99
+ return [verifier.entries[i] for i in range(verifier.index)]
100
+
101
+
102
+ def log(
103
+ store: StoreLike,
104
+ *,
105
+ protocol: str | None = None,
106
+ type: str | None = None,
107
+ status: str | None = None,
108
+ tail: int | None = None,
109
+ ) -> list[Entry]:
110
+ """Entries in ledger order, optionally filtered by protocol_id, entry type and record status; ``tail`` keeps the last N."""
111
+ with _session(store, write=False) as real:
112
+ verifier = _load(real, missing_ok=False)
113
+ return select(verifier, protocol=protocol, entry_type=type, status=status, tail=tail)
114
+
115
+
116
+ def show(store: StoreLike, seq: int) -> dict[str, Any]:
117
+ """One entry with its protocol, the entries it points at and the entries that point at it."""
118
+ with _session(store, write=False) as real:
119
+ verifier = _load(real, missing_ok=False)
120
+ return _show(verifier, seq)
121
+
122
+
123
+ def summary(store: StoreLike, protocol: str | None = None) -> dict[str, Any]:
124
+ """Verdict, head, counts by entry type and result status, a per-protocol table and the problems found.
125
+
126
+ Unlike the other reads this does not raise when the ledger fails verification: ``ok`` is false and ``problems`` lists why.
127
+ """
128
+ with _session(store, write=False) as real:
129
+ verdict, verifier = scan(real.read(missing_ok=False), card_hash)
130
+ return summarize(verdict, verifier, protocol)
131
+
132
+
133
+ def init(store: StoreLike) -> dict[str, Any]:
134
+ """Create the store with an empty ledger; harmless if it exists."""
135
+ with _session(store, write=True) as real:
136
+ created = not real.ledger_path.exists()
137
+ real.append_line(b"")
138
+ return {"created": created, "path": str(real.path)}
139
+
140
+
141
+ def head(store: StoreLike) -> dict[str, Any]:
142
+ """The last entry hash and seq, to be published or anchored elsewhere."""
143
+ with _session(store, write=False) as real:
144
+ verifier = _load(real, missing_ok=False)
145
+ empty = verifier.index == 0
146
+ return {
147
+ "count": verifier.index,
148
+ "hash": None if empty else verifier.tip_hash,
149
+ "seq": None if empty else verifier.index - 1,
150
+ }
151
+
152
+
153
+ def issue(
154
+ store: StoreLike, seq: int, *, out: str | os.PathLike[str] | None = None, clock: Clock | None = None
155
+ ) -> dict[str, Any]:
156
+ """Render the card of record ``seq`` to JSON and SVG and record an ``issue`` entry."""
157
+ if type(seq) is not int:
158
+ raise InputError("BAD_ENTRY", "seq must be an integer")
159
+ with _session(store, write=True) as real:
160
+ verifier = _load(real, missing_ok=False)
161
+ target = verifier.entries.get(seq)
162
+ if target is None or target["type"] != "record":
163
+ raise InputError("DANGLING_REF", f"seq {seq} is not a record")
164
+ card = build_card(verifier, seq)
165
+ body = {"card_sha256": sha256_hex(card), "format": CARD_FORMAT, "record_seq": seq}
166
+ entry, line = _stage(verifier, "issue", body, clock)
167
+ json_path, svg_path = write_card_files(card, Path(out) if out is not None else real.cards_dir)
168
+ real.append_line(line)
169
+ return {"card": card, "entry": entry, "json_path": str(json_path), "svg_path": str(svg_path)}
170
+
171
+
172
+ def repair_truncate_partial_tail(store: StoreLike) -> int:
173
+ """Remove the unterminated last line. Returns the number of bytes removed."""
174
+ with _session(store, write=True) as real:
175
+ data = real.read(missing_ok=False)
176
+ keep = data.rfind(b"\n") + 1
177
+ if keep == len(data):
178
+ raise InputError("NO_PARTIAL_TAIL", "the ledger has no partial last line")
179
+ verdict, _ = scan(data[:keep], card_hash)
180
+ if not verdict.ok:
181
+ raise VerificationFailed(verdict.violations)
182
+ real.truncate(keep)
183
+ return len(data) - keep