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/core.py
ADDED
|
@@ -0,0 +1,1570 @@
|
|
|
1
|
+
# lean-pkg core -- the shared library core under the command line (cli.py)
|
|
2
|
+
"""The shared core of lean-pkg: what every command module builds on.
|
|
3
|
+
|
|
4
|
+
`Fail` and `UsageError`, the registry constants and the package-record schema, time policy
|
|
5
|
+
(now_iso, parse_ts), the git and gh helpers (git, scrubbed_env, git_show_bytes, bound_tree, ...),
|
|
6
|
+
the building blocks of the docs-only rule (docs_build_input, nested_exclusions, ...), registry IO
|
|
7
|
+
(resolution, load, lock, save), the event log (one line per event, EVENT_KEYS) and the pure
|
|
8
|
+
lease-time helpers.
|
|
9
|
+
|
|
10
|
+
It never imports cli: cli.py and the command modules import it (`from . import core`; a module that
|
|
11
|
+
also needs a name still defined in cli.py imports cli under its own name). Its only lean_pkg import is
|
|
12
|
+
build_scope, a leaf module, inside the functions that use it. Moved here from cli.py (#317); cli.py
|
|
13
|
+
re-exports every name for at least one release, for outside scripts. The supported interface is the
|
|
14
|
+
CLI and its --json outputs, not `import lean_pkg` (AGENTS.md).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import collections
|
|
20
|
+
import contextlib
|
|
21
|
+
import datetime as dt
|
|
22
|
+
import fnmatch
|
|
23
|
+
import fcntl
|
|
24
|
+
import hashlib
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import pathlib
|
|
28
|
+
import posixpath
|
|
29
|
+
import re
|
|
30
|
+
import shlex
|
|
31
|
+
import shutil
|
|
32
|
+
import stat
|
|
33
|
+
import subprocess
|
|
34
|
+
import sys
|
|
35
|
+
import tempfile
|
|
36
|
+
import urllib.error
|
|
37
|
+
import urllib.request
|
|
38
|
+
|
|
39
|
+
import yaml
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
HOME = pathlib.Path.home()
|
|
43
|
+
REGISTRY_ENV = "LEAN_PKG_REGISTRY"
|
|
44
|
+
REGISTRY_VERSION = 3 # schema version written by `init` and `migrate`
|
|
45
|
+
SUPPORTED_REGISTRY_VERSIONS = (1, 2, 3) # readable by every command; older files lack the keys below
|
|
46
|
+
V2_PACKAGE_DEFAULTS = {
|
|
47
|
+
"license_spdx": None, # SPDX id detected or declared (ADR-0070 D5)
|
|
48
|
+
"formalization_yaml": None, # repo-relative path when the package has one
|
|
49
|
+
"palomar": [], # [{id, version, commit, comparator_config, registered_at, review_outcome, preflight_run}]
|
|
50
|
+
"doi": None, # {"concept": str|None, "versions": [{"doi","tag","commit","minted_at"}]}
|
|
51
|
+
"reservoir": None, # {"listed_at": iso, "url": str} or None
|
|
52
|
+
"consent": [], # [{"who","role","recorded_at","pointer"}]; pointer is a private-repo path
|
|
53
|
+
}
|
|
54
|
+
V3_PACKAGE_DEFAULTS = {
|
|
55
|
+
"claims_file": "claims.yaml", # repo-relative path of the package's claims/1 file
|
|
56
|
+
"claims": [], # last synced copy of that file's claims (see `claims sync`)
|
|
57
|
+
"claims_synced_commit": None, # 40-hex commit the cached claims were read at
|
|
58
|
+
}
|
|
59
|
+
# ADR-0070 D5 evidence events: name -> required --field keys. Each has a registry effect (see do_record).
|
|
60
|
+
EVIDENCE_EVENTS = {
|
|
61
|
+
"consent-recorded": ("who", "role", "pointer"),
|
|
62
|
+
"palomar-preflight-pass": ("commit", "run"),
|
|
63
|
+
"palomar-submitted": ("commit", "submission_id", "comparator_config"),
|
|
64
|
+
"palomar-review": ("commit", "outcome"),
|
|
65
|
+
"palomar-registered": ("commit", "id", "version", "comparator_config"),
|
|
66
|
+
"palomar-withdrawn": ("id", "version"),
|
|
67
|
+
"doi-minted": ("doi", "tag", "commit"),
|
|
68
|
+
"reservoir-listed": ("url",),
|
|
69
|
+
"mathlib-pr-opened": ("url",),
|
|
70
|
+
"mathlib-pr-merged": ("url",),
|
|
71
|
+
}
|
|
72
|
+
RETRACT_EVENT = "retract" # `record NAME retract`: append-only correction of an evidence entry
|
|
73
|
+
|
|
74
|
+
# The event-line schema (1.0 command tree, section 6, item 2; docs/formats.md "Event log"). Every line
|
|
75
|
+
# carries EVENT_LINE_KEYS; `v` is the line's version, EVENT_LINE_VERSION since 0.22.0, and a line without
|
|
76
|
+
# it (written before) is version 0, read exactly as before. A reader that interprets events skips a line
|
|
77
|
+
# of a newer (or unreadable) version and says so; it never guesses at it.
|
|
78
|
+
EVENT_LINE_VERSION = 1
|
|
79
|
+
EVENT_LINE_KEYS = ("ts", "event", "name", "v")
|
|
80
|
+
# Events written only to the log (no history[] entry, no `actor` unless listed); every other event is a
|
|
81
|
+
# package event written by record(), which may also carry `actor` (the --agent of the invocation, #21.3).
|
|
82
|
+
LOG_ONLY_EVENTS = ("registry-created", "registry-migrated", "registry-recommended", "index-added",
|
|
83
|
+
"prior-art-searched")
|
|
84
|
+
# `updated` carries <field>_from (the old value) for each field it changed: these fields.
|
|
85
|
+
UPDATED_FROM_FIELDS = ("lean_toolchain", "mathlib_pin", "status") # plus every UPDATABLE field
|
|
86
|
+
_GATE_EVENT_KEYS = ("commit", "job_id", "checker", "receipt", "descendant_of", "docs_paths", "opt_in",
|
|
87
|
+
"comparator", "comparator_cleared", "status_unchanged", "pins")
|
|
88
|
+
_LEASE_EVENT_KEYS = ("agent", "workspace", "ttl_hours", "reason", "contact")
|
|
89
|
+
# Every event name lean-pkg writes, with the keys it may carry beyond EVENT_LINE_KEYS. docs/formats.md
|
|
90
|
+
# documents the same table and tests/test_formats.py checks both against every emitting call in src/.
|
|
91
|
+
EVENT_KEYS: dict[str, tuple[str, ...]] = {
|
|
92
|
+
"registry-created": ("registry", "version", "forced"),
|
|
93
|
+
"registry-migrated": ("from_version", "to_version", "changes"),
|
|
94
|
+
"registry-recommended": ("recommended", "previous", "reason"),
|
|
95
|
+
"registered": ("repo", "local_path", "status", "visibility", "lean_toolchain", "mathlib_pin", "workspace",
|
|
96
|
+
"agent", "reason", "like", "license_spdx"),
|
|
97
|
+
"updated": ("fields", "reason", "forced", "notes_replaced", "<field>_from"),
|
|
98
|
+
"claimed": _LEASE_EVENT_KEYS,
|
|
99
|
+
"claim-forced": _LEASE_EVENT_KEYS,
|
|
100
|
+
"claim-refreshed": ("agent", "workspace", "ttl_hours", "reason", "contact", "contact_cleared"),
|
|
101
|
+
"released": ("agent", "workspace", "released_by", "reason"),
|
|
102
|
+
"release-forced": ("agent", "workspace", "released_by", "reason"),
|
|
103
|
+
"lease-expired": ("agent", "workspace", "claimed_at", "ttl_hours"),
|
|
104
|
+
"gate-passed": _GATE_EVENT_KEYS,
|
|
105
|
+
"regated": ("previous_commit", *_GATE_EVENT_KEYS, "reason", "non_descendant"),
|
|
106
|
+
"comparator-attached": ("commit", "comparator", "host", "job_id", "descendant_of", "docs_paths", "opt_in"),
|
|
107
|
+
"comparator-replaced": ("commit", "comparator", "host", "job_id", "replaced", "descendant_of", "docs_paths",
|
|
108
|
+
"opt_in"),
|
|
109
|
+
"promoted": ("commit", "visibility"),
|
|
110
|
+
"publication-withdrawn": ("status_from", "status_to", "visibility_from", "visibility_to", "reason", "by",
|
|
111
|
+
"github_visibility", "promoted_commit", "forced"),
|
|
112
|
+
"publication-hold-released": ("reason", "hold", "by", "forced"),
|
|
113
|
+
"audit-fix": ("field", "old", "new", "source"),
|
|
114
|
+
"relocated": ("old_path", "new_path", "reason", "cleared", "agent", "redetected"),
|
|
115
|
+
"status-changed": ("status_from", "status_to", "reason"),
|
|
116
|
+
"palomar-prepared": ("commit", "bundle", "bundle_sha256"),
|
|
117
|
+
"claims-synced": ("commit", "file", "claims"),
|
|
118
|
+
"index-added": ("repo", "commit", "trust", "index"),
|
|
119
|
+
"prior-art-searched": ("term", "sources", "hits", "record", "decision", "actor"),
|
|
120
|
+
"evidence-retracted": ("retracted_event", "retracted_ts", "retracted_entry", "reason"),
|
|
121
|
+
**{e: (*keys, "reason", *(("concept", "track") if e == "doi-minted" else ()))
|
|
122
|
+
for e, keys in EVIDENCE_EVENTS.items()},
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def event_line_version(line: dict) -> int | None:
|
|
127
|
+
"""The version of one parsed event line: 0 without `v` (written before 0.22.0), the integer `v`
|
|
128
|
+
otherwise; None when `v` is not a non-negative integer (unreadable, never guessed at)."""
|
|
129
|
+
if "v" not in line:
|
|
130
|
+
return 0
|
|
131
|
+
v = line["v"]
|
|
132
|
+
return v if isinstance(v, int) and not isinstance(v, bool) and v >= 0 else None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def event_line_problems(line: dict) -> list[str]:
|
|
136
|
+
"""Why a line lean-pkg writes would not match the documented event-line schema (EVENT_KEYS): an
|
|
137
|
+
undocumented event name, or a key that event does not document. Empty when it matches."""
|
|
138
|
+
event = line.get("event")
|
|
139
|
+
if event not in EVENT_KEYS:
|
|
140
|
+
return [f"event {event!r} is not documented in EVENT_KEYS (docs/formats.md)"]
|
|
141
|
+
allowed = set(EVENT_LINE_KEYS) | set(EVENT_KEYS[event])
|
|
142
|
+
if event not in LOG_ONLY_EVENTS:
|
|
143
|
+
allowed.add("actor")
|
|
144
|
+
from_ok = ("<field>_from" in allowed and
|
|
145
|
+
{f"{f}_from" for f in (*UPDATED_FROM_FIELDS, *UPDATABLE)})
|
|
146
|
+
return [f"event {event!r} key {k!r} is not documented in EVENT_KEYS (docs/formats.md)"
|
|
147
|
+
for k in sorted(line) if k not in allowed and not (from_ok and k in from_ok)]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
_HEX40 = re.compile(r"[0-9a-f]{40}")
|
|
151
|
+
RESERVOIR_URL_RE = re.compile(r"^https://reservoir\.lean-lang\.org/@([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/?$")
|
|
152
|
+
RESERVOIR_API = "https://reservoir.lean-lang.org/api/v1/packages/{owner}/{name}"
|
|
153
|
+
DOI_RE = re.compile(r"10\.\d{4,9}/\S+", re.IGNORECASE)
|
|
154
|
+
GITHUB_URL_RE = re.compile(r"https://github\.com/[^/\s]+/[^/\s]+(?:/\S*)?")
|
|
155
|
+
PALOMAR_REGISTERED_STATUSES = ("public", "upstreamed")
|
|
156
|
+
PRIVATE_EVIDENCE_HINT = "private path in evidence; use a URL or repo-relative pointer"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def reservoir_listing_status(owner: str, name: str) -> int | None:
|
|
160
|
+
"""HTTP status of Reservoir's package endpoint (200 = listed, 404 = not listed),
|
|
161
|
+
or None when the network is unreachable. Tests monkeypatch this function."""
|
|
162
|
+
req = urllib.request.Request(RESERVOIR_API.format(owner=owner, name=name),
|
|
163
|
+
headers={"User-Agent": "lean-pkg"})
|
|
164
|
+
try:
|
|
165
|
+
with urllib.request.urlopen(req, timeout=10) as r:
|
|
166
|
+
return int(r.status)
|
|
167
|
+
except urllib.error.HTTPError as e:
|
|
168
|
+
return int(e.code)
|
|
169
|
+
except (urllib.error.URLError, TimeoutError, OSError):
|
|
170
|
+
return None
|
|
171
|
+
DEFAULT_REGISTRY_NAME = "lean-packages.yaml"
|
|
172
|
+
EVENTS_NAME = "lean-package-events.jsonl"
|
|
173
|
+
NOTIFY_ENV = "LEAN_PKG_NOTIFY_CMD"
|
|
174
|
+
|
|
175
|
+
STATUSES = ["scratch", "active", "gate-pending", "verified-private",
|
|
176
|
+
"public", "upstreamed", "archived"]
|
|
177
|
+
VISIBILITIES = ["private", "public"]
|
|
178
|
+
# register may only mint pre-evidence statuses; verified-private is gate's, public is promote's
|
|
179
|
+
# (register accepts public only for an already-public repository: --visibility public --reason).
|
|
180
|
+
REGISTER_STATUSES = ["scratch", "active", "gate-pending", "public"]
|
|
181
|
+
UPSTREAM_TARGETS = ["none", "mathlib", "palomar"]
|
|
182
|
+
# DOI track (#51): absent = palomar (doi-minted needs a palomar-* event on the commit, rule doi-in-palomar);
|
|
183
|
+
# doi-only lets a public package with no Palomar-shaped claim record its DOI without one.
|
|
184
|
+
TRACKS = ("palomar", "doi-only")
|
|
185
|
+
DEFAULT_AXIOMS = ["propext", "Quot.sound", "Classical.choice"]
|
|
186
|
+
DEFAULT_TTL_HOURS = 24
|
|
187
|
+
# Upper bound for --ttl (claim/renew) and the board's TTL prompt: one year. A larger value is a usage
|
|
188
|
+
# error (exit 2) refused before anything is written; an unbounded one overflowed the expiry computation
|
|
189
|
+
# after the lease was already saved.
|
|
190
|
+
MAX_TTL_HOURS = 8760
|
|
191
|
+
|
|
192
|
+
# The package record, one row per top-level key: (key, tier, meaning). The single source of truth for
|
|
193
|
+
# `status --help`, `status --fields` validation, docs/cli.md "Package record" (tests keep them equal) and
|
|
194
|
+
# validate's REQUIRED_FIELDS. Tiers: v1 (validate requires it at every schema version), v2/v3 (the
|
|
195
|
+
# V2/V3_PACKAGE_DEFAULTS keys `migrate` adds), optional (absent unless set). A meaning ending "[bulk]" marks
|
|
196
|
+
# a large cached array: `--no-claims` on status/list/board drops exactly those keys (BULK_FIELDS).
|
|
197
|
+
PACKAGE_FIELDS = (
|
|
198
|
+
("name", "v1", "package name; equals its key under packages"),
|
|
199
|
+
("repo", "v1", "git URL (or local bare path) of the repository"),
|
|
200
|
+
("local_path", "v1", "checkout path, $HOME-relative"),
|
|
201
|
+
("visibility", "v1", "private | public; GitHub is the mirror"),
|
|
202
|
+
("status", "v1", "lifecycle status: " + " | ".join(STATUSES)),
|
|
203
|
+
("owner_project", "v1", "project that owns the package"),
|
|
204
|
+
("workspace", "v1", "workspace that registered it"),
|
|
205
|
+
("agent", "v1", "agent that registered it"),
|
|
206
|
+
("lease", "v1", "live claim {workspace, agent, claimed_at, ttl_hours, reason, contact?} or null; contact: "
|
|
207
|
+
"optional address of the holding session (claim/renew --contact); status/list/board "
|
|
208
|
+
"output adds the derived expires_at (claimed_at + ttl_hours, UTC; never stored)"),
|
|
209
|
+
("lean_toolchain", "v1", "lean-toolchain detected in the checkout"),
|
|
210
|
+
("mathlib_pin", "v1", "Mathlib revision from lake-manifest.json"),
|
|
211
|
+
("upstream_target", "v1", "upstream goal: " + " | ".join(UPSTREAM_TARGETS)),
|
|
212
|
+
("automation", "v1", "automation disclosure (required when upstream_target is mathlib)"),
|
|
213
|
+
("gate", "v1", "trust gate {receipt, comparator, axioms_allowed}: receipt paths in the repo"),
|
|
214
|
+
("promoted_at", "v1", "when promote --yes made it public, or null"),
|
|
215
|
+
("promoted_commit", "v1", "the commit promoted, or null"),
|
|
216
|
+
("reaudit_after", "v1", "ISO date after which to re-audit, or null"),
|
|
217
|
+
("notes", "v1", "free text"),
|
|
218
|
+
("history", "v1", "append-only event list (status prints the last 5; --json all)"),
|
|
219
|
+
("license_spdx", "v2", "SPDX license id or expression, or null"),
|
|
220
|
+
("formalization_yaml", "v2", "repo-relative path of formalization.yaml, or null"),
|
|
221
|
+
("palomar", "v2", "Palomar evidence entries [{id, version, commit, comparator_config, ...}]"),
|
|
222
|
+
("doi", "v2", "{concept, versions[{doi, tag, commit, minted_at}]} or null"),
|
|
223
|
+
("reservoir", "v2", "{listed_at, url} once Reservoir lists it, or null"),
|
|
224
|
+
("consent", "v2", "consent records [{who, role, recorded_at, pointer}]"),
|
|
225
|
+
("claims_file", "v3", "repo-relative path of the claims/1 file"),
|
|
226
|
+
("claims", "v3", "cached claims from the last `claims sync` (can be hundreds of KB) [bulk]"),
|
|
227
|
+
("claims_synced_commit", "v3", "40-hex commit the cached claims were read at, or null"),
|
|
228
|
+
("paper", "optional", "{arxiv, status} of the paper behind a paper-coupled package"),
|
|
229
|
+
("namespace_notes", "optional", "{Lean root namespace: why sharing it with another package is intended}"),
|
|
230
|
+
("source_paper", "optional", "{title, authors[], arxiv, doi} of the formalized paper (credited in "
|
|
231
|
+
"formalization.yaml acknowledgements, never as project.authors)"),
|
|
232
|
+
("ai_assistance", "optional", "{tools[], roles[]}: AI tools used and for what (rendered into acknowledgements)"),
|
|
233
|
+
("track", "optional", "DOI track: " + " | ".join(TRACKS) + " (absent = palomar); doi-only lets a public package "
|
|
234
|
+
"record doi-minted without a palomar-* event (update --track)"),
|
|
235
|
+
("docs_descendants", "optional", "true: a receipt bound to commit C is also accepted at a descendant of C where "
|
|
236
|
+
"no build input under the package directory changed (docs-only rule, "
|
|
237
|
+
"docs/receipts.md), unless lean-pkg-binding.yaml committed at C decides; false "
|
|
238
|
+
"vetoes the file's opt-in; absent = false (update --accept-docs-descendants)"),
|
|
239
|
+
("build_inputs", "optional", "[glob]: extra package-relative paths the docs-only rule treats as build inputs, "
|
|
240
|
+
"added to those of lean-pkg-binding.yaml at C (fnmatch; a glob without / also "
|
|
241
|
+
"matches a basename) (update --build-inputs)"),
|
|
242
|
+
("headline_config", "optional", "repo-relative path of the headline comparator configuration (the paper's "
|
|
243
|
+
"main results; formalization.yaml status.main_results lists its theorems); "
|
|
244
|
+
"absent = comparator.headline.json when tracked (update --headline-config)"),
|
|
245
|
+
("publication_hold", "optional", "{reason, at, by}: the owner withdrew publication (update "
|
|
246
|
+
"--withdraw-publication); promote refuses while it is set; only update "
|
|
247
|
+
"--release-publication-hold lifts it"),
|
|
248
|
+
)
|
|
249
|
+
REQUIRED_FIELDS = [k for k, tier, _ in PACKAGE_FIELDS if tier == "v1"]
|
|
250
|
+
BULK_FIELDS = [k for k, _, meaning in PACKAGE_FIELDS if meaning.endswith("[bulk]")]
|
|
251
|
+
LEASE_FIELDS = ["workspace", "agent", "claimed_at", "ttl_hours", "reason"]
|
|
252
|
+
LEASE_OPTIONAL_FIELDS = ["contact"] # absent unless set; `--fields lease.contact` yields null then
|
|
253
|
+
LEASE_CONTACT_MAX = 200 # characters
|
|
254
|
+
RECEIPT_FIELDS = ["commit", "lean_toolchain", "mathlib_rev", "sorry_count",
|
|
255
|
+
"axioms", "report_sha256", "job_id", "checker",
|
|
256
|
+
"generated_at"]
|
|
257
|
+
# The lower-tier receipt's schema marker (1.0 command tree, section 6, item 1): every writer (receipt slurm,
|
|
258
|
+
# receipt systemd/local) puts `schema` first since 0.22.0. A receipt without the key is version 0 and is
|
|
259
|
+
# judged exactly as before, forever: receipts are evidence bound to bytes and never rewritten. A newer
|
|
260
|
+
# lower-receipt/N is refused (upgrade lean-pkg), as a newer registry version is.
|
|
261
|
+
LOWER_RECEIPT_SCHEMAS = ("lower-receipt/1",)
|
|
262
|
+
LOWER_RECEIPT_SCHEMA = LOWER_RECEIPT_SCHEMAS[-1]
|
|
263
|
+
_LOWER_RECEIPT_SCHEMA_RE = re.compile(r"lower-receipt/([1-9][0-9]*)")
|
|
264
|
+
COMPARATOR_SCHEMAS = ("comparator-receipt/1", "comparator-receipt/2")
|
|
265
|
+
COMPARATOR_SCHEMA = COMPARATOR_SCHEMAS[-1]
|
|
266
|
+
COMPARATOR_MECHANISMS = ("toolchain", "legacy")
|
|
267
|
+
COMPARATOR_TOOLCHAIN_DIGESTS = ["lake_sha256", "leanexport_sha256", "leanchecker_sha256",
|
|
268
|
+
"nanoda_bin_sha256", "con-ron_sha256"]
|
|
269
|
+
COMPARATOR_PASS_LINE = "Your solution is okay!"
|
|
270
|
+
# One acceptance predicate for both mechanisms, shared with the runner (comparator_receipt imports
|
|
271
|
+
# it). Observed live on 2026-10-06 (Lean v4.35.0-rc2): `lake comparator` prints the per-kernel lines
|
|
272
|
+
# ("con-ron kernel accepts the solution", "nanoda kernel accepts the solution", "Lean default kernel
|
|
273
|
+
# accepts the solution") and then the full line "Your solution is okay!"; the legacy stack prints the
|
|
274
|
+
# same final line. Only that full line counts.
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def comparator_pass(log_text: str, mechanism: str) -> bool:
|
|
278
|
+
"""True when a comparator log shows acceptance: the full line COMPARATOR_PASS_LINE."""
|
|
279
|
+
return COMPARATOR_PASS_LINE in log_text.splitlines()
|
|
280
|
+
COMPARATOR_TOOLS = ["comparator", "lean4export", "nanoda", "landrun"]
|
|
281
|
+
COMPARATOR_FIELDS = ["schema", "commit", "lean_toolchain", "tools", "host",
|
|
282
|
+
"job_id", "generated_at", "result", "configs"]
|
|
283
|
+
COMPARATOR_CONFIG_FIELDS = ["path", "sha256", "challenge_module",
|
|
284
|
+
"solution_module", "theorem_names",
|
|
285
|
+
"definition_names", "permitted_axioms", "log",
|
|
286
|
+
"log_sha256", "result"]
|
|
287
|
+
# the configuration's list fields: omitted (or null) in a committed config means the empty list (#61)
|
|
288
|
+
COMPARATOR_LIST_FIELDS = ("theorem_names", "definition_names", "permitted_axioms")
|
|
289
|
+
LICENSE_NAMES = ["LICENSE", "LICENSE.md", "LICENSE.txt",
|
|
290
|
+
"COPYING", "COPYING.md", "COPYING.txt"]
|
|
291
|
+
|
|
292
|
+
BOARD_HEADER = ("NAME", "STATUS", "VIS", "LEASE", "EXPIRES", "PIN", "REAUDIT")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class Fail(Exception):
|
|
296
|
+
"""User-facing refusal: printed to stderr, exit 1."""
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class UsageError(Exception):
|
|
300
|
+
"""Interactive path attempted off-tty, or other usage-level error: exit 2."""
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
# --------------------------------------------------------------------------
|
|
304
|
+
# small utilities
|
|
305
|
+
|
|
306
|
+
# Time policy (one for every timestamp the tool writes): UTC, ISO-8601 with an explicit offset
|
|
307
|
+
# (+00:00), second precision. Dates the tool writes (wiki `updated:`, search headers, record file
|
|
308
|
+
# names) are the UTC date. Events written in the same second keep their order by position in
|
|
309
|
+
# history[] and the event log (file order is the tiebreak; there is no sequence field).
|
|
310
|
+
# A naive timestamp (legacy, hand-written) is read as UTC; validate accepts it, doctor counts it.
|
|
311
|
+
|
|
312
|
+
def now_iso() -> str:
|
|
313
|
+
"""Now, under the time policy: UTC, ISO-8601 with offset, second precision."""
|
|
314
|
+
return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def utc_today() -> str:
|
|
318
|
+
"""Today's UTC date as YYYY-MM-DD (the time policy's date)."""
|
|
319
|
+
return dt.datetime.now(dt.timezone.utc).date().isoformat()
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def is_naive_ts(s) -> bool:
|
|
323
|
+
"""True for a parseable ISO-8601 timestamp without an offset (read as UTC by parse_ts)."""
|
|
324
|
+
try:
|
|
325
|
+
v = dt.datetime.fromisoformat(str(s).strip().replace("Z", "+00:00"))
|
|
326
|
+
except ValueError:
|
|
327
|
+
return False
|
|
328
|
+
return v.tzinfo is None
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def naive_timestamps(reg: dict) -> int:
|
|
332
|
+
"""How many lease claimed_at / history ts values in the registry are naive (legacy)."""
|
|
333
|
+
n = 0
|
|
334
|
+
for pkg in (reg.get("packages") or {}).values():
|
|
335
|
+
if not isinstance(pkg, dict):
|
|
336
|
+
continue
|
|
337
|
+
lease = pkg.get("lease")
|
|
338
|
+
if isinstance(lease, dict) and lease.get("claimed_at") and is_naive_ts(lease["claimed_at"]):
|
|
339
|
+
n += 1
|
|
340
|
+
for h in pkg.get("history") or []:
|
|
341
|
+
if isinstance(h, dict) and h.get("ts") and is_naive_ts(h["ts"]):
|
|
342
|
+
n += 1
|
|
343
|
+
return n
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def parse_ts(s: str) -> dt.datetime:
|
|
347
|
+
"""Parse an ISO-8601 timestamp; a naive one is legacy and read as UTC (see the time policy)."""
|
|
348
|
+
s = str(s).strip()
|
|
349
|
+
if s.endswith("Z"):
|
|
350
|
+
s = s[:-1] + "+00:00"
|
|
351
|
+
v = dt.datetime.fromisoformat(s)
|
|
352
|
+
if v.tzinfo is None:
|
|
353
|
+
v = v.replace(tzinfo=dt.timezone.utc)
|
|
354
|
+
return v
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
# Repository-selecting Git variables (#27). A launcher that leaks one (GIT_INDEX_FILE from a hook, say)
|
|
358
|
+
# points every git, and Lake's dependency checkout, at another repository's index or object store.
|
|
359
|
+
# Subprocesses that work on a package checkout run without them; the registry repository's own git
|
|
360
|
+
# calls (registry_git) keep the caller's environment. GIT_CONFIG_*, GIT_SSH_COMMAND and
|
|
361
|
+
# GIT_TERMINAL_PROMPT are deliberately kept.
|
|
362
|
+
GIT_REPO_ENV = ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY",
|
|
363
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_COMMON_DIR", "GIT_NAMESPACE")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def git_env_set(env=None) -> list[str]:
|
|
367
|
+
"""The repository-selecting Git variables set in env (default: os.environ), in GIT_REPO_ENV order."""
|
|
368
|
+
env = os.environ if env is None else env
|
|
369
|
+
return [n for n in GIT_REPO_ENV if n in env]
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def scrubbed_env(env=None) -> dict:
|
|
373
|
+
"""A copy of env (default: os.environ) without the repository-selecting Git variables."""
|
|
374
|
+
return {k: v for k, v in (os.environ if env is None else env).items() if k not in GIT_REPO_ENV}
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def run(cmd: list[str], cwd: str | None = None, scrub: bool = False) -> subprocess.CompletedProcess:
|
|
378
|
+
"""The one subprocess helper. Never raises on nonzero exit; a binary that cannot be run (not on
|
|
379
|
+
PATH, not executable, a missing cwd) is returncode 127 with the OSError in stderr. scrub=True drops
|
|
380
|
+
GIT_REPO_ENV (for a package checkout)."""
|
|
381
|
+
try:
|
|
382
|
+
return subprocess.run(cmd, capture_output=True, text=True, check=False, cwd=cwd,
|
|
383
|
+
env=scrubbed_env() if scrub else None)
|
|
384
|
+
except OSError as e:
|
|
385
|
+
missing = isinstance(e, FileNotFoundError) and e.filename in (cmd[0], None) and shutil.which(cmd[0]) is None
|
|
386
|
+
why = f"{cmd[0]} not on PATH" if missing else f"{cmd[0]}: {e.strerror or e}"
|
|
387
|
+
return subprocess.CompletedProcess(cmd, 127, "", why)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def git(repo: pathlib.Path, *args: str) -> subprocess.CompletedProcess:
|
|
391
|
+
"""git in a package checkout, without the repository-selecting Git variables (#27)."""
|
|
392
|
+
return run(["git", "-C", str(repo), *args], scrub=True)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def registry_git(root: pathlib.Path, *args: str) -> subprocess.CompletedProcess:
|
|
396
|
+
"""git in the registry repository (or lean-pkg's own checkout): the caller's environment as is."""
|
|
397
|
+
return run(["git", "-C", str(root), *args])
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def gh(*args: str) -> subprocess.CompletedProcess:
|
|
401
|
+
return run(["gh", *args])
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def find_reuse() -> str | None:
|
|
405
|
+
return shutil.which("reuse")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def notify(message: str) -> str:
|
|
409
|
+
"""Optional notification hook. If env LEAN_PKG_NOTIFY_CMD is set, run that
|
|
410
|
+
command (split shell-style, no shell) with the message on stdin.
|
|
411
|
+
|
|
412
|
+
Returns "sent" (exit 0), "failed" (nonzero exit or not runnable), or
|
|
413
|
+
"not-configured" (variable unset or empty). Never raises."""
|
|
414
|
+
cmd = os.environ.get(NOTIFY_ENV, "").strip()
|
|
415
|
+
if not cmd:
|
|
416
|
+
return "not-configured"
|
|
417
|
+
try:
|
|
418
|
+
argv = shlex.split(cmd)
|
|
419
|
+
p = subprocess.run(argv, input=message + "\n", capture_output=True,
|
|
420
|
+
text=True, check=False)
|
|
421
|
+
except (OSError, ValueError):
|
|
422
|
+
return "failed"
|
|
423
|
+
return "sent" if p.returncode == 0 else "failed"
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def gh_nwo(repo_url: str) -> str | None:
|
|
427
|
+
"""owner/repo from a GitHub git URL (ssh or https), else None."""
|
|
428
|
+
m = re.search(r"github\.com[:/]([^/\s]+)/([^/\s]+?)(?:\.git)?/?$",
|
|
429
|
+
str(repo_url).strip())
|
|
430
|
+
return f"{m.group(1)}/{m.group(2)}" if m else None
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def repo_path(pkg: dict) -> pathlib.Path:
|
|
434
|
+
# $HOME-relative by convention; an absolute local_path passes through.
|
|
435
|
+
return HOME / pathlib.Path(str(pkg["local_path"]))
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def git_head(repo: pathlib.Path) -> str | None:
|
|
439
|
+
p = git(repo, "rev-parse", "HEAD")
|
|
440
|
+
return p.stdout.strip() if p.returncode == 0 else None
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _rev(repo: pathlib.Path, ref: str) -> str | None:
|
|
444
|
+
p = git(repo, "rev-parse", "--verify", "-q", ref + "^{commit}")
|
|
445
|
+
return p.stdout.strip() if p.returncode == 0 and p.stdout.strip() else None
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _is_ancestor(repo: pathlib.Path, a: str, b: str) -> bool:
|
|
449
|
+
return git(repo, "merge-base", "--is-ancestor", a, b).returncode == 0
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def reference_branch(repo: pathlib.Path) -> tuple[str | None, str | None, str]:
|
|
453
|
+
"""The branch a package's evidence is judged against, its tip, and a note; local refs only.
|
|
454
|
+
Order: the remote default branch (refs/remotes/origin/HEAD), else `main`, else `master`.
|
|
455
|
+
When both refs/heads/<b> and refs/remotes/origin/<b> exist, the tip is the one that contains
|
|
456
|
+
the other (a fetched origin ahead of a never-pulled local branch wins); when they diverged,
|
|
457
|
+
origin wins and the note says so. With no candidate branch, (None, HEAD, "").
|
|
458
|
+
The registry has no per-package branch field, so none is consulted."""
|
|
459
|
+
candidates = []
|
|
460
|
+
p = git(repo, "symbolic-ref", "-q", "refs/remotes/origin/HEAD")
|
|
461
|
+
if p.returncode == 0 and p.stdout.strip().startswith("refs/remotes/origin/"):
|
|
462
|
+
candidates.append(p.stdout.strip()[len("refs/remotes/origin/"):])
|
|
463
|
+
candidates += [b for b in ("main", "master") if b not in candidates]
|
|
464
|
+
for b in candidates:
|
|
465
|
+
local = _rev(repo, f"refs/heads/{b}")
|
|
466
|
+
remote = _rev(repo, f"refs/remotes/origin/{b}")
|
|
467
|
+
if not (local or remote):
|
|
468
|
+
continue
|
|
469
|
+
if not (local and remote) or local == remote:
|
|
470
|
+
return b, local or remote, ""
|
|
471
|
+
if _is_ancestor(repo, local, remote):
|
|
472
|
+
return b, remote, ""
|
|
473
|
+
if _is_ancestor(repo, remote, local):
|
|
474
|
+
return b, local, ""
|
|
475
|
+
return b, remote, f"local {b} and origin/{b} diverged; judged against origin/{b}"
|
|
476
|
+
return None, git_head(repo), ""
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def current_branch(repo: pathlib.Path) -> str | None:
|
|
480
|
+
"""The checked-out branch's short name, or None on a detached HEAD (or outside a checkout)."""
|
|
481
|
+
p = git(repo, "symbolic-ref", "-q", "--short", "HEAD")
|
|
482
|
+
return p.stdout.strip() if p.returncode == 0 and p.stdout.strip() else None
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def default_branch(repo: pathlib.Path) -> str | None:
|
|
486
|
+
"""The repository's default branch from local refs only (no network): the target of
|
|
487
|
+
refs/remotes/origin/HEAD, else `main`, else `master`, when that local or origin/ branch exists;
|
|
488
|
+
else None."""
|
|
489
|
+
p = git(repo, "symbolic-ref", "-q", "refs/remotes/origin/HEAD")
|
|
490
|
+
if p.returncode == 0 and p.stdout.strip().startswith("refs/remotes/origin/"):
|
|
491
|
+
return p.stdout.strip()[len("refs/remotes/origin/"):]
|
|
492
|
+
for b in ("main", "master"):
|
|
493
|
+
if _rev(repo, f"refs/heads/{b}") or _rev(repo, f"refs/remotes/origin/{b}"):
|
|
494
|
+
return b
|
|
495
|
+
return None
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def branch_state(repo: pathlib.Path | None) -> dict:
|
|
499
|
+
"""{current, default, detached, is_default} for a package checkout (#48); the `status --json`
|
|
500
|
+
"branch" object. Outside a checkout with a commit: all null/false."""
|
|
501
|
+
head = git_head(repo) if repo is not None and repo.is_dir() else None
|
|
502
|
+
if head is None:
|
|
503
|
+
return {"current": None, "default": None, "detached": False, "is_default": False}
|
|
504
|
+
cur, dflt = current_branch(repo), default_branch(repo)
|
|
505
|
+
return {"current": cur, "default": dflt, "detached": cur is None,
|
|
506
|
+
"is_default": cur is not None and cur == dflt}
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def branch_notice(repo: pathlib.Path | None, state: dict | None = None) -> str | None:
|
|
510
|
+
"""`evaluating branch X, not the default D` / `evaluating a detached HEAD <sha12>, not the
|
|
511
|
+
default D` when the checkout is not on its default branch (#48); None when it is, or when no
|
|
512
|
+
default branch can be determined. Informational only: HEAD is still what is evaluated."""
|
|
513
|
+
st = state if state is not None else branch_state(repo)
|
|
514
|
+
if st["default"] is None or st["is_default"]:
|
|
515
|
+
return None
|
|
516
|
+
if st["detached"]:
|
|
517
|
+
head = git_head(repo) or ""
|
|
518
|
+
return f"evaluating a detached HEAD {head[:12]}, not the default {st['default']}"
|
|
519
|
+
return f"evaluating branch {st['current']}, not the default {st['default']}"
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def formalization_rel(pkg: dict | None) -> str | None:
|
|
523
|
+
"""The package's recorded formalization.yaml path (package-relative), for the evidence rule."""
|
|
524
|
+
rel = str((pkg or {}).get("formalization_yaml") or "").strip()
|
|
525
|
+
while rel.startswith("./"):
|
|
526
|
+
rel = rel[2:]
|
|
527
|
+
return rel or None
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def under_any(path: str, dirs) -> bool:
|
|
535
|
+
"""`path` is one of the package-relative directories `dirs` or lies under one."""
|
|
536
|
+
return any(path == d or path.startswith(d + "/") for d in dirs)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def nested_label(paths, dirs) -> str:
|
|
540
|
+
"""The directories among `dirs` that hold at least one of `paths`, as `a/, b/`."""
|
|
541
|
+
return ", ".join(f"{d}/" for d in sorted(dirs) if any(x == d or x.startswith(d + "/") for x in paths))
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
# The packages of the registry this process loaded last (load_registry): the nested-package rule (#3)
|
|
545
|
+
# reads their roots. A caller with no registry loaded sees none, which keeps the stricter rule.
|
|
546
|
+
_LOADED_PACKAGES: dict = {}
|
|
547
|
+
# The top-level keys other than `packages` of the registry this process last loaded (mutated, never rebound):
|
|
548
|
+
# run_command clears it per invocation, and recommended.after_command reads `lean_pkg` from it.
|
|
549
|
+
_LOADED_TOP: dict = {}
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def registered_nested_dirs(repo: pathlib.Path, packages: dict | None = None) -> tuple[str, ...]:
|
|
553
|
+
"""The local_path roots of other registered packages strictly inside the package directory `repo`,
|
|
554
|
+
relative to it, sorted (the same roots the declaration scan skips, #117)."""
|
|
555
|
+
pkgs = _LOADED_PACKAGES if packages is None else packages
|
|
556
|
+
try:
|
|
557
|
+
mine = pathlib.Path(repo).resolve()
|
|
558
|
+
except (OSError, RuntimeError):
|
|
559
|
+
return ()
|
|
560
|
+
out = set()
|
|
561
|
+
for other in (pkgs or {}).values():
|
|
562
|
+
if not isinstance(other, dict) or not other.get("local_path"):
|
|
563
|
+
continue
|
|
564
|
+
try:
|
|
565
|
+
root = repo_path(other).resolve()
|
|
566
|
+
except (OSError, RuntimeError, TypeError, ValueError):
|
|
567
|
+
continue
|
|
568
|
+
if root != mine and mine in root.parents:
|
|
569
|
+
out.add(root.relative_to(mine).as_posix())
|
|
570
|
+
return tuple(sorted(out))
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def nested_exclusions(repo: pathlib.Path, bound: str, head: str,
|
|
574
|
+
nested: tuple[str, ...]) -> tuple[tuple[str, ...], list[str]]:
|
|
575
|
+
"""(excluded, kept): the nested registered package directories whose changes between bound and head
|
|
576
|
+
are not this package's, and one `dir/ (why)` note per nested directory that stays a build input
|
|
577
|
+
because this package depends on it or reads it: a `path` package in lake-manifest.json, a lakefile
|
|
578
|
+
that requires or names it, a lean_lib/lean_exe/input whose sources lie there, or a symlink committed
|
|
579
|
+
at bound (outside it) that resolves into it. Read at bound and at head; fails closed (an unreadable
|
|
580
|
+
file or tree keeps the directory)."""
|
|
581
|
+
from .build_scope import nested_dependency, overlaps
|
|
582
|
+
if not nested:
|
|
583
|
+
return (), []
|
|
584
|
+
p = git(repo, "diff", "--no-renames", "--name-only", "--relative", bound, head)
|
|
585
|
+
changed = [x for x in p.stdout.splitlines() if x.strip()]
|
|
586
|
+
touched = [d for d in nested if any(x == d or x.startswith(d + "/") for x in changed)]
|
|
587
|
+
if not touched:
|
|
588
|
+
return (), []
|
|
589
|
+
try:
|
|
590
|
+
tree = bound_tree(repo, bound)
|
|
591
|
+
except Fail as e:
|
|
592
|
+
return (), [f"{d}/ (the tree at {bound[:12]} is unreadable: {e})" for d in touched]
|
|
593
|
+
excluded, kept = [], []
|
|
594
|
+
for d in touched:
|
|
595
|
+
why = None
|
|
596
|
+
for rev in (bound, head):
|
|
597
|
+
why = nested_dependency(lambda rel, rev=rev: git_show_bytes(repo, rel, rev), d)
|
|
598
|
+
if why:
|
|
599
|
+
why = f"{why} at {rev[:12]}"
|
|
600
|
+
break
|
|
601
|
+
if not why:
|
|
602
|
+
for link, mode in sorted(tree.items()):
|
|
603
|
+
if not mode.startswith("120000:") or link == d or link.startswith(d + "/"):
|
|
604
|
+
continue
|
|
605
|
+
t = resolve_tree_path(tree, link)
|
|
606
|
+
if t is not None and overlaps(t, d):
|
|
607
|
+
why = f"symlink {link} resolves into it"
|
|
608
|
+
break
|
|
609
|
+
if why:
|
|
610
|
+
kept.append(f"{d}/ ({why})")
|
|
611
|
+
else:
|
|
612
|
+
excluded.append(d)
|
|
613
|
+
return tuple(excluded), kept
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
# Docs-only descendants (opt-in per package: lean-pkg-binding.yaml committed at the bound commit, or the
|
|
617
|
+
# record field docs_descendants, `update NAME --accept-docs-descendants`). Build inputs, matched on
|
|
618
|
+
# package-relative paths at any depth.
|
|
619
|
+
DOCS_BUILD_BASENAMES = ("lake-manifest.json", "lean-toolchain")
|
|
620
|
+
# Changes the docs rule never admits, whatever the record's build_inputs say. lean-pkg-binding.yaml is the
|
|
621
|
+
# committed opt-in (binding_file, proposal 0002): read at the bound commit only, so a change to it after that
|
|
622
|
+
# commit is refused here and a reader at HEAD sees the very bytes that bound it (or none).
|
|
623
|
+
DOCS_ALWAYS_REFUSED = (".gitattributes", ".gitmodules", ".lfsconfig", "claims.yaml", "lean-pkg-binding.yaml")
|
|
624
|
+
# Files outside a subdirectory package that still change the bytes its build sees (filters, eol, LFS):
|
|
625
|
+
# checked at the repository root and in every directory between it and the package directory.
|
|
626
|
+
DOCS_ANCESTOR_FILES = (".gitattributes", ".gitmodules", ".lfsconfig")
|
|
627
|
+
# Lake's build caches and compiled artifacts (Lake 4.35: Lake/Config/Module.lean, Build/Common.lean,
|
|
628
|
+
# Util/NativeLib.lean): a `.lake` directory at any depth (build/, packages/, a dependency's own .lake) and
|
|
629
|
+
# any file with one of these suffixes. Lake reads them in place of rebuilding, so a committed one is never
|
|
630
|
+
# docs and never evidence, whatever the record's build_inputs say or where it lies (#5). Case-folded.
|
|
631
|
+
LAKE_ARTIFACT_SUFFIXES = (".olean", ".olean.server", ".olean.private", ".ilean", ".ir", ".ir.sig",
|
|
632
|
+
".trace", ".hash", ".c", ".c.o.export", ".c.o.noexport", ".bc", ".bc.o", ".o",
|
|
633
|
+
".ltar", ".so", ".dylib", ".dll", ".a", ".lib", ".exe")
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def lake_artifact(path: str) -> str | None:
|
|
637
|
+
"""`build cache/artifact ...` when the package-relative `path` has a `.lake` component at any depth
|
|
638
|
+
or ends in a Lake artifact suffix (LAKE_ARTIFACT_SUFFIXES); None otherwise."""
|
|
639
|
+
parts = [x.casefold() for x in path.replace("\\", "/").split("/") if x]
|
|
640
|
+
if ".lake" in parts:
|
|
641
|
+
return "build cache/artifact: under .lake/"
|
|
642
|
+
base = parts[-1] if parts else ""
|
|
643
|
+
for suf in sorted(LAKE_ARTIFACT_SUFFIXES, key=len, reverse=True):
|
|
644
|
+
if base.endswith(suf) and base != suf:
|
|
645
|
+
return f"build cache/artifact: *{suf}"
|
|
646
|
+
return None
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def resolve_tree_path(tree: dict[str, str], path: str) -> str | None:
|
|
650
|
+
"""The package-relative path `path` reaches at a commit whose tree is `tree` (bound_tree), every
|
|
651
|
+
committed symlink on the way followed (a chain, or a directory symlink part-way, included); None when
|
|
652
|
+
it leaves the package directory (absolute target, `..` above the top) or loops."""
|
|
653
|
+
links = {p: m.split(":", 1)[1].replace("\\", "/") for p, m in tree.items() if m.startswith("120000:")}
|
|
654
|
+
todo = [c for c in path.split("/") if c not in ("", ".")]
|
|
655
|
+
done: list[str] = []
|
|
656
|
+
hops = 0
|
|
657
|
+
while todo:
|
|
658
|
+
c = todo.pop(0)
|
|
659
|
+
if c == "..":
|
|
660
|
+
if not done:
|
|
661
|
+
return None
|
|
662
|
+
done.pop()
|
|
663
|
+
continue
|
|
664
|
+
cand = "/".join(done + [c])
|
|
665
|
+
if cand in links:
|
|
666
|
+
hops += 1
|
|
667
|
+
target = links[cand]
|
|
668
|
+
if hops > 40 or target.startswith("/"):
|
|
669
|
+
return None
|
|
670
|
+
todo = [x for x in target.split("/") if x not in ("", ".")] + todo
|
|
671
|
+
continue
|
|
672
|
+
done.append(c)
|
|
673
|
+
return "/".join(done)
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def is_evidence_path(path: str, formalization: str | None = None) -> bool:
|
|
677
|
+
"""A package-relative path the evidence-only rule treats as evidence: under .lean-receipts/ (or the
|
|
678
|
+
directory itself), or the package's formalization.yaml (derived keys may change)."""
|
|
679
|
+
return path == ".lean-receipts" or path.startswith(".lean-receipts/") or bool(
|
|
680
|
+
formalization and path == formalization)
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def evidence_symlinks(tree: dict[str, str], formalization: str | None = None) -> list[str]:
|
|
684
|
+
"""`path -> target` for each committed symlink whose target resolves into .lean-receipts/ (or to the
|
|
685
|
+
formalization file): a later commit could change what it points to as an evidence-only edit."""
|
|
686
|
+
out = []
|
|
687
|
+
for path, mode in sorted(tree.items()):
|
|
688
|
+
if mode.startswith("120000:") and not is_evidence_path(path, formalization):
|
|
689
|
+
r = resolve_tree_path(tree, path)
|
|
690
|
+
if r is not None and is_evidence_path(r, formalization):
|
|
691
|
+
out.append(f"{path} -> {mode.split(':', 1)[1]}")
|
|
692
|
+
return out
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def symlink_targets(tree: dict[str, str]) -> dict[str, str]:
|
|
696
|
+
"""{resolved package-relative target: symlink path} for every committed symlink that stays inside
|
|
697
|
+
the package directory and does not resolve to the package directory itself."""
|
|
698
|
+
out: dict[str, str] = {}
|
|
699
|
+
for path, mode in sorted(tree.items()):
|
|
700
|
+
if mode.startswith("120000:"):
|
|
701
|
+
r = resolve_tree_path(tree, path)
|
|
702
|
+
if r:
|
|
703
|
+
out.setdefault(r, path)
|
|
704
|
+
return out
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def linked_changes(targets: dict[str, str], paths: list[str]) -> list[str]:
|
|
708
|
+
"""`path (target of symlink L)` for each changed path that is a symlink target or lies under one."""
|
|
709
|
+
out = []
|
|
710
|
+
for x in paths:
|
|
711
|
+
for t, link in targets.items():
|
|
712
|
+
if x == t or x.startswith(t + "/"):
|
|
713
|
+
out.append(f"{x} (target of symlink {link})")
|
|
714
|
+
break
|
|
715
|
+
return out
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def linked_evidence_changes(repo: pathlib.Path, bound: str, paths: list[str],
|
|
719
|
+
formalization: str | None = None) -> list[str]:
|
|
720
|
+
"""The changed evidence paths that a symlink committed at `bound` resolves to (fails closed: an
|
|
721
|
+
unreadable tree counts every changed evidence path)."""
|
|
722
|
+
ev = [x for x in paths if is_evidence_path(x, formalization)]
|
|
723
|
+
if not ev:
|
|
724
|
+
return []
|
|
725
|
+
try:
|
|
726
|
+
tree = bound_tree(repo, bound)
|
|
727
|
+
except Fail:
|
|
728
|
+
return [f"{x} (the tree at {bound[:12]} is unreadable)" for x in ev]
|
|
729
|
+
if not any(m.startswith("120000:") for m in tree.values()):
|
|
730
|
+
return []
|
|
731
|
+
return linked_changes(symlink_targets(tree), ev)
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def ancestor_attribute_changes(repo: pathlib.Path, bound: str, head: str) -> list[str]:
|
|
735
|
+
"""Repository-relative paths of .gitattributes/.gitmodules/.lfsconfig that changed between bound and
|
|
736
|
+
head at the repository root or in any directory between it and the package directory `repo` (the
|
|
737
|
+
package directory itself is covered by the --relative diff). Empty at the repository root."""
|
|
738
|
+
prefix = git(repo, "rev-parse", "--show-prefix").stdout.strip().strip("/")
|
|
739
|
+
if not prefix:
|
|
740
|
+
return []
|
|
741
|
+
top = git(repo, "rev-parse", "--show-toplevel").stdout.strip()
|
|
742
|
+
parts = prefix.split("/")
|
|
743
|
+
dirs = [""] + ["/".join(parts[:i]) + "/" for i in range(1, len(parts))]
|
|
744
|
+
specs = [f":(literal){d}{f}" for d in dirs for f in DOCS_ANCESTOR_FILES]
|
|
745
|
+
p = git(pathlib.Path(top), "diff", "--no-renames", "--name-only", bound, head, "--", *specs)
|
|
746
|
+
return [x for x in p.stdout.splitlines() if x.strip()]
|
|
747
|
+
DOCS_PATHS_MAX = 50 # docs_paths recorded in an event / --json
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def checker_paths(repo: pathlib.Path, bound: str, checker) -> list[str]:
|
|
751
|
+
"""Best effort: the tokens of a receipt's `checker` text that name a file tracked at `bound`
|
|
752
|
+
(package-relative, no '..', not absolute). Those files are build inputs for the docs rule."""
|
|
753
|
+
if not isinstance(checker, str) or not checker.strip():
|
|
754
|
+
return []
|
|
755
|
+
try:
|
|
756
|
+
tokens = shlex.split(checker)
|
|
757
|
+
except ValueError:
|
|
758
|
+
tokens = checker.split()
|
|
759
|
+
out = []
|
|
760
|
+
for t in tokens:
|
|
761
|
+
t = t.strip()
|
|
762
|
+
while t.startswith("./"):
|
|
763
|
+
t = t[2:]
|
|
764
|
+
pp = pathlib.PurePosixPath(t) if t else None
|
|
765
|
+
if not t or t.startswith("-") or pp.is_absolute() or ".." in pp.parts or t in out:
|
|
766
|
+
continue
|
|
767
|
+
if git(repo, "cat-file", "-e", f"{bound}:./{t}").returncode == 0:
|
|
768
|
+
out.append(t)
|
|
769
|
+
return out
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
CLAIMS_COMMIT_FIRST = ("commit claims.yaml before the verify run, or re-gate "
|
|
773
|
+
"(docs/lifecycle.md#commit-the-claims-before-the-gate)")
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def docs_build_input(path: str, globs, extra, scopes=None) -> str | None:
|
|
777
|
+
"""Why a package-relative path is a build input for the docs rule, or None for a non-build file.
|
|
778
|
+
`scopes`: the Lake scopes (build_scope.LakeScope) read at the bound commit and at HEAD; a `.lean` file
|
|
779
|
+
is a build input when one of them owns it. None (no scope could be read): every `.lean` file is.
|
|
780
|
+
The record's build_inputs globs never match under .lean-receipts/: an extension-wide glob (`*.json`,
|
|
781
|
+
`**/*.json`) or an "everything but README" glob would otherwise turn new evidence into a build input."""
|
|
782
|
+
from .build_scope import scope_reason
|
|
783
|
+
art = lake_artifact(path) # before every admission, .lean-receipts/ included (#5)
|
|
784
|
+
if art:
|
|
785
|
+
return art
|
|
786
|
+
base = posixpath.basename(path)
|
|
787
|
+
if base in DOCS_ALWAYS_REFUSED:
|
|
788
|
+
return base
|
|
789
|
+
if base.endswith(".lean") and (scopes is None or base.startswith("lakefile.")):
|
|
790
|
+
return "*.lean"
|
|
791
|
+
for sc in scopes or []:
|
|
792
|
+
why = scope_reason(sc, path)
|
|
793
|
+
if why:
|
|
794
|
+
return why
|
|
795
|
+
if base.startswith("lakefile."):
|
|
796
|
+
return "lakefile.*"
|
|
797
|
+
if base in DOCS_BUILD_BASENAMES:
|
|
798
|
+
return base
|
|
799
|
+
if path in extra:
|
|
800
|
+
return "checker"
|
|
801
|
+
if is_evidence_path(path): # the evidence the gate reads: never a build input by a record's glob (#5)
|
|
802
|
+
return None
|
|
803
|
+
for g in globs or []:
|
|
804
|
+
if fnmatch.fnmatchcase(path, g) or ("/" not in g and fnmatch.fnmatchcase(base, g)):
|
|
805
|
+
return f"build_inputs {g}"
|
|
806
|
+
return None
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def ensure_interactive() -> None:
|
|
818
|
+
"""Every prompt path must call this first: off a tty, refuse (exit 2)
|
|
819
|
+
instead of blocking on input. Agents always use flags or --json."""
|
|
820
|
+
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
|
821
|
+
raise UsageError("interactive mode needs a tty on stdin+stdout; "
|
|
822
|
+
"use flags or --json instead")
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def print_json(payload) -> None:
|
|
826
|
+
print(json.dumps(payload, indent=2, sort_keys=True, default=str))
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
def require_nonempty(flag: str, value) -> None:
|
|
830
|
+
"""Refuse an empty or whitespace-only value for a flag that names something (a path, a repo)."""
|
|
831
|
+
if value is not None and not str(value).strip():
|
|
832
|
+
raise Fail(f"{flag} must not be empty")
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def local_path_key(stored) -> str:
|
|
836
|
+
"""Comparison form of a RECORDED local_path as this host resolves it: $HOME-joined (an absolute
|
|
837
|
+
path passes through, as in repo_path), normalised, symlinks resolved."""
|
|
838
|
+
return os.path.realpath(os.path.normpath(str(HOME / pathlib.Path(str(stored).strip()))))
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def normalize_local_path(p, flag: str = "--path") -> tuple[str, str]:
|
|
842
|
+
"""The one normaliser for a --path given to register / update --path: (stored form, comparison
|
|
843
|
+
key). A leading `~/` is expanded against $HOME (`~user` is refused); a relative path is taken
|
|
844
|
+
relative to $HOME; the stored form is $HOME-relative when the path lies under $HOME, absolute
|
|
845
|
+
otherwise, with `.`/`..`/`//`/trailing slashes collapsed. Empty or $HOME itself is refused."""
|
|
846
|
+
require_nonempty(flag, p)
|
|
847
|
+
s = str(p).strip()
|
|
848
|
+
if s == "~" or s.startswith("~/"):
|
|
849
|
+
s = str(HOME) + s[1:]
|
|
850
|
+
elif s.startswith("~"):
|
|
851
|
+
raise Fail(f"{flag} {p!r}: only a leading ~/ is expanded (to $HOME); give the path explicitly")
|
|
852
|
+
home = os.path.normpath(str(HOME))
|
|
853
|
+
absolute = os.path.normpath(os.path.join(home, s))
|
|
854
|
+
if absolute == home:
|
|
855
|
+
raise Fail(f"{flag} {p!r} resolves to $HOME itself; name the package checkout")
|
|
856
|
+
rel = os.path.relpath(absolute, home)
|
|
857
|
+
stored = absolute if rel == ".." or rel.startswith("../") else rel
|
|
858
|
+
return stored, os.path.realpath(absolute)
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def detect_toolchain(repo: pathlib.Path) -> tuple[str | None, str | None]:
|
|
862
|
+
"""(toolchain, warning) from the first line of <repo>/lean-toolchain."""
|
|
863
|
+
f = repo / "lean-toolchain"
|
|
864
|
+
if not f.is_file():
|
|
865
|
+
return None, f"no lean-toolchain at {f}"
|
|
866
|
+
lines = f.read_text().splitlines()
|
|
867
|
+
if not lines or not lines[0].strip():
|
|
868
|
+
return None, f"empty lean-toolchain at {f}"
|
|
869
|
+
return lines[0].strip(), None
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
LEAN_LIB_RE = re.compile(r"^\s*lean_lib\s+(«[^»\n]+»|[A-Za-z_][A-Za-z0-9_'!?.]*)", re.MULTILINE)
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def lean_root_namespaces(repo: pathlib.Path) -> set[str]:
|
|
876
|
+
"""Root namespaces (top-level module names) a checkout's Lean libraries claim, from the working
|
|
877
|
+
tree: every `lean_lib` in lakefile.lean, else every [[lean_lib]] name in lakefile.toml, else the
|
|
878
|
+
top-level *.lean files (lakefile.lean excluded). Empty when nothing is found or readable (#22.7)."""
|
|
879
|
+
names: list[str] = []
|
|
880
|
+
try:
|
|
881
|
+
text = (repo / "lakefile.lean").read_text(encoding="utf-8", errors="replace")
|
|
882
|
+
names = [m.group(1) for m in LEAN_LIB_RE.finditer(text)]
|
|
883
|
+
except OSError:
|
|
884
|
+
pass
|
|
885
|
+
if not names:
|
|
886
|
+
try:
|
|
887
|
+
import tomllib
|
|
888
|
+
data = tomllib.loads((repo / "lakefile.toml").read_text(encoding="utf-8"))
|
|
889
|
+
libs = data.get("lean_lib") or []
|
|
890
|
+
names = [str(lib["name"]) for lib in libs if isinstance(lib, dict) and lib.get("name")]
|
|
891
|
+
except (OSError, ValueError, TypeError):
|
|
892
|
+
pass
|
|
893
|
+
if not names:
|
|
894
|
+
try:
|
|
895
|
+
names = [p.stem for p in repo.glob("*.lean") if p.name != "lakefile.lean"]
|
|
896
|
+
except OSError:
|
|
897
|
+
names = []
|
|
898
|
+
return {n.strip("«»").split(".")[0] for n in names if n.strip("«»")}
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def namespace_clashes(reg: dict, repo: pathlib.Path, skip: str | None = None) -> dict[str, list[str]]:
|
|
902
|
+
"""{root namespace: [other package names]} for the namespaces of `repo` that another registered
|
|
903
|
+
package's checkout (on this host) also claims."""
|
|
904
|
+
mine = lean_root_namespaces(repo) if repo.is_dir() else set()
|
|
905
|
+
out: dict[str, list[str]] = {}
|
|
906
|
+
if not mine:
|
|
907
|
+
return out
|
|
908
|
+
for other in sorted(reg.get("packages") or {}):
|
|
909
|
+
pkg = reg["packages"][other] or {}
|
|
910
|
+
if other == skip or not pkg.get("local_path"):
|
|
911
|
+
continue
|
|
912
|
+
try:
|
|
913
|
+
theirs = repo_path(pkg)
|
|
914
|
+
if theirs.resolve() == repo.resolve() or not theirs.is_dir():
|
|
915
|
+
continue
|
|
916
|
+
except (OSError, ValueError, TypeError):
|
|
917
|
+
continue
|
|
918
|
+
for ns in sorted(mine & lean_root_namespaces(theirs)):
|
|
919
|
+
out.setdefault(ns, []).append(other)
|
|
920
|
+
return out
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def namespace_notes(clashes: dict[str, list[str]]) -> list[str]:
|
|
924
|
+
return [f"note: Lean root namespace {ns} is also used by {', '.join(others)}; two packages with one "
|
|
925
|
+
f"root namespace cannot be built or imported together (rename one lean_lib)"
|
|
926
|
+
for ns, others in clashes.items()]
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def detect_mathlib_pin(repo: pathlib.Path) -> tuple[str | None, str | None]:
|
|
930
|
+
"""(short pin, warning): rev of the mathlib package in lake-manifest.json."""
|
|
931
|
+
mf = repo / "lake-manifest.json"
|
|
932
|
+
if not mf.is_file():
|
|
933
|
+
return None, "no lake-manifest.json — mathlib_pin set to null"
|
|
934
|
+
try:
|
|
935
|
+
data = json.loads(mf.read_text())
|
|
936
|
+
except ValueError:
|
|
937
|
+
return None, "lake-manifest.json is not valid JSON — mathlib_pin set to null"
|
|
938
|
+
for p in data.get("packages") or []:
|
|
939
|
+
if str(p.get("name", "")).lower() in ("mathlib", "«mathlib»"):
|
|
940
|
+
rev = p.get("rev")
|
|
941
|
+
if rev:
|
|
942
|
+
return str(rev)[:10], None
|
|
943
|
+
return None, "mathlib is a path dep or has no rev in " \
|
|
944
|
+
"lake-manifest.json — mathlib_pin set to null"
|
|
945
|
+
return None, "no mathlib package in lake-manifest.json — mathlib_pin set to null"
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
# --------------------------------------------------------------------------
|
|
949
|
+
# registry IO, events
|
|
950
|
+
|
|
951
|
+
def registry_not_found(path: pathlib.Path) -> str:
|
|
952
|
+
"""The refusal for a missing registry: where the path came from and how to make one."""
|
|
953
|
+
src = _RESOLVED_SOURCE.get(str(path))
|
|
954
|
+
return (f"registry not found: {path} (" + (f"resolved from {src}; " if src else "")
|
|
955
|
+
+ f"create one with `lean-pkg registry init`, or set {REGISTRY_ENV} / ~/.lean-pkg/registry)")
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def load_registry(path: pathlib.Path, *, check_version: bool = True) -> dict:
|
|
959
|
+
if not path.is_file():
|
|
960
|
+
raise Fail(registry_not_found(path))
|
|
961
|
+
try:
|
|
962
|
+
data = yaml.safe_load(path.read_text())
|
|
963
|
+
except yaml.YAMLError as e:
|
|
964
|
+
raise Fail(f"registry is not valid YAML: {e}") from e
|
|
965
|
+
if not isinstance(data, dict) or not isinstance(data.get("packages"), dict):
|
|
966
|
+
raise Fail(f"registry has no top-level 'packages' map: {path}")
|
|
967
|
+
v = data.get("version")
|
|
968
|
+
if check_version and isinstance(v, int) and not isinstance(v, bool) \
|
|
969
|
+
and v > max(SUPPORTED_REGISTRY_VERSIONS):
|
|
970
|
+
# A newer schema read by an older lean-pkg: refuse rather than show a silently partial view.
|
|
971
|
+
raise Fail(f"registry schema version {v} is not supported (supported: "
|
|
972
|
+
f"{', '.join(map(str, SUPPORTED_REGISTRY_VERSIONS))}); this lean-pkg is older than the "
|
|
973
|
+
f"registry: upgrade lean-pkg (`lean-pkg migrate` upgrades only older registries)")
|
|
974
|
+
global _LOADED_PACKAGES
|
|
975
|
+
_LOADED_PACKAGES = data["packages"]
|
|
976
|
+
_LOADED_TOP.clear() # the other top-level keys (version, lean_pkg, ...): the recommended-version notice
|
|
977
|
+
_LOADED_TOP.update((k, v) for k, v in data.items() if k != "packages")
|
|
978
|
+
return data
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
LOCK_SUFFIX = ".lock"
|
|
982
|
+
_LOCKS_HELD: dict[str, int] = {} # lock file -> nesting depth held by THIS process
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def lock_path(reg_path: pathlib.Path) -> pathlib.Path:
|
|
986
|
+
"""<registry>.lock, beside the registry file (a symlinked registry locks beside its target)."""
|
|
987
|
+
p = pathlib.Path(reg_path).resolve()
|
|
988
|
+
return p.with_name(p.name + LOCK_SUFFIX)
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
@contextlib.contextmanager
|
|
992
|
+
def registry_lock(reg_path: pathlib.Path):
|
|
993
|
+
"""Exclusive fcntl.flock on <registry>.lock for load -> check -> mutate -> save -> append.
|
|
994
|
+
|
|
995
|
+
Every writer takes it, so concurrent processes on one host serialize; the lock file is created if
|
|
996
|
+
missing and never deleted. Reentrant within a process (save_registry takes it too)."""
|
|
997
|
+
lp = lock_path(reg_path)
|
|
998
|
+
key = str(lp)
|
|
999
|
+
if key in _LOCKS_HELD:
|
|
1000
|
+
_LOCKS_HELD[key] += 1
|
|
1001
|
+
try:
|
|
1002
|
+
yield lp
|
|
1003
|
+
finally:
|
|
1004
|
+
_LOCKS_HELD[key] -= 1
|
|
1005
|
+
return
|
|
1006
|
+
try:
|
|
1007
|
+
fd = os.open(lp, os.O_RDWR | os.O_CREAT, 0o666)
|
|
1008
|
+
except OSError as e:
|
|
1009
|
+
raise Fail(f"cannot open the registry lock {lp}: {e.strerror or e}") from e
|
|
1010
|
+
try:
|
|
1011
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
1012
|
+
_LOCKS_HELD[key] = 1
|
|
1013
|
+
try:
|
|
1014
|
+
yield lp
|
|
1015
|
+
finally:
|
|
1016
|
+
del _LOCKS_HELD[key]
|
|
1017
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
1018
|
+
finally:
|
|
1019
|
+
os.close(fd)
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
def _umask() -> int:
|
|
1023
|
+
old = os.umask(0)
|
|
1024
|
+
os.umask(old)
|
|
1025
|
+
return old
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def save_registry(path: pathlib.Path, data: dict) -> None:
|
|
1029
|
+
"""Atomic save (private temp file in the same directory, fsync, os.replace; the old file's mode is
|
|
1030
|
+
kept), then the event lines record() queued on `data` are appended. Under the registry lock. Every
|
|
1031
|
+
event log with queued lines is checked appendable first: one that is not (read-only, a directory)
|
|
1032
|
+
refuses the save with nothing written, so a YAML change never lands without its event line."""
|
|
1033
|
+
path = pathlib.Path(path)
|
|
1034
|
+
target = path.resolve() if path.is_symlink() else path
|
|
1035
|
+
text = yaml.safe_dump(data, sort_keys=False, default_flow_style=False, allow_unicode=True, width=120)
|
|
1036
|
+
with registry_lock(target):
|
|
1037
|
+
check_event_logs_appendable(data)
|
|
1038
|
+
fd, tmp = tempfile.mkstemp(dir=target.parent, prefix=target.name + ".", suffix=".tmp")
|
|
1039
|
+
try:
|
|
1040
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
1041
|
+
f.write(text)
|
|
1042
|
+
f.flush()
|
|
1043
|
+
os.fsync(f.fileno())
|
|
1044
|
+
try:
|
|
1045
|
+
mode = stat.S_IMODE(os.stat(target).st_mode)
|
|
1046
|
+
except FileNotFoundError:
|
|
1047
|
+
mode = 0o666 & ~_umask()
|
|
1048
|
+
os.chmod(tmp, mode)
|
|
1049
|
+
os.replace(tmp, target)
|
|
1050
|
+
except BaseException:
|
|
1051
|
+
with contextlib.suppress(OSError):
|
|
1052
|
+
os.unlink(tmp)
|
|
1053
|
+
raise
|
|
1054
|
+
flush_events(data)
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
LEAN_PKG_HOME_ENV = "LEAN_PKG_HOME"
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def lean_pkg_home() -> pathlib.Path:
|
|
1061
|
+
"""The user-level base directory: $LEAN_PKG_HOME, else ~/.lean-pkg (read at call time, not import time)."""
|
|
1062
|
+
env = os.environ.get(LEAN_PKG_HOME_ENV, "").strip()
|
|
1063
|
+
return pathlib.Path(env).expanduser() if env else pathlib.Path.home() / ".lean-pkg"
|
|
1064
|
+
|
|
1065
|
+
|
|
1066
|
+
def user_default_registry() -> tuple[pathlib.Path | None, str]:
|
|
1067
|
+
"""(registry file or None, detail) for the user-level default <lean_pkg_home>/registry.
|
|
1068
|
+
|
|
1069
|
+
A directory (or a symlink to one) holding lean-packages.yaml yields that file; a file (or a symlink to one) IS
|
|
1070
|
+
the registry file, resolved so that saves rewrite the target, not the link, and the event log lands beside it."""
|
|
1071
|
+
p = lean_pkg_home() / "registry"
|
|
1072
|
+
if p.is_dir():
|
|
1073
|
+
f = p / DEFAULT_REGISTRY_NAME
|
|
1074
|
+
if f.is_file():
|
|
1075
|
+
return f, f"{f}" + (f" ({p} -> {p.resolve()})" if p.is_symlink() else "")
|
|
1076
|
+
return None, f"{p} is a directory without {DEFAULT_REGISTRY_NAME}; not used"
|
|
1077
|
+
if p.is_file():
|
|
1078
|
+
f = p.resolve() if p.is_symlink() else p
|
|
1079
|
+
return f, f"{p}" + (f" -> {f}" if f != p else "") + " (registry file)"
|
|
1080
|
+
if p.is_symlink():
|
|
1081
|
+
return None, f"{p} is a dangling symlink; not used"
|
|
1082
|
+
return None, (f"{p} not configured (mkdir -p {p.parent} && ln -s /path/to/registry-repo {p}; "
|
|
1083
|
+
f"base dir: env {LEAN_PKG_HOME_ENV})")
|
|
1084
|
+
|
|
1085
|
+
|
|
1086
|
+
_RESOLVED_SOURCE: dict[str, str] = {} # registry path -> how registry_source found it (for the not-found hint)
|
|
1087
|
+
|
|
1088
|
+
|
|
1089
|
+
def registry_source(args) -> tuple[pathlib.Path, str]:
|
|
1090
|
+
"""(registry path, source): --registry "flag", else $LEAN_PKG_REGISTRY "env", else the user-level default
|
|
1091
|
+
<lean_pkg_home>/registry "user-default", else ./lean-packages.yaml "cwd". A flag or env value naming a
|
|
1092
|
+
directory means its lean-packages.yaml, as the user-level default does."""
|
|
1093
|
+
if getattr(args, "registry", None) or os.environ.get(REGISTRY_ENV, "").strip():
|
|
1094
|
+
path, src = (pathlib.Path(args.registry).expanduser(), "flag") if getattr(args, "registry", None) \
|
|
1095
|
+
else (pathlib.Path(os.environ[REGISTRY_ENV].strip()).expanduser(), "env")
|
|
1096
|
+
if path.is_dir():
|
|
1097
|
+
path = path / DEFAULT_REGISTRY_NAME
|
|
1098
|
+
else:
|
|
1099
|
+
user, _ = user_default_registry()
|
|
1100
|
+
path, src = (user, "user-default") if user is not None \
|
|
1101
|
+
else (pathlib.Path.cwd() / DEFAULT_REGISTRY_NAME, "cwd")
|
|
1102
|
+
_RESOLVED_SOURCE[str(path)] = src
|
|
1103
|
+
return path, src
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
def registry_path(args) -> pathlib.Path:
|
|
1107
|
+
"""--registry, else $LEAN_PKG_REGISTRY, else ~/.lean-pkg/registry, else ./lean-packages.yaml."""
|
|
1108
|
+
return registry_source(args)[0]
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
EVENTS_ENV = "LEAN_PKG_EVENTS"
|
|
1112
|
+
|
|
1113
|
+
|
|
1114
|
+
def events_source(args) -> tuple[pathlib.Path, str]:
|
|
1115
|
+
"""(event log path, source): --events "flag"; else, when --registry is given, its sibling
|
|
1116
|
+
lean-package-events.jsonl "registry-sibling" (an explicit registry never writes into the log env
|
|
1117
|
+
LEAN_PKG_EVENTS names); else env LEAN_PKG_EVENTS "env"; else the resolved registry's sibling "sibling"."""
|
|
1118
|
+
if getattr(args, "events", None):
|
|
1119
|
+
return pathlib.Path(args.events).expanduser(), "flag"
|
|
1120
|
+
if getattr(args, "registry", None):
|
|
1121
|
+
return registry_path(args).parent / EVENTS_NAME, "registry-sibling"
|
|
1122
|
+
env = os.environ.get(EVENTS_ENV, "").strip()
|
|
1123
|
+
if env:
|
|
1124
|
+
return pathlib.Path(env).expanduser(), "env"
|
|
1125
|
+
return registry_path(args).parent / EVENTS_NAME, "sibling"
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
def events_path(args) -> pathlib.Path:
|
|
1129
|
+
"""--events, else the sibling of an explicit --registry, else env LEAN_PKG_EVENTS, else the sibling
|
|
1130
|
+
lean-package-events.jsonl of the resolved registry."""
|
|
1131
|
+
return events_source(args)[0]
|
|
1132
|
+
|
|
1133
|
+
|
|
1134
|
+
SNAPSHOT_ENV = "LEAN_PKG_REGISTRY_SNAPSHOT"
|
|
1135
|
+
SNAPSHOT_REFUSAL = "read-only: --registry-snapshot"
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
def registry_snapshot_arg(args) -> str | None:
|
|
1139
|
+
"""--registry-snapshot COMMIT, else env LEAN_PKG_REGISTRY_SNAPSHOT, else None."""
|
|
1140
|
+
flag = (getattr(args, "registry_snapshot", None) or "").strip()
|
|
1141
|
+
return flag or os.environ.get(SNAPSHOT_ENV, "").strip() or None
|
|
1142
|
+
|
|
1143
|
+
|
|
1144
|
+
def registry_sync_counts(root: pathlib.Path, branch: str) -> tuple[int, int] | None:
|
|
1145
|
+
"""(behind, ahead) of HEAD against the local ref refs/remotes/origin/BRANCH, as last fetched (this never
|
|
1146
|
+
fetches); None when there is no such ref. The one count behind doctor's registry-repo and install lines
|
|
1147
|
+
and registry_state."""
|
|
1148
|
+
counts = registry_git(root, "rev-list", "--left-right", "--count", f"refs/remotes/origin/{branch}...HEAD")
|
|
1149
|
+
if counts.returncode != 0:
|
|
1150
|
+
return None
|
|
1151
|
+
try:
|
|
1152
|
+
behind, ahead = (int(x) for x in counts.stdout.split())
|
|
1153
|
+
except ValueError:
|
|
1154
|
+
return None
|
|
1155
|
+
return behind, ahead
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
def registry_state(reg_p: pathlib.Path) -> dict | None:
|
|
1159
|
+
"""The registry commit a reader's lease state comes from (#385), from local refs only (no fetch, no
|
|
1160
|
+
network): {root, commit, committed_at, age_seconds, branch, upstream, behind, ahead, dirty}. branch is
|
|
1161
|
+
null on a detached HEAD; upstream, behind and ahead are null without a local origin/<branch> ref; dirty
|
|
1162
|
+
says the registry file has uncommitted changes (null when git cannot tell). None when git is not on
|
|
1163
|
+
PATH, the registry is not inside a git work tree or HEAD has no commit: never an error."""
|
|
1164
|
+
if shutil.which("git") is None:
|
|
1165
|
+
return None
|
|
1166
|
+
reg_p = pathlib.Path(os.path.realpath(pathlib.Path(reg_p).expanduser()))
|
|
1167
|
+
if reg_p.is_dir():
|
|
1168
|
+
reg_p = reg_p / DEFAULT_REGISTRY_NAME
|
|
1169
|
+
if not reg_p.parent.is_dir():
|
|
1170
|
+
return None
|
|
1171
|
+
top = registry_git(reg_p.parent, "rev-parse", "--show-toplevel")
|
|
1172
|
+
if top.returncode != 0 or not top.stdout.strip():
|
|
1173
|
+
return None
|
|
1174
|
+
root = pathlib.Path(top.stdout.strip())
|
|
1175
|
+
log = registry_git(root, "log", "-1", "--format=%H %cI")
|
|
1176
|
+
fields = log.stdout.split() if log.returncode == 0 else []
|
|
1177
|
+
if len(fields) != 2:
|
|
1178
|
+
return None # an unborn HEAD: nothing committed yet
|
|
1179
|
+
sha, committed_at = fields
|
|
1180
|
+
try:
|
|
1181
|
+
age = int((dt.datetime.now(dt.timezone.utc) - dt.datetime.fromisoformat(committed_at)).total_seconds())
|
|
1182
|
+
except ValueError:
|
|
1183
|
+
age = None
|
|
1184
|
+
br = registry_git(root, "symbolic-ref", "-q", "--short", "HEAD")
|
|
1185
|
+
branch = br.stdout.strip() if br.returncode == 0 and br.stdout.strip() else None
|
|
1186
|
+
counts = registry_sync_counts(root, branch) if branch else None
|
|
1187
|
+
st = registry_git(root, "--no-optional-locks", "status", "--porcelain", "--untracked-files=no", "--",
|
|
1188
|
+
str(reg_p))
|
|
1189
|
+
return {"root": str(root), "commit": sha, "committed_at": committed_at,
|
|
1190
|
+
"age_seconds": None if age is None else max(age, 0), "branch": branch,
|
|
1191
|
+
"upstream": f"origin/{branch}" if counts is not None else None,
|
|
1192
|
+
"behind": counts[0] if counts is not None else None,
|
|
1193
|
+
"ahead": counts[1] if counts is not None else None,
|
|
1194
|
+
"dirty": bool(st.stdout.strip()) if st.returncode == 0 else None}
|
|
1195
|
+
|
|
1196
|
+
|
|
1197
|
+
def registry_state_of(args) -> dict | None:
|
|
1198
|
+
"""registry_state for the invocation's registry; None under --registry-snapshot (the reader named the
|
|
1199
|
+
commit itself) and on any internal error (a stamp must never fail the command)."""
|
|
1200
|
+
if registry_snapshot_arg(args):
|
|
1201
|
+
return None
|
|
1202
|
+
try:
|
|
1203
|
+
return registry_state(registry_path(args))
|
|
1204
|
+
except Exception: # noqa: BLE001 -- best effort: the stamp is information, never a refusal
|
|
1205
|
+
return None
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def registry_behind_warning(state: dict | None) -> str | None:
|
|
1209
|
+
"""The one stderr line a lease reader prints when its registry clone is behind the origin/<branch> it last
|
|
1210
|
+
fetched (#385); None when it is not, or cannot be told. Local refs only: a clone that was never fetched
|
|
1211
|
+
looks up to date, which is why every lease line also names the commit it was read from."""
|
|
1212
|
+
if not state or not state.get("behind"):
|
|
1213
|
+
return None
|
|
1214
|
+
root = shlex.quote(state["root"])
|
|
1215
|
+
return (f"lean-pkg: WARN: registry clone is {state['behind']} commit(s) behind {state['upstream']} as last "
|
|
1216
|
+
f"fetched (lease state may be stale): git -C {root} pull --ff-only, or lean-pkg doctor --fetch")
|
|
1217
|
+
|
|
1218
|
+
|
|
1219
|
+
def registry_home_dir(args) -> pathlib.Path:
|
|
1220
|
+
"""The directory the registry file lives in: under --registry-snapshot the working-tree directory, not
|
|
1221
|
+
the temporary copy (siblings such as index/ and the adoption ledger are read from there)."""
|
|
1222
|
+
origin = getattr(args, "snapshot_origin_dir", None)
|
|
1223
|
+
return pathlib.Path(origin) if origin else registry_path(args).parent
|
|
1224
|
+
|
|
1225
|
+
|
|
1226
|
+
def _git_show_bytes(top: pathlib.Path, rev: str, rel: str) -> bytes | None:
|
|
1227
|
+
"""The blob `git show REV:REL` in the repository at `top`, or None when REL is not in REV."""
|
|
1228
|
+
try:
|
|
1229
|
+
p = subprocess.run(["git", "-C", str(top), "show", f"{rev}:{rel}"],
|
|
1230
|
+
capture_output=True, check=False)
|
|
1231
|
+
except OSError as e:
|
|
1232
|
+
raise Fail(f"--registry-snapshot: cannot run git: {e.strerror or e}") from e
|
|
1233
|
+
return p.stdout if p.returncode == 0 else None
|
|
1234
|
+
|
|
1235
|
+
|
|
1236
|
+
def materialize_snapshot(args, commit: str, tmp: pathlib.Path) -> str:
|
|
1237
|
+
"""Write the registry file (and its event log, when that commit has one) as of COMMIT into `tmp` and
|
|
1238
|
+
point args at the copies; returns the full commit sha. The registry must live in a git work tree."""
|
|
1239
|
+
reg_p, _ = registry_source(args)
|
|
1240
|
+
reg_p = pathlib.Path(os.path.realpath(reg_p.expanduser()))
|
|
1241
|
+
if reg_p.is_dir():
|
|
1242
|
+
reg_p = reg_p / DEFAULT_REGISTRY_NAME
|
|
1243
|
+
ev_p = pathlib.Path(os.path.realpath(events_path(args)))
|
|
1244
|
+
d = reg_p.parent
|
|
1245
|
+
top_p = registry_git(d, "rev-parse", "--show-toplevel") if d.is_dir() else None
|
|
1246
|
+
if top_p is None or top_p.returncode != 0 or not top_p.stdout.strip():
|
|
1247
|
+
raise Fail(f"--registry-snapshot: the registry {reg_p} is not inside a git work tree")
|
|
1248
|
+
top = pathlib.Path(os.path.realpath(top_p.stdout.strip()))
|
|
1249
|
+
rv = registry_git(top, "rev-parse", "--verify", "--quiet", f"{commit}^{{commit}}")
|
|
1250
|
+
sha = rv.stdout.strip()
|
|
1251
|
+
if rv.returncode != 0 or not sha:
|
|
1252
|
+
raise Fail(f"--registry-snapshot: {commit!r} is not a commit in {top}")
|
|
1253
|
+
rel = reg_p.relative_to(top).as_posix()
|
|
1254
|
+
blob = _git_show_bytes(top, sha, rel)
|
|
1255
|
+
if blob is None:
|
|
1256
|
+
raise Fail(f"--registry-snapshot: {rel} does not exist at {sha[:12]} in {top}")
|
|
1257
|
+
snap_reg = tmp / DEFAULT_REGISTRY_NAME
|
|
1258
|
+
snap_reg.write_bytes(blob)
|
|
1259
|
+
snap_ev = tmp / EVENTS_NAME # absent unless the commit has the log: an empty history, never the live log
|
|
1260
|
+
try:
|
|
1261
|
+
ev_rel = ev_p.relative_to(top).as_posix()
|
|
1262
|
+
except ValueError:
|
|
1263
|
+
ev_rel = None
|
|
1264
|
+
ev_blob = _git_show_bytes(top, sha, ev_rel) if ev_rel else None
|
|
1265
|
+
if ev_blob is not None:
|
|
1266
|
+
snap_ev.write_bytes(ev_blob)
|
|
1267
|
+
args.snapshot_origin_dir = str(d)
|
|
1268
|
+
args.registry, args.events = str(snap_reg), str(snap_ev)
|
|
1269
|
+
args.no_commit = True
|
|
1270
|
+
args.registry_snapshot_sha = sha
|
|
1271
|
+
return sha
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
|
|
1275
|
+
|
|
1276
|
+
|
|
1277
|
+
|
|
1278
|
+
def _event_line(ts: str, name, event: str, **fields) -> str:
|
|
1279
|
+
"""One event-log line: EVENT_LINE_KEYS (`v` last, so no field can replace it) and the event's fields."""
|
|
1280
|
+
return json.dumps({"ts": ts, "event": event, "name": name, **fields, "v": EVENT_LINE_VERSION},
|
|
1281
|
+
sort_keys=True) + "\n"
|
|
1282
|
+
|
|
1283
|
+
|
|
1284
|
+
def _write_event_lines(events_p: pathlib.Path, lines: list[str]) -> None:
|
|
1285
|
+
events_p.parent.mkdir(parents=True, exist_ok=True)
|
|
1286
|
+
with open(events_p, "a", encoding="utf-8") as f:
|
|
1287
|
+
f.write("".join(lines))
|
|
1288
|
+
f.flush()
|
|
1289
|
+
os.fsync(f.fileno())
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
def append_event(events_p: pathlib.Path, ts: str, name, event: str, **fields) -> None:
|
|
1293
|
+
"""Append one event line now: for events with no registry change to save (registry-created after
|
|
1294
|
+
the file is written, registry-migrated after the save, index-added, prior-art-searched)."""
|
|
1295
|
+
_write_event_lines(events_p, [_event_line(ts, name, event, **fields)])
|
|
1296
|
+
|
|
1297
|
+
|
|
1298
|
+
# Event lines record() queued, per registry object (id -> (the object, [(events path, line)])); the
|
|
1299
|
+
# object is held so its id cannot be reused. save_registry flushes them AFTER the YAML is replaced, so
|
|
1300
|
+
# a failure before the save leaves no orphan event line.
|
|
1301
|
+
_PENDING_EVENTS: dict[int, tuple[dict, list[tuple[pathlib.Path, str]]]] = {}
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def _event_log_problem(p: pathlib.Path) -> str | None:
|
|
1305
|
+
"""Why the event log `p` cannot be appended to, or None. Nothing is created: an existing file is
|
|
1306
|
+
opened for append and closed (its content and mtime unchanged); a missing one needs its nearest
|
|
1307
|
+
existing ancestor to be a writable directory (_write_event_lines creates the rest)."""
|
|
1308
|
+
try:
|
|
1309
|
+
if p.exists() or p.is_symlink():
|
|
1310
|
+
if p.is_dir():
|
|
1311
|
+
return "is a directory"
|
|
1312
|
+
with open(p, "a", encoding="utf-8"):
|
|
1313
|
+
pass
|
|
1314
|
+
return None
|
|
1315
|
+
anc = p.parent
|
|
1316
|
+
while not anc.exists():
|
|
1317
|
+
if anc.parent == anc:
|
|
1318
|
+
break
|
|
1319
|
+
anc = anc.parent
|
|
1320
|
+
if not anc.is_dir():
|
|
1321
|
+
return f"{anc} is not a directory"
|
|
1322
|
+
if not os.access(anc, os.W_OK | os.X_OK):
|
|
1323
|
+
return f"{anc} is not writable"
|
|
1324
|
+
return None
|
|
1325
|
+
except OSError as e:
|
|
1326
|
+
return e.strerror or type(e).__name__
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
def check_event_logs_appendable(reg: dict) -> None:
|
|
1330
|
+
"""Fail (nothing written) when an event log with lines queued on `reg` cannot be appended to."""
|
|
1331
|
+
entry = _PENDING_EVENTS.get(id(reg))
|
|
1332
|
+
for p in dict.fromkeys(p for p, _ in (entry[1] if entry else [])):
|
|
1333
|
+
why = _event_log_problem(p)
|
|
1334
|
+
if why:
|
|
1335
|
+
raise Fail(f"event log {p} cannot be appended to ({why}); nothing written — fix the event "
|
|
1336
|
+
f"log (or pass --events PATH) and re-run")
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
def flush_events(reg: dict) -> None:
|
|
1340
|
+
"""Append the lines queued on `reg` (one write + fsync per event log) and forget them. A log that
|
|
1341
|
+
cannot be written raises with its lines (and those of the logs not yet reached) still queued."""
|
|
1342
|
+
entry = _PENDING_EVENTS.get(id(reg))
|
|
1343
|
+
if not entry:
|
|
1344
|
+
return
|
|
1345
|
+
by_path: dict[pathlib.Path, list[str]] = {}
|
|
1346
|
+
for p, line in entry[1]:
|
|
1347
|
+
by_path.setdefault(p, []).append(line)
|
|
1348
|
+
for p, lines in by_path.items():
|
|
1349
|
+
_write_event_lines(p, lines)
|
|
1350
|
+
entry[1][:] = [(q, line) for q, line in entry[1] if q != p]
|
|
1351
|
+
_PENDING_EVENTS.pop(id(reg), None)
|
|
1352
|
+
|
|
1353
|
+
|
|
1354
|
+
# #21.3: the agent a gate/comparator/record/promote --yes/claims sync/search --record invocation acts as
|
|
1355
|
+
# (its --agent), set by lease_actor() for this invocation; record() stores it as `actor`.
|
|
1356
|
+
_ACTOR: dict = {"agent": None}
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
def lease_actor(reg: dict, name: str | None, agent: str | None, what: str) -> str | None:
|
|
1360
|
+
"""The lease-holder rule for evidence writers that take an optional --agent (#21.3). With --agent:
|
|
1361
|
+
another agent's live lease refuses (an unparseable lease too), and the agent is recorded as the
|
|
1362
|
+
event's `actor`. Without it nothing is refused (the behaviour before #21.3); a live lease returns
|
|
1363
|
+
a warning naming the holder, which the caller prints on stderr."""
|
|
1364
|
+
_ACTOR["agent"] = agent or None
|
|
1365
|
+
pkg = (reg.get("packages") or {}).get(name) if name else None
|
|
1366
|
+
if not isinstance(pkg, dict):
|
|
1367
|
+
return None
|
|
1368
|
+
lease = pkg.get("lease")
|
|
1369
|
+
live = lease_live_or_none(lease, dt.datetime.now(dt.timezone.utc))
|
|
1370
|
+
if live is None:
|
|
1371
|
+
if agent:
|
|
1372
|
+
refuse_invalid_lease(name, lease)
|
|
1373
|
+
return None
|
|
1374
|
+
if not live:
|
|
1375
|
+
return None
|
|
1376
|
+
holder = lease.get("agent")
|
|
1377
|
+
if not agent:
|
|
1378
|
+
return (f"{name}: lease held by {holder}; {what} without --agent does not check the holder "
|
|
1379
|
+
f"(pass --agent {holder} to record the actor; another agent is then refused)")
|
|
1380
|
+
if agent != holder:
|
|
1381
|
+
raise Fail(f"{name}: lease held by {holder}, not {agent} — {what} refused; ask {holder} to "
|
|
1382
|
+
f"release it, or run as --agent {holder}")
|
|
1383
|
+
return None
|
|
1384
|
+
|
|
1385
|
+
|
|
1386
|
+
def warn_lease(msg: str | None) -> None:
|
|
1387
|
+
if msg:
|
|
1388
|
+
print(f"lean-pkg: warning: {msg}", file=sys.stderr)
|
|
1389
|
+
|
|
1390
|
+
|
|
1391
|
+
def record(reg: dict, events_p: pathlib.Path, pkg: dict, event: str, **fields) -> None:
|
|
1392
|
+
"""One transition = one history[] entry + one event-log line. Append-only. The line is queued and
|
|
1393
|
+
written by the save_registry(reg) that persists the history entry, never before it."""
|
|
1394
|
+
if _ACTOR["agent"] and "agent" not in fields and "actor" not in fields:
|
|
1395
|
+
fields = {**fields, "actor": _ACTOR["agent"]}
|
|
1396
|
+
ts = now_iso()
|
|
1397
|
+
pkg.setdefault("history", []).append({"ts": ts, "event": event, **fields})
|
|
1398
|
+
_PENDING_EVENTS.setdefault(id(reg), (reg, []))[1].append(
|
|
1399
|
+
(pathlib.Path(events_p), _event_line(ts, pkg.get("name"), event, **fields)))
|
|
1400
|
+
|
|
1401
|
+
|
|
1402
|
+
# Validator rules a refusal names, keyed by a substring of the validator's message.
|
|
1403
|
+
RULE_HINTS = {
|
|
1404
|
+
"matches no palomar entry": "rule doi-in-palomar: a doi-minted commit must already be recorded by a "
|
|
1405
|
+
"palomar-* event on the package (record that first; a public package with no Palomar claim: "
|
|
1406
|
+
"update NAME --track doi-only, or record ... --track doi-only)",
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
|
|
1410
|
+
def _err_key(e: str) -> str:
|
|
1411
|
+
"""Comparison form of a validator message: a trailing parenthetical (a context listing) is dropped."""
|
|
1412
|
+
return re.sub(r" \([^()]*\)$", "", e)
|
|
1413
|
+
|
|
1414
|
+
|
|
1415
|
+
def split_new_errors(before: list[str], after: list[str]) -> tuple[list[str], list[str]]:
|
|
1416
|
+
"""(errors this change introduces or repeats beyond the count before, pre-existing errors it leaves)."""
|
|
1417
|
+
left = collections.Counter(_err_key(e) for e in before)
|
|
1418
|
+
new, old = [], []
|
|
1419
|
+
for e in after:
|
|
1420
|
+
k = _err_key(e)
|
|
1421
|
+
if left[k] > 0:
|
|
1422
|
+
left[k] -= 1
|
|
1423
|
+
old.append(e)
|
|
1424
|
+
else:
|
|
1425
|
+
new.append(next((f"{e} [{h}]" for m, h in RULE_HINTS.items() if m in e), e))
|
|
1426
|
+
return new, old
|
|
1427
|
+
|
|
1428
|
+
|
|
1429
|
+
def report_preexisting(errors: list[str]) -> None:
|
|
1430
|
+
"""Pre-existing schema errors do not block an unrelated write; they are reported on stderr."""
|
|
1431
|
+
for e in errors:
|
|
1432
|
+
print(f"lean-pkg: pre-existing (not caused by this change): {e}", file=sys.stderr)
|
|
1433
|
+
|
|
1434
|
+
|
|
1435
|
+
def _fingerprint(entry: dict) -> str:
|
|
1436
|
+
return json.dumps(entry, sort_keys=True, default=str)
|
|
1437
|
+
|
|
1438
|
+
|
|
1439
|
+
def retracted_entries(pkg: dict) -> list[dict]:
|
|
1440
|
+
"""Copies of the history entries that evidence-retracted entries retract (each stores its target verbatim,
|
|
1441
|
+
so a later entry with the same event and ts is not swept up)."""
|
|
1442
|
+
hist = pkg.get("history") if isinstance(pkg, dict) else None
|
|
1443
|
+
return [h["retracted_entry"] for h in (hist if isinstance(hist, list) else [])
|
|
1444
|
+
if isinstance(h, dict) and h.get("event") == "evidence-retracted"
|
|
1445
|
+
and isinstance(h.get("retracted_entry"), dict)]
|
|
1446
|
+
|
|
1447
|
+
|
|
1448
|
+
def live_history(pkg: dict) -> list[dict]:
|
|
1449
|
+
"""history[] without the entries an evidence-retracted entry retracts."""
|
|
1450
|
+
gone = {_fingerprint(e) for e in retracted_entries(pkg)}
|
|
1451
|
+
hist = pkg.get("history") if isinstance(pkg, dict) else None
|
|
1452
|
+
return [h for h in (hist if isinstance(hist, list) else []) if isinstance(h, dict)
|
|
1453
|
+
and _fingerprint(h) not in gone]
|
|
1454
|
+
|
|
1455
|
+
|
|
1456
|
+
def get_pkg(reg: dict, name: str) -> dict:
|
|
1457
|
+
pkg = (reg.get("packages") or {}).get(name)
|
|
1458
|
+
if pkg is None:
|
|
1459
|
+
known = ", ".join(sorted(reg.get("packages") or {})) or "(none)"
|
|
1460
|
+
raise Fail(f"unknown package: {name!r} (known: {known})")
|
|
1461
|
+
return pkg
|
|
1462
|
+
|
|
1463
|
+
|
|
1464
|
+
# --------------------------------------------------------------------------
|
|
1465
|
+
# leases: the pure lease-time helpers (the lease commands stay in cli.py)
|
|
1466
|
+
|
|
1467
|
+
def lease_expiry(lease: dict) -> dt.datetime:
|
|
1468
|
+
ttl = int(lease.get("ttl_hours") or DEFAULT_TTL_HOURS)
|
|
1469
|
+
return parse_ts(lease["claimed_at"]) + dt.timedelta(hours=ttl)
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
LEASE_PARSE_ERRORS = (TypeError, ValueError, KeyError, AttributeError, OverflowError)
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
def lease_expiry_or_none(lease) -> dt.datetime | None:
|
|
1476
|
+
"""lease_expiry, or None when the lease's fields cannot be parsed (a hand-edited claimed_at: zzz or
|
|
1477
|
+
ttl_hours: 'x'): readers render such a lease as INVALID instead of raising."""
|
|
1478
|
+
try:
|
|
1479
|
+
return lease_expiry(lease)
|
|
1480
|
+
except LEASE_PARSE_ERRORS:
|
|
1481
|
+
return None
|
|
1482
|
+
|
|
1483
|
+
|
|
1484
|
+
def lease_invalid(lease) -> bool:
|
|
1485
|
+
return bool(lease) and lease_expiry_or_none(lease) is None
|
|
1486
|
+
|
|
1487
|
+
|
|
1488
|
+
def refuse_invalid_lease(name: str, lease) -> None:
|
|
1489
|
+
"""Writers refuse a package whose lease cannot be parsed; `release --force` is the way out."""
|
|
1490
|
+
if lease_invalid(lease):
|
|
1491
|
+
get = lease.get if isinstance(lease, dict) else (lambda _k: None)
|
|
1492
|
+
raise Fail(f"{name}: lease fields unparseable (claimed_at={get('claimed_at')!r}, "
|
|
1493
|
+
f"ttl_hours={get('ttl_hours')!r}); clear it with "
|
|
1494
|
+
f"`lean-pkg release {name} --force --reason TEXT`")
|
|
1495
|
+
|
|
1496
|
+
|
|
1497
|
+
def lease_live(lease: dict | None, now: dt.datetime) -> bool:
|
|
1498
|
+
"""True while a lease runs. Raises on unparseable fields: writers call refuse_invalid_lease first,
|
|
1499
|
+
readers use lease_expiry_or_none."""
|
|
1500
|
+
return bool(lease) and now < lease_expiry(lease)
|
|
1501
|
+
|
|
1502
|
+
|
|
1503
|
+
def lease_live_or_none(lease, now: dt.datetime) -> bool | None:
|
|
1504
|
+
"""lease_live for readers: None when the lease cannot be parsed."""
|
|
1505
|
+
exp = lease_expiry_or_none(lease) if lease else None
|
|
1506
|
+
if lease and exp is None:
|
|
1507
|
+
return None
|
|
1508
|
+
return bool(lease) and now < exp
|
|
1509
|
+
|
|
1510
|
+
|
|
1511
|
+
# --------------------------------------------------------------------------
|
|
1512
|
+
# fields `update` may set (event_line_problems reads them)
|
|
1513
|
+
|
|
1514
|
+
# Fields `update` may set. Everything else is owned by a dedicated subcommand
|
|
1515
|
+
# and is refused by name, so `update` can never become a way around the trust
|
|
1516
|
+
# gate: `gate`/`promoted_at`/`promoted_commit`/`visibility` belong to `gate`
|
|
1517
|
+
# and `promote`, and `lease`/`workspace`/`agent` to `claim`/`release`.
|
|
1518
|
+
UPDATABLE = {"automation", "notes", "upstream_target", "reaudit_after",
|
|
1519
|
+
"owner_project", "repo", "license_spdx", "formalization_yaml", "paper", "namespace_notes",
|
|
1520
|
+
"source_paper", "ai_assistance", "track", "docs_descendants", "build_inputs", "headline_config"}
|
|
1521
|
+
|
|
1522
|
+
|
|
1523
|
+
# --------------------------------------------------------------------------
|
|
1524
|
+
# git object helpers (the gate and the docs-only rule read the bound commit through them)
|
|
1525
|
+
|
|
1526
|
+
def sha256_bytes(b: bytes) -> str:
|
|
1527
|
+
return hashlib.sha256(b).hexdigest()
|
|
1528
|
+
|
|
1529
|
+
|
|
1530
|
+
def git_show_bytes(repo: pathlib.Path, rel: str, rev: str = "HEAD") -> bytes | None:
|
|
1531
|
+
"""Bytes of <rev>:<rel>, or None when the path is not tracked there. `rel` is relative to the
|
|
1532
|
+
package directory `repo`, which may be a subdirectory of its git repository: a bare `rel` is read
|
|
1533
|
+
as `./rel` (git resolves a bare `<rev>:<path>` from the repository root, #21.2)."""
|
|
1534
|
+
spec = rel if rel.startswith(("./", "../")) else f"./{rel}"
|
|
1535
|
+
p = subprocess.run(["git", "-C", str(repo), "show", f"{rev}:{spec}"],
|
|
1536
|
+
capture_output=True, env=scrubbed_env())
|
|
1537
|
+
return p.stdout if p.returncode == 0 else None
|
|
1538
|
+
|
|
1539
|
+
|
|
1540
|
+
def tracked_at(repo: pathlib.Path, rel: str, rev: str = "HEAD") -> bool:
|
|
1541
|
+
"""True when <rel> (relative to the package directory `repo`) is committed at <rev>."""
|
|
1542
|
+
return git(repo, "cat-file", "-e", f"{rev}:./{rel}").returncode == 0
|
|
1543
|
+
|
|
1544
|
+
|
|
1545
|
+
def bound_tree(repo: pathlib.Path, commit: str) -> dict[str, str]:
|
|
1546
|
+
"""{package-relative path: git mode} of every entry (trees included) under the package directory at
|
|
1547
|
+
`commit`; symlink entries map to "120000:<target>" so their committed targets can be judged. Fails
|
|
1548
|
+
closed: a git error (or output it cannot parse) is a refusal, never an empty or a safe tree."""
|
|
1549
|
+
def run_git(*args: str) -> bytes:
|
|
1550
|
+
p = subprocess.run(["git", "-C", str(repo), *args], capture_output=True, env=scrubbed_env())
|
|
1551
|
+
if p.returncode != 0:
|
|
1552
|
+
err = p.stderr.decode("utf-8", "replace").strip().splitlines()
|
|
1553
|
+
raise Fail(f"cannot read the tree at {commit[:12]} (git {args[0]} exited {p.returncode}"
|
|
1554
|
+
+ (f": {err[0]}" if err else "") + "); refusing rather than judging it safe")
|
|
1555
|
+
return p.stdout
|
|
1556
|
+
out: dict[str, str] = {}
|
|
1557
|
+
for rec in run_git("ls-tree", "-r", "-t", "-z", commit, ".").decode("utf-8", "replace").split("\0"):
|
|
1558
|
+
if not rec:
|
|
1559
|
+
continue
|
|
1560
|
+
meta, sep, path = rec.partition("\t")
|
|
1561
|
+
fields = meta.split()
|
|
1562
|
+
if not sep or len(fields) != 3:
|
|
1563
|
+
raise Fail(f"cannot read the tree at {commit[:12]}: unexpected git ls-tree record {rec[:80]!r}")
|
|
1564
|
+
mode, _kind, sha = fields
|
|
1565
|
+
if path in ("./", "."):
|
|
1566
|
+
continue
|
|
1567
|
+
if mode == "120000":
|
|
1568
|
+
mode = "120000:" + run_git("cat-file", "blob", sha).decode("utf-8", "replace")
|
|
1569
|
+
out[path.rstrip("/")] = mode
|
|
1570
|
+
return out
|