courant-dev 0.5.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 (152) hide show
  1. courant/__init__.py +26 -0
  2. courant/case/__init__.py +0 -0
  3. courant/case/_foam_reader.py +269 -0
  4. courant/case/config.py +134 -0
  5. courant/case/mesh.py +135 -0
  6. courant/case/reads.py +90 -0
  7. courant/case/schemes.py +99 -0
  8. courant/case/solvers.py +170 -0
  9. courant/cli/__init__.py +0 -0
  10. courant/cli/commands/__init__.py +6 -0
  11. courant/cli/commands/audit.py +40 -0
  12. courant/cli/commands/convergence.py +68 -0
  13. courant/cli/commands/ctest.py +76 -0
  14. courant/cli/commands/doctor.py +162 -0
  15. courant/cli/commands/gate.py +88 -0
  16. courant/cli/commands/live.py +73 -0
  17. courant/cli/commands/mcp.py +57 -0
  18. courant/cli/commands/preflight.py +36 -0
  19. courant/cli/commands/spec.py +231 -0
  20. courant/cli/commands/tour.py +122 -0
  21. courant/cli/commands/update.py +213 -0
  22. courant/cli/commands/verify.py +222 -0
  23. courant/cli/config.py +244 -0
  24. courant/cli/guard.py +69 -0
  25. courant/cli/main.py +130 -0
  26. courant/cli/tail.py +351 -0
  27. courant/config.py +155 -0
  28. courant/converge/__init__.py +57 -0
  29. courant/converge/assess.py +823 -0
  30. courant/converge/exact.py +112 -0
  31. courant/converge/render.py +182 -0
  32. courant/converge/scale.py +87 -0
  33. courant/converge/sentences.py +82 -0
  34. courant/converge/series.py +413 -0
  35. courant/converge/steady.py +261 -0
  36. courant/converge/tables.py +1019 -0
  37. courant/converge/transient.py +314 -0
  38. courant/ctest/__init__.py +6 -0
  39. courant/ctest/build.py +82 -0
  40. courant/ctest/data/judge-v0.labels.jsonl +31 -0
  41. courant/ctest/data/judge-v0.tasks.jsonl.gz +0 -0
  42. courant/ctest/judges/__init__.py +27 -0
  43. courant/ctest/judges/constant.py +18 -0
  44. courant/ctest/judges/courant.py +23 -0
  45. courant/ctest/judges/llm.py +166 -0
  46. courant/ctest/run.py +74 -0
  47. courant/ctest/schema.py +46 -0
  48. courant/ctest/score.py +91 -0
  49. courant/ctest/splits.py +20 -0
  50. courant/data/__init__.py +46 -0
  51. courant/data/certification.json +1 -0
  52. courant/data/certified_codes.json +18 -0
  53. courant/data/demo/icoFoam_cavity__cfl_blowup.case.json +68 -0
  54. courant/data/demo/icoFoam_cavity__cfl_blowup.log.gz +0 -0
  55. courant/data/demo/icoFoam_cavity__healthy.case.json +68 -0
  56. courant/data/demo/icoFoam_cavity__healthy.log.gz +0 -0
  57. courant/data/demo/icoFoam_cavity__transport_units.case.json +68 -0
  58. courant/data/demo/icoFoam_cavity__transport_units.log.gz +0 -0
  59. courant/data/demo/pitzDaily_fixed_budget.tar.gz +0 -0
  60. courant/data/schemas/audit.1.json +129 -0
  61. courant/data/schemas/cache.1.json +77 -0
  62. courant/data/schemas/convergence.1.json +112 -0
  63. courant/data/schemas/error-rates.1.json +53 -0
  64. courant/data/schemas/preflight.1.json +250 -0
  65. courant/data/schemas/record.1.json +155 -0
  66. courant/data/schemas/release-signature.1.json +39 -0
  67. courant/data/schemas/spec.1.json +258 -0
  68. courant/data/schemas/support.1.json +80 -0
  69. courant/data/schemas/verdict.1.json +716 -0
  70. courant/data/schemas/verdict.2.json +752 -0
  71. courant/diagnosis/__init__.py +0 -0
  72. courant/diagnosis/bundle.py +168 -0
  73. courant/diagnosis/checkers.py +919 -0
  74. courant/diagnosis/deterministic.py +110 -0
  75. courant/diagnosis/findings.py +107 -0
  76. courant/diagnosis/kb.py +188 -0
  77. courant/diagnosis/kb_data.py +253 -0
  78. courant/diagnosis/llm.py +299 -0
  79. courant/diagnosis/redact.py +425 -0
  80. courant/diagnosis/schema.py +83 -0
  81. courant/events/__init__.py +35 -0
  82. courant/events/core.py +194 -0
  83. courant/events/diverged.py +55 -0
  84. courant/gate/__init__.py +1 -0
  85. courant/gate/config.py +150 -0
  86. courant/gate/run.py +295 -0
  87. courant/live/__init__.py +16 -0
  88. courant/live/engine.py +155 -0
  89. courant/live/watch.py +164 -0
  90. courant/llm/__init__.py +59 -0
  91. courant/llm/allowlist.py +60 -0
  92. courant/llm/anthropic.py +137 -0
  93. courant/llm/budget.py +491 -0
  94. courant/llm/door.py +1071 -0
  95. courant/llm/errors.py +105 -0
  96. courant/llm/openrouter.py +118 -0
  97. courant/llm/policy.py +268 -0
  98. courant/llm/transport.py +48 -0
  99. courant/mcp/__init__.py +7 -0
  100. courant/mcp/server.py +113 -0
  101. courant/mcp/tools.py +177 -0
  102. courant/record/__init__.py +22 -0
  103. courant/record/filter.py +99 -0
  104. courant/record/record.py +149 -0
  105. courant/release.py +205 -0
  106. courant/signing.py +99 -0
  107. courant/spec/__init__.py +31 -0
  108. courant/spec/check.py +353 -0
  109. courant/spec/deck.py +455 -0
  110. courant/spec/extract.py +181 -0
  111. courant/spec/impossible.py +197 -0
  112. courant/spec/model.py +194 -0
  113. courant/taxonomy.py +219 -0
  114. courant/verification/__init__.py +30 -0
  115. courant/verification/_fluid_reader.py +228 -0
  116. courant/verification/bounding.py +84 -0
  117. courant/verification/checks.py +369 -0
  118. courant/verification/convergence.py +257 -0
  119. courant/verification/fields.py +38 -0
  120. courant/verification/grade.py +101 -0
  121. courant/verification/suite.py +30 -0
  122. courant/verify/__init__.py +37 -0
  123. courant/verify/about.py +100 -0
  124. courant/verify/audit.py +209 -0
  125. courant/verify/batch.py +141 -0
  126. courant/verify/cache.py +329 -0
  127. courant/verify/checks.py +37 -0
  128. courant/verify/html.py +330 -0
  129. courant/verify/ingest.py +115 -0
  130. courant/verify/junit.py +48 -0
  131. courant/verify/outcome.py +74 -0
  132. courant/verify/pack.py +106 -0
  133. courant/verify/pipeline.py +396 -0
  134. courant/verify/policy.py +167 -0
  135. courant/verify/preflight.py +166 -0
  136. courant/verify/render.py +174 -0
  137. courant/verify/schema.py +398 -0
  138. courant/verify/sentences.py +137 -0
  139. courant/verify/support.py +142 -0
  140. courant/verify/verdict2.py +235 -0
  141. courant/watcher/__init__.py +13 -0
  142. courant/watcher/anomaly.py +244 -0
  143. courant/watcher/exitcode.py +23 -0
  144. courant/watcher/parser.py +435 -0
  145. courant/watcher/watcher.py +49 -0
  146. courant_dev-0.5.0.dist-info/METADATA +146 -0
  147. courant_dev-0.5.0.dist-info/RECORD +152 -0
  148. courant_dev-0.5.0.dist-info/WHEEL +5 -0
  149. courant_dev-0.5.0.dist-info/entry_points.txt +3 -0
  150. courant_dev-0.5.0.dist-info/licenses/LICENSE +202 -0
  151. courant_dev-0.5.0.dist-info/licenses/NOTICE +4 -0
  152. courant_dev-0.5.0.dist-info/top_level.txt +1 -0
courant/mcp/tools.py ADDED
@@ -0,0 +1,177 @@
1
+ """The MCP tools as plain functions (TRD MCP-2), testable without a transport.
2
+
3
+ Read-only by construction (MCP-4): no tool writes a file, runs a process or
4
+ opens a socket. Paths are confined to the roots the user allows (MCP-3).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from pathlib import Path
12
+
13
+ ROOT = Path(__file__).resolve().parents[2]
14
+
15
+
16
+ class OutsideRoot(PermissionError):
17
+ pass
18
+
19
+
20
+ class Confinement:
21
+ """Only paths inside one of these roots may be read."""
22
+
23
+ def __init__(self, roots: list[str | Path]):
24
+ self.roots = [Path(r).resolve() for r in (roots or [Path.cwd()])]
25
+
26
+ def check(self, path: str | Path) -> Path:
27
+ p = Path(path).expanduser().resolve()
28
+ if not any(p == r or p.is_relative_to(r) for r in self.roots):
29
+ raise OutsideRoot(f"{p} is outside the allowed roots: "
30
+ + ", ".join(str(r) for r in self.roots))
31
+ return p
32
+
33
+
34
+ def _schema_error(schema: int) -> dict | None:
35
+ from courant.verify.verdict2 import SCHEMAS
36
+
37
+ if schema not in SCHEMAS:
38
+ return {"error": f"schema must be 1 or 2, not {schema!r}: 2 is courant.verdict/2 (the "
39
+ "default), 1 is courant.verdict/1, kept for one minor release"}
40
+ return None
41
+
42
+
43
+ def verify_run(path: str, case_json: str | None = None, spec: str | None = None,
44
+ spec_sha256: str | None = None, schema: int = 2, *, confine: Confinement) -> dict:
45
+ """Verify a completed simulation (a case directory or a solver log).
46
+
47
+ Returns the verdict JSON (schema courant.verdict/2 by default, courant.verdict/1 with
48
+ `schema=1`): accept, reject or insufficient, the basis it was judged on, the cited reasons,
49
+ what was not checked, and a suggested next action that is never applied. With `spec` (a
50
+ courant.spec/1 file), every value the task specification names is also checked against the
51
+ case, and a case that set up a different problem is rejected however well it ran.
52
+ """
53
+ from courant.verify import InputError, verify_path
54
+ from courant.verify.verdict2 import in_schema
55
+
56
+ if (bad := _schema_error(schema)) is not None:
57
+ return bad
58
+ target = confine.check(path)
59
+ sidecar = confine.check(case_json) if case_json else None
60
+ spec_path = confine.check(spec) if spec else None
61
+ try:
62
+ verdict = verify_path(target, sidecar, spec=spec_path, spec_locked_sha256=spec_sha256)
63
+ except InputError as exc:
64
+ return {"error": str(exc)}
65
+ return json.loads(in_schema(verdict, schema).to_json())
66
+
67
+
68
+ #: GATE-5 / SB-18: said with every score, because the score is advice and not a certification.
69
+ ADVISORY = ("Advisory: this judges the run as you left it, from your own log. It is not a "
70
+ "certification; a score for the record is taken on a re-solve of your final case.")
71
+
72
+
73
+ #: The fields of SB-11's outcome the advisory tool returns (GATE-5).
74
+ _SCORED = {"outcome", "executed", "executed_source", "reported_success", "silent_error",
75
+ "unverified_success"}
76
+
77
+
78
+ def score_agent_output(case: str, spec: str, spec_sha256: str | None = None,
79
+ reported_success: bool | None = None, schema: int = 2, *,
80
+ confine: Confinement) -> dict:
81
+ """Judge an agent's finished case against the task it was given (GATE-5). Advisory.
82
+
83
+ `case` is the case directory the agent left, its own log included; `spec` is the task
84
+ specification (courant.spec/1) and `spec_sha256` the hash it was locked at; `reported_success`
85
+ is whether the agent is about to tell its user the run worked. Returns the verdict document
86
+ (courant.verdict/2 by default), SB-11's `outcome` (also as `task_class`), and the flags
87
+ `silent_error` (the run executed, you reported success, and the gate rejects it) and
88
+ `unverified_success` (the same, with insufficient). Read-only.
89
+ """
90
+ from courant.verify import InputError, from_path, verify_inputs, with_spec
91
+ from courant.verify.schema import executed_in_log, outcome_of
92
+ from courant.verify.verdict2 import in_schema
93
+
94
+ if (bad := _schema_error(schema)) is not None:
95
+ return bad
96
+ target = confine.check(case)
97
+ spec_path = confine.check(spec)
98
+ try:
99
+ inputs = with_spec(from_path(target), spec_path, spec_sha256)
100
+ verdict = verify_inputs(inputs)
101
+ except InputError as exc:
102
+ return {"error": str(exc)}
103
+ scored = outcome_of(verdict, executed=executed_in_log(inputs.log_text),
104
+ executed_source="agent_log", reported_success=reported_success
105
+ ).model_dump(include=_SCORED)
106
+ return {"advisory": True, "note": ADVISORY,
107
+ "verdict": json.loads(in_schema(verdict, schema).to_json()),
108
+ "task_class": scored["outcome"], **scored}
109
+
110
+
111
+ def check_convergence(path: str, transient_average: bool = False, *, confine: Confinement) -> dict:
112
+ """Where a run's monitored answer stopped changing, and what the rest of the run cost.
113
+
114
+ `path` is a case directory with function-object output under postProcessing/, or a log.
115
+ Read-only. Returns the status (PASS, WARN, FAIL or NOT_ASSESSABLE), the stopping step,
116
+ the change after it, and the iterations, wall clock and core-hours spent after it.
117
+ """
118
+ from courant.converge import Options, convergence_path, summary
119
+
120
+ target = confine.check(path)
121
+ conv = convergence_path(target, None, Options(transient_average=transient_average))
122
+ out = summary(conv)
123
+ out["messages"] = [f.message for f in conv.findings if f.severity in ("WARN", "FAIL") and f.message]
124
+ return out
125
+
126
+
127
+ def explain_code(code: str) -> dict:
128
+ """What a failure-mode code means, and the usual correction (a suggestion only)."""
129
+ from courant.diagnosis.kb_data import build_default_kb
130
+ from courant.taxonomy import TAXONOMY
131
+
132
+ entry = TAXONOMY.get(code)
133
+ if entry is None:
134
+ return {"error": f"unknown code {code!r}", "known": sorted(TAXONOMY)}
135
+ kb = build_default_kb().get(code)
136
+ fixes = [f.description for f in kb.canonical_fixes] if kb else []
137
+ return {"code": code, "name": entry.title, "description": entry.summary,
138
+ "typical_corrections": fixes,
139
+ "certified_on_real_output": code in certified_codes()}
140
+
141
+
142
+ def _parse_certified_codes(text: str) -> set[str]:
143
+ """Tier 1 of docs/COVERAGE.md: named on output a real solver produced."""
144
+ m = re.search(r"## 1\..*?(?=\n## 2\.)", text, re.S)
145
+ return set(re.findall(r"`([A-Z]+\.[A-Z_]+)`", m.group(0))) if m else set()
146
+
147
+
148
+ def certified_codes() -> set[str]:
149
+ """The packaged copy (PKG-5), so an installed server answers outside the repository."""
150
+ from courant.data import certified_codes as packaged
151
+
152
+ return set(packaged())
153
+
154
+
155
+ def list_failure_modes() -> list[dict]:
156
+ """Every failure mode Courant knows, and whether it is certified on real output."""
157
+ from courant.taxonomy import TAXONOMY
158
+
159
+ certified = certified_codes()
160
+ return [{"code": code, "name": entry.title, "certified_on_real_output": code in certified}
161
+ for code, entry in sorted(TAXONOMY.items())]
162
+
163
+
164
+ def verifier_certification() -> dict:
165
+ """The verifier's own measured error rates, from the packaged results only (PKG-5)."""
166
+ from courant.data import certification
167
+
168
+ data = certification()
169
+ if data is None:
170
+ return {"certified": False, "note": "no certification results in this build"}
171
+ card = data["scorecard"]["all"]
172
+ return {"certified": True, "tag": data.get("tag"), "date": data.get("date"),
173
+ "policy": data.get("policy"), "corpus": data.get("corpus"),
174
+ "false_accepts": {k: card["far"][k] for k in ("n", "of", "lo", "hi")},
175
+ "false_alarms": {k: card["frr"][k] for k in ("n", "of", "lo", "hi")},
176
+ "abstentions": {k: card["abstain"][k] for k in ("n", "of")},
177
+ "hypotheses": data.get("hypotheses", {})}
@@ -0,0 +1,22 @@
1
+ """Verified records (TRD REC-1, REC-2; PRD 2.0 P2-REC-1).
2
+
3
+ A record is one run's answer in a form that travels: the specification, the verdict, who produced
4
+ and who requested the run, the Courant version, and the full VER-14 manifest. It re-derives byte
5
+ for byte, as a pack does (`check_record`), and a dataset pipeline admits only the records whose
6
+ verdict is an `accept` judged against a locked specification (`admit`).
7
+
8
+ from courant.record import build_record, check_record, admit
9
+ """
10
+
11
+ from courant.record.filter import Admission, admit, filter_records
12
+ from courant.record.record import (
13
+ SCHEMA,
14
+ RecordError,
15
+ build_record,
16
+ check_record,
17
+ read_record,
18
+ write_record,
19
+ )
20
+
21
+ __all__ = ["SCHEMA", "Admission", "RecordError", "admit", "build_record", "check_record",
22
+ "filter_records", "read_record", "write_record"]
@@ -0,0 +1,99 @@
1
+ """The reference dataset filter (TRD REC-2): the interface a surrogate-training pipeline needs.
2
+
3
+ A record is admitted only when ALL of these hold, and `admit` checks each:
4
+
5
+ - it is a `courant.record/1` whose verdict is `courant.verdict/2`, and its manifest equals its
6
+ verdict's `run.inputs`;
7
+ - its verdict is `accept` on the basis `validity+conformance`;
8
+ - the specification it carries is the one the DATASET OWNER expects: its SHA-256, the hash it
9
+ was locked at and the hash the verdict was judged against are all in `expected_spec_sha256`,
10
+ an argument with no default. A record is evidence about a run against whatever specification it
11
+ carries, and the agent that produced the run can write that specification itself
12
+ (`courant spec init` drafts one that its own run satisfies); only a hash the owner fixed
13
+ before the run says the run was asked the owner's question. A record whose specification is
14
+ any other is refused, however well it re-derives;
15
+ - every file in its manifest is on disk under the root and hashes to what the manifest says;
16
+ - by default, the record re-derives byte for byte (`check_record`, with the specification the
17
+ record carries, which the previous check has tied to the owner's hash). `rederive=False`
18
+ skips this last step, and the admission then says so; the hashes are then checked but the
19
+ verdict is the record's own claim.
20
+
21
+ What is not enforced: that the owner's specification describes the problem they meant (that is
22
+ their review), and the provenance fields (`producer`, `requester`), which are claims.
23
+
24
+ The filter decides nothing about physics: it reads what the gate decided (ARC-13).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from collections.abc import Iterable
30
+ from dataclasses import dataclass
31
+ from pathlib import Path
32
+
33
+ from courant.record.record import RecordError, check_record, manifest_problem, read_record
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Admission:
38
+ admitted: bool
39
+ reason: str
40
+ path: str = ""
41
+
42
+
43
+ def _expected(value: str | Iterable[str]) -> frozenset[str]:
44
+ values = [value] if isinstance(value, str) else list(value)
45
+ return frozenset(v.strip().lower() for v in values if v and v.strip())
46
+
47
+
48
+ def admit(record_path: str | Path, root: str | Path, *, expected_spec_sha256: str | Iterable[str],
49
+ rederive: bool = True) -> Admission:
50
+ """Whether the record at `record_path` may enter a dataset whose files are under `root` and
51
+ whose owner fixed the specification hash(es) `expected_spec_sha256` before the runs."""
52
+ expected = _expected(expected_spec_sha256)
53
+ name = str(record_path)
54
+ try:
55
+ record = read_record(record_path)
56
+ except RecordError as exc:
57
+ return Admission(False, str(exc), name)
58
+ verdict = record["verdict"]
59
+ if verdict.get("schema") != "courant.verdict/2":
60
+ return Admission(False, f"the verdict is {verdict.get('schema')!r}, not courant.verdict/2",
61
+ name)
62
+ if verdict.get("verdict") != "accept":
63
+ return Admission(False, f"the verdict is {verdict.get('verdict')}, not accept", name)
64
+ if verdict.get("basis") != "validity+conformance":
65
+ return Admission(False, f"the basis is {verdict.get('basis')}, not validity+conformance",
66
+ name)
67
+ if record["manifest"] != verdict.get("run", {}).get("inputs"):
68
+ return Admission(False, "the record's manifest is not its verdict's inputs", name)
69
+ spec = record.get("spec")
70
+ conformance = verdict.get("conformance") or {}
71
+ if (spec is None or not spec.get("locked_sha256")
72
+ or spec["locked_sha256"] != conformance.get("spec_sha256")
73
+ or spec["sha256"] != conformance.get("spec_sha256")):
74
+ return Admission(False, "the specification is not the locked one the verdict was judged on",
75
+ name)
76
+ if {spec["sha256"], spec["locked_sha256"], conformance.get("spec_sha256")} - expected:
77
+ return Admission(False, f"the specification (sha256 {str(spec['sha256'])[:12]}) is not one "
78
+ "the dataset owner expects", name)
79
+ problem = manifest_problem(record, root)
80
+ if problem:
81
+ return Admission(False, problem, name)
82
+ if not rederive:
83
+ return Admission(True, "accept on validity+conformance; manifest hashes match; "
84
+ "not re-derived", name)
85
+ ok, message = check_record(record_path, root)
86
+ return Admission(ok, ("accept on validity+conformance; " + message) if ok else message, name)
87
+
88
+
89
+ def filter_records(records: Iterable[str | Path], root: str | Path, *,
90
+ expected_spec_sha256: str | Iterable[str], rederive: bool = True) -> tuple[list[Path], list[Admission]]:
91
+ """(the admitted record paths, the refusals with their reasons)."""
92
+ admitted, refused = [], []
93
+ for r in records:
94
+ a = admit(r, root, expected_spec_sha256=expected_spec_sha256, rederive=rederive)
95
+ if a.admitted:
96
+ admitted.append(Path(r))
97
+ else:
98
+ refused.append(a)
99
+ return admitted, refused
@@ -0,0 +1,149 @@
1
+ """`courant.record/1`: write one, and re-derive it (TRD REC-1).
2
+
3
+ {"schema": "courant.record/1",
4
+ "tool": {"name", "version"},
5
+ "provenance": {"producer", "requester", "courant_version"},
6
+ "target": {"name", "source", "case_json"}, # where the run was, relative to the root
7
+ "spec": {"text", "sha256", "locked_sha256"} | null, # the file's own bytes, as text
8
+ "manifest": [{"path", "bytes", "sha256"}, ...], # VER-14, equal to verdict.run.inputs
9
+ "verdict": <courant.verdict/2>}
10
+
11
+ The record names no absolute path and nothing machine-specific, so it is the same bytes on any
12
+ machine that has the same inputs and the same Courant (VER-9, INV-6). The specification travels
13
+ inside it as its exact text, so the record re-derives with nothing but the run's files.
14
+
15
+ The verdict inside is decided by `courant.verify`, never here (ARC-13): `build_record` takes a
16
+ verdict, and `check_record` asks `verify_path` for a fresh one.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import tempfile
24
+ from pathlib import Path
25
+
26
+ from courant.verify.schema import canonical_json
27
+ from courant.verify.verdict2 import VerdictV2, as_v2
28
+
29
+ SCHEMA = "courant.record/1"
30
+
31
+
32
+ class RecordError(ValueError):
33
+ """The record cannot be read as a `courant.record/1`."""
34
+
35
+
36
+ def build_record(verdict, *, target_name: str, case_json_name: str | None = None,
37
+ spec_text: str | None = None, spec_locked_sha256: str | None = None,
38
+ producer: str | None = None, requester: str | None = None) -> dict:
39
+ """The record as data. `verdict` is either major; the record holds version 2."""
40
+ v: VerdictV2 = as_v2(verdict)
41
+ spec = None
42
+ if spec_text is not None:
43
+ spec = {"text": spec_text,
44
+ "sha256": hashlib.sha256(spec_text.encode("utf-8")).hexdigest(),
45
+ "locked_sha256": spec_locked_sha256.strip().lower() if spec_locked_sha256 else None}
46
+ return {
47
+ "schema": SCHEMA,
48
+ "tool": {"name": v.tool.name, "version": v.tool.version},
49
+ "provenance": {"producer": producer, "requester": requester,
50
+ "courant_version": v.tool.version},
51
+ "target": {"name": target_name, "source": v.run.source, "case_json": case_json_name},
52
+ "spec": spec,
53
+ "manifest": [f.model_dump(mode="json") for f in v.run.inputs],
54
+ "verdict": json.loads(v.to_json()),
55
+ }
56
+
57
+
58
+ def write_record(verdict, out: str | Path, *, target_name: str, case_json_name: str | None = None,
59
+ spec_path: str | Path | None = None, spec_locked_sha256: str | None = None,
60
+ producer: str | None = None, requester: str | None = None) -> Path:
61
+ """Write `out` (canonical JSON, VER-9)."""
62
+ text = Path(spec_path).read_bytes().decode("utf-8") if spec_path is not None else None
63
+ record = build_record(verdict, target_name=target_name, case_json_name=case_json_name,
64
+ spec_text=text, spec_locked_sha256=spec_locked_sha256,
65
+ producer=producer, requester=requester)
66
+ out = Path(out)
67
+ out.parent.mkdir(parents=True, exist_ok=True)
68
+ out.write_text(canonical_json(record), encoding="utf-8")
69
+ return out
70
+
71
+
72
+ def read_record(path: str | Path) -> dict:
73
+ """The record at `path`, checked to be a `courant.record/1` of the shape REC-1 names."""
74
+ try:
75
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
76
+ except (OSError, ValueError) as exc:
77
+ raise RecordError(f"cannot read {path}: {exc}") from exc
78
+ if not isinstance(data, dict) or data.get("schema") != SCHEMA:
79
+ found = data.get("schema") if isinstance(data, dict) else None
80
+ raise RecordError(f"not a {SCHEMA}: schema {found!r}")
81
+ for key in ("tool", "provenance", "target", "manifest", "verdict"):
82
+ if key not in data:
83
+ raise RecordError(f"{SCHEMA} without {key!r}")
84
+ return data
85
+
86
+
87
+ def manifest_problem(record: dict, root: str | Path) -> str | None:
88
+ """The first manifest entry whose file under `root` is missing or changed, as a sentence."""
89
+ for entry in record["manifest"]:
90
+ p = Path(root) / entry["path"]
91
+ if not p.is_file():
92
+ return f"input missing: {entry['path']}"
93
+ data = p.read_bytes()
94
+ have = hashlib.sha256(data).hexdigest()
95
+ if len(data) != entry["bytes"] or have != entry["sha256"]:
96
+ return f"input changed: {entry['path']} (sha256 {have[:12]} != {entry['sha256'][:12]})"
97
+ return None
98
+
99
+
100
+ def check_record(record_path: str | Path, root: str | Path) -> tuple[bool, str]:
101
+ """Re-derive a record from its inputs under `root`. (identical, message).
102
+
103
+ Every manifest file is re-hashed; then the run is verified again with the specification the
104
+ record carries, the record is rebuilt from that verdict and the record's own provenance, and
105
+ its bytes are compared with the file's. The first difference is named."""
106
+ from courant.verify import InputError, verify_path
107
+
108
+ try:
109
+ record = read_record(record_path)
110
+ except RecordError as exc:
111
+ return False, str(exc)
112
+ problem = manifest_problem(record, root)
113
+ if problem:
114
+ return False, problem
115
+ root = Path(root)
116
+ target = record["target"]
117
+ spec = record.get("spec")
118
+ locked = (spec or {}).get("locked_sha256")
119
+ with tempfile.TemporaryDirectory(prefix="courant-record-") as tmp:
120
+ spec_path = None
121
+ if spec is not None:
122
+ spec_path = Path(tmp) / "spec.json"
123
+ spec_path.write_bytes(spec["text"].encode("utf-8"))
124
+ try:
125
+ if target["source"] == "case_dir":
126
+ verdict = verify_path(root, spec=spec_path, spec_locked_sha256=locked)
127
+ else:
128
+ cj = root / target["case_json"] if target.get("case_json") else None
129
+ verdict = verify_path(root / target["name"], cj, spec=spec_path,
130
+ spec_locked_sha256=locked)
131
+ except InputError as exc:
132
+ return False, f"the run no longer reads: {exc}"
133
+ prov = record["provenance"]
134
+ fresh = canonical_json(build_record(
135
+ verdict, target_name=target["name"], case_json_name=target.get("case_json"),
136
+ spec_text=spec["text"] if spec else None, spec_locked_sha256=locked,
137
+ producer=prov.get("producer"), requester=prov.get("requester")))
138
+ stored = Path(record_path).read_text(encoding="utf-8")
139
+ if fresh == stored:
140
+ return True, (f"identical: {len(record['manifest'])} inputs re-hashed, record re-derived "
141
+ f"byte for byte")
142
+ for i, (a, b) in enumerate(zip(fresh, stored, strict=False)):
143
+ if a != b:
144
+ note = ""
145
+ if record["tool"]["version"] != verdict.tool.version:
146
+ note = (f" (written by Courant {record['tool']['version']}, re-derived by "
147
+ f"{verdict.tool.version})")
148
+ return False, f"record differs at byte {i}: ...{stored[max(0, i - 40):i + 40]!r}{note}"
149
+ return False, "record differs in length"
courant/release.py ADDED
@@ -0,0 +1,205 @@
1
+ """A release's checksums and their signature (TRD OPS-4, OPS-7).
2
+
3
+ A release directory holds its artefacts, `SHA256SUMS` (one `<sha256> <name>` line per artefact,
4
+ sorted by name) and `SHA256SUMS.sig.json` (`courant.release-signature/1`): the Ed25519 signature
5
+ of the exact bytes of `SHA256SUMS`, under the release key (H-SIGNING-KEY). The release workflow
6
+ writes them; `courant update` checks them before it replaces anything. One format, one reader:
7
+ this module.
8
+
9
+ The signature is checked against the public key pinned in this build (`RELEASE_PUBLIC_KEY`), never
10
+ against the key a signature file names. A build with no key pinned refuses to install: an update
11
+ it cannot verify is not an update.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import re
18
+ from pathlib import Path
19
+
20
+ SIG_SCHEMA = "courant.release-signature/1"
21
+ SUMS = "SHA256SUMS"
22
+ SUMS_SIG = "SHA256SUMS.sig.json"
23
+ #: The release public key, Ed25519, 32 bytes as hex (H-SIGNING-KEY, created 11 Oct 2026; base64
24
+ #: `BJNjkWdYITix4o8Yg1QwH/I8bIgc0GTHeKLbXVyCEZI=`). Its private half never enters a repository.
25
+ RELEASE_PUBLIC_KEY: str | None = "0493639167582138b1e28f188354301ff23c6c881cd064c778a2db5d5c821192"
26
+ #: The variable naming the file that holds the release's private key, where it is signed.
27
+ KEY_ENV = "COURANT_RELEASE_SIGNING_KEY"
28
+
29
+ _LINE = re.compile(r"([0-9a-f]{64}) [ *]([^\s/\\][^/\\]*)")
30
+ _VERSION = re.compile(r"# courant-dev (\d+\.\d+\.\d+)")
31
+
32
+
33
+ class ReleaseError(ValueError):
34
+ """A release that cannot be trusted. The message says why, in one line."""
35
+
36
+
37
+ def sums_text(files: dict[str, bytes], version: str) -> str:
38
+ """`SHA256SUMS` for these artefacts {name: bytes}, sorted by name, after a first line
39
+ `# courant-dev <version>`: the signature covers the version, so an older signed release
40
+ cannot be served as a newer one (OPS-7)."""
41
+ return f"# courant-dev {version}\n" + "".join(
42
+ f"{hashlib.sha256(files[n]).hexdigest()} {n}\n" for n in sorted(files))
43
+
44
+
45
+ def sums_version(text: str) -> str | None:
46
+ """The release version `SHA256SUMS` names on its first line, or None."""
47
+ first = text.splitlines()[0].strip() if text.strip() else ""
48
+ m = _VERSION.fullmatch(first)
49
+ return m.group(1) if m else None
50
+
51
+
52
+ def _version_tuple(v: str) -> tuple[int, ...]:
53
+ try:
54
+ parts = tuple(int(x) for x in str(v).strip().removeprefix("v").split("."))
55
+ except ValueError:
56
+ raise ReleaseError(f"{v!r} is not a version MAJOR.MINOR.PATCH") from None
57
+ if len(parts) != 3:
58
+ raise ReleaseError(f"{v!r} is not a version MAJOR.MINOR.PATCH")
59
+ return parts
60
+
61
+
62
+ def check_version(signed: str | None, requested: str, current: str,
63
+ allow_older: bool = False) -> str:
64
+ """The signed release's version, once it is what was asked for. Under `latest` it must be
65
+ strictly above this agent's; an explicit version must equal it, and one below this agent's
66
+ installs only with `allow_older` (`courant update --allow-downgrade`)."""
67
+ if signed is None:
68
+ raise ReleaseError(f"the signed {SUMS} names no version")
69
+ if requested == "latest":
70
+ if _version_tuple(signed) <= _version_tuple(current):
71
+ raise ReleaseError(f"the release served as latest is {signed}, not newer than this "
72
+ f"agent ({current})")
73
+ return signed
74
+ if _version_tuple(signed) != _version_tuple(requested):
75
+ raise ReleaseError(f"asked for {requested.removeprefix('v')}, the signed release is "
76
+ f"{signed}")
77
+ if _version_tuple(signed) < _version_tuple(current) and not allow_older:
78
+ raise ReleaseError(f"{signed} is older than this agent ({current}); pass "
79
+ "--allow-downgrade to install it")
80
+ return signed
81
+
82
+
83
+ def parse_sums(text: str) -> dict[str, str]:
84
+ """{artefact name: sha256} from `SHA256SUMS`. A malformed line or a name given twice is an
85
+ error, never skipped; the first line may name the version."""
86
+ out: dict[str, str] = {}
87
+ for i, line in enumerate(text.splitlines(), 1):
88
+ if not line.strip() or (i == 1 and _VERSION.fullmatch(line.strip())):
89
+ continue
90
+ m = _LINE.fullmatch(line.strip())
91
+ if not m:
92
+ raise ReleaseError(f"{SUMS} line {i} is not '<sha256> <name>'")
93
+ if m.group(2) in out:
94
+ raise ReleaseError(f"{SUMS} names {m.group(2)} twice")
95
+ out[m.group(2)] = m.group(1)
96
+ if not out:
97
+ raise ReleaseError(f"{SUMS} lists no artefacts")
98
+ return out
99
+
100
+
101
+ def signature_doc(sums: bytes, public_key_hex: str, signature_hex: str) -> dict:
102
+ return {"schema": SIG_SCHEMA, "algorithm": "ed25519", "signed": SUMS,
103
+ "signed_sha256": hashlib.sha256(sums).hexdigest(),
104
+ "public_key": public_key_hex, "signature": signature_hex}
105
+
106
+
107
+ def verify_sums(sums: bytes, doc: dict, public_key: str | None) -> dict[str, str]:
108
+ """The checksums, once their signature verifies under `public_key`; ReleaseError otherwise."""
109
+ from courant.signing import verify_bytes
110
+
111
+ if not public_key:
112
+ raise ReleaseError("no release public key is pinned in this build (H-SIGNING-KEY), "
113
+ "so no release can be verified")
114
+ if not isinstance(doc, dict) or doc.get("schema") != SIG_SCHEMA:
115
+ raise ReleaseError(f"{SUMS_SIG} is not {SIG_SCHEMA}")
116
+ if doc.get("algorithm") != "ed25519":
117
+ raise ReleaseError(f"{SUMS_SIG} is not an Ed25519 signature")
118
+ if doc.get("signed_sha256") != hashlib.sha256(sums).hexdigest():
119
+ raise ReleaseError(f"{SUMS} is not the file {SUMS_SIG} signed")
120
+ if str(doc.get("public_key", "")).lower() != public_key.lower():
121
+ raise ReleaseError("signed with a different key than the pinned release key")
122
+ if not verify_bytes(sums, str(doc.get("signature", "")), public_key):
123
+ raise ReleaseError("the signature does not verify")
124
+ return parse_sums(sums.decode())
125
+
126
+
127
+ def verify_asset(name: str, payload: bytes, sums: bytes, doc: dict,
128
+ public_key: str | None = RELEASE_PUBLIC_KEY, *, requested: str = "latest",
129
+ current: str | None = None, allow_older: bool = False) -> str:
130
+ """The asset's SHA-256, once the signed checksums name it with exactly that hash and name
131
+ the version that was asked for (`check_version`)."""
132
+ from courant import __version__
133
+
134
+ listed = verify_sums(sums, doc, public_key)
135
+ check_version(sums_version(sums.decode()), requested, current or __version__, allow_older)
136
+ if name not in listed:
137
+ raise ReleaseError(f"the signed {SUMS} does not list {name}")
138
+ actual = hashlib.sha256(payload).hexdigest()
139
+ if actual != listed[name]:
140
+ raise ReleaseError(f"{name} does not match the signed {SUMS}: expected "
141
+ f"{listed[name]}, got {actual}")
142
+ return actual
143
+
144
+
145
+ def write_sums(dist: str | Path, version: str) -> Path:
146
+ """SHA256SUMS over every artefact in `dist`, its first line naming the release's version, so
147
+ the signature binds the version too (OPS-7: no replayed older release)."""
148
+ dist = Path(dist)
149
+ files = {p.name: p.read_bytes() for p in sorted(dist.iterdir())
150
+ if p.is_file() and p.name not in (SUMS, SUMS_SIG)}
151
+ path = dist / SUMS
152
+ path.write_text(sums_text(files, version))
153
+ return path
154
+
155
+
156
+ def sign_sums(dist: str | Path, key_path: str | Path | None = None,
157
+ variable: str = KEY_ENV) -> tuple[Path, str]:
158
+ """Sign `dist`'s SHA256SUMS with the key `key_path` (or the file `variable` names) points
159
+ at; returns (the signature file, the public key hex). The key is never printed."""
160
+ import json
161
+
162
+ from courant.signing import sign_bytes
163
+
164
+ dist = Path(dist)
165
+ sums = (dist / SUMS).read_bytes()
166
+ public, sig = sign_bytes(sums, key_path=key_path, env=variable)
167
+ path = dist / SUMS_SIG
168
+ path.write_text(json.dumps(signature_doc(sums, public, sig), indent=2, sort_keys=True) + "\n")
169
+ return path, public
170
+
171
+
172
+ def verify_directory(directory: str | Path, public_key: str | None) -> dict[str, str]:
173
+ """Every artefact in a release directory against its signed checksums."""
174
+ import json
175
+
176
+ d = Path(directory)
177
+ sums = (d / SUMS).read_bytes()
178
+ listed = verify_sums(sums, json.loads((d / SUMS_SIG).read_text()), public_key)
179
+ for name, want in listed.items():
180
+ p = d / name
181
+ if not p.is_file():
182
+ raise ReleaseError(f"{name} is listed in {SUMS} and missing")
183
+ if hashlib.sha256(p.read_bytes()).hexdigest() != want:
184
+ raise ReleaseError(f"{name} does not match {SUMS}")
185
+ return listed
186
+
187
+
188
+ __all__ = [
189
+ "KEY_ENV",
190
+ "RELEASE_PUBLIC_KEY",
191
+ "SIG_SCHEMA",
192
+ "SUMS",
193
+ "SUMS_SIG",
194
+ "ReleaseError",
195
+ "check_version",
196
+ "parse_sums",
197
+ "sign_sums",
198
+ "signature_doc",
199
+ "sums_text",
200
+ "sums_version",
201
+ "verify_asset",
202
+ "verify_directory",
203
+ "verify_sums",
204
+ "write_sums",
205
+ ]