create-lathe 0.0.0-stage → 0.4.0

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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/bin/create-lathe.js +80 -0
  4. package/dist/framework.lock +113 -0
  5. package/dist/package/crates/instrument/Cargo.lock +415 -0
  6. package/dist/package/crates/instrument/Cargo.toml +27 -0
  7. package/dist/package/crates/instrument/examples/instrument.rs +73 -0
  8. package/dist/package/crates/instrument/src/client.rs +128 -0
  9. package/dist/package/crates/instrument/src/lib.rs +32 -0
  10. package/dist/package/crates/instrument/src/logging.rs +109 -0
  11. package/dist/package/crates/instrument/src/protocol.rs +49 -0
  12. package/dist/package/crates/instrument/src/registry.rs +166 -0
  13. package/dist/package/crates/instrument/src/selftest.rs +314 -0
  14. package/dist/package/crates/instrument/src/server.rs +303 -0
  15. package/dist/package/crates/instrument/tests/command_log.rs +60 -0
  16. package/dist/package/crates/instrument/tests/round_trip.rs +134 -0
  17. package/dist/package/crates/instrument/tests/selftest_fail.rs +25 -0
  18. package/dist/package/crates/instrument/tests/selftest_pass.rs +24 -0
  19. package/dist/package/crates/instrument/tests/support/mod.rs +38 -0
  20. package/dist/package/pi/context/journal-de-lot.md +24 -0
  21. package/dist/package/pi/context/tech-skill.md +19 -0
  22. package/dist/package/pi/context/ticket-closed.md +18 -0
  23. package/dist/package/scripts/framework.py +1314 -0
  24. package/dist/package/scripts/gates.py +1134 -0
  25. package/dist/package/scripts/setup.py +195 -0
  26. package/dist/package/skills/bootstrap/SKILL.md +110 -0
  27. package/dist/package/skills/documentation/SKILL.md +110 -0
  28. package/dist/package/skills/documentation/references/agents-md.md +70 -0
  29. package/dist/package/skills/documentation/references/corpus.md +112 -0
  30. package/dist/package/skills/journal/SKILL.md +81 -0
  31. package/dist/package/skills/journal/references/entry.md +172 -0
  32. package/dist/package/skills/lathe/SKILL.md +168 -0
  33. package/dist/package/skills/lathe/evals/routing.md +196 -0
  34. package/dist/package/skills/lathe/references/install.md +128 -0
  35. package/dist/package/skills/lathe/references/invariants.md +31 -0
  36. package/dist/package/skills/mutants/SKILL.md +85 -0
  37. package/dist/package/skills/mutants/references/cargo-mutants.md +176 -0
  38. package/dist/package/skills/mutants/references/triage.md +88 -0
  39. package/dist/package/skills/optimize/SKILL.md +87 -0
  40. package/dist/package/skills/optimize/references/codspeed.md +126 -0
  41. package/dist/package/skills/probe/SKILL.md +82 -0
  42. package/dist/package/skills/probe/references/wait-and-read.md +53 -0
  43. package/dist/package/skills/replicate-ui/SKILL.md +64 -0
  44. package/dist/package/skills/rust/SKILL.md +147 -0
  45. package/dist/package/skills/rust/references/errors.md +63 -0
  46. package/dist/package/skills/rust/references/unsafe.md +65 -0
  47. package/dist/package/skills/scaffold/SKILL.md +78 -0
  48. package/dist/package/skills/scaffold/profiles/rust-cli/.cargo/config.toml +2 -0
  49. package/dist/package/skills/scaffold/profiles/rust-cli/AGENTS.md +22 -0
  50. package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.lock +7 -0
  51. package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.toml +17 -0
  52. package/dist/package/skills/scaffold/profiles/rust-cli/README.md +15 -0
  53. package/dist/package/skills/scaffold/profiles/rust-cli/deny.toml +14 -0
  54. package/dist/package/skills/scaffold/profiles/rust-cli/rustfmt.toml +2 -0
  55. package/dist/package/skills/scaffold/profiles/rust-cli/src/main.rs +38 -0
  56. package/dist/package/skills/scaffold/profiles/rust-cli/tests/cli.rs +27 -0
  57. package/dist/package/skills/scaffold/profiles/rust-library/.cargo/config.toml +2 -0
  58. package/dist/package/skills/scaffold/profiles/rust-library/AGENTS.md +21 -0
  59. package/dist/package/skills/scaffold/profiles/rust-library/Cargo.lock +7 -0
  60. package/dist/package/skills/scaffold/profiles/rust-library/Cargo.toml +18 -0
  61. package/dist/package/skills/scaffold/profiles/rust-library/README.md +15 -0
  62. package/dist/package/skills/scaffold/profiles/rust-library/deny.toml +14 -0
  63. package/dist/package/skills/scaffold/profiles/rust-library/rustfmt.toml +2 -0
  64. package/dist/package/skills/scaffold/profiles/rust-library/src/lib.rs +25 -0
  65. package/dist/package/skills/scaffold/profiles/rust-native-desktop/.cargo/config.toml +2 -0
  66. package/dist/package/skills/scaffold/profiles/rust-native-desktop/AGENTS.md +23 -0
  67. package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.lock +9252 -0
  68. package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.toml +24 -0
  69. package/dist/package/skills/scaffold/profiles/rust-native-desktop/README.md +15 -0
  70. package/dist/package/skills/scaffold/profiles/rust-native-desktop/deny.toml +35 -0
  71. package/dist/package/skills/scaffold/profiles/rust-native-desktop/rustfmt.toml +2 -0
  72. package/dist/package/skills/scaffold/profiles/rust-native-desktop/src/main.rs +74 -0
  73. package/dist/package/skills/scaffold/references/gates.md +29 -0
  74. package/dist/package/skills/scaffold/references/profiles.md +36 -0
  75. package/dist/package/skills/update/SKILL.md +115 -0
  76. package/dist/package/skills/verify-visual/SKILL.md +82 -0
  77. package/dist/package/skills/verify-visual/references/baseline.md +46 -0
  78. package/dist/package/skills/visual-loop/SKILL.md +72 -0
  79. package/dist/package/workflows/batch-to-review.md +41 -0
  80. package/dist/package/workflows/framework-improvement.md +38 -0
  81. package/dist/package/workflows/hard-bug.md +37 -0
  82. package/dist/package/workflows/new-rust-cli.md +33 -0
  83. package/dist/package/workflows/new-rust-desktop-app.md +41 -0
  84. package/dist/package/workflows/new-rust-library.md +34 -0
  85. package/dist/package/workflows/performance-work.md +41 -0
  86. package/dist/package/workflows/ui-change.md +40 -0
  87. package/package.json +33 -4
@@ -0,0 +1,1134 @@
1
+ #!/usr/bin/env python3
2
+ """Run one gate level over a project: four statuses, one verdict rule.
3
+
4
+ gates.py fast --project DIR # under a minute, at every edit
5
+ gates.py verify --project DIR # under five minutes, before review
6
+ gates.py mutants --project DIR # the batch's campaign, before its review
7
+ gates.py campaign --project DIR # the same campaign, coverage reported beside it
8
+ gates.py docs --project DIR # is the agent documentation still true?
9
+ gates.py deps --project DIR # one official skill per technology used
10
+
11
+ The rule is single: a check fails when its exit code is not zero. Rust tooling
12
+ spreads failure over 1, 2, 3, 4, 100 and 101 (EVIDENCE.md E-15), so a check
13
+ written against `code == 1` is green from the second tool onward. A tool that
14
+ is not installed is MISSING, never OK: an absent proof read as a pass is how a
15
+ gate starts lying.
16
+
17
+ `docs` and `deps` inspect files instead of running binaries, so they cannot be
18
+ MISSING. Their rules are still checks: a defect makes the rule's own code 1,
19
+ which keeps "code != 0 means failure" true for every consumer, and a rule that
20
+ does not apply skips with `code: null`.
21
+
22
+ Exit codes: 0 every check green, 1 a failure or a missing required tool, 2 usage.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import contextlib
29
+ import json
30
+ import os
31
+ import re
32
+ import shutil
33
+ import signal
34
+ import subprocess
35
+ import sys
36
+ import time
37
+ from collections.abc import Callable, Iterator
38
+ from dataclasses import dataclass
39
+ from pathlib import Path
40
+
41
+ # One spelling of "a Lathe skill installed globally", and of "which technology needs
42
+ # which skill": framework.py owns both, the gate asks instead of copying the rule.
43
+ import framework
44
+
45
+ PROFILE_FILE = "AGENTS.md"
46
+ PROFILE_LINE = re.compile(r"^Profile:\s*(\S+)", re.MULTILINE)
47
+ OK, FAIL, MISSING, SKIP = "OK", "FAIL", "MISSING", "SKIP"
48
+ DOCS_DIR = Path("documentation") / "llm"
49
+ # Both corpora are verified, and every message names the one it came from: the journal
50
+ # is the corpus a later reader trusts most, and sending them to `documentation/llm`
51
+ # for a defect that lives in the changelog is a gate paid twice.
52
+ CORPUS_DIRS = (DOCS_DIR, Path("documentation") / "changelog")
53
+ CORPUS_SUBJECT = " ".join(relative.as_posix() for relative in CORPUS_DIRS)
54
+ MAX_BLOCK_LINES = 15
55
+ HEADER_FIELDS = ("titre", "type", "public", "verifie_le", "sources")
56
+ ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
57
+ # A journal entry is a register, not a description of the present: its sources are the
58
+ # tickets of a lot, which live in `.scratch/` and are deleted when the lot closes, and
59
+ # its links point into that same directory. Judging either one makes every entry that
60
+ # follows the shipped template red for ever, and an entry is never rewritten.
61
+ JOURNAL_TYPE = "journal"
62
+ SCRATCH_DIR = ".scratch"
63
+ # The corpus is written in the project's language, which is English unless the project
64
+ # says otherwise (D-35), so both vocabularies are matched. `above` and `below` cover
65
+ # `see above` and `see below`; `earlier` is how the same reference reads in a report.
66
+ BACKREF = re.compile(r"\bci-(?:dessus|dessous)\b|\b(?:above|below|earlier)\b", re.IGNORECASE)
67
+ LINK = re.compile(r"\[[^\]]*\]\(\s*<?([^)\s>]+)")
68
+ FENCE = re.compile(r"^\s*(```|~~~)")
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Check:
73
+ """One command, the binary that must exist for it, and its own timeout."""
74
+
75
+ name: str
76
+ cmd: tuple[str, ...]
77
+ tool: str
78
+ timeout: int
79
+ library_only: bool = False
80
+ # Non-empty: the check never runs, and this field says why.
81
+ skip: str = ""
82
+ # Environment the command needs to be strict, when the strictness lives in a
83
+ # Cargo setting rather than a flag (E-15).
84
+ env: tuple[tuple[str, str], ...] = ()
85
+ # Output fragments that mean "there is nothing to check here", not "it broke".
86
+ nothing_to_do: tuple[str, ...] = ()
87
+
88
+
89
+ FAST = (
90
+ Check("fmt", ("cargo", "fmt", "--all", "--check"), "cargo-fmt", 20),
91
+ # `-- -D warnings` invalidates the build cache; the documented route since
92
+ # Cargo 1.97 is the warnings setting, which keeps the cache (E-15).
93
+ Check(
94
+ "clippy",
95
+ ("cargo", "clippy", "--all-targets", "--all-features"),
96
+ "cargo-clippy",
97
+ 90,
98
+ env=(("CARGO_BUILD_WARNINGS", "deny"),),
99
+ ),
100
+ # nextest never runs doctests, so the doctest check is its own command (E-16)
101
+ # and lives in both blocking levels: a stale doc example is a broken build.
102
+ # A binary-only crate has no library target, and `cargo test --doc` exits 101
103
+ # with "no library targets found". That is an absence, not a failure.
104
+ Check(
105
+ "doctests",
106
+ ("cargo", "test", "--doc"),
107
+ "cargo",
108
+ 45,
109
+ nothing_to_do=("no library targets found",),
110
+ ),
111
+ )
112
+
113
+ VERIFY = (
114
+ Check("nextest", ("cargo", "nextest", "run", "--all-features"), "cargo-nextest", 150),
115
+ Check(
116
+ "doctests",
117
+ ("cargo", "test", "--doc"),
118
+ "cargo",
119
+ 45,
120
+ nothing_to_do=("no library targets found",),
121
+ ),
122
+ Check("doc", ("cargo", "doc", "--no-deps", "--all-features"), "cargo", 45),
123
+ Check("deny", ("cargo", "deny", "check"), "cargo-deny", 60, library_only=True),
124
+ Check(
125
+ "semver-checks",
126
+ ("cargo", "semver-checks"),
127
+ "cargo-semver-checks",
128
+ 240,
129
+ library_only=True,
130
+ ),
131
+ )
132
+
133
+ COVERAGE = (
134
+ # cargo-machete is deliberately absent: hygiene, not correctness, and not
135
+ # installed on a normal machine. A level that is red by default teaches
136
+ # people to ignore gates. Run it by hand when dependency drift is suspected.
137
+ # `mutants` is not here: a bare `cargo mutants` writes `mutants.out` at the tree
138
+ # root, tests the whole workspace and knows nothing of the lot. The `mutants`
139
+ # inspection below runs it in one fixed place, on the lot's diff, and is what a
140
+ # batch runs before its review. Two entry points would mean two procedures.
141
+ # Coverage would pass with red tests under --ignore-run-fail and never sees
142
+ # doctests: it is reported, refused as a verdict, and never blocks (R-074).
143
+ Check(
144
+ "llvm-cov",
145
+ ("cargo", "llvm-cov", "--ignore-run-fail"),
146
+ "cargo-llvm-cov",
147
+ 600,
148
+ skip="indicateur: la couverture ne prouve pas la justesse (R-074), jamais un verdict",
149
+ ),
150
+ )
151
+
152
+
153
+ @dataclass(frozen=True)
154
+ class Level:
155
+ name: str
156
+ budget: int # seconds the level promises to stay under
157
+ offline: bool
158
+ checks: tuple[Check, ...]
159
+
160
+
161
+ LEVELS = {
162
+ level.name: level
163
+ for level in (
164
+ Level("fast", 120, False, FAST),
165
+ Level("verify", 300, False, VERIFY),
166
+ )
167
+ }
168
+ # `coverage` is not a level on purpose: it is one indicator check that can never fail,
169
+ # so exposing it as a gate would be the fake green `campaign` used to be. It is reported
170
+ # inside `campaign`, after the campaign, and it never changes the verdict (R-074).
171
+
172
+
173
+ @dataclass
174
+ class Result:
175
+ check: Check
176
+ status: str
177
+ code: int | None
178
+ duration: float
179
+ note: str = ""
180
+
181
+
182
+ def fail(message: str, code: int = 1) -> int:
183
+ print(f"error: {message}", file=sys.stderr)
184
+ return code
185
+
186
+
187
+ def detect_profile(project: Path, forced: str | None) -> str:
188
+ """`Profile: <nom>` in the project's AGENTS.md, or `generic` when absent."""
189
+ if forced:
190
+ return forced
191
+ path = project / PROFILE_FILE
192
+ if path.is_file():
193
+ match = PROFILE_LINE.search(path.read_text(encoding="utf-8", errors="replace"))
194
+ if match:
195
+ return match.group(1)
196
+ return "generic"
197
+
198
+
199
+ def is_library(profile: str) -> bool:
200
+ """A profile is a library profile when its name says so."""
201
+ return "library" in profile.lower()
202
+
203
+
204
+ def skip_reason(check: Check, profile: str) -> str:
205
+ """Why a check does not run. Empty means it runs."""
206
+ if check.skip:
207
+ return check.skip
208
+ if check.library_only and not is_library(profile):
209
+ return f"réservé aux profils bibliothèque, profil courant {profile}"
210
+ return ""
211
+
212
+
213
+ COMPONENTS = {"cargo-fmt": "rustup component add rustfmt", "cargo-clippy": "rustup component add clippy"}
214
+
215
+
216
+ def install_hint(tool: str) -> str:
217
+ """How to get the tool, not just its name: two of them are rustup components."""
218
+ if tool in COMPONENTS:
219
+ return COMPONENTS[tool]
220
+ return f"cargo install {tool}" if tool.startswith("cargo-") else f"installer {tool}"
221
+
222
+
223
+ def execute(check: Check, project: Path, offline: bool, reason: str, remaining: float) -> Result:
224
+ if reason:
225
+ return Result(check, SKIP, None, 0.0, reason)
226
+ if shutil.which(check.tool) is None:
227
+ return Result(check, MISSING, None, 0.0, f"{check.tool} absent du PATH — {install_hint(check.tool)}")
228
+
229
+ if remaining <= 0:
230
+ return Result(check, FAIL, None, 0.0, "budget du niveau épuisé avant ce check")
231
+
232
+ env = dict(os.environ)
233
+ for key, value in check.env:
234
+ env[key] = value
235
+ if offline:
236
+ env["CARGO_NET_OFFLINE"] = "true"
237
+ # The level promises a duration; the per-check timeout is only an upper bound.
238
+ budget = min(check.timeout, remaining)
239
+ started = time.monotonic()
240
+ try:
241
+ # Popen, not run(): the handle is what lets the timeout kill the group.
242
+ # Killing cargo alone leaves its rustc children running.
243
+ proc = subprocess.Popen(
244
+ check.cmd,
245
+ cwd=project,
246
+ env=env,
247
+ stdin=subprocess.DEVNULL,
248
+ stdout=subprocess.PIPE,
249
+ stderr=subprocess.PIPE,
250
+ text=True,
251
+ encoding="utf-8",
252
+ errors="replace",
253
+ start_new_session=True,
254
+ )
255
+ except OSError as exc:
256
+ # The tool exists but could not run: that is a failure, not an absence,
257
+ # and --allow-missing must never acquit it.
258
+ return Result(check, FAIL, None, time.monotonic() - started, f"lancement impossible ({exc})")
259
+
260
+ try:
261
+ out, err = proc.communicate(timeout=budget)
262
+ except subprocess.TimeoutExpired:
263
+ with contextlib.suppress(OSError):
264
+ os.killpg(proc.pid, signal.SIGKILL)
265
+ with contextlib.suppress(subprocess.TimeoutExpired):
266
+ proc.communicate(timeout=5)
267
+ return Result(check, FAIL, None, time.monotonic() - started, f"timeout après {budget:.0f}s")
268
+
269
+ duration = time.monotonic() - started
270
+ if proc.returncode == 0:
271
+ return Result(check, OK, 0, duration)
272
+
273
+ combined = f"{out}\n{err}"
274
+ for fragment in check.nothing_to_do:
275
+ if fragment in combined:
276
+ # `code: null` on purpose: the step was skipped, nothing failed, and a
277
+ # consumer reading "code != 0 means failure" must not see 101 here.
278
+ return Result(check, SKIP, None, duration, f"rien à vérifier — {fragment} (cargo a rendu {proc.returncode})")
279
+ # The exit code alone does not say what broke, and a gate an agent must re-run
280
+ # to understand is a gate twice paid. Keep the tail of the real output.
281
+ tail = (err or out or "").strip().splitlines()
282
+ note = f"code {proc.returncode}"
283
+ if tail:
284
+ note += " — " + " | ".join(tail[-3:])[:300]
285
+ return Result(check, FAIL, proc.returncode, duration, note)
286
+
287
+
288
+ def run_level(level: Level, project: Path, profile: str) -> list[Result]:
289
+ results = []
290
+ elapsed = 0.0
291
+ for check in level.checks:
292
+ result = execute(check, project, level.offline, skip_reason(check, profile), level.budget - elapsed)
293
+ results.append(result)
294
+ elapsed += result.duration
295
+ return results
296
+
297
+
298
+ def exit_code(results: list[Result], allow_missing: bool) -> int:
299
+ """The gate's single verdict: a failure, or a missing tool nobody waived."""
300
+ if any(result.status == FAIL for result in results):
301
+ return 1
302
+ if any(result.status == MISSING for result in results) and not allow_missing:
303
+ return 1
304
+ return 0
305
+
306
+
307
+ CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]")
308
+
309
+
310
+ def clean(text: str) -> str:
311
+ """Cargo output and an AGENTS.md are untrusted input for a terminal."""
312
+ return CONTROL.sub("?", text)
313
+
314
+
315
+ def line_for(result: Result) -> str:
316
+ line = f"{result.status:<7} {result.check.name} ({result.duration:.1f}s)"
317
+ return clean(f"{line} — {result.note}" if result.note else line)
318
+
319
+
320
+ def as_json(level: Level, results: list[Result]) -> list[dict]:
321
+ return [
322
+ {
323
+ "name": result.check.name,
324
+ "level": level.name,
325
+ "command": " ".join(result.check.cmd),
326
+ "code": result.code,
327
+ "status": result.status,
328
+ "duration": round(result.duration, 3),
329
+ "note": result.note,
330
+ }
331
+ for result in results
332
+ ]
333
+
334
+
335
+ def inspected(name: str, subject: str) -> Check:
336
+ """A rule that reads files instead of running a binary: no tool, no timeout."""
337
+ return Check(name, (subject,), "", 0)
338
+
339
+
340
+ def defect_note(defects: list[str]) -> str:
341
+ """Name what to fix: a gate an agent must re-run to understand is paid twice."""
342
+ shown = " | ".join(defects[:5])
343
+ more = f" (+{len(defects) - 5} autre(s))" if len(defects) > 5 else ""
344
+ return f"{len(defects)} défaut(s) — {shown}{more}"[:400]
345
+
346
+
347
+ def rule_result(name: str, subject: str, defects: list[str], duration: float) -> Result:
348
+ """A rule of our own reports code 1, the value a failing tool would report."""
349
+ if not defects:
350
+ return Result(inspected(name, subject), OK, 0, duration)
351
+ return Result(inspected(name, subject), FAIL, 1, duration, defect_note(defects))
352
+
353
+
354
+ def skipped(name: str, subject: str, note: str) -> Result:
355
+ """`code: null` on purpose: nothing was checked here, so nothing failed."""
356
+ return Result(inspected(name, subject), SKIP, None, 0.0, note)
357
+
358
+
359
+ def front_matter(text: str) -> dict[str, object] | None:
360
+ """The YAML block at the top of a document, read without a YAML library.
361
+
362
+ Only the shape this corpus uses is understood: `key: value` lines, and a list of
363
+ `- value` lines under a bare key. Anything else stays absent rather than guessed.
364
+ """
365
+ lines = text.splitlines()
366
+ if not lines or lines[0].strip() != "---":
367
+ return None
368
+ fields: dict[str, object] = {}
369
+ listing: list[str] | None = None
370
+ for line in lines[1:]:
371
+ stripped = line.strip()
372
+ if stripped == "---":
373
+ return fields
374
+ if not stripped or stripped.startswith("#"):
375
+ continue
376
+ if stripped.startswith("- ") and listing is not None:
377
+ listing.append(stripped[2:].strip())
378
+ continue
379
+ key, separator, value = stripped.partition(":")
380
+ if not separator:
381
+ continue
382
+ if value.strip():
383
+ fields[key.strip()] = value.strip()
384
+ listing = None
385
+ else:
386
+ listing = []
387
+ fields[key.strip()] = listing
388
+ # A header that never closes is not a header.
389
+ return None
390
+
391
+
392
+ def as_list(value: object) -> list[str]:
393
+ """A header field that may be one value or a list of them."""
394
+ if isinstance(value, list):
395
+ return [str(item) for item in value]
396
+ return [str(value)] if value else []
397
+
398
+
399
+ def prose(text: str) -> Iterator[tuple[int, str]]:
400
+ """Numbered lines outside fenced blocks: a link inside a sample is not a link."""
401
+ fenced = False
402
+ for number, line in enumerate(text.splitlines(), start=1):
403
+ if FENCE.match(line):
404
+ fenced = not fenced
405
+ continue
406
+ if not fenced:
407
+ yield number, line
408
+
409
+
410
+ def read_text(path: Path) -> str:
411
+ return path.read_text(encoding="utf-8", errors="replace")
412
+
413
+
414
+ def declared_type(fields: dict[str, object] | None) -> str:
415
+ """The `type` field of a header, normalised: `Journal` and `journal` are one type."""
416
+ return str((fields or {}).get("type") or "").strip().lower()
417
+
418
+
419
+ def is_journal(path: Path, parsed: dict[Path, dict[str, object] | None]) -> bool:
420
+ """Whether this document is a journal entry, which `sources` and `links` exempt."""
421
+ return declared_type(parsed[path]) == JOURNAL_TYPE
422
+
423
+
424
+ def is_transient(entry: str) -> bool:
425
+ """Whether a `sources` entry names `.scratch/`, the directory git ignores."""
426
+ return entry.removeprefix("./").startswith(SCRATCH_DIR + "/")
427
+
428
+
429
+ def header_defects(
430
+ project: Path, documents: list[Path], parsed: dict[Path, dict[str, object] | None]
431
+ ) -> list[str]:
432
+ """Every document declares the five fields, and `verifie_le` is a date.
433
+
434
+ Absent and empty are two defects: a missing field is a document that forgot it,
435
+ while `sources:` with nothing under it is a document that claims to be verifiable
436
+ and names nothing — the reader cannot check either one, but the repair differs.
437
+ """
438
+ defects = []
439
+ for path in documents:
440
+ shown = path.relative_to(project).as_posix()
441
+ fields = parsed[path]
442
+ if fields is None:
443
+ defects.append(f"{shown}: pas d'en-tête (--- … ---)")
444
+ continue
445
+ absent = [name for name in HEADER_FIELDS if name not in fields]
446
+ if absent:
447
+ defects.append(f"{shown}: champ(s) manquant(s) {', '.join(absent)}")
448
+ for name in HEADER_FIELDS:
449
+ if name in fields and not fields[name]:
450
+ defects.append(f"{shown}: {name} vide — un champ déclaré sans valeur ne se vérifie pas")
451
+ declared = fields.get("verifie_le")
452
+ if declared and not ISO_DATE.match(str(declared)):
453
+ defects.append(f"{shown}: verifie_le doit être AAAA-MM-JJ, trouvé {declared!r}")
454
+ return defects
455
+
456
+
457
+ def source_defects(
458
+ project: Path, documents: list[Path], parsed: dict[Path, dict[str, object] | None]
459
+ ) -> list[str]:
460
+ """Every path declared in `sources` exists: a path nobody can open is a claim.
461
+
462
+ Two exemptions, both about what the entry can be held to: a URL cannot be resolved
463
+ offline, and `.scratch/` is ignored by git, so a path under it is gone from every
464
+ checkout and from the register that cites it long before the document expires.
465
+ """
466
+ defects = []
467
+ for path in documents:
468
+ shown = path.relative_to(project).as_posix()
469
+ if is_journal(path, parsed):
470
+ continue
471
+ for entry in as_list((parsed[path] or {}).get("sources")):
472
+ if "://" in entry or is_transient(entry):
473
+ continue
474
+ if not (project / entry.removeprefix("./")).exists():
475
+ defects.append(f"{shown}: source absente {entry}")
476
+ return defects
477
+
478
+
479
+ def link_defects(
480
+ project: Path, documents: list[Path], parsed: dict[Path, dict[str, object] | None]
481
+ ) -> list[str]:
482
+ """A relative link that resolves nowhere is the same defect as a missing source.
483
+
484
+ A journal entry is exempt: its links name the `.scratch/` ticket the lot closed, so
485
+ the one document that records what happened would be red for having done it.
486
+ """
487
+ defects = []
488
+ for path in documents:
489
+ if is_journal(path, parsed):
490
+ continue
491
+ shown = path.relative_to(project).as_posix()
492
+ for _, line in prose(read_text(path)):
493
+ for target in LINK.findall(line):
494
+ if "://" in target or target.startswith(("#", "mailto:")):
495
+ continue
496
+ relative = target.split("#", 1)[0]
497
+ if relative and not (path.parent / relative).exists():
498
+ defects.append(f"{shown}: lien cassé {target}")
499
+ return defects
500
+
501
+
502
+ def backref_defects(project: Path, documents: list[Path]) -> list[str]:
503
+ """A section stays readable on its own: a back-reference is a broken promise."""
504
+ defects = []
505
+ for path in documents:
506
+ shown = path.relative_to(project).as_posix()
507
+ for number, line in prose(read_text(path)):
508
+ for match in BACKREF.finditer(line):
509
+ defects.append(f"{shown}:{number}: renvoi «{match.group(0)}» — un lien ou rien")
510
+ return defects
511
+
512
+
513
+ def block_defects(project: Path, documents: list[Path]) -> list[str]:
514
+ """A block over 15 lines expires with the next refactor: cite the symbol.
515
+
516
+ A fence that never closes is a defect at any length. It also makes every later
517
+ line of the document a sample, so `links` and `backrefs` stop seeing the rest of
518
+ the file — a fifteen-line slip would otherwise be a silent green.
519
+ """
520
+ defects = []
521
+ for path in documents:
522
+ shown = path.relative_to(project).as_posix()
523
+ fenced, start, length = False, 0, 0
524
+ for number, line in enumerate(read_text(path).splitlines(), start=1):
525
+ if not FENCE.match(line):
526
+ if fenced:
527
+ length += 1
528
+ continue
529
+ if fenced:
530
+ if length > MAX_BLOCK_LINES:
531
+ defects.append(f"{shown}:{start}: bloc de {length} lignes (max {MAX_BLOCK_LINES})")
532
+ fenced, start, length = False, 0, 0
533
+ else:
534
+ fenced, start, length = True, number + 1, 0
535
+ if fenced:
536
+ defects.append(
537
+ f"{shown}:{start}: bloc non fermé après {length} ligne(s) — ferme le bloc, "
538
+ "sinon la suite du document n'est plus vérifiée"
539
+ )
540
+ return defects
541
+
542
+
543
+ def last_commit_date(project: Path, relative: str) -> str:
544
+ """`git log -1 --format=%cs` for one path: the short committer date, or empty."""
545
+ try:
546
+ proc = subprocess.run(
547
+ ("git", "log", "-1", "--format=%cs", "--", relative),
548
+ cwd=project,
549
+ capture_output=True,
550
+ text=True,
551
+ encoding="utf-8",
552
+ errors="replace",
553
+ )
554
+ except OSError:
555
+ return ""
556
+ return proc.stdout.strip() if proc.returncode == 0 else ""
557
+
558
+
559
+ def is_repository(project: Path) -> bool:
560
+ """Whether the dates exist at all: no git, or no repository, is an absence."""
561
+ if shutil.which("git") is None:
562
+ return False
563
+ try:
564
+ proc = subprocess.run(
565
+ ("git", "rev-parse", "--is-inside-work-tree"),
566
+ cwd=project,
567
+ capture_output=True,
568
+ text=True,
569
+ encoding="utf-8",
570
+ errors="replace",
571
+ )
572
+ except OSError:
573
+ return False
574
+ return proc.returncode == 0 and proc.stdout.strip() == "true"
575
+
576
+
577
+ def freshness_result(
578
+ project: Path, documents: list[Path], parsed: dict[Path, dict[str, object] | None]
579
+ ) -> Result:
580
+ """A document older than a file it cites describes the previous state.
581
+
582
+ Never red without evidence of a date: no git, or a project that is not a
583
+ repository, means the cross-check does not apply here. That is a SKIP.
584
+ """
585
+ subject = CORPUS_SUBJECT
586
+ if shutil.which("git") is None:
587
+ return skipped("freshness", subject, "git absent du PATH — fraîcheur non croisée")
588
+ if not is_repository(project):
589
+ return skipped("freshness", subject, "pas un dépôt git — fraîcheur non croisée")
590
+
591
+ started = time.monotonic()
592
+ defects = []
593
+ for path in documents:
594
+ shown = path.relative_to(project).as_posix()
595
+ fields = parsed[path] or {}
596
+ declared = str(fields.get("verifie_le") or "")
597
+ if not ISO_DATE.match(declared):
598
+ # Already reported by `headers`; a missing date is not a stale document.
599
+ continue
600
+ if declared_type(fields) == JOURNAL_TYPE:
601
+ continue
602
+ for entry in as_list(fields.get("sources")):
603
+ if "://" in entry or is_transient(entry):
604
+ continue
605
+ written = last_commit_date(project, entry.removeprefix("./"))
606
+ if written and written > declared:
607
+ defects.append(f"{shown}: {entry} modifié le {written}, après verifie_le {declared}")
608
+ return rule_result("freshness", subject, defects, time.monotonic() - started)
609
+
610
+
611
+ def corpus_documents(project: Path) -> list[Path]:
612
+ """Every Markdown file of every corpus that exists, each corpus read in order."""
613
+ documents: list[Path] = []
614
+ for relative in CORPUS_DIRS:
615
+ corpus = project / relative
616
+ if corpus.is_dir():
617
+ documents.extend(sorted(path for path in corpus.rglob("*.md") if path.is_file()))
618
+ return documents
619
+
620
+
621
+ def docs_results(project: Path) -> list[Result]:
622
+ """The rules of both corpora, one result each, or one SKIP without either.
623
+
624
+ `documentation/changelog/` is scanned with `documentation/llm/`: the journal is
625
+ the corpus every later reader trusts most, and a defect there was verified by
626
+ nothing. A project with neither directory is not at fault: the gate skips with
627
+ `code: null`, so a consumer reading "code != 0 means failure" never sees a
628
+ failure here.
629
+ """
630
+ subject = CORPUS_SUBJECT
631
+ present = [relative for relative in CORPUS_DIRS if (project / relative).is_dir()]
632
+ if not present:
633
+ return [
634
+ skipped(
635
+ "corpus",
636
+ subject,
637
+ f"{' et '.join(relative.as_posix() + '/' for relative in CORPUS_DIRS)} absents "
638
+ "— un projet sans corpus n'est pas fautif",
639
+ )
640
+ ]
641
+ documents = corpus_documents(project)
642
+ if not documents:
643
+ return [
644
+ skipped(
645
+ "corpus",
646
+ subject,
647
+ f"aucun document dans {' et '.join(relative.as_posix() + '/' for relative in present)} "
648
+ "— rien à vérifier",
649
+ )
650
+ ]
651
+
652
+ parsed = {path: front_matter(read_text(path)) for path in documents}
653
+ rules: list[tuple[str, Callable[[], list[str]]]] = [
654
+ ("headers", lambda: header_defects(project, documents, parsed)),
655
+ ("sources", lambda: source_defects(project, documents, parsed)),
656
+ ("links", lambda: link_defects(project, documents, parsed)),
657
+ ("backrefs", lambda: backref_defects(project, documents)),
658
+ ("blocks", lambda: block_defects(project, documents)),
659
+ ]
660
+ results = []
661
+ for name, rule in rules:
662
+ started = time.monotonic()
663
+ defects = rule()
664
+ results.append(rule_result(name, subject, defects, time.monotonic() - started))
665
+ results.append(freshness_result(project, documents, parsed))
666
+ return results
667
+
668
+
669
+ def deps_results(project: Path) -> list[Result]:
670
+ """One official skill per technology used, and no Lathe skill installed globally.
671
+
672
+ Without a Cargo.toml there is nothing to deduce: SKIP with `code: null`, because
673
+ a project that is not Rust owes nothing to this gate.
674
+ """
675
+ manifest = project / "Cargo.toml"
676
+ if not manifest.is_file():
677
+ return [skipped("manifest", "Cargo.toml", "aucun Cargo.toml — aucune technologie à déduire")]
678
+
679
+ results = []
680
+ started = time.monotonic()
681
+ global_lathe = framework.global_lathe_skills()
682
+ global_defects = [
683
+ f"{name} installé en global dans {framework.global_skills()} — un skill sert un projet, pas la machine"
684
+ for name in global_lathe
685
+ ]
686
+ results.append(
687
+ rule_result("global", framework.global_skills().as_posix(), global_defects, time.monotonic() - started)
688
+ )
689
+
690
+ started = time.monotonic()
691
+ installed = project / ".agents" / "skills"
692
+ needed = framework.detected_technologies(project)
693
+ absent = [
694
+ f"{skill} absent (pour {technology}) — installe la compétence officielle dans {installed}"
695
+ for technology, skill in sorted(needed.items())
696
+ if not (installed / skill / "SKILL.md").is_file()
697
+ ]
698
+ results.append(rule_result("technologies", manifest.as_posix(), absent, time.monotonic() - started))
699
+ return results
700
+
701
+
702
+ # --- the mutation campaign -------------------------------------------------------
703
+ # One canonical place, because an agent that has to guess where the report is will
704
+ # guess wrong, and a campaign nobody reads is ten minutes bought for nothing.
705
+ LATHE_STATE = Path(".lathe")
706
+ MUTANTS_ROOT = LATHE_STATE / "mutants"
707
+ MUTANTS_OUT = MUTANTS_ROOT / "mutants.out"
708
+ MUTANTS_DIFF = MUTANTS_ROOT / "lot.diff"
709
+ MUTANTS_BASE = MUTANTS_ROOT / "base"
710
+ MUTANTS_JUSTIFIED = LATHE_STATE / "justified.txt"
711
+ # A green campaign certifies one commit range. Lathe reads this file instead of
712
+ # re-running thirty minutes of mutation testing to learn the same thing, and a new
713
+ # commit invalidates it by construction.
714
+ MUTANTS_VERDICT = LATHE_STATE / "mutants" / "verdict"
715
+ OUTCOMES = ("caught", "missed", "timeout", "unviable")
716
+
717
+ # Filled by main(): the inspection signature is `Path -> results`, and these are the
718
+ # four numbers only the command line knows. Typed rather than a loose dict, so the
719
+ # campaign reads ints and the checker does not have to guess.
720
+ @dataclass
721
+ class MutantOptions:
722
+ base: str = ""
723
+ jobs: int = 2
724
+ timeout: int = 120
725
+ budget: int = 3600
726
+
727
+
728
+ MUTANT_OPTIONS = MutantOptions()
729
+
730
+
731
+ def git_text(project: Path, args: tuple[str, ...]) -> tuple[int, str]:
732
+ """git's stdout and status. A broken git is a failure, never a silent green."""
733
+ try:
734
+ proc = subprocess.run(
735
+ ("git", *args),
736
+ cwd=project,
737
+ stdin=subprocess.DEVNULL,
738
+ stdout=subprocess.PIPE,
739
+ stderr=subprocess.DEVNULL,
740
+ text=True,
741
+ encoding="utf-8",
742
+ errors="replace",
743
+ timeout=120,
744
+ )
745
+ except (OSError, subprocess.SubprocessError):
746
+ return -1, ""
747
+ return proc.returncode, proc.stdout
748
+
749
+
750
+ def lines_of(path: Path) -> list[str]:
751
+ """The non-empty lines of a file, or nothing when it does not exist."""
752
+ if not path.is_file():
753
+ return []
754
+ return [line.strip() for line in read_text(path).splitlines() if line.strip()]
755
+
756
+
757
+ def ignored_defects(project: Path) -> list[str]:
758
+ """An output directory git can see is a directory that ends up in a commit."""
759
+ code, _ = git_text(project, ("check-ignore", "-q", (MUTANTS_OUT / "probe").as_posix()))
760
+ if code == 0:
761
+ return []
762
+ return [f"{MUTANTS_ROOT.as_posix()}/ n'est pas ignoré — `gates.py mutants --start` écrit la ligne une fois"]
763
+
764
+
765
+ def clean_defects(project: Path) -> list[str]:
766
+ """Results must belong to a state anyone can check out again."""
767
+ code, out = git_text(project, ("status", "--porcelain", "--untracked-files=no"))
768
+ if code != 0:
769
+ return ["git status a échoué"]
770
+ dirty = [line[3:] for line in out.splitlines() if line.strip()]
771
+ if not dirty:
772
+ return []
773
+ shown = ", ".join(dirty[:5])
774
+ more = f" (+{len(dirty) - 5})" if len(dirty) > 5 else ""
775
+ return [f"{len(dirty)} fichier(s) modifié(s) — commite avant de mesurer: {shown}{more}"]
776
+
777
+
778
+ TEST_TREES = ("tests/", "benches/")
779
+
780
+
781
+ def production_paths(diff: str) -> list[str]:
782
+ """The production `.rs` files a diff touches, relative to the manifest.
783
+
784
+ A diff that only moves tests or docs legitimately produces no mutant: `--in-diff`
785
+ matches code under test, not test code. Only production files make an empty
786
+ campaign suspicious.
787
+ """
788
+ paths = []
789
+ for line in diff.splitlines():
790
+ if not line.startswith("+++ "):
791
+ continue
792
+ path = line[4:].strip()
793
+ if path.startswith("b/"):
794
+ path = path[2:]
795
+ if path == "/dev/null" or not path.endswith(".rs"):
796
+ continue
797
+ if path.startswith(TEST_TREES) or path.rsplit("/", 1)[-1].endswith("_test.rs"):
798
+ continue
799
+ paths.append(path)
800
+ return paths
801
+
802
+
803
+ def resolved_base(project: Path) -> str:
804
+ """The commit the lot started from: the flag wins, then the record on disk."""
805
+ forced = MUTANT_OPTIONS.base.strip()
806
+ if forced:
807
+ return forced
808
+ recorded = lines_of(project / MUTANTS_BASE)
809
+ return recorded[0] if recorded else ""
810
+
811
+
812
+ def base_defects(project: Path) -> list[str]:
813
+ base = resolved_base(project)
814
+ if not base:
815
+ return [
816
+ f"aucune base de lot — `gates.py mutants --start` avant le premier ticket, "
817
+ f"ou `--base <révision>` (le fichier {MUTANTS_BASE.as_posix()} est vide)"
818
+ ]
819
+ code, out = git_text(project, ("rev-parse", "--verify", base + "^{commit}"))
820
+ if code != 0:
821
+ return [f"{base} n'est pas une révision de ce dépôt"]
822
+ return []
823
+
824
+
825
+ def justified_entries(project: Path) -> list[str]:
826
+ """Survivors the lot accepted in writing: a prefix of the line, or any substring."""
827
+ return [
828
+ line
829
+ for line in lines_of(project / MUTANTS_JUSTIFIED)
830
+ if not line.startswith("#")
831
+ ]
832
+
833
+
834
+ def certified(project: Path, base: str, subject: str, duration: float, note: str) -> Result:
835
+ """Write the verdict Lathe reads, then report the green."""
836
+ code, head = git_text(project, ("rev-parse", "HEAD"))
837
+ head = head.strip() if code == 0 else ""
838
+ verdict = project / MUTANTS_VERDICT
839
+ verdict.parent.mkdir(parents=True, exist_ok=True)
840
+ verdict.write_text(f"{base} {head}\n", encoding="utf-8")
841
+ return Result(inspected("campaign", subject), OK, 0, duration, note)
842
+
843
+
844
+ def survivor_lines(project: Path) -> list[str]:
845
+ return lines_of(project / MUTANTS_OUT / "missed.txt")
846
+
847
+
848
+ def outcome_counts(project: Path) -> dict[str, int]:
849
+ return {name: len(lines_of(project / MUTANTS_OUT / f"{name}.txt")) for name in OUTCOMES}
850
+
851
+
852
+ def run_campaign(project: Path) -> Result:
853
+ """One invocation, one fixed output directory, and a verdict read from the files."""
854
+ subject = MUTANTS_OUT.as_posix()
855
+ started = time.monotonic()
856
+ base = resolved_base(project)
857
+ # `--relative` because cargo-mutants matches diff paths against the manifest it
858
+ # runs from. A root-relative diff yields "No mutants to filter" and exit 0: the
859
+ # worst possible green, one that looks like a clean campaign.
860
+ code, diff = git_text(project, ("diff", "--relative", "--no-color", f"{base}...HEAD", "--", "."))
861
+ if code != 0:
862
+ return Result(inspected("campaign", subject), FAIL, code, time.monotonic() - started,
863
+ f"git diff a échoué (code {code})")
864
+ diff_path = project / MUTANTS_DIFF
865
+ diff_path.parent.mkdir(parents=True, exist_ok=True)
866
+ diff_path.write_text(diff, encoding="utf-8")
867
+ touched = sum(1 for line in diff.splitlines() if line.startswith("+++ "))
868
+ if not touched:
869
+ return Result(inspected("campaign", subject), SKIP, None, time.monotonic() - started,
870
+ f"le lot n'a modifié aucun fichier depuis {base} — rien à muter")
871
+ production = production_paths(diff)
872
+ if not production:
873
+ return Result(inspected("campaign", subject), SKIP, None, time.monotonic() - started,
874
+ f"{touched} fichier(s) modifiés, aucun Rust de production — "
875
+ "les tests ne se mutent pas")
876
+
877
+ cmd = (
878
+ "cargo", "mutants",
879
+ "-D", MUTANTS_DIFF.as_posix(),
880
+ "-o", MUTANTS_ROOT.as_posix(),
881
+ "--no-times",
882
+ "--baseline", "run",
883
+ "--timeout", str(MUTANT_OPTIONS.timeout),
884
+ "-j", str(MUTANT_OPTIONS.jobs),
885
+ )
886
+ budget = MUTANT_OPTIONS.budget
887
+ try:
888
+ proc = subprocess.Popen(
889
+ cmd, cwd=project, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
890
+ stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace",
891
+ start_new_session=True,
892
+ )
893
+ except OSError as exc:
894
+ return Result(inspected("campaign", subject), FAIL, None, time.monotonic() - started,
895
+ f"lancement impossible ({exc})")
896
+ try:
897
+ output, _ = proc.communicate(timeout=budget)
898
+ except subprocess.TimeoutExpired:
899
+ with contextlib.suppress(OSError):
900
+ os.killpg(proc.pid, signal.SIGKILL)
901
+ with contextlib.suppress(subprocess.TimeoutExpired):
902
+ proc.communicate(timeout=5)
903
+ return Result(inspected("campaign", subject), FAIL, None, time.monotonic() - started,
904
+ f"campagne interrompue après {budget:.0f}s — budget du niveau")
905
+
906
+ duration = time.monotonic() - started
907
+ counts = outcome_counts(project)
908
+ tested = sum(counts.values())
909
+ detail = ", ".join(f"{count} {name}" for name, count in counts.items() if count)
910
+
911
+ if proc.returncode == 3:
912
+ return Result(inspected("campaign", subject), FAIL, 3, duration,
913
+ f"{counts['timeout']} mutant(s) ont dépassé {MUTANT_OPTIONS.timeout}s — "
914
+ "un mutant qui pend n'est ni tué ni survivant: augmente --mutant-timeout, "
915
+ "ou marque le code lent #[mutants::skip]")
916
+ if proc.returncode == 4:
917
+ return Result(inspected("campaign", subject), FAIL, 4, duration,
918
+ "les tests échouent sur l'arbre non muté — la suite est rouge avant toute mutation")
919
+ if proc.returncode == 5:
920
+ return Result(inspected("campaign", subject), FAIL, 5, duration,
921
+ "le diff ne correspond plus à l'arbre — relance depuis un arbre propre")
922
+ if proc.returncode == 6:
923
+ return Result(inspected("campaign", subject), FAIL, 6, duration,
924
+ "le fichier de diff n'est pas un diff valide")
925
+
926
+ if tested == 0:
927
+ # Measured: a diff whose paths do not match the manifest makes cargo-mutants
928
+ # print "No mutants to filter" and exit 0. Green here would certify nothing.
929
+ return Result(inspected("campaign", subject), FAIL, proc.returncode, duration,
930
+ f"{len(production)} fichier(s) Rust de production dans le diff mais aucun "
931
+ f"mutant généré — chemins du diff, exclude_globs ou #[mutants::skip]: "
932
+ f"{', '.join(production[:5])}")
933
+
934
+ if proc.returncode == 0:
935
+ return certified(project, base, subject, duration, detail)
936
+
937
+ if proc.returncode == 2: # measured on v27.1.0: 2 means missed mutants
938
+ justified = justified_entries(project)
939
+ open_survivors = [
940
+ line for line in survivor_lines(project)
941
+ if not any(line.startswith(entry) or entry in line for entry in justified)
942
+ ]
943
+ if not open_survivors:
944
+ return certified(project, base, subject, duration,
945
+ f"{detail} — tous justifiés dans {MUTANTS_JUSTIFIED.as_posix()}")
946
+ return Result(inspected("campaign", subject), FAIL, 2, duration,
947
+ defect_note([f"{line}" for line in open_survivors]))
948
+
949
+ tail = output.strip().splitlines()
950
+ note = f"code {proc.returncode}"
951
+ if tail:
952
+ note += " — " + " | ".join(tail[-3:])[:300]
953
+ return Result(inspected("campaign", subject), FAIL, proc.returncode, duration, note)
954
+
955
+
956
+ def record_base(project: Path) -> int:
957
+ """`--start`: the lot's base commit, and the ignore line, written once."""
958
+ code, out = git_text(project, ("rev-parse", "HEAD"))
959
+ if code != 0 or not out.strip():
960
+ return fail("hors dépôt git: aucun commit de départ à enregistrer", 2)
961
+ base = out.strip()
962
+ target = project / MUTANTS_BASE
963
+ target.parent.mkdir(parents=True, exist_ok=True)
964
+ target.write_text(base + "\n", encoding="utf-8")
965
+ ignore = project / LATHE_STATE / ".gitignore"
966
+ line = "mutants/\n"
967
+ if not ignore.is_file():
968
+ ignore.write_text(line, encoding="utf-8")
969
+ elif line.strip() not in read_text(ignore).split():
970
+ with ignore.open("a", encoding="utf-8") as handle:
971
+ handle.write(line)
972
+ print(f"base du lot: {base} — sortie: {MUTANTS_OUT.as_posix()}/")
973
+ return 0
974
+
975
+
976
+ def mutants_results(project: Path) -> list[Result]:
977
+ """Preconditions first, then the one campaign. A red precondition costs nothing.
978
+
979
+ Thirty minutes of mutation testing on a dirty tree produces a report nobody can
980
+ reproduce, and `--in-place` is the one flag that can edit the source itself: both
981
+ are refused before a single mutant is generated.
982
+ """
983
+ if not (project / "Cargo.toml").is_file():
984
+ return [skipped("manifest", "Cargo.toml", "aucun Cargo.toml — aucun code Rust à muter")]
985
+ code, _ = git_text(project, ("rev-parse", "--git-dir"))
986
+ if code != 0:
987
+ return [Result(inspected("repository", "git"), FAIL, 1, 0.0,
988
+ "hors dépôt git — une campagne se mesure contre un commit, donc rien ne peut être certifié")]
989
+ if shutil.which("cargo-mutants") is None:
990
+ return [Result(inspected("tool", "cargo-mutants"), MISSING, None, 0.0,
991
+ "cargo-mutants absent du PATH — cargo install cargo-mutants")]
992
+
993
+ results = []
994
+ for name, rule in (
995
+ ("ignored", ignored_defects),
996
+ ("clean", clean_defects),
997
+ ("base", base_defects),
998
+ ):
999
+ started = time.monotonic()
1000
+ defects = rule(project)
1001
+ results.append(rule_result(name, "campagne", defects, time.monotonic() - started))
1002
+ if any(result.status == FAIL for result in results):
1003
+ results.append(skipped("campaign", MUTANTS_OUT.as_posix(),
1004
+ "préconditions rouges — la campagne n'a pas été lancée"))
1005
+ return results
1006
+ results.append(run_campaign(project))
1007
+ return results
1008
+
1009
+
1010
+ def campaign_results(project: Path) -> list[Result]:
1011
+ """The batch-end gate: the campaign, and coverage reported beside it.
1012
+
1013
+ `campaign` used to be `llvm-cov` alone, which is a permanent SKIP: the level
1014
+ printed `0 OK · 1 SKIP` and `VERDICT: tout vert`, exit 0. A level that cannot
1015
+ fail is not a gate (the defect `D-44` already fixed for mutation). It now runs
1016
+ the same inspection as `mutants` — one procedure, two names — and coverage is
1017
+ reported after it, never as a verdict (R-074).
1018
+ """
1019
+ results = mutants_results(project)
1020
+ coverage = run_level(Level("coverage", 900, True, COVERAGE), project, detect_profile(project, None))
1021
+ return results + coverage
1022
+
1023
+
1024
+ # Project-level inspections: they inspect files, so they declare their own level with
1025
+ # no check inside it — the level supplies a name and a budget to the same report.
1026
+ INSPECTIONS: dict[str, tuple[Level, Callable[[Path], list[Result]]]] = {
1027
+ "docs": (Level("docs", 60, True, ()), docs_results),
1028
+ "deps": (Level("deps", 30, True, ()), deps_results),
1029
+ "mutants": (Level("mutants", 3600, True, ()), mutants_results),
1030
+ "campaign": (Level("campaign", 3600, True, ()), campaign_results),
1031
+ }
1032
+
1033
+
1034
+ def summarise(level: Level, project: Path, profile: str, results: list[Result], allow_missing: bool) -> int:
1035
+ """Print the report and return the gate exit code."""
1036
+ total = sum(result.duration for result in results)
1037
+ # The profile comes from the project's AGENTS.md, which is untrusted input for a
1038
+ # terminal like any other; an escape sequence in it must not reach the screen.
1039
+ print(clean(f"gate {level.name} — projet {project} — profil {profile}"))
1040
+ for result in results:
1041
+ print(line_for(result))
1042
+
1043
+ count = {status: sum(1 for r in results if r.status == status) for status in (OK, FAIL, MISSING, SKIP)}
1044
+ print(
1045
+ f"{len(results)} checks · {count[OK]} OK · {count[FAIL]} FAIL · "
1046
+ f"{count[MISSING]} MISSING · {count[SKIP]} SKIP · {total:.1f}s / budget {level.budget}s"
1047
+ )
1048
+
1049
+ failures = [result.check.name for result in results if result.status == FAIL]
1050
+ missing = [result.check.name for result in results if result.status == MISSING]
1051
+ waived = missing if allow_missing else []
1052
+ blocking = missing if not allow_missing else []
1053
+
1054
+ parts = []
1055
+ if failures:
1056
+ parts.append(f"échec — {', '.join(failures)}")
1057
+ if blocking:
1058
+ parts.append(f"outil requis manquant: {', '.join(blocking)} (--allow-missing pour passer outre)")
1059
+ if parts:
1060
+ verdict = "VERDICT: " + " · ".join(parts)
1061
+ elif count[OK] == 0:
1062
+ # Every check skipped: nothing ran, so nothing is green. Saying `tout vert` here
1063
+ # would certify a level that proved nothing — the defect `campaign` had.
1064
+ verdict = (
1065
+ f"VERDICT: rien vérifié — {count[SKIP]} contrôle(s) SKIP, "
1066
+ "0 exécuté : ce niveau ne prouve rien sur ce projet"
1067
+ )
1068
+ elif waived:
1069
+ verdict = "VERDICT: vert sous réserve — outil(s) manquant(s) acquitté(s): " + ", ".join(waived)
1070
+ else:
1071
+ verdict = "VERDICT: tout vert"
1072
+ print(clean(verdict))
1073
+ return exit_code(results, allow_missing)
1074
+
1075
+
1076
+ def main(argv: list[str]) -> int:
1077
+ parser = argparse.ArgumentParser(
1078
+ prog="gates.py",
1079
+ description="Run one gate level; exit 0 only when every check is green.",
1080
+ )
1081
+ parser.add_argument(
1082
+ "level",
1083
+ choices=sorted([*LEVELS, *INSPECTIONS]),
1084
+ help="fast, verify, campaign, docs, deps or mutants",
1085
+ )
1086
+ parser.add_argument("--project", default=".", type=Path, help="project directory (default: .)")
1087
+ parser.add_argument("--profile", help="force the profile instead of reading `Profile:` in AGENTS.md")
1088
+ parser.add_argument("--allow-missing", action="store_true", help="a missing tool warns instead of failing")
1089
+ parser.add_argument(
1090
+ "--json",
1091
+ action="store_true",
1092
+ help="a JSON array of per-check objects, nothing else on stdout",
1093
+ )
1094
+ mutants = parser.add_argument_group("mutants", "only meaningful with the `mutants` level")
1095
+ mutants.add_argument("--start", action="store_true", help="record this commit as the lot's base")
1096
+ mutants.add_argument("--base", default="", help="base revision, instead of the recorded one")
1097
+ mutants.add_argument("--jobs", type=int, default=2, help="parallel cargo jobs (default: 2)")
1098
+ mutants.add_argument("--mutant-timeout", type=int, default=120, help="per-mutant timeout in seconds")
1099
+ mutants.add_argument("--budget", type=int, default=3600, help="whole campaign budget in seconds")
1100
+ args = parser.parse_args(argv)
1101
+
1102
+ if not args.project.is_dir():
1103
+ return fail(f"{args.project} n'est pas un répertoire", 2)
1104
+
1105
+ if args.start:
1106
+ return record_base(args.project)
1107
+ MUTANT_OPTIONS.base = args.base
1108
+ MUTANT_OPTIONS.jobs = args.jobs
1109
+ MUTANT_OPTIONS.timeout = args.mutant_timeout
1110
+ MUTANT_OPTIONS.budget = args.budget
1111
+
1112
+ profile = detect_profile(args.project, args.profile)
1113
+ if args.level in INSPECTIONS:
1114
+ level, inspect_project = INSPECTIONS[args.level]
1115
+ results = inspect_project(args.project)
1116
+ else:
1117
+ # cargo walks up to find the manifest; so do we, so the message is ours and not
1118
+ # three identical "could not find Cargo.toml" failures.
1119
+ probe = args.project.resolve()
1120
+ while probe != probe.parent and not (probe / "Cargo.toml").is_file():
1121
+ probe = probe.parent
1122
+ if not (probe / "Cargo.toml").is_file():
1123
+ return fail(f"aucun Cargo.toml dans {args.project} ni dans ses ancêtres", 2)
1124
+ level = LEVELS[args.level]
1125
+ results = run_level(level, args.project, profile)
1126
+
1127
+ if args.json:
1128
+ print(json.dumps(as_json(level, results), ensure_ascii=False, indent=2))
1129
+ return exit_code(results, args.allow_missing)
1130
+ return summarise(level, args.project, profile, results, args.allow_missing)
1131
+
1132
+
1133
+ if __name__ == "__main__":
1134
+ sys.exit(main(sys.argv[1:]))