create-lathe 0.0.0-stage → 0.4.1

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