ucde 0.2.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.
ucde/cli.py ADDED
@@ -0,0 +1,363 @@
1
+ """Command-line access to the evidence ledger and optional local inference."""
2
+
3
+ import argparse
4
+ from contextlib import closing, suppress
5
+ from dataclasses import asdict
6
+ import json
7
+ from pathlib import Path
8
+ import sqlite3
9
+ import sys
10
+
11
+ from . import __version__
12
+ from .archive import verify_archive
13
+ from .crate import create_crate
14
+ from .model import ConflictError, Evidence, LedgerHead, ValidationError, bounded_integer, validated_evidence
15
+ from .ollama import DEFAULT_TIMEOUT, DEFAULT_URL, OllamaClient, OllamaError
16
+ from .packet import PACKET_MAX_BYTES, PACKET_STRATEGIES, compare_packets, export_packet, replay_packet, verify_packet
17
+ from .ranking import STRATEGIES
18
+ from .store import MAX_REVISION, MemoryStore
19
+
20
+
21
+ MAX_INPUT_BYTES = 1024 * 1024
22
+
23
+
24
+ def _add_search_arguments(parser: argparse.ArgumentParser, *, portable: bool) -> None:
25
+ parser.add_argument("query", help="search text, or an empty string to browse")
26
+ parser.add_argument("--context", action="append", default=[], metavar="KEY=VALUE")
27
+ for selector in ("subject", "variable", "method", "scale"):
28
+ parser.add_argument(f"--{selector}")
29
+ for cutoff, description in (
30
+ ("known-at", "inclusive upper bound on recording time"),
31
+ ("observed-after", "inclusive lower bound on observation time"),
32
+ ("observed-before", "inclusive upper bound on observation time"),
33
+ ("target-at", "observation time to rank towards"),
34
+ ):
35
+ parser.add_argument(f"--{cutoff}", metavar="ISO_8601", help=description,
36
+ required=portable and cutoff == "known-at")
37
+ strategies = PACKET_STRATEGIES if portable else STRATEGIES
38
+ parser.add_argument("--strategy", choices=sorted(strategies), default="adaptive",
39
+ help="ranking strategy (nearest requires --target-at)")
40
+ parser.add_argument("--limit", type=int, default=10)
41
+ parser.add_argument("--candidate-limit", type=int, default=200)
42
+
43
+
44
+ def _parser() -> argparse.ArgumentParser:
45
+ parser = argparse.ArgumentParser(prog="ucde", description="Local experimental evidence memory", allow_abbrev=False)
46
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
47
+ parser.add_argument("--db", type=Path, help="evidence database for ledger commands")
48
+ commands = parser.add_subparsers(dest="command", required=True)
49
+ commands.add_parser("init", help="initialize an evidence database")
50
+ verify = commands.add_parser("verify", help="audit the file and ledger invariants; exit 1 on any problem")
51
+ verify.add_argument("--max-problems", type=int, metavar="N", help="maximum reported ledger problems (default: 100)")
52
+ verify.add_argument("--head-file", type=Path, metavar="TRUSTED_JSON", help="independently stored ledger chain head")
53
+ verify.add_argument("file", nargs="?", type=Path, help="packet file, equivalent to verify-packet")
54
+ verify.add_argument("--expected-sha256", help="independently obtained packet digest")
55
+
56
+ enable_chain = commands.add_parser("enable-chain", help="enable schema 3 commitments on a new copy of the ledger")
57
+ enable_chain.add_argument("--output", type=Path, metavar="NEW_DB", required=True, help="new database file")
58
+ commands.add_parser("chain-head", help="show the current schema 3 ledger head")
59
+
60
+ checkpoint = commands.add_parser("checkpoint", help="fingerprint the retained ledger history")
61
+ checkpoint.add_argument("--known-at", metavar="ISO_8601", help="inclusive recording cutoff")
62
+ checkpoint.add_argument("--expected-sha256", help="independently stored checkpoint digest, requires --known-at")
63
+
64
+ archive = commands.add_parser("archive", help="write retained ledger history to a new archive file")
65
+ archive.add_argument("--output", type=Path, metavar="NEW_PATH", required=True, help="new archive file to write")
66
+ archive.add_argument("--known-at", metavar="ISO_8601", help="inclusive recording cutoff")
67
+
68
+ verify_archive_command = commands.add_parser("verify-archive", help="verify a history archive offline")
69
+ verify_archive_command.add_argument("file", type=Path, help="UTF-8 history archive")
70
+ verify_archive_command.add_argument("--expected-sha256", required=True, help="independently stored checkpoint digest")
71
+
72
+ crate = commands.add_parser("crate", help="package a verified archive as an RO-Crate")
73
+ crate.add_argument("archive", type=Path, help="UTF-8 history archive")
74
+ crate.add_argument("--expected-sha256", required=True, help="independently stored checkpoint digest")
75
+ crate.add_argument("--output", type=Path, metavar="NEW_DIR", required=True, help="new crate directory")
76
+ crate.add_argument("--name", required=True, help="dataset name")
77
+ crate.add_argument("--description", required=True, help="dataset description")
78
+ crate.add_argument("--date-published", metavar="YYYY-MM-DD", required=True, help="publication date to record")
79
+ crate.add_argument("--license", metavar="URL_OR_TERMS", required=True, help="license supplied for this crate")
80
+
81
+ put = commands.add_parser("put", help="write evidence or append a correction")
82
+ put.add_argument("file", help="UTF-8 evidence JSON file, or - for standard input")
83
+ put.add_argument("--expected-revision", type=int, default=0)
84
+
85
+ search = commands.add_parser("search", help="retrieve eligible evidence")
86
+ _add_search_arguments(search, portable=False)
87
+ search.add_argument("--vector-scan-limit", type=int, default=5000)
88
+ search.add_argument("--embedding", type=Path, help="JSON file containing an explicit query vector")
89
+ search.add_argument("--embedding-space", help="identifier of the supplied vector's embedding space")
90
+
91
+ export = commands.add_parser("export", help="export a historical evidence packet")
92
+ _add_search_arguments(export, portable=True)
93
+ export.add_argument("--output", type=Path, metavar="NEW_PATH", help="write UTF-8 JSON to a new file")
94
+
95
+ verify_packet_command = commands.add_parser("verify-packet", help="verify an evidence packet offline")
96
+ verify_packet_command.add_argument("file", type=Path, help="UTF-8 packet JSON file")
97
+ verify_packet_command.add_argument("--expected-sha256", help="independently obtained packet digest")
98
+
99
+ compare = commands.add_parser("compare", help="compare two evidence packets offline")
100
+ compare.add_argument("before", type=Path, help="UTF-8 JSON file for the baseline packet")
101
+ compare.add_argument("after", type=Path, help="UTF-8 JSON file for the comparison packet")
102
+ compare.add_argument("--before-sha256", help="independently obtained baseline packet digest")
103
+ compare.add_argument("--after-sha256", help="independently obtained comparison packet digest")
104
+
105
+ replay = commands.add_parser("replay", help="rerun an evidence packet against a read-only ledger")
106
+ replay.add_argument("file", type=Path, help="UTF-8 packet JSON file")
107
+ replay.add_argument("--expected-sha256", help="independently obtained packet digest")
108
+
109
+ commands.add_parser("history", help="show all revisions for an evidence ID").add_argument("id")
110
+ retract = commands.add_parser("retract", help="append a retraction")
111
+ restore = commands.add_parser("restore", help="restore an earlier revision in a new revision")
112
+ restore.add_argument("id")
113
+ restore.add_argument("revision", type=int)
114
+ retract.add_argument("id")
115
+ for mutation in (retract, restore):
116
+ mutation.add_argument("--expected-revision", type=int, required=True)
117
+ mutation.add_argument("--source", required=True)
118
+ mutation.add_argument("--locator", required=True)
119
+
120
+ purge = commands.add_parser("purge", help="remove all revisions for an evidence ID", allow_abbrev=False)
121
+ purge.add_argument("id")
122
+ purge.add_argument("--expected-revision", type=int, required=True)
123
+ purge.add_argument("--yes", action="store_true", required=True, help="confirm permanent ledger deletion")
124
+
125
+ models = commands.add_parser("models", help="list models reported by local Ollama")
126
+ generate = commands.add_parser("generate", help="send explicit text to local Ollama")
127
+ generate.add_argument("--model", required=True)
128
+ prompt = generate.add_mutually_exclusive_group(required=True)
129
+ prompt.add_argument("--prompt")
130
+ prompt.add_argument("--stdin", action="store_true", help="read a UTF-8 prompt from standard input")
131
+ for inference in (models, generate):
132
+ inference.add_argument("--url", default=DEFAULT_URL, help="HTTP origin on a numeric loopback address")
133
+ inference.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, metavar="SECONDS")
134
+ return parser
135
+
136
+
137
+ def _read_input(path: str | Path) -> str:
138
+ if path == "-":
139
+ raw = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1)
140
+ else:
141
+ with Path(path).open("rb") as source:
142
+ raw = source.read(MAX_INPUT_BYTES + 1)
143
+ if len(raw) > MAX_INPUT_BYTES:
144
+ raise ValidationError("input exceeds 1 MiB")
145
+ return raw.decode("utf-8-sig")
146
+
147
+
148
+ def _unique_object(pairs: list[tuple[str, object]]) -> dict:
149
+ result = {}
150
+ for key, value in pairs:
151
+ if key in result:
152
+ raise ValidationError("JSON contains a duplicate object key")
153
+ result[key] = value
154
+ return result
155
+
156
+
157
+ def _read_json(path: str | Path) -> object:
158
+ def invalid_constant(value: str) -> None:
159
+ raise ValidationError(f"invalid JSON constant {value}")
160
+
161
+ return json.loads(_read_input(path), object_pairs_hook=_unique_object, parse_constant=invalid_constant)
162
+
163
+
164
+ def _read_head(path: Path) -> LedgerHead:
165
+ values = _read_json(path)
166
+ if not isinstance(values, dict) or values.keys() != {"format", "ledger_id", "sequence", "sha256"}:
167
+ raise ValidationError("head file must describe a ledger head with format, ledger_id, sequence and sha256")
168
+ return LedgerHead(**values)
169
+
170
+
171
+ def _enable_chain(store: MemoryStore, output: Path) -> LedgerHead:
172
+ target = output.absolute()
173
+ companions = tuple(target.with_name(target.name + suffix) for suffix in ("-journal", "-wal", "-shm"))
174
+ for path in companions:
175
+ if path.exists() or path.is_symlink():
176
+ raise FileExistsError(f"output has an existing SQLite companion file: {path}")
177
+ reserved = target.open("xb")
178
+ try:
179
+ reserved.close()
180
+ with (
181
+ closing(store._connect()) as source,
182
+ closing(sqlite3.connect(target.as_uri() + "?mode=rw", uri=True)) as copy,
183
+ ):
184
+ source.backup(copy)
185
+ return MemoryStore(target).enable_chain()
186
+ except BaseException:
187
+ for path in (*companions, target):
188
+ with suppress(OSError):
189
+ path.unlink()
190
+ raise
191
+
192
+
193
+ def _search_options(args: argparse.Namespace) -> dict:
194
+ context = {}
195
+ for item in args.context:
196
+ key, separator, value = item.partition("=")
197
+ if not separator or not key or not value or key in context:
198
+ raise ValidationError("--context requires a distinct KEY=VALUE for each entry")
199
+ context[key] = value
200
+ return {
201
+ "context": context, "subject": args.subject, "variable": args.variable, "method": args.method,
202
+ "scale": args.scale, "known_at": args.known_at, "observed_after": args.observed_after,
203
+ "observed_before": args.observed_before, "target_at": args.target_at,
204
+ "limit": args.limit, "candidate_limit": args.candidate_limit, "strategy": args.strategy,
205
+ }
206
+
207
+
208
+ def _search(store: MemoryStore, args: argparse.Namespace) -> dict:
209
+ options = _search_options(args)
210
+ embedding = None
211
+ if args.embedding is not None:
212
+ vector = _read_json(args.embedding)
213
+ if not isinstance(vector, list):
214
+ raise ValidationError("--embedding must contain a JSON array")
215
+ embedding = vector
216
+ return asdict(store.search(
217
+ args.query, **options, vector_scan_limit=args.vector_scan_limit,
218
+ embedding=embedding, embedding_space=args.embedding_space,
219
+ ))
220
+
221
+
222
+ def _export(store: MemoryStore, args: argparse.Namespace) -> dict | None:
223
+ packet = export_packet(store, args.query, **_search_options(args))
224
+ encoded = (json.dumps(packet, ensure_ascii=False, allow_nan=False, indent=2) + "\n").encode("utf-8")
225
+ if len(encoded) > PACKET_MAX_BYTES:
226
+ raise ValidationError("export exceeds the packet verification size limit")
227
+ if args.output is None:
228
+ sys.stdout.buffer.write(encoded)
229
+ return None
230
+ output = args.output.open("xb")
231
+ try:
232
+ with output as destination:
233
+ destination.write(encoded)
234
+ except (OSError, KeyboardInterrupt):
235
+ with suppress(OSError):
236
+ args.output.unlink()
237
+ raise
238
+ return {"path": str(args.output), "sha256": packet["sha256"]}
239
+
240
+
241
+ def _read_packet(path: Path) -> bytes:
242
+ with path.open("rb") as source:
243
+ return source.read(PACKET_MAX_BYTES + 1)
244
+
245
+
246
+ def _verify(args: argparse.Namespace) -> dict:
247
+ packet = verify_packet(_read_packet(args.file), expected_sha256=args.expected_sha256)
248
+ return {"status": "verified", "sha256": packet["sha256"]}
249
+
250
+
251
+ def _compare(args: argparse.Namespace) -> dict:
252
+ return compare_packets(
253
+ _read_packet(args.before), _read_packet(args.after),
254
+ before_sha256=args.before_sha256, after_sha256=args.after_sha256,
255
+ )
256
+
257
+
258
+ def _ledger(args: argparse.Namespace) -> dict | list | None:
259
+ if args.command == "put":
260
+ values = _read_json(args.file)
261
+ if not isinstance(values, dict):
262
+ raise ValidationError("evidence input must be a JSON object")
263
+ try:
264
+ evidence = validated_evidence(Evidence(**values))
265
+ except TypeError as error:
266
+ raise ValidationError(f"invalid evidence fields: {error}") from error
267
+ bounded_integer(args.expected_revision, "expected_revision", 0, MAX_REVISION)
268
+ if args.expected_revision and not args.db.is_file():
269
+ raise ConflictError(f"expected revision {args.expected_revision}, found 0")
270
+ elif args.command in {"retract", "restore", "purge"} and not args.db.is_file():
271
+ raise FileNotFoundError("evidence store does not exist")
272
+
273
+ read_only = args.command in {
274
+ "search", "history", "export", "verify", "replay", "checkpoint", "archive", "enable-chain", "chain-head",
275
+ }
276
+ store = MemoryStore(args.db, read_only=read_only)
277
+ match args.command:
278
+ case "init":
279
+ return {"database": str(store.path)}
280
+ case "verify":
281
+ limit = args.max_problems if args.max_problems is not None else 100
282
+ head = _read_head(args.head_file) if args.head_file is not None else None
283
+ return asdict(store.verify(max_problems=limit, expected_head=head))
284
+ case "enable-chain":
285
+ return asdict(_enable_chain(store, args.output))
286
+ case "chain-head":
287
+ return asdict(store.chain_head())
288
+ case "checkpoint":
289
+ return asdict(store.checkpoint(known_at=args.known_at, expected_sha256=args.expected_sha256))
290
+ case "archive":
291
+ return asdict(store.export_archive(args.output, known_at=args.known_at))
292
+ case "put":
293
+ return asdict(store.put(evidence, expected_revision=args.expected_revision))
294
+ case "search":
295
+ return _search(store, args)
296
+ case "export":
297
+ return _export(store, args)
298
+ case "replay":
299
+ return replay_packet(store, _read_packet(args.file), expected_sha256=args.expected_sha256)
300
+ case "history":
301
+ return [asdict(revision) for revision in store.history(args.id)]
302
+ case "retract":
303
+ return asdict(store.retract(args.id, expected_revision=args.expected_revision, source=args.source,
304
+ locator=args.locator))
305
+ case "restore":
306
+ return asdict(store.restore(args.id, args.revision, expected_revision=args.expected_revision,
307
+ source=args.source, locator=args.locator))
308
+ case "purge":
309
+ return {"purged": store.purge(args.id, expected_revision=args.expected_revision)}
310
+ case _:
311
+ raise AssertionError("unhandled ledger command")
312
+
313
+
314
+ def main(argv: list[str] | None = None) -> int:
315
+ parser = _parser()
316
+ args = parser.parse_args(argv)
317
+ inference = args.command in {"models", "generate"}
318
+ packet_verification = args.command == "verify-packet" or (args.command == "verify" and args.file is not None)
319
+ if args.command == "verify":
320
+ if packet_verification and args.head_file is not None:
321
+ parser.error("--head-file applies to the ledger audit")
322
+ if packet_verification and (args.db is not None or args.max_problems is not None):
323
+ parser.error("--db and --max-problems apply to the ledger audit")
324
+ if not packet_verification and args.expected_sha256 is not None:
325
+ parser.error("--expected-sha256 requires a packet file")
326
+ if not (inference or packet_verification or args.command in {"compare", "verify-archive", "crate"}) and args.db is None:
327
+ parser.error("ledger commands require --db PATH before the subcommand")
328
+
329
+ payload: dict | list | None
330
+ try:
331
+ if inference:
332
+ client = OllamaClient(args.url, timeout=args.timeout)
333
+ if args.command == "models":
334
+ payload = {"models": client.list_models()}
335
+ else:
336
+ prompt = _read_input("-") if args.stdin else args.prompt
337
+ payload = client.generate(args.model, prompt)
338
+ elif packet_verification:
339
+ payload = _verify(args)
340
+ elif args.command == "verify-archive":
341
+ payload = asdict(verify_archive(args.file, expected_sha256=args.expected_sha256))
342
+ elif args.command == "crate":
343
+ payload = asdict(create_crate(
344
+ args.archive, args.output, expected_sha256=args.expected_sha256, name=args.name,
345
+ description=args.description, date_published=args.date_published, license=args.license,
346
+ ))
347
+ elif args.command == "compare":
348
+ payload = _compare(args)
349
+ else:
350
+ payload = _ledger(args)
351
+ if payload is not None:
352
+ print(json.dumps(payload, allow_nan=False))
353
+ if args.command == "verify" and not packet_verification and isinstance(payload, dict) and not payload["ok"]:
354
+ return 1
355
+ if args.command in {"replay", "checkpoint", "verify-archive"} and isinstance(payload, dict) and payload["matched"] is False:
356
+ return 1
357
+ except ConflictError as error:
358
+ print(f"ucde: revision conflict: {error}", file=sys.stderr)
359
+ return 1
360
+ except (ValueError, OSError, RecursionError, sqlite3.Error, OllamaError) as error:
361
+ print(f"ucde: {error}", file=sys.stderr)
362
+ return 1
363
+ return 0
ucde/crate.py ADDED
@@ -0,0 +1,98 @@
1
+ """Package a verified historical archive as an attached RO-Crate."""
2
+
3
+ from contextlib import suppress
4
+ from dataclasses import asdict
5
+ from datetime import date
6
+ import json
7
+ from pathlib import Path
8
+ from shutil import copyfileobj
9
+ from urllib.parse import urlsplit
10
+
11
+ from .archive import verify_archive
12
+ from .model import LedgerCheckpoint, ValidationError, checked_sha256, checked_text
13
+ from .provenance import write_provenance
14
+
15
+
16
+ _PROFILE = "https://w3id.org/ro/crate/1.2"
17
+ _DESCRIPTOR = "ro-crate-metadata.json"
18
+ _HISTORY = "history.jsonl"
19
+ _CHECKPOINT = "checkpoint.json"
20
+ _PROVENANCE = "provenance.jsonld"
21
+ _DATA_FILES = (
22
+ (_HISTORY, "UCDE history archive", "application/x-ndjson"),
23
+ (_CHECKPOINT, "Ledger checkpoint receipt", "application/json"),
24
+ (_PROVENANCE, "W3C PROV-O provenance graph", "application/ld+json"),
25
+ )
26
+
27
+
28
+ def _publication_date(value: str) -> str:
29
+ try:
30
+ if date.fromisoformat(value).isoformat() == value:
31
+ return value
32
+ except (TypeError, ValueError):
33
+ pass
34
+ raise ValidationError("date_published must be a calendar date in YYYY-MM-DD format")
35
+
36
+
37
+ def _metadata(name: str, description: str, date_published: str, license: str) -> dict[str, object]:
38
+ root: dict[str, object] = {
39
+ "@id": "./", "@type": "Dataset", "name": name, "description": description,
40
+ "datePublished": date_published, "license": license,
41
+ "hasPart": [{"@id": path} for path, _, _ in _DATA_FILES],
42
+ }
43
+ graph: list[dict[str, object]] = [
44
+ {"@id": _DESCRIPTOR, "@type": "CreativeWork", "about": {"@id": "./"}, "conformsTo": {"@id": _PROFILE}},
45
+ root,
46
+ ]
47
+ for path, label, media_type in _DATA_FILES:
48
+ graph.append({"@id": path, "@type": "File", "name": label, "encodingFormat": media_type})
49
+ if license.startswith(("https://", "http://")) and not any(character.isspace() for character in license):
50
+ try:
51
+ linked_license = bool(urlsplit(license).hostname)
52
+ except ValueError:
53
+ linked_license = False
54
+ if linked_license:
55
+ root["license"] = {"@id": license}
56
+ graph.append({
57
+ "@id": license, "@type": "CreativeWork", "name": license,
58
+ "description": "Usage terms supplied for this research package.",
59
+ })
60
+ return {"@context": f"{_PROFILE}/context", "@graph": graph}
61
+
62
+
63
+ def _write_json(path: Path, value: dict) -> None:
64
+ with path.open("x", encoding="utf-8", newline="\n") as output:
65
+ json.dump(value, output, ensure_ascii=False, allow_nan=False, indent=2)
66
+ output.write("\n")
67
+
68
+
69
+ def create_crate(
70
+ archive_path: str | Path, destination: str | Path, *, expected_sha256: str,
71
+ name: str, description: str, date_published: str, license: str,
72
+ ) -> LedgerCheckpoint:
73
+ """Copy an anchored archive into a new RO-Crate with a detached provenance graph."""
74
+ expected = checked_sha256(expected_sha256, "expected_sha256")
75
+ metadata = _metadata(
76
+ checked_text(name, "name"), checked_text(description, "description", 16384),
77
+ _publication_date(date_published), checked_text(license, "license", 4096),
78
+ )
79
+ output = Path(destination)
80
+ output.mkdir()
81
+ try:
82
+ history = output / _HISTORY
83
+ with Path(archive_path).open("rb") as source, history.open("xb") as package_archive:
84
+ copyfileobj(source, package_archive)
85
+ receipt = verify_archive(history, expected_sha256=expected)
86
+ if receipt.matched is not True:
87
+ raise ValidationError("archive digest does not match the expected checkpoint")
88
+ write_provenance(history, output / _PROVENANCE)
89
+ _write_json(output / _CHECKPOINT, asdict(receipt))
90
+ _write_json(output / _DESCRIPTOR, metadata)
91
+ except BaseException:
92
+ for filename in (_HISTORY, _PROVENANCE, _CHECKPOINT, _DESCRIPTOR):
93
+ with suppress(OSError):
94
+ (output / filename).unlink()
95
+ with suppress(OSError):
96
+ output.rmdir()
97
+ raise
98
+ return receipt