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/report.py ADDED
@@ -0,0 +1,727 @@
1
+ # lean-pkg report -- a redacted bug report in the repository's own issue format
2
+ """`lean-pkg report [--command "<lean-pkg args>"] [--body TEXT] [--from-log FILE[:N]] [--package NAME]
3
+ [--expected TEXT] [--workaround TEXT] [--blocking yes|no] [--title T] [--enhancement] [--repo OWNER/NAME]
4
+ [--dry-run|--yes] [--json]` (#47, #55): assemble a bug report in the shape of
5
+ `.github/ISSUE_TEMPLATE/bug_report.md` (same section headings, same order: SECTIONS, which a test
6
+ keeps equal to the template's) and, with `--yes`, file it with `gh issue create` on lean-pkg/lean-pkg
7
+ (label `bug`, or `enhancement`; `--repo` for a fork).
8
+
9
+ Filled automatically, all read-only:
10
+
11
+ - Version: the `lean-pkg --version` line, the Python version and the platform, then the ok/warn lines
12
+ of `doctor --json` and the `comparator host-check --json` verdict.
13
+ - Command / What happened: the command as given, re-run through the CLI entry point in a subprocess
14
+ (`--json` appended when it is not there and the subcommand's parser has the flag), its exit code,
15
+ stdout and stderr. A command that would write (the registry, a package file, a README) is not
16
+ re-run; the body says so. `--body TEXT` (free text, no re-run) and `--from-log FILE[:N]` (the last N
17
+ lines, default 200, of a stage log, under "Log excerpt") go first in What happened, before any re-run;
18
+ at least one of `--command`, `--body`, `--from-log` is required (#55).
19
+ - Minimal registry or receipt: with `--package`, the registry record (status, visibility, lease fields,
20
+ gate and comparator receipt paths with the commits they bind).
21
+ - Checklist: ticked from what is known (`--json` used; `validate` passes).
22
+
23
+ Intake fields, each rendered only when given: `--blocking yes|no` (a `**Blocking**` line before Version),
24
+ `--expected TEXT` (fills What you expected, else the template's placeholder comment) and `--workaround TEXT`
25
+ (a `**Workaround**` section after it). The first line of every body is MARKER, `<!-- lean-pkg-report/1 -->`,
26
+ so an intake channel can recognise a report and its format; `--json` carries the same string as `schema`.
27
+
28
+ Redaction is mandatory and applies to every captured text (the command, its output, the doctor and
29
+ host lines, the record, the title, --expected, --workaround) before it is printed or sent, in this order:
30
+
31
+ 0. in the sections report attaches itself (version, doctor, host, record, the re-run's stdout and
32
+ stderr) only: every record's and lease's `agent`, `workspace` and `contact` value -> `<agent>`,
33
+ `<workspace>`, `<contact>` (#330);
34
+ 1. the registry file -> `<registry>`, its directory -> `<registry-dir>`, every record's checkout
35
+ (`local_path`, as stored, joined to $HOME and resolved) -> `<checkout>`; the user-level default
36
+ registry (`~/.lean-pkg/registry`, which doctor resolves), when it is another one ->
37
+ `<user-default-registry>` / `<user-default-registry-dir>`; the other local paths doctor and the
38
+ version line name (local_paths, #330): lean-pkg's package directory -> `<lean-pkg-install>`, an
39
+ editable install's checkout -> `<lean-pkg-checkout>`, the Python executable -> `<python>`, the git
40
+ work tree holding the registry -> `<registry-repo>`, the index directory -> `<index-dir>`, an event
41
+ log that is not the registry's sibling -> `<events-path>`;
42
+ 2. the current user's home directory -> `~`;
43
+ 3. the `public_safety` scanner: its built-in families, the `--package` checkout's
44
+ `.lean-pkg-private-patterns` and the registry directory's one, and the user/host tokens derived
45
+ from every registry record (`local_path`, `agent`, `workspace`, lease); each match becomes `[…]`.
46
+ Email addresses are redacted even when a record declares them.
47
+
48
+ Every redacted section, the user's (title, --command, --body, --from-log, --package, --expected,
49
+ --workaround) and the attached
50
+ ones, is scanned once more, line by line; a blocking hit left refuses (exit 1, the hit families listed
51
+ and the sections named, nothing filed). The report's own fixed prose is not scanned: a derived token can
52
+ be an ordinary word (#330). Default is a dry run (print title, labels and body; exit 0). `--yes`
53
+ needs `gh` on PATH and `gh auth status` passing (else exit 1 with the `gh auth login` hint).
54
+ """
55
+
56
+ from __future__ import annotations
57
+
58
+ import argparse
59
+ import contextlib
60
+ import io
61
+ import json
62
+ import os
63
+ import pathlib
64
+ import platform
65
+ import re
66
+ import shlex
67
+ import shutil
68
+ import subprocess
69
+ import sys
70
+ import tempfile
71
+
72
+ import yaml
73
+
74
+ from . import audit, cli, cli_parser
75
+ from . import core
76
+ from . import public_safety as ps
77
+
78
+ REPO = "lean-pkg/lean-pkg"
79
+ TEMPLATE = ".github/ISSUE_TEMPLATE/bug_report.md"
80
+ # The bold section labels of TEMPLATE, in order (tests/test_report.py keeps them equal).
81
+ SECTIONS = ("Version", "Command", "What happened", "What you expected", "Minimal registry or receipt",
82
+ "Checklist")
83
+ # Bold labels report adds beyond the template, each only when its flag is given: --blocking and --workaround.
84
+ INTAKE_SECTIONS = ("Blocking", "Workaround")
85
+ # The format marker: the first line of every report body (dry run, --yes, --json) and --json `schema`.
86
+ SCHEMA = "lean-pkg-report/1"
87
+ MARKER = f"<!-- {SCHEMA} -->"
88
+ REGISTRY_TOKEN, REGISTRY_DIR_TOKEN, CHECKOUT_TOKEN = "<registry>", "<registry-dir>", "<checkout>"
89
+ USER_REGISTRY_TOKEN, USER_REGISTRY_DIR_TOKEN = "<user-default-registry>", "<user-default-registry-dir>"
90
+ INDEX_DIR_TOKEN, EVENTS_TOKEN, REGISTRY_REPO_TOKEN = "<index-dir>", "<events-path>", "<registry-repo>"
91
+ INSTALL_TOKEN, LEAN_PKG_CHECKOUT_TOKEN, PYTHON_TOKEN = "<lean-pkg-install>", "<lean-pkg-checkout>", "<python>"
92
+ # #330: the registry fields whose values name a person, an agent or a machine. In the sections report
93
+ # attaches itself, each value becomes its field's placeholder before the scanner runs.
94
+ NAME_FIELDS = (("agent", "<agent>"), ("workspace", "<workspace>"), ("contact", "<contact>"))
95
+ NAME_MIN_LEN = 3
96
+ USER, ATTACHED = "user", "attached" # the origin of a section the blocking guard scans
97
+ RERUN_TIMEOUT = 600 # seconds for the re-run command
98
+ KEEP_HEAD, KEEP_TAIL = 150, 50 # lines kept of a long captured stream
99
+ LOG_TAIL = 200 # default N of --from-log FILE[:N]
100
+ GLOBAL_VALUE_FLAGS = ("--registry", "--events", "--registry-snapshot")
101
+ _REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
102
+ _PATH_END = r"(?![A-Za-z0-9._-])"
103
+ _SUB: list = [] # the CLI's subparsers action, captured by add_parsers
104
+
105
+
106
+ # --------------------------------------------------------------------------
107
+ # redaction
108
+
109
+ class Redactor:
110
+ """Every captured text goes through __call__: placeholders for the registry, checkouts and the index,
111
+ `~` for the home directory, then the public-safety scanner (each match -> […]). The sections report
112
+ attaches itself go through attached(), which first replaces every registry agent, workspace and contact
113
+ value with its placeholder (#330). count: replacements made."""
114
+
115
+ def __init__(self, scanner: ps.Scanner, literals: dict[str, str], homes: list[str],
116
+ names: dict[str, str] | None = None):
117
+ self.scanner = scanner
118
+ self.count = 0
119
+ self.literals = literals
120
+ keys = sorted(literals, key=len, reverse=True)
121
+ self.literal_rx = re.compile("(?:" + "|".join(re.escape(k) for k in keys) + ")" + _PATH_END) if keys else None
122
+ homes = sorted({h for h in homes if len(h) > 1}, key=len, reverse=True)
123
+ self.home_rx = re.compile("(?:" + "|".join(re.escape(h) for h in homes) + ")" + _PATH_END) if homes else None
124
+ self.names = names or {}
125
+ nkeys = sorted(self.names, key=len, reverse=True)
126
+ self.names_rx = (re.compile(r"(?<![A-Za-z0-9_.-])(?:" + "|".join(re.escape(k) for k in nkeys)
127
+ + r")(?![A-Za-z0-9_.-])") if nkeys else None)
128
+
129
+ def attached(self, text: str | None) -> str:
130
+ """A section report attaches itself (doctor, host, version, record, the re-run's output): registry
131
+ names -> placeholders, then __call__."""
132
+ if text and self.names_rx is not None:
133
+ text, n = self.names_rx.subn(lambda m: self.names[m.group(0)], text)
134
+ self.count += n
135
+ return self(text)
136
+
137
+ def __call__(self, text: str | None) -> str:
138
+ if not text:
139
+ return text or ""
140
+ if self.literal_rx is not None:
141
+ text, n = self.literal_rx.subn(lambda m: self.literals[m.group(0)], text)
142
+ self.count += n
143
+ if self.home_rx is not None:
144
+ text, n = self.home_rx.subn("~", text)
145
+ self.count += n
146
+ spans = self.scanner.spans(text)
147
+ if spans:
148
+ text, starts = ps._redact(text, spans)
149
+ self.count += len(set(starts))
150
+ return text
151
+
152
+ def blocking_families(self, text: str) -> list[str]:
153
+ """The pattern families of the blocking hits still in text (labels only, never the strings)."""
154
+ return sorted({ps.PATTERNS_FILE if pat.kind == "file" else pat.label
155
+ for _n, pat, _ex in self.scanner.scan_text(text) if pat.severity == ps.BLOCK})
156
+
157
+ def blocking_sections(self, sections: list[tuple[str, str, str]]) -> list[dict]:
158
+ """#330: [{section, origin, families}] of the (name, origin, redacted text) sections holding a
159
+ blocking hit. The guard scans what the report carries from the user and from its probes, never
160
+ its own fixed prose (a registry-derived name such as `home` is also an English word)."""
161
+ out = []
162
+ for name, origin, text in sections:
163
+ fams = self.blocking_families(text) if text else []
164
+ if fams:
165
+ out.append({"section": name, "origin": origin, "families": fams})
166
+ return out
167
+
168
+
169
+ def _path_forms(p: pathlib.Path) -> set[str]:
170
+ out = {str(p)}
171
+ with contextlib.suppress(OSError, RuntimeError):
172
+ out.add(str(p.resolve()))
173
+ return {s for s in out if len(s) > 1}
174
+
175
+
176
+ def registry_names(records: dict) -> dict[str, str]:
177
+ """{value: placeholder} of every record's agent and workspace and its lease's agent, workspace and
178
+ contact (#330); a value shorter than NAME_MIN_LEN or a scanner stopword is left to the scanner."""
179
+ names: dict[str, str] = {}
180
+ for rec in records.values():
181
+ if not isinstance(rec, dict):
182
+ continue
183
+ lease = rec.get("lease") if isinstance(rec.get("lease"), dict) else {}
184
+ for src in (rec, lease):
185
+ for field, token in NAME_FIELDS:
186
+ v = src.get(field)
187
+ v = v.strip() if isinstance(v, str) else ""
188
+ if len(v) >= NAME_MIN_LEN and v.casefold() not in ps.DERIVED_STOPWORDS:
189
+ names.setdefault(v, token)
190
+ return names
191
+
192
+
193
+ def local_paths(reg_path: pathlib.Path, args) -> list[tuple[str, pathlib.Path]]:
194
+ """(placeholder, path) of the local paths doctor and the version line name besides the registry and the
195
+ checkouts (#330): lean-pkg's package directory and, for an editable install, its checkout; the Python
196
+ executable; the git work tree holding the registry; the index directory; the event log when it is not
197
+ the registry's sibling (that one already reads `<registry-dir>/lean-package-events.jsonl`). A probe
198
+ that fails names nothing."""
199
+ out: list[tuple[str, pathlib.Path]] = []
200
+
201
+ def probe(token: str, fn) -> None:
202
+ with contextlib.suppress(OSError, RuntimeError, ValueError, TypeError, KeyError, AttributeError):
203
+ p = fn()
204
+ if p is not None and str(p) not in ("", "/", "."):
205
+ out.append((token, pathlib.Path(p).absolute()))
206
+
207
+ pkg_dir = cli.package_dir()
208
+ probe(INSTALL_TOKEN, lambda: pkg_dir)
209
+ info = cli.install_detect(pkg_dir) if shutil.which("git") else {}
210
+ if info.get("install") == "editable":
211
+ probe(LEAN_PKG_CHECKOUT_TOKEN, lambda: info["path"])
212
+ probe(PYTHON_TOKEN, lambda: sys.executable)
213
+ if shutil.which("git") and reg_path.parent.is_dir():
214
+ top = core.registry_git(reg_path.parent, "rev-parse", "--show-toplevel")
215
+ if top.returncode == 0 and top.stdout.strip():
216
+ probe(REGISTRY_REPO_TOKEN, lambda: top.stdout.strip())
217
+ if args is not None:
218
+ from . import index as index_mod
219
+ probe(INDEX_DIR_TOKEN, lambda: index_mod.index_source(args)[0])
220
+
221
+ def events():
222
+ ev = core.events_source(args)[0].absolute()
223
+ return ev if _path_forms(ev.parent).isdisjoint(_path_forms(reg_path.parent)) else None
224
+ probe(EVENTS_TOKEN, events)
225
+ return out
226
+
227
+
228
+ def build_redactor(reg_path: pathlib.Path, records: dict, pkg: dict | None, args=None) -> Redactor:
229
+ """The redaction layers for this report (see the module docstring for the order)."""
230
+ literals: dict[str, str] = {}
231
+ # #330: every other local path the attached sections name, whole (absolute and resolved forms): a
232
+ # path left to `~` and the scanner keeps whatever follows a redacted prefix such as `~/Dropbox/`.
233
+ # Set first, so a registry placeholder below wins over one of these naming the same path.
234
+ for token, path in local_paths(reg_path, args):
235
+ for s in _path_forms(path):
236
+ literals[s] = token
237
+ for rec in records.values():
238
+ if not isinstance(rec, dict) or not rec.get("local_path"):
239
+ continue
240
+ with contextlib.suppress(KeyError, TypeError, ValueError):
241
+ for s in _path_forms(core.repo_path(rec)):
242
+ literals[s] = CHECKOUT_TOKEN
243
+ stored = str(rec["local_path"])
244
+ if len(stored) >= 4 and "/" in stored.strip("/"):
245
+ literals.setdefault(stored, CHECKOUT_TOKEN)
246
+ with contextlib.suppress(OSError, RuntimeError):
247
+ user_reg, _detail = core.user_default_registry()
248
+ if user_reg is not None: # doctor's user-default line resolves its symlink
249
+ for s in _path_forms(user_reg.parent) | _path_forms(core.lean_pkg_home() / "registry"):
250
+ literals[s] = USER_REGISTRY_DIR_TOKEN
251
+ for s in _path_forms(user_reg):
252
+ literals[s] = USER_REGISTRY_TOKEN
253
+ for s in _path_forms(reg_path.parent):
254
+ literals[s] = REGISTRY_DIR_TOKEN
255
+ for s in _path_forms(reg_path):
256
+ literals[s] = REGISTRY_TOKEN
257
+ homes = set()
258
+ for h in (core.HOME, pathlib.Path.home(), os.environ.get("HOME") or ""):
259
+ if str(h):
260
+ homes |= _path_forms(pathlib.Path(h))
261
+ checkout = None
262
+ if pkg is not None:
263
+ with contextlib.suppress(KeyError, TypeError, ValueError):
264
+ checkout = core.repo_path(pkg)
265
+ root = checkout if checkout is not None and checkout.is_dir() else reg_path.parent
266
+ sc = ps.Scanner(pkg or {}, root, None)
267
+ sc.emails = set() # a report declares no address: every one is redacted
268
+ if root != reg_path.parent: # the registry directory's patterns file too
269
+ pats, allow, problems, _present = ps.read_patterns_file(reg_path.parent)
270
+ sc.patterns = pats + sc.patterns
271
+ sc.allow += allow
272
+ sc.problems += problems
273
+ for rec in records.values():
274
+ if isinstance(rec, dict) and rec is not pkg:
275
+ sc.patterns += ps.derived_patterns(rec)
276
+ for problem in sc.problems:
277
+ print(f"lean-pkg: WARN {problem}", file=sys.stderr)
278
+ return Redactor(sc, literals, sorted(homes), registry_names(records))
279
+
280
+
281
+ # --------------------------------------------------------------------------
282
+ # the command to re-run
283
+
284
+ def _parse_quietly(parser: argparse.ArgumentParser, argv: list[str]):
285
+ """parser.parse_known_args(argv) with argparse's own output and exits swallowed; None when it
286
+ would exit (a usage error, --help)."""
287
+ saved = cli_parser._Parser.json_requested
288
+ cli_parser._Parser.json_requested = False
289
+ try:
290
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
291
+ return parser.parse_known_args(argv)[0]
292
+ except SystemExit:
293
+ return None
294
+ finally:
295
+ cli_parser._Parser.json_requested = saved
296
+
297
+
298
+ def _deepest(parser: argparse.ArgumentParser, ns) -> argparse.ArgumentParser:
299
+ """The parser that handled the invocation (a nested one such as `claims list`)."""
300
+ for a in parser._actions:
301
+ if isinstance(a, argparse._SubParsersAction):
302
+ chosen = getattr(ns, a.dest, None) if a.dest != argparse.SUPPRESS else None
303
+ if chosen in a.choices:
304
+ return _deepest(a.choices[chosen], ns)
305
+ return parser
306
+
307
+
308
+ def _writes(cmd: str, ns) -> str | None:
309
+ """Why re-running this invocation would write something, else None (conservative)."""
310
+ if cmd == "report":
311
+ return "report does not re-run itself"
312
+ if cmd == "verify" and not getattr(ns, "dry_run", False):
313
+ return "verify writes receipts and gates the package"
314
+ if cmd == "board":
315
+ return None # off a tty (the re-run's stdout is a pipe): the static table
316
+ if cli.is_write_invocation(ns):
317
+ return "it writes the registry or its event log"
318
+ fn = lambda attr: getattr(getattr(ns, attr, None), "__name__", "") # noqa: E731
319
+ if cmd == "wiki" and getattr(ns, "out", None):
320
+ return "--out writes a file"
321
+ if cmd == "formalization" and (getattr(ns, "write", False) or getattr(ns, "out", None)):
322
+ return "--write/--out writes formalization.yaml"
323
+ if cmd == "comparator" and getattr(ns, "name", None) == cli.CONFIG_CMD \
324
+ and not (getattr(ns, "coverage", None) or getattr(ns, "dry_run", False)):
325
+ return "comparator config writes the package's comparator configuration"
326
+ if cmd == "index" and fn("index_fn") in ("run_render", "run_migrate") and not getattr(ns, "check", False):
327
+ return "it writes index files"
328
+ if cmd == "receipt":
329
+ form = {"local": "systemd"}.get(getattr(ns, "receipt_cmd", None), getattr(ns, "receipt_cmd", None))
330
+ return f"receipt {form or 'slurm'} writes a receipt and a redacted verify log"
331
+ if cmd == "claims" and fn("claims_fn") == "run_migrate" and not getattr(ns, "dry_run", False):
332
+ return "it writes a claims file"
333
+ return None
334
+
335
+
336
+ def plan_rerun(tokens: list[str]) -> dict:
337
+ """{"argv": tokens to run (or None: not re-run), "json_added": bool, "skip": reason or None}. Old spellings
338
+ (`claim`, `init`, ...) are rewritten to the canonical ones first, so a moved writer is still recognised."""
339
+ from . import command_tree
340
+ tokens, _hits = command_tree.rewrite_argv(tokens, GLOBAL_VALUE_FLAGS)
341
+ i = 0
342
+ while i < len(tokens) and tokens[i].startswith("-"):
343
+ i += 2 if tokens[i] in GLOBAL_VALUE_FLAGS else 1
344
+ sub = _SUB[0] if _SUB else None
345
+ if sub is None or i >= len(tokens) or tokens[i] not in sub.choices:
346
+ return {"argv": tokens, "json_added": False, "skip": None} # argparse refuses it before any work
347
+ cmd, parser = tokens[i], sub.choices[tokens[i]]
348
+ ns = _parse_quietly(parser, tokens[i + 1:])
349
+ if ns is None:
350
+ return {"argv": tokens, "json_added": False, "skip": None} # a usage error or --help: no work done
351
+ cmd = getattr(ns, "cmd", None) or cmd # a noun's verb keeps its pre-1.0 cmd (`lease claim`: claim)
352
+ ns.cmd = cmd
353
+ why = _writes(cmd, ns)
354
+ if why:
355
+ return {"argv": None, "json_added": False, "skip": why}
356
+ has_json = any("--json" in a.option_strings for a in _deepest(parser, ns)._actions)
357
+ if has_json and "--json" not in tokens and "--" not in tokens:
358
+ return {"argv": tokens + ["--json"], "json_added": True, "skip": None}
359
+ return {"argv": tokens, "json_added": False, "skip": None}
360
+
361
+
362
+ def run_child(argv: list[str]) -> tuple[int | None, str, str]:
363
+ """(exit code or None on timeout, stdout, stderr) of `lean-pkg ARGV`, run as this very package."""
364
+ env = dict(os.environ)
365
+ src = str(pathlib.Path(__file__).resolve().parents[1])
366
+ env["PYTHONPATH"] = os.pathsep.join([src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
367
+ try:
368
+ p = subprocess.run([sys.executable, "-m", "lean_pkg.cli", *argv], capture_output=True, text=True,
369
+ check=False, env=env, stdin=subprocess.DEVNULL, timeout=RERUN_TIMEOUT)
370
+ except subprocess.TimeoutExpired as e:
371
+ out = e.stdout.decode(errors="replace") if isinstance(e.stdout, bytes) else (e.stdout or "")
372
+ err = e.stderr.decode(errors="replace") if isinstance(e.stderr, bytes) else (e.stderr or "")
373
+ return None, out, err + f"\n(timed out after {RERUN_TIMEOUT}s)"
374
+ return p.returncode, p.stdout, p.stderr
375
+
376
+
377
+ # --------------------------------------------------------------------------
378
+ # the read-only facts
379
+
380
+ def version_text() -> str:
381
+ from . import __version__
382
+ line = cli.version_line(__version__, cli.install_detect(cli.package_dir()))
383
+ return f"{line}; Python {platform.python_version()}; {platform.platform()}"
384
+
385
+
386
+ def doctor_lines(args) -> list[str]:
387
+ """`doctor --json`: its ok and warn lines, one each."""
388
+ checks, _ok = cli.doctor_checks(args)
389
+ return [f"{c['level']} {c['item']}: {c['detail']}" for c in checks if c["level"] in ("ok", "warn")]
390
+
391
+
392
+ def host_verdict() -> str:
393
+ from .comparator_receipt import host_checks
394
+ res = host_checks()
395
+ return f"verdict: {res['verdict']}"
396
+
397
+
398
+ def _receipt_commit(repo: pathlib.Path, rel) -> str | None:
399
+ try:
400
+ return str(json.loads((repo / str(rel)).read_text())["commit"])
401
+ except (OSError, ValueError, KeyError, TypeError):
402
+ return None
403
+
404
+
405
+ def record_lines(pkg: dict) -> list[str]:
406
+ """The registry record's status, lease and receipt fields; local_path is always `<checkout>`."""
407
+ out = [f"name: {pkg.get('name')}", f"status: {pkg.get('status')}", f"visibility: {pkg.get('visibility')}",
408
+ f"local_path: {CHECKOUT_TOKEN}", f"lean_toolchain: {pkg.get('lean_toolchain')}"]
409
+ lease = pkg.get("lease")
410
+ if isinstance(lease, dict):
411
+ exp = core.lease_expiry_or_none(lease)
412
+ out.append("lease: " + ", ".join(f"{k}={lease.get(k)}" for k in ("agent", "workspace", "contact",
413
+ "claimed_at", "ttl_hours",
414
+ "reason"))
415
+ + f", expires_at={exp.isoformat() if exp else None}")
416
+ else:
417
+ out.append("lease: none")
418
+ gate = pkg.get("gate") if isinstance(pkg.get("gate"), dict) else {}
419
+ try:
420
+ repo = core.repo_path(pkg)
421
+ except (KeyError, TypeError, ValueError):
422
+ repo = None
423
+ for label, key in (("gate receipt", "receipt"), ("comparator receipt", "comparator")):
424
+ rel = gate.get(key)
425
+ if not rel:
426
+ out.append(f"{label}: none")
427
+ continue
428
+ commit = _receipt_commit(repo, rel) if repo is not None else None
429
+ out.append(f"{label}: {rel} (commit {commit or 'unreadable'})")
430
+ return out
431
+
432
+
433
+ # --------------------------------------------------------------------------
434
+ # the body
435
+
436
+ def fence(text: str, lang: str = "") -> str:
437
+ """text in a code fence longer than any backtick run inside it."""
438
+ run = max((len(m) for m in re.findall(r"`+", text)), default=0)
439
+ f = "`" * max(3, run + 1)
440
+ return f"{f}{lang}\n{text.rstrip(chr(10))}\n{f}"
441
+
442
+
443
+ def clip(text: str) -> str:
444
+ lines = text.rstrip("\n").splitlines()
445
+ if len(lines) <= KEEP_HEAD + KEEP_TAIL:
446
+ return "\n".join(lines)
447
+ return "\n".join(lines[:KEEP_HEAD] + [f"[... {len(lines) - KEEP_HEAD - KEEP_TAIL} line(s) omitted ...]"]
448
+ + lines[-KEEP_TAIL:])
449
+
450
+
451
+ def render_body(f: dict) -> str:
452
+ """The issue body: SECTIONS in order, each filled from the (already redacted) facts in f."""
453
+ v, c, h, e, m, k = SECTIONS
454
+ b, w = INTAKE_SECTIONS
455
+ parts = [MARKER,
456
+ "<!-- filed with `lean-pkg report`: captured text is redacted (paths, home directory, "
457
+ "private patterns, registry-derived names) -->", ""]
458
+ if f.get("blocking"):
459
+ parts += [f"**{b}**: {f['blocking']}", ""]
460
+ parts += [f"**{v}**: {f['version']}", ""]
461
+ parts += ["`lean-pkg doctor --json` (ok/warn lines):", fence("\n".join(f["doctor"]) or "(none)"), "",
462
+ f"`lean-pkg comparator host-check --json`: {f['host']}", ""]
463
+ parts += [f"**{c}** (exact, with flags; private paths redacted):", "", fence(f["command"]), ""]
464
+ given = [] # --body, then --from-log (#55), before any re-run
465
+ if f.get("body_text"):
466
+ given += [f["body_text"].rstrip("\n"), ""]
467
+ if f.get("log"):
468
+ lg = f["log"]
469
+ given += [f"_Log excerpt_ (last {lg['lines']} line(s) of `{lg['path']}`):", fence(lg["text"] or "(empty)"), ""]
470
+ if f["run"] is None:
471
+ head = f"**{h}**:" if given else f"**{h}** (paste the output, including any JSON reason):"
472
+ parts += [head, ""] + given + ([f["what"], ""] if f["what"] else [])
473
+ else:
474
+ r = f["run"]
475
+ rerun = ("re-run by `lean-pkg report`" + (", with `--json` appended" if r["json_added"] else "")
476
+ + f"; exit code {r['exit']}")
477
+ streams = ["stdout:", fence(r["stdout"] or "(empty)"), "", "stderr:", fence(r["stderr"] or "(empty)"), ""]
478
+ if given:
479
+ parts += [f"**{h}**:", ""] + given + [rerun[0].upper() + rerun[1:] + ":", ""] + streams
480
+ else:
481
+ parts += [f"**{h}** ({rerun}):", ""] + streams
482
+ parts += [f"**{e}**:", "", (f.get("expected") or "<!-- what should have happened -->").rstrip("\n"), ""]
483
+ if f.get("workaround"):
484
+ parts += [f"**{w}**:", "", f["workaround"].rstrip("\n"), ""]
485
+ parts += [f"**{m}** that reproduces it, if the problem is about validation (attach a file; replace "
486
+ f"private paths with placeholders):", ""]
487
+ if f["record"]:
488
+ parts += [f"Registry record of `{f['package']}` (`lean-pkg report --package`):", fence("\n".join(f["record"])), ""]
489
+ parts += [f"**{k}**",
490
+ f"- [{'x' if f['json'] else ' '}] I ran the command with `--json` and included the full reason.",
491
+ f"- [{'x' if f['valid'] else ' '}] The registry passes `lean-pkg validate` apart from this problem.",
492
+ ""]
493
+ return "\n".join(parts)
494
+
495
+
496
+ # --------------------------------------------------------------------------
497
+ # the command
498
+
499
+ def report_sections(f: dict, title: str, title_is_user: bool) -> list[tuple[str, str, str]]:
500
+ """(name, origin, redacted text) of every variable part of the title and body (#330): the user's own
501
+ text, and the sections report attaches itself. render_body adds only fixed prose around them."""
502
+ out = [("title", USER if title_is_user else ATTACHED, title), ("--command", USER, f["command"]),
503
+ ("--body", USER, f.get("body_text") or ""), ("--package", USER, f.get("package") or ""),
504
+ ("--expected", USER, f.get("expected") or ""), ("--workaround", USER, f.get("workaround") or "")]
505
+ if f.get("log"):
506
+ out.append(("--from-log", USER, f["log"]["path"] + "\n" + (f["log"]["text"] or "")))
507
+ out += [("version", ATTACHED, f["version"]), ("doctor", ATTACHED, "\n".join(f["doctor"])),
508
+ ("host-check", ATTACHED, f["host"]), ("record", ATTACHED, "\n".join(f["record"]))]
509
+ if f["run"] is not None:
510
+ out += [("stdout", ATTACHED, f["run"]["stdout"]), ("stderr", ATTACHED, f["run"]["stderr"])]
511
+ return out
512
+
513
+
514
+ def where(hits: list[dict]) -> str:
515
+ """`your text (--body)`, `an attached section (doctor)`, or both, for a refusal."""
516
+ mine = [h["section"] for h in hits if h["origin"] == USER]
517
+ theirs = [h["section"] for h in hits if h["origin"] == ATTACHED]
518
+ parts = [f"your text ({', '.join(mine)})"] if mine else []
519
+ if theirs:
520
+ parts.append(f"{'an attached section' if len(theirs) == 1 else 'attached sections'} ({', '.join(theirs)})")
521
+ return " and ".join(parts)
522
+
523
+
524
+ def _gh_ready() -> None:
525
+ if shutil.which("gh") is None:
526
+ raise core.Fail("gh is not on PATH: install the GitHub CLI, run `gh auth login`, then re-run with --yes "
527
+ "(nothing filed)")
528
+ p = core.gh("auth", "status", "--hostname", "github.com")
529
+ if p.returncode != 0:
530
+ raise core.Fail("gh is not logged in to github.com: run `gh auth login`, then re-run with --yes "
531
+ "(nothing filed)")
532
+
533
+
534
+ def _tokens(command: str) -> list[str]:
535
+ try:
536
+ tokens = shlex.split(command)
537
+ except ValueError as e:
538
+ raise core.UsageError(f"--command: cannot split it into arguments ({e})") from e
539
+ if tokens and tokens[0] == "lean-pkg":
540
+ tokens = tokens[1:]
541
+ if not tokens:
542
+ raise core.UsageError("--command needs the lean-pkg arguments, e.g. --command \"status NAME\"")
543
+ return tokens
544
+
545
+
546
+ def _log_spec(spec: str) -> tuple[pathlib.Path, int]:
547
+ """--from-log FILE[:N] -> (file, N); N defaults to LOG_TAIL. A FILE that exists as given wins over a
548
+ `:N` reading (a colon in the file name)."""
549
+ if not spec:
550
+ raise core.UsageError("--from-log needs FILE or FILE:N")
551
+ path, n = spec, LOG_TAIL
552
+ if not pathlib.Path(spec).is_file() and ":" in spec:
553
+ path, _sep, tail = spec.rpartition(":")
554
+ if not re.fullmatch(r"[0-9]+", tail) or int(tail) < 1:
555
+ raise core.UsageError(f"--from-log FILE:N: N must be a positive integer, got {tail!r}")
556
+ n = int(tail)
557
+ p = pathlib.Path(path)
558
+ if not p.is_file():
559
+ raise core.UsageError(f"--from-log: no such file: {path}")
560
+ return p, n
561
+
562
+
563
+ def _log_tail(p: pathlib.Path, n: int) -> list[str]:
564
+ try:
565
+ text = p.read_text(encoding="utf-8", errors="replace")
566
+ except OSError as e:
567
+ raise core.UsageError(f"--from-log: cannot read {p} ({e.strerror or e})") from e
568
+ return text.rstrip("\n").splitlines()[-n:] if text.strip("\n") else []
569
+
570
+
571
+ def cmd_report(args) -> int:
572
+ if args.repo is not None and not _REPO_RE.match(args.repo):
573
+ raise core.UsageError(f"--repo must be OWNER/NAME, got {args.repo!r}")
574
+ if args.title is not None and not args.title.strip():
575
+ raise core.UsageError("--title must not be empty")
576
+ for flag in ("body", "expected", "workaround"):
577
+ if getattr(args, flag) is not None and not getattr(args, flag).strip():
578
+ raise core.UsageError(f"--{flag} must not be empty")
579
+ if args.command is None and args.body is None and args.from_log is None:
580
+ raise core.UsageError("report needs at least one of --command \"ARGS\" (re-run it), --body TEXT "
581
+ "(describe it) or --from-log FILE[:N] (the tail of a stage log)")
582
+ tokens = _tokens(args.command) if args.command is not None else None
583
+ log = None
584
+ if args.from_log is not None:
585
+ log_path, log_n = _log_spec(args.from_log)
586
+ log = {"path": str(log_path), "tail": _log_tail(log_path, log_n)}
587
+ if args.yes:
588
+ _gh_ready()
589
+ reg_path = core.registry_path(args)
590
+ data, records, valid = None, {}, False
591
+ if reg_path.is_file():
592
+ try:
593
+ data = core.load_registry(reg_path)
594
+ records = data.get("packages") or {}
595
+ except core.Fail:
596
+ data = None
597
+ with contextlib.suppress(OSError, yaml.YAMLError):
598
+ valid = not audit.validate_registry(yaml.safe_load(reg_path.read_text()))
599
+ pkg = None
600
+ if args.package is not None:
601
+ if data is None:
602
+ core.load_registry(reg_path) # raises the right refusal
603
+ pkg = core.get_pkg(data, args.package)
604
+ red = build_redactor(reg_path, records, pkg, args)
605
+ att = red.attached
606
+
607
+ def safely(fn, *a):
608
+ try:
609
+ return fn(*a)
610
+ except Exception as e: # noqa: BLE001 -- a report diagnoses; one broken probe is a line, not a crash
611
+ return f"unavailable ({type(e).__name__}: {e})"
612
+
613
+ doctor = safely(doctor_lines, args)
614
+ facts = {"version": att(safely(version_text)),
615
+ "doctor": [att(x) for x in doctor] if isinstance(doctor, list) else [att(doctor)],
616
+ "host": att(safely(host_verdict)),
617
+ "package": red(args.package) if args.package else None,
618
+ "record": [att(x) for x in record_lines(pkg)] if pkg is not None else [],
619
+ "valid": valid, "run": None, "json": False, "what": None,
620
+ "body_text": red(args.body.strip("\n")) if args.body is not None else None,
621
+ "expected": red(args.expected.strip("\n")) if args.expected is not None else None,
622
+ "workaround": red(args.workaround.strip("\n")) if args.workaround is not None else None,
623
+ "blocking": args.blocking,
624
+ "log": ({"path": red(log["path"]), "lines": len(log["tail"]), "text": red("\n".join(log["tail"]))}
625
+ if log is not None else None)}
626
+ if tokens is None:
627
+ facts["command"] = "lean-pkg ..."
628
+ shown = None
629
+ else:
630
+ shown = "lean-pkg " + args.command.strip().removeprefix("lean-pkg").strip()
631
+ facts["command"] = red(shown)
632
+ plan = plan_rerun(tokens)
633
+ facts["json"] = "--json" in tokens or plan["json_added"]
634
+ if plan["argv"] is None:
635
+ facts["what"] = (f"(not re-run by `lean-pkg report`: {plan['skip']}; paste its output, including "
636
+ f"any JSON reason)")
637
+ else:
638
+ argv = list(plan["argv"])
639
+ for flag, dest in (("--registry", "registry"), ("--events", "events")):
640
+ if getattr(args, dest, None) and flag not in argv and not any(a.startswith(flag + "=") for a in argv):
641
+ argv = [flag, str(getattr(args, dest))] + argv
642
+ code, out, err = run_child(argv)
643
+ facts["run"] = {"json_added": plan["json_added"], "exit": "timeout" if code is None else code,
644
+ "stdout": att(clip(out)), "stderr": att(clip(err))}
645
+ if args.title is not None:
646
+ title = red(args.title.strip().splitlines()[0])
647
+ else:
648
+ from . import __version__
649
+ title = "report: " + (red(shown.splitlines()[0]) if shown else f"lean-pkg {__version__}")
650
+ labels = ["enhancement" if args.enhancement else "bug"]
651
+ body = render_body(facts)
652
+ repo = args.repo or REPO
653
+ hits = red.blocking_sections(report_sections(facts, title, args.title is not None or shown is not None))
654
+ families = sorted({f for h in hits for f in h["families"]})
655
+ payload = {"ok": True, "filed": False, "url": None, "title": title, "labels": labels, "body": body,
656
+ "redactions": red.count, "schema": SCHEMA}
657
+ if facts["log"] is not None:
658
+ payload["log_excerpt"] = {"path": facts["log"]["path"], "lines": facts["log"]["lines"]}
659
+ if families:
660
+ msg = (f"report: a blocking private pattern remains after redaction ({', '.join(families)}) in "
661
+ f"{where(hits)}; nothing filed")
662
+ if args.json_out:
663
+ core.print_json(dict(payload, ok=False, body=None, error=msg, families=families, sections=hits))
664
+ print(f"lean-pkg: {msg}", file=sys.stderr)
665
+ return 1
666
+ if not args.yes:
667
+ if args.json_out:
668
+ core.print_json(payload)
669
+ else:
670
+ print(f"title: {title}\nlabels: {', '.join(labels)}\nrepository: {repo}\nredactions: {red.count}\n---")
671
+ print(body.rstrip("\n"))
672
+ print(f"---\ndry run: nothing filed; `--yes` files it on {repo} with `gh issue create` "
673
+ f"(needs `gh auth login`)")
674
+ return 0
675
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-report-") as d:
676
+ body_file = pathlib.Path(d) / "body.md"
677
+ body_file.write_text(body, encoding="utf-8")
678
+ p = core.gh("issue", "create", "-R", repo, "--title", title, "--label", labels[0],
679
+ "--body-file", str(body_file))
680
+ if p.returncode != 0:
681
+ raise core.Fail(f"gh issue create failed (exit {p.returncode}): "
682
+ f"{red((p.stderr or p.stdout).strip()) or 'no output'}; nothing filed")
683
+ urls = re.findall(r"https://\S+", p.stdout or "")
684
+ url = urls[-1] if urls else None
685
+ payload.update(filed=True, url=url)
686
+ if args.json_out:
687
+ core.print_json(payload)
688
+ else:
689
+ print(url or (p.stdout or "").strip())
690
+ return 0
691
+
692
+
693
+ def add_parsers(sub, add_json) -> None:
694
+ _SUB[:] = [sub]
695
+ s = sub.add_parser("report", help="read-only: a redacted bug report in the repository's issue format; "
696
+ "dry run unless --yes (files it with gh issue create)")
697
+ s.add_argument("--command", default=None, metavar="ARGS",
698
+ help="the lean-pkg arguments to capture, quoted as one string (\"status NAME\"); re-run in a "
699
+ "subprocess (with --json when the subcommand has it) unless it would write; "
700
+ "a value starting with '-' needs --command=VALUE")
701
+ s.add_argument("--body", default=None, metavar="TEXT",
702
+ help="free text for What happened, nothing re-run (before the re-run when --command is "
703
+ "given too); redacted like everything else")
704
+ s.add_argument("--from-log", default=None, metavar="FILE[:N]",
705
+ help=f"the last N lines (default {LOG_TAIL}) of a stage log, under Log excerpt in What "
706
+ "happened; redacted like everything else; a missing file is a usage error")
707
+ s.add_argument("--expected", default=None, metavar="TEXT",
708
+ help="what you expected instead, for What you expected; redacted like --body")
709
+ s.add_argument("--workaround", default=None, metavar="TEXT",
710
+ help="what you did instead, as a Workaround section after What you expected; redacted like "
711
+ "--body")
712
+ s.add_argument("--blocking", default=None, choices=("yes", "no"),
713
+ help="whether the problem blocks your work: a Blocking line before Version (none without it)")
714
+ s.add_argument("--package", default=None, metavar="NAME",
715
+ help="add the package's registry record (status, lease, receipt commits); its "
716
+ f"{ps.PATTERNS_FILE} joins the redaction")
717
+ s.add_argument("--title", default=None, help="issue title (default: report: <the command>, else "
718
+ "report: lean-pkg <version>)")
719
+ s.add_argument("--enhancement", action="store_true", help="label enhancement instead of bug")
720
+ s.add_argument("--target-repo", dest="repo", default=None, metavar="OWNER/NAME",
721
+ help=f"repository to file on (default {REPO})")
722
+ mode = s.add_mutually_exclusive_group()
723
+ mode.add_argument("--dry-run", action="store_true", help="print title, labels and body; file nothing (default)")
724
+ mode.add_argument("--yes", action="store_true",
725
+ help="file it with `gh issue create` and print the URL (needs `gh auth login`)")
726
+ add_json(s)
727
+ s.set_defaults(fn=cmd_report)