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.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/search.py ADDED
@@ -0,0 +1,865 @@
1
+ # lean-pkg search -- claim-level prior-art search before building
2
+ """`lean-pkg search TERM`: one block per source, in a fixed order, each with its
3
+ revision and state (`ok` or `skipped: <reason>`), and a closing line naming every
4
+ source consulted. Local sources (the registry's packages and cached claims, the
5
+ public index) always run and are scored deterministically: exact alias (or package
6
+ name) 3, keyword 2, every term token present 1; no embeddings. A registry hit is a
7
+ package (`hit_kind: package`: name, notes, owner_project, repo) or a claim. A package with no synced
8
+ claims is searched by declaration instead: its checkout at HEAD (`git grep` over tracked `*.lean`
9
+ files, declaration names and their docstrings), `hit_kind: declaration (unclaimed)`, trust none,
10
+ ranked after the claim and package hits; a package without a git checkout is reported as not
11
+ searched (#49). Network sources (lean_pkg.adapters) run unless --offline; each is reported
12
+ separately and never merged into the local score. A skipped source is never a zero.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import hashlib
19
+ import pathlib
20
+ import re
21
+ import subprocess
22
+ import sys
23
+
24
+ from . import claims as cl
25
+ from . import core
26
+ from . import index as idx
27
+ from . import lean_scan
28
+ from . import adapters
29
+ from .adapters import fold, github, leansearch, loogle, palomar, reservoir
30
+
31
+ LOCAL_SOURCES = ("registry", "index")
32
+ NETWORK_SOURCES = ("loogle", "leansearch", "reservoir", "palomar", "github")
33
+ SOURCES = LOCAL_SOURCES + NETWORK_SOURCES
34
+ ADAPTERS = {"loogle": loogle, "leansearch": leansearch, "reservoir": reservoir,
35
+ "palomar": palomar, "github": github}
36
+ LATE_STATUSES = ("experimental", "superseded")
37
+ HIT_KEYS = ("source", "id", "package", "decl", "kind", "summary", "trust", "status", "pin",
38
+ "file", "score", "where", "hit_kind", "repo")
39
+ # A claim hit gains `conditional: true` only when the claim is conditional (proposal 0003, #320; as `claims list`
40
+ # marks it): a registry claim that lists `hypotheses`, or an index claim whose derived `status` is conditional.
41
+ OPTIONAL_HIT_KEYS = ("conditional",)
42
+ PACKAGE_FIELDS = ("name", "notes", "owner_project", "repo")
43
+ _TOKEN_SPLIT = re.compile(r"[\W_]+", re.UNICODE)
44
+ # A home directory anywhere; a cluster or system root (/scratch/<x>, /work/<x>, /gpfs/<x>, /srv/<x>, /mnt/<x>,
45
+ # /tmp/<x>, /lustre/<x>) only where a path starts (not inside a URL such as https://host/work/page).
46
+ _PATHLIKE = re.compile(r"(?:~|/home/|/Users/|[A-Za-z]:\\|(?<![\w.:/-])/(?:scratch|work|gpfs|srv|mnt|tmp|lustre)/"
47
+ r"(?=[^\s/]))\S*")
48
+ ROUTES = ("signature", "natural-language")
49
+ SIGNATURE_SOURCES = ("loogle",) # sources that only take declaration/type patterns
50
+ LOOGLE_NL_REASON = ("natural-language query; Loogle takes declaration patterns — try e.g. "
51
+ "`?a + ?b = ?b + ?a` (--loogle-query PATTERN sends a pattern of its own; --loogle forces "
52
+ "the term)")
53
+ # Appended to Loogle's own parse error ("Unknown identifier exponential", "expected end of input"): the term
54
+ # reached Loogle but mixed prose with Lean (field report).
55
+ LOOGLE_SYNTAX_HINT = ("; Loogle takes Lean names, terms and patterns (`Real.exp`, `?a * ?b = ?b * ?a`, "
56
+ "`\"martingale\"` for a name fragment), not prose: keep the prose as TERM and pass the "
57
+ "Lean part with --loogle-query")
58
+ _SIG_MARKERS = ("→", "->", "∀", "∃", "fun ", "λ", ":", "(", "?", "_", "⊢", '"', "↔", "<->")
59
+ _DOTTED = re.compile(r"\b[A-Z][A-Za-z0-9']*\.[A-Za-z_]")
60
+ DECL_HIT_KIND = "declaration (unclaimed)"
61
+ DECL_KEYWORDS = lean_scan.KEYWORDS
62
+ DECL_HITS_PER_PACKAGE = 10 # declaration hits kept per package; the rest are counted, not listed
63
+ DECL_FILES_MAX = 2000 # files read per package after the git grep prefilter; past it, coverage says so
64
+ EXCERPT_MAX = 160
65
+
66
+
67
+ def scrub_paths(text) -> str:
68
+ """Replace anything that looks like a local path with <path> (skip reasons come from outside)."""
69
+ return _PATHLIKE.sub("<path>", str(text or ""))
70
+
71
+
72
+ def tokens(text) -> list[str]:
73
+ """Lowercase alphanumeric tokens of any script; accents folded; split on non-word runs."""
74
+ return [tok for tok in _TOKEN_SPLIT.split(fold(text)) if tok]
75
+
76
+
77
+ def norm(text) -> str:
78
+ return " ".join(tokens(text))
79
+
80
+
81
+ def score_claim(term: str, claim: dict) -> tuple[int, str | None]:
82
+ """(score, where): 3 exact alias, 2 keyword, 1 every term token occurs in decl, summary,
83
+ aliases, keywords or citation; 0 no match. Case-insensitive; tokens split on non-alphanumerics."""
84
+ q, qt = norm(term), set(tokens(term))
85
+ if not qt:
86
+ return 0, None
87
+ if any(norm(a) == q for a in claim.get("aliases") or []):
88
+ return 3, "alias"
89
+ if any(norm(k) == q for k in claim.get("keywords") or []):
90
+ return 2, "keyword"
91
+ words: set[str] = set()
92
+ for f in ("decl", "summary", "citation"):
93
+ words.update(tokens(claim.get(f)))
94
+ for f in ("aliases", "keywords"):
95
+ for a in claim.get(f) or []:
96
+ words.update(tokens(a))
97
+ return (1, "token") if qt <= words else (0, None)
98
+
99
+
100
+ def score_package(term: str, name: str, pkg: dict) -> tuple[int, str | None]:
101
+ """(score, where) over a package's own metadata: 3 the name equals the term, 1 every term
102
+ token occurs in name, notes, owner_project or repo; 0 no match."""
103
+ q, qt = norm(term), set(tokens(term))
104
+ if not qt:
105
+ return 0, None
106
+ if norm(name) == q:
107
+ return 3, "name"
108
+ words: set[str] = set()
109
+ for f in PACKAGE_FIELDS:
110
+ words.update(tokens(name if f == "name" else pkg.get(f)))
111
+ return (1, "token") if qt <= words else (0, None)
112
+
113
+
114
+ def route_of(term: str) -> str:
115
+ """`signature` when the term looks like a Lean declaration or type pattern (an arrow, binder,
116
+ colon, parenthesis, `?` metavariable, `_`, `⊢`, a quoted name fragment, a math operator, or a
117
+ dotted name such as `Nat.succ` / `Mathlib.Order`); otherwise `natural-language`."""
118
+ import unicodedata
119
+ t = str(term or "")
120
+ if any(m in t for m in _SIG_MARKERS) or _DOTTED.search(t):
121
+ return "signature"
122
+ if any(unicodedata.category(ch) == "Sm" for ch in t): # = + < > ≤ ∑ ∫ ∈ ⊆ ...
123
+ return "signature"
124
+ return "natural-language"
125
+
126
+
127
+ def rank(hits: list[dict]) -> list[dict]:
128
+ """Reusable before experimental and superseded; then by score, then by id."""
129
+ return sorted(hits, key=lambda h: (h["status"] in LATE_STATUSES, -h["score"], str(h["id"])))
130
+
131
+
132
+ def _hit(source: str, c: dict, package: str, trust, pin, score: int, where: str) -> dict:
133
+ hit = {"source": source, "id": c.get("id"), "package": package, "decl": c.get("decl"),
134
+ "kind": c.get("kind"), "summary": c.get("summary"), "trust": trust or "none",
135
+ "status": c.get("status") or "reusable", "pin": pin, "file": c.get("file"),
136
+ "score": score, "where": where, "hit_kind": "claim", "repo": None}
137
+ if c.get("hypotheses") or c.get("conditional") is True: # a conditional claim, always (proposal 0003)
138
+ hit["conditional"] = True
139
+ return hit
140
+
141
+
142
+ def _package_hit(name: str, pkg: dict, score: int, where: str) -> dict:
143
+ return {"source": "registry", "id": name, "package": name, "decl": None, "kind": None,
144
+ "summary": pkg.get("notes") or None, "trust": cl.package_trust(pkg),
145
+ "status": pkg.get("status"), "pin": None, "file": None, "score": score, "where": where,
146
+ "hit_kind": "package", "repo": scrub_paths(pkg.get("repo")) if pkg.get("repo") else None}
147
+
148
+
149
+ def block(source: str, state: str, reason: str | None = None, revision: str | None = None,
150
+ hits: list | None = None, route: str | None = None, partial: list | None = None,
151
+ capped: list | None = None, cap_limit: int | None = None, total: int | None = None,
152
+ incomplete: str | None = None, cache_writes: list | None = None) -> dict:
153
+ """One source's answer. `partial`/`capped` name parts of a network source that failed or hit their
154
+ result limit (`total`: the matches it found, when it lists fewer); `incomplete` says why a local source
155
+ did not read everything (the registry's file cap or unreadable files, the index's unreadable entries)."""
156
+ return {"source": source, "state": state, "reason": scrub_paths(reason) if reason else reason,
157
+ "revision": revision, "hits": hits or [], "route": route, "partial": list(partial or []),
158
+ "capped": list(capped or []), "cap_limit": cap_limit if capped else None,
159
+ "total": total if capped else None, "incomplete": incomplete,
160
+ "cache_writes": list(cache_writes or [])}
161
+
162
+
163
+ # --------------------------------------------------------------------------
164
+ # declaration fallback (#49): packages without synced claims
165
+
166
+ def has_synced_claims(pkg: dict) -> bool:
167
+ """True when the registry caches at least one synced claim for the package (`claims coverage`
168
+ `synced`). `empty`, `unsynced` and `none` all leave search blind to the package's claims."""
169
+ return bool(pkg.get("claims"))
170
+
171
+
172
+ def lean_declarations(text: str) -> list[tuple[int, str, str, str | None, str, str]]:
173
+ """(line, keyword, qualified name, docstring or None, stripped line, name as written) for every
174
+ declaration (lean_pkg.lean_scan: comments and strings skipped, docstrings attached across attribute
175
+ lines, `namespace`/`section`/`end` tracked so the name is fully qualified)."""
176
+ return lean_scan.declarations(text)
177
+
178
+
179
+ def _doc_text(doc: str | None) -> str:
180
+ if not doc:
181
+ return ""
182
+ d = doc.strip()
183
+ d = d[3:] if d.startswith("/--") else d
184
+ d = d[:-2] if d.endswith("-/") else d
185
+ return " ".join(d.split())
186
+
187
+
188
+ def _excerpt(text: str) -> str:
189
+ t = scrub_paths(" ".join(str(text).split()))
190
+ return t if len(t) <= EXCERPT_MAX else t[:EXCERPT_MAX - 1].rstrip() + "…"
191
+
192
+
193
+ def _decl_terms(term: str) -> list[str]:
194
+ toks = tokens(term)
195
+ long = [t for t in toks if len(t) >= 2]
196
+ return sorted(set(long or toks))
197
+
198
+
199
+ def _decl_order(h: dict) -> tuple:
200
+ """Name matches first, then package, file and line (numeric)."""
201
+ rel, _, line = h["file"].rpartition(":")
202
+ return (h["where"] != "name", h["package"], rel, int(line) if line.isdigit() else 0)
203
+
204
+
205
+ def _read_blobs(repo: pathlib.Path, rev: str, rels: list[str]) -> dict[str, bytes]:
206
+ """{rel: bytes} for package-relative paths at `rev`, through one `git cat-file --batch` (one process for
207
+ thousands of files instead of one `git show` each). A path git reports missing, or one cat-file cannot
208
+ name (a newline in it), is left out: the caller counts it as unreadable."""
209
+ rels = [r for r in rels if "\n" not in r]
210
+ if not rels:
211
+ return {}
212
+ spec = "".join(f"{rev}:./{r}\n" for r in rels).encode("utf-8", errors="surrogateescape")
213
+ p = subprocess.run(["git", "-C", str(repo), "cat-file", "--batch"], input=spec, capture_output=True,
214
+ env=core.scrubbed_env())
215
+ out, data, i = {}, p.stdout, 0
216
+ for rel in rels:
217
+ nl = data.find(b"\n", i)
218
+ if nl < 0:
219
+ break
220
+ header = data[i:nl].split()
221
+ i = nl + 1
222
+ if len(header) == 3 and header[1] == b"blob":
223
+ size = int(header[2])
224
+ out[rel] = data[i:i + size]
225
+ i += size + 1 # the object, then its trailing newline
226
+ return out
227
+
228
+
229
+ def _accent_table() -> dict[str, list[str]]:
230
+ """{ascii letter: [the letter in both cases, then every Latin letter that folds to it, precomposed and
231
+ decomposed]}: what `git grep` must accept so a folded query word still finds `Itô` or `GÖDEL`."""
232
+ import unicodedata
233
+ table: dict[str, set[str]] = {}
234
+ for cp in list(range(0xC0, 0x250)) + list(range(0x1E00, 0x1F00)):
235
+ ch = chr(cp)
236
+ f = fold(ch)
237
+ if len(f) == 1 and f.isascii() and f.isalpha():
238
+ table.setdefault(f, set()).update({ch, unicodedata.normalize("NFD", ch)})
239
+ return {k: [k, k.upper()] + sorted(v - {k, k.upper()}) for k, v in table.items()}
240
+
241
+
242
+ _ACCENTS = _accent_table()
243
+
244
+
245
+ def grep_pattern(word: str) -> str:
246
+ """An extended regular expression matching `word` (already folded) in any case and with any Latin
247
+ accents: `ito` -> `(i|I|í|...)(t|T|ţ|...)(o|O|ô|...)`. Letters without variants stay literal."""
248
+ out = []
249
+ for ch in word:
250
+ alts = _ACCENTS.get(ch)
251
+ if alts:
252
+ out.append("(" + "|".join(alts) + ")")
253
+ else:
254
+ out.append(re.sub(r"([\\.^$|?*+()\[\]{}])", r"\\\1", ch))
255
+ return "".join(out)
256
+
257
+
258
+ def git_bytes(repo: pathlib.Path, *args: str) -> subprocess.CompletedProcess:
259
+ """`git -c core.quotePath=false ARGS` in a package checkout with byte output (file names are not always
260
+ UTF-8); returncode 127 when git cannot be run."""
261
+ cmd = ["git", "-C", str(repo), "-c", "core.quotePath=false", *args]
262
+ try:
263
+ return subprocess.run(cmd, capture_output=True, check=False, env=core.scrubbed_env())
264
+ except OSError as e:
265
+ return subprocess.CompletedProcess(cmd, 127, b"", str(e).encode())
266
+
267
+
268
+ def _candidate_files(repo: pathlib.Path, words: list[str], nested: tuple[str, ...]) -> list[str] | str:
269
+ """Tracked `*.lean` files at HEAD containing every word (case- and accent-insensitive), sorted; a one-line
270
+ failure (git_failure) when git grep failed. Paths come NUL-separated and unquoted, so a non-ASCII file name
271
+ is kept as is."""
272
+ args = ["grep", "-l", "-z", "-I", "-E", "--all-match"]
273
+ for w in words:
274
+ args += ["-e", grep_pattern(w)]
275
+ args += ["HEAD", "--", "*.lean", *[f":(exclude){d}/" for d in nested]]
276
+ p = git_bytes(repo, *args)
277
+ if p.returncode not in (0, 1):
278
+ return git_failure(p)
279
+ names = [x.decode("utf-8", errors="surrogateescape") for x in p.stdout.split(b"\0") if x]
280
+ return sorted(n.split(":", 1)[1] for n in names if ":" in n)
281
+
282
+
283
+ # Why a package was not searched by declaration: (label for the text line, read-only remedy). The remedy names
284
+ # commands keyed by the package name, never a host path, so the output can be shared (field report R2).
285
+ NOT_SEARCHED = {
286
+ "no-path": ("no path", "no local_path is recorded; see `lean-pkg status {name} --fields local_path,repo`"),
287
+ "no-checkout": ("no checkout", "local_path is not a directory on this host; see "
288
+ "`lean-pkg status {name} --fields local_path,repo` and clone the repository there"),
289
+ "no-git-head": ("no git HEAD", "the checkout has no commit or is not a git work tree; see "
290
+ "`lean-pkg status {name} --fields local_path` and `lean-pkg doctor`"),
291
+ "scan-error": ("scan error", "git grep failed in the checkout (detail: its exit status and cause); see `lean-pkg doctor` and check the checkout with `git status` and `git fsck`"),
292
+ }
293
+
294
+
295
+ class NotSearched(str):
296
+ """The code a declaration search returns instead of hits (a key of NOT_SEARCHED); `detail` says what
297
+ failed (for scan-error: git grep's exit status and a fixed cause, never its stderr), else None."""
298
+ detail: str | None = None
299
+
300
+ @classmethod
301
+ def of(cls, code: str, detail: str | None = None) -> "NotSearched":
302
+ out = cls(code)
303
+ out.detail = detail
304
+ return out
305
+
306
+
307
+ # git's stderr never reaches the output (it can name host paths and users; #112): a failure is reported as its
308
+ # exit status plus one of these fixed causes, matched on the stderr text, else `cause not recognised`.
309
+ GIT_FAILURE_CAUSES = (
310
+ (("dubious ownership", "safe.directory"), "repository owned by another user (git safe.directory)"),
311
+ (("promisor", "could not fetch", "unable to read", "missing blob", "bad object", "invalid object",
312
+ "loose object"), "object missing or unreadable (a partial or damaged clone; try `git fsck`)"),
313
+ (("packfile", ".pack", ".idx"), "pack file unreadable (damaged, or replaced by a concurrent repack or gc)"),
314
+ (("index.lock", ".lock': file exists"), "a git lock file is held by another process"),
315
+ (("too many open files",), "too many open files"),
316
+ (("cannot allocate memory", "out of memory"), "out of memory"),
317
+ (("regular expression", "regex", "regexp"), "the search pattern was rejected"),
318
+ (("not a git repository",), "not a git work tree"),
319
+ )
320
+
321
+
322
+ def git_failure(p: subprocess.CompletedProcess) -> str:
323
+ """`git grep exit 128: object missing or unreadable (...)` or `git grep killed by signal 11`: the exit status
324
+ and a fixed cause from GIT_FAILURE_CAUSES; git's own stderr is never copied (it can name host paths)."""
325
+ rc = p.returncode
326
+ if rc < 0 or rc in (134, 137, 139):
327
+ return f"git grep killed by signal {-rc if rc < 0 else rc - 128} (a crash; rerun, and check the host)"
328
+ err = (p.stderr.decode("utf-8", errors="replace") if isinstance(p.stderr, bytes)
329
+ else str(p.stderr or "")).lower()
330
+ cause = next((c for keys, c in GIT_FAILURE_CAUSES if any(k in err for k in keys)), "cause not recognised")
331
+ return f"git grep exit {rc}: {cause}"
332
+
333
+
334
+ def declaration_hits(term: str, name: str, pkg: dict,
335
+ nested: tuple[str, ...] = ()) -> tuple[list[dict], int, dict | None] | NotSearched:
336
+ """(hits, omitted, capped) from the package's checkout at HEAD, or a NotSearched code (no-path,
337
+ no-checkout, no-git-head, scan-error) when it could not be searched. A declaration matches when every query
338
+ word (case-insensitive, accents folded on both sides, as a substring so camelCase names match) occurs in its
339
+ name or its docstring; a name match ranks before a docstring-only match. Names are fully qualified
340
+ (`namespace` tracked): a dotted query (`DemoA.heatFlowMass_le`) is matched against the qualified name, a
341
+ plain one against the name as written. `omitted` counts matching declarations beyond the
342
+ DECL_HITS_PER_PACKAGE shown; `capped` is None when every candidate file was read, else
343
+ {"candidates", "inspected", "unreadable"}: more candidate files matched the git grep prefilter than
344
+ DECL_FILES_MAX allows reading, or `unreadable` of them could not be read. Those files were never examined,
345
+ so a zero is not an absence (field report: a theorem in the 201st file was silently missed). `nested`
346
+ lists the checkout-relative roots of other registered packages inside this one; their files belong to them
347
+ and are not scanned here (field report: a contrib package's declarations were attributed to its parent)."""
348
+ if not pkg.get("local_path"):
349
+ return NotSearched("no-path")
350
+ try:
351
+ repo = core.repo_path(pkg)
352
+ except Exception:
353
+ return NotSearched("no-path")
354
+ if not repo.is_dir():
355
+ return NotSearched("no-checkout")
356
+ head = core.git_head(repo)
357
+ if head is None:
358
+ return NotSearched("no-git-head")
359
+ words = _decl_terms(term)
360
+ dotted = "." in str(term)
361
+ candidates = _candidate_files(repo, words, nested)
362
+ if isinstance(candidates, str):
363
+ return NotSearched.of("scan-error", candidates)
364
+ files = candidates[:DECL_FILES_MAX]
365
+ blobs = _read_blobs(repo, head, files)
366
+ unreadable = sum(1 for rel in files if rel not in blobs)
367
+ capped = ({"candidates": len(candidates), "inspected": len(files) - unreadable, "unreadable": unreadable}
368
+ if len(candidates) > len(files) or unreadable else None)
369
+ found = []
370
+ for rel in files:
371
+ blob = blobs.get(rel)
372
+ if blob is None:
373
+ continue
374
+ for line, kw, qual, doc, st, written in lean_declarations(blob.decode("utf-8", errors="replace")):
375
+ dtext = _doc_text(doc)
376
+ in_name = fold(qual if dotted else written)
377
+ if not all(w in in_name + " " + fold(dtext) for w in words):
378
+ continue
379
+ where = "name" if all(w in in_name for w in words) else "docstring"
380
+ found.append({"source": "registry", "id": f"{name}:{rel}:{line}", "package": name,
381
+ "decl": qual, "kind": kw, "summary": _excerpt(dtext or st), "trust": "none",
382
+ "status": None, "pin": head, "file": f"{rel}:{line}", "score": 1,
383
+ "where": where, "hit_kind": DECL_HIT_KIND, "repo": None})
384
+ found.sort(key=_decl_order)
385
+ return found[:DECL_HITS_PER_PACKAGE], max(0, len(found) - DECL_HITS_PER_PACKAGE), capped
386
+
387
+
388
+ def package_roots(pkgs: dict) -> dict[str, pathlib.Path]:
389
+ """Each package's resolved checkout directory (packages without a usable local_path are left out)."""
390
+ roots = {}
391
+ for name, pkg in pkgs.items():
392
+ if isinstance(pkg, dict) and pkg.get("local_path"):
393
+ try:
394
+ roots[name] = core.repo_path(pkg).resolve()
395
+ except (OSError, RuntimeError, TypeError, ValueError):
396
+ continue
397
+ return roots
398
+
399
+
400
+ def nested_roots(name: str, roots: dict[str, pathlib.Path]) -> tuple[str, ...]:
401
+ """The roots of other registered packages strictly inside `name`'s, relative to it, sorted."""
402
+ mine = roots.get(name)
403
+ if mine is None:
404
+ return ()
405
+ out = set()
406
+ for other, root in roots.items():
407
+ if other != name and root != mine and mine in root.parents:
408
+ out.add(root.relative_to(mine).as_posix())
409
+ return tuple(sorted(out))
410
+
411
+
412
+ def not_searched_groups(cov: dict, names: bool) -> str:
413
+ """`no checkout: a, b; no git HEAD: c` (or with names=False `no checkout`, `no checkout: 2, no git HEAD: 1`)
414
+ in NOT_SEARCHED order; `no checkout` alone when nothing was skipped, as before."""
415
+ by: dict[str, list[str]] = {}
416
+ for r in cov.get("not_searched_reasons") or []:
417
+ by.setdefault(r["code"], []).append(
418
+ f"{r['package']} ({r['detail']})" if names and r.get("detail") else r["package"])
419
+ if not by:
420
+ return "no checkout"
421
+ if not names and list(by) == ["no-checkout"]:
422
+ return "no checkout"
423
+ parts = []
424
+ for code in NOT_SEARCHED:
425
+ if code in by:
426
+ label = NOT_SEARCHED[code][0]
427
+ parts.append(f"{label}: {', '.join(by[code])}" if names else f"{label}: {len(by[code])}")
428
+ return ("; " if names else ", ").join(parts)
429
+
430
+
431
+ def coverage_text(cov: dict | None) -> str | None:
432
+ """The blind-source line: how many packages search could only see by declaration, or not at all."""
433
+ if cov is None:
434
+ return None
435
+ total = cov["claims"] + cov["declaration_only"] + len(cov["not_searched"])
436
+ blind = total - cov["claims"]
437
+ if not blind:
438
+ return f"registry coverage: all {total} package(s) have synced claims"
439
+ ns = cov["not_searched"]
440
+ text = (f"registry coverage: {blind} of {total} packages have no synced claims: "
441
+ f"{cov['declaration_only']} searched by declaration only, {len(ns)} not searched ("
442
+ + not_searched_groups(cov, names=True) + ")")
443
+ if cov.get("declaration_hits_omitted"):
444
+ text += f"; {cov['declaration_hits_omitted']} more declaration hit(s) not listed"
445
+ for c in cov.get("declaration_files_capped") or []:
446
+ text += f"; {c['package']}: {capped_phrase(c)}, so a zero there is not an absence"
447
+ return text
448
+
449
+
450
+ def capped_phrase(c: dict) -> str:
451
+ """`only 3 of 5 candidate file(s) inspected (file cap)`, `(1 unreadable)` or `(file cap; 1 unreadable)`."""
452
+ unreadable = c.get("unreadable") or 0
453
+ why = (["file cap"] if c["candidates"] - c["inspected"] - unreadable > 0 else []) + \
454
+ ([f"{unreadable} unreadable"] if unreadable else [])
455
+ return f"only {c['inspected']} of {c['candidates']} candidate file(s) inspected ({'; '.join(why)})"
456
+
457
+
458
+ def registry_incomplete(cov: dict | None) -> str | None:
459
+ """Why the registry source read only part of what it should have, or None: candidate files a package's
460
+ declaration search did not read, or registered packages it could not search at all (#376: those make the
461
+ search incomplete too, so `complete`, --require-complete and the record never treat them as searched).
462
+ Counts only, never package names: the text reaches the --record page."""
463
+ cov = cov or {}
464
+ parts = []
465
+ capped = cov.get("declaration_files_capped") or []
466
+ if capped:
467
+ cap = any(c["candidates"] - c["inspected"] - (c.get("unreadable") or 0) > 0 for c in capped)
468
+ unreadable = sum(c.get("unreadable") or 0 for c in capped)
469
+ why = (["a file cap"] if cap else []) + ([f"{unreadable} unreadable candidate file(s)"] if unreadable else [])
470
+ parts.append(f"declaration search hit {' and '.join(why)}")
471
+ missed = cov.get("not_searched") or []
472
+ if missed:
473
+ parts.append(f"{len(missed)} registered package(s) not searched ({not_searched_groups(cov, names=False)})")
474
+ return f"{'; '.join(parts)} (see the coverage line)" if parts else None
475
+
476
+
477
+ # --------------------------------------------------------------------------
478
+ # local sources
479
+
480
+ def registry_revision(path: pathlib.Path) -> str:
481
+ return "sha256:" + hashlib.sha256(path.read_bytes()).hexdigest()[:12]
482
+
483
+
484
+ def registry_block(term: str, reg_path: pathlib.Path) -> dict:
485
+ return registry_search(term, reg_path)[0]
486
+
487
+
488
+ def registry_search(term: str, reg_path: pathlib.Path) -> tuple[dict, dict | None]:
489
+ """(registry block, coverage): coverage is {claims, declaration_only, not_searched[],
490
+ declaration_hits_omitted} over the registered packages, or None when the registry was skipped."""
491
+ if not reg_path.is_file():
492
+ return block("registry", "skipped", "no registry file"), None
493
+ try:
494
+ reg = core.load_registry(reg_path)
495
+ except core.Fail as e:
496
+ return block("registry", "skipped", f"unreadable: {e}"), None
497
+ pkgs = reg.get("packages") or {}
498
+ bad = [n for n, p in pkgs.items() if not isinstance(p, dict)]
499
+ if not isinstance(pkgs, dict) or bad:
500
+ return block("registry", "skipped",
501
+ f"unreadable registry (packages.{bad[0] if bad else '?'} is not a mapping)"), None
502
+ hits, decl_hits = [], []
503
+ cov = {"claims": 0, "declaration_only": 0, "not_searched": [], "not_searched_reasons": [],
504
+ "declaration_hits_omitted": 0, "declaration_files_capped": []}
505
+ roots = package_roots(pkgs)
506
+ for name in sorted(pkgs):
507
+ if has_synced_claims(pkgs[name]):
508
+ cov["claims"] += 1
509
+ continue
510
+ got = declaration_hits(term, name, pkgs[name], nested_roots(name, roots))
511
+ if isinstance(got, NotSearched):
512
+ cov["not_searched"].append(name)
513
+ cov["not_searched_reasons"].append({"package": name, "code": str(got),
514
+ "remedy": NOT_SEARCHED[got][1].format(name=name),
515
+ "detail": got.detail})
516
+ else:
517
+ cov["declaration_only"] += 1
518
+ decl_hits += got[0]
519
+ cov["declaration_hits_omitted"] += got[1]
520
+ if got[2]:
521
+ cov["declaration_files_capped"].append({"package": name, **got[2]})
522
+ decl_hits.sort(key=_decl_order)
523
+ for name in sorted(pkgs):
524
+ pkg = reg["packages"][name]
525
+ trust, pin = cl.package_trust(pkg), pkg.get("claims_synced_commit")
526
+ s, where = score_package(term, name, pkg)
527
+ if s:
528
+ hits.append(_package_hit(name, pkg, s, where))
529
+ for c in pkg.get("claims") or []:
530
+ if isinstance(c, dict):
531
+ s, where = score_claim(term, c)
532
+ if s:
533
+ hits.append(_hit("registry", c, name, trust, pin, s, where))
534
+ return block("registry", "ok", None, registry_revision(reg_path), rank(hits) + decl_hits,
535
+ incomplete=registry_incomplete(cov)), cov
536
+
537
+
538
+ def entry_claims(entry: dict) -> list[dict]:
539
+ """The claims of an index entry: its `claims[]` (index-entry/2) when present, else one
540
+ claim per headline item (index-entry/1). Entry `fields` act as keywords."""
541
+ name, trust = entry.get("name"), entry.get("trust")
542
+ heads = {h.get("name"): h for h in entry.get("headline") or [] if isinstance(h, dict)}
543
+ if isinstance(entry.get("claims"), list):
544
+ base = [c for c in entry["claims"] if isinstance(c, dict)]
545
+ else:
546
+ base = [{"id": f"{name}/{cl.slug_of_decl(h)}", "decl": h, "kind": "theorem",
547
+ "summary": heads[h].get("summary"), "judged_as": heads[h].get("judged_as"),
548
+ "trust": trust} for h in heads if isinstance(h, str)]
549
+ pin = (entry.get("pin") or {}).get("commit") if isinstance(entry.get("pin"), dict) else None
550
+ return [{**c, "status": "reusable", "keywords": list(entry.get("fields") or []),
551
+ "file": (heads.get(c.get("decl")) or {}).get("file"), "pin": pin,
552
+ "trust": c.get("trust") or trust, **({"conditional": True} if c.get("status") == "conditional" else {})}
553
+ for c in base]
554
+
555
+
556
+ def index_revision(root: pathlib.Path) -> str:
557
+ p = core.git(root, "rev-parse", "--short=12", "HEAD")
558
+ return f"git:{p.stdout.strip()}" if p.returncode == 0 else "unversioned"
559
+
560
+
561
+ def index_block(term: str, root: pathlib.Path) -> dict:
562
+ if not root.is_dir():
563
+ return block("index", "skipped", "no index directory")
564
+ hits, unreadable = [], 0
565
+ for n in idx.entry_names(root):
566
+ try:
567
+ entry = idx.load_entry(root / n / idx.ENTRY_FILE)
568
+ except core.Fail:
569
+ unreadable += 1
570
+ continue
571
+ if not isinstance(entry, dict):
572
+ unreadable += 1
573
+ continue
574
+ for c in entry_claims(entry):
575
+ s, where = score_claim(term, c)
576
+ if s:
577
+ hits.append(_hit("index", c, n, c["trust"], c["pin"], s, where))
578
+ reason = f"{unreadable} unreadable entr{'y' if unreadable == 1 else 'ies'} not searched" if unreadable else None
579
+ # An entry that could not be read was not searched: the index answered only in part (complete: false).
580
+ return block("index", "ok", reason, index_revision(root), rank(hits), incomplete=reason)
581
+
582
+
583
+ def adapter_block(source: str, term: str, timeout: float = 10) -> dict:
584
+ """Run one network adapter; any failure inside it is `skipped`, never fatal, never zero. The block's
585
+ `cache_writes` lists what the adapter wrote under the lean-pkg cache meanwhile (relative paths)."""
586
+ adapters.CACHE_WRITES.clear()
587
+ b = _adapter_block(source, term, timeout)
588
+ b["cache_writes"] = list(adapters.CACHE_WRITES)
589
+ adapters.CACHE_WRITES.clear()
590
+ if source == "loogle" and b["state"] == "skipped" and str(b["reason"] or "").startswith("query not understood"):
591
+ b["reason"] += LOOGLE_SYNTAX_HINT
592
+ return b
593
+
594
+
595
+ def _adapter_block(source: str, term: str, timeout: float = 10) -> dict:
596
+ try:
597
+ r = ADAPTERS[source].search(term, timeout=timeout)
598
+ except Exception as e: # one broken source must not end the search
599
+ return block(source, "skipped", f"adapter error: {type(e).__name__}")
600
+ if not isinstance(r, dict) or r.get("state") not in ("ok", "skipped") or \
601
+ not isinstance(r.get("hits"), list):
602
+ return block(source, "skipped", "adapter returned an unexpected result")
603
+ if r["state"] == "skipped":
604
+ return block(source, "skipped", str(r.get("reason") or "unavailable"), r.get("revision"))
605
+ partial = r.get("partial") if isinstance(r.get("partial"), list) else []
606
+ capped = r.get("capped") if isinstance(r.get("capped"), list) else []
607
+ limit = r.get("cap_limit") if isinstance(r.get("cap_limit"), int) else None
608
+ total = r.get("total") if isinstance(r.get("total"), int) and not isinstance(r.get("total"), bool) else None
609
+ return block(source, "ok", r.get("reason"), r.get("revision"), r["hits"],
610
+ partial=[str(x) for x in partial], capped=[str(x) for x in capped], cap_limit=limit,
611
+ total=total)
612
+
613
+
614
+ # --------------------------------------------------------------------------
615
+ # the search
616
+
617
+ def parse_sources(text: str | None) -> tuple[str, ...]:
618
+ if text is None:
619
+ return SOURCES
620
+ chosen = [s.strip() for s in text.split(",") if s.strip()]
621
+ unknown = [s for s in chosen if s not in SOURCES]
622
+ if not chosen or unknown:
623
+ raise core.UsageError(f"--sources: unknown or empty {unknown or text!r}; "
624
+ f"choose from {','.join(SOURCES)}")
625
+ return tuple(s for s in SOURCES if s in chosen)
626
+
627
+
628
+ def do_search(term: str, *, reg_path: pathlib.Path, index_dir: pathlib.Path,
629
+ package: str | None = None, sources: tuple[str, ...] = SOURCES,
630
+ offline: bool = False, force_loogle: bool = False,
631
+ loogle_query: str | None = None) -> tuple[list[str], dict]:
632
+ """`loogle_query`, when given, is what Loogle receives instead of the term (whatever the term's route);
633
+ every other source still gets the term."""
634
+ if not tokens(term):
635
+ raise core.UsageError("TERM needs at least one letter or digit")
636
+ if loogle_query is not None:
637
+ if not loogle_query.strip():
638
+ raise core.UsageError("--loogle-query needs a Lean name, term or pattern")
639
+ if "loogle" not in sources:
640
+ raise core.UsageError("--loogle-query was given but --sources does not select loogle")
641
+ if package and reg_path.is_file() and package not in (core.load_registry(reg_path)["packages"]):
642
+ raise core.UsageError(f"--package {package!r} is not in the registry")
643
+ blocks, route, cov = [], route_of(term), None
644
+ for src in SOURCES:
645
+ if src not in sources:
646
+ blocks.append(block(src, "skipped", "not selected"))
647
+ elif src == "registry":
648
+ b, cov = registry_search(term, reg_path)
649
+ blocks.append(b)
650
+ elif src == "index":
651
+ blocks.append(index_block(term, index_dir))
652
+ elif offline:
653
+ blocks.append(block(src, "skipped", "offline"))
654
+ elif src == "loogle" and loogle_query is not None:
655
+ blocks.append(adapter_block(src, loogle_query))
656
+ elif src in SIGNATURE_SOURCES and route == "natural-language" and not force_loogle:
657
+ blocks.append(block(src, "skipped", LOOGLE_NL_REASON))
658
+ else:
659
+ blocks.append(adapter_block(src, term))
660
+ blocks[-1]["route"] = route
661
+ date = core.now_iso()[:10]
662
+ payload = {"ok": True, "term": term, "date": date, "package": package, "offline": offline,
663
+ "route": route, "sources": blocks, "total_hits": sum(len(b["hits"]) for b in blocks),
664
+ "coverage": cov, "loogle_query": loogle_query,
665
+ "cache": {"root": adapters.cache_root_source(),
666
+ "writes": [w for b in blocks for w in b.get("cache_writes") or []]}}
667
+ # Completeness at a glance (#14, G9): a source skipped (offline, an outage, a route) means a zero count
668
+ # is not a negative result; callers that copy "0 hits" into a record must see that here.
669
+ skipped = [b["source"] for b in blocks if b["state"] != "ok"]
670
+ # A source that answered with one of its parts failed (GitHub code search rate-limited while the
671
+ # repository search worked) is incomplete too, or its zero reads as an absence (field report).
672
+ # A part that returned exactly its result limit (GitHub's 30), or listed fewer matches than it found
673
+ # (Palomar, Reservoir, Loogle), is truncated the same way; so is a local source that could not read
674
+ # everything (the registry's file cap or unreadable files, an unreadable index entry).
675
+ truncated = [b["source"] for b in blocks
676
+ if b["state"] == "ok" and (b.get("partial") or b.get("capped") or b.get("incomplete"))]
677
+ payload.update({"complete": not skipped and not truncated, "searched": len(blocks) - len(skipped),
678
+ "skipped_sources": skipped, "truncated_sources": truncated})
679
+ return render_text(payload), payload
680
+
681
+
682
+ def _n(k: int) -> str:
683
+ return f"{k} hit" + ("" if k == 1 else "s")
684
+
685
+
686
+ def state_text(b: dict) -> str:
687
+ return "ok" if b["state"] == "ok" else f"skipped: {b['reason']}"
688
+
689
+
690
+ def consulted_state(b: dict) -> str:
691
+ """`ok, 3 hits`; `partial, 0 hits` when a part of the source failed; `capped, 30 hits` when a part
692
+ returned its result limit; else `skipped: <reason>`."""
693
+ if b["state"] != "ok":
694
+ return state_text(b)
695
+ return ("partial, " if b.get("partial") else "capped, " if b.get("capped")
696
+ else "incomplete, " if b.get("incomplete") else "ok, ") + _n(len(b["hits"]))
697
+
698
+
699
+ def part_problems(b: dict) -> list[str]:
700
+ """`code search failed`, `code search returned its 30-result limit`: why a source answered in part."""
701
+ lim = f"{b['cap_limit']}-result" if b.get("cap_limit") else "result"
702
+ return ([f"{p} search failed" for p in b.get("partial") or []]
703
+ + [f"{b['total']} matches found, first {b['cap_limit']} listed"
704
+ if p == "results" and b.get("total") and b.get("cap_limit")
705
+ else f"{p} search returned its {lim} limit" for p in b.get("capped") or []])
706
+
707
+
708
+ def truncation_text(payload: dict) -> str:
709
+ """Why each source in `truncated_sources` answered only in part, e.g. `registry: declaration search hit a
710
+ file cap (see the coverage line); github: code search failed`, `index: 1 unreadable entry not searched`
711
+ or `palomar: 50 matches found, first 30 listed`."""
712
+ parts = {b["source"]: part_problems(b) for b in payload["sources"]}
713
+ out = []
714
+ for src in payload.get("truncated_sources") or []:
715
+ b = next(x for x in payload["sources"] if x["source"] == src)
716
+ why = parts.get(src) or []
717
+ if b.get("incomplete"):
718
+ why = why + [b["incomplete"]]
719
+ out.append(f"{src}: {', '.join(why)}" if why else f"{src} answered only in part")
720
+ return "; ".join(out)
721
+
722
+
723
+ def render_text(payload: dict) -> list[str]:
724
+ lines = [f'lean-pkg search "{payload["term"]}" on {payload["date"]}'
725
+ + (f" for package {payload['package']}" if payload["package"] else "")
726
+ + (f' (Loogle query "{payload["loogle_query"]}")' if payload.get("loogle_query") else "")]
727
+ for b in payload["sources"]:
728
+ if b["state"] != "ok":
729
+ lines.append(f"{b['source']}: skipped: {b['reason']}")
730
+ continue
731
+ rev = f" at {b['revision']}" if b["revision"] else ""
732
+ note = f" ({b['reason']})" if b["reason"] else ""
733
+ lines.append(f"{b['source']}: ok{rev}, {_n(len(b['hits']))}{note}")
734
+ for h in b["hits"]:
735
+ if h.get("hit_kind") == DECL_HIT_KIND:
736
+ lines.append(f" [{h['score']} {h['where']}] {h['package']}: {h['decl']} "
737
+ f"({h['kind']}, {DECL_HIT_KIND}, trust {h['trust']}, {h['file']})")
738
+ lines.append(f" {h['summary']}")
739
+ elif h.get("hit_kind") == "package":
740
+ repo = f" — {h['repo']}" if h["repo"] else ""
741
+ lines.append(f" [{h['score']} {h['where']}] package: {h['package']} ({h['status']}){repo}")
742
+ if h["summary"]:
743
+ lines.append(f" {h['summary']}")
744
+ elif "id" in h:
745
+ pin = f", pin {str(h['pin'])[:12]}" if h["pin"] else ""
746
+ cond = " (conditional)" if h.get("conditional") else ""
747
+ lines.append(f" [{h['score']} {h['where']}] {h['id']} {h['decl']} "
748
+ f"({h['kind']}, {h['status']}{cond}, trust {h['trust']}{pin})")
749
+ lines.append(f" {h['summary']}")
750
+ else:
751
+ lines.append(f" {h['name']} {h.get('url') or ''}".rstrip())
752
+ if h.get("summary"):
753
+ lines.append(f" {h['summary']}")
754
+ cov_line = coverage_text(payload.get("coverage"))
755
+ if cov_line:
756
+ lines.append(cov_line)
757
+ cache = payload.get("cache") or {}
758
+ if cache.get("writes"):
759
+ root = {"--cache-dir": "the --cache-dir directory", "XDG_CACHE_HOME": "$XDG_CACHE_HOME/lean-pkg",
760
+ "default": "~/.cache/lean-pkg"}.get(cache.get("root"), "the lean-pkg cache")
761
+ lines.append(f"cache: wrote {', '.join(cache['writes'])} under {root} (a cache refresh; the registry was "
762
+ "not written; --cache-dir DIR keeps a search's cache private)")
763
+ why = truncation_text(payload)
764
+ if why and not payload.get("skipped_sources"):
765
+ lines.append(f"incomplete: {why}; a zero here is not a negative result")
766
+ if payload.get("skipped_sources"):
767
+ n, k = len(payload["sources"]), len(payload["skipped_sources"])
768
+ cap = f"; {why}" if why else ""
769
+ lines.append(f"incomplete: searched {n - k} of {n} sources; skipped: {', '.join(payload['skipped_sources'])}"
770
+ f"{cap}; a zero here is not a negative result")
771
+ lines.append("consulted: " + ", ".join(
772
+ f"{b['source']} ({consulted_state(b)})"
773
+ for b in payload["sources"]))
774
+ return lines
775
+
776
+
777
+ # --------------------------------------------------------------------------
778
+ # CLI glue: lean_pkg.cli.main calls add_parsers(sub, add_json)
779
+
780
+ def cmd_search(args) -> int:
781
+ if args.repo_dir and not args.record:
782
+ raise core.UsageError("--repo is only used with --record")
783
+ if args.agent and not args.record:
784
+ raise core.UsageError("--agent is only used with --record")
785
+ reg_path = core.registry_path(args)
786
+ if args.cache_dir is not None and not str(args.cache_dir).strip():
787
+ raise core.UsageError("--cache-dir needs a directory")
788
+ saved_root = adapters.CACHE_ROOT
789
+ try:
790
+ if args.cache_dir is not None:
791
+ adapters.CACHE_ROOT = pathlib.Path(args.cache_dir).expanduser().resolve()
792
+ out, payload = do_search(args.term, reg_path=reg_path,
793
+ index_dir=idx.index_root(args), package=args.package,
794
+ sources=parse_sources(args.sources), offline=args.offline,
795
+ force_loogle=args.loogle, loogle_query=args.loogle_query)
796
+ finally:
797
+ adapters.CACHE_ROOT = saved_root
798
+ if args.record:
799
+ from . import prior_art
800
+ events_p = core.events_path(args) if (args.events or reg_path.is_file()) else None
801
+ # the network search above runs unlocked; the record file and its event under the registry lock
802
+ with core.registry_lock(reg_path) if reg_path.is_file() else contextlib.nullcontext():
803
+ if reg_path.is_file() and args.package: # #21.3: the lease-holder rule, as for record
804
+ core.warn_lease(core.lease_actor(core.load_registry(reg_path), args.package, args.agent,
805
+ "search --record"))
806
+ lines, payload["record"] = prior_art.write_record(payload, reg_path=reg_path,
807
+ events_p=events_p, repo_dir=args.repo_dir,
808
+ actor=args.agent)
809
+ payload["nav_hint"] = (prior_art.nav_hint(payload["record"]["path"])
810
+ if payload["record"].get("mkdocs") else None)
811
+ out += lines
812
+ failed = args.require_complete and not payload["complete"]
813
+ if failed:
814
+ # Opt-in (field report): an incomplete search exits 1 so a script cannot read its zero as an absence.
815
+ why = truncation_text(payload)
816
+ msg = ("search incomplete (--require-complete): "
817
+ + (f"skipped: {', '.join(payload['skipped_sources'])}" if payload["skipped_sources"] else "")
818
+ + ("; " if payload["skipped_sources"] and why else "") + why)
819
+ payload.update({"ok": False, "error": msg})
820
+ if args.json_out:
821
+ core.print_json(payload)
822
+ else:
823
+ print("\n".join(out))
824
+ if failed:
825
+ print(f"lean-pkg: {msg}", file=sys.stderr)
826
+ return 1
827
+ return 0
828
+
829
+
830
+ def add_parsers(sub, add_json) -> None:
831
+ s = sub.add_parser("search", help="prior-art search over claims, the index and public sources",
832
+ description="Prior-art search. Packages without synced claims are searched by declaration "
833
+ "(fully qualified names; accents folded). A source that skipped, failed in part, "
834
+ "listed fewer matches than it found or could not read everything makes the "
835
+ "search incomplete (complete: false): a zero there is not an absence.")
836
+ s.add_argument("term", help="what to look for (quote a phrase)")
837
+ s.add_argument("--package", default=None,
838
+ help="the registered package this search is for (it labels the output; every "
839
+ "package's claims are still searched)")
840
+ s.add_argument("--offline", action="store_true", help="skip every network source")
841
+ s.add_argument("--loogle", action="store_true",
842
+ help="send the term to Loogle even when it reads as natural language (by default "
843
+ "only declaration/type patterns go to Loogle)")
844
+ s.add_argument("--loogle-query", default=None, metavar="PATTERN",
845
+ help="send PATTERN to Loogle instead of the term (a Lean name, term or pattern such as "
846
+ "'Real.exp' or '?a * ?b = ?b * ?a'); the other sources still get the term")
847
+ s.add_argument("--require-complete", action="store_true",
848
+ help="exit 1 when the search is incomplete (a source skipped, failed in part, capped, or "
849
+ "read only part of what it should); the output is printed in full first")
850
+ s.add_argument("--cache-dir", default=None, metavar="DIR",
851
+ help="use DIR as the lean-pkg cache for this search (Palomar snapshots, Reservoir index) "
852
+ "instead of $XDG_CACHE_HOME/lean-pkg or ~/.cache/lean-pkg")
853
+ s.add_argument("--sources", default=None, metavar="a,b,c",
854
+ help="subset of: " + ",".join(SOURCES) + " (order is fixed)")
855
+ s.add_argument("--index", default=None,
856
+ help=f"index root (default: ${idx.INDEX_ENV}, else ./{idx.DEFAULT_INDEX_DIR})")
857
+ s.add_argument("--record", action="store_true",
858
+ help="write docs/prior-art/<date>-<slug>.md in the package checkout (or --repo) "
859
+ "and a prior-art-searched event")
860
+ s.add_argument("--repo", dest="repo_dir", metavar="DIR", default=None, help="research repository for --record")
861
+ s.add_argument("--agent", default=None,
862
+ help="with --record: the agent acting (recorded as the event's actor); another agent's live "
863
+ "lease on --package then refuses")
864
+ add_json(s)
865
+ s.set_defaults(fn=cmd_search)