Pieza: calidad

Dos hooks y unas reglas de ESLint que mantienen el formato, el lint, los tipos y las pruebas en verde sin pedírselo al agente. Sale del arnés por capas y sirve para cualquier arnés de la serie.

Antes de empezar

  • Arnés por capasArnés

    La mini app organizada en capas (controladores, servicios y repositorios), con instrucciones para el agente y un hook que le impide terminar si rompe la regla de las capas.

    Publicado

La idea clave: el agente no tiene que acordarse de formatear, pasar el linter ni ejecutar las pruebas. Un hook formatea cada archivo justo después de que el agente lo edita. Otro hook, al final, ejecuta el formato, el lint, los tipos y las pruebas, y no deja terminar al agente hasta que todo pasa.

Qué problema evita

Puedes escribir en el AGENTS.md «ejecuta las pruebas y el linter antes de terminar». El agente casi siempre lo hace. Pero «casi siempre» no basta, y algunos errores se cuelan incluso cuando lo hace:

  • Formato desordenado. El agente escribe código que funciona, pero con otro estilo: comillas dobles, líneas larguísimas. El diff se llena de cambios que no importan y revisarlo cuesta más.
  • Funciones que crecen sin parar. Para cubrir un caso nuevo, un agente suele añadir otro if a la función que ya está editando. Funciona, pero cada vez se lee peor.
  • Pruebas en verde con los tipos rotos. Vitest ejecuta TypeScript sin comprobar los tipos. Si el agente solo ejecuta npm test, un error de tipos pasa sin que nadie lo vea.
  • Silenciar el linter. Si una regla le molesta, el agente puede añadir un comentario eslint-disable y seguir.

Piensa en el corrector de un procesador de texto y en el editor de una revista. El corrector arregla las faltas mientras escribes, sin preguntarte. El editor no deja publicar el artículo hasta que está bien. La pieza tiene los dos: un hook que formatea al momento y otro que lo revisa todo al final.

El arnés por capas ya traía ESLint y Prettier, pero solo como comandos: el agente tenía que acordarse de ejecutarlos. Esta pieza los ejecuta sola y añade unas reglas pensadas para agentes. El arnés por capas ya usa esta versión.

Qué archivos añade

Parte Archivos Qué hace
Formato al editar .agents/hooks/format-after-edit.mjs Después de que el agente escribe o edita un archivo, lo formatea con Prettier. Si Prettier no puede leerlo, por ejemplo por un error de sintaxis, el agente ve el error.
Comprobaciones al terminar .agents/hooks/check-quality-before-stop.mjs Cuando el agente intenta terminar, ejecuta npm run format:check, npm run lint, npm run typecheck y npm test. Si alguno falla, el agente todavía no puede terminar.
Reglas de ESLint eslint.config.js Los conjuntos de reglas recomendados, cuatro límites al tamaño de una función y los comentarios eslint-disable desactivados.
Reglas de formato prettier.config.mjs, .prettierignore El estilo de Prettier y los archivos que no toca.
Instrucciones La sección Quality de AGENTS.md Explica al agente qué hacen los hooks y qué no puede tocar para pasar una comprobación.
Pruebas test/ Ejecutan los dos hooks como lo hace un agente y comprueban qué cambian, qué informan y con qué código terminan.

Un hook es un comando que la herramienta del agente ejecuta sola en un momento concreto; lo explica el tema sobre Hooks. Por qué conviene que el agente compruebe su trabajo con pruebas, tipos y linter lo explica Verificación y evaluación.

Las reglas de ESLint

La configuración parte de los conjuntos recomendados de ESLint y de typescript-eslint, que ya marcan, por ejemplo, el tipo any y el comentario @ts-ignore. Encima añade pocas reglas, y cada una lleva en el archivo la razón por la que está:

Regla y límite Por qué
complexity: 10 Cuenta los caminos que puede seguir una función: cada if, bucle o && suma uno. ESLint usa 20 por defecto; con 10, la función se parte antes.
max-depth: 3 Limita cuántos bloques hay uno dentro de otro. Mucho anidamiento suele pedir un return temprano.
max-params: 4 Una función con muchos parámetros es fácil de llamar mal.
max-lines-per-function: 50 Sin contar líneas en blanco ni comentarios. No se aplica a las pruebas, porque un bloque describe agrupa muchas pruebas cortas.
noInlineConfig ESLint ignora los comentarios eslint-disable. Una excepción tiene que ir en eslint.config.js, donde se ve al revisar.
eqeqeq y consistent-type-imports Vienen del arnés por capas: === en lugar de ==, y los imports que solo traen tipos marcados como import type.

Los cuatro límites van contra la costumbre de añadir una rama más a la función que ya existe. Los valores son un punto de partida, no una medida científica. El código del arnés por capas los cumple sin cambios.

noInlineConfig es la regla más interesante para un agente. En la pieza de seguridad, nada técnico impide esconder una clave con un comentario secretlint-disable: solo lo prohíbe AGENTS.md. Aquí sí hay una barrera. Si el agente escribe // eslint-disable-next-line, ESLint avisa de que el comentario no tiene efecto y sigue marcando el error. El agente todavía podría cambiar eslint.config.js, pero ese cambio queda a la vista en el diff.

Cómo trabaja el hook de formato

  • Lee la ruta del archivo editado de la entrada JSON. La busca en tool_input.file_path (así la envía Claude Code), en file_path (Cursor) o en las cabeceras de un parche dentro de tool_input.command, como *** Update File: src/app.ts, porque Codex edita con parches.
  • Solo toca archivos de su propio proyecto y respeta .prettierignore. Se salta los archivos que Prettier no conoce.
  • Arranca el script de Prettier que está en node_modules directamente con node, en lugar de usar npx prettier. npx arranca npm primero, y eso sumaría tiempo a cada edición.
  • Es una ayuda, no una barrera: si la entrada no es JSON o no trae un archivo, no hace nada. La garantía está en el hook de parada, que revisa el formato de todos los archivos, también los que el agente escribe desde la terminal y este hook no ve.

Cómo trabaja el hook de parada

Sigue el mismo contrato que el resto de la serie. Busca la raíz del proyecto desde su propia ubicación y ejecuta los cuatro comandos aunque uno falle, para que el agente reciba todos los problemas de una vez. Si alguno falla, escribe la salida en stderr (la salida de error) y termina con código 2. Si todo pasa, termina con código 0 sin escribir nada.

Ejecuta npm run typecheck además del lint y las pruebas porque, como dice la documentación de Vitest, las pruebas no comprueban los tipos si no se pide. Lo comprobé en el arnés por capas: con un error de tipos, las 65 pruebas pasaron igual.

El explorador

Al cargarse, el explorador abre AGENTS.md. La pieza no tiene la mini app: solo su configuración, sus hooks y las pruebas de esos hooks. Las dependencias y package-lock.json no aparecen.

// Stop hook: connect it to your agent's stop event, the moment the agent is about to finish.
// It runs the formatting check, the linter, the type checker and the tests. If any of them fails,
// it prints the output to stderr and exits with code 2. Agents that follow this convention read
// code 2 as "not done yet" and send the output back to the agent. Exit code 0 with no output means
// every check passed.
//
// The script is not tied to one agent: it reads no agent-specific input or environment variable.
// stdin (the hook's JSON input) is not read: the checks do not depend on it. The checks run on
// every stop, so the only way to pass is to fix the code. Whether the agent caps how many times in
// a row it can be sent back depends on the agent that runs the hook.
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

// The project root is two folders up from .agents/hooks/. Agents start hooks from different
// folders, so the script does not rely on the current directory.
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
const projectDir = path.resolve(scriptDir, '..', '..');

// Every command runs even if an earlier one fails, so the agent gets every problem in one report.
// typecheck is here because Vitest runs TypeScript without checking its types: the tests can pass
// while the types are wrong.
const CHECKS = ['npm run format:check', 'npm run lint', 'npm run typecheck', 'npm test'];
const CHECK_TIMEOUT_MS = 120_000;
const MAX_OUTPUT_CHARS = 4_000;

const failures = [];
for (const command of CHECKS) {
  // shell: true lets Windows run npm.cmd. The commands are fixed strings, not user input.
  const result = spawnSync(command, {
    cwd: projectDir,
    shell: true,
    encoding: 'utf8',
    timeout: CHECK_TIMEOUT_MS,
  });
  if (result.status !== 0) {
    const output = [result.stdout, result.stderr, result.error?.message]
      .filter(Boolean)
      .join('\n')
      .trim();
    failures.push({ command, output: tail(output) });
  }
}

if (failures.length > 0) {
  const report = [
    'Quality check failed. Fix these before you finish.',
    'Run `npm run format` to fix formatting. Fix lint, type and test errors in the code, not in the checks.',
    '',
  ];
  for (const failure of failures) {
    report.push(`$ ${failure.command}`, failure.output, '');
  }
  process.stderr.write(report.join('\n'));
  process.exitCode = 2;
}

// Keeps only the end of long output, where the errors and failing assertions usually are.
function tail(text) {
  if (text.length <= MAX_OUTPUT_CHARS) {
    return text;
  }
  return `...(${text.length - MAX_OUTPUT_CHARS} characters cut)\n${text.slice(-MAX_OUTPUT_CHARS)}`;
}
// Post-edit hook: connect it to your agent's event that runs after it writes or edits a file.
// It reads the hook's JSON input from stdin, finds the edited files and formats them with Prettier,
// using the project's Prettier config and .prettierignore. If Prettier cannot format a file, for
// example because of a syntax error, it prints the reason to stderr and exits with code 2, so the
// agent sees it. Everything else exits with code 0 and no output: a file outside the project, a
// file that Prettier does not know or ignores, or input without a file path.
//
// The script is not tied to one agent: it reads no agent-specific environment variable. The file
// is read from `tool_input.file_path` or from `file_path`, the two places where agents put it, or
// from the file headers of a patch in `tool_input.command`, for agents that edit with patches.
//
// Formatting here is a convenience, not a gate. Files that the agent changes from the terminal
// never reach this hook, so the stop hook checks the formatting of every file.
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

// The project root is two folders up from .agents/hooks/. Agents start hooks from different
// folders, so the script does not rely on the current directory.
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
const projectDir = path.resolve(scriptDir, '..', '..');

// The hook runs Prettier's own script with node. `npx prettier` would start npm first, which adds
// time to every edit.
const PRETTIER = path.join(projectDir, 'node_modules', 'prettier', 'bin', 'prettier.cjs');
const TIMEOUT_MS = 30_000;

// A patch names each file it adds, changes or moves in a header line such as
// `*** Update File: src/app.ts`.
const PATCH_FILE_HEADER = /^\*\*\* (?:Add File|Update File|Move to): (.+)$/gmu;

readStdin().then((text) => {
  const files = readEditedFiles(text).filter((file) => isInsideProject(file) && existsSync(file));
  if (files.length > 0) {
    format(files);
  }
});

// Reads stdin as a stream. readFileSync(0) would be shorter, but it does not read piped input in
// every Node runtime: in StackBlitz it did not get the input.
function readStdin() {
  return new Promise((resolve, reject) => {
    let text = '';
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', (chunk) => {
      text += chunk;
    });
    process.stdin.on('end', () => resolve(text));
    process.stdin.on('error', reject);
  });
}

// Returns the absolute paths of the edited files, or an empty list when the input has none. Input
// that is not JSON does nothing: a formatter must not get in the agent's way.
function readEditedFiles(text) {
  let input;
  try {
    input = JSON.parse(text);
  } catch {
    return [];
  }
  const base = typeof input?.cwd === 'string' ? input.cwd : projectDir;
  return namedFiles(input)
    .map((name) => name.trim())
    .filter((name) => name !== '')
    .map((name) => path.resolve(base, name));
}

function namedFiles(input) {
  const filePath = input?.tool_input?.file_path ?? input?.file_path;
  if (typeof filePath === 'string') {
    return [filePath];
  }
  const command = input?.tool_input?.command;
  if (typeof command === 'string') {
    return [...command.matchAll(PATCH_FILE_HEADER)].map((match) => match[1]);
  }
  return [];
}

// The hook only touches files inside its own project.
function isInsideProject(file) {
  const relative = path.relative(projectDir, file);
  return relative !== '' && !path.isAbsolute(relative) && relative.split(path.sep)[0] !== '..';
}

function format(files) {
  if (!existsSync(PRETTIER)) {
    report('Prettier is not installed. Run `npm install` in the project.');
    return;
  }
  // --ignore-unknown skips files that Prettier cannot format, such as images.
  const result = spawnSync(
    process.execPath,
    [PRETTIER, '--write', '--ignore-unknown', '--log-level', 'warn', '--no-color', ...files],
    { cwd: projectDir, encoding: 'utf8', timeout: TIMEOUT_MS },
  );
  if (result.status !== 0) {
    const output = [result.stdout, result.stderr, result.error?.message]
      .filter(Boolean)
      .join('\n')
      .trim();
    report(output);
  }
}

function report(output) {
  process.stderr.write(
    ['Formatting failed. The edit was saved, but Prettier could not format it.', output, ''].join(
      '\n',
    ),
  );
  process.exitCode = 2;
}
import { spawn } from 'node:child_process';
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterAll, describe, it } from 'vitest';

// These tests run the stop hook the way an agent does. The hook runs `npm test`, so running it on
// this project from a test would start these tests again. Instead, each test copies the hook into a
// small fake project, in the system's temporary folder, whose checks pass or fail on demand. The
// folders are deleted at the end.

const hook = fileURLToPath(
  new URL('../.agents/hooks/check-quality-before-stop.mjs', import.meta.url),
);
const projectDirs: string[] = [];

const CHECK_NAMES = ['format:check', 'lint', 'typecheck', 'test'];

// Each fake check writes its name to ran.txt and fails if its name is in failing.json.
const CHECK_SCRIPT = `import { appendFileSync, readFileSync } from 'node:fs';
const name = process.argv[2];
appendFileSync('ran.txt', name + '\\n');
if (JSON.parse(readFileSync('failing.json', 'utf8')).includes(name)) {
  console.log(name + ' found 1 problem');
  process.exitCode = 1;
}
`;

function createProject(failing: string[]): string {
  const projectDir = mkdtempSync(path.join(tmpdir(), 'quality-hook-'));
  projectDirs.push(projectDir);
  mkdirSync(path.join(projectDir, '.agents', 'hooks'), { recursive: true });
  copyFileSync(hook, path.join(projectDir, '.agents', 'hooks', 'check-quality-before-stop.mjs'));
  const scripts = Object.fromEntries(
    CHECK_NAMES.map((check) => [check, `node check.mjs ${check}`]),
  );
  writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify({ private: true, scripts }));
  writeFileSync(path.join(projectDir, 'check.mjs'), CHECK_SCRIPT);
  writeFileSync(path.join(projectDir, 'failing.json'), JSON.stringify(failing));
  return projectDir;
}

// The hook runs from this project's folder, not the fake project's, as when an agent starts it
// from another folder. spawn is asynchronous, so both tests can run at the same time.
function runHook(projectDir: string): Promise<{ code: number | null; stderr: string }> {
  return new Promise((resolve, reject) => {
    const child = spawn(process.execPath, [
      path.join(projectDir, '.agents', 'hooks', 'check-quality-before-stop.mjs'),
    ]);
    let stderr = '';
    child.stderr.setEncoding('utf8').on('data', (chunk: string) => {
      stderr += chunk;
    });
    child.on('error', reject);
    child.on('close', (code) => resolve({ code, stderr }));
    child.stdin.end('{}');
  });
}

function checksThatRan(projectDir: string): string[] {
  return readFileSync(path.join(projectDir, 'ran.txt'), 'utf8').trim().split('\n');
}

afterAll(() => {
  for (const projectDir of projectDirs) {
    rmSync(projectDir, { recursive: true, force: true });
  }
});

// Each test runs npm four times, which takes a few seconds, so the timeout is longer than usual.
describe.concurrent('check-quality-before-stop hook', { timeout: 60_000 }, () => {
  it('passes when every check passes', async ({ expect }) => {
    const projectDir = createProject([]);

    const result = await runHook(projectDir);

    expect(result.code).toBe(0);
    expect(result.stderr).toBe('');
    expect(checksThatRan(projectDir)).toEqual(CHECK_NAMES);
  });

  it('fails with code 2 and reports every failing check', async ({ expect }) => {
    const projectDir = createProject(['lint', 'test']);

    const result = await runHook(projectDir);

    expect(result.code).toBe(2);
    expect(result.stderr).toContain('Quality check failed');
    expect(result.stderr).toContain('$ npm run lint');
    expect(result.stderr).toContain('lint found 1 problem');
    expect(result.stderr).toContain('$ npm test');
    expect(result.stderr).toContain('test found 1 problem');
    expect(result.stderr).not.toContain('$ npm run typecheck');
    // A failing check does not stop the ones after it.
    expect(checksThatRan(projectDir)).toEqual(CHECK_NAMES);
  });
});
import { spawn } from 'node:child_process';
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';

// These tests run the hook the way an agent does: JSON on stdin, then read the exit code, stderr
// and the edited file.
//
// Each test copies the hook into a fake project in the system's temporary folder. Creating and
// deleting files inside this project would race with other checks that read every file at the same
// time, such as a secret scan in a harness.

const hook = fileURLToPath(new URL('../.agents/hooks/format-after-edit.mjs', import.meta.url));
const prettierScript = fileURLToPath(
  new URL('../node_modules/prettier/bin/prettier.cjs', import.meta.url),
);

const UNFORMATTED = 'export const  book = {title:"Dune",\n  year:1965}\n';
const FORMATTED = "export const book = { title: 'Dune', year: 1965 };\n";

let projectDir = '';
let outsideDir = '';

interface HookResult {
  code: number | null;
  stderr: string;
  stdout: string;
}

function createProject(): string {
  const dir = mkdtempSync(path.join(tmpdir(), 'format-hook-'));
  mkdirSync(path.join(dir, '.agents', 'hooks'), { recursive: true });
  copyFileSync(hook, path.join(dir, '.agents', 'hooks', 'format-after-edit.mjs'));
  for (const name of ['prettier.config.mjs', '.prettierignore']) {
    copyFileSync(fileURLToPath(new URL(`../${name}`, import.meta.url)), path.join(dir, name));
  }
  // The hook runs node_modules/prettier/bin/prettier.cjs of its own project. In the fake project,
  // that file loads the Prettier installed in this one.
  const binDir = path.join(dir, 'node_modules', 'prettier', 'bin');
  mkdirSync(binDir, { recursive: true });
  writeFileSync(path.join(binDir, 'prettier.cjs'), `require(${JSON.stringify(prettierScript)});\n`);
  return dir;
}

// spawn writes stdin as a stream, which works in every runtime the template runs in, StackBlitz too.
function runHook(input: string): Promise<HookResult> {
  return new Promise((resolve, reject) => {
    const child = spawn(process.execPath, [
      path.join(projectDir, '.agents', 'hooks', 'format-after-edit.mjs'),
    ]);
    let stdout = '';
    let stderr = '';
    child.stdout.setEncoding('utf8').on('data', (chunk: string) => {
      stdout += chunk;
    });
    child.stderr.setEncoding('utf8').on('data', (chunk: string) => {
      stderr += chunk;
    });
    child.on('error', reject);
    child.on('close', (code) => resolve({ code, stderr, stdout }));
    child.stdin.end(input);
  });
}

function writeFile(dir: string, name: string, content: string): string {
  const file = path.join(dir, name);
  mkdirSync(path.dirname(file), { recursive: true });
  writeFileSync(file, content);
  return file;
}

// The input after an edit tool call, with the file in tool_input.file_path.
function editCall(file: string): string {
  return JSON.stringify({
    hook_event_name: 'PostToolUse',
    tool_name: 'Edit',
    tool_input: { file_path: file },
  });
}

beforeEach(() => {
  projectDir = createProject();
  outsideDir = mkdtempSync(path.join(tmpdir(), 'format-hook-outside-'));
});

afterEach(() => {
  rmSync(projectDir, { recursive: true, force: true });
  rmSync(outsideDir, { recursive: true, force: true });
});

// Each test starts Prettier in a new Node process. On October 18, 2026, StackBlitz needed more than
// the default 5 seconds for some of them, so the timeout is longer.
describe('format-after-edit hook', { timeout: 30_000 }, () => {
  it('formats the file in tool_input.file_path', async () => {
    const file = writeFile(projectDir, 'src/book.ts', UNFORMATTED);

    const result = await runHook(editCall(file));

    expect(result.code).toBe(0);
    expect(result.stderr).toBe('');
    expect(result.stdout).toBe('');
    expect(readFileSync(file, 'utf8')).toBe(FORMATTED);
  });

  it('formats the file in a top-level file_path', async () => {
    const file = writeFile(projectDir, 'src/book.ts', UNFORMATTED);

    const result = await runHook(JSON.stringify({ file_path: file }));

    expect(result.code).toBe(0);
    expect(readFileSync(file, 'utf8')).toBe(FORMATTED);
  });

  it('reads a relative path from the folder in cwd', async () => {
    const file = writeFile(projectDir, 'src/book.ts', UNFORMATTED);
    const input = { cwd: path.join(projectDir, 'src'), tool_input: { file_path: 'book.ts' } };

    const result = await runHook(JSON.stringify(input));

    expect(result.code).toBe(0);
    expect(readFileSync(file, 'utf8')).toBe(FORMATTED);
  });

  it('formats every file named in the headers of a patch in tool_input.command', async () => {
    const changed = writeFile(projectDir, 'src/book.ts', UNFORMATTED);
    const added = writeFile(projectDir, 'src/member.ts', UNFORMATTED);
    const patch = [
      '*** Begin Patch',
      '*** Update File: src/book.ts',
      '@@',
      '-old line',
      '+new line',
      '*** Add File: src/member.ts',
      '+new file',
      '*** End Patch',
    ].join('\n');
    const input = { cwd: projectDir, tool_name: 'apply_patch', tool_input: { command: patch } };

    const result = await runHook(JSON.stringify(input));

    expect(result.code).toBe(0);
    expect(readFileSync(changed, 'utf8')).toBe(FORMATTED);
    expect(readFileSync(added, 'utf8')).toBe(FORMATTED);
  });

  it('fails with code 2 when Prettier cannot parse the file, and leaves it as it was', async () => {
    const broken = 'export const = ;\n';
    const file = writeFile(projectDir, 'src/broken.ts', broken);

    const result = await runHook(editCall(file));

    expect(result.code).toBe(2);
    expect(result.stderr).toContain('Formatting failed');
    expect(result.stderr).toContain('broken.ts');
    expect(result.stderr).toContain('SyntaxError');
    expect(readFileSync(file, 'utf8')).toBe(broken);
  });

  it('leaves a file outside the project alone', async () => {
    const file = writeFile(outsideDir, 'book.ts', UNFORMATTED);

    const result = await runHook(editCall(file));

    expect(result.code).toBe(0);
    expect(readFileSync(file, 'utf8')).toBe(UNFORMATTED);
  });

  it('leaves a file that Prettier does not know alone', async () => {
    const content = 'some   notes\n';
    const file = writeFile(projectDir, 'notes.unknown', content);

    const result = await runHook(editCall(file));

    expect(result.code).toBe(0);
    expect(result.stderr).toBe('');
    expect(readFileSync(file, 'utf8')).toBe(content);
  });

  it.each([
    ['a tool call without a file', JSON.stringify({ tool_input: { command: 'npm test' } })],
    ['a file that does not exist', editCall('src/missing.ts')],
    ['input that is not JSON', 'not json'],
  ])('does nothing for %s', async (_case, input) => {
    const result = await runHook(input);

    expect(result.code).toBe(0);
    expect(result.stderr).toBe('');
  });
});
node_modules/
node_modules/
package-lock.json
# AGENTS.md

## Project

This folder is the **quality piece** of the Agent Atlas harness series. It is not an app: it holds the formatting and lint settings, two hooks and the tests of those hooks, ready to add to a harness. The layered harness (`../layered/`) already includes it.

Use npm in this folder, not pnpm. Run `npm run verify` before you say a task is done.

The `Quality` section below is the one to paste into the `AGENTS.md` of a harness.

## Quality

- After you write or edit a file, the hook `.agents/hooks/format-after-edit.mjs` formats it with Prettier. You do not need to format by hand. If the hook says it could not format a file, the file usually has a syntax error: fix it.
- When you try to finish, the hook `.agents/hooks/check-quality-before-stop.mjs` runs `npm run format:check`, `npm run lint`, `npm run typecheck` and `npm test`. If one fails, you cannot finish until it passes. Run `npm run format` for formatting problems. Fix lint, type and test errors in the code.
- ESLint limits the size of a function: complexity 10, nesting depth 3, 4 parameters and 50 lines. If you reach a limit, split the function. Do not move the code somewhere else only to pass the check.
- `eslint-disable` comments have no effect here. Do not add them. If a rule is wrong for a case, tell the user. Exceptions go in `eslint.config.js`, where a reviewer sees them, and only the user adds them.
- Never weaken, skip or delete a test to make the checks pass. Never edit the quality hooks, `eslint.config.js`, `prettier.config.mjs`, `.prettierignore` or your agent's hook settings to get past a check.

## Files

| File                                          | What it does                                                                                             |
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `.agents/hooks/format-after-edit.mjs`         | Runs after the agent writes or edits a file and formats that file with Prettier                          |
| `.agents/hooks/check-quality-before-stop.mjs` | Runs when the agent tries to finish and fails if formatting, lint, types or tests fail (exit code 2)     |
| `eslint.config.js`                            | The ESLint rules: the recommended sets, a few limits on the size of a function, and no `eslint-disable`  |
| `prettier.config.mjs`, `.prettierignore`      | The Prettier settings and the files it skips                                                             |
| `test/`                                       | Runs both hooks the way an agent does and checks what they change, what they report and their exit codes |

## Verification

Run these from this folder:

- `npm run format:check`: Prettier. Use `npm run format` to fix formatting.
- `npm run lint`: ESLint.
- `npm run typecheck`: TypeScript, for the tests.
- `npm test`: the tests of both hooks.
- `npm run verify`: all of the above, in that order.
import eslint from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint';

// A few rules on top of the recommended sets, each with the reason it is here.
export default tseslint.config(
  eslint.configs.recommended,
  tseslint.configs.recommended,
  {
    // Scripts such as the hooks run in Node, so they get Node globals like `process`.
    files: ['**/*.{js,mjs,cjs}'],
    languageOptions: { globals: globals.node },
  },
  {
    linterOptions: {
      // An agent that cannot pass a rule may silence it with an `eslint-disable` comment. With this
      // option ESLint ignores those comments, so an exception has to go in this file, where a
      // reviewer sees it.
      noInlineConfig: true,
    },
    rules: {
      // Type-only imports are erased when the code runs. Marking them makes the dependencies
      // easier to read, and it matches verbatimModuleSyntax in tsconfig.json.
      '@typescript-eslint/consistent-type-imports': 'error',
      // Strict equality avoids silent coercions such as '' == 0.
      eqeqeq: 'error',
      // Agents tend to handle a new case by adding one more branch to the function they are
      // editing. These four limits ask for a new function instead, before it becomes hard to read.
      complexity: ['error', 10],
      'max-depth': ['error', 3],
      'max-params': ['error', 4],
      'max-lines-per-function': ['error', { max: 50, skipBlankLines: true, skipComments: true }],
    },
  },
  {
    // A describe block groups many tests, so its length says nothing about how complex it is.
    files: ['test/**'],
    rules: { 'max-lines-per-function': 'off' },
  },
);
{
  "name": "harness-piece-quality",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22"
  },
  "scripts": {
    "test": "vitest run",
    "typecheck": "tsc --noEmit",
    "lint": "eslint .",
    "format": "prettier --write .",
    "format:check": "prettier --check .",
    "verify": "npm run format:check && npm run lint && npm run typecheck && npm test"
  },
  "devDependencies": {
    "@eslint/js": "10.0.1",
    "@types/node": "22.20.5",
    "eslint": "10.12.0",
    "globals": "17.13.0",
    "prettier": "3.9.10",
    "typescript": "5.9.3",
    "typescript-eslint": "8.71.2",
    "vitest": "5.0.4"
  }
}
/** @type {import('prettier').Config} */
export default {
  printWidth: 100,
  semi: true,
  singleQuote: true,
  trailingComma: 'all',
};
# Quality piece

A reusable part of the Agent Atlas harness series. It keeps the formatting, the lint, the types and the tests passing without you having to ask the agent. It started as the ESLint and Prettier setup of the [layered harness](../layered/), and the layered harness now uses this version.

It is not an app. It holds the settings, two hooks and their tests, so you can check the hooks before you copy them into a harness.

## Run it

```bash
npm install
npm run verify
```

## What it adds to a harness

| Part                 | Files                                         | What it does                                                                                                                                  |
| -------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Format after an edit | `.agents/hooks/format-after-edit.mjs`         | After the agent writes or edits a file, formats that file with Prettier. If Prettier cannot parse it, the agent sees the error.               |
| Checks at the stop   | `.agents/hooks/check-quality-before-stop.mjs` | When the agent tries to finish, runs the formatting check, ESLint, TypeScript and the tests. If one fails, the agent cannot finish yet.       |
| Lint rules           | `eslint.config.js`                            | The recommended sets, limits on the size of a function (complexity, nesting, parameters and lines), and `eslint-disable` comments turned off. |
| Formatting rules     | `prettier.config.mjs`, `.prettierignore`      | The Prettier settings and the files it skips.                                                                                                 |
| Instructions         | The `Quality` section of `AGENTS.md`          | Tells the agent what the hooks do and what it must not change to pass a check.                                                                |

Both hooks follow the same contract as the rest of the series: they find the project root from their own location, read no agent-specific environment variable, and report a problem with exit code 2 and the reason on stderr. Exit code 0 with no output means "go on".

The format hook reads the edited file from `tool_input.file_path` or `file_path`, or from the file headers of a patch (`*** Update File: <path>`) in `tool_input.command`. It runs `node node_modules/prettier/bin/prettier.cjs` instead of `npx prettier`, which would start npm first.

## Add it to a harness

1. Copy `.agents/hooks/format-after-edit.mjs`, `.agents/hooks/check-quality-before-stop.mjs`, `eslint.config.js`, `prettier.config.mjs`, `.prettierignore` and the two files in `test/` into the harness.
2. Install the tools with `npm install --save-dev --save-exact eslint @eslint/js typescript-eslint globals prettier`. The harness also needs TypeScript and Vitest.
3. Add the scripts `"lint": "eslint ."`, `"format": "prettier --write ."`, `"format:check": "prettier --check ."` and `"typecheck": "tsc --noEmit"` to `package.json`, and add them to the harness's `verify` script.
4. If the harness has another stop hook that runs `npm test`, remove `npm test` from it. This piece runs the tests now.
5. Paste the `Quality` section of `AGENTS.md` into the harness's `AGENTS.md`.
6. Connect the hooks to your agent (next section).
7. Run `npm run format` once, then `npm run verify`.

## Connect it to your agent

Agents do not share a settings format, so the files in `.agents/` do nothing on their own. Each agent's own settings point to them:

- **After an edit:** register `node .agents/hooks/format-after-edit.mjs` on the event that runs after the agent writes or edits a file.
- **Stop:** register `node .agents/hooks/check-quality-before-stop.mjs` on the event that runs when the agent is about to finish.

The Agent Atlas page for this piece shows the settings for some agents and says what was tested: <https://agentatlas-dev.vercel.app/en/harnesses/quality/>.

## Checks

| Command                | What it checks                             |
| ---------------------- | ------------------------------------------ |
| `npm run format:check` | Prettier formatting                        |
| `npm run lint`         | ESLint                                     |
| `npm run typecheck`    | TypeScript types of the tests              |
| `npm test`             | Both hooks, run the way an agent runs them |
| `npm run verify`       | All of the above, in order                 |

## Limits

- The format hook only sees edits made with the agent's file tools. A file written from the terminal is not formatted until someone runs `npm run format`; the stop hook catches it.
- The stop hook runs every check on every stop, so a slow test suite makes every stop slow.
- ESLint finds long or tangled functions, not bad names or a wrong design. That still needs a review.
- Tests only prove what they check. The stop hook cannot tell a good test from a weak one, and nothing technical stops the agent from weakening a test or changing the settings. `AGENTS.md` forbids it, but that is an instruction, not a barrier.
- How many times in a row a stop hook can send the agent back depends on the agent. The scripts do not limit it.
{
  "compilerOptions": {
    "strict": true,
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "noEmit": true,
    "types": ["node"],
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true
  },
  "include": ["test"]
}

Cómo usarla

Puedes ejecutar las pruebas de la pieza en el navegador o en tu equipo.

En el navegador, el botón Ejecutar en el navegador abre la pieza en StackBlitz, un servicio externo, en una pestaña nueva. StackBlitz instala las dependencias y ejecuta npm test: 12 pruebas que lanzan los dos hooks como lo haría un agente. El 16 de octubre de 2026 lo probé en Chromium 152 con el botón «Abrir StackBlitz en esta pestaña»: pasaron las 12 pruebas, y su terminal midió 33 s para instalar las dependencias y ejecutarlas. No lo probé en Firefox ni en Safari, ni con el botón de pestaña nueva.

En tu equipo necesitas Node 22 o superior. Copia los archivos de la pieza en una carpeta y ejecuta, con npm:

npm install
npm run verify

npm run verify comprueba el formato, pasa ESLint, comprueba los tipos de las pruebas y ejecuta las 12 pruebas.

Añadirla a un arnés

  1. Copia .agents/hooks/format-after-edit.mjs, .agents/hooks/check-quality-before-stop.mjs, eslint.config.js, prettier.config.mjs, .prettierignore y los dos archivos de test/ en el arnés.
  2. Instala las herramientas con npm install --save-dev --save-exact eslint @eslint/js typescript-eslint globals prettier. El arnés también necesita TypeScript y Vitest.
  3. Añade a package.json los scripts lint, format, format:check y typecheck, que están en el package.json de la pieza, y súmalos al script verify.
  4. Si el arnés tiene otro hook de parada que ejecuta npm test, quítaselo: ahora las pruebas las ejecuta esta pieza.
  5. Pega la sección Quality del AGENTS.md de la pieza en el AGENTS.md del arnés.
  6. Conecta los hooks a tu agente, como explica el apartado siguiente.
  7. Ejecuta npm run format una vez y después npm run verify.

Así la añadí al arnés por capas. Las reglas nuevas de ESLint no pidieron ningún cambio en su código. Su hook de parada, que ejecutaba las reglas de capas y las pruebas, pasó a llamarse check-architecture-before-stop.mjs y ahora solo comprueba las capas. Las pruebas pasaron de 53 a 65, y el arnés tiene tres hooks de parada: arquitectura, secretos y calidad.

El día 6 copié la pieza sin cambios en el arnés hexagonal: los mismos archivos y las mismas 12 pruebas. Su código cumplió las reglas de ESLint a la primera.

El día 7 la copié también sin cambios en el arnés de monolito modular. Las pruebas de su módulo de préstamos viven dentro de src/, junto al código, y el lint también las revisa; cumplieron las reglas a la primera.

El día 8 la copié sin cambios en el arnés orientado a eventos. Allí el lint revisa también scripts/check-events.ts, el comando que dibuja el mapa de eventos, y el código nuevo cumplió las reglas a la primera. El hook de parada de esta pieza es el que detecta un evento con otra forma, porque falla npm run typecheck o fallan las pruebas.

Conectarla a tu agente

Cada agente lee los hooks desde su propia configuración. Esos archivos no vienen en la pieza: créalos tú en la carpeta del arnés. Si ya conectaste otras piezas, añade estos hooks a la misma configuración.

Claude Code. En .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": ["${CLAUDE_PROJECT_DIR}/.agents/hooks/format-after-edit.mjs"],
            "timeout": 30
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": ["${CLAUDE_PROJECT_DIR}/.agents/hooks/check-quality-before-stop.mjs"],
            "timeout": 600
          }
        ]
      }
    ]
  }
}
  • PostToolUse es el momento después de usar una herramienta, y Edit|Write cubre las dos con las que Claude Code escribe archivos. Su guía de hooks trae un ejemplo parecido con Prettier. Según su documentación, un archivo que cambia desde la terminal no dispara este hook.
  • Si el hook de formato termina con código 2, Claude Code le muestra el motivo al agente, pero la edición ya está hecha: no se deshace.
  • Claude Code ejecuta los hooks de parada cada vez que termina de responder, no solo al final de una tarea, y los ejecuta todos en paralelo. En el arnés por capas, la espera es la del hook más lento, que es este.
  • timeout se mide en segundos. 600 es el valor por defecto de Claude Code para un hook de comando; lo escribo para que se vea que el hook de parada puede tardar.

Codex. En .codex/hooks.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "^apply_patch$",
        "hooks": [
          {
            "type": "command",
            "command": "node .agents/hooks/format-after-edit.mjs",
            "timeout": 30
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node .agents/hooks/check-quality-before-stop.mjs",
            "timeout": 600
          }
        ]
      }
    ]
  }
}
  • Codex edita archivos con la herramienta apply_patch. Según su documentación, el hook la recibe con el parche en tool_input.command. La forma de las cabeceras del parche, como *** Update File: <ruta>, la saqué de las pruebas del código de Codex, no de su documentación.
  • Si el hook de formato termina con código 2, Codex cambia el resultado de la herramienta por el mensaje del hook.
  • Su documentación dice que, en la parada, espera un JSON en la salida estándar cuando el hook termina con código 0. Los hooks de parada de la serie no escriben nada en ese caso, y no pude comprobar si Codex lo acepta.
  • Como en las otras piezas, ábrelo en la carpeta del arnés y marca los hooks como de confianza con /hooks.

Cursor. En .cursor/hooks.json:

{
  "version": 1,
  "hooks": {
    "afterFileEdit": [
      {
        "type": "command",
        "command": "node .agents/hooks/format-after-edit.mjs",
        "timeout": 30
      }
    ]
  }
}

Según su documentación, afterFileEdit se ejecuta después de que el agente edita un archivo, es útil para formatear y envía la ruta absoluta en file_path, que es donde la busca el script. No dice qué hace con la salida de este hook. Su hook de parada espera un JSON con followup_message en la salida estándar, así que el hook de parada necesitaría un pequeño adaptador, que no escribí.

No probé ninguna de estas configuraciones en una sesión real. Salen de la documentación de cada agente, consultada el 16 de octubre de 2026.

Qué se puede automatizar y qué no

Qué Qué lo hace Qué se escapa
El formato El hook de formato al editar y format:check al terminar Nada, si los dos están conectados: lo que no formatea el primero lo para el segundo.
Errores de lint ESLint en el hook de parada Lo que las reglas no miran.
Funciones largas o enredadas Los cuatro límites de ESLint Una función corta pero mal pensada.
Silenciar el linter noInlineConfig Un cambio en eslint.config.js, que se ve en el diff.
Errores de tipos npm run typecheck en el hook de parada Lo que TypeScript no puede saber, como un dato que llega mal por HTTP.
Pruebas que fallan npm test en el hook de parada Una prueba debilitada o borrada.
Si las pruebas comprueban lo importante Tú No se automatiza.
Nombres claros y un buen diseño Tú No se automatiza. La pieza de código limpio le da al agente reglas y una revisión.

Qué se comprobó

Lo que probé el 16 de octubre de 2026, en Windows 11 con Node 24.19:

  • En la pieza, npm run verify pasó: formato, lint, tipos y 12 de 12 pruebas.
  • En el arnés por capas, con la pieza añadida, npm run verify pasó: tipos, lint con las reglas nuevas, formato, no dependency violations found (15 modules, 39 dependencies cruised), secretlint y 65 de 65 pruebas.
  • Rompí una prueba a propósito: cambié el límite de préstamos de 3 a 4. El hook de calidad salió con código 2 en unos 13 segundos, con $ npm test y las 2 pruebas que fallaron. Después lo deshice.
  • Cambié el tipo que devuelve add en book-service.ts de Book a number. npm test pasó las 65 pruebas, pero el hook salió con código 2 por npm run typecheck, con error TS2322. Después lo deshice.
  • Añadí // eslint-disable-next-line encima de una variable de tipo any. ESLint avisó de que el comentario no tenía efecto y siguió marcando el any como error.
  • Escribí un archivo sin formato desde la terminal, sin pasar por el hook de formato. El hook de parada salió con código 2 por npm run format:check.
  • Le pasé al hook de formato una entrada como la de Claude Code, con una ruta de Windows. Formateó el archivo en 0,45 a 0,53 segundos.
  • El hook de las capas sigue funcionando: con un import de BookRepository en un controlador salió con código 2 en unos 2,4 segundos.

Los tiempos con el código correcto: el hook de calidad tardó unos 11 segundos en la pieza y unos 14,5 en el arnés por capas. Lo más lento son las pruebas (de 4 a 8 segundos en el arnés), el lint (unos 4) y la comprobación de tipos (unos 2,5). Cada comando arranca a través de npm, que suma casi un segundo. En el arnés por capas, los tres hooks de parada lanzados a la vez, como hace Claude Code, tardaron unos 15 segundos. El de las capas tarda unos 2,4 y el de secretos, unos 1,5.

En StackBlitz, con Chromium 152 y el botón de la misma pestaña, pasaron las 12 pruebas de la pieza (33 s en su terminal) y las 65 del arnés por capas (38 s). El 18 de octubre, StackBlitz iba más lento y 5 pruebas del hook de formato fallaron en el arnés por capas por superar el límite de 5 segundos de Vitest. Les subí el límite a 30 segundos; después pasaron las 12 de la pieza (37 s en su terminal) y todas las del arnés. Las pruebas de los hooks crean sus proyectos falsos en la carpeta temporal del sistema, no dentro del proyecto. Así no chocan con el escáner de secretos del arnés por capas, que lee todos los archivos mientras corren las demás pruebas y podría fallar si un archivo desaparece a mitad de lectura.

Lo que no pude probar: una sesión real de un agente. El CLI de Claude Code de la máquina (2.1.220) seguía sin la sesión iniciada. Codex avisó el 15 de octubre de que la cuenta había llegado a su límite de uso hasta el 2 de noviembre, así que no lo intenté. Cursor no está instalado. Los hooks los probé con entradas simuladas, como las que describen las documentaciones.

Limitaciones

  • El hook de formato solo ve las ediciones que el agente hace con sus herramientas de archivos. Un archivo escrito desde la terminal no se formatea solo: lo detecta format:check al terminar, y el agente tiene que ejecutar npm run format.
  • El hook de parada lo ejecuta todo en cada parada, también cuando el agente solo responde una pregunta. En esa máquina tardó entre 11 y 15 segundos, y un conjunto de pruebas lento haría lenta cada parada.
  • ESLint mide el tamaño y el enredo de una función, no si los nombres o el diseño son buenos.
  • El hook no distingue una prueba buena de una floja. Nada técnico impide que el agente debilite una prueba, cambie eslint.config.js o toque los hooks. AGENTS.md se lo prohíbe, pero es una instrucción, no una barrera.
  • Cuántas veces seguidas puede devolver el hook de parada al agente depende del agente. El script no lo limita.
  • Solo lo probé en Windows 11 con Node 24.19.

Siguiente paso

La pieza de código limpio, del día 5, separa qué parte del código limpio se puede automatizar y qué sigue necesitando criterio. Puedes ver el calendario completo en Arneses por arquitectura.

Fuentes

Consultadas el 16 de octubre de 2026:

  • Hooks: comprobaciones que se ejecutan solasTécnica

    Comandos que se ejecutan automáticamente en momentos concretos del trabajo del agente, como antes de editar un archivo o al terminar, para que los pasos importantes no dependan de que el agente se acuerde.

    Publicado
  • Verificación y evaluaciónTécnica

    Cómo comprobar que el agente hizo bien el trabajo sin fiarte de su palabra: darle formas de verificarse a sí mismo, revisar el resultado y el proceso, y comparar configuraciones con honestidad.

    Publicado