Piece: clean code
A duplicate code detector that warns without blocking, seven short rules for AGENTS.md, and a review skill. It separates the part of clean code you can automate from the part that still needs judgment.
Before you start
- Piece: qualityHarness
Two hooks and a few ESLint rules that keep formatting, lint, types, and tests passing without asking the agent. It comes from the layered harness and works in any harness of the series.
Published
The key idea: part of clean code can be automated and part cannot. A tool, jscpd, finds copied code, and a hook shows it to the agent as a warning, not a block. What no tool measures well, such as names or what each function does, goes into seven short rules in
AGENTS.mdand a review skill that the agent follows before it delivers.
What problem it prevents
An agent writes code fast, and haste brings three habits:
- Rewriting what already exists. The agent has not read the whole project, so it writes a second version of a function that was already in another file. It works, but now the same rule lives in two places, and a future change may reach only one.
- Copy and paste. For a feature that looks like another one, it copies the whole block and changes a couple of things.
- Merging what only looks alike. This is the opposite mistake. The agent sees two similar blocks and merges them into one function with a parameter to tell the cases apart. That function ends up harder to understand than the two copies.
The DRY principle (“don’t repeat yourself”) is often read as “don’t repeat text”, but it is about knowledge. In an interview with Artima, Dave Thomas, one of the authors of The Pragmatic Programmer, explains that each rule of the system should have a single place where it lives. Two identical blocks that stand for different rules do not break DRY. And Sandi Metz, in “The Wrong Abstraction”, argues that copying code costs much less than choosing the wrong abstraction.
Think of a metal detector on the beach. It beeps at any metal object, a ring or a bottle cap. Deciding whether to dig is up to you. jscpd is that detector: it finds the copies, but it does not know which ones matter. That is why this piece warns instead of blocking, and leaves the rest to a few short rules and a review.
What files it adds
| Part | Files | What it does |
|---|---|---|
| Duplicate detector | .jscpd.json and the check:duplicates script |
Runs jscpd on the folders named in the script. It reports copies of at least 5 lines and 50 tokens, and never fails. |
| Warning at the stop | .agents/hooks/report-duplicates-before-stop.mjs |
When the agent tries to finish, runs jscpd on the folders of the check:duplicates script and reports each new duplicate once, with code 2. If the agent tries again, it lets it finish. |
| Review before delivering | .agents/skills/clean-code-review/SKILL.md |
The steps the agent follows before it says it is done: duplicates, names, responsibilities, and the scope of the change. |
| Instructions | The Clean code section of AGENTS.md |
Seven rules, few on purpose. |
| Tests | test/ |
Run the hook the way an agent does, against small fake projects, and check what it reports and its exit code. |
A hook is a command that the agent’s tool runs on its own at a specific moment; the Hooks topic explains it. A skill is a procedure that the agent loads only when it needs it; the Skills topic explains it.
Why a warning and not a block
jscpd counts tokens (the words, symbols, and numbers in the code) and looks for repeated runs. It does not know whether two copies stand for the same rule. If the hook blocked, the agent could only finish by merging the copies, even when merging them is worse.
The problem is that a stop hook can only do two things: let the agent finish or send it back to work. I looked in the docs of Claude Code, Codex, and Cursor for a way to leave the agent a message without sending it back, and I found none. In Claude Code, the additionalContext field of the stop hook gives feedback without marking it as an error, but the conversation also goes on. Codex and Cursor only describe blocking or sending a follow-up message.
So the hook sends the agent back once per duplicate:
- The first time it finds a duplicate, it writes the list to stderr and exits with code 2. The agent keeps working and decides what to do with each copy.
- If the agent decides to keep the copy and tries to finish again, the hook lets it: that duplicate was already reported.
- It remembers the reported duplicates in
node_modules/.cache/report-duplicates/reported.json, the usual cache folder of Node tools, which git already ignores. It identifies each duplicate by its two files and its code, not by line numbers, so a line added above it does not make it new. - It only remembers duplicates that still exist. If one disappears and comes back, it reports it again. To see every warning again, delete that folder.
- If jscpd cannot run, for example because it is not installed or because the
check:duplicatesscript does not start withjscpd, the hook also exits with code 2: a check that does not run should not pass in silence.
jscpd has options to fail, threshold (a maximum percentage of duplicated code) and exitCode. They are useful in continuous integration, but the piece does not use them.
How jscpd works
- It splits the code into tokens and looks for repeated runs of at least 50 tokens and 5 lines, its defaults. In its normal mode it ignores spaces and line breaks, so a reformatted copy still counts.
- It compares tokens, so it does not see the same logic written with other names. Rule 1 and the skill ask the agent to look for that.
- The piece uses jscpd 4.3.0. Since version 5, jscpd has a Rust engine and runs a native binary for each system, which cannot run in StackBlitz, where the series runs its tests in the browser. I checked the code of its launcher: it has no JavaScript fallback. It is the same reason I chose secretlint over gitleaks on day 3.
npm auditshows 5 high-severity findings after installing jscpd 4. They all come from one flaw inbraces, a dependency that arrives throughfast-glob, published on September 18, 2026, with no fixed version. A deeply nested brace pattern can crash the process. Here the patterns come from your ownpackage.jsonand.jscpd.json, not from anyone outside.- The folders it scans go in the script (
jscpd src), not in.jscpd.json. On Windows, with the folder written in the config file, jscpd 4.3.0 found no files: it turns the path into an absolute one and then does not match it. With the folder in the command it works. The hook reads the folders from that same script and starts jscpd withnode, without going through npm, which added about 0.7 seconds to every run.
In the layered harness, the script scans only src/. I ran jscpd over the whole harness to see what would happen: it found 7 duplicates, 4 among the hook scripts and 3 in the tests. The hook ones are on purpose: each piece brings its own copy of the code that runs npm and collects the errors, so it works on its own. They are a good example of a duplicate worth keeping.
The seven rules in AGENTS.md
How many rules fit in an AGENTS.md before it gets crowded? No documentation gives a number of rules, but they all point the same way:
- The Claude Code docs recommend files under 200 lines. They say that a file that is too long makes the agent ignore part of the instructions, and that obvious practices such as “write clean code” are not worth writing.
- The Codex docs say that a short, accurate
AGENTS.mdis more useful than a long one full of vague rules, and by default Codex stops reading instructions once together they pass 32 KiB. - The Cursor docs recommend rules under 500 lines and starting with a few.
- A 2025 study, “How Many Instructions Can LLMs Follow at Once?”, measured that models follow fewer instructions as they get more, and follow the first ones better. Its task was synthetic (writing reports with required words), so it is only a hint.
That is why the section has seven rules, each one concrete and checkable by reading the code:
| Rule | Why it is there |
|---|---|
| 1. Look for a function that already does the job before writing a new one | It is the kind of duplication jscpd cannot see: the same logic written again with other names. |
| 2. Use the words of the domain and avoid vague names | No tool knows whether data or handle says anything. Concrete examples (book, member, loan) work better than “use good names”. |
| 3. A function does one thing | The “and” test: if you need “and” to describe it, split it. ESLint already measures size in the quality piece; this measures something else. |
| 4. Do not merge what only looks alike | The counterweight to DRY: extract a shared function when the copies hold the same rule and would change together. If that function would need a parameter to know who is calling it, keep the copies. |
| 5. Write only what the task needs | Anthropic’s prompting guide warns that some of its models tend to over-engineer: extra files, unnecessary abstractions, or flexibility nobody asked for. |
| 6. The duplicate warning | Explains what the hook does, that it is a warning, and what the agent must not touch to hide a duplicate. |
| 7. Follow the skill before delivering | Takes the agent to the review without copying its steps into AGENTS.md. |
I left out what another piece already does (formatting and the size of functions), the obvious (“write clean code”), and what only matters sometimes, which goes into the skill. How to choose what goes into the agent’s context is explained in Context engineering.
The review skill
The clean-code-review skill has six steps: duplicates (run npm run check:duplicates and look for the same logic with other names), names, responsibilities, scope, verify again, and tell the user which duplicates it kept and why.
It is a skill and not a rule because it is only needed at the end. At the start, the agent loads only its name and description; it reads the rest when it uses it. That way the review takes no room in AGENTS.md.
The plan also considered a reviewer subagent. A subagent would review with a clean context, without what the agent already believes about its own code, and that is an advantage. But each agent defines subagents in a different format, and the series covers them on day 7. The Claude Code docs also warn about a risk: a reviewer asked to find problems almost always finds some, and chasing all of them leads to over-engineering. That is why the skill starts by saying to change only what is clearly better.
The explorer
On load, the explorer opens AGENTS.md. The piece has no mini app: only its settings, its hook, its skill, and the tests of the hook. Dependencies and package-lock.json are not shown.
.agents/hooks/report-duplicates-before-stop.mjs
// Stop hook: connect it to your agent's stop event, the moment the agent is about to finish.
// It runs jscpd on the folders named in the `check:duplicates` script and reports the duplicated
// blocks it has not reported before. Duplicated code is sometimes the right choice, so this is a
// warning, not a gate: each duplicate is reported once. The first time, the hook prints the list to
// stderr and exits with code 2, which agents that follow this convention read as "not done yet". If
// the agent decides to keep a duplicate and tries to finish again, the hook lets it. Exit code 0
// with no output means there is nothing new to report.
//
// 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 check does not depend on it.
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } 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, '..', '..');
// node_modules/.cache/ is where Node tools usually keep their caches, and git already ignores it.
// The JSON report and the list of reported duplicates live there, out of the agent's way.
const CACHE_DIR = 'node_modules/.cache/report-duplicates';
const REPORT_FILE = path.join(projectDir, CACHE_DIR, 'jscpd-report.json');
const REPORTED_FILE = path.join(projectDir, CACHE_DIR, 'reported.json');
const JSCPD = path.join(projectDir, 'node_modules', 'jscpd', 'bin', 'jscpd');
const CHECK_TIMEOUT_MS = 60_000;
const MAX_LISTED = 10;
const problem = runJscpd();
if (problem !== null) {
// A check that cannot run must not pass in silence. The usual cause is a missing install or a
// folder in check:duplicates that does not exist.
process.stderr.write(
`Could not run the duplicate check (\`npm run check:duplicates\`).\n${problem}\n` +
'Fix the setup, or tell the user if you cannot.\n',
);
process.exitCode = 2;
} else {
const duplicates = readDuplicates();
const reported = readReported();
const fresh = duplicates.filter((duplicate) => !reported.has(duplicate.id));
// Only the duplicates that still exist are remembered. If one is removed and comes back later, it
// is reported again.
writeReported(duplicates.map((duplicate) => duplicate.id));
if (fresh.length > 0) {
process.stderr.write(warning(fresh));
process.exitCode = 2;
}
}
// The folders come from the check:duplicates script in package.json (for example `jscpd src`), so
// the hook and the command a person runs always scan the same code. The hook starts jscpd with node
// instead of npm, which added about 0.7 seconds to every run. Returns null when the report is ready,
// or the reason it is not.
function runJscpd() {
const [command, ...args] = readCheckDuplicatesScript();
if (command !== 'jscpd') {
return 'The check:duplicates script in package.json must run jscpd, for example `jscpd src`.';
}
rmSync(REPORT_FILE, { force: true });
const reportArgs = ['--silent', '--reporters', 'json', '--output', CACHE_DIR];
const result = spawnSync(process.execPath, [JSCPD, ...args, ...reportArgs], {
cwd: projectDir,
encoding: 'utf8',
timeout: CHECK_TIMEOUT_MS,
});
if (result.status === 0 && existsSync(REPORT_FILE)) {
return null;
}
return [result.stdout, result.stderr, result.error?.message].filter(Boolean).join('\n').trim();
}
function readCheckDuplicatesScript() {
try {
const packageJson = JSON.parse(readFileSync(path.join(projectDir, 'package.json'), 'utf8'));
return String(packageJson.scripts?.['check:duplicates'] ?? '')
.trim()
.split(/\s+/);
} catch {
return [];
}
}
// Each duplicate gets an id from its two files and its code, not its line numbers, so an edit
// above it does not make it new.
function readDuplicates() {
const report = JSON.parse(readFileSync(REPORT_FILE, 'utf8'));
return report.duplicates.map((duplicate) => {
const first = location(duplicate.firstFile);
const second = location(duplicate.secondFile);
const files = [first.file, second.file].sort().join('\n');
const id = createHash('sha256').update(`${files}\n${duplicate.fragment}`).digest('hex');
return { id, first, second, lines: duplicate.lines };
});
}
// jscpd writes paths with the separator of the operating system. The agent gets forward slashes.
function location(file) {
return { file: file.name.replaceAll('\\', '/'), start: file.start, end: file.end };
}
function readReported() {
try {
return new Set(JSON.parse(readFileSync(REPORTED_FILE, 'utf8')));
} catch {
return new Set();
}
}
function writeReported(ids) {
mkdirSync(path.dirname(REPORTED_FILE), { recursive: true });
writeFileSync(REPORTED_FILE, `${JSON.stringify(ids, null, 2)}\n`);
}
function warning(fresh) {
const lines = [
'Duplicated code: a warning, not a failure. jscpd found the same code in more than one place:',
'',
];
for (const { first, second, lines: count } of fresh.slice(0, MAX_LISTED)) {
lines.push(
`- ${first.file}:${first.start}-${first.end} and ${second.file}:${second.start}-${second.end} (${count} lines)`,
);
}
if (fresh.length > MAX_LISTED) {
lines.push(`- and ${fresh.length - MAX_LISTED} more. Run \`npm run check:duplicates\`.`);
}
lines.push(
'',
'Look at each one before you finish:',
'- If both copies hold the same rule and would change together, move it into one function and call it from both places.',
'- If they only look alike, or a shared function would need a flag or extra parameters to tell its callers apart, keep the copies.',
'Tell the user which duplicates you kept and why. Each duplicate is reported once: when you try to finish again, this hook lets you.',
'',
);
return lines.join('\n');
}.agents/skills/clean-code-review/SKILL.md
---
name: clean-code-review
description: Review your own changes for duplicated code, names and responsibilities before you say a task is done. Use at the end of any task that added or changed code, or when the user asks for a clean-code review.
---
# Clean-code review
Review only the code this task changed. List it with `git status` and `git diff`. Change only what is clearly better: a review that adds layers, helpers or defensive code that nobody asked for makes the code worse.
1. **Duplicates.** Run `npm run check:duplicates`. jscpd only finds copies with the same tokens, so it misses the same logic written with other names. For each function you added, search the code for its main domain word (for example, `grep -rn "loan" src`) and read what is already there. For each duplicate, extract a shared function only if both copies hold the same rule and would change together. If they only look alike, or a shared function would need a flag or extra parameters to tell its callers apart, keep the copies.
2. **Names.** Each new file, function and variable says what it is or does, with the words of the domain (book, member, loan). Rename vague names such as `data`, `info`, `item`, `handle`, `process`, `utils` or `temp`. A boolean reads as a question: `isAvailable`, `hasActiveLoans`.
3. **Responsibilities.** Each new function does one thing. If you need "and" to describe it, split it. Keep each part in the folder where the project's `AGENTS.md` says it goes.
4. **Scope.** Remove what the task did not ask for: unused parameters and options, abstractions written for a future need, commented-out code, and changes to files the task did not need.
5. **Verify.** If you changed anything, run `npm run verify` again.
6. **Report.** Tell the user in a few lines what this review changed, and which duplicates you kept and why.test/report-duplicates-before-stop.test.ts
import { spawn } from 'node:child_process';
import { copyFileSync, mkdirSync, mkdtempSync, 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, then read its exit code and stderr. Each
// test copies the hook and .jscpd.json into a small fake project in the system's temporary folder
// and writes some source files. The hook runs the real jscpd installed in this project. The folders
// are deleted at the end.
const hook = fileURLToPath(
new URL('../.agents/hooks/report-duplicates-before-stop.mjs', import.meta.url),
);
const jscpdConfig = fileURLToPath(new URL('../.jscpd.json', import.meta.url));
const jscpdBin = fileURLToPath(new URL('../node_modules/jscpd/bin/jscpd', import.meta.url));
const projectDirs: string[] = [];
// A function that validates a text field, and the same function copied under another name. jscpd
// sees the copy: only the function name changed.
const READ_TITLE = `export function readTitle(input: unknown): string {
if (typeof input !== 'string') {
throw new Error('The value must be text');
}
const text = input.trim();
if (text.length === 0 || text.length > 200) {
throw new Error('The value must have between 1 and 200 characters');
}
return text;
}
`;
const READ_NAME_COPY = READ_TITLE.replace('readTitle', 'readName');
// The same logic with every name and message changed. jscpd compares tokens, so it does not see it.
const READ_NAME_RENAMED = `export function readName(value: unknown): string {
if (typeof value !== 'string') {
throw new Error('A name is text');
}
const name = value.trim();
if (name.length === 0 || name.length > 200) {
throw new Error('A name has between 1 and 200 characters');
}
return name;
}
`;
const COUNT_LOANS = `export function countActiveLoans(loans: { returnedAt: string | null }[]): number {
return loans.filter((loan) => loan.returnedAt === null).length;
}
`;
function createProject(checkDuplicates = 'jscpd src'): string {
const projectDir = mkdtempSync(path.join(tmpdir(), 'duplicates-hook-'));
projectDirs.push(projectDir);
mkdirSync(path.join(projectDir, '.agents', 'hooks'), { recursive: true });
copyFileSync(
hook,
path.join(projectDir, '.agents', 'hooks', 'report-duplicates-before-stop.mjs'),
);
copyFileSync(jscpdConfig, path.join(projectDir, '.jscpd.json'));
const scripts = { 'check:duplicates': checkDuplicates };
writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify({ private: true, scripts }));
// The hook runs node_modules/jscpd/bin/jscpd of its own project. In the fake project, that file
// loads the jscpd installed in this one.
const binDir = path.join(projectDir, 'node_modules', 'jscpd', 'bin');
mkdirSync(binDir, { recursive: true });
writeFileSync(path.join(binDir, 'jscpd'), `require(${JSON.stringify(jscpdBin)});\n`);
mkdirSync(path.join(projectDir, 'src'));
return projectDir;
}
function writeSource(projectDir: string, name: string, content: string): void {
writeFileSync(path.join(projectDir, 'src', name), content);
}
// 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 the 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', 'report-duplicates-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('{}');
});
}
afterAll(() => {
for (const projectDir of projectDirs) {
rmSync(projectDir, { recursive: true, force: true });
}
});
// Each run starts jscpd, which takes about a second on a computer and much longer in StackBlitz,
// so the timeout is longer than usual. The hook starts jscpd without npm, which keeps each run light
// enough to run the tests at the same time there too.
describe.concurrent('report-duplicates-before-stop hook', { timeout: 120_000 }, () => {
it('passes in silence when there is no duplicated code', async ({ expect }) => {
const projectDir = createProject();
writeSource(projectDir, 'books.ts', READ_TITLE);
writeSource(projectDir, 'loans.ts', COUNT_LOANS);
const result = await runHook(projectDir);
expect(result.stderr).toBe('');
expect(result.code).toBe(0);
});
it('reports a copied function once, with code 2 and both locations', async ({ expect }) => {
const projectDir = createProject();
writeSource(projectDir, 'books.ts', READ_TITLE);
writeSource(projectDir, 'members.ts', READ_NAME_COPY);
const first = await runHook(projectDir);
// The agent keeps the copy and tries to finish again: the hook lets it.
const second = await runHook(projectDir);
expect(first.code).toBe(2);
expect(first.stderr).toContain('Duplicated code: a warning, not a failure.');
expect(first.stderr).toMatch(/src\/books\.ts:\d+-\d+/);
expect(first.stderr).toMatch(/src\/members\.ts:\d+-\d+/);
expect(first.stderr).toContain('Each duplicate is reported once');
expect(second.stderr).toBe('');
expect(second.code).toBe(0);
});
it('reports a new duplicate, and a duplicate that was removed and comes back', async ({
expect,
}) => {
const projectDir = createProject();
writeSource(projectDir, 'books.ts', READ_TITLE);
writeSource(projectDir, 'members.ts', READ_NAME_COPY);
await runHook(projectDir);
// The copy in members.ts goes away and a new one appears in authors.ts.
writeSource(projectDir, 'members.ts', COUNT_LOANS);
writeSource(projectDir, 'authors.ts', READ_TITLE.replace('readTitle', 'readAuthor'));
const fresh = await runHook(projectDir);
// The copy in members.ts comes back.
writeSource(projectDir, 'members.ts', READ_NAME_COPY);
const back = await runHook(projectDir);
expect(fresh.code).toBe(2);
expect(fresh.stderr).toMatch(/src\/authors\.ts:\d+-\d+/);
expect(fresh.stderr).not.toContain('src/members.ts');
expect(back.code).toBe(2);
expect(back.stderr).toMatch(/src\/members\.ts:\d+-\d+/);
});
// A limit of jscpd, not of the hook: the clean-code-review skill asks the agent to look for this.
it('does not see the same logic written with other names', async ({ expect }) => {
const projectDir = createProject();
writeSource(projectDir, 'books.ts', READ_TITLE);
writeSource(projectDir, 'members.ts', READ_NAME_RENAMED);
const result = await runHook(projectDir);
expect(result.stderr).toBe('');
expect(result.code).toBe(0);
});
it('fails with code 2 when the duplicate check cannot run', async ({ expect }) => {
const projectDir = createProject('jscpd missing-folder');
writeSource(projectDir, 'books.ts', READ_TITLE);
const result = await runHook(projectDir);
expect(result.code).toBe(2);
expect(result.stderr).toContain('Could not run the duplicate check');
expect(result.stderr).toContain('missing-folder');
});
});.gitignore
node_modules/.jscpd.json
{
"format": ["typescript", "javascript"],
"minTokens": 50,
"minLines": 5,
"noTips": true
}AGENTS.md
# AGENTS.md
## Project
This folder is the **clean-code piece** of the Agent Atlas harness series. It is not an app: it holds the settings of the duplicate detector (jscpd), a stop hook, a review skill and the tests of the hook, 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 `Clean code` section below is the one to paste into the `AGENTS.md` of a harness. It has seven rules on purpose: each rule added to this file makes the others easier to miss.
## Clean code
- Before you write a new function, search the code for one that already does the job, and reuse it.
- Name files, functions and variables with the words of the domain (book, member, loan). Do not use vague names such as `data`, `info`, `handle` or `utils`.
- A function does one thing. If you need "and" to describe what it does, split it.
- Do not merge code only because it looks alike. Extract a shared function when the copies hold the same rule and would change together. If the shared function would need a flag or extra parameters to tell its callers apart, keep the copies.
- Write only what the task needs: no options, parameters or abstractions for later, and no changes to code the task does not touch.
- When you try to finish, the hook `.agents/hooks/report-duplicates-before-stop.mjs` runs jscpd on the folders of the `check:duplicates` script and lists the duplicated blocks it has not reported before. It is a warning: decide on each one with the rule above and tell the user which ones you kept. Never edit `.jscpd.json`, the `check:duplicates` script or the hook to hide a duplicate.
- Before you say a task is done, follow the skill `clean-code-review` (`.agents/skills/clean-code-review/SKILL.md`).
## Files
| File | What it does |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `.agents/hooks/report-duplicates-before-stop.mjs` | Runs when the agent tries to finish and reports each new duplicated block once (exit code 2), then lets it finish |
| `.agents/skills/clean-code-review/SKILL.md` | The review steps before a task is done: duplicates, names, responsibilities and scope |
| `.jscpd.json` | The jscpd settings: which languages it reads and how long a copy must be to count |
| `test/` | Runs the hook the way an agent does, against small fake projects, and checks what it reports and its exit codes |
## Verification
Run these from this folder:
- `npm run typecheck`: TypeScript, for the tests.
- `npm test`: the tests of the hook.
- `npm run verify`: both, in that order.
- `npm run check:duplicates`: jscpd on this folder's code. It reports duplicates but never fails, so it is not part of `verify`.package.json
{
"name": "harness-piece-clean-code",
"private": true,
"type": "module",
"engines": {
"node": ">=22"
},
"scripts": {
"test": "vitest run",
"typecheck": "tsc --noEmit",
"check:duplicates": "jscpd .agents test",
"verify": "npm run typecheck && npm test"
},
"devDependencies": {
"@types/node": "22.20.5",
"jscpd": "4.3.0",
"typescript": "5.9.3",
"vitest": "5.0.4"
}
}README.md
# Clean-code piece
A reusable part of the Agent Atlas harness series. It separates the part of clean code that a tool can check from the part that still needs judgment. A tool, jscpd, finds copied code and a stop hook shows it to the agent as a warning. Short rules in `AGENTS.md` and a review skill cover names, responsibilities and scope, which no tool checks well.
It is not an app. It holds the settings, a hook, a skill and the tests of the hook, so you can check the hook before you copy it into a harness. The [layered harness](../layered/) already includes it.
## Run it
```bash
npm install
npm run verify
```
## What it adds to a harness
| Part | Files | What it does |
| ------------------------ | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Duplicate check | `.jscpd.json`, the `check:duplicates` script | Runs jscpd on the folders named in the script. It reports copies of at least 5 lines and 50 tokens, and never fails. |
| Duplicate warning | `.agents/hooks/report-duplicates-before-stop.mjs` | When the agent tries to finish, runs jscpd on the folders of the `check:duplicates` script and reports each new duplicate once (exit code 2). When the agent tries to finish again, it lets it. |
| Review before delivering | `.agents/skills/clean-code-review/SKILL.md` | The steps the agent follows before it says a task is done: duplicates, names, responsibilities and scope. |
| Instructions | The `Clean code` section of `AGENTS.md` | Seven rules, on purpose: each rule added to the file makes the others easier to miss. |
The hook follows the same contract as the rest of the series: it finds the project root from its own location, reads no agent-specific environment variable, and reports with exit code 2 and the reason on stderr. Exit code 0 with no output means "go on".
The hook reads the folders to scan from the `check:duplicates` script, which must start with `jscpd`, so the hook and the command you run scan the same code. It starts jscpd with `node` instead of `npm run`, which added about 0.7 seconds to every run.
Duplicated code is sometimes the right choice, so the hook is a warning, not a gate. A stop hook can only let the agent finish or send it back, so the hook sends it back once per duplicate. It remembers the duplicates it reported in `node_modules/.cache/report-duplicates/reported.json`, by their files and their code, not their line numbers. A duplicate that is removed and comes back is reported again. Delete that folder to see every duplicate again.
## Add it to a harness
1. Copy `.agents/hooks/report-duplicates-before-stop.mjs`, `.agents/skills/clean-code-review/SKILL.md`, `.jscpd.json` and `test/report-duplicates-before-stop.test.ts` into the harness.
2. Install jscpd with `npm install --save-dev --save-exact jscpd@4.3.0`. The tests also need TypeScript and Vitest.
3. Add the script `"check:duplicates": "jscpd src"` to `package.json`, with the folders that hold the app's code. It has to start with `jscpd`, because the hook reads the folders from it. In this folder the script scans `.agents` and `test`, because the piece has no `src`. Do not add it to `verify`: it never fails.
4. Paste the `Clean code` section of `AGENTS.md` into the harness's `AGENTS.md`.
5. Connect the hook to your agent (next section). Connect the skill too if your agent does not read `.agents/skills/`.
6. Run `npm run verify` and `npm run check:duplicates`.
## Connect it to your agent
Agents do not share a settings format, so the hook in `.agents/` does nothing on its own. Register `node .agents/hooks/report-duplicates-before-stop.mjs` on the event that runs when the agent is about to finish.
Some agents read skills from `.agents/skills/`. Others read them from their own folder, so the skill has to be copied there.
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/clean-code/>.
## Why jscpd 4
jscpd 5 has a Rust engine and runs a native binary for each platform. That binary cannot run in StackBlitz, where the series runs its tests in the browser. jscpd 4.3.0 (npm tag `latest-4`) is plain JavaScript.
`npm audit` reports 5 high-severity findings after the install. They all come from one advisory in `braces` (GHSA-vfj7-8cjw-p6xm), which jscpd 4 loads through `fast-glob` and `micromatch`. A deeply nested brace pattern can crash the process. Here the patterns come from your own `package.json` and `.jscpd.json`, not from outside input. No fixed version of `braces` exists yet.
## Checks
| Command | What it checks |
| -------------------------- | ------------------------------------------------------ |
| `npm run typecheck` | TypeScript types of the tests |
| `npm test` | The hook, run the way an agent runs it |
| `npm run verify` | Both, in order |
| `npm run check:duplicates` | jscpd on this folder's code (a report, it never fails) |
## Limits
- jscpd compares tokens. It finds copied code even with other spacing or line breaks, but not the same logic written with other names. The review skill asks the agent to look for that.
- jscpd only sees the size of a copy. It cannot tell a duplicate that should be one function from two pieces of code that only look alike. That is the agent's call, or yours.
- Names, responsibilities and scope are not checked by any tool here. The rules and the skill are instructions, not barriers.
- Nothing technical stops the agent from editing `.jscpd.json`, the script or the hook to hide a duplicate. `AGENTS.md` forbids it.
- A duplicate reported once is not reported again, even in a later session, while it exists.tsconfig.json
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"noEmit": true,
"types": ["node"],
"skipLibCheck": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true
},
"include": ["test"]
}How to use it
You can run the tests of the piece in the browser or on your machine.
In the browser, the Run in the browser button opens the piece in StackBlitz, an external service, in a new tab. StackBlitz installs the dependencies and runs npm test: 5 tests that run the hook against fake projects with the real jscpd. On October 18, 2026, I tested it in Chromium 152 with the “Open StackBlitz in this tab” button: all 5 tests passed, and its terminal measured 28 s to install the dependencies and run them. I did not test it in Firefox or Safari, or with the new-tab button.
StackBlitz is an external service and opens in a new tab. It works best in Chrome and Edge; in Firefox and Safari it is in beta. The first run takes a while because it installs the dependencies.
On your machine you need Node 22 or later. Copy the files of the piece into a folder and run, with npm:
npm install
npm run verify
npm run check:duplicates
npm run verify checks the types of the tests and runs the 5 tests. npm run check:duplicates runs jscpd over the code of the piece; since the piece has no src/, here it scans .agents and test.
Add it to a harness
- Copy
.agents/hooks/report-duplicates-before-stop.mjs,.agents/skills/clean-code-review/SKILL.md,.jscpd.json, andtest/report-duplicates-before-stop.test.tsinto the harness. - Install jscpd with
npm install --save-dev --save-exact jscpd@4.3.0. The tests also need TypeScript and Vitest. - Add the script
"check:duplicates": "jscpd src"topackage.json, with the folders that hold the app’s code. It has to start withjscpd, because the hook reads the folders from it. Do not add it toverify: it never fails, so it checks nothing there. - Paste the
Clean codesection of the piece’sAGENTS.mdinto the harness’sAGENTS.md. - Connect the hook to your agent, and the skill too if your agent does not read
.agents/skills/. The next section explains how. - Run
npm run verifyandnpm run check:duplicates.
That is how I added it to the layered harness. jscpd found no duplicates in its src/, so no code had to change. The tests went from 65 to 70, and the harness now has four stop hooks: architecture, secrets, quality, and duplicates.
On day 6 I copied the piece without changes into the hexagonal harness: the same files and the same 5 tests. jscpd found no duplicates in its src/ either.
On day 7 I also copied it without changes into the modular monolith harness. jscpd found no duplicates in its src/, which there includes the loans module tests.
On day 8 I copied it without changes into the event-driven harness, with its review skill next to the new skill, add-event. jscpd found no duplicates in its src/ either.
Connect it to your agent
Each agent reads hooks and skills from its own settings. Those files are not in the piece: create them yourself in the harness folder. If you already connected other pieces, add this hook to the same settings.
Claude Code. In .claude/settings.json:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PROJECT_DIR}/.agents/hooks/report-duplicates-before-stop.mjs"],
"timeout": 120
}
]
}
]
}
}
- Claude Code does not read
.agents/skills/. Copy the.agents/skills/clean-code-review/folder to.claude/skills/clean-code-review/. - According to its docs, when a stop hook exits with code 2, the agent receives the stderr text and keeps working. It stops after 8 continuations in a row, but this hook does not get there: it reports each duplicate once.
Codex. It reads AGENTS.md and the skills in .agents/skills/ on its own. For the hook, in .codex/hooks.json:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node .agents/hooks/report-duplicates-before-stop.mjs",
"timeout": 120
}
]
}
]
}
}
As with the other pieces, open it in the harness folder and mark the hook as trusted with /hooks. Its docs say that, at the stop, it expects JSON on standard output when the hook exits with code 0; the script writes nothing in that case, and I could not check whether Codex accepts it.
Cursor. It reads AGENTS.md and the skills in .agents/skills/. Its stop hook expects JSON with followup_message on standard output, so this hook would need a small adapter, which I did not write.
I did not test any of these setups in a real session. They come from each agent’s docs, accessed on October 18, 2026.
What can be automated and what cannot
| What | What does it | Automated? |
|---|---|---|
| Copied code | jscpd in the stop hook | Yes, as a warning |
| The same logic written with other names | Rule 1 and the skill | No: jscpd does not see it |
| Whether a duplicate should be one function | The agent or you, with rule 4 | No |
| Long or tangled functions | ESLint in the quality piece | Yes: complexity, nesting, parameters, and lines |
| A function that does one thing | Rule 3 and the skill | Partly: ESLint measures size, not responsibility |
| Clear names | Rule 2 and the skill | No |
| Each thing in its layer | dependency-cruiser in the layered harness | Yes, for imports; not for where the logic lives |
| Code for a future nobody asked for | Rule 5 and the skill | No |
What was checked
What I tested on October 18, 2026, on Windows 11 with Node 24.19:
- In the piece,
npm run verifypassed: types and 5 of 5 tests. - In the layered harness, with the piece added,
npm run verifypassed: types, lint, formatting,no dependency violations found (15 modules, 39 dependencies cruised), secretlint, and 70 of 70 tests. - I duplicated code on purpose: I created
src/services/reservation-service.tsby copying fromLoanService.lendthe checks that the book and the member exist, as a hurried agent would. The hook exited with code 2 in about 1.3 seconds and wrotesrc/services/loan-service.ts:21-30 and src/services/reservation-service.ts:11-20 (10 lines). Run again, it exited with code 0 and wrote nothing. I added a line above the copy and it stayed at 0. I deleted the file: it exited with 0 and the list of reported duplicates was empty. - I copied the 6-line
readTextfunction fromhttp.tsintomembers-controller.tsunder another name. The hook did not report it: with the minimum of 50 tokens, jscpd does not see it. With a minimum of 30 it did find it, but in the original code it also flagged the end of two routes, inbooks-controller.tsandloans-controller.ts, which look alike but are not worth merging. I kept the minimum at 50. - One of the tests writes the same function with other names and checks that jscpd does not see it. It is a limit of jscpd, and the test keeps it on record.
- I ran the hook from another folder, as an agent that starts somewhere else does, with a simulated stop event on its input.
The times vary because the machine had other work running. The duplicate hook took about a second with nothing to report. The 5 new tests add to the quality hook, which runs every test on every stop: in the layered harness it took about 15 seconds with them and about 14 without them, measured the same day. The four stop hooks started at the same time, as Claude Code does, took about 15 seconds.
In StackBlitz, with Chromium 152 and the same-tab button, the piece’s 5 tests passed (28 s in its terminal), and so did the layered harness’s 70 (56 s). It did not work the first time:
- The first version of the hook ran
npm run check:duplicates. In StackBlitz each test took up to 55 seconds, and in the layered harness tests of other hooks ran out of time. Now the hook starts jscpd without npm: the piece’s tests went from 58 to 12 seconds in Vitest. - Even so, 5 or 6 tests of the security and quality pieces failed because they went over Vitest’s 5-second limit. I used the same button on the published site, with the October 16 harness and without this piece: 5 of 65 tests failed and, on a second try, 6, all of them by timeout on that second try. StackBlitz was slower than on that day. I raised the limit of those tests to 30 seconds in their three copies, and then they all passed: 39 of 39 in the security piece and 12 of 12 in the quality piece.
What I could not test: a real agent session. The machine’s Claude Code CLI (2.1.220) answered OAuth session expired and could not be refreshed. Codex said on October 15 that the account had reached its usage limit until November 2, so I did not try it. Cursor is not installed. I also did not ask an agent to do a task inside the harness.
Limitations
- jscpd finds copied code, not the same logic written with other names. With the minimum of 50 tokens it also misses short copies, such as a 6-line function.
- jscpd cannot tell whether two copies are the same rule or only look alike. That decision belongs to the agent or to you.
- No tool checks names, responsibilities, or the scope of a change. The rules and the skill are instructions, not barriers.
- Nothing technical stops the agent from changing
.jscpd.json, the script, or the hook to hide a duplicate.AGENTS.mdforbids it. - A duplicate that was reported is not reported again while it exists, even in a later session.
- The 5 tests of the hook are added to
npm test, which the quality hook runs on every stop. In the layered harness they added about a second to every stop. - I only tested it on Windows 11 with Node 24.19.
Next step
With this piece, the layered harness has all three reusable pieces: security, quality, and clean code. The hexagonal harness, from day 6, reuses all three as they are; only the architecture part changes. So do the modular monolith harness, from day 7, and the event-driven harness, from day 8. The guide to choosing a harness compares them.
Sources
Accessed on October 18, 2026:
- jscpd, official repository. The master-v4 branch has the code and docs of version 4.
- Clone types, jscpd docs. Explains which copies it detects and which it does not.
- GHSA-vfj7-8cjw-p6xm, security advisory for
braces. - Troubleshooting, docs of WebContainers, the runtime behind StackBlitz.
- Hooks reference, Claude Code docs.
- How Claude remembers your project and Best practices, Claude Code docs.
- Skills, Claude Code docs.
- Claude prompting best practices, Anthropic guide.
- Hooks, Custom instructions with AGENTS.md, and Best practices, Codex docs.
- Hooks, Rules, and Skills, Cursor docs.
- Specification, Agent Skills open format.
- How Many Instructions Can LLMs Follow at Once?, Jaroslawicz et al., 2025.
- Orthogonality and the DRY Principle, Bill Venners interviews Dave Thomas, 2003.
- The Wrong Abstraction, Sandi Metz, 2016.
Related content
- Context engineering for agentsTechnique
What information the agent receives at each moment, why more is not always better, and how to give it just enough: the essentials up front and the rest when it needs them.
Published - Skills: reusable procedures for agentsTechnique
A folder with instructions, and optionally scripts and references, that teaches the agent one specific kind of task. It is only loaded when needed.
Published