Tous les chapitres

QualitéChapitre 14 · 11 min de lecture

La garde du diff

Un script qui lit la modification proposée et rejette les raccourcis classiques avant même que les tests tournent.

Ce qu'elle cherche

Les contrôles des chapitres précédents vérifient l'état du code. La garde vérifie le changement : elle compare la branche à sa base et cherche ce qu'un agent fait quand il veut que ce soit vert :

Dans le diffPourquoi c'est rejeté
Un fichier protégé modifié, déplacé ou copiéL'agent change les règles qui le jugent
eslint-disable, @ts-ignore, @ts-expect-error, as any, as never, <any>, as unknown as ajoutésIl fait taire un contrôle
.skip, .only, .todo, xit ajoutésIl désactive des tests
Un fichier de test suppriméIl retire une preuve
Plus d'assertions expect( retirées qu'ajoutées dans un fichier de testIl affaiblit une preuve

Le script

scripts/guard-diff.mjs
/**
 * Guard against the shortcuts an agent takes to turn a red check green.
 * It reads a git diff and fails when the change:
 *   - touches a protected file (CI, hooks, agent settings, lint/test config, specs, dependencies),
 *   - adds a way to silence a check (eslint-disable, @ts-ignore, `as any`, a skipped or focused test),
 *   - deletes a test file or removes more assertions than it adds.
 *
 *   node scripts/guard-diff.mjs                 working tree against HEAD
 *   node scripts/guard-diff.mjs --staged        staged changes only (pre-commit hook)
 *   node scripts/guard-diff.mjs --base origin/main   a branch against its base (CI)
 *
 * A human who has reviewed the change sets ALLOW_PROTECTED=1 (in CI, from a label only humans can add).
 * This script is a fast first signal. The real lock is CODEOWNERS plus branch protection (see the guide).
 */
import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";

/** Paths an agent must not change on its own. A trailing "/" protects a whole folder. */
export const PROTECTED = [
  ".git/",
  ".github/",
  ".claude/",
  ".githooks/",
  "AGENTS.md",
  "CLAUDE.md",
  "specs/",
  "scripts/guard-diff.mjs",
  "test/guard-diff.test.ts",
  "eslint.config.mjs",
  "tsconfig.json",
  "vitest.config.ts",
  "stryker.config.json",
  "package.json",
  "package-lock.json",
  ".npmrc",
];

/** Added code that switches a check off. */
const SILENCERS = [
  { re: /eslint-disable/, why: "silences a lint rule" },
  { re: /@ts-(ignore|nocheck|expect-error)/, why: "silences the type checker" },
  { re: /<any>|\bas\s+never\b/, why: "casts away the type" },
  { re: /\bas\s+any\b/, why: "casts to any" },
  { re: /\bas\s+unknown\s+as\b/, why: "forces a type through unknown" },
  { re: /\b(it|test|describe)\.(skip|only|todo)\b/, why: "skips or focuses tests" },
  { re: /\bx(it|describe)\(/, why: "skips tests" },
];

/** @param {string} file */
const isTest = (file) => /^test\/|\.test\.ts$/.test(file);
/**
 * @param {string} file project-relative path with "/" separators
 * @param {boolean} [ignoreCase] true on case-insensitive file systems (macOS, Windows)
 */
export function isProtected(file, ignoreCase = false) {
  const f = ignoreCase ? file.toLowerCase() : file;
  return PROTECTED.some((entry) => {
    const p = ignoreCase ? entry.toLowerCase() : entry;
    return p.endsWith("/") ? f.startsWith(p) : f === p;
  });
}

/**
 * @param {string} diff output of `git diff` (unified format)
 * @returns {Array<{ file: string; reason: string; line?: string }>}
 */
export function findViolations(diff) {
  /** @type {Array<{ file: string; reason: string; line?: string }>} */
  const violations = [];
  /** @type {Map<string, number>} net number of `expect(` per test file */
  const assertions = new Map();
  let file = "";

  for (const line of diff.split("\n")) {
    const header = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
    if (header) {
      // Check both sides: moving a protected file away is a change to it too.
      file = header[2] ?? "";
      const from = header[1] ?? "";
      if (isProtected(file) || isProtected(from)) violations.push({ file, reason: "protected file changed" });
      continue;
    }
    const moved = line.match(/^(?:rename|copy) (?:from|to) (.+)$/);
    if (moved && isProtected(moved[1] ?? "") && !isProtected(file)) {
      violations.push({ file: moved[1] ?? "", reason: "protected file renamed or copied" });
      continue;
    }
    if (line.startsWith("deleted file mode") && isTest(file)) {
      violations.push({ file, reason: "test file deleted" });
      continue;
    }
    if (line.startsWith("+++") || line.startsWith("---") || isProtected(file)) continue;

    const added = line.startsWith("+");
    const removed = line.startsWith("-");
    if (!added && !removed) continue;
    const code = line.slice(1);

    if (added) {
      for (const { re, why } of SILENCERS) {
        if (re.test(code)) violations.push({ file, reason: why, line: code.trim() });
      }
    }
    if (isTest(file)) {
      const count = (code.match(/\bexpect\(/g) ?? []).length;
      assertions.set(file, (assertions.get(file) ?? 0) + (added ? count : -count));
    }
  }

  for (const [testFile, net] of assertions) {
    if (net < 0) violations.push({ file: testFile, reason: `${String(-net)} assertion(s) removed` });
  }
  return violations;
}

function main() {
  const args = process.argv.slice(2);
  const baseIndex = args.indexOf("--base");
  const gitArgs = ["diff", "--no-color", "--no-ext-diff", "--no-renames"];
  if (args.includes("--staged")) gitArgs.push("--cached");
  else if (baseIndex !== -1) gitArgs.push(`${args[baseIndex + 1] ?? "origin/main"}...HEAD`);
  else gitArgs.push("HEAD");

  const diff = execFileSync("git", gitArgs, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
  const violations = findViolations(diff);
  if (violations.length === 0) {
    console.log("guard: no protected file, silenced check or weakened test in this diff");
    return;
  }

  for (const v of violations) console.error(`guard: ${v.file}: ${v.reason}${v.line ? `\n         ${v.line}` : ""}`);
  if (process.env.ALLOW_PROTECTED === "1") {
    console.warn("guard: ALLOW_PROTECTED=1, a human approved these changes");
    return;
  }
  console.error("guard: blocked. Fix the code instead, or ask a human to review and approve this change.");
  process.exit(1);
}

if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) main();

Trois modes, selon où il tourne :

  • node scripts/guard-diff.mjs : la copie de travail contre le dernier commit (hook d'arrêt de l'agent).
  • --staged : ce qui va être committé (hook pre-commit).
  • --base origin/main : la branche contre sa base (CI).

L'approbation humaine

Parfois, un changement protégé est légitime : une nouvelle règle de lint, une dépendance que tu as décidé d'ajouter. La garde accepte alors la variable ALLOW_PROTECTED=1. En CI, elle vient d'un label, human-approved, que tu poses après avoir lu les fichiers protégés modifiés :

YAML
env:
  ALLOW_PROTECTED: ${{ contains(github.event.pull_request.labels.*.name, 'human-approved') && '1' || '0' }}

Le hook Bash bloque ALLOW_PROTECTED= dans les commandes de l'agent, et l'agent ne doit pas pouvoir poser de label (ch. 10).

Elle a ses propres tests

test/guard-diff.test.ts
import { describe, expect, it } from "vitest";
import { findViolations, isProtected } from "../scripts/guard-diff.mjs";

const diffOf = (file: string, body: string, extra = "") =>
  `diff --git a/${file} b/${file}\n${extra}--- a/${file}\n+++ b/${file}\n@@ -1,1 +1,1 @@\n${body}\n`;

describe("guard-diff", () => {
  it("accepts a plain code change", () => {
    expect(findViolations(diffOf("src/a.ts", "-const a = 1;\n+const a = 2;"))).toEqual([]);
  });

  it("flags a protected file", () => {
    expect(findViolations(diffOf(".github/workflows/ci.yml", "+  - run: echo"))).toEqual([
      { file: ".github/workflows/ci.yml", reason: "protected file changed" },
    ]);
  });

  it.each([
    ["// eslint-disable-next-line", "silences a lint rule"],
    ["// @ts-ignore", "silences the type checker"],
    ["// @ts-expect-error wrong types upstream", "silences the type checker"],
    ["const x = y as never;", "casts away the type"],
    ["const x = y as any;", "casts to any"],
    ["const x = y as unknown as Order;", "forces a type through unknown"],
  ])("flags an added silencer: %s", (code, reason) => {
    expect(findViolations(diffOf("src/a.ts", `+${code}`))).toEqual([{ file: "src/a.ts", reason, line: code }]);
  });

  it("flags a skipped or focused test", () => {
    const reasons = findViolations(diffOf("test/a.test.ts", '+it.skip("x", () => {});\n+describe.only("y", () => {});'))
      .map((v) => v.reason);
    expect(reasons).toEqual(["skips or focuses tests", "skips or focuses tests"]);
  });

  it("flags a protected file moved away", () => {
    const diff = "diff --git a/vitest.config.ts b/old/vitest.config.ts\nsimilarity index 100%\nrename from vitest.config.ts\nrename to old/vitest.config.ts\n";
    expect(findViolations(diff).map((v) => v.reason)).toContain("protected file changed");
  });

  it("ignores a silencer that is removed, not added", () => {
    expect(findViolations(diffOf("src/a.ts", "-// @ts-ignore"))).toEqual([]);
  });

  it("flags a deleted test file", () => {
    expect(findViolations(diffOf("test/a.test.ts", "-it('x', () => {});", "deleted file mode 100644\n"))).toContainEqual({
      file: "test/a.test.ts",
      reason: "test file deleted",
    });
  });

  it("flags removed assertions, but not a rewritten one", () => {
    const removed = diffOf("test/a.test.ts", "-  expect(a).toBe(1);\n-  expect(b).toBe(2);\n+  expect(a).toBe(1);");
    expect(findViolations(removed)).toEqual([{ file: "test/a.test.ts", reason: "1 assertion(s) removed" }]);
    const rewritten = diffOf("test/a.test.ts", "-  expect(a).toBe(1);\n+  expect(a).toEqual(1);");
    expect(findViolations(rewritten)).toEqual([]);
  });

  it("protects whole folders and exact files only", () => {
    expect(isProtected(".claude/settings.json")).toBe(true);
    expect(isProtected("package.json")).toBe(true);
    expect(isProtected("src/package.json")).toBe(false);
    expect(isProtected("specs-old.md")).toBe(false);
    expect(isProtected("agents.md")).toBe(false);
    expect(isProtected("agents.md", true)).toBe(true);
  });
});

La garde et ses tests font partie de la zone protégée : un agent ne peut pas affaiblir la garde pour faire passer sa modification.

Le crochet de commit

.githooks/pre-commit
#!/bin/sh
# Installed with `npm run hooks:install`. Fast checks on what is about to be committed.
# An agent cannot skip it: the Bash hook blocks `--no-verify`, and CI runs the same checks anyway.
set -e
node scripts/guard-diff.mjs --staged
npm run -s verify:fast

La même garde, avant chaque commit, plus les contrôles rapides. npm run hooks:install l'active (il pointe Git vers .githooks/). L'agent ne peut pas le sauter : --no-verify est bloqué par le hook Bash, et la CI relance tout de toute façon.

L'adapter

  • La liste PROTECTED : ajoute les migrations, la configuration de déploiement, les politiques de sécurité de ton projet.
  • Les SILENCERS : ajoute les équivalents de ton écosystème (# type: ignore, # noqa en Python, #[allow(...)] en Rust).
  • Garde la règle simple. Une garde qui produit des faux positifs finit contournée par tout le monde, toi compris. Si un motif bloque souvent du code légitime, affine-le et ajoute le cas aux tests.

Une erreur, un passage peu clair ?Proposer une correction de ce chapitre