lean-pkg 0.25.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.
- lean_pkg/__init__.py +3 -0
- lean_pkg/adapters/__init__.py +148 -0
- lean_pkg/adapters/github.py +65 -0
- lean_pkg/adapters/leansearch.py +68 -0
- lean_pkg/adapters/loogle.py +45 -0
- lean_pkg/adapters/palomar.py +170 -0
- lean_pkg/adapters/reservoir.py +127 -0
- lean_pkg/anchor.py +678 -0
- lean_pkg/audit.py +716 -0
- lean_pkg/binding_file.py +446 -0
- lean_pkg/blueprint.py +213 -0
- lean_pkg/build_scope.py +282 -0
- lean_pkg/ci_github.py +917 -0
- lean_pkg/claim_axioms.py +421 -0
- lean_pkg/claims.py +1155 -0
- lean_pkg/claims_mark.py +197 -0
- lean_pkg/cli.py +5208 -0
- lean_pkg/cli_parser.py +768 -0
- lean_pkg/command_tree.py +615 -0
- lean_pkg/comparator_config.py +990 -0
- lean_pkg/comparator_contracts.py +382 -0
- lean_pkg/comparator_receipt.py +2854 -0
- lean_pkg/comparator_stage.py +623 -0
- lean_pkg/comparator_types.py +830 -0
- lean_pkg/container.py +172 -0
- lean_pkg/core.py +1570 -0
- lean_pkg/coverage.py +1278 -0
- lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
- lean_pkg/data/toolchain-advisories.yaml +77 -0
- lean_pkg/data/upgrade-breaking.yaml +20 -0
- lean_pkg/data/verify-workflow-pins.yaml +14 -0
- lean_pkg/deps_closure.py +512 -0
- lean_pkg/deps_fill.py +445 -0
- lean_pkg/dup_constants.py +448 -0
- lean_pkg/exercise.py +828 -0
- lean_pkg/exercise_forbid.py +288 -0
- lean_pkg/export_paths.py +77 -0
- lean_pkg/extract.py +1172 -0
- lean_pkg/extract_decls.py +501 -0
- lean_pkg/extract_ledger.py +1408 -0
- lean_pkg/extract_summary.py +132 -0
- lean_pkg/extract_types.py +502 -0
- lean_pkg/extract_write.py +138 -0
- lean_pkg/formalization.py +1078 -0
- lean_pkg/formalization_kept.py +182 -0
- lean_pkg/fresh_repo.py +709 -0
- lean_pkg/gate.py +2141 -0
- lean_pkg/headline.py +211 -0
- lean_pkg/help_topics.py +442 -0
- lean_pkg/holes.py +289 -0
- lean_pkg/host_routes.py +376 -0
- lean_pkg/hypotheses.py +788 -0
- lean_pkg/index.py +1749 -0
- lean_pkg/json_stdout.py +48 -0
- lean_pkg/lake_hygiene.py +289 -0
- lean_pkg/lean_diag.py +280 -0
- lean_pkg/lean_scan.py +1300 -0
- lean_pkg/ledger.py +582 -0
- lean_pkg/next_step.py +510 -0
- lean_pkg/page.py +1831 -0
- lean_pkg/page_html.py +153 -0
- lean_pkg/palomar.py +316 -0
- lean_pkg/palomar_check.py +1027 -0
- lean_pkg/port_modules.py +677 -0
- lean_pkg/prior_art.py +286 -0
- lean_pkg/producer.py +212 -0
- lean_pkg/producer_skew.py +208 -0
- lean_pkg/public_safety.py +1487 -0
- lean_pkg/publish.py +402 -0
- lean_pkg/rebase.py +984 -0
- lean_pkg/receipt.py +2385 -0
- lean_pkg/receipt_check.py +1064 -0
- lean_pkg/receipt_ci.py +660 -0
- lean_pkg/receipt_systemd.py +890 -0
- lean_pkg/recommended.py +232 -0
- lean_pkg/report.py +727 -0
- lean_pkg/reservoir.py +203 -0
- lean_pkg/scaffold.py +588 -0
- lean_pkg/schemas/formalization-0.4.schema.json +344 -0
- lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
- lean_pkg/scripts/ClaimAxioms.lean +47 -0
- lean_pkg/scripts/ContractsOnly.lean +300 -0
- lean_pkg/scripts/DupConstants.lean +149 -0
- lean_pkg/scripts/HypProbe.lean +257 -0
- lean_pkg/scripts/comparator-check.sh +396 -0
- lean_pkg/scripts/verify-comparator.sh +135 -0
- lean_pkg/seal_bundle.py +647 -0
- lean_pkg/search.py +865 -0
- lean_pkg/site_profiles/easley.yaml +10 -0
- lean_pkg/site_profiles/github-actions.yaml +12 -0
- lean_pkg/sites.py +225 -0
- lean_pkg/stacks.py +373 -0
- lean_pkg/statements_module.py +217 -0
- lean_pkg/templates/Apache-2.0.txt +202 -0
- lean_pkg/toolchain_advisories.py +225 -0
- lean_pkg/upgrade.py +706 -0
- lean_pkg/verify.py +495 -0
- lean_pkg-0.25.0.dist-info/METADATA +93 -0
- lean_pkg-0.25.0.dist-info/RECORD +103 -0
- lean_pkg-0.25.0.dist-info/WHEEL +5 -0
- lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
- lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
- lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/gate.py
ADDED
|
@@ -0,0 +1,2141 @@
|
|
|
1
|
+
# lean-pkg -- the trust gate
|
|
2
|
+
"""The trust gate: `lean-pkg gate` (validate a lower-tier receipt, bind it to the package's commit, move
|
|
3
|
+
gate-pending -> verified-private), `gate --check`, the comparator evidence path (`comparator attach` and
|
|
4
|
+
`comparator check`: validate_comparator, the copy into the package), the report-log and pin checks, and the
|
|
5
|
+
descendant rules (which commits a receipt bound to an ancestor still covers). `--repo DIR` (repo_override),
|
|
6
|
+
which the read-only commands share, is here too.
|
|
7
|
+
|
|
8
|
+
Moved verbatim out of cli.py (#317, stage 3). cli.py re-exports every name defined here for at least one
|
|
9
|
+
release; lean-pkg's own modules import this module as `gate_mod` (`from . import gate as gate_mod`:
|
|
10
|
+
`gate` is a common local name for a package's gate record). It imports core.py at the top level and the
|
|
11
|
+
command modules it calls only inside the functions that call them; it never imports cli.py. Code here
|
|
12
|
+
reads this module's globals: a test patches a name here (conftest.patch_core patches a core name on every
|
|
13
|
+
module that imports it).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import copy
|
|
19
|
+
import datetime as dt
|
|
20
|
+
import gzip
|
|
21
|
+
import hashlib
|
|
22
|
+
import io
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import pathlib
|
|
26
|
+
import posixpath
|
|
27
|
+
import re
|
|
28
|
+
import shlex
|
|
29
|
+
import shutil
|
|
30
|
+
import sys
|
|
31
|
+
import zlib
|
|
32
|
+
|
|
33
|
+
import yaml
|
|
34
|
+
|
|
35
|
+
from .core import (
|
|
36
|
+
_ACTOR, ancestor_attribute_changes, bound_tree, branch_notice, checker_paths, CLAIMS_COMMIT_FIRST,
|
|
37
|
+
COMPARATOR_CONFIG_FIELDS, COMPARATOR_FIELDS, COMPARATOR_LIST_FIELDS, COMPARATOR_MECHANISMS,
|
|
38
|
+
comparator_pass, COMPARATOR_PASS_LINE, COMPARATOR_SCHEMAS, COMPARATOR_TOOLCHAIN_DIGESTS, COMPARATOR_TOOLS,
|
|
39
|
+
DEFAULT_AXIOMS, docs_build_input, DOCS_PATHS_MAX, events_path, evidence_symlinks, Fail, formalization_rel,
|
|
40
|
+
get_pkg, gh_nwo, git, git_head, git_show_bytes, _is_ancestor, lake_artifact, lease_actor, lease_live,
|
|
41
|
+
linked_changes, linked_evidence_changes, load_registry, LOWER_RECEIPT_SCHEMA, _LOWER_RECEIPT_SCHEMA_RE,
|
|
42
|
+
LOWER_RECEIPT_SCHEMAS, nested_exclusions, nested_label, parse_ts, print_json, RECEIPT_FIELDS, record,
|
|
43
|
+
refuse_invalid_lease, registered_nested_dirs, registry_behind_warning, registry_path, registry_state_of,
|
|
44
|
+
repo_path, require_nonempty, save_registry,
|
|
45
|
+
sha256_bytes, symlink_targets, tracked_at, under_any, UsageError, warn_lease,
|
|
46
|
+
)
|
|
47
|
+
from .holes import SIDECAR as SIGNOFF_SIDECAR, check_definition_holes, parse_sidecar
|
|
48
|
+
from . import binding_file
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# --------------------------------------------------------------------------
|
|
52
|
+
# the descendant rules: which commits a receipt bound to an ancestor still covers (evidence-only,
|
|
53
|
+
# docs-only). They stay here: formalization_derived_only reads formalization.py, which imports cli.
|
|
54
|
+
|
|
55
|
+
def formalization_derived_only(repo: pathlib.Path, bound: str, head: str, rel: str) -> str | None:
|
|
56
|
+
"""None when <rel> differs between bound and head only in keys the formalization renderer derives
|
|
57
|
+
(status.evidence and the rest of formalization.DERIVED_PATHS), compared as YAML data; else the
|
|
58
|
+
reason, naming the changed kept key(s) (#23.5)."""
|
|
59
|
+
from .formalization import changed_kept_keys
|
|
60
|
+
docs = []
|
|
61
|
+
for rev in (bound, head):
|
|
62
|
+
raw = git_show_bytes(repo, f"./{rel}", rev)
|
|
63
|
+
if raw is None:
|
|
64
|
+
return (f"{rel} is not tracked at {rev[:12]}; only a regeneration of a file already "
|
|
65
|
+
f"committed at the bound commit is evidence")
|
|
66
|
+
try:
|
|
67
|
+
doc = yaml.safe_load(raw.decode("utf-8", errors="replace"))
|
|
68
|
+
except yaml.YAMLError:
|
|
69
|
+
return f"{rel} at {rev[:12]} is not valid YAML"
|
|
70
|
+
docs.append(doc if isinstance(doc, dict) else {})
|
|
71
|
+
changed = changed_kept_keys(*docs)
|
|
72
|
+
if changed:
|
|
73
|
+
return (f"{rel} changed in kept (hand-authored) key(s) {', '.join(changed[:5])}; only its "
|
|
74
|
+
f"derived keys (status.evidence and the rest `lean-pkg formalization` regenerates) may "
|
|
75
|
+
f"change after the bound commit")
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def evidence_only_descendant(repo: pathlib.Path, bound: str,
|
|
80
|
+
head: str, formalization: str | None = None,
|
|
81
|
+
exclude: tuple[str, ...] = ()) -> tuple[bool, str]:
|
|
82
|
+
"""Evidence-only descendant rule (see DESIGN.md): a receipt bound to commit `bound` is
|
|
83
|
+
accepted at `head` when head == bound, or when head descends from bound and
|
|
84
|
+
the only paths that differ live under .lean-receipts/ (the evidence itself).
|
|
85
|
+
Paths are taken relative to the package directory `repo`: when the package is a
|
|
86
|
+
subdirectory of its git repository (lean/, lean/contrib/), only changes under that
|
|
87
|
+
directory count, and within it only <dir>/.lean-receipts/ is evidence.
|
|
88
|
+
`formalization` (the package's recorded formalization.yaml path, see formalization_rel):
|
|
89
|
+
that file may also differ when only its derived keys changed, since it must cite the
|
|
90
|
+
receipt and so cannot be inside the bound commit (#23.5). claims.yaml never may.
|
|
91
|
+
`exclude`: package-relative directories of nested registered packages this package does not depend
|
|
92
|
+
on (nested_exclusions); changes under them are not this package's (#3).
|
|
93
|
+
Returns (ok, note)."""
|
|
94
|
+
if bound == head:
|
|
95
|
+
return True, ""
|
|
96
|
+
p = git(repo, "merge-base", "--is-ancestor", bound, head)
|
|
97
|
+
if p.returncode != 0:
|
|
98
|
+
return False, f"{bound[:12]} is not an ancestor of HEAD {head[:12]}"
|
|
99
|
+
prefix = git(repo, "rev-parse", "--show-prefix").stdout.strip()
|
|
100
|
+
# --relative: only paths under the package directory, relative to it.
|
|
101
|
+
# --no-renames: a rename into .lean-receipts/ is a source change.
|
|
102
|
+
p = git(repo, "diff", "--no-renames", "--name-only", "--relative", bound, head)
|
|
103
|
+
paths = [x for x in p.stdout.splitlines() if x.strip()]
|
|
104
|
+
ignored = [x for x in paths if under_any(x, exclude)]
|
|
105
|
+
paths = [x for x in paths if not under_any(x, exclude)]
|
|
106
|
+
# A Lake build cache or compiled artifact is never evidence, under .lean-receipts/ included (#5).
|
|
107
|
+
cached = [f"{x} ({lake_artifact(x)})" for x in paths if lake_artifact(x)]
|
|
108
|
+
if cached:
|
|
109
|
+
return False, (f"HEAD {head[:12]} differs from {bound[:12]} in {'; '.join(cached[:5])}"
|
|
110
|
+
+ (f" (+{len(cached) - 5} more)" if len(cached) > 5 else "")
|
|
111
|
+
+ "; Lake reads it in place of a build, so it is never evidence")
|
|
112
|
+
foreign = [x for x in paths if not x.startswith(".lean-receipts/")]
|
|
113
|
+
# Outside a subdirectory package: .gitattributes/.gitmodules/.lfsconfig at the repository root or between
|
|
114
|
+
# it and the package still change the bytes the build sees (filters, eol, LFS); never evidence.
|
|
115
|
+
outside = ancestor_attribute_changes(repo, bound, head)
|
|
116
|
+
if outside:
|
|
117
|
+
return False, (f"HEAD {head[:12]} differs from {bound[:12]} in {', '.join(outside[:5])} "
|
|
118
|
+
f"(outside the package directory; can change the bytes the build sees)")
|
|
119
|
+
# A committed symlink at the bound commit that resolves into .lean-receipts/ (or to the formalization file)
|
|
120
|
+
# would let an "evidence" edit change what the build reads.
|
|
121
|
+
linked = linked_evidence_changes(repo, bound, paths, formalization) if paths else []
|
|
122
|
+
if linked:
|
|
123
|
+
return False, (f"HEAD {head[:12]} differs from {bound[:12]} in evidence that a committed symlink "
|
|
124
|
+
f"points to: {', '.join(linked[:5])}; a symlink target is never evidence")
|
|
125
|
+
if (prefix or ignored) and not paths:
|
|
126
|
+
if ignored:
|
|
127
|
+
return True, (f"descendant of {bound[:12]} with no change under {prefix or './'} outside nested "
|
|
128
|
+
f"registered package(s) {nested_label(ignored, exclude)}")
|
|
129
|
+
return True, f"descendant of {bound[:12]} with no change under {prefix}"
|
|
130
|
+
if formalization and formalization in foreign:
|
|
131
|
+
problem = formalization_derived_only(repo, bound, head, formalization)
|
|
132
|
+
if problem:
|
|
133
|
+
return False, f"HEAD {head[:12]} differs from {bound[:12]}: {problem}"
|
|
134
|
+
foreign.remove(formalization)
|
|
135
|
+
if foreign or not paths:
|
|
136
|
+
return False, (f"HEAD {head[:12]} differs from {bound[:12]} outside "
|
|
137
|
+
f".lean-receipts/: {foreign[:5]}")
|
|
138
|
+
return True, (f"evidence-only descendant of {bound[:12]} (+{len(paths)} evidence file(s))"
|
|
139
|
+
+ (f"; ignored {len(ignored)} change(s) under nested registered package(s) "
|
|
140
|
+
f"{nested_label(ignored, exclude)}" if ignored else ""))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def docs_only_descendant(repo: pathlib.Path, bound: str, head: str, pkg: dict | None,
|
|
144
|
+
checker=None, exclude: tuple[str, ...] = (),
|
|
145
|
+
opted: str = "opted in") -> tuple[bool, str, list[str]]:
|
|
146
|
+
"""The docs-only descendant rule (docs/receipts.md): head descends from bound and no build input
|
|
147
|
+
under the package directory changed. Build inputs: the .lean files a lean_lib or lean_exe of the
|
|
148
|
+
package owns (read from lakefile.toml at bound and at head; every *.lean when there is a
|
|
149
|
+
lakefile.lean, no lakefile.toml, or one that cannot be read precisely), input_file/input_dir and
|
|
150
|
+
`require` path targets, lakefile.*, lake-manifest.json,
|
|
151
|
+
lean-toolchain at any depth, the record's build_inputs globs, the files the receipt's checker names;
|
|
152
|
+
always refused: a Lake build cache or compiled artifact (lake_artifact: a .lake component at any depth,
|
|
153
|
+
or an artifact suffix; .lean-receipts/ included), a symlink or gitlink added/changed/removed, .gitattributes, .gitmodules, .lfsconfig,
|
|
154
|
+
claims.yaml (and the recorded claims_file), lean-pkg-binding.yaml (the opt-in itself, at any depth);
|
|
155
|
+
for a subdirectory package also a .gitattributes,
|
|
156
|
+
.gitmodules or .lfsconfig at the repository root or in any directory between it and the package.
|
|
157
|
+
The formalization.yaml keeps its derived-keys-only rule. `exclude`: as for evidence_only_descendant.
|
|
158
|
+
`opted`: the admission note's last clause, naming where the opt-in came from (binding_file.OptIn.label).
|
|
159
|
+
Returns (ok, note, docs_paths): docs_paths are the changed non-build, non-evidence paths."""
|
|
160
|
+
from .build_scope import lake_scope
|
|
161
|
+
pkg = pkg or {}
|
|
162
|
+
if not _is_ancestor(repo, bound, head):
|
|
163
|
+
return False, f"{bound[:12]} is not an ancestor of HEAD {head[:12]}", []
|
|
164
|
+
p = git(repo, "diff", "--no-renames", "--raw", "-z", "--relative", bound, head)
|
|
165
|
+
fields = p.stdout.split("\0")
|
|
166
|
+
globs = [g for g in (pkg.get("build_inputs") or []) if isinstance(g, str) and g.strip()]
|
|
167
|
+
extra = set(checker_paths(repo, bound, checker))
|
|
168
|
+
scopes, why_conservative = [], ""
|
|
169
|
+
for rev in (bound, head):
|
|
170
|
+
sc, why_sc = lake_scope(lambda rel, rev=rev: git_show_bytes(repo, rel, rev))
|
|
171
|
+
if sc is None:
|
|
172
|
+
scopes, why_conservative = None, why_sc
|
|
173
|
+
break
|
|
174
|
+
scopes.append(sc)
|
|
175
|
+
claims_rel = str(pkg.get("claims_file") or "claims.yaml").strip()
|
|
176
|
+
while claims_rel.startswith("./"):
|
|
177
|
+
claims_rel = claims_rel[2:]
|
|
178
|
+
fz_rel = formalization_rel(pkg) or "formalization.yaml"
|
|
179
|
+
refused: list[str] = []
|
|
180
|
+
claims_changed: list[str] = [] # refused only because they are the claims file
|
|
181
|
+
docs: list[str] = []
|
|
182
|
+
admitted: list[str] = [] # docs, evidence and formalization paths: none may be a symlink target
|
|
183
|
+
ignored = 0
|
|
184
|
+
i = 0
|
|
185
|
+
while i + 1 < len(fields):
|
|
186
|
+
meta, path = fields[i], fields[i + 1]
|
|
187
|
+
i += 2
|
|
188
|
+
if not meta.startswith(":"):
|
|
189
|
+
continue
|
|
190
|
+
if under_any(path, exclude):
|
|
191
|
+
ignored += 1
|
|
192
|
+
continue
|
|
193
|
+
parts = meta[1:].split()
|
|
194
|
+
modes = parts[:2]
|
|
195
|
+
if any(m in ("120000", "160000") for m in modes):
|
|
196
|
+
kind = "gitlink" if "160000" in modes else "symlink"
|
|
197
|
+
refused.append(f"{path} ({kind} {parts[-1][:1]})")
|
|
198
|
+
continue
|
|
199
|
+
why = "claims_file" if path == claims_rel else docs_build_input(path, globs, extra, scopes)
|
|
200
|
+
if why:
|
|
201
|
+
refused.append(f"{path} ({why}{', deleted' if parts[-1].startswith('D') else ''})")
|
|
202
|
+
if why in ("claims_file", "claims.yaml") and not parts[-1].startswith("D"):
|
|
203
|
+
claims_changed.append(refused[-1])
|
|
204
|
+
continue
|
|
205
|
+
if path == fz_rel:
|
|
206
|
+
problem = formalization_derived_only(repo, bound, head, fz_rel)
|
|
207
|
+
if problem:
|
|
208
|
+
refused.append(f"{path} ({problem})")
|
|
209
|
+
admitted.append(path)
|
|
210
|
+
continue
|
|
211
|
+
admitted.append(path)
|
|
212
|
+
if path.startswith(".lean-receipts/"):
|
|
213
|
+
continue
|
|
214
|
+
docs.append(path)
|
|
215
|
+
refused += [f"{x} (outside the package directory; can change the bytes the build sees)"
|
|
216
|
+
for x in ancestor_attribute_changes(repo, bound, head)]
|
|
217
|
+
if admitted: # a non-build file a committed symlink points to is read through that symlink
|
|
218
|
+
try:
|
|
219
|
+
refused += linked_changes(symlink_targets(bound_tree(repo, bound)), admitted)
|
|
220
|
+
except Fail as e:
|
|
221
|
+
refused.append(f"{len(admitted)} file(s) ({e})")
|
|
222
|
+
if refused:
|
|
223
|
+
if refused == claims_changed:
|
|
224
|
+
names = ", ".join(x.split(" (", 1)[0] for x in claims_changed)
|
|
225
|
+
return False, (f"{names} changed after the receipt commit {bound[:12]} (HEAD {head[:12]}); gate "
|
|
226
|
+
f"reads the claims at the receipt commit, so they are part of what it binds: "
|
|
227
|
+
f"{CLAIMS_COMMIT_FIRST}"), []
|
|
228
|
+
lean_note = ""
|
|
229
|
+
if scopes is None and any(" (*.lean" in x for x in refused):
|
|
230
|
+
lean_note = (f" (every *.lean counts as a build input: {why_conservative}; only a lakefile.toml's "
|
|
231
|
+
f"lean_lib/lean_exe targets narrow it)")
|
|
232
|
+
return False, (f"build input(s) changed between {bound[:12]} and HEAD {head[:12]}: "
|
|
233
|
+
f"{'; '.join(refused[:3])}" + (f" (+{len(refused) - 3} more)" if len(refused) > 3 else "")
|
|
234
|
+
+ lean_note + "; the receipt must be rebuilt at HEAD"), []
|
|
235
|
+
docs.sort()
|
|
236
|
+
shown = ", ".join(docs[:5]) + (f", +{len(docs) - 5} more" if len(docs) > 5 else "")
|
|
237
|
+
return True, (f"docs-only descendant of {bound[:12]} ({len(docs)} non-build file(s): {shown}; "
|
|
238
|
+
f"{opted}" + (f"; ignored {ignored} change(s) under nested registered package(s) "
|
|
239
|
+
f"{', '.join(d + '/' for d in exclude)}" if ignored else "") + ")"), docs
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def package_binding(repo: pathlib.Path, bound: str, head: str, pkg: dict | None,
|
|
243
|
+
checker=None, formalization: str | None = None, nested: tuple[str, ...] | None = None,
|
|
244
|
+
opt_in=None) -> tuple[bool, str, list[str] | None, object]:
|
|
245
|
+
"""The binding rule for a package's commit-bound evidence: the evidence-only rule, then, when the
|
|
246
|
+
package opts in, the docs-only rule. The opt-in (binding_file.resolve_opt_in, unless `opt_in` is given)
|
|
247
|
+
is lean-pkg-binding.yaml read at `bound` and nowhere else, with the registry record's precedence: a
|
|
248
|
+
record docs_descendants: false vetoes, a record true with no file at `bound` still opts in, a file at
|
|
249
|
+
`bound` decides. (ok, note, docs_paths, opt_in): docs_paths is a list only when the docs rule admitted
|
|
250
|
+
head; opt_in (binding_file.OptIn) is None when the evidence-only rule decided without it. Without the
|
|
251
|
+
opt-in the verdict and note are the evidence-only rule's, plus the clauses that say why the docs rule
|
|
252
|
+
did not apply (a hint when it would have admitted head, the file added after `bound`, a file at
|
|
253
|
+
`bound` that does not opt in, the record's veto).
|
|
254
|
+
`formalization` overrides the record's pointer (gate --refresh-formalization); `checker` defaults
|
|
255
|
+
to the recorded gate receipt's. `nested`: the package-relative roots of nested registered packages
|
|
256
|
+
(default: from the registry this process loaded, registered_nested_dirs); changes under one are not
|
|
257
|
+
this package's unless it depends on it (nested_exclusions, #3)."""
|
|
258
|
+
from . import binding_file
|
|
259
|
+
pkg = pkg or {}
|
|
260
|
+
fz = formalization if formalization is not None else formalization_rel(pkg)
|
|
261
|
+
if nested is None:
|
|
262
|
+
nested = registered_nested_dirs(repo)
|
|
263
|
+
exclude, kept = nested_exclusions(repo, bound, head, nested) if bound != head else ((), [])
|
|
264
|
+
kept_note = (f"; nested registered package(s) still counted as build input(s): {'; '.join(kept)}"
|
|
265
|
+
if kept else "")
|
|
266
|
+
ok, note = evidence_only_descendant(repo, bound, head, fz, exclude)
|
|
267
|
+
if ok or not _is_ancestor(repo, bound, head):
|
|
268
|
+
return ok, note + ("" if ok else kept_note), None, None
|
|
269
|
+
note += kept_note
|
|
270
|
+
if opt_in is None:
|
|
271
|
+
opt_in = binding_file.resolve_opt_in(repo, bound, pkg)
|
|
272
|
+
if checker is None:
|
|
273
|
+
checker = (recorded_json(repo, (pkg.get("gate") or {}).get("receipt")) or {}).get("checker")
|
|
274
|
+
dpkg = {**pkg, "build_inputs": list(opt_in.build_inputs)}
|
|
275
|
+
if fz:
|
|
276
|
+
dpkg["formalization_yaml"] = fz
|
|
277
|
+
dok, dnote, docs = docs_only_descendant(repo, bound, head, dpkg, checker, exclude, opted=opt_in.label)
|
|
278
|
+
# rule 2: a file that exists at head but not at the bound commit grants nothing
|
|
279
|
+
added = (f"; {binding_file.FILE} was added after {bound[:12]}; the opt-in is read at the bound commit only"
|
|
280
|
+
if opt_in.file_state == "absent" and tracked_at(repo, binding_file.FILE, head) else "")
|
|
281
|
+
why_not = "".join(f"; {n}" for n in opt_in.notes)
|
|
282
|
+
if opt_in.rule == "docs-only":
|
|
283
|
+
if dok:
|
|
284
|
+
return True, dnote, docs, opt_in
|
|
285
|
+
return False, f"{note}; docs-only rule ({opt_in.label}): {dnote}{added}", None, opt_in
|
|
286
|
+
if dok and opt_in.file_state == "absent":
|
|
287
|
+
name = pkg.get("name") or "NAME"
|
|
288
|
+
return False, (f"{note}; every changed path is a non-build file, so the package can opt in: commit "
|
|
289
|
+
f"{binding_file.FILE} (schema: {binding_file.SCHEMA}, docs_descendants: true) in the "
|
|
290
|
+
f"package directory before the next verify run (docs/receipts.md#docs-only-descendants-opt-in), "
|
|
291
|
+
f"or `lean-pkg update {name} --accept-docs-descendants --reason TEXT`"), None, opt_in
|
|
292
|
+
if CLAIMS_COMMIT_FIRST in dnote:
|
|
293
|
+
return False, f"{note}; {dnote}{why_not}{added}", None, opt_in
|
|
294
|
+
return False, f"{note}{why_not}{added}", None, opt_in
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def package_descendant(repo: pathlib.Path, bound: str, head: str, pkg: dict | None,
|
|
298
|
+
checker=None, formalization: str | None = None,
|
|
299
|
+
nested: tuple[str, ...] | None = None, opt_in=None) -> tuple[bool, str, list[str] | None]:
|
|
300
|
+
"""package_binding without the opt-in: (ok, note, docs_paths). Every caller that does not report where
|
|
301
|
+
the opt-in came from uses this."""
|
|
302
|
+
ok, note, docs, _opt_in = package_binding(repo, bound, head, pkg, checker=checker,
|
|
303
|
+
formalization=formalization, nested=nested, opt_in=opt_in)
|
|
304
|
+
return ok, note, docs
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def docs_admission_line(head: str, bound: str, note: str) -> str:
|
|
308
|
+
"""The text line of a docs-only admission: `✓ HEAD <c12> is a docs-only descendant of ...`."""
|
|
309
|
+
return f"✓ HEAD {head[:12]} is a {note}"
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def docs_admission(repo: pathlib.Path, commit: str, pkg: dict, checker=None) -> tuple[dict, str | None]:
|
|
313
|
+
"""({descendant_of, docs_paths, opt_in} or {}, text line or None): the additive event/JSON fields when
|
|
314
|
+
the docs-only rule (not the evidence-only rule) admitted HEAD for evidence bound to `commit`. opt_in is
|
|
315
|
+
{source, commit, path}: source "committed" (lean-pkg-binding.yaml at `commit`, path package-relative)
|
|
316
|
+
or "registry" (the record's docs_descendants: true, path null)."""
|
|
317
|
+
head = git_head(repo) or ""
|
|
318
|
+
if not head or head == commit:
|
|
319
|
+
return {}, None
|
|
320
|
+
ok, note, docs, opt_in = package_binding(repo, commit, head, pkg, checker=checker)
|
|
321
|
+
if not ok or docs is None:
|
|
322
|
+
return {}, None
|
|
323
|
+
return ({"descendant_of": commit, "docs_paths": docs[:DOCS_PATHS_MAX], "opt_in": opt_in.view()},
|
|
324
|
+
docs_admission_line(head, commit, note))
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
# --------------------------------------------------------------------------
|
|
328
|
+
# gate
|
|
329
|
+
|
|
330
|
+
# The results ledger is the project's own record of outcomes, outside lean-pkg (field report: name it).
|
|
331
|
+
RL_REMINDER = ("results-ledger: lean-pkg recorded this outcome for {name} (`lean-pkg status {name}`; per claim: "
|
|
332
|
+
"`lean-pkg claims ledger {name}`); if your project keeps a results ledger of its own, add it "
|
|
333
|
+
"there (docs/lifecycle.md#results-ledger)")
|
|
334
|
+
|
|
335
|
+
# a lower-tier receipt's sealed sacct record (`receipt slurm --seal-sacct`) is missing at HEAD or not its bytes
|
|
336
|
+
SACCT_SEAL_RESTORE = "sacct seal record missing or changed: "
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def check_lower_receipt_schema(receipt: dict, *, newer_only: bool = False) -> None:
|
|
340
|
+
"""The lower-tier receipt's `schema` marker: absent is version 0 (a receipt written before 0.22.0, judged
|
|
341
|
+
as before); LOWER_RECEIPT_SCHEMAS pass. A newer lower-receipt/N is refused naming the upgrade; any other
|
|
342
|
+
value is refused as malformed (unless newer_only, the check that runs before the required fields, so a
|
|
343
|
+
newer receipt that dropped a field is still told to upgrade)."""
|
|
344
|
+
if "schema" not in receipt:
|
|
345
|
+
return
|
|
346
|
+
s = receipt["schema"]
|
|
347
|
+
if s in LOWER_RECEIPT_SCHEMAS:
|
|
348
|
+
return
|
|
349
|
+
m = _LOWER_RECEIPT_SCHEMA_RE.fullmatch(s) if isinstance(s, str) else None
|
|
350
|
+
if m and int(m.group(1)) > int(LOWER_RECEIPT_SCHEMA.rsplit("/", 1)[1]):
|
|
351
|
+
raise Fail(f"lower-tier receipt schema {s} is not supported (supported: "
|
|
352
|
+
f"{', '.join(LOWER_RECEIPT_SCHEMAS)}, and a receipt without a schema key); this lean-pkg is "
|
|
353
|
+
f"older than the receipt: upgrade lean-pkg")
|
|
354
|
+
if not newer_only:
|
|
355
|
+
raise Fail(f"receipt schema must be {LOWER_RECEIPT_SCHEMA!r} (or absent, in a receipt written before "
|
|
356
|
+
f"0.22.0), got {s!r}")
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def validate_receipt(pkg: dict, repo: pathlib.Path, receipt: dict) -> None:
|
|
360
|
+
check_lower_receipt_schema(receipt, newer_only=True)
|
|
361
|
+
for f in RECEIPT_FIELDS:
|
|
362
|
+
if f not in receipt:
|
|
363
|
+
raise Fail(f"receipt missing required field {f!r}")
|
|
364
|
+
check_lower_receipt_schema(receipt)
|
|
365
|
+
commit = str(receipt["commit"])
|
|
366
|
+
if not re.fullmatch(r"[0-9a-f]{40}", commit):
|
|
367
|
+
raise Fail(f"receipt commit is not a full lowercase 40-hex sha: {commit!r}")
|
|
368
|
+
head = git_head(repo)
|
|
369
|
+
if head is None:
|
|
370
|
+
raise Fail(f"cannot resolve HEAD in {repo}")
|
|
371
|
+
ok, note, _docs = package_descendant(repo, commit, head, pkg, checker=receipt.get("checker"))
|
|
372
|
+
if not ok:
|
|
373
|
+
raise Fail(f"receipt commit {commit[:12]}… != repo HEAD {head[:12]}… — "
|
|
374
|
+
f"the receipt must bind to HEAD or an evidence-only descendant "
|
|
375
|
+
f"({note})")
|
|
376
|
+
check_toolchain_at(repo, commit, receipt["lean_toolchain"], "toolchain mismatch")
|
|
377
|
+
check_path_deps_at(repo, commit, formalization_rel(pkg))
|
|
378
|
+
if not str(receipt["mathlib_rev"]).strip():
|
|
379
|
+
raise Fail(f"receipt mathlib_rev is empty (a package without Mathlib says {NO_MATHLIB!r})")
|
|
380
|
+
committed = committed_mathlib(repo, commit)
|
|
381
|
+
rev = str(receipt["mathlib_rev"]).strip()
|
|
382
|
+
if committed not in (None, NO_MATHLIB) and not _same_rev(rev, committed):
|
|
383
|
+
raise Fail(f"mathlib mismatch: receipt mathlib_rev={rev!r}, the mathlib rev in lake-manifest.json "
|
|
384
|
+
f"committed at {commit[:12]}={committed!r}; the receipt must name the Mathlib the bound commit "
|
|
385
|
+
f"pins" + (f" ({NO_MATHLIB!r} is the value of a package without Mathlib)" if rev == NO_MATHLIB
|
|
386
|
+
else ""))
|
|
387
|
+
# committed == NO_MATHLIB with another value: a receipt written before `none` was a checked value; it is
|
|
388
|
+
# read as before (not checked, receipt_check_lines says so), never refused
|
|
389
|
+
sc = receipt["sorry_count"]
|
|
390
|
+
if isinstance(sc, bool) or not isinstance(sc, int):
|
|
391
|
+
raise Fail(f"sorry_count must be an integer, got {sc!r}")
|
|
392
|
+
if sc != 0:
|
|
393
|
+
raise Fail(f"sorry_count must be 0, got {sc} — the trust gate is not clean")
|
|
394
|
+
axioms = receipt["axioms"]
|
|
395
|
+
if not isinstance(axioms, list) or not all(isinstance(a, str) for a in axioms):
|
|
396
|
+
raise Fail("axioms must be a list of strings")
|
|
397
|
+
allowed = set((pkg.get("gate") or {}).get("axioms_allowed") or DEFAULT_AXIOMS)
|
|
398
|
+
extra = sorted(set(axioms) - allowed)
|
|
399
|
+
if extra:
|
|
400
|
+
raise Fail(f"axioms {extra} outside allowed set {sorted(allowed)}")
|
|
401
|
+
if "claim_axioms" in receipt: # additive (AX1): per-claim axioms read from the built environment
|
|
402
|
+
from . import claim_axioms
|
|
403
|
+
problems = claim_axioms.summary_problems(receipt["claim_axioms"], allowed)
|
|
404
|
+
if problems:
|
|
405
|
+
raise Fail("; ".join(problems))
|
|
406
|
+
if "slurm_sacct" in receipt: # additive (`receipt slurm --seal-sacct`): the sealed sacct record at HEAD
|
|
407
|
+
from . import receipt as receipt_mod
|
|
408
|
+
why = receipt_mod.committed_sacct_seal_problem(repo, receipt)
|
|
409
|
+
if why:
|
|
410
|
+
# the record missing at HEAD or not its bytes: restoring the byte-exact file is enough
|
|
411
|
+
restore = "is not committed at HEAD" in why or "does not hash to" in why
|
|
412
|
+
raise Fail(f"{SACCT_SEAL_RESTORE if restore else 'sacct seal: '}{why}")
|
|
413
|
+
if "ci" in receipt: # additive (proposal 0008): the GitHub Actions run block, level 1 (offline)
|
|
414
|
+
from . import ci_github
|
|
415
|
+
problems, _workflow = ci_github.level1(receipt, repo)
|
|
416
|
+
if problems:
|
|
417
|
+
raise Fail("ci block (a GitHub Actions run, level 1; docs/formats.md#the-ci-block): "
|
|
418
|
+
+ "; ".join(problems))
|
|
419
|
+
sha = str(receipt["report_sha256"])
|
|
420
|
+
if not re.fullmatch(r"[0-9a-fA-F]{64}", sha):
|
|
421
|
+
raise Fail(f"report_sha256 must be 64 hex chars, got {sha!r}")
|
|
422
|
+
for f in ("job_id", "checker", "generated_at"):
|
|
423
|
+
if not str(receipt[f]).strip():
|
|
424
|
+
raise Fail(f"receipt field {f!r} is empty")
|
|
425
|
+
check_timestamp(receipt["generated_at"], "receipt")
|
|
426
|
+
receipt_job_slug(receipt["job_id"])
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def check_timestamp(value, what: str) -> None:
|
|
430
|
+
"""generated_at must parse as an ISO-8601 timestamp (parse_ts), not merely be non-empty."""
|
|
431
|
+
try:
|
|
432
|
+
parse_ts(value)
|
|
433
|
+
except (ValueError, TypeError):
|
|
434
|
+
raise Fail(f"{what} field 'generated_at' is not an ISO-8601 timestamp: {value!r}") from None
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def receipt_job_slug(job_id) -> str:
|
|
438
|
+
"""The job id as it appears in the stored receipt's file name: characters outside
|
|
439
|
+
[A-Za-z0-9._-] become '-', and leading dots and dashes are stripped (so '../../evil' is
|
|
440
|
+
'evil', never a '..'-led name). An empty result is refused."""
|
|
441
|
+
slug = re.sub(r"[^A-Za-z0-9._-]+", "-", str(job_id)).lstrip(".-")
|
|
442
|
+
if not slug:
|
|
443
|
+
raise Fail(f"receipt job_id {str(job_id)!r} leaves no usable file-name characters")
|
|
444
|
+
return slug
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def check_toolchain_at(repo: pathlib.Path, commit: str, claimed, label: str) -> None:
|
|
448
|
+
"""The receipt's lean_toolchain must equal the lean-toolchain file committed at the bound
|
|
449
|
+
commit (relative to the package directory). The working-tree file never counts."""
|
|
450
|
+
blob = git_show_bytes(repo, "./lean-toolchain", commit)
|
|
451
|
+
if blob is None:
|
|
452
|
+
raise Fail(f"{repo}: no lean-toolchain committed at {commit[:12]}")
|
|
453
|
+
committed = blob.decode("utf-8", "replace").strip()
|
|
454
|
+
if str(claimed).strip() != committed:
|
|
455
|
+
wt = repo / "lean-toolchain"
|
|
456
|
+
work = wt.read_text().strip() if wt.is_file() else None
|
|
457
|
+
raise Fail(f"{label}: receipt={str(claimed).strip()!r} committed at {commit[:12]}="
|
|
458
|
+
f"{committed!r}"
|
|
459
|
+
+ (f" (the working-tree file says {work!r}; uncommitted files do not count)"
|
|
460
|
+
if work is not None and work != committed else ""))
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def outside_path_deps(manifest: bytes) -> list[str]:
|
|
464
|
+
"""`name (dir)` for each `path` package in lake-manifest.json bytes whose dir leaves the package
|
|
465
|
+
directory (absolute, or `..` after normalising). Its sources are outside what a receipt binds, so an
|
|
466
|
+
edit to them is never drift. Judged lexically on the committed text; ValueError on bad JSON."""
|
|
467
|
+
data = json.loads(manifest.decode("utf-8", "replace"))
|
|
468
|
+
out = []
|
|
469
|
+
for p in (data.get("packages") or []) if isinstance(data, dict) else []:
|
|
470
|
+
if not isinstance(p, dict) or p.get("type") != "path":
|
|
471
|
+
continue
|
|
472
|
+
d = str(p.get("dir") or "")
|
|
473
|
+
norm = posixpath.normpath(d.replace("\\", "/")) if d else "."
|
|
474
|
+
if posixpath.isabs(norm) or norm == ".." or norm.startswith("../"):
|
|
475
|
+
out.append(f"{p.get('name')} ({d})")
|
|
476
|
+
return out
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def escaping_symlinks(tree: dict[str, str]) -> list[str]:
|
|
480
|
+
"""`path -> target` for each committed symlink whose target is absolute or has a `..` component. A
|
|
481
|
+
target that only descends cannot leave the directory holding the symlink, so no chain of the
|
|
482
|
+
remaining symlinks can leave the package directory either."""
|
|
483
|
+
out = []
|
|
484
|
+
for path, mode in sorted(tree.items()):
|
|
485
|
+
if mode.startswith("120000:"):
|
|
486
|
+
target = mode.split(":", 1)[1]
|
|
487
|
+
t = target.replace("\\", "/")
|
|
488
|
+
if posixpath.isabs(t) or ".." in t.split("/"):
|
|
489
|
+
out.append(f"{path} -> {target}")
|
|
490
|
+
return out
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def path_dep_tree_problems(tree: dict[str, str], manifest: bytes) -> list[str]:
|
|
494
|
+
"""For each in-package `path` dependency: its dir, and every directory on the way to it, must be a
|
|
495
|
+
tracked directory at the bound commit (not a symlink, a submodule gitlink, or untracked such as
|
|
496
|
+
.lake/), and nothing under it may be a gitlink. Lexically escaping ones are outside_path_deps'."""
|
|
497
|
+
data = json.loads(manifest.decode("utf-8", "replace"))
|
|
498
|
+
out = []
|
|
499
|
+
for p in (data.get("packages") or []) if isinstance(data, dict) else []:
|
|
500
|
+
if not isinstance(p, dict) or p.get("type") != "path":
|
|
501
|
+
continue
|
|
502
|
+
d = str(p.get("dir") or "")
|
|
503
|
+
norm = posixpath.normpath(d.replace("\\", "/")) if d else "."
|
|
504
|
+
if posixpath.isabs(norm) or norm == ".." or norm.startswith("../") or norm == ".":
|
|
505
|
+
continue
|
|
506
|
+
parts = norm.split("/")
|
|
507
|
+
for i in range(1, len(parts) + 1):
|
|
508
|
+
prefix = "/".join(parts[:i])
|
|
509
|
+
mode = tree.get(prefix)
|
|
510
|
+
if mode != "040000":
|
|
511
|
+
what = ("a symlink" if mode and mode.startswith("120000") else
|
|
512
|
+
"a submodule (gitlink)" if mode == "160000" else
|
|
513
|
+
"a file" if mode else "not tracked")
|
|
514
|
+
out.append(f"{p.get('name')} ({d}): {prefix} is {what} at the bound commit")
|
|
515
|
+
break
|
|
516
|
+
else:
|
|
517
|
+
links = [q for q, m in tree.items() if m == "160000" and q.startswith(norm + "/")]
|
|
518
|
+
if links:
|
|
519
|
+
out.append(f"{p.get('name')} ({d}): contains a submodule (gitlink) {links[0]}")
|
|
520
|
+
return out
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def check_evidence_symlinks_at(repo: pathlib.Path, commit: str, formalization: str | None = None,
|
|
524
|
+
tree: dict[str, str] | None = None) -> None:
|
|
525
|
+
"""Refuse a bound commit with a committed symlink that resolves into .lean-receipts/ (or to the
|
|
526
|
+
package's formalization.yaml): the evidence-only rule admits later edits there, so the symlink would
|
|
527
|
+
let a source change pass as evidence."""
|
|
528
|
+
links = evidence_symlinks(tree if tree is not None else bound_tree(repo, commit), formalization)
|
|
529
|
+
if links:
|
|
530
|
+
raise Fail(f"symlinks at {commit[:12]} point into evidence the binding rule lets change later: "
|
|
531
|
+
f"{', '.join(links)}. The receipt would not bind what they point to; replace them with the "
|
|
532
|
+
f"files (outside .lean-receipts/), then a new commit and a new receipt")
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def check_path_deps_at(repo: pathlib.Path, commit: str, formalization: str | None = None) -> None:
|
|
536
|
+
"""Refuse a receipt whose bound commit lets the build read sources outside the package directory:
|
|
537
|
+
a `path` dependency in lake-manifest.json (committed at the bound commit) that leaves the directory
|
|
538
|
+
lexically, or that reaches through a symlink, a submodule or an untracked directory; and any
|
|
539
|
+
committed symlink whose target is absolute or climbs with `..`. Judged on the commit's tree, never
|
|
540
|
+
the working tree. A manifest that is absent is left to the other checks; one that is not valid JSON
|
|
541
|
+
is refused."""
|
|
542
|
+
tree = bound_tree(repo, commit)
|
|
543
|
+
links = escaping_symlinks(tree)
|
|
544
|
+
if links:
|
|
545
|
+
raise Fail(f"symlinks at {commit[:12]} can leave the package directory: {', '.join(links)}. The "
|
|
546
|
+
f"receipt does not bind what they point to; replace them with the files (or a target "
|
|
547
|
+
f"that only descends, with no `..`), then a new commit and a new receipt")
|
|
548
|
+
check_evidence_symlinks_at(repo, commit, formalization, tree)
|
|
549
|
+
blob = git_show_bytes(repo, "./lake-manifest.json", commit)
|
|
550
|
+
if blob is None:
|
|
551
|
+
return
|
|
552
|
+
try:
|
|
553
|
+
outside = outside_path_deps(blob)
|
|
554
|
+
problems = path_dep_tree_problems(tree, blob)
|
|
555
|
+
except ValueError:
|
|
556
|
+
raise Fail(f"lake-manifest.json at {commit[:12]} is not valid JSON; cannot check its path "
|
|
557
|
+
f"dependencies") from None
|
|
558
|
+
if outside:
|
|
559
|
+
raise Fail(f"lake-manifest.json at {commit[:12]} has path dependencies outside the package directory: "
|
|
560
|
+
f"{', '.join(outside)}. The receipt does not bind their sources, so an edit to them would "
|
|
561
|
+
f"never count as drift. Require them from git pinned to a rev (lake-manifest.json then "
|
|
562
|
+
f"pins it) or move them inside the package directory; then a new commit and a new receipt")
|
|
563
|
+
if problems:
|
|
564
|
+
raise Fail(f"lake-manifest.json at {commit[:12]} has path dependencies the receipt does not bind: "
|
|
565
|
+
f"{'; '.join(problems)}. A path dependency must be a directory tracked in the package "
|
|
566
|
+
f"itself; require it from git pinned to a rev instead; then a new commit and a new receipt")
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def dirty_tracked(repo: pathlib.Path) -> list[str]:
|
|
570
|
+
"""Tracked files under the package directory that differ from HEAD (staged or not)."""
|
|
571
|
+
p = git(repo, "status", "--porcelain", "--untracked-files=no", "--", ".")
|
|
572
|
+
return [x[3:] for x in p.stdout.splitlines() if x.strip()]
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def dirty_guard(repo: pathlib.Path, name: str, refuse: bool) -> list[str]:
|
|
576
|
+
"""Evidence is judged at the bound commit, never the working tree; a dirty checkout is a WARN
|
|
577
|
+
on stderr (the lab's workflow edits while gating) or, with --refuse-dirty, a refusal. A checkout
|
|
578
|
+
off its default branch (or detached) is a second stderr WARN, never a refusal (#48)."""
|
|
579
|
+
dirty = dirty_tracked(repo)
|
|
580
|
+
if dirty:
|
|
581
|
+
shown = ", ".join(dirty[:5]) + (", ..." if len(dirty) > 5 else "")
|
|
582
|
+
msg = (f"{name}: {len(dirty)} tracked file(s) modified in the checkout ({shown}); "
|
|
583
|
+
f"receipts are checked against the bound commit, not these edits")
|
|
584
|
+
if refuse:
|
|
585
|
+
raise Fail(f"--refuse-dirty: {msg}; commit or stash them first")
|
|
586
|
+
print(f"WARN: {msg} (--refuse-dirty refuses)", file=sys.stderr)
|
|
587
|
+
notice = branch_notice(repo)
|
|
588
|
+
if notice: # #48: informational, never a refusal; evidence commits are often made detached
|
|
589
|
+
print(f"WARN: {notice}", file=sys.stderr)
|
|
590
|
+
return dirty
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
COMPARATOR_CONFIG_RE = re.compile(r"^(comparator[^/]*\.json|comparator/config[^/]*\.json)$")
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def cfg_name(path: str) -> str:
|
|
597
|
+
"""Same rule as comparator-check.sh / comparator-receipt: strip .json, '/' -> '_'."""
|
|
598
|
+
base = path[:-5] if path.endswith(".json") else path
|
|
599
|
+
return base.replace("/", "_")
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def head_comparator_configs(repo: pathlib.Path, rev: str = "HEAD") -> list[str]:
|
|
603
|
+
"""Every comparator configuration tracked at <rev> (the set the runner checks)."""
|
|
604
|
+
p = git(repo, "ls-tree", "-r", "--name-only", rev)
|
|
605
|
+
if p.returncode != 0:
|
|
606
|
+
return []
|
|
607
|
+
return sorted(x for x in p.stdout.splitlines() if COMPARATOR_CONFIG_RE.match(x))
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _safe_rel(path, what: str) -> str:
|
|
611
|
+
"""A repo-relative path: no leading '/', no '..' component."""
|
|
612
|
+
if not isinstance(path, str) or not path.strip():
|
|
613
|
+
raise Fail(f"comparator {what} path is empty")
|
|
614
|
+
pp = pathlib.PurePosixPath(path)
|
|
615
|
+
if pp.is_absolute() or ".." in pp.parts:
|
|
616
|
+
raise Fail(f"comparator {what} path must be repo-relative without '..': {path!r}")
|
|
617
|
+
return path
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
_WARNED: set[str] = set()
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def warn_once(msg: str) -> None:
|
|
624
|
+
"""A `lean-pkg: warning:` line, printed once per process (validators run many times per command)."""
|
|
625
|
+
if msg not in _WARNED:
|
|
626
|
+
_WARNED.add(msg)
|
|
627
|
+
print(f"lean-pkg: warning: {msg}", file=sys.stderr)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def sidecar_at(repo: pathlib.Path, rev: str = "HEAD") -> dict:
|
|
631
|
+
"""lean-pkg-signoff.json tracked at <rev> (holes.py), strictly parsed; empty when not tracked there.
|
|
632
|
+
Raises ValueError on a malformed file."""
|
|
633
|
+
return parse_sidecar(git_show_bytes(repo, SIGNOFF_SIDECAR, rev), f"{SIGNOFF_SIDECAR} at {rev[:12]}")
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def validate_comparator(pkg: dict, repo: pathlib.Path, comp: dict,
|
|
637
|
+
receipt_commit: str | None) -> None:
|
|
638
|
+
"""Re-derive a comparator PASS from bytes (see DESIGN.md). Fails closed."""
|
|
639
|
+
if not isinstance(comp, dict):
|
|
640
|
+
raise Fail("comparator receipt must be a JSON object")
|
|
641
|
+
for f in COMPARATOR_FIELDS:
|
|
642
|
+
if f not in comp:
|
|
643
|
+
raise Fail(f"comparator receipt missing required field {f!r}")
|
|
644
|
+
if comp.get("test_only"):
|
|
645
|
+
raise Fail("comparator receipt is marked test_only (produced under the test-only digest "
|
|
646
|
+
"override); it is not evidence")
|
|
647
|
+
if comp.get("partial"):
|
|
648
|
+
raise Fail("comparator receipt is marked partial (comparator-receipt --slots judged only a subset of "
|
|
649
|
+
"the slots); it is diagnostic, not evidence: run comparator-receipt without --slots")
|
|
650
|
+
schema = comp["schema"]
|
|
651
|
+
if schema not in COMPARATOR_SCHEMAS:
|
|
652
|
+
raise Fail(f"comparator schema must be one of {COMPARATOR_SCHEMAS}, got {schema!r}")
|
|
653
|
+
if schema == "comparator-receipt/1":
|
|
654
|
+
mechanism = "legacy"
|
|
655
|
+
else:
|
|
656
|
+
mechanism = comp.get("mechanism")
|
|
657
|
+
if mechanism not in COMPARATOR_MECHANISMS:
|
|
658
|
+
raise Fail(f"comparator mechanism must be one of {COMPARATOR_MECHANISMS}, "
|
|
659
|
+
f"got {mechanism!r}")
|
|
660
|
+
commit = str(comp["commit"])
|
|
661
|
+
if not re.fullmatch(r"[0-9a-f]{40}", commit):
|
|
662
|
+
raise Fail(f"comparator commit is not a full lowercase 40-hex sha: {commit!r}")
|
|
663
|
+
head = git_head(repo)
|
|
664
|
+
if head is None:
|
|
665
|
+
raise Fail(f"cannot resolve HEAD in {repo}")
|
|
666
|
+
ok, note, _docs = package_descendant(repo, commit, head, pkg)
|
|
667
|
+
if not ok:
|
|
668
|
+
raise Fail(f"comparator commit {commit[:12]}… != repo HEAD {head[:12]}… — "
|
|
669
|
+
f"the comparator receipt must bind to HEAD or an evidence-only "
|
|
670
|
+
f"descendant ({note})")
|
|
671
|
+
if receipt_commit and commit != receipt_commit:
|
|
672
|
+
raise Fail(f"comparator commit {commit[:12]}… != lower-tier receipt commit "
|
|
673
|
+
f"{receipt_commit[:12]}… — both tiers must bind to one commit")
|
|
674
|
+
check_toolchain_at(repo, commit, comp["lean_toolchain"], "comparator toolchain mismatch")
|
|
675
|
+
check_evidence_symlinks_at(repo, commit, formalization_rel(pkg))
|
|
676
|
+
tools = comp["tools"]
|
|
677
|
+
if not isinstance(tools, dict):
|
|
678
|
+
raise Fail("comparator tools must be a mapping")
|
|
679
|
+
if mechanism == "legacy":
|
|
680
|
+
for tname in COMPARATOR_TOOLS:
|
|
681
|
+
v = str(tools.get(tname) or "")
|
|
682
|
+
if not re.fullmatch(r"[0-9a-f]{40}", v):
|
|
683
|
+
raise Fail(f"comparator tools.{tname} must be a 40-hex commit, got {v!r}")
|
|
684
|
+
else:
|
|
685
|
+
if not str(tools.get("lean_toolchain") or "").strip():
|
|
686
|
+
raise Fail("comparator tools.lean_toolchain is empty (toolchain mechanism)")
|
|
687
|
+
for tname in COMPARATOR_TOOLCHAIN_DIGESTS:
|
|
688
|
+
v = str(tools.get(tname) or "")
|
|
689
|
+
if not re.fullmatch(r"[0-9a-f]{64}", v):
|
|
690
|
+
raise Fail(f"comparator tools.{tname} must be a 64-hex sha256, got {v!r}")
|
|
691
|
+
for f in ("host", "job_id", "generated_at"):
|
|
692
|
+
if not str(comp[f]).strip():
|
|
693
|
+
raise Fail(f"comparator field {f!r} is empty")
|
|
694
|
+
check_timestamp(comp["generated_at"], "comparator receipt")
|
|
695
|
+
if "ci" in comp: # additive (proposal 0008, S5): written on a GitHub-hosted runner, level 1
|
|
696
|
+
from . import ci_github
|
|
697
|
+
problems, _workflow = ci_github.level1(comp, repo)
|
|
698
|
+
if problems:
|
|
699
|
+
raise Fail("comparator ci block (a GitHub Actions run, level 1; docs/formats.md#the-ci-block): "
|
|
700
|
+
+ "; ".join(problems))
|
|
701
|
+
if comp["result"] != "pass":
|
|
702
|
+
raise Fail(f"comparator result must be 'pass', got {comp['result']!r}")
|
|
703
|
+
configs = comp["configs"]
|
|
704
|
+
if not isinstance(configs, list) or not configs:
|
|
705
|
+
raise Fail("comparator configs must be a non-empty list")
|
|
706
|
+
allowed = set((pkg.get("gate") or {}).get("axioms_allowed") or DEFAULT_AXIOMS)
|
|
707
|
+
listed = [_safe_rel(c.get("path"), "config") for c in configs if isinstance(c, dict)]
|
|
708
|
+
expected = head_comparator_configs(repo, commit)
|
|
709
|
+
if sorted(listed) != expected:
|
|
710
|
+
missing = sorted(set(expected) - set(listed))
|
|
711
|
+
extra = sorted(set(listed) - set(expected))
|
|
712
|
+
raise Fail(f"comparator receipt must list exactly the configs tracked at "
|
|
713
|
+
f"{commit[:12]} (bound commit; HEAD {head[:12]}): "
|
|
714
|
+
f"missing {missing}, extra/duplicate {extra}")
|
|
715
|
+
try:
|
|
716
|
+
sidecar = sidecar_at(repo, commit)
|
|
717
|
+
except ValueError as e:
|
|
718
|
+
raise Fail(str(e)) from None
|
|
719
|
+
for i, cfg in enumerate(configs):
|
|
720
|
+
if not isinstance(cfg, dict):
|
|
721
|
+
raise Fail(f"comparator configs[{i}] is not an object")
|
|
722
|
+
for f in COMPARATOR_CONFIG_FIELDS:
|
|
723
|
+
if f not in cfg:
|
|
724
|
+
raise Fail(f"comparator configs[{i}] missing field {f!r}")
|
|
725
|
+
path = _safe_rel(cfg["path"], "config")
|
|
726
|
+
if cfg["result"] != "pass":
|
|
727
|
+
raise Fail(f"comparator config {path} result must be 'pass', "
|
|
728
|
+
f"got {cfg['result']!r}")
|
|
729
|
+
blob = git_show_bytes(repo, path, commit)
|
|
730
|
+
if blob is None:
|
|
731
|
+
raise Fail(f"comparator config {path} is not tracked at {commit[:12]} (HEAD {head[:12]})")
|
|
732
|
+
if sha256_bytes(blob) != str(cfg["sha256"]).lower():
|
|
733
|
+
raise Fail(f"comparator config {path} sha256 mismatch against bytes at {commit[:12]}")
|
|
734
|
+
try:
|
|
735
|
+
blob_cfg = json.loads(blob)
|
|
736
|
+
except ValueError:
|
|
737
|
+
blob_cfg = None
|
|
738
|
+
if not isinstance(blob_cfg, dict):
|
|
739
|
+
raise Fail(f"comparator config {path} at {commit[:12]} is not a JSON object")
|
|
740
|
+
# #61: a list field the committed config omits (or sets to null) means [], exactly as the
|
|
741
|
+
# runner records it; any other difference, ["a"] vs [] included, is still a refusal.
|
|
742
|
+
for f in ("challenge_module", "solution_module", "theorem_names",
|
|
743
|
+
"definition_names", "permitted_axioms"):
|
|
744
|
+
want = blob_cfg.get(f)
|
|
745
|
+
if want is None and f in COMPARATOR_LIST_FIELDS:
|
|
746
|
+
want = []
|
|
747
|
+
if cfg[f] != want:
|
|
748
|
+
raise Fail(f"comparator config {path}: receipt {f} differs from the "
|
|
749
|
+
f"config at {commit[:12]} ({cfg[f]!r} vs {want!r})")
|
|
750
|
+
names = cfg["theorem_names"]
|
|
751
|
+
if not isinstance(names, list) or not names \
|
|
752
|
+
or not all(isinstance(n, str) and n for n in names):
|
|
753
|
+
raise Fail(f"comparator config {path}: theorem_names must be a "
|
|
754
|
+
f"non-empty list of strings")
|
|
755
|
+
ax = cfg["permitted_axioms"]
|
|
756
|
+
if not isinstance(ax, list) or not all(isinstance(a, str) for a in ax):
|
|
757
|
+
raise Fail(f"comparator config {path}: permitted_axioms must be a "
|
|
758
|
+
f"list of strings")
|
|
759
|
+
extra = sorted(set(ax) - allowed)
|
|
760
|
+
if extra:
|
|
761
|
+
raise Fail(f"comparator config {path}: permitted_axioms {extra} outside "
|
|
762
|
+
f"allowed set {sorted(allowed)}")
|
|
763
|
+
# Definition holes (value-blind in comparator) need a human sign-off, judged against the
|
|
764
|
+
# config bytes and lean-pkg-signoff.json at the bound commit, never the receipt's copy; a
|
|
765
|
+
# copy the receipt does carry (`signoff`, which the page renders) must equal it.
|
|
766
|
+
try:
|
|
767
|
+
so = check_definition_holes(blob_cfg, f"comparator config {path}", cfg_rel=path,
|
|
768
|
+
cfg_bytes=blob, sidecar=sidecar, warn=warn_once)
|
|
769
|
+
except ValueError as e:
|
|
770
|
+
raise Fail(str(e)) from None
|
|
771
|
+
if "signoff" in cfg and cfg["signoff"] != so:
|
|
772
|
+
raise Fail(f"comparator config {path}: the receipt's signoff copy differs from the sign-off "
|
|
773
|
+
f"in {SIGNOFF_SIDECAR} at {commit[:12]} (the receipt must record what was signed)")
|
|
774
|
+
log_rel = _safe_rel(cfg["log"], "log")
|
|
775
|
+
if not log_rel.startswith(".lean-receipts/"):
|
|
776
|
+
raise Fail(f"comparator log must live under .lean-receipts/: {log_rel!r}")
|
|
777
|
+
bound = f".lean-receipts/{commit[:12]}-comparator-{cfg_name(path)}.log"
|
|
778
|
+
if log_rel != bound:
|
|
779
|
+
raise Fail(f"comparator log for {path} must be {bound}, got {log_rel!r}")
|
|
780
|
+
if (repo / ".lean-receipts").is_symlink():
|
|
781
|
+
raise Fail(f"{repo}/.lean-receipts is a symlink; evidence must live inside the repo")
|
|
782
|
+
log_p = repo / log_rel
|
|
783
|
+
if log_p.is_symlink():
|
|
784
|
+
raise Fail(f"comparator log {log_rel} is a symlink; evidence must be a regular file")
|
|
785
|
+
if not log_p.is_file():
|
|
786
|
+
# Field report #5: a comparator log is looked up only under the package checkout, never
|
|
787
|
+
# beside the receipt (unlike the redacted verify log). The hint names where it looked and
|
|
788
|
+
# how to bring preserved evidence back; the refusal itself is unchanged.
|
|
789
|
+
raise Fail(f"comparator log missing: {log_rel} (package checkout {repo.absolute()}; "
|
|
790
|
+
f"tried {log_p.absolute()}). Comparator logs resolve relative to the package "
|
|
791
|
+
f"checkout only, never beside the receipt; if they were preserved elsewhere, "
|
|
792
|
+
f"restore each to the path its configs[].log names, byte-exact, and check it "
|
|
793
|
+
f"against its log_sha256 (docs/receipts.md, \"Restoring preserved evidence\"); "
|
|
794
|
+
f"nothing is rerun or resealed")
|
|
795
|
+
log_bytes = log_p.read_bytes()
|
|
796
|
+
# #21.2: a log produced after the bound commit cannot be read at that commit; once committed
|
|
797
|
+
# (at HEAD, an evidence-only descendant), the committed bytes are the evidence, so a working
|
|
798
|
+
# copy that differs from them is refused here rather than first at promote.
|
|
799
|
+
committed_log = git_show_bytes(repo, log_rel, "HEAD")
|
|
800
|
+
if committed_log is not None and committed_log != log_bytes:
|
|
801
|
+
raise Fail(f"comparator log {log_rel} differs from its copy committed at HEAD {head[:12]}; "
|
|
802
|
+
f"the committed bytes are the evidence: restore them (git checkout -- {log_rel}) "
|
|
803
|
+
f"or commit the new log with a receipt that names it")
|
|
804
|
+
if sha256_bytes(log_bytes) != str(cfg["log_sha256"]).lower():
|
|
805
|
+
raise Fail(f"comparator log_sha256 mismatch for {log_rel}")
|
|
806
|
+
lines = log_bytes.decode("utf-8", "replace").splitlines()
|
|
807
|
+
if not comparator_pass("\n".join(lines), mechanism):
|
|
808
|
+
raise Fail(f"comparator log {log_rel} has no PASS line for the {mechanism} mechanism "
|
|
809
|
+
f"({COMPARATOR_PASS_LINE!r} as a full line)")
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def binding_lines(pkg: dict, repo: pathlib.Path, commit: str, toolchain, checker=None) -> list[str]:
|
|
813
|
+
"""The ✓ lines of a validated binding (#26.2): commit vs HEAD, the formalization.yaml rule, the
|
|
814
|
+
toolchain at the bound commit. Called only after the validator passed, so every line is a pass."""
|
|
815
|
+
head = git_head(repo) or ""
|
|
816
|
+
_ok, note, docs = package_descendant(repo, commit, head, pkg, checker=checker)
|
|
817
|
+
out = [f"✓ binding: commit {commit[:12]} is HEAD" if commit == head
|
|
818
|
+
else docs_admission_line(head, commit, note) if docs is not None
|
|
819
|
+
else f"✓ binding: HEAD {head[:12]}: {note}"]
|
|
820
|
+
rel = formalization_rel(pkg)
|
|
821
|
+
if rel and commit != head:
|
|
822
|
+
changed = git(repo, "diff", "--no-renames", "--name-only", "--relative", commit, head, "--", rel)
|
|
823
|
+
out.append(f"✓ {rel}: only derived keys changed since {commit[:12]} (evidence-only rule)"
|
|
824
|
+
if changed.stdout.strip() else f"✓ {rel}: unchanged since {commit[:12]}")
|
|
825
|
+
elif not rel:
|
|
826
|
+
out.append("✓ formalization.yaml: no registry pointer, so no exception was applied")
|
|
827
|
+
out.append(f"✓ lean_toolchain {str(toolchain).strip()} = lean-toolchain committed at {commit[:12]}")
|
|
828
|
+
if git_show_bytes(repo, "./lake-manifest.json", commit) is not None:
|
|
829
|
+
out.append(f"✓ lake-manifest.json at {commit[:12]}: no path dependency outside the package directory")
|
|
830
|
+
out.append(f"✓ no symlink at {commit[:12]} leaves the package directory or points into .lean-receipts/")
|
|
831
|
+
return out
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
def receipt_check_lines(pkg: dict, repo: pathlib.Path, receipt: dict) -> list[str]:
|
|
835
|
+
allowed = sorted(set((pkg.get("gate") or {}).get("axioms_allowed") or DEFAULT_AXIOMS))
|
|
836
|
+
committed = committed_mathlib(repo, receipt["commit"])
|
|
837
|
+
rev, c12 = str(receipt["mathlib_rev"]).strip(), receipt["commit"][:12]
|
|
838
|
+
if committed == NO_MATHLIB:
|
|
839
|
+
mathlib = (f"✓ mathlib_rev {NO_MATHLIB}: lake-manifest.json committed at {c12} has no mathlib package"
|
|
840
|
+
if rev == NO_MATHLIB else
|
|
841
|
+
f"· mathlib_rev {rev} not checked: lake-manifest.json committed at {c12} has no mathlib "
|
|
842
|
+
f"package (a receipt written now says {NO_MATHLIB!r})")
|
|
843
|
+
elif committed:
|
|
844
|
+
mathlib = f"✓ mathlib_rev {rev} = the mathlib rev in lake-manifest.json committed at {c12}"
|
|
845
|
+
else:
|
|
846
|
+
mathlib = f"· mathlib_rev not checked: no readable mathlib entry in lake-manifest.json at {c12}"
|
|
847
|
+
return binding_lines(pkg, repo, receipt["commit"], receipt["lean_toolchain"], receipt.get("checker")) + [
|
|
848
|
+
mathlib,
|
|
849
|
+
"✓ sorry_count 0",
|
|
850
|
+
f"✓ axioms {sorted(receipt['axioms'])} within {allowed}",
|
|
851
|
+
*claim_axioms_lines(receipt),
|
|
852
|
+
*sacct_seal_lines(receipt),
|
|
853
|
+
*ci_check_lines(receipt, repo),
|
|
854
|
+
f"✓ mathlib_rev, report_sha256, job_id {receipt['job_id']}, checker, generated_at well-formed"]
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def ci_check_lines(receipt: dict, repo: pathlib.Path) -> list[str]:
|
|
858
|
+
"""The receipt's additive `ci` block (a GitHub Actions run, proposal 0008) at level 1, when present and
|
|
859
|
+
valid (validate_receipt refuses an invalid one), or the note that a gha- receipt without it backs nothing."""
|
|
860
|
+
from . import ci_github
|
|
861
|
+
return ci_github.check_lines(receipt, repo)
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def sacct_seal_lines(receipt: dict) -> list[str]:
|
|
865
|
+
"""The receipt's additive `slurm_sacct` block (`receipt slurm --seal-sacct`), when present and valid
|
|
866
|
+
(validate_receipt refuses an invalid one)."""
|
|
867
|
+
b = receipt.get("slurm_sacct")
|
|
868
|
+
if not isinstance(b, dict):
|
|
869
|
+
return []
|
|
870
|
+
return [f"✓ slurm_sacct: job {b.get('job')} COMPLETED, exit 0:0, {b.get('start')} .. {b.get('end')} contains "
|
|
871
|
+
f"generated_at; the sealed record {b.get('file')} is committed at HEAD and hashes to "
|
|
872
|
+
f"{str(b.get('sha256'))[:12]}"]
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def claim_axioms_lines(receipt: dict) -> list[str]:
|
|
876
|
+
"""The receipt's additive `claim_axioms` key (AX1), when present and valid (validate_receipt refuses an
|
|
877
|
+
invalid one): every claim's axioms read from the built environment, not only the printed theorems."""
|
|
878
|
+
ca = receipt.get("claim_axioms")
|
|
879
|
+
if not isinstance(ca, dict):
|
|
880
|
+
return []
|
|
881
|
+
extra = sorted({a for e in ca.get("nonstandard") or [] for a in e.get("axioms") or []})
|
|
882
|
+
return [f"✓ claim_axioms: {ca.get('checked')} claim(s) read from the built environment (every claim in "
|
|
883
|
+
f"claims.yaml), none missing" + (f"; beyond the standard three, allowed: {extra}" if extra else "")]
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def build_provenance_line(bp: dict) -> str:
|
|
887
|
+
"""One line for a comparator receipt's additive build_provenance (#56); never validated."""
|
|
888
|
+
src = bp.get("source")
|
|
889
|
+
tail = f" (source: {src})" if src else ""
|
|
890
|
+
# Lake's artifact cache writes oleans without compiling them: never counted as compiled (lake_hygiene)
|
|
891
|
+
cached = [f"{bp[k]} {what}" for k, what in (("restored", "olean(s) restored, not compiled"),
|
|
892
|
+
("cache_reused", "module(s) Lake reports reused from a cache"))
|
|
893
|
+
if isinstance(bp.get(k), int) and bp[k]]
|
|
894
|
+
cached_tail = f"; {', '.join(cached)}" if cached else ""
|
|
895
|
+
if bp.get("compiled") is True:
|
|
896
|
+
n = bp.get("modules_built")
|
|
897
|
+
return (f"build: compiled {n} module(s)" if isinstance(n, int) else "build: compiled") + tail + cached_tail
|
|
898
|
+
if bp.get("prebuilt") is True:
|
|
899
|
+
return f"build: prebuilt (source: {src or 'not declared'})" + cached_tail
|
|
900
|
+
if bp.get("compiled") is False:
|
|
901
|
+
return "build: no build stage ran (skipped)" + tail
|
|
902
|
+
return "build: provenance not recorded (the setup was prepared before build_provenance)" + tail
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def comparator_check_lines(pkg: dict, repo: pathlib.Path, comp: dict, lower_commit: str | None,
|
|
906
|
+
with_binding: bool = True) -> list[str]:
|
|
907
|
+
mech = "legacy" if comp.get("schema") == "comparator-receipt/1" else comp.get("mechanism")
|
|
908
|
+
out = binding_lines(pkg, repo, comp["commit"], comp["lean_toolchain"]) if with_binding else []
|
|
909
|
+
out.append(f"✓ comparator: {len(comp['configs'])} config(s) re-derived from bytes at {comp['commit'][:12]}, "
|
|
910
|
+
f"each log PASS ({mech} mechanism)")
|
|
911
|
+
out.append(f"✓ comparator commit = lower-tier receipt commit {lower_commit[:12]}" if lower_commit
|
|
912
|
+
else "· no lower-tier receipt to pair with (commit equality not checked)")
|
|
913
|
+
out += ci_check_lines(comp, repo) # proposal 0008, S5: a GitHub Actions run, level 1
|
|
914
|
+
if isinstance(comp.get("build_provenance"), dict): # #56: printed, never validated
|
|
915
|
+
out.append(f"· {build_provenance_line(comp['build_provenance'])}")
|
|
916
|
+
om = comp.get("olean_manifest")
|
|
917
|
+
if isinstance(om, dict): # printed, never validated (no oleans here to rehash)
|
|
918
|
+
out.append(f"· olean manifest: {om.get('files')} compiled module file(s), sha256 "
|
|
919
|
+
f"{str(om.get('sha256'))[:12]}… (captured at {om.get('captured')}; checked by the runner "
|
|
920
|
+
f"before and after the comparison)")
|
|
921
|
+
return out
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def claims_schema_at(name: str, pkg: dict, repo: pathlib.Path, commit: str) -> dict:
|
|
925
|
+
"""#58: the claims/1 schema check (claims.schema_check_text, the validator `claims sync` uses) on
|
|
926
|
+
the package's claims file as tracked at the gated commit, never the working tree, then
|
|
927
|
+
`claims sync`'s declaration check (claims.decl_problems) with each claim's file read at that same
|
|
928
|
+
commit, and the declared statements module's check (statements_module.problems, #369) at that commit.
|
|
929
|
+
{checked, commit, file, ok, claims, errors, declarations: {checked, ok, problems}}; `ok` is
|
|
930
|
+
False on either kind of problem; checked False (ok null) when no file is tracked there."""
|
|
931
|
+
from . import claims as claims_mod
|
|
932
|
+
from . import index as idx
|
|
933
|
+
rel = pkg.get("claims_file") or claims_mod.DEFAULT_CLAIMS_FILE
|
|
934
|
+
blob = git_show_bytes(repo, rel, commit)
|
|
935
|
+
unchecked = {"checked": False, "ok": None, "problems": []}
|
|
936
|
+
if blob is None:
|
|
937
|
+
return {"checked": False, "commit": commit, "file": rel, "ok": None, "claims": None, "errors": [],
|
|
938
|
+
"declarations": unchecked}
|
|
939
|
+
text = blob.decode("utf-8", errors="replace")
|
|
940
|
+
n, errors = claims_mod.schema_check_text(text, rel, name)
|
|
941
|
+
decls = unchecked
|
|
942
|
+
try:
|
|
943
|
+
listed = claims_mod.load_claims_text(text, rel).get("claims")
|
|
944
|
+
except Fail:
|
|
945
|
+
listed = None
|
|
946
|
+
# decl_problems needs a claim's id, decl and file; with schema errors present, only the claims
|
|
947
|
+
# whose three fields are well formed are looked up (no other rule is added).
|
|
948
|
+
usable = [c for c in (listed if isinstance(listed, list) else [])
|
|
949
|
+
if isinstance(c, dict) and isinstance(c.get("id"), str) and isinstance(c.get("decl"), str)
|
|
950
|
+
and idx._is_rel(c.get("file")) and str(c["file"]).endswith(".lean")]
|
|
951
|
+
if usable:
|
|
952
|
+
read = claims_mod._reader(repo, commit)
|
|
953
|
+
problems = claims_mod.decl_problems(read, usable) + claims_mod.evidence_problems(read, usable)
|
|
954
|
+
decls = {"checked": True, "ok": not problems, "problems": problems}
|
|
955
|
+
from . import statements_module as stm # #369: the declared statements module, at the same commit
|
|
956
|
+
statements, sproblems = stm.at_commit(repo, rel, commit)
|
|
957
|
+
if statements is not None and sproblems:
|
|
958
|
+
problems = list(decls["problems"]) + sproblems
|
|
959
|
+
decls = {"checked": True, "ok": False, "problems": problems}
|
|
960
|
+
return {"checked": True, "commit": commit, "file": rel, "ok": not errors and decls["ok"] is not False,
|
|
961
|
+
"claims": n, "errors": errors, "declarations": decls}
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def claims_problems(cs: dict) -> list[str]:
|
|
965
|
+
"""Schema errors first, then declaration problems in `claims sync`'s wording."""
|
|
966
|
+
return list(cs["errors"]) + list(cs.get("declarations", {}).get("problems", []))
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def claims_schema_line(cs: dict) -> str:
|
|
970
|
+
at = f"{cs['file']} at {str(cs['commit'])[:12]}"
|
|
971
|
+
if not cs["checked"]:
|
|
972
|
+
return f"· no {cs['file']} tracked at {str(cs['commit'])[:12]} (claims schema not checked)"
|
|
973
|
+
if cs["ok"]:
|
|
974
|
+
found = ", declarations found" if cs["declarations"]["checked"] else ""
|
|
975
|
+
return f"✓ {at}: schema ok ({cs['claims']} claims){found}"
|
|
976
|
+
problems = claims_problems(cs)
|
|
977
|
+
more = f" (+{len(problems) - 1} more)" if len(problems) > 1 else ""
|
|
978
|
+
return f"✗ {at}: {problems[0]}{more}"
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def load_json_object(path_arg, what: str) -> tuple[pathlib.Path, dict]:
|
|
982
|
+
p = pathlib.Path(str(path_arg)).expanduser()
|
|
983
|
+
if not p.is_file():
|
|
984
|
+
raise Fail(f"{what} not found: {p}")
|
|
985
|
+
try:
|
|
986
|
+
obj = json.loads(p.read_text())
|
|
987
|
+
except ValueError as e:
|
|
988
|
+
raise Fail(f"{what} is not valid JSON: {e}") from e
|
|
989
|
+
if not isinstance(obj, dict):
|
|
990
|
+
raise Fail(f"{what} must be a JSON object")
|
|
991
|
+
return p, obj
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
def locate_evidence_arg(path_arg, what: str, name: str, repo: pathlib.Path,
|
|
995
|
+
resolved: list | None = None) -> pathlib.Path:
|
|
996
|
+
"""The file a --receipt / --comparator argument names (field report #5). A path that exists as given
|
|
997
|
+
(relative to the caller's cwd, or absolute) is used as given. A relative path that does not exist
|
|
998
|
+
from the cwd but exists under the package's registered checkout (or --repo DIR) is resolved there,
|
|
999
|
+
and the resolution is announced on stderr and appended to `resolved`: the same relative path anchored
|
|
1000
|
+
at the checkout, never another matching receipt. Otherwise the refusal names the caller's cwd, the
|
|
1001
|
+
checkout, every path tried and how to pass the file."""
|
|
1002
|
+
p = pathlib.Path(str(path_arg)).expanduser()
|
|
1003
|
+
if p.is_file() or p.is_absolute():
|
|
1004
|
+
return p
|
|
1005
|
+
under = repo / p
|
|
1006
|
+
if under.is_file():
|
|
1007
|
+
note = (f"{name}: {what} {path_arg} does not exist relative to the cwd {pathlib.Path.cwd()}; "
|
|
1008
|
+
f"resolved against the package checkout: {under}")
|
|
1009
|
+
print(f"lean-pkg: note: {note}", file=sys.stderr)
|
|
1010
|
+
if resolved is not None:
|
|
1011
|
+
resolved.append({"what": what, "arg": str(path_arg), "path": str(under), "base": str(repo)})
|
|
1012
|
+
return under
|
|
1013
|
+
raise Fail(f"{what} not found: {path_arg} (caller cwd {pathlib.Path.cwd()}; package checkout {repo}; "
|
|
1014
|
+
f"tried {pathlib.Path.cwd() / p} and {under}). Pass an absolute path, run from the checkout, "
|
|
1015
|
+
f"or give a path relative to the checkout; for `gate --check` / `comparator --check` on "
|
|
1016
|
+
f"another checkout pass --repo DIR")
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
def replaced_comparator_rel(repo: pathlib.Path, commit: str) -> str:
|
|
1020
|
+
"""Where `comparator --replace` keeps the older receipt for `commit` (#21.1): beside it, never
|
|
1021
|
+
overwritten: .lean-receipts/<c12>-comparator.replaced-<UTC stamp>[-N].json."""
|
|
1022
|
+
stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
1023
|
+
base = f".lean-receipts/{commit[:12]}-comparator.replaced-{stamp}"
|
|
1024
|
+
rel, n = f"{base}.json", 1
|
|
1025
|
+
while (repo / rel).exists() or (repo / rel).is_symlink():
|
|
1026
|
+
n += 1
|
|
1027
|
+
rel = f"{base}-{n}.json"
|
|
1028
|
+
return rel
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
def evidence_dest_problem(repo: pathlib.Path, dest_rel: str) -> str | None:
|
|
1032
|
+
"""Why gate/comparator must not write `dest_rel` (under .lean-receipts/): .lean-receipts itself or the
|
|
1033
|
+
destination is a symlink (a planted link would carry the write outside the repository), or the
|
|
1034
|
+
directory is not a directory. None when the write may go ahead."""
|
|
1035
|
+
d = repo / ".lean-receipts"
|
|
1036
|
+
if d.is_symlink():
|
|
1037
|
+
return f"{d} is a symlink; refusing to write evidence through it (nothing copied or recorded)"
|
|
1038
|
+
if d.exists() and not d.is_dir():
|
|
1039
|
+
return f"{d} is not a directory (nothing copied or recorded)"
|
|
1040
|
+
dest = repo / dest_rel
|
|
1041
|
+
if dest.is_symlink():
|
|
1042
|
+
return f"{dest} is a symlink; refusing to write through it (remove it; nothing copied or recorded)"
|
|
1043
|
+
if dest.exists() and not dest.is_file():
|
|
1044
|
+
return f"{dest} is not a regular file (nothing copied or recorded)"
|
|
1045
|
+
return None
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
def plan_comparator_copy(repo: pathlib.Path, commit: str, src: pathlib.Path,
|
|
1049
|
+
replace: bool = False) -> dict:
|
|
1050
|
+
"""Every check copy_comparator makes, before anything is written (gate runs it before it copies the
|
|
1051
|
+
lower-tier receipt, so a refusal writes nothing): {dest_rel, action: present | copy | replace, moved}."""
|
|
1052
|
+
dest_rel = f".lean-receipts/{commit[:12]}-comparator.json"
|
|
1053
|
+
dest = repo / dest_rel
|
|
1054
|
+
why = evidence_dest_problem(repo, dest_rel)
|
|
1055
|
+
if why:
|
|
1056
|
+
raise Fail(why)
|
|
1057
|
+
if not dest.exists():
|
|
1058
|
+
return {"dest_rel": dest_rel, "action": "copy", "moved": None}
|
|
1059
|
+
if recorded_json(repo, dest_rel) == json.loads(src.read_text()):
|
|
1060
|
+
return {"dest_rel": dest_rel, "action": "present", "moved": None}
|
|
1061
|
+
if not replace:
|
|
1062
|
+
raise Fail(f"{dest} already holds a different comparator receipt for commit {commit[:12]}; "
|
|
1063
|
+
f"to keep it, pass that file (--receipt {dest}); to record the newer one, re-run "
|
|
1064
|
+
f"with --replace (the older file is kept beside it as "
|
|
1065
|
+
f".lean-receipts/{commit[:12]}-comparator.replaced-<UTC stamp>.json and the event "
|
|
1066
|
+
f"is comparator-replaced)")
|
|
1067
|
+
moved = replaced_comparator_rel(repo, commit)
|
|
1068
|
+
return {"dest_rel": dest_rel, "action": "replace", "moved": moved}
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def apply_comparator_copy(repo: pathlib.Path, plan: dict, src: pathlib.Path) -> tuple[str, str, str | None]:
|
|
1072
|
+
"""(path of the receipt in the repo, note, where the replaced older receipt now lives or None)."""
|
|
1073
|
+
dest_rel, moved = plan["dest_rel"], plan["moved"]
|
|
1074
|
+
dest = repo / dest_rel
|
|
1075
|
+
if plan["action"] == "present":
|
|
1076
|
+
return dest_rel, f"comparator receipt already present at {dest_rel} (not re-copied)", None
|
|
1077
|
+
if moved:
|
|
1078
|
+
os.replace(dest, repo / moved)
|
|
1079
|
+
dest.parent.mkdir(exist_ok=True)
|
|
1080
|
+
shutil.copy2(src, dest)
|
|
1081
|
+
note = (f"comparator receipt copied to {dest} — NOT committed there; "
|
|
1082
|
+
f"commit it with its logs in the verified repo yourself")
|
|
1083
|
+
if moved:
|
|
1084
|
+
note += f"; the older receipt for this commit is kept at {moved} (commit that too)"
|
|
1085
|
+
return dest_rel, note, moved
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
def copy_comparator(repo: pathlib.Path, commit: str, src: pathlib.Path,
|
|
1089
|
+
replace: bool = False) -> tuple[str, str, str | None]:
|
|
1090
|
+
"""(path of the receipt in the repo, note, where the replaced older receipt now lives or None)."""
|
|
1091
|
+
return apply_comparator_copy(repo, plan_comparator_copy(repo, commit, src, replace), src)
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
REPORT_LOG_SUFFIX = "-verify.redacted.log"
|
|
1095
|
+
# A compressed sealed log (`receipt slurm|systemd --compress-log`) is `<log name>.gz`: deterministic gzip
|
|
1096
|
+
# (level 9, mtime 0, no file name in the header). report_sha256 stays the SHA-256 of the UNCOMPRESSED log;
|
|
1097
|
+
# the receipt's additive `report_compressed` {format: gzip, sha256: <of the .gz>, bytes: <decoded (uncompressed)
|
|
1098
|
+
# length>} binds the .gz itself and bounds its decompression.
|
|
1099
|
+
REPORT_GZ_SUFFIX = ".gz"
|
|
1100
|
+
REPORT_GZ_LEVEL = 9
|
|
1101
|
+
# The decompression bound for a .gz whose receipt records no `report_compressed.bytes` (a log compressed by
|
|
1102
|
+
# hand for an older receipt): output past it is refused, never hashed further (gzip-bomb guard).
|
|
1103
|
+
REPORT_GZ_DEFAULT_CAP = 4 << 30
|
|
1104
|
+
_CHUNK = 1 << 20
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
def gzip_deterministic(data: bytes) -> bytes:
|
|
1108
|
+
"""`data` as gzip with a fixed header (no file name, mtime 0, OS byte 255) at level 9: the same bytes
|
|
1109
|
+
for the same input and zlib, on every host and at every time."""
|
|
1110
|
+
buf = io.BytesIO()
|
|
1111
|
+
with gzip.GzipFile(filename="", mode="wb", compresslevel=REPORT_GZ_LEVEL, fileobj=buf, mtime=0) as g:
|
|
1112
|
+
g.write(data)
|
|
1113
|
+
return buf.getvalue()
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
def gunzip_digest(src, limit: int, what: str) -> tuple[str, int]:
|
|
1117
|
+
"""(sha256, length) of the decompressed stream of `src` (a path or bytes), read in chunks and never
|
|
1118
|
+
past `limit` bytes of output: more refuses (gzip-bomb guard), and so does a stream that is not valid
|
|
1119
|
+
gzip (bad header, CRC or length check, truncated)."""
|
|
1120
|
+
h, n = hashlib.sha256(), 0
|
|
1121
|
+
try:
|
|
1122
|
+
with (open(src, "rb") if isinstance(src, (str, os.PathLike)) else io.BytesIO(src)) as raw, \
|
|
1123
|
+
gzip.GzipFile(fileobj=raw, mode="rb") as g:
|
|
1124
|
+
while True:
|
|
1125
|
+
chunk = g.read(min(_CHUNK, limit - n + 1))
|
|
1126
|
+
if not chunk:
|
|
1127
|
+
break
|
|
1128
|
+
n += len(chunk)
|
|
1129
|
+
if n > limit:
|
|
1130
|
+
raise Fail(f"{what} decompresses to more than the {limit} bytes the receipt allows "
|
|
1131
|
+
f"(report_compressed.bytes); refused without reading further")
|
|
1132
|
+
h.update(chunk)
|
|
1133
|
+
except (OSError, EOFError, zlib.error) as e:
|
|
1134
|
+
raise Fail(f"{what} is not a valid gzip stream ({e.__class__.__name__}: {e}); the compressed log "
|
|
1135
|
+
f"cannot be checked against report_sha256") from None
|
|
1136
|
+
return h.hexdigest(), n
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def report_compressed_bound(receipt: dict) -> tuple[int, str | None]:
|
|
1140
|
+
"""(decompression limit, the .gz SHA-256 or None) from the receipt's optional `report_compressed`;
|
|
1141
|
+
a malformed value refuses. It never replaces report_sha256, which is always the uncompressed hash."""
|
|
1142
|
+
rc = receipt.get("report_compressed")
|
|
1143
|
+
if rc is None:
|
|
1144
|
+
return REPORT_GZ_DEFAULT_CAP, None
|
|
1145
|
+
if not isinstance(rc, dict) or rc.get("format") != "gzip":
|
|
1146
|
+
raise Fail("report_compressed must be {format: \"gzip\", sha256, bytes}, got "
|
|
1147
|
+
f"{json.dumps(rc)[:80]}")
|
|
1148
|
+
gz_sha, size = rc.get("sha256"), rc.get("bytes")
|
|
1149
|
+
if not (isinstance(gz_sha, str) and re.fullmatch(r"[0-9a-fA-F]{64}", gz_sha)):
|
|
1150
|
+
raise Fail("report_compressed.sha256 must be 64 hex chars (the SHA-256 of the .gz file)")
|
|
1151
|
+
if isinstance(size, bool) or not isinstance(size, int) or size < 0:
|
|
1152
|
+
raise Fail("report_compressed.bytes must be a non-negative integer (the uncompressed log's length)")
|
|
1153
|
+
if gz_sha.lower() == str(receipt.get("report_sha256", "")).lower():
|
|
1154
|
+
raise Fail("report_compressed.sha256 equals report_sha256: report_sha256 must be the SHA-256 of the "
|
|
1155
|
+
"uncompressed log, never of the .gz")
|
|
1156
|
+
return size, gz_sha.lower()
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
def _file_sha256(path: pathlib.Path) -> str:
|
|
1160
|
+
h = hashlib.sha256()
|
|
1161
|
+
with open(path, "rb") as f:
|
|
1162
|
+
for chunk in iter(lambda: f.read(_CHUNK), b""):
|
|
1163
|
+
h.update(chunk)
|
|
1164
|
+
return h.hexdigest()
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
def report_log_name(receipt: dict) -> str:
|
|
1168
|
+
return f"{str(receipt['commit'])[:12]}-{receipt_job_slug(receipt['job_id'])}{REPORT_LOG_SUFFIX}"
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def report_log_check(repo: pathlib.Path, receipt: dict, receipt_path: pathlib.Path) -> tuple[str, dict]:
|
|
1172
|
+
"""report_sha256 against the redacted verify log `receipt slurm|systemd` writes beside the receipt
|
|
1173
|
+
(<c12>-<job slug>-verify.redacted.log, or that name + .gz with --compress-log): looked for beside the
|
|
1174
|
+
--receipt file, in the package's .lean-receipts/ and tracked there at HEAD. Every copy found must hash
|
|
1175
|
+
to report_sha256 (a mismatch refuses); a .gz copy is stream-decompressed (bounded by
|
|
1176
|
+
report_compressed.bytes) and its UNCOMPRESSED bytes must hash to report_sha256, with that length, and
|
|
1177
|
+
the .gz itself to report_compressed.sha256 when recorded. None found, or a copy that cannot be read,
|
|
1178
|
+
is a refusal too (report_log_missing): a receipt whose report_sha256 binds nothing is not evidence.
|
|
1179
|
+
(line, {checked, log, where})."""
|
|
1180
|
+
name = report_log_name(receipt)
|
|
1181
|
+
gz = name + REPORT_GZ_SUFFIX
|
|
1182
|
+
want = str(receipt["report_sha256"]).lower()
|
|
1183
|
+
limit, gz_want = report_compressed_bound(receipt)
|
|
1184
|
+
found: list[tuple[str, str, object]] = [] # (where, file name, path or bytes)
|
|
1185
|
+
seen: set[str] = set()
|
|
1186
|
+
for where, base in (("beside the receipt", receipt_path.parent), (".lean-receipts/", repo / ".lean-receipts")):
|
|
1187
|
+
for fname in (name, gz):
|
|
1188
|
+
path = base / fname
|
|
1189
|
+
key = os.path.realpath(path)
|
|
1190
|
+
if key in seen or not path.is_file():
|
|
1191
|
+
continue
|
|
1192
|
+
seen.add(key)
|
|
1193
|
+
found.append((where, fname, path))
|
|
1194
|
+
for fname in (name, gz):
|
|
1195
|
+
blob = git_show_bytes(repo, f"./.lean-receipts/{fname}", "HEAD")
|
|
1196
|
+
if blob is not None:
|
|
1197
|
+
found.append(("tracked at HEAD", fname, blob))
|
|
1198
|
+
if not found:
|
|
1199
|
+
raise Fail(report_log_missing(repo, receipt, receipt_path))
|
|
1200
|
+
try:
|
|
1201
|
+
wheres = _report_log_verify(found, name, gz, want, limit, gz_want)
|
|
1202
|
+
except OSError as e:
|
|
1203
|
+
raise Fail(report_log_missing(repo, receipt, receipt_path,
|
|
1204
|
+
f"a copy cannot be read ({e.__class__.__name__}: {e.strerror or e})")) from None
|
|
1205
|
+
return (f"✓ report_sha256 = sha256 of {name} ({', '.join(wheres)})",
|
|
1206
|
+
{"checked": True, "log": name, "where": wheres})
|
|
1207
|
+
|
|
1208
|
+
|
|
1209
|
+
REPORT_LOG_RESTORE = 'docs/receipts.md, "Restoring preserved evidence"'
|
|
1210
|
+
REPORT_LOG_MISSING = "report log missing: "
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
def report_log_rels(repo: pathlib.Path, receipt: dict) -> list[str]:
|
|
1214
|
+
"""The sealed log copies (.log, .log.gz) of a lower-tier receipt present under the package's
|
|
1215
|
+
.lean-receipts/ (package-relative): the files `promote` needs committed beside the receipt."""
|
|
1216
|
+
try:
|
|
1217
|
+
name = report_log_name(receipt)
|
|
1218
|
+
except (Fail, KeyError):
|
|
1219
|
+
return []
|
|
1220
|
+
return [f".lean-receipts/{f}" for f in (name, name + REPORT_GZ_SUFFIX) if (repo / ".lean-receipts" / f).is_file()]
|
|
1221
|
+
|
|
1222
|
+
|
|
1223
|
+
def recorded_report_log_problem(repo: pathlib.Path, receipt: dict, rel: str) -> str | None:
|
|
1224
|
+
"""report_log_check for a recorded lower-tier receipt (`rel`, package-relative): None when its sealed
|
|
1225
|
+
log is there and hashes to report_sha256, else the refusal text (missing, unreadable or mismatched).
|
|
1226
|
+
Every consumer that judges a recorded receipt (ledger, next, comparator, palomar, promote) uses this, so
|
|
1227
|
+
none accepts a receipt `gate` would refuse."""
|
|
1228
|
+
try:
|
|
1229
|
+
report_log_check(repo, receipt, repo / rel)
|
|
1230
|
+
except Fail as e:
|
|
1231
|
+
return str(e)
|
|
1232
|
+
return None
|
|
1233
|
+
|
|
1234
|
+
|
|
1235
|
+
SEALED_LOG_TEXT_CAP = 256 << 20 # sealed_log_text reads no more than this (uncompressed) into memory
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def sealed_log_text(repo: pathlib.Path, receipt: dict, rel: str) -> str | None:
|
|
1239
|
+
"""The text of a recorded lower-tier receipt's sealed verify log: the first copy report_log_check looks at
|
|
1240
|
+
(beside the receipt `rel`, in .lean-receipts/, tracked there at HEAD; the .log, else its .gz decompressed)
|
|
1241
|
+
whose uncompressed bytes hash to report_sha256. None when there is none, it cannot be read, or it is larger
|
|
1242
|
+
than SEALED_LOG_TEXT_CAP: a reader of the log's facts (the claims ledger, proposal 0003) then has none."""
|
|
1243
|
+
try:
|
|
1244
|
+
name = report_log_name(receipt)
|
|
1245
|
+
want = str(receipt["report_sha256"]).lower()
|
|
1246
|
+
except (Fail, KeyError, TypeError):
|
|
1247
|
+
return None
|
|
1248
|
+
cands: list = []
|
|
1249
|
+
for base in ((repo / rel).parent, repo / ".lean-receipts"):
|
|
1250
|
+
cands += [(base / name, False), (base / (name + REPORT_GZ_SUFFIX), True)]
|
|
1251
|
+
for fname, unpack in ((name, False), (name + REPORT_GZ_SUFFIX, True)):
|
|
1252
|
+
cands.append((lambda f=fname: git_show_bytes(repo, f"./.lean-receipts/{f}", "HEAD"), unpack))
|
|
1253
|
+
for src, unpack in cands:
|
|
1254
|
+
try:
|
|
1255
|
+
if isinstance(src, pathlib.Path):
|
|
1256
|
+
if not src.is_file() or src.stat().st_size > SEALED_LOG_TEXT_CAP:
|
|
1257
|
+
continue
|
|
1258
|
+
data = src.read_bytes()
|
|
1259
|
+
else:
|
|
1260
|
+
data = src()
|
|
1261
|
+
if data is None:
|
|
1262
|
+
continue
|
|
1263
|
+
if unpack:
|
|
1264
|
+
with gzip.GzipFile(fileobj=io.BytesIO(data), mode="rb") as g:
|
|
1265
|
+
data = g.read(SEALED_LOG_TEXT_CAP + 1)
|
|
1266
|
+
if len(data) > SEALED_LOG_TEXT_CAP:
|
|
1267
|
+
continue
|
|
1268
|
+
except (OSError, EOFError, zlib.error):
|
|
1269
|
+
continue
|
|
1270
|
+
if sha256_bytes(data) == want:
|
|
1271
|
+
return data.decode("utf-8", "replace")
|
|
1272
|
+
return None
|
|
1273
|
+
|
|
1274
|
+
|
|
1275
|
+
def report_log_missing(repo: pathlib.Path, receipt: dict, receipt_path: pathlib.Path,
|
|
1276
|
+
why: str = "none found") -> str:
|
|
1277
|
+
"""The refusal for a lower-tier receipt whose redacted verify log is not there to hash: where it was
|
|
1278
|
+
looked for, the path it must be restored to, and how (byte-exact, never rerun or resealed)."""
|
|
1279
|
+
name = report_log_name(receipt)
|
|
1280
|
+
want = str(receipt.get("report_sha256") or "").lower()
|
|
1281
|
+
return (f"{REPORT_LOG_MISSING}{name} (or {name}{REPORT_GZ_SUFFIX}): {why}; looked beside the receipt "
|
|
1282
|
+
f"({receipt_path.parent.absolute()}), in {(repo / '.lean-receipts').absolute()} and tracked there at "
|
|
1283
|
+
f"HEAD. Without it report_sha256 binds nothing, so the receipt is not evidence. Restore the sealed "
|
|
1284
|
+
f"redacted log byte-exact to .lean-receipts/{name} (a copy kept under another name may be copied "
|
|
1285
|
+
f"there when its SHA-256 is the receipt's report_sha256 {want[:16]}...) and commit it ({REPORT_LOG_RESTORE}); "
|
|
1286
|
+
f"never rerun or reseal it. A receipt whose log is lost needs a new run")
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def _report_log_verify(found: list, name: str, gz: str, want: str, limit: int, gz_want: str | None) -> list[str]:
|
|
1290
|
+
"""Hash every copy report_log_check found; a mismatch refuses. [where]; OSError propagates."""
|
|
1291
|
+
wheres = []
|
|
1292
|
+
for where, fname, src in found:
|
|
1293
|
+
if fname == name:
|
|
1294
|
+
got = _file_sha256(src) if isinstance(src, pathlib.Path) else sha256_bytes(src)
|
|
1295
|
+
if got != want:
|
|
1296
|
+
raise Fail(f"report_sha256 mismatch: {name} ({where}) hashes to {got}, the receipt says {want}; "
|
|
1297
|
+
f"the redacted log is not the one the receipt binds")
|
|
1298
|
+
wheres.append(where)
|
|
1299
|
+
continue
|
|
1300
|
+
if gz_want is not None:
|
|
1301
|
+
got = _file_sha256(src) if isinstance(src, pathlib.Path) else sha256_bytes(src)
|
|
1302
|
+
if got != gz_want:
|
|
1303
|
+
raise Fail(f"report_compressed.sha256 mismatch: {gz} ({where}) hashes to {got}, the receipt says "
|
|
1304
|
+
f"{gz_want}; the compressed log is not the one the receipt binds")
|
|
1305
|
+
got, n = gunzip_digest(src, limit, f"{gz} ({where})")
|
|
1306
|
+
if got != want:
|
|
1307
|
+
raise Fail(f"report_sha256 mismatch: {gz} ({where}) decompresses to bytes hashing to {got}, the receipt "
|
|
1308
|
+
f"says {want}; the redacted log is not the one the receipt binds (report_sha256 is the "
|
|
1309
|
+
f"SHA-256 of the uncompressed log, never of the .gz)")
|
|
1310
|
+
if gz_want is not None and n != limit:
|
|
1311
|
+
raise Fail(f"report_compressed.bytes mismatch: {gz} ({where}) decompresses to {n} bytes, the receipt "
|
|
1312
|
+
f"says {limit}")
|
|
1313
|
+
wheres.append(f"{where}, decompressed from .gz")
|
|
1314
|
+
return wheres
|
|
1315
|
+
|
|
1316
|
+
|
|
1317
|
+
def plan_report_log_copy(repo: pathlib.Path, receipt: dict, receipt_path: pathlib.Path) -> list[tuple[pathlib.Path, str]]:
|
|
1318
|
+
"""The sealed log copies `gate` adds beside the canonical receipt .lean-receipts/<c12>-<job>.json, so
|
|
1319
|
+
that copy still verifies (field report: a receipt passed from a nested or outside path left its log
|
|
1320
|
+
behind): each form (.log, .log.gz) found beside the --receipt file, when .lean-receipts/ holds neither.
|
|
1321
|
+
Run after report_log_check (which verified every copy). [(source, dest_rel)]; refusals as for the
|
|
1322
|
+
receipt copy (a symlinked .lean-receipts or destination)."""
|
|
1323
|
+
name = report_log_name(receipt)
|
|
1324
|
+
canon = repo / ".lean-receipts"
|
|
1325
|
+
src_dir = receipt_path.parent
|
|
1326
|
+
if canon.is_dir() and os.path.realpath(src_dir) == os.path.realpath(canon):
|
|
1327
|
+
return []
|
|
1328
|
+
forms = (name, name + REPORT_GZ_SUFFIX)
|
|
1329
|
+
plan = [(src_dir / f, f".lean-receipts/{f}") for f in forms if (src_dir / f).is_file()]
|
|
1330
|
+
if not plan:
|
|
1331
|
+
return []
|
|
1332
|
+
for f in forms:
|
|
1333
|
+
why = evidence_dest_problem(repo, f".lean-receipts/{f}")
|
|
1334
|
+
if why:
|
|
1335
|
+
raise Fail(why)
|
|
1336
|
+
if any((canon / f).exists() for f in forms):
|
|
1337
|
+
return []
|
|
1338
|
+
return plan
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def receipt_private_strings(blobs: list[tuple[str, bytes]], refuse: bool,
|
|
1342
|
+
sink: list | None = None) -> list[dict]:
|
|
1343
|
+
"""Scan receipt bytes (keys and values) for private strings before they are copied into the
|
|
1344
|
+
repository. Each hit is {"field", "kind"} (the private text itself is never echoed). With
|
|
1345
|
+
`refuse`, any hit is a refusal; otherwise the hits are returned (and appended to `sink`) and
|
|
1346
|
+
the caller prints them with warn_private once it knows what happened to the receipt."""
|
|
1347
|
+
from .index import private_string_hits
|
|
1348
|
+
hits = [{"field": f, "kind": k} for where, blob in blobs
|
|
1349
|
+
for f, k, _ in private_string_hits(blob, where)]
|
|
1350
|
+
if hits and refuse:
|
|
1351
|
+
raise Fail("--refuse-private: receipt holds private strings, nothing copied: "
|
|
1352
|
+
+ "; ".join(f"{h['field']} ({h['kind']})" for h in hits))
|
|
1353
|
+
if sink is not None:
|
|
1354
|
+
sink.extend(hits)
|
|
1355
|
+
return hits
|
|
1356
|
+
|
|
1357
|
+
|
|
1358
|
+
# What happened to the receipt, by outcome event, for the private-string WARN line. A receipt that was
|
|
1359
|
+
# accepted says "kept"; only a refusal for another reason says nothing was copied (field report: the old
|
|
1360
|
+
# default read "refused" on a receipt `gate --check` had accepted).
|
|
1361
|
+
PRIVATE_WARN_OUTCOME = {
|
|
1362
|
+
"gate-passed": "kept: the receipt is now in .lean-receipts/ as is",
|
|
1363
|
+
"regated": "kept: the receipt is now in .lean-receipts/ as is",
|
|
1364
|
+
"comparator-attached": "kept: the receipt is now in .lean-receipts/ as is",
|
|
1365
|
+
"comparator-replaced": "kept: the receipt is now in .lean-receipts/ as is",
|
|
1366
|
+
"already-gated": "kept: already recorded; nothing copied now",
|
|
1367
|
+
"already-attached": "kept: already recorded; nothing copied now",
|
|
1368
|
+
"gate-checked": "not refused for it; nothing copied (--check)",
|
|
1369
|
+
"comparator-checked": "not refused for it; nothing copied (--check)",
|
|
1370
|
+
None: "nothing copied: refused for another reason, below",
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
|
|
1374
|
+
def warn_private(hits: list[dict], event: str | None) -> None:
|
|
1375
|
+
outcome = PRIVATE_WARN_OUTCOME.get(event, PRIVATE_WARN_OUTCOME[None])
|
|
1376
|
+
for h in hits:
|
|
1377
|
+
print(f"WARN: receipt field {h['field']} contains a {h['kind']} "
|
|
1378
|
+
f"({outcome}; --refuse-private refuses such a receipt)", file=sys.stderr)
|
|
1379
|
+
|
|
1380
|
+
|
|
1381
|
+
def _with_private_warnings(fn, *args, **kwargs) -> tuple[list[str], dict]:
|
|
1382
|
+
"""Run do_gate/do_comparator's body and print the private-string WARN lines worded for
|
|
1383
|
+
the outcome: copied, already recorded, --check, or refused for another reason."""
|
|
1384
|
+
sink: list[dict] = []
|
|
1385
|
+
try:
|
|
1386
|
+
out, payload = fn(*args, private_sink=sink, **kwargs)
|
|
1387
|
+
except Fail:
|
|
1388
|
+
warn_private(sink, None)
|
|
1389
|
+
raise
|
|
1390
|
+
warn_private(sink, payload.get("event"))
|
|
1391
|
+
return out, payload
|
|
1392
|
+
|
|
1393
|
+
|
|
1394
|
+
def recorded_json(repo: pathlib.Path, rel) -> dict | None:
|
|
1395
|
+
if not rel:
|
|
1396
|
+
return None
|
|
1397
|
+
try:
|
|
1398
|
+
return json.loads((repo / rel).read_text())
|
|
1399
|
+
except Exception:
|
|
1400
|
+
return None
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
REGATE_STATUSES = ("verified-private", "public")
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
def to_gate_pending_cmd(name: str, commit: str) -> str:
|
|
1407
|
+
"""The exact move an `active` package needs before its first gate (field report: the receipt's
|
|
1408
|
+
`next:` hint led to a gate refusal that did not say how to get to gate-pending)."""
|
|
1409
|
+
what = f"receipt for {commit[:12]} ready" if commit else "receipt ready"
|
|
1410
|
+
return f'`lean-pkg update {name} --status gate-pending --reason "{what}"`'
|
|
1411
|
+
|
|
1412
|
+
|
|
1413
|
+
def regate_status_problem(name: str, pkg: dict) -> str | None:
|
|
1414
|
+
"""Why `gate --regate` cannot apply to this package (#67), or None: it re-gates a gated package, so the
|
|
1415
|
+
status is verified-private (or public, which `gate` already accepts) and a gate receipt is recorded."""
|
|
1416
|
+
status = pkg.get("status")
|
|
1417
|
+
if status not in REGATE_STATUSES:
|
|
1418
|
+
return (f"{name}: --regate re-gates a gated package (verified-private or public), got {status!r}; "
|
|
1419
|
+
f"use `lean-pkg gate {name} --receipt R` without --regate")
|
|
1420
|
+
if not (pkg.get("gate") or {}).get("receipt"):
|
|
1421
|
+
return (f"{name}: --regate: no gate receipt is recorded, so there is nothing to re-gate; "
|
|
1422
|
+
f"use `lean-pkg gate {name} --receipt R` without --regate")
|
|
1423
|
+
return None
|
|
1424
|
+
|
|
1425
|
+
|
|
1426
|
+
def regate_lineage(name: str, pkg: dict, repo: pathlib.Path, commit: str,
|
|
1427
|
+
reason: str | None) -> tuple[str | None, bool, str | None]:
|
|
1428
|
+
"""(previous_commit, non_descendant, problem) for `gate --regate` (#67): the new receipt's commit must
|
|
1429
|
+
descend from the commit of the recorded gate receipt (`git merge-base --is-ancestor`); a --reason
|
|
1430
|
+
accepts any other commit, recorded as non_descendant. An unreadable recorded receipt has no commit to
|
|
1431
|
+
compare, which needs a --reason too."""
|
|
1432
|
+
rec = recorded_json(repo, (pkg.get("gate") or {}).get("receipt"))
|
|
1433
|
+
prev = str(rec["commit"]) if isinstance(rec, dict) and rec.get("commit") else None
|
|
1434
|
+
if prev and _is_ancestor(repo, prev, commit):
|
|
1435
|
+
return prev, False, None
|
|
1436
|
+
if reason:
|
|
1437
|
+
return prev, True, None
|
|
1438
|
+
if prev is None:
|
|
1439
|
+
return None, False, (f"{name}: --regate: the recorded gate receipt "
|
|
1440
|
+
f"{(pkg.get('gate') or {}).get('receipt')!r} is missing or has no commit, so the "
|
|
1441
|
+
f"new commit cannot be checked as its descendant; pass --reason TEXT to re-gate "
|
|
1442
|
+
f"anyway (recorded as non_descendant)")
|
|
1443
|
+
return prev, False, (f"{name}: --regate: receipt commit {commit[:12]} is not a descendant of the gated "
|
|
1444
|
+
f"commit {prev[:12]}; pass --reason TEXT to re-gate it anyway (recorded as "
|
|
1445
|
+
f"non_descendant: true)")
|
|
1446
|
+
|
|
1447
|
+
|
|
1448
|
+
def _same_rev(a: str, b: str) -> bool:
|
|
1449
|
+
return bool(a and b) and (a.startswith(b) or b.startswith(a))
|
|
1450
|
+
|
|
1451
|
+
|
|
1452
|
+
# The explicit mathlib_rev of a package without Mathlib: its lake-manifest.json is readable and lists no
|
|
1453
|
+
# `mathlib` package. A value, not a sentinel: it is compared with the manifest like any rev.
|
|
1454
|
+
NO_MATHLIB = "none"
|
|
1455
|
+
|
|
1456
|
+
|
|
1457
|
+
def manifest_mathlib(blob: bytes | None) -> str | None:
|
|
1458
|
+
"""The mathlib rev a lake-manifest.json pins; NO_MATHLIB when it is readable and lists no `mathlib`
|
|
1459
|
+
package; None when it is absent or unreadable (or lists mathlib without a rev)."""
|
|
1460
|
+
try:
|
|
1461
|
+
data = json.loads(blob.decode("utf-8")) if blob is not None else None
|
|
1462
|
+
except (ValueError, UnicodeDecodeError):
|
|
1463
|
+
return None
|
|
1464
|
+
pkgs = data.get("packages") if isinstance(data, dict) else None
|
|
1465
|
+
if not isinstance(pkgs, list):
|
|
1466
|
+
return None
|
|
1467
|
+
for p in pkgs:
|
|
1468
|
+
if isinstance(p, dict) and str(p.get("name", "")).casefold() in ("mathlib", "«mathlib»"):
|
|
1469
|
+
return str(p["rev"]).strip() if p.get("rev") else None
|
|
1470
|
+
return NO_MATHLIB
|
|
1471
|
+
|
|
1472
|
+
|
|
1473
|
+
def committed_mathlib(repo: pathlib.Path, commit: str) -> str | None:
|
|
1474
|
+
"""manifest_mathlib of lake-manifest.json committed at `commit`."""
|
|
1475
|
+
return manifest_mathlib(git_show_bytes(repo, "./lake-manifest.json", commit))
|
|
1476
|
+
|
|
1477
|
+
|
|
1478
|
+
def committed_mathlib_rev(repo: pathlib.Path, commit: str) -> str | None:
|
|
1479
|
+
"""The mathlib package's rev in lake-manifest.json committed at `commit`; None when unreadable or when
|
|
1480
|
+
the package has no Mathlib (committed_mathlib tells the two apart)."""
|
|
1481
|
+
rev = committed_mathlib(repo, commit)
|
|
1482
|
+
return None if rev == NO_MATHLIB else rev
|
|
1483
|
+
|
|
1484
|
+
|
|
1485
|
+
def receipt_pin_changes(pkg: dict, repo: pathlib.Path, receipt: dict) -> tuple[dict, dict]:
|
|
1486
|
+
"""(changes, kept) for the package's lean_toolchain and mathlib_pin against the receipt's lean_toolchain and
|
|
1487
|
+
mathlib_rev (field report: a deliberate pin bump, gated, left `list` on the old pin). A receipt value is
|
|
1488
|
+
adopted only when it agrees with the file committed at the receipt's commit (`lean-toolchain`, the mathlib
|
|
1489
|
+
rev in `lake-manifest.json`); otherwise the recorded value is kept and `kept` says why, {field: {receipt,
|
|
1490
|
+
manifest}}; never a refusal. validate_receipt already refuses a mathlib_rev that disagrees with a readable
|
|
1491
|
+
manifest, so `kept` for mathlib_pin is only the case of no readable mathlib entry (manifest None). mathlib_pin keeps register's 10-character form; revs that are prefixes of one
|
|
1492
|
+
another are equal."""
|
|
1493
|
+
changes, kept = {}, {}
|
|
1494
|
+
commit = str(receipt.get("commit") or "")
|
|
1495
|
+
tc = str(receipt.get("lean_toolchain") or "").strip()
|
|
1496
|
+
if tc and pkg.get("lean_toolchain") != tc:
|
|
1497
|
+
blob = git_show_bytes(repo, "./lean-toolchain", commit) if commit else None
|
|
1498
|
+
committed = blob.decode("utf-8", "replace").strip() if blob is not None else None
|
|
1499
|
+
if committed == tc:
|
|
1500
|
+
changes["lean_toolchain"] = {"from": pkg.get("lean_toolchain"), "to": tc}
|
|
1501
|
+
else:
|
|
1502
|
+
kept["lean_toolchain"] = {"receipt": tc, "manifest": committed}
|
|
1503
|
+
rev = str(receipt.get("mathlib_rev") or "").strip()
|
|
1504
|
+
old = str(pkg.get("mathlib_pin") or "")
|
|
1505
|
+
committed = committed_mathlib(repo, commit) if commit and rev else None
|
|
1506
|
+
if committed == NO_MATHLIB:
|
|
1507
|
+
# no Mathlib at the receipt's commit: the pin is null (what register records), whatever the receipt
|
|
1508
|
+
# says; a legacy value other than `none` is not checked, and never becomes a pin
|
|
1509
|
+
if pkg.get("mathlib_pin"):
|
|
1510
|
+
changes["mathlib_pin"] = {"from": pkg.get("mathlib_pin"), "to": None}
|
|
1511
|
+
elif rev and not _same_rev(rev, old):
|
|
1512
|
+
if committed is None:
|
|
1513
|
+
kept["mathlib_pin"] = {"receipt": rev, "manifest": None}
|
|
1514
|
+
elif _same_rev(rev, committed):
|
|
1515
|
+
changes["mathlib_pin"] = {"from": pkg.get("mathlib_pin"), "to": rev[:10]}
|
|
1516
|
+
# a disagreeing rev never reaches here: validate_receipt refuses it
|
|
1517
|
+
return changes, kept
|
|
1518
|
+
|
|
1519
|
+
|
|
1520
|
+
def pins_kept_lines(name: str, kept: dict, commit: str) -> list[str]:
|
|
1521
|
+
files = {"lean_toolchain": ("lean_toolchain", "lean-toolchain"), "mathlib_pin": ("mathlib_rev", "lake-manifest.json")}
|
|
1522
|
+
out = []
|
|
1523
|
+
for field, v in kept.items():
|
|
1524
|
+
key, f = files[field]
|
|
1525
|
+
found = v["manifest"] if v["manifest"] is not None else "unreadable"
|
|
1526
|
+
out.append(f"{name}: pins kept: receipt {key} {v['receipt']} does not match {f} at {commit[:12]} ({found})")
|
|
1527
|
+
return out
|
|
1528
|
+
|
|
1529
|
+
|
|
1530
|
+
def pin_changes_text(changes: dict) -> str:
|
|
1531
|
+
return ", ".join(f"{f} {v['from'] or '-'} -> {v['to'] or '-'}" for f, v in changes.items())
|
|
1532
|
+
|
|
1533
|
+
|
|
1534
|
+
def do_gate(reg_path, reg, events_p, name, receipt_arg,
|
|
1535
|
+
comparator_arg=None, refuse_private: bool = False,
|
|
1536
|
+
refuse_dirty: bool = False, formalization_path: str | None = None,
|
|
1537
|
+
regate: bool = False, reason: str | None = None) -> tuple[list[str], dict]:
|
|
1538
|
+
return _with_private_warnings(_do_gate, reg_path, reg, events_p, name, receipt_arg,
|
|
1539
|
+
comparator_arg, refuse_private, refuse_dirty=refuse_dirty,
|
|
1540
|
+
formalization_path=formalization_path, regate=regate, reason=reason)
|
|
1541
|
+
|
|
1542
|
+
|
|
1543
|
+
def toolchain_advisories_of(receipt) -> list[dict]:
|
|
1544
|
+
"""The toolchain advisories (#237) the receipt's lean_toolchain is affected by: a warning, never a
|
|
1545
|
+
refusal (cmd_gate prints one WARN line per match). An unreadable advisories file is one WARN line."""
|
|
1546
|
+
from . import toolchain_advisories as ta
|
|
1547
|
+
found, problem = ta.lookup(receipt.get("lean_toolchain") if isinstance(receipt, dict) else None)
|
|
1548
|
+
if problem:
|
|
1549
|
+
print(problem, file=sys.stderr)
|
|
1550
|
+
return found
|
|
1551
|
+
|
|
1552
|
+
|
|
1553
|
+
def do_gate_check(reg, name, receipt_arg, comparator_arg=None, refuse_private: bool = False,
|
|
1554
|
+
refuse_dirty: bool = False, regate: bool = False,
|
|
1555
|
+
reason: str | None = None) -> tuple[list[str], dict]:
|
|
1556
|
+
return _with_private_warnings(_do_gate_check, reg, name, receipt_arg, comparator_arg, refuse_private,
|
|
1557
|
+
refuse_dirty=refuse_dirty, regate=regate, reason=reason)
|
|
1558
|
+
|
|
1559
|
+
|
|
1560
|
+
def _do_gate_check(reg, name, receipt_arg, comparator_arg=None, refuse_private: bool = False,
|
|
1561
|
+
private_sink=None, refuse_dirty: bool = False, regate: bool = False,
|
|
1562
|
+
reason: str | None = None) -> tuple[list[str], dict]:
|
|
1563
|
+
"""`gate NAME --receipt R --check` (#26.2): every validation `gate` makes, against HEAD; writes
|
|
1564
|
+
nothing, records no event, works at any status. The mirror of `comparator --check`."""
|
|
1565
|
+
pkg = get_pkg(reg, name)
|
|
1566
|
+
repo = repo_path(pkg)
|
|
1567
|
+
if not repo.is_dir():
|
|
1568
|
+
raise Fail(f"{name}: local_path does not exist: {repo}")
|
|
1569
|
+
dirty = dirty_guard(repo, name, refuse_dirty)
|
|
1570
|
+
resolved: list[dict] = []
|
|
1571
|
+
rp, receipt = load_json_object(locate_evidence_arg(receipt_arg, "receipt", name, repo, resolved), "receipt")
|
|
1572
|
+
cp = comp = None
|
|
1573
|
+
if comparator_arg is not None:
|
|
1574
|
+
cp, comp = load_json_object(locate_evidence_arg(comparator_arg, "comparator receipt", name, repo,
|
|
1575
|
+
resolved), "comparator receipt")
|
|
1576
|
+
private = receipt_private_strings([("receipt", rp.read_bytes())]
|
|
1577
|
+
+ ([("comparator", cp.read_bytes())] if cp else []),
|
|
1578
|
+
refuse_private, private_sink)
|
|
1579
|
+
validate_receipt(pkg, repo, receipt)
|
|
1580
|
+
commit = receipt["commit"]
|
|
1581
|
+
report_line, report_view = report_log_check(repo, receipt, rp)
|
|
1582
|
+
log_copy = plan_report_log_copy(repo, receipt, rp)
|
|
1583
|
+
report_view["copy"] = [d for _s, d in log_copy]
|
|
1584
|
+
checks = [f"· {r['what']} {r['arg']} resolved against the package checkout: {r['path']}" for r in resolved]
|
|
1585
|
+
checks += receipt_check_lines(pkg, repo, receipt) + [report_line]
|
|
1586
|
+
if log_copy:
|
|
1587
|
+
checks.append(f"· gate would also copy {', '.join(report_view['copy'])} beside the canonical receipt "
|
|
1588
|
+
f"(the log beside --receipt; .lean-receipts/ holds no copy)")
|
|
1589
|
+
if comp is not None:
|
|
1590
|
+
validate_comparator(pkg, repo, comp, commit)
|
|
1591
|
+
checks += comparator_check_lines(pkg, repo, comp, commit, with_binding=False)
|
|
1592
|
+
cs = claims_schema_at(name, pkg, repo, commit)
|
|
1593
|
+
checks.append(claims_schema_line(cs))
|
|
1594
|
+
docs_view, _docs_line = docs_admission(repo, commit, pkg, receipt.get("checker"))
|
|
1595
|
+
status = pkg.get("status")
|
|
1596
|
+
lineage_ok = True
|
|
1597
|
+
regate_view = None
|
|
1598
|
+
if regate: # #67: the checks `gate --regate` adds, without writing
|
|
1599
|
+
problem = regate_status_problem(name, pkg)
|
|
1600
|
+
if problem is None:
|
|
1601
|
+
prev, non_desc, problem = regate_lineage(name, pkg, repo, commit, reason)
|
|
1602
|
+
regate_view = {"previous_commit": prev, "non_descendant": non_desc}
|
|
1603
|
+
if problem is None:
|
|
1604
|
+
checks.append(f"✓ regate: {commit[:12]} " + (
|
|
1605
|
+
f"is not a descendant of the gated commit {str(prev)[:12]} (accepted with --reason)"
|
|
1606
|
+
if non_desc and prev else "accepted with --reason (no readable gated commit)"
|
|
1607
|
+
if non_desc else f"descends from the gated commit {str(prev)[:12]}"))
|
|
1608
|
+
if problem is not None:
|
|
1609
|
+
lineage_ok = False
|
|
1610
|
+
checks.append(f"✗ regate: {problem.split(': ', 1)[-1]}")
|
|
1611
|
+
elif status not in ("gate-pending", "public"):
|
|
1612
|
+
checks.append(f"· status {status}: `gate` itself needs gate-pending (or public)"
|
|
1613
|
+
+ (f"; re-gate with `lean-pkg gate {name} --receipt R --regate`"
|
|
1614
|
+
if status == "verified-private" else "")
|
|
1615
|
+
+ (f"; first: {to_gate_pending_cmd(name, commit)}" if status == "active" else ""))
|
|
1616
|
+
pins, pins_kept = receipt_pin_changes(pkg, repo, receipt)
|
|
1617
|
+
if pins:
|
|
1618
|
+
checks.append(f"· pins: gate would record {pin_changes_text(pins)} (from the receipt)")
|
|
1619
|
+
checks += [f"· {line.split(': ', 1)[1]}" for line in pins_kept_lines(name, pins_kept, commit)]
|
|
1620
|
+
ok = cs["ok"] is not False and lineage_ok
|
|
1621
|
+
msg = (f"{name}: receipt valid at commit {commit[:12]}"
|
|
1622
|
+
+ (f" with comparator ({len(comp['configs'])} config(s))" if comp else "")
|
|
1623
|
+
+ ("" if cs["ok"] is not False else f"; {cs['file']} FAILS the claims "
|
|
1624
|
+
+ ("schema" if cs["errors"] else "declaration check") + " (`gate` would refuse)")
|
|
1625
|
+
+ ("" if lineage_ok else "; `gate --regate` would refuse (see the regate line)")
|
|
1626
|
+
+ " — not recorded (--check)")
|
|
1627
|
+
payload = {"ok": ok, "name": name, "event": "gate-checked", "recorded": False, "commit": commit,
|
|
1628
|
+
"head": git_head(repo), "status": status, "checks": checks,
|
|
1629
|
+
"comparator": ({"commit": comp["commit"], "configs": len(comp["configs"])} if comp else None),
|
|
1630
|
+
"private_strings": private, "dirty": dirty, "claims_schema": cs, "pins": pins,
|
|
1631
|
+
"pins_kept": pins_kept, "report_log": report_view, "resolved_paths": resolved, **docs_view,
|
|
1632
|
+
"toolchain_advisories": toolchain_advisories_of(receipt),
|
|
1633
|
+
**binding_file.admission_deprecations(name, docs_view)}
|
|
1634
|
+
if regate:
|
|
1635
|
+
payload["regate"] = regate_view
|
|
1636
|
+
return [msg] + [f" {c}" for c in checks], payload
|
|
1637
|
+
|
|
1638
|
+
|
|
1639
|
+
def _do_gate(reg_path, reg, events_p, name, receipt_arg, comparator_arg=None,
|
|
1640
|
+
refuse_private: bool = False, private_sink=None,
|
|
1641
|
+
refuse_dirty: bool = False, formalization_path: str | None = None,
|
|
1642
|
+
regate: bool = False, reason: str | None = None) -> tuple[list[str], dict]:
|
|
1643
|
+
"""formalization_path (#26.4): the formalization.yaml `--refresh-formalization` is about to own and
|
|
1644
|
+
point the registry at; when no pointer is recorded yet, the evidence rule's derived-only exception
|
|
1645
|
+
is judged for that path (the refresh records it as the pointer right after the gate)."""
|
|
1646
|
+
pkg = get_pkg(reg, name)
|
|
1647
|
+
repo = repo_path(pkg)
|
|
1648
|
+
if not repo.is_dir():
|
|
1649
|
+
raise Fail(f"{name}: local_path does not exist: {repo}")
|
|
1650
|
+
vpkg = pkg if (formalization_rel(pkg) or not formalization_path) \
|
|
1651
|
+
else {**pkg, "formalization_yaml": formalization_path}
|
|
1652
|
+
dirty = dirty_guard(repo, name, refuse_dirty)
|
|
1653
|
+
resolved: list[dict] = []
|
|
1654
|
+
rp, receipt = load_json_object(locate_evidence_arg(receipt_arg, "receipt", name, repo, resolved), "receipt")
|
|
1655
|
+
cp = comp = None
|
|
1656
|
+
if comparator_arg is not None:
|
|
1657
|
+
cp, comp = load_json_object(locate_evidence_arg(comparator_arg, "comparator receipt", name, repo,
|
|
1658
|
+
resolved), "comparator receipt")
|
|
1659
|
+
private = receipt_private_strings([("receipt", rp.read_bytes())]
|
|
1660
|
+
+ ([("comparator", cp.read_bytes())] if cp else []),
|
|
1661
|
+
refuse_private, private_sink)
|
|
1662
|
+
gate = pkg.get("gate") or {}
|
|
1663
|
+
# Idempotent retry: an identical receipt (pair) already recorded is a
|
|
1664
|
+
# no-op success, so agent retries are safe.
|
|
1665
|
+
recorded = recorded_json(repo, gate.get("receipt"))
|
|
1666
|
+
if recorded is not None and recorded == receipt:
|
|
1667
|
+
rec_comp = recorded_json(repo, gate.get("comparator"))
|
|
1668
|
+
if comp is None or (rec_comp is not None and rec_comp == comp):
|
|
1669
|
+
payload = {"ok": True, "name": name, "event": "already-gated",
|
|
1670
|
+
"status": pkg.get("status"), "gate": pkg.get("gate"),
|
|
1671
|
+
"receipt": gate.get("receipt"), "private_strings": private,
|
|
1672
|
+
"dirty": dirty, "toolchain_advisories": toolchain_advisories_of(receipt)}
|
|
1673
|
+
return ([f"{name}: already gated (receipt {gate.get('receipt')}); "
|
|
1674
|
+
f"nothing to do"], payload)
|
|
1675
|
+
raise Fail(f"{name}: already gated with this receipt; to add or replace "
|
|
1676
|
+
f"comparator evidence use `lean-pkg comparator {name} --receipt ...`")
|
|
1677
|
+
# gate-pending is the designed entry. A package that was public before it was
|
|
1678
|
+
# ever gated (for example a collaborator-owned repository registered as public)
|
|
1679
|
+
# may also receive evidence: the status stays public, the receipt and the
|
|
1680
|
+
# gate-passed event are recorded. verified-private re-certifies through the
|
|
1681
|
+
# manual move back to gate-pending, or in one step with --regate (#67).
|
|
1682
|
+
if regate:
|
|
1683
|
+
problem = regate_status_problem(name, pkg)
|
|
1684
|
+
if problem:
|
|
1685
|
+
raise Fail(problem)
|
|
1686
|
+
elif pkg.get("status") not in ("gate-pending", "public"):
|
|
1687
|
+
raise Fail(f"{name}: gate requires status gate-pending (or public, for "
|
|
1688
|
+
f"evidence on an already-public package), got {pkg.get('status')!r}"
|
|
1689
|
+
+ (f"; to re-gate a new commit in one step: `lean-pkg gate {name} --receipt R --regate` "
|
|
1690
|
+
f"(the receipt's commit must descend from the gated one, else add --reason TEXT)"
|
|
1691
|
+
if pkg.get("status") == "verified-private" else "")
|
|
1692
|
+
+ (f"; first: {to_gate_pending_cmd(name, str(receipt.get('commit') or ''))}, then gate again"
|
|
1693
|
+
if pkg.get("status") == "active" and isinstance(receipt, dict) else ""))
|
|
1694
|
+
was_public = pkg.get("status") == "public"
|
|
1695
|
+
validate_receipt(vpkg, repo, receipt)
|
|
1696
|
+
commit = receipt["commit"]
|
|
1697
|
+
report_line, report_view = report_log_check(repo, receipt, rp)
|
|
1698
|
+
if comp is not None:
|
|
1699
|
+
validate_comparator(vpkg, repo, comp, commit)
|
|
1700
|
+
docs_view, docs_line = docs_admission(repo, commit, vpkg, receipt.get("checker"))
|
|
1701
|
+
prev_commit, non_descendant = None, False
|
|
1702
|
+
if regate:
|
|
1703
|
+
prev_commit, non_descendant, problem = regate_lineage(name, pkg, repo, commit, reason)
|
|
1704
|
+
if problem:
|
|
1705
|
+
raise Fail(problem + "; nothing copied or recorded")
|
|
1706
|
+
cs = claims_schema_at(name, pkg, repo, commit)
|
|
1707
|
+
if cs["ok"] is False:
|
|
1708
|
+
problems = claims_problems(cs)
|
|
1709
|
+
if cs["errors"]:
|
|
1710
|
+
what = "fails the claims/1 schema"
|
|
1711
|
+
fix = (f"fix the file, check it with `lean-pkg claims check --file {cs['file']}`"
|
|
1712
|
+
+ (" (schema only; the declarations are checked by `claims sync` at HEAD)"
|
|
1713
|
+
if cs["declarations"]["problems"] else ""))
|
|
1714
|
+
else:
|
|
1715
|
+
what = "names declarations missing from their files at that commit"
|
|
1716
|
+
fix = (f"fix the declarations or the claims' decl/file entries (`lean-pkg claims sync {name}` "
|
|
1717
|
+
f"runs the same check at HEAD)")
|
|
1718
|
+
raise Fail(f"{name}: {cs['file']} at {commit[:12]} {what}, so `claims sync` "
|
|
1719
|
+
f"would refuse what this gate binds: " + "; ".join(problems[:3])
|
|
1720
|
+
+ (f" (+{len(problems) - 3} more)" if len(problems) > 3 else "")
|
|
1721
|
+
+ f". Nothing copied or recorded. Fixing it is a new commit, which needs a new receipt "
|
|
1722
|
+
f"and a re-gate: {fix}, "
|
|
1723
|
+
f"commit, re-run the receipt at that commit, then `lean-pkg gate {name} --receipt R`")
|
|
1724
|
+
|
|
1725
|
+
job = receipt_job_slug(receipt["job_id"])
|
|
1726
|
+
dest_rel = f".lean-receipts/{commit[:12]}-{job}.json"
|
|
1727
|
+
dest = repo / dest_rel
|
|
1728
|
+
out: list[str] = [f"{r['what']} {r['arg']} resolved against the package checkout: {r['path']}"
|
|
1729
|
+
for r in resolved] + [claims_schema_line(cs), report_line]
|
|
1730
|
+
# Every precondition of both copies runs before either is written, so a refusal writes nothing.
|
|
1731
|
+
why = evidence_dest_problem(repo, dest_rel)
|
|
1732
|
+
if why:
|
|
1733
|
+
raise Fail(why)
|
|
1734
|
+
log_copy = plan_report_log_copy(repo, receipt, rp)
|
|
1735
|
+
report_view["copy"] = [d for _s, d in log_copy]
|
|
1736
|
+
present = dest.exists()
|
|
1737
|
+
if present and recorded_json(repo, dest_rel) != receipt:
|
|
1738
|
+
raise Fail(f"{dest} already holds a different receipt for commit {commit[:12]} and job "
|
|
1739
|
+
f"{receipt['job_id']}; pass that file (--receipt {dest}), or give the new run its own "
|
|
1740
|
+
f"job_id")
|
|
1741
|
+
comp_plan = plan_comparator_copy(repo, commit, cp) if comp is not None else None
|
|
1742
|
+
if present:
|
|
1743
|
+
out.append(f"receipt already present at {dest_rel} (not re-copied)")
|
|
1744
|
+
else:
|
|
1745
|
+
dest.parent.mkdir(exist_ok=True)
|
|
1746
|
+
shutil.copy2(rp, dest)
|
|
1747
|
+
out.append(f"receipt copied to {dest} — NOT committed there; "
|
|
1748
|
+
f"commit it in the verified repo yourself")
|
|
1749
|
+
for src, log_rel in log_copy: # the sealed log follows the receipt, so the canonical copy verifies
|
|
1750
|
+
shutil.copy2(src, repo / log_rel)
|
|
1751
|
+
out.append(f"sealed log copied to {repo / log_rel} beside the receipt — NOT committed there; "
|
|
1752
|
+
f"commit it with the receipt")
|
|
1753
|
+
pkg.setdefault("gate", {})["receipt"] = dest_rel
|
|
1754
|
+
fields = dict(commit=commit, job_id=str(receipt["job_id"]),
|
|
1755
|
+
checker=str(receipt["checker"]), receipt=dest_rel, **docs_view)
|
|
1756
|
+
if docs_line:
|
|
1757
|
+
out.append(docs_line)
|
|
1758
|
+
comp_rel = None
|
|
1759
|
+
if comp is not None:
|
|
1760
|
+
comp_rel, note, _moved = apply_comparator_copy(repo, comp_plan, cp)
|
|
1761
|
+
out.append(note)
|
|
1762
|
+
pkg["gate"]["comparator"] = comp_rel
|
|
1763
|
+
fields["comparator"] = comp_rel
|
|
1764
|
+
else:
|
|
1765
|
+
prev_comp = pkg["gate"].get("comparator")
|
|
1766
|
+
prev = recorded_json(repo, prev_comp) if prev_comp else None
|
|
1767
|
+
if prev_comp and (prev is None or str(prev.get("commit")) != commit):
|
|
1768
|
+
pkg["gate"]["comparator"] = None
|
|
1769
|
+
fields["comparator_cleared"] = prev_comp
|
|
1770
|
+
out.append(f"comparator evidence {prev_comp} cleared: it was bound to another commit; "
|
|
1771
|
+
f"attach a fresh one with `lean-pkg comparator {name} --receipt ...`")
|
|
1772
|
+
else:
|
|
1773
|
+
pkg["gate"].setdefault("comparator", None)
|
|
1774
|
+
if was_public:
|
|
1775
|
+
fields["status_unchanged"] = True
|
|
1776
|
+
new_status = "public"
|
|
1777
|
+
else:
|
|
1778
|
+
new_status = "verified-private"
|
|
1779
|
+
pkg["status"] = new_status
|
|
1780
|
+
pins, pins_kept = receipt_pin_changes(pkg, repo, receipt)
|
|
1781
|
+
for field, change in pins.items():
|
|
1782
|
+
pkg[field] = change["to"]
|
|
1783
|
+
if pins:
|
|
1784
|
+
fields["pins"] = pins
|
|
1785
|
+
event = "gate-passed"
|
|
1786
|
+
if regate: # #67: one transition, one event naming both commits
|
|
1787
|
+
event = "regated"
|
|
1788
|
+
fields = {"previous_commit": prev_commit, **fields, "reason": reason or ""}
|
|
1789
|
+
if non_descendant:
|
|
1790
|
+
fields["non_descendant"] = True
|
|
1791
|
+
record(reg, events_p, pkg, event, **fields)
|
|
1792
|
+
save_registry(reg_path, reg)
|
|
1793
|
+
if regate:
|
|
1794
|
+
out.append(f"{name}: {new_status}, re-gated {str(prev_commit or 'unknown')[:12]} -> {commit[:12]}"
|
|
1795
|
+
+ (" (not a descendant; --reason given)" if non_descendant else "")
|
|
1796
|
+
+ (f" with comparator evidence {comp_rel}" if comp_rel else ""))
|
|
1797
|
+
elif was_public:
|
|
1798
|
+
out.append(f"{name}: public, evidence recorded, status unchanged (commit {commit[:12]})"
|
|
1799
|
+
+ (f" with comparator evidence {comp_rel}" if comp_rel else ""))
|
|
1800
|
+
else:
|
|
1801
|
+
out.append(f"{name}: gate-pending -> verified-private (commit {commit[:12]})"
|
|
1802
|
+
+ (f" with comparator evidence {comp_rel}" if comp_rel else ""))
|
|
1803
|
+
if pins:
|
|
1804
|
+
out.append(f"{name}: pins updated from the receipt: {pin_changes_text(pins)}")
|
|
1805
|
+
out += pins_kept_lines(name, pins_kept, commit)
|
|
1806
|
+
out.append(RL_REMINDER.format(name=name))
|
|
1807
|
+
ignored = attached_ignored_evidence(pkg, repo)
|
|
1808
|
+
payload = {"ok": True, "name": name, "event": event,
|
|
1809
|
+
"status": new_status, "gate": pkg["gate"],
|
|
1810
|
+
"receipt": dest_rel, "commit": commit, "rl_reminder": True,
|
|
1811
|
+
"rl_hint": RL_REMINDER.format(name=name),
|
|
1812
|
+
"status_unchanged": was_public or regate, "private_strings": private, "dirty": dirty,
|
|
1813
|
+
"ignored_evidence": ignored, "claims_schema": cs, "pins": pins,
|
|
1814
|
+
"pins_kept": pins_kept, "report_log": report_view, "resolved_paths": resolved, **docs_view,
|
|
1815
|
+
"toolchain_advisories": toolchain_advisories_of(receipt),
|
|
1816
|
+
**binding_file.admission_deprecations(name, docs_view)}
|
|
1817
|
+
if regate:
|
|
1818
|
+
payload.update(previous_commit=prev_commit, non_descendant=non_descendant, reason=reason or "")
|
|
1819
|
+
if comp_rel:
|
|
1820
|
+
payload["comparator"] = comp_rel
|
|
1821
|
+
return out, payload
|
|
1822
|
+
|
|
1823
|
+
|
|
1824
|
+
def attached_ignored_evidence(pkg: dict, repo: pathlib.Path) -> list[dict]:
|
|
1825
|
+
"""After `gate`/`comparator` attach evidence: [{path, rule}] for the evidence files git ignores,
|
|
1826
|
+
each also a stderr WARN, so the gap shows now and not at promote time (#40)."""
|
|
1827
|
+
from . import publish as publish_mod
|
|
1828
|
+
ignored = publish_mod.ignored_evidence(repo, publish_mod.evidence_paths(pkg, repo))
|
|
1829
|
+
publish_mod.warn_ignored_evidence(ignored)
|
|
1830
|
+
return ignored
|
|
1831
|
+
|
|
1832
|
+
|
|
1833
|
+
def do_comparator(reg_path, reg, events_p, name, receipt_arg,
|
|
1834
|
+
check_only: bool = False, refuse_private: bool = False,
|
|
1835
|
+
refuse_dirty: bool = False, replace: bool = False) -> tuple[list[str], dict]:
|
|
1836
|
+
return _with_private_warnings(_do_comparator, reg_path, reg, events_p, name, receipt_arg,
|
|
1837
|
+
check_only, refuse_private, refuse_dirty=refuse_dirty, replace=replace)
|
|
1838
|
+
|
|
1839
|
+
|
|
1840
|
+
def _do_comparator(reg_path, reg, events_p, name, receipt_arg, check_only: bool = False,
|
|
1841
|
+
refuse_private: bool = False, private_sink=None,
|
|
1842
|
+
refuse_dirty: bool = False, replace: bool = False) -> tuple[list[str], dict]:
|
|
1843
|
+
pkg = get_pkg(reg, name)
|
|
1844
|
+
repo = repo_path(pkg)
|
|
1845
|
+
if not repo.is_dir():
|
|
1846
|
+
raise Fail(f"{name}: local_path does not exist: {repo}")
|
|
1847
|
+
dirty = dirty_guard(repo, name, refuse_dirty)
|
|
1848
|
+
cp, comp = load_json_object(locate_evidence_arg(receipt_arg, "comparator receipt", name, repo),
|
|
1849
|
+
"comparator receipt")
|
|
1850
|
+
private = receipt_private_strings([("comparator", cp.read_bytes())], refuse_private, private_sink)
|
|
1851
|
+
gate = pkg.get("gate") or {}
|
|
1852
|
+
if check_only:
|
|
1853
|
+
lower = recorded_json(repo, gate.get("receipt"))
|
|
1854
|
+
lower_commit = str(lower.get("commit") or "") if lower else None
|
|
1855
|
+
validate_comparator(pkg, repo, comp, lower_commit or None)
|
|
1856
|
+
why = recorded_report_log_problem(repo, lower, gate["receipt"]) if isinstance(lower, dict) else None
|
|
1857
|
+
if why: # the tier this receipt pairs with must still be evidence
|
|
1858
|
+
raise Fail(f"{name}: the recorded gate receipt {gate['receipt']}: {why}")
|
|
1859
|
+
docs_view, _docs_line = docs_admission(repo, comp["commit"], pkg)
|
|
1860
|
+
n = len(comp["configs"])
|
|
1861
|
+
msg = (f"{name}: comparator receipt valid at commit {comp['commit'][:12]} "
|
|
1862
|
+
f"({n} config(s)) — not recorded (--check)"
|
|
1863
|
+
+ ("" if lower_commit else "; no lower-tier receipt recorded yet"))
|
|
1864
|
+
checks = comparator_check_lines(pkg, repo, comp, lower_commit or None)
|
|
1865
|
+
payload = {"ok": True, "name": name, "event": "comparator-checked",
|
|
1866
|
+
"recorded": False, "commit": comp["commit"], "configs": n,
|
|
1867
|
+
"lower_receipt_commit": lower_commit, "head": git_head(repo), "checks": checks,
|
|
1868
|
+
"private_strings": private, "dirty": dirty, **docs_view,
|
|
1869
|
+
**binding_file.admission_deprecations(name, docs_view)}
|
|
1870
|
+
return [msg] + [f" {c}" for c in checks], payload
|
|
1871
|
+
rec_comp = recorded_json(repo, gate.get("comparator"))
|
|
1872
|
+
if rec_comp is not None and rec_comp == comp:
|
|
1873
|
+
payload = {"ok": True, "name": name, "event": "already-attached",
|
|
1874
|
+
"status": pkg.get("status"), "gate": gate,
|
|
1875
|
+
"comparator": gate.get("comparator"), "private_strings": private,
|
|
1876
|
+
"dirty": dirty}
|
|
1877
|
+
return ([f"{name}: comparator receipt already attached "
|
|
1878
|
+
f"({gate.get('comparator')}); nothing to do"], payload)
|
|
1879
|
+
if pkg.get("status") not in ("verified-private", "public"):
|
|
1880
|
+
raise Fail(f"{name}: comparator requires status verified-private or public "
|
|
1881
|
+
f"(gate first), got {pkg.get('status')!r}")
|
|
1882
|
+
lower = recorded_json(repo, gate.get("receipt"))
|
|
1883
|
+
if lower is None:
|
|
1884
|
+
raise Fail(f"{name}: no readable lower-tier receipt at {gate.get('receipt')!r}; "
|
|
1885
|
+
f"run `lean-pkg gate` first")
|
|
1886
|
+
validate_comparator(pkg, repo, comp, str(lower.get("commit") or ""))
|
|
1887
|
+
why = recorded_report_log_problem(repo, lower, gate["receipt"])
|
|
1888
|
+
if why: # the tier this receipt pairs with must still be evidence
|
|
1889
|
+
raise Fail(f"{name}: the recorded gate receipt {gate['receipt']}: {why}; nothing recorded")
|
|
1890
|
+
commit = comp["commit"]
|
|
1891
|
+
docs_view, docs_line = docs_admission(repo, commit, pkg)
|
|
1892
|
+
comp_rel, note, moved = copy_comparator(repo, commit, cp, replace=replace)
|
|
1893
|
+
pkg.setdefault("gate", {})["comparator"] = comp_rel
|
|
1894
|
+
event = "comparator-replaced" if moved else "comparator-attached"
|
|
1895
|
+
extra = {"replaced": moved} if moved else {}
|
|
1896
|
+
record(reg, events_p, pkg, event, commit=commit,
|
|
1897
|
+
comparator=comp_rel, host=str(comp["host"]), job_id=str(comp["job_id"]), **extra, **docs_view)
|
|
1898
|
+
save_registry(reg_path, reg)
|
|
1899
|
+
out = [note, *([docs_line] if docs_line else []),
|
|
1900
|
+
f"{name}: {event} ({comp_rel}, commit {commit[:12]}, "
|
|
1901
|
+
f"{len(comp['configs'])} config(s))" + (f"; older receipt kept at {moved}" if moved else "")]
|
|
1902
|
+
payload = {"ok": True, "name": name, "event": event, **extra,
|
|
1903
|
+
"status": pkg.get("status"), "gate": pkg["gate"],
|
|
1904
|
+
"comparator": comp_rel, "commit": commit, "private_strings": private,
|
|
1905
|
+
"dirty": dirty, "ignored_evidence": attached_ignored_evidence(pkg, repo), **docs_view,
|
|
1906
|
+
**binding_file.admission_deprecations(name, docs_view)}
|
|
1907
|
+
return out, payload
|
|
1908
|
+
|
|
1909
|
+
|
|
1910
|
+
# --------------------------------------------------------------------------
|
|
1911
|
+
# --repo DIR: a read-only command run against another checkout of the package
|
|
1912
|
+
|
|
1913
|
+
def _remote_abs_path(url: str) -> str | None:
|
|
1914
|
+
"""The absolute repository path a non-GitHub remote names, whatever host it is reached through:
|
|
1915
|
+
`/p`, `file:///p`, scp-style `host:/p` and `ssh://[user@]host[:port]/p` all give `/p` (no
|
|
1916
|
+
`.git`, no trailing slash). None for a relative or home-relative path (`host:p`, `host:~/p`)."""
|
|
1917
|
+
u = str(url).strip()
|
|
1918
|
+
m = (re.fullmatch(r"file://(/.*)", u) or re.fullmatch(r"ssh://[^/]+(/.*)", u)
|
|
1919
|
+
or re.fullmatch(r"[^/:\s]+:(/.*)", u) or re.fullmatch(r"(/.*)", u))
|
|
1920
|
+
if not m:
|
|
1921
|
+
return None
|
|
1922
|
+
return re.sub(r"(\.git)?/*$", "", m.group(1)) or None
|
|
1923
|
+
|
|
1924
|
+
|
|
1925
|
+
def _same_remote(a: str, b: str) -> bool:
|
|
1926
|
+
"""Do two remote URLs name the same repository? GitHub URLs by owner/repo (any scheme, any case);
|
|
1927
|
+
otherwise exact match up to `.git`/trailing slash, or (field report) the same absolute path when
|
|
1928
|
+
one side is a plain local path: a registry `repo` that is the bare repo's path on the registry host
|
|
1929
|
+
matches `Host:<that path>` from a checkout elsewhere. Two remotes that both name a host keep the
|
|
1930
|
+
exact comparison."""
|
|
1931
|
+
na, nb = gh_nwo(a), gh_nwo(b)
|
|
1932
|
+
if na and nb:
|
|
1933
|
+
return na.lower() == nb.lower()
|
|
1934
|
+
norm = lambda u: re.sub(r"(\.git)?/*$", "", str(u).strip())
|
|
1935
|
+
if bool(norm(a)) and norm(a) == norm(b):
|
|
1936
|
+
return True
|
|
1937
|
+
local = lambda u: str(u).strip().startswith(("/", "file://"))
|
|
1938
|
+
if local(a) or local(b):
|
|
1939
|
+
pa, pb = _remote_abs_path(a), _remote_abs_path(b)
|
|
1940
|
+
return pa is not None and pa == pb
|
|
1941
|
+
return False
|
|
1942
|
+
|
|
1943
|
+
|
|
1944
|
+
def repo_override(reg: dict, name: str, repo_arg: str) -> tuple[dict, dict]:
|
|
1945
|
+
"""`--repo DIR` on a read-only command (field report: one local_path per package, but checkouts
|
|
1946
|
+
on different hosts hold different branches): (a copy of the registry whose NAME record points at
|
|
1947
|
+
DIR for this one call, {path, registered_path, remote_match}). Never saved. DIR must be a git
|
|
1948
|
+
work tree; when it has remotes and the record names a repo, one remote must be that repo
|
|
1949
|
+
(remote_match True; `Host:/p` matches a local-path repo `/p`, see _same_remote), unless DIR is the
|
|
1950
|
+
registered local_path itself. Otherwise remote_match is None and the caller vouches for DIR."""
|
|
1951
|
+
pkg = get_pkg(reg, name)
|
|
1952
|
+
d = pathlib.Path(os.path.expanduser(repo_arg)).resolve()
|
|
1953
|
+
if not d.is_dir():
|
|
1954
|
+
raise Fail(f"--repo {repo_arg}: not a directory")
|
|
1955
|
+
p = git(d, "rev-parse", "--is-inside-work-tree")
|
|
1956
|
+
if p.returncode != 0 or p.stdout.strip() != "true":
|
|
1957
|
+
raise Fail(f"--repo {repo_arg}: not inside a git work tree")
|
|
1958
|
+
want = str(pkg.get("repo") or "").strip()
|
|
1959
|
+
p = git(d, "config", "--get-regexp", r"^remote\..*\.url$")
|
|
1960
|
+
urls = [line.split(None, 1)[1] for line in p.stdout.splitlines() if len(line.split(None, 1)) == 2]
|
|
1961
|
+
registered = pkg.get("local_path")
|
|
1962
|
+
try:
|
|
1963
|
+
registered = str(repo_path(pkg))
|
|
1964
|
+
except (KeyError, TypeError, ValueError):
|
|
1965
|
+
pass
|
|
1966
|
+
is_registered = False
|
|
1967
|
+
try:
|
|
1968
|
+
is_registered = registered is not None and pathlib.Path(registered).resolve() == d
|
|
1969
|
+
except OSError:
|
|
1970
|
+
pass
|
|
1971
|
+
match = None
|
|
1972
|
+
if want and urls and any(_same_remote(u, want) for u in urls):
|
|
1973
|
+
match = True
|
|
1974
|
+
elif want and urls and not is_registered: # the registered checkout itself needs no remote proof
|
|
1975
|
+
raise Fail(f"--repo {repo_arg}: no git remote of it is the package's repo {want} "
|
|
1976
|
+
f"(remotes: {', '.join(urls)}); pass a checkout of {name}")
|
|
1977
|
+
copied = dict(reg)
|
|
1978
|
+
copied["packages"] = dict(reg.get("packages") or {})
|
|
1979
|
+
copied["packages"][name] = {**copy.deepcopy(pkg), "local_path": str(d)}
|
|
1980
|
+
return copied, {"path": str(d), "registered_path": registered, "remote_match": match}
|
|
1981
|
+
|
|
1982
|
+
|
|
1983
|
+
def repo_override_note(view: dict) -> str | None:
|
|
1984
|
+
"""The stderr note for `--repo DIR`; None when DIR is the registered local_path itself (field
|
|
1985
|
+
report: the note then named the same path twice and said nothing)."""
|
|
1986
|
+
try:
|
|
1987
|
+
if view.get("registered_path") and \
|
|
1988
|
+
pathlib.Path(view["registered_path"]).resolve() == pathlib.Path(view["path"]).resolve():
|
|
1989
|
+
return None
|
|
1990
|
+
except OSError:
|
|
1991
|
+
pass
|
|
1992
|
+
return (f"lean-pkg: note: using --repo {view['path']} instead of the registered local_path "
|
|
1993
|
+
f"{view['registered_path']} (this call only; the registry is unchanged)"
|
|
1994
|
+
+ ("" if view["remote_match"] else "; no remote to compare with the record's repo: "
|
|
1995
|
+
"the caller vouches that it is this package's checkout"))
|
|
1996
|
+
|
|
1997
|
+
|
|
1998
|
+
# --------------------------------------------------------------------------
|
|
1999
|
+
# the gate command
|
|
2000
|
+
|
|
2001
|
+
def refresh_preflight(reg: dict, name: str, agent: str | None) -> None:
|
|
2002
|
+
"""--refresh-formalization, before the gate writes anything: the package's checkout exists, no other
|
|
2003
|
+
agent holds a live lease (the file write needs it), and the current render passes the schema (a kept
|
|
2004
|
+
key that fails it would otherwise refuse only after the gate has been recorded)."""
|
|
2005
|
+
from . import formalization as fz
|
|
2006
|
+
pkg = get_pkg(reg, name)
|
|
2007
|
+
repo = repo_path(pkg)
|
|
2008
|
+
if not repo.is_dir() or git_head(repo) is None:
|
|
2009
|
+
raise Fail(f"{name}: --refresh-formalization needs the git checkout at {repo}")
|
|
2010
|
+
refuse_invalid_lease(name, pkg.get("lease"))
|
|
2011
|
+
lease = pkg.get("lease")
|
|
2012
|
+
if lease_live(lease, dt.datetime.now(dt.timezone.utc)) and agent != lease.get("agent"):
|
|
2013
|
+
raise Fail(f"{name}: lease held by {lease.get('agent')} — pass --agent {lease.get('agent')}; "
|
|
2014
|
+
f"nothing written")
|
|
2015
|
+
_text, doc, _w, _existing = fz.render_for(pkg, repo)
|
|
2016
|
+
mode, errors = fz.validate_doc(doc)
|
|
2017
|
+
if errors:
|
|
2018
|
+
raise Fail(f"{name}: formalization.yaml would fail the {fz.SCHEMA_VERSION} schema ({mode}); fix "
|
|
2019
|
+
f"its kept keys first; nothing written:\n " + "\n ".join(errors))
|
|
2020
|
+
|
|
2021
|
+
|
|
2022
|
+
def do_gate_refresh(reg_path, reg, events_p, args) -> tuple[list[str], dict, list[str]]:
|
|
2023
|
+
"""`gate NAME --receipt R --refresh-formalization` (#22.4): gate, then regenerate formalization.yaml
|
|
2024
|
+
(derived keys, including status.evidence, from the new receipt; kept keys survive) in one step.
|
|
2025
|
+
Refuses, writing nothing, when the gate is an identical re-gate and the file is already current."""
|
|
2026
|
+
from . import formalization as fz
|
|
2027
|
+
refresh_preflight(reg, args.name, args.agent)
|
|
2028
|
+
out, payload = do_gate(reg_path, reg, events_p, args.name, args.receipt, args.comparator,
|
|
2029
|
+
refuse_private=args.refuse_private, refuse_dirty=args.refuse_dirty,
|
|
2030
|
+
formalization_path=fz.target_rel(get_pkg(reg, args.name)),
|
|
2031
|
+
regate=getattr(args, "regate", False), reason=getattr(args, "reason", None))
|
|
2032
|
+
gated = payload.get("event") in ("gate-passed", "regated")
|
|
2033
|
+
pkg = get_pkg(reg, args.name)
|
|
2034
|
+
if not gated:
|
|
2035
|
+
text, _doc, _w, existing = fz.render_for(pkg, repo_path(pkg))
|
|
2036
|
+
if existing == text and pkg.get("formalization_yaml") == fz.target_rel(pkg):
|
|
2037
|
+
raise Fail(f"{args.name}: nothing to refresh: already gated with this receipt and "
|
|
2038
|
+
f"{fz.target_rel(pkg)} is current; nothing written")
|
|
2039
|
+
f_lines, f_payload, warnings = fz.do_formalization(
|
|
2040
|
+
reg_path, reg, events_p, args.name, write=True, out=None, force=True, authors=None,
|
|
2041
|
+
agent=args.agent, reason="lean-pkg gate --refresh-formalization")
|
|
2042
|
+
payload["formalization"] = {k: f_payload[k] for k in ("path", "written", "unchanged", "registry_updated",
|
|
2043
|
+
"validation", "placeholders")}
|
|
2044
|
+
return out + f_lines, payload, warnings
|
|
2045
|
+
|
|
2046
|
+
|
|
2047
|
+
def _move_record_hint(name: str) -> str:
|
|
2048
|
+
"""The one way to make the writing gate bind another checkout: move the registered local_path."""
|
|
2049
|
+
return f"move the record with `lean-pkg update {name} --path DIR --reason TEXT`"
|
|
2050
|
+
|
|
2051
|
+
|
|
2052
|
+
def gate_next_command(args, payload: dict, regate: bool, reason: str | None) -> str | None:
|
|
2053
|
+
"""#386: the writing `gate` a passing `--check` stands for: the same evidence flags (as given), --agent
|
|
2054
|
+
A when --check got one (else the AGENT placeholder). None when the check fails or the writing gate
|
|
2055
|
+
would refuse the status (the check lines then say what comes first)."""
|
|
2056
|
+
if not payload.get("ok") or not (regate or payload.get("status") in ("gate-pending", "public")):
|
|
2057
|
+
return None
|
|
2058
|
+
q = shlex.quote
|
|
2059
|
+
parts = ["lean-pkg", "gate", q(args.name), "--receipt", q(args.receipt)]
|
|
2060
|
+
if args.comparator is not None:
|
|
2061
|
+
parts += ["--comparator", q(args.comparator)]
|
|
2062
|
+
if regate:
|
|
2063
|
+
parts.append("--regate")
|
|
2064
|
+
if reason is not None:
|
|
2065
|
+
parts += ["--reason", q(reason)]
|
|
2066
|
+
parts += [f for f, on in (("--refuse-private", args.refuse_private),
|
|
2067
|
+
("--refuse-dirty", args.refuse_dirty)) if on]
|
|
2068
|
+
agent = getattr(args, "agent", None)
|
|
2069
|
+
parts += ["--agent", q(agent) if agent is not None else "AGENT"]
|
|
2070
|
+
return " ".join(parts)
|
|
2071
|
+
|
|
2072
|
+
|
|
2073
|
+
def cmd_gate(args) -> int:
|
|
2074
|
+
reg_path, events_p = registry_path(args), events_path(args)
|
|
2075
|
+
regate, reason = getattr(args, "regate", False), getattr(args, "reason", None)
|
|
2076
|
+
if reason is not None:
|
|
2077
|
+
if not regate:
|
|
2078
|
+
raise UsageError("gate --reason goes with --regate (it accepts a non-descendant re-gate)")
|
|
2079
|
+
require_nonempty("--reason", reason)
|
|
2080
|
+
reason = reason.strip()
|
|
2081
|
+
repo_arg = getattr(args, "repo", None)
|
|
2082
|
+
if repo_arg is not None and not getattr(args, "check", False):
|
|
2083
|
+
# field report: a writing gate binds the registered checkout; move it with `update --path`
|
|
2084
|
+
raise UsageError("gate --repo goes with --check: a writing gate binds the registered local_path "
|
|
2085
|
+
f"(drop --repo to gate that checkout; validate DIR with `gate {args.name} --check "
|
|
2086
|
+
f"--repo DIR`; {_move_record_hint(args.name)})")
|
|
2087
|
+
if getattr(args, "check", False):
|
|
2088
|
+
if getattr(args, "refresh_formalization", False):
|
|
2089
|
+
raise UsageError("gate --check writes nothing; --refresh-formalization does not apply (it writes "
|
|
2090
|
+
"formalization.yaml after the gate): pass it to the writing "
|
|
2091
|
+
f"`lean-pkg gate {args.name} --receipt R --refresh-formalization --agent A`")
|
|
2092
|
+
if getattr(args, "agent", None) is not None: # #386: carried into the next: command, not refused
|
|
2093
|
+
print(f"lean-pkg: note: gate --check takes no lease and checks none; --agent {args.agent} is "
|
|
2094
|
+
"used by the writing gate (see next:)", file=sys.stderr)
|
|
2095
|
+
reg, override = load_registry(reg_path), None
|
|
2096
|
+
# #385: the registry commit the record (and the lease warning) was read from; local refs, no fetch.
|
|
2097
|
+
# Said before the checks, so a refusal read from a stale clone carries it too.
|
|
2098
|
+
rstate = registry_state_of(args)
|
|
2099
|
+
if behind := registry_behind_warning(rstate):
|
|
2100
|
+
print(behind, file=sys.stderr)
|
|
2101
|
+
if repo_arg is not None:
|
|
2102
|
+
reg, override = repo_override(reg, args.name, repo_arg)
|
|
2103
|
+
if note := repo_override_note(override):
|
|
2104
|
+
print(note, file=sys.stderr)
|
|
2105
|
+
out, payload = do_gate_check(reg, args.name, args.receipt, args.comparator,
|
|
2106
|
+
refuse_private=args.refuse_private, refuse_dirty=args.refuse_dirty,
|
|
2107
|
+
regate=regate, reason=reason)
|
|
2108
|
+
payload["repo_override"] = override
|
|
2109
|
+
payload["registry_state"] = rstate
|
|
2110
|
+
from . import palomar_check # advisory (feature request #6): never changes the verdict; no WARN
|
|
2111
|
+
# for a package not aiming at Palomar (#387: the same predicate as audit; JSON skipped says so)
|
|
2112
|
+
payload["palomar_check"] = view = palomar_check.hook(reg, args.name, payload.get("commit"))
|
|
2113
|
+
if view and (warning := palomar_check.summary_warning(view)):
|
|
2114
|
+
print(f"WARN: {warning}", file=sys.stderr)
|
|
2115
|
+
payload["next_command"] = nxt = gate_next_command(args, payload, regate, reason)
|
|
2116
|
+
if nxt is not None:
|
|
2117
|
+
out.append(f"next: {nxt}")
|
|
2118
|
+
if override is not None and repo_override_note(override) is not None:
|
|
2119
|
+
out.append(f" (the writing gate binds the registered local_path {override['registered_path']}, "
|
|
2120
|
+
f"not --repo: run it there, or {_move_record_hint(args.name)})")
|
|
2121
|
+
elif getattr(args, "refresh_formalization", False):
|
|
2122
|
+
_ACTOR["agent"] = getattr(args, "agent", None) or None # its own lease check runs in do_gate_refresh
|
|
2123
|
+
out, payload, warnings = do_gate_refresh(reg_path, load_registry(reg_path), events_p, args)
|
|
2124
|
+
for w in warnings:
|
|
2125
|
+
print(f"lean-pkg: warning: {w}", file=sys.stderr)
|
|
2126
|
+
else:
|
|
2127
|
+
reg = load_registry(reg_path)
|
|
2128
|
+
warn_lease(lease_actor(reg, args.name, getattr(args, "agent", None), "gate"))
|
|
2129
|
+
out, payload = do_gate(reg_path, reg, events_p,
|
|
2130
|
+
args.name, args.receipt, args.comparator,
|
|
2131
|
+
refuse_private=args.refuse_private, refuse_dirty=args.refuse_dirty,
|
|
2132
|
+
regate=regate, reason=reason)
|
|
2133
|
+
from .toolchain_advisories import warn_line # #237: a warning, never a refusal
|
|
2134
|
+
for view in payload.get("toolchain_advisories") or []:
|
|
2135
|
+
print(warn_line(view), file=sys.stderr)
|
|
2136
|
+
binding_file.print_deprecations(payload)
|
|
2137
|
+
if args.json_out:
|
|
2138
|
+
print_json(payload)
|
|
2139
|
+
else:
|
|
2140
|
+
print("\n".join(out))
|
|
2141
|
+
return 0 if payload.get("ok", True) else 1
|