{"version":"0.1.0","categories":{"slop":"AI tells","errors":"Error handling","types":"Type safety","tests":"Tests and CI","perf":"Performance","security":"Security","design":"Design","async":"Async","react":"React","hygiene":"Hygiene","custom":"Your rules"},"templates":[{"id":"fix","title":"Fix these findings","body":"Fix the review findings below.\n\nFor each one: read the code around it, confirm the problem is real, and make the smallest change that removes the cause (not the symptom). If a finding is wrong, leave the code and say why in one line. Run the tests after each file. Do not add fallbacks, compatibility shims or comments that narrate the change."},{"id":"lint-rule","title":"Fix, then add a check","body":"Fix each finding below, then write the check that would have caught it: a lint rule, a test, or a type that makes the bad version impossible. Prefer one check that covers the whole class over one per instance."},{"id":"sweep","title":"Sweep one defect class","body":"The findings below are instances of a few defect classes. For each class, find every instance in the codebase (not just these), fix them in one uniform pass, and list what you changed. Stop and ask if a fix would change behavior."},{"id":"staff-audit","title":"Adversarial Staff+ audit","body":"Act as a Staff+ engineer and security researcher doing an adversarial review. Ground rules: no filler or lint, trace across boundaries, verify before claiming, back every claim with file:line and a concrete failure trace, rank by blast radius.\n\nCover: (1) the system's mental model, hidden assumptions and top 3 implicit invariants; (2) correctness: races, TOCTOU, non-atomic read-modify-write, missing idempotency, half-written state, lifecycle leaks, swallowed errors; (3) security and trust boundaries: authN/authZ, IDOR, tenant leaks, injection, SSRF, path traversal, unsafe deserialization, secrets in logs, CSRF/CORS/webhook gaps, DoS; (4) performance cliffs at 10x-100x: O(n^2), N+1, missing indexes, unbounded queries, lock contention, blocking I/O, retry storms, missing timeouts and backpressure; (5) architecture: wrong boundaries, leaky abstractions, god modules, duplicated sources of truth, failure-mode blind spots; (6) a top-5 fix order.\n\nFor each finding give Severity, Location, Root cause, Trigger, Blast radius and Minimal safe fix. Start from the static findings below; they are leads, not conclusions."},{"id":"first-principles","title":"First-principles challenge","body":"Study this project until you understand its purpose, requirements and constraints. Then imagine the code never existed. Could the same or better behavior come from far less complexity, fewer dependencies, lower cost and higher reliability?\n\nChallenge every assumption: which hard problems need not exist, which subsystems could be one simpler mechanism, which expensive operations could be removed rather than optimized, what existing technology already solves.\n\nDevelop three competing designs: radical simplicity, maximum performance, and the production ideal you would choose to build and maintain. Prove them with small isolated experiments, not argument. Compare each against today's design on functional coverage, complexity, latency, resources, cost, reliability and security, maintainability, extensibility and migration effort. Deliver: which decisions are necessary, which are avoidable, the single highest-leverage change, and a migration path that keeps behavior. Do not modify the project; do not invent benchmark numbers. The findings below are symptoms to explain."},{"id":"entropy","title":"Reduce architectural entropy","body":"Goal: reduce architectural entropy. Targets: one source of truth per fact, one canonical implementation per job, deep modules with small interfaces, high cohesion and low coupling, changes that stay local, deletion over accumulation, architecture that is enforced by checks.\n\nLoop: scan, find the entropy, read every caller, propose options, pick the simplest, take a test baseline, migrate fully, delete the old path, review, verify, add an anti-regression check. Apply the deletion test to every abstraction: if deleting it makes complexity vanish, delete it; if complexity spreads to callers, keep it."},{"id":"untangle","title":"Untangle the codebase","body":"Untangle this code: remove leaky abstractions, copy-pasted blocks, temporary workarounds that became permanent, and wrappers that only forward calls. Every change keeps behavior identical; prove it with the existing tests plus any test you need to add first."},{"id":"property-tests","title":"Property tests and invariants","body":"Turn every bug we have fixed into a property test. Find the implicit invariants in this code, then either prove each one or find a counterexample."},{"id":"state-machines","title":"Find implicit state machines","body":"Find every implicit state machine in this app: status strings, boolean pairs, flags that only make sense together. Make each one explicit (states, transitions, one place that owns them) where that improves the user experience, the developer experience and the agent experience at once, without breaking anything."},{"id":"perf","title":"Hot-path performance pass","body":"Do a performance pass on the hot paths:\n- Find every place that loads a whole database row to read a couple of fields, and select only what is needed.\n- Remove unnecessary `new URL()` parsing.\n- Compile regexes once at module level, never inside functions or loops.\n- Promote hot reads of one key from a large jsonb column to a real column; jsonb reads detoast the whole value.\n- Find sequential awaits on hot paths that could run in parallel.\nMeasure before and after; report the numbers you measured, not estimates."},{"id":"e2e","title":"End-to-end proof","body":"Prefer end-to-end tests as the way to prove these fixes. Write the E2E check first, watch it fail, then fix. At the end, produce a verifiable, repeatable artifact (a log, a screenshot, a recording or a report) that shows the fixed behavior."}],"rules":[{"id":"placeholder-code","title":"Placeholder instead of code","severity":"high","category":"slop","languages":["*"],"scope":"any","why":"Models elide code with `// ... existing code ...` or `# implementation here`. When that lands in a commit, the real code is gone or was never written.","fix":"Write the code, or restore what was cut. If it is future work, open an issue and leave no stub.","bad":"function save(user) {\n  // ... existing code ...\n}","good":"function save(user) {\n  return db.users.insert(user);\n}","lang":"ts","research":"placeholder-code","message":"A placeholder where code should be (existing code). Something was elided or never written.","detects":"pattern","source":{"name":"Stubs and elided code (`// ... existing code ...`, `raise NotImplementedError`, \"implementation here\")","why":"Code that looks finished and does nothing passes review and fails in use.","links":[{"label":"KarpeSlop","url":"https://github.com/CodeDeficient/KarpeSlop"},{"label":"Signs of AI code","url":"https://dev.to/funsize_engineer/signs-of-ai-code-48jd"},{"label":"14 patterns AI code generators get wrong","url":"https://dev.to/radpdx/14-patterns-ai-code-generators-get-wrong-and-how-to-catch-them-45l9"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/placeholder-code","examples":{"flagged":[{"path":null,"text":"function a() {\n  // ... existing code ...\n}"},{"path":"src/app.py","text":"def f():\n    # implementation goes here\n    pass\n"},{"path":null,"text":"// ..."}],"clean":[{"path":null,"text":"// Load the rest lazily.\nconst a = 1;"},{"path":null,"text":"const s = '...';"}]}},{"id":"stub-body","title":"Stubbed implementation","severity":"high","category":"slop","languages":["ts","py"],"scope":"prod","why":"A function that only throws `not implemented` passes type checks and review, then fails in production on the first call.","fix":"Implement it or delete it and its callers. Abstract methods belong on an ABC or interface.","bad":"export function refund(id: string) {\n  throw new Error(\"Not implemented\");\n}","good":"export function refund(id: string) {\n  return payments.refund(id);\n}","lang":"ts","research":"placeholder-code","message":"A stub (throw new Error(\"Not implemented) in shipped code. Callers will hit it at runtime.","detects":"pattern","source":{"name":"Stubs and elided code (`// ... existing code ...`, `raise NotImplementedError`, \"implementation here\")","why":"Code that looks finished and does nothing passes review and fails in use.","links":[{"label":"KarpeSlop","url":"https://github.com/CodeDeficient/KarpeSlop"},{"label":"Signs of AI code","url":"https://dev.to/funsize_engineer/signs-of-ai-code-48jd"},{"label":"14 patterns AI code generators get wrong","url":"https://dev.to/radpdx/14-patterns-ai-code-generators-get-wrong-and-how-to-catch-them-45l9"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/stub-body","examples":{"flagged":[{"path":null,"text":"function a() { throw new Error(\"Not implemented yet\"); }"},{"path":"src/app.py","text":"def f():\n    raise NotImplementedError\n"}],"clean":[{"path":null,"text":"function a() { throw new Error(\"Payment declined\"); }"}]}},{"id":"changelog-comment","title":"Change-log comment","severity":"medium","category":"slop","languages":["*"],"scope":"any","why":"Comments like `// Added retry` or `// now uses the new client` describe the diff, not the code. They are true for one commit and misleading forever after.","fix":"Delete it, or rewrite it to say why the code is the way it is. Put the history in the commit message.","bad":"// Updated to use the new retry helper\nawait withRetry(send);","good":"// The upstream drops the first request after idle, so retry once.\nawait withRetry(send);","lang":"ts","research":"changelog-comment","message":"This comment narrates the edit (// Added). Git already records what changed; the comment will be wrong after the next edit.","detects":"pattern","source":{"name":"Comments that narrate the edit or its history (\"Added retry\", \"now uses X\", \"previously\")","why":"They are true for one commit and wrong after the next, and git already holds the history.","links":[{"label":"Your AI code bias makes you a worse reviewer","url":"https://revelry.co/insights/artificial-intelligence/your-ai-code-bias-makes-you-a-worse-reviewer/"},{"label":"Signs of AI code","url":"https://dev.to/funsize_engineer/signs-of-ai-code-48jd"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/changelog-comment","examples":{"flagged":[{"path":null,"text":"// Added caching for speed\nconst c = new Map();"},{"path":"src/app.py","text":"# Fixed the bug with empty lists\nx = 1\n"},{"path":null,"text":"// now uses the shared client"}],"clean":[{"path":null,"text":"// Cache by id: lookups repeat within one request.\nconst c = new Map();"},{"path":null,"text":"const label = \"Added\";"}]}},{"id":"assistant-voice","title":"Chat voice in a comment","severity":"medium","category":"slop","languages":["*"],"scope":"any","why":"Comments addressed to the person who asked for the change ('I've added', 'feel free to') are pasted from an assistant's answer. They say nothing about the code.","fix":"Delete it, or state the fact the next reader needs.","bad":"// I've added a retry here so it works now","good":"// Retry once: the upstream drops idle connections.","lang":"ts","research":"assistant-voice","message":"This comment talks to the reader like a chat reply (I've).","detects":"pattern","source":{"name":"Chat voice and hedging in comments (\"let me\", \"feel free\", \"this should work\")","why":"It is leftover model talk that says nothing about the code.","links":[{"label":"KarpeSlop","url":"https://github.com/CodeDeficient/KarpeSlop"},{"label":"15 AI coding tools scored with a linter","url":"https://dev.to/yuvrajangadsingh/i-scored-15-ai-coding-tools-with-a-linter-the-gap-between-them-is-8x-3lp9"}],"notes":["skill: humanizer"]},"url":"https://redline.kevinliu.studio/rules/assistant-voice","examples":{"flagged":[{"path":null,"text":"// I've added a retry here"},{"path":"src/app.py","text":"# Here's the updated parser\n"},{"path":null,"text":"// Feel free to tweak this"}],"clean":[{"path":null,"text":"// Retry once: the upstream drops idle connections."},{"path":null,"text":"const msg = \"let me in\";"}]}},{"id":"stale-api","title":"Deprecated API","severity":"medium","category":"slop","languages":["ts","py"],"scope":"any","why":"Deprecated APIs still work today and print warnings, change behavior or disappear in the next major version.","fix":"Use the current API: `Buffer.from`, `new URL`, `datetime.now(UTC)`, `asyncio.run`, `slice`.","bad":"const b = new Buffer(str);","good":"const b = Buffer.from(str);","lang":"ts","research":"stale-api","message":"`new Buffer` is deprecated. Models trained on old code keep suggesting it.","detects":"pattern","source":{"name":"Deprecated APIs from older training data (`new Buffer()`, `url.parse`, `distutils`, `asyncio.get_event_loop()`)","why":"They warn, behave differently or are already gone in current runtimes.","links":[{"label":"5 code smells only AI creates","url":"https://dev.to/bzprchny/5-code-smells-only-ai-creates-and-how-to-detect-them-1e3l"},{"label":"The coding personalities of leading LLMs","url":"https://www.sonarsource.com/sem/the-coding-personalities-of-leading-llms/claude/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/stale-api","examples":{"flagged":[{"path":null,"text":"const b = new Buffer(s);"},{"path":"src/app.py","text":"from datetime import datetime\nt = datetime.utcnow()\n"}],"clean":[{"path":null,"text":"const b = Buffer.from(s);"}]}},{"id":"floating-model","title":"Floating model alias","severity":"medium","category":"slop","languages":["ts","py"],"scope":"any","why":"Aliases move to new snapshots without notice, so prompts, costs and outputs change with no code change.","fix":"Pin a dated model id and upgrade on purpose.","bad":"model: \"some-model-latest\"","good":"model: \"some-model-2026-06-01\"","lang":"ts","research":"llm-call-config","message":"A `-latest` alias (\"claude-sonnet-latest\"). The model behind it can change under you.","detects":"pattern","source":{"name":"Floating model aliases (`-latest`) and model calls with no timeout or token cap","why":"Behavior changes silently, and calls can hang or overspend.","links":[{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/floating-model","examples":{"flagged":[{"path":null,"text":"const m = \"claude-sonnet-latest\";"}],"clean":[{"path":null,"text":"const m = \"model-2026-06-01\";"}]}},{"id":"placeholder-value","title":"Placeholder value","severity":"medium","category":"slop","languages":["ts","py","c","sh"],"scope":"prod","why":"Generated code ships with `YOUR_API_KEY` and `your-domain.com` in it. It runs, then fails at the first real request.","fix":"Read the real value from config, and fail at startup when it's missing.","bad":"const BASE_URL = \"https://your-domain.com/api\";","good":"const BASE_URL = config.apiUrl;","lang":"ts","research":"placeholder-values","message":"A placeholder value (\"https://your-domain.com/api/YOUR_PROJECT_ID\") that was never filled in.","detects":"pattern","source":{"name":"Placeholder config values (`YOUR_API_KEY`, `changeme`, `your-domain.com`)","why":"They break at runtime or leak into production config.","links":[{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"},{"label":"KarpeSlop","url":"https://github.com/CodeDeficient/KarpeSlop"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/placeholder-value","examples":{"flagged":[{"path":null,"text":"const u = \"https://your-domain.com/api/YOUR_PROJECT_ID\";"},{"path":null,"text":"const k = \"changeme\";"}],"clean":[{"path":null,"text":"const u = config.apiUrl;"}]}},{"id":"versioned-name","title":"Versioned or boastful name","severity":"medium","category":"slop","languages":["ts","py","c"],"scope":"any","why":"`parseV2`, `fetchDataNew`, `enhancedSearch` mean a second copy was added beside the first instead of replacing it. Names should say what a thing does.","fix":"Replace the old version, delete it, and give the survivor the plain name.","bad":"export function fetchUserV2(id) { ... }","good":"export function fetchUser(id) { ... }","lang":"ts","research":"versioned-name","message":"`parseDataNew` names a version, not a meaning. The old one is still around, or soon nobody will know which is which.","detects":"pattern","source":{"name":"Versioned or boastful names (`saveV2`, `parseNew`, `EnhancedClient`)","why":"The name records how the code was edited instead of what it does, and it implies a second copy.","links":[{"label":"KarpeSlop","url":"https://github.com/CodeDeficient/KarpeSlop"}],"notes":["skill: code-review","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/versioned-name","examples":{"flagged":[{"path":null,"text":"function parseDataNew(x) {}"},{"path":null,"text":"const enhancedSearch = 1;"},{"path":"src/app.py","text":"def load_final(x):\n    return x\n"}],"clean":[{"path":null,"text":"const newValue = 1;"},{"path":null,"text":"function isNew(x) {}"},{"path":null,"text":"const parse = 1;"},{"path":null,"text":"awsCopy(a, b);"},{"path":null,"text":"const s = n.toFixed(2);"},{"path":null,"text":"expect(newSoftLockups(a)).toBeNull();"}]}},{"id":"restating-comment","title":"Comment repeats the code","severity":"low","category":"slop","languages":["ts","py","c"],"scope":"any","why":"`// increment counter` above `counter++` doubles the reading and goes stale when the code changes. It's the most common AI comment.","fix":"Delete it. Write comments for what the code can't say: why, constraints, links.","bad":"// Get the user\nconst user = getUser(id);","good":"const user = getUser(id);","lang":"ts","research":"restating-comment","message":"This comment repeats the next line in words. It adds reading, not information.","detects":"structure","source":{"name":"Comments and docstrings that repeat the next line, the function name or the structure (\"Step 1\", \"This function handles\")","why":"The reader learns nothing, and the comment drifts out of date when the code changes.","links":[{"label":"Taxonomy: narrating comments","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/narrating-comments/"},{"label":"Deslopping AI code","url":"https://www.anaconda.com/blog/deslopping-ai-code"},{"label":"Stop reviewing AI code, start deleting it","url":"https://dev.to/krisnamic/stop-reviewing-ai-code-start-deleting-it-o40"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/restating-comment","examples":{"flagged":[{"path":null,"text":"// Get the user\nconst user = getUser(id);\n"},{"path":"src/app.py","text":"# return the user\nreturn user\n"}],"clean":[{"path":null,"text":"// Cached: lookups repeat within one request\nconst user = getUser(id);\n"}]}},{"id":"obvious-docstring","title":"Docstring restates the name","severity":"low","category":"slop","languages":["py"],"scope":"any","why":"'Get the user.' on `get_user` tells nothing new. Docstrings earn their place with units, edge cases and failure modes.","fix":"Delete it, or say what the name can't.","bad":"def get_user(user_id):\n    \"\"\"Get the user.\"\"\"","good":"def get_user(user_id):\n    \"\"\"Return the user, or raise NotFound. Reads the replica.\"\"\"","lang":"py","research":"restating-comment","message":"The docstring restates the name `get_user`. Say what a reader can't see: units, edge cases, why.","detects":"structure","source":{"name":"Comments and docstrings that repeat the next line, the function name or the structure (\"Step 1\", \"This function handles\")","why":"The reader learns nothing, and the comment drifts out of date when the code changes.","links":[{"label":"Taxonomy: narrating comments","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/narrating-comments/"},{"label":"Deslopping AI code","url":"https://www.anaconda.com/blog/deslopping-ai-code"},{"label":"Stop reviewing AI code, start deleting it","url":"https://dev.to/krisnamic/stop-reviewing-ai-code-start-deleting-it-o40"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/obvious-docstring","examples":{"flagged":[{"path":null,"text":"def get_user(user_id):\n    \"\"\"Gets the user.\"\"\"\n    return 1\n"}],"clean":[{"path":null,"text":"def get_user(user_id):\n    \"\"\"Read from the replica; may lag by a second.\"\"\"\n    return 1\n"}]}},{"id":"em-dash","title":"Em or en dash","severity":"low","category":"slop","languages":["*"],"scope":"any","why":"Readers now take the em dash as a sign nobody edited the text. In logs and UI strings it also breaks grep and plain-ASCII terminals.","fix":"Use a comma, colon, parentheses or a plain hyphen, or split the sentence.","bad":"throw new Error(\"Upload failed — try again\");","good":"throw new Error(\"Upload failed. Try again.\");","lang":"ts","research":"em-dash","message":"An em or en dash (—) in a comment or string. It is the most-cited tell of machine-written text.","detects":"pattern","source":{"name":"Em and en dashes (U+2014, U+2013) in comments and strings","why":"Readers take them as a sign of unedited generated text, and they break plain-ASCII grep and terminals.","links":[{"label":"Em dashes and spotting AI writing","url":"https://www.plagiarismtoday.com/2025/06/26/em-dashes-hyphens-and-spotting-ai-writing/"},{"label":"ChatGPT and the em dash","url":"https://www.rollingstone.com/culture/culture-features/chatgpt-hypen-em-dash-ai-writing-1235314945/"}],"notes":["skill: humanizer"]},"url":"https://redline.kevinliu.studio/rules/em-dash","examples":{"flagged":[{"path":null,"text":"const s = \"fast — and cheap\";"},{"path":null,"text":"// one – two"}],"clean":[{"path":null,"text":"const s = \"fast - and cheap\";"},{"path":null,"text":"const a = b - c;"}]}},{"id":"emoji","title":"Emoji in code","severity":"low","category":"slop","languages":["ts","py","c","sh"],"scope":"any","why":"Emoji in logs, comments and error messages are a common AI tell. They don't grep, some terminals render them as boxes, and they add no meaning a word wouldn't.","fix":"Say it in words: `ok`, `failed`, `warning`.","bad":"console.info(\"✅ Upload complete!\");","good":"console.info(\"upload complete\");","lang":"ts","research":"emoji","message":"Emoji (✅) in source. Logs and comments read like a chat reply, not a program.","detects":"pattern","source":{"name":"Emoji in comments, logs and error strings","why":"They do not grep, some terminals show them as boxes, and readers take them as a model tell.","links":[{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"},{"label":"Your AI code bias makes you a worse reviewer","url":"https://revelry.co/insights/artificial-intelligence/your-ai-code-bias-makes-you-a-worse-reviewer/"}],"notes":["skill: humanizer"]},"url":"https://redline.kevinliu.studio/rules/emoji","examples":{"flagged":[{"path":null,"text":"logger.info(\"✅ done\")"},{"path":null,"text":"// 🚀 ship it"}],"clean":[{"path":null,"text":"logger.info(\"done\")"}]}},{"id":"filler-comment","title":"Filler comment","severity":"low","category":"slop","languages":["*"],"scope":"any","why":"'This function is responsible for…' and section labels like `// Imports` restate the structure a reader can already see. Models add them by reflex.","fix":"Delete it. Keep comments for the why: a constraint, a trade-off, a link.","bad":"// Helper functions\n// This function is responsible for formatting dates\nfunction fmt(d) {}","good":"function formatDate(d) {}","lang":"ts","research":"restating-comment","message":"A comment that labels instead of explaining (// Imports).","detects":"pattern","source":{"name":"Comments and docstrings that repeat the next line, the function name or the structure (\"Step 1\", \"This function handles\")","why":"The reader learns nothing, and the comment drifts out of date when the code changes.","links":[{"label":"Taxonomy: narrating comments","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/narrating-comments/"},{"label":"Deslopping AI code","url":"https://www.anaconda.com/blog/deslopping-ai-code"},{"label":"Stop reviewing AI code, start deleting it","url":"https://dev.to/krisnamic/stop-reviewing-ai-code-start-deleting-it-o40"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/filler-comment","examples":{"flagged":[{"path":null,"text":"// Imports\nimport a from 'a';"},{"path":null,"text":"// This function is responsible for parsing\nfunction p() {}"}],"clean":[{"path":null,"text":"// Dates arrive in UTC; render them in the user's zone.\nfunction fmt() {}"}]}},{"id":"doc-sprawl","title":"Generated summary file","severity":"low","category":"slop","languages":["*"],"scope":"any","why":"Agents leave `IMPLEMENTATION_SUMMARY.md` and `FIXES_REPORT.md` behind. They narrate one session and nobody updates them.","fix":"Put the summary in the PR description. Keep docs that explain the system, not the session.","bad":"IMPLEMENTATION_SUMMARY.md","good":"(the PR description)","lang":"ts","research":"doc-sprawl","message":"A new summary or report file in the repo. It describes one session's work and will be stale tomorrow.","detects":"structure","source":{"name":"Generated `SUMMARY.md`, `REPORT.md` and `FINAL_*.md` files","why":"The files go stale at once and mislead the next reader or agent.","links":[{"label":"AI-driven documentation sprawl","url":"https://www.thoughtworks.com/radar/techniques/ai-driven-documentation-sprawl"},{"label":"Why does the agent keep creating summary files","url":"https://forum.cursor.com/t/why-does-claude-in-cursor-keep-creating-markdown-work-summary-files/150420"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/doc-sprawl","examples":{"flagged":[{"path":"IMPLEMENTATION_SUMMARY.md","text":"# Summary\n"}],"clean":[{"path":"docs/architecture.md","text":"# Architecture\n"}]}},{"id":"hype-words","title":"Marketing words","severity":"low","category":"slop","languages":["*"],"scope":"any","why":"Words like robust, seamless and comprehensive are filler that models lean on. They make docs longer and say nothing checkable.","fix":"Say the specific fact: 'retries 3 times', 'handles empty input', 'uses the index'.","bad":"// Robust, comprehensive validation for user input","good":"// Rejects empty names and emails without an @.","lang":"ts","research":"hype-words","message":"'robust' in a comment or string. It describes how the author felt, not what the code does.","detects":"pattern","source":{"name":"Marketing words in comments, docs and names (`robust`, `seamless`, `comprehensive`, `leverage`)","why":"Adjectives make claims nobody can check and mark text nobody edited.","links":[{"label":"Your AI code bias makes you a worse reviewer","url":"https://revelry.co/insights/artificial-intelligence/your-ai-code-bias-makes-you-a-worse-reviewer/"},{"label":"KarpeSlop","url":"https://github.com/CodeDeficient/KarpeSlop"}],"notes":["skill: humanizer"]},"url":"https://redline.kevinliu.studio/rules/hype-words","examples":{"flagged":[{"path":null,"text":"// A robust parser"},{"path":null,"text":"const s = \"Seamlessly sync your data\";"},{"path":"src/app.py","text":"# leverage the cache\n"}],"clean":[{"path":null,"text":"// Parses ISO dates."},{"path":null,"text":"const robustness = 1;"}]}},{"id":"numbered-name","title":"Numbered placeholder name","severity":"low","category":"slop","languages":["ts","py"],"scope":"any","why":"`data2`, `result3` mean the author ran out of names. The reader has to trace where each one came from.","fix":"Name it for what it holds: `overdueLoans`, `memberRow`.","bad":"const data2 = await load(id);","good":"const overdueLoans = await load(id);","lang":"ts","research":"placeholder-names","message":"`const data2` is a numbered stand-in, not a name.","detects":"pattern","source":{"name":"Numbered or vague names (`data2`, `result2`, `tmp1`, `do_stuff`)","why":"The name hides what the value is.","links":[{"label":"Detecting AI slop in codebases","url":"https://dev.to/rohan_san_54b7ab7e50faa83/how-i-built-a-tool-that-detects-ai-slop-in-codebases-and-what-patterns-i-found-gmc"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/numbered-name","examples":{"flagged":[{"path":null,"text":"const data2 = await load();"},{"path":"src/app.py","text":"result2 = run()\n"}],"clean":[{"path":null,"text":"const users = await load();"}]}},{"id":"step-comment","title":"Numbered step comments","severity":"low","category":"slop","languages":["*"],"scope":"any","why":"`// Step 1:`, `// Step 2:` scaffolding is a tutorial habit. It goes stale when a step is added and hides the one comment that matters.","fix":"Delete the step labels. If the steps are real units, make them functions with names.","bad":"// Step 1: load\nconst a = load();\n// Step 2: save\nsave(a);","good":"save(load());","lang":"ts","research":"restating-comment","message":"A numbered step comment (// Step 1:). The code already runs in order.","detects":"pattern","source":{"name":"Comments and docstrings that repeat the next line, the function name or the structure (\"Step 1\", \"This function handles\")","why":"The reader learns nothing, and the comment drifts out of date when the code changes.","links":[{"label":"Taxonomy: narrating comments","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/narrating-comments/"},{"label":"Deslopping AI code","url":"https://www.anaconda.com/blog/deslopping-ai-code"},{"label":"Stop reviewing AI code, start deleting it","url":"https://dev.to/krisnamic/stop-reviewing-ai-code-start-deleting-it-o40"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/step-comment","examples":{"flagged":[{"path":null,"text":"// Step 1: load the file\nconst a = 1;"},{"path":null,"text":"# step 2) parse"}],"clean":[{"path":null,"text":"// Steps are retried by the queue."}]}},{"id":"section-banner","title":"Section banner comment","severity":"low","category":"slop","languages":["ts","py","c"],"scope":"any","why":"`// ===== Helpers =====` banners split a file into chapters instead of splitting it into files. Models add them to look organised.","fix":"Delete the banner. If the sections are real, move each one to its own module.","bad":"# ========== Helpers ==========","good":"# (helpers live in helpers/dates.py)","lang":"ts","research":"section-banner","message":"A banner comment. If the file needs signposts this big, it holds more than one module.","detects":"pattern","source":{"name":"Banner comments (`# ===== Helpers =====`) in short files","why":"They add length and no information.","links":[{"label":"Taxonomy: narrating comments","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/narrating-comments/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/section-banner","examples":{"flagged":[{"path":null,"text":"// ===== Helpers ====="},{"path":"src/app.py","text":"# ------------------------------\n"}],"clean":[{"path":null,"text":"// Helpers for parsing dates."}]}},{"id":"todo-marker","title":"TODO left in","severity":"low","category":"slop","languages":["*"],"scope":"any","why":"TODOs are where reviews hide unfinished work. They rarely get done and nobody owns them.","fix":"Finish the work in this change, or open an issue and link it.","bad":"// TODO: handle errors\nconst r = await send();","good":"const r = await send(); // errors propagate to the caller","lang":"ts","research":"todo-marker","message":"A TODO left in the change. Do it now, file it, or delete it.","detects":"pattern","source":{"name":"TODO, FIXME, XXX and HACK left in","why":"A note nobody owns is never done.","links":[{"label":"Detecting AI slop in codebases","url":"https://dev.to/rohan_san_54b7ab7e50faa83/how-i-built-a-tool-that-detects-ai-slop-in-codebases-and-what-patterns-i-found-gmc"},{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/todo-marker","examples":{"flagged":[{"path":null,"text":"// TODO: fix later"},{"path":"src/app.py","text":"# FIXME broken\n"}],"clean":[{"path":null,"text":"const todo = \"TODO\";"},{"path":null,"text":"// Todos load from the API."}]}},{"id":"bare-except","title":"Bare except","severity":"high","category":"errors","languages":["py"],"scope":"any","why":"`except:` catches everything, including Ctrl-C and `sys.exit`, so the program can't even be stopped cleanly.","fix":"Catch the specific exceptions you expect.","bad":"try:\n    load()\nexcept:\n    pass","good":"try:\n    load()\nexcept FileNotFoundError:\n    return DEFAULTS","lang":"py","research":"broad-except","message":"A bare `except:` also catches KeyboardInterrupt and SystemExit, and every bug in the block.","detects":"structure","source":{"name":"Bare `except:`, `except Exception`, and a re-raise that drops the cause","why":"It catches bugs you did not expect along with the error you did, and loses the original traceback.","links":[{"label":"Ruff: blind-except","url":"https://docs.astral.sh/ruff/rules/blind-except"},{"label":"Ruff: bare-except","url":"https://docs.astral.sh/ruff/rules/bare-except"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/bare-except","examples":{"flagged":[{"path":null,"text":"try:\n    go()\nexcept:\n    retry()\n"}],"clean":[{"path":null,"text":"try:\n    go()\nexcept OSError:\n    retry()\n"}]}},{"id":"empty-catch","title":"Empty catch","severity":"high","category":"errors","languages":["ts","py"],"scope":"any","why":"An empty catch makes every failure look like success. The bug surfaces later and far away, with no trace of the cause.","fix":"Let the error propagate, or handle the specific error you expect and rethrow the rest.","bad":"try {\n  await save(order);\n} catch {}","good":"await save(order);","lang":"ts","research":"swallowed-error","message":"This catch block is empty, so the error disappears. Nothing will tell you this failed.","detects":"structure","source":{"name":"Empty catch, `except: pass`, `.catch(() => {})`, and catch blocks that only log","why":"The failure disappears from the person who could fix it.","links":[{"label":"Ruff: try-except-pass","url":"https://docs.astral.sh/ruff/rules/try-except-pass"},{"label":"Taxonomy: swallowed exceptions","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/swallowed-exceptions/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/empty-catch","examples":{"flagged":[{"path":null,"text":"try {\n  go();\n} catch (e) {}\n"},{"path":"src/app.py","text":"try:\n    go()\nexcept ValueError:\n    pass\n"}],"clean":[{"path":null,"text":"try {\n  go();\n} catch (e) {\n  throw new Error('save failed', { cause: e });\n}\n"}]}},{"id":"mutable-default","title":"Mutable default argument","severity":"high","category":"errors","languages":["py"],"scope":"any","why":"Python evaluates defaults once. A list or dict default is shared by every call, so state leaks between calls.","fix":"Default to `None` and create the value inside the function.","bad":"def add(item, items=[]):\n    items.append(item)","good":"def add(item, items=None):\n    items = [] if items is None else items","lang":"py","research":"mutable-default","message":"A mutable default in `f`. It's created once and shared by every call, so one call's changes leak into the next.","detects":"structure","source":{"name":"Mutable default arguments in Python","why":"The default is built once and shared by every call.","links":[{"label":"Ruff: mutable-argument-default","url":"https://docs.astral.sh/ruff/rules/mutable-argument-default"},{"label":"Taxonomy: mutable default arguments","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/mutable-default-arguments/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/mutable-default","examples":{"flagged":[{"path":null,"text":"def f(x=[]):\n    return x\n"},{"path":null,"text":"def f(*, x={}):\n    return x\n"}],"clean":[{"path":null,"text":"def f(x=None):\n    return x\n"}]}},{"id":"promise-catch-noop","title":"Rejection swallowed","severity":"high","category":"errors","languages":["ts"],"scope":"any","why":"An empty `.catch` turns every failure into silent success. The bug shows up later, far from the cause, with no log.","fix":"Let it reject, handle the specific error you expect, or log and rethrow.","bad":"save(user).catch(() => {});","good":"await save(user); // the caller decides what a failure means","lang":"ts","research":"swallowed-error","message":"`.catch(() => {})` throws the error away. When this fails, nothing will say so.","detects":"pattern","source":{"name":"Empty catch, `except: pass`, `.catch(() => {})`, and catch blocks that only log","why":"The failure disappears from the person who could fix it.","links":[{"label":"Ruff: try-except-pass","url":"https://docs.astral.sh/ruff/rules/try-except-pass"},{"label":"Taxonomy: swallowed exceptions","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/swallowed-exceptions/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/promise-catch-noop","examples":{"flagged":[{"path":null,"text":"save(x).catch(() => {});"},{"path":null,"text":"load().catch(() => null)"},{"path":null,"text":"p.catch(noop)"}],"clean":[{"path":null,"text":"save(x).catch((e) => report(e));"}]}},{"id":"match-error-message","title":"Branches on error text","severity":"medium","category":"errors","languages":["ts","py"],"scope":"any","why":"Error messages are for people and change without notice. A reworded message silently changes control flow.","fix":"Check the error type or code (`instanceof`, `err.code`, a specific exception class).","bad":"if (err.message.includes(\"timeout\")) retry();","good":"if (err instanceof TimeoutError) retry();","lang":"ts","research":"match-error-by-message","message":"Decides what to do by reading the error's message text.","detects":"pattern","source":{"name":"Branching on an error's message text","why":"The branch flips silently when the wording changes.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/match-error-message","examples":{"flagged":[{"path":null,"text":"if (err.message.includes(\"timeout\")) retry();"},{"path":"src/app.py","text":"if 'timeout' in str(e):\n    pass\n"}],"clean":[{"path":null,"text":"if (err instanceof TimeoutError) retry();"}]}},{"id":"catch-returns-empty","title":"Error turned into an empty value","severity":"medium","category":"errors","languages":["ts","py"],"scope":"any","why":"Returning `null` or `[]` from a catch makes 'it failed' look like 'there was nothing'. The UI shows an empty list instead of an error.","fix":"Let it throw, or return an explicit error result the caller must handle.","bad":"try {\n  return await listOrders();\n} catch {\n  return [];\n}","good":"return await listOrders();","lang":"ts","research":"defensive-code","message":"Turns the error into an empty value. Callers can't tell 'failed' from 'nothing there'.","detects":"structure","source":{"name":"Fallbacks and guards that hide missing data (`?? []`, `.get(k, \"\")`, `hasattr` probes, catch that returns empty, long `?.` chains)","why":"A timeout looks like an empty result, and broken assumptions travel downstream.","links":[{"label":"Issue: agent adds unsafe fallbacks","url":"https://claudeissues.com/issue/31890-bug-error-handling-ignores-claude-md-directives-adds-unsafe-fallbacks-instead-of"},{"label":"Fallbacks are evil","url":"https://dev.to/tertiumnon/fallbacks-are-evil-5bh2"},{"label":"X post by karpathy","url":"https://x.com/karpathy/status/1976077806443569355"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/catch-returns-empty","examples":{"flagged":[{"path":null,"text":"try {\n  return go();\n} catch (e) {\n  return [];\n}\n"},{"path":"src/app.py","text":"try:\n    return go()\nexcept KeyError:\n    return None\n"}],"clean":[{"path":null,"text":"try {\n  return go();\n} catch (e) {\n  throw e;\n}\n"}]}},{"id":"broad-except","title":"except Exception","severity":"medium","category":"errors","languages":["py"],"scope":"any","why":"Catching `Exception` treats a typo, a None and a network error the same way. Bugs get handled as if they were expected failures.","fix":"Catch the exceptions this block can actually raise, or re-raise after cleanup.","bad":"try:\n    sync()\nexcept Exception:\n    retry()","good":"try:\n    sync()\nexcept (TimeoutError, ConnectionError):\n    retry()","lang":"py","research":"broad-except","message":"`except Exception` catches every bug in the block, not just the failure you expect.","detects":"structure","source":{"name":"Bare `except:`, `except Exception`, and a re-raise that drops the cause","why":"It catches bugs you did not expect along with the error you did, and loses the original traceback.","links":[{"label":"Ruff: blind-except","url":"https://docs.astral.sh/ruff/rules/blind-except"},{"label":"Ruff: bare-except","url":"https://docs.astral.sh/ruff/rules/bare-except"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/broad-except","examples":{"flagged":[{"path":null,"text":"try:\n    go()\nexcept Exception:\n    retry()\n"}],"clean":[{"path":null,"text":"try:\n    go()\nexcept Exception:\n    cleanup()\n    raise\n"}]}},{"id":"log-and-continue","title":"Logs the error and carries on","severity":"medium","category":"errors","languages":["ts","py"],"scope":"any","why":"Logging an error and continuing means the caller thinks it worked. The log line is the only witness, and nobody reads it in time.","fix":"Rethrow after logging, or return a result the caller has to check.","bad":"try {\n  await charge(card);\n} catch (e) {\n  console.error(e);\n}","good":"await charge(card); // the caller shows the decline","lang":"ts","research":"swallowed-error","message":"Logs the error and carries on as if it worked. The caller gets no signal that this failed.","detects":"structure","source":{"name":"Empty catch, `except: pass`, `.catch(() => {})`, and catch blocks that only log","why":"The failure disappears from the person who could fix it.","links":[{"label":"Ruff: try-except-pass","url":"https://docs.astral.sh/ruff/rules/try-except-pass"},{"label":"Taxonomy: swallowed exceptions","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/swallowed-exceptions/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/log-and-continue","examples":{"flagged":[{"path":null,"text":"try {\n  go();\n} catch (e) {\n  console.error(e);\n}\n"},{"path":"src/app.py","text":"try:\n    go()\nexcept ValueError as e:\n    logger.warning(e)\n"}],"clean":[{"path":null,"text":"try {\n  go();\n} catch (e) {\n  console.error(e);\n  throw e;\n}\n"}]}},{"id":"missing-timeout","title":"Network call without a timeout","severity":"medium","category":"errors","languages":["py"],"scope":"any","why":"Without a timeout one stuck upstream holds a worker until the process dies. At scale that becomes an outage.","fix":"Pass `timeout=` (and retry with backoff if the call is idempotent).","bad":"requests.get(url)","good":"requests.get(url, timeout=10)","lang":"py","research":"missing-timeout","message":"`requests.get` has no timeout, so a slow server can hang this forever.","detects":"pattern","source":{"name":"Network calls with no timeout or abort signal","why":"One slow upstream can hang a worker forever.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"},{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/missing-timeout","examples":{"flagged":[{"path":null,"text":"r = requests.get(url)\n"}],"clean":[{"path":null,"text":"r = requests.get(url, timeout=5)\n"}]}},{"id":"throw-literal","title":"Throws a non-Error","severity":"medium","category":"errors","languages":["ts"],"scope":"any","why":"Throwing a string or object loses the stack trace and breaks `instanceof Error` checks in handlers.","fix":"`throw new Error(\"…\")`, or a subclass with a `cause`.","bad":"throw \"user not found\";","good":"throw new NotFoundError(\"user not found\");","lang":"ts","research":"throw-literal","message":"Throws a throw \"… value instead of an Error. There will be no stack trace.","detects":"pattern","source":{"name":"Throwing a string or plain object","why":"There is no stack trace, and `instanceof Error` checks fail.","links":[{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/throw-literal","examples":{"flagged":[{"path":null,"text":"throw \"bad\";"},{"path":null,"text":"throw { code: 1 };"}],"clean":[{"path":null,"text":"throw new Error(\"bad\");"}]}},{"id":"assert-for-validation","title":"assert used for validation","severity":"low","category":"errors","languages":["py"],"scope":"prod","why":"Asserts are for invariants in tests and debugging. Under `python -O` they are removed, so input validation built on them disappears.","fix":"Raise a real exception (`ValueError`, `TypeError`) for bad input.","bad":"assert user_id, 'missing user'","good":"if not user_id:\n    raise ValueError('missing user id')","lang":"py","research":"assert-in-prod","message":"`assert` in shipped code. Python drops asserts under `-O`, so this check can vanish.","detects":"pattern","source":{"name":"`assert` used for runtime validation in Python","why":"Python drops asserts under `-O`, so the check disappears.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/assert-for-validation","examples":{"flagged":[{"path":null,"text":"assert x > 0\n"}],"clean":[{"path":"tests/test_a.py","text":"assert x > 0\n"}]}},{"id":"error-discarded","title":"Error caught and ignored","severity":"low","category":"errors","languages":["ts"],"scope":"any","why":"A catch that never reads the error handles every failure the same way, including the ones you didn't expect.","fix":"Check the error type and rethrow anything you didn't mean to handle.","bad":"try {\n  parse(s);\n} catch {\n  useDefault();\n}","good":"try {\n  parse(s);\n} catch (e) {\n  if (!(e instanceof SyntaxError)) throw e;\n  useDefault();\n}","lang":"ts","research":"swallowed-error","message":"Catches an error and never looks at it. Every failure, expected or not, takes this path.","detects":"structure","source":{"name":"Empty catch, `except: pass`, `.catch(() => {})`, and catch blocks that only log","why":"The failure disappears from the person who could fix it.","links":[{"label":"Ruff: try-except-pass","url":"https://docs.astral.sh/ruff/rules/try-except-pass"},{"label":"Taxonomy: swallowed exceptions","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/taxonomy/patterns/swallowed-exceptions/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/error-discarded","examples":{"flagged":[{"path":null,"text":"try {\n  go();\n} catch {\n  fallback();\n}\n"}],"clean":[{"path":null,"text":"try {\n  go();\n} catch (e) {\n  if (e instanceof X) fallback(e);\n  else throw e;\n}\n"}]}},{"id":"exit-in-library","title":"Exits the process","severity":"low","category":"errors","languages":["ts","py"],"scope":"prod","why":"Exiting deep in a call stack skips cleanup, loses buffered logs and makes the code impossible to reuse or test.","fix":"Throw an error and let the entry point decide the exit code.","bad":"if (!cfg) process.exit(1);","good":"if (!cfg) throw new Error(\"missing config\");","lang":"ts","research":"exit-in-library","message":"`process.exit` kills the whole process from library code.","detects":"pattern","source":{"name":"`process.exit` or `sys.exit` in library code","why":"It skips cleanup, loses buffered logs and makes the code hard to reuse or test.","links":[],"notes":["no outside source yet"]},"url":"https://redline.kevinliu.studio/rules/exit-in-library","examples":{"flagged":[{"path":null,"text":"process.exit(1);"}],"clean":[{"path":"src/cli.ts","text":"process.exit(1);"},{"path":"src/app.py","text":"sys.exit(main(sys.argv[1:]))\n"}]}},{"id":"silent-default","title":"Fallback hides missing data","severity":"low","category":"errors","languages":["ts","py"],"scope":"any","why":"Defaulting to `[]`, `{}` or `''` makes a missing field look like an empty one. The bug surfaces later as wrong output, not as an error.","fix":"Fail loudly when the field is required; default only where empty is a real, expected value.","bad":"const items = order.items ?? [];","good":"const items = order.items; // required by the schema","lang":"ts","research":"defensive-code","message":"Falls back to an empty value (?? []). If the data is missing by mistake, this hides it.","detects":"pattern","source":{"name":"Fallbacks and guards that hide missing data (`?? []`, `.get(k, \"\")`, `hasattr` probes, catch that returns empty, long `?.` chains)","why":"A timeout looks like an empty result, and broken assumptions travel downstream.","links":[{"label":"Issue: agent adds unsafe fallbacks","url":"https://claudeissues.com/issue/31890-bug-error-handling-ignores-claude-md-directives-adds-unsafe-fallbacks-instead-of"},{"label":"Fallbacks are evil","url":"https://dev.to/tertiumnon/fallbacks-are-evil-5bh2"},{"label":"X post by karpathy","url":"https://x.com/karpathy/status/1976077806443569355"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/silent-default","examples":{"flagged":[{"path":null,"text":"const a = b ?? [];"},{"path":"src/app.py","text":"x = d.get('k', '')\n"}],"clean":[{"path":null,"text":"const a = b ?? defaultItems;"}]}},{"id":"fetch-without-timeout","title":"fetch without a timeout","severity":"low","category":"errors","languages":["ts"],"scope":"prod","why":"`fetch` has no default timeout. A hung upstream holds the request, the connection and the user until something else gives up.","fix":"Pass `signal: AbortSignal.timeout(ms)`.","bad":"const res = await fetch(url);","good":"const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });","lang":"ts","research":"missing-timeout","message":"`fetch` without a `signal` waits as long as the server likes. Pass `AbortSignal.timeout(ms)`.","detects":"structure","source":{"name":"Network calls with no timeout or abort signal","why":"One slow upstream can hang a worker forever.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"},{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/fetch-without-timeout","examples":{"flagged":[{"path":null,"text":"const r = await fetch(url);"}],"clean":[{"path":null,"text":"const r = await fetch(url, { signal: AbortSignal.timeout(5000) });"}]}},{"id":"generic-error-message","title":"Generic error message","severity":"low","category":"errors","languages":["ts","py"],"scope":"any","why":"'Something went wrong' tells the on-call engineer nothing. Good messages name the operation and the input that failed.","fix":"Name what failed and include the key value: `could not load invoice ${id}: ${status}`.","bad":"throw new Error(\"Something went wrong\");","good":"throw new Error(`invoice ${id} failed to load: HTTP ${res.status}`);","lang":"ts","research":"generic-error-message","message":"The error message says nothing (new Error(\"Something went wrong\")). Whoever reads the log won't know what failed or why.","detects":"pattern","source":{"name":"Error text with no content (\"Something went wrong\", \"failed\")","why":"Whoever reads the log cannot tell what failed or with which input.","links":[],"notes":["owner's notes","skill: no-sus-code-doctor"]},"url":"https://redline.kevinliu.studio/rules/generic-error-message","examples":{"flagged":[{"path":null,"text":"throw new Error(\"Something went wrong\");"},{"path":"src/app.py","text":"raise ValueError(\"Unknown error\")\n"}],"clean":[{"path":null,"text":"throw new Error(`invoice ${id} not found`);"}]}},{"id":"raise-bare-exception","title":"Raises plain Exception","severity":"low","category":"errors","languages":["py"],"scope":"any","why":"A generic exception forces callers into `except Exception`, which also catches real bugs.","fix":"Raise a specific built-in (`ValueError`, `LookupError`) or your own subclass.","bad":"raise Exception(\"bad input\")","good":"raise ValueError(\"member id must be a UUID\")","lang":"py","research":"generic-exception-class","message":"Raises a plain `Exception`. Callers can't catch it without catching everything.","detects":"pattern","source":{"name":"Raising bare `Exception` in Python","why":"Callers cannot catch this failure without catching every failure.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/raise-bare-exception","examples":{"flagged":[{"path":null,"text":"raise Exception(\"bad\")\n"}],"clean":[{"path":null,"text":"raise ValueError(\"bad\")\n"}]}},{"id":"raise-without-from","title":"Re-raise loses the cause","severity":"low","category":"errors","languages":["py"],"scope":"any","why":"Raising a new exception inside `except` without `from` buries the original error in 'During handling…' noise.","fix":"`raise NewError(...) from err` (or `from None` when hiding it is the point).","bad":"except KeyError:\n    raise ConfigError('missing key')","good":"except KeyError as err:\n    raise ConfigError('missing key') from err","lang":"py","research":"broad-except","message":"Raises a new error inside `except` without `from`. The original cause is hidden in the traceback.","detects":"structure","source":{"name":"Bare `except:`, `except Exception`, and a re-raise that drops the cause","why":"It catches bugs you did not expect along with the error you did, and loses the original traceback.","links":[{"label":"Ruff: blind-except","url":"https://docs.astral.sh/ruff/rules/blind-except"},{"label":"Ruff: bare-except","url":"https://docs.astral.sh/ruff/rules/bare-except"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/raise-without-from","examples":{"flagged":[{"path":null,"text":"try:\n    go()\nexcept KeyError:\n    raise ValueError('x')\n"}],"clean":[{"path":null,"text":"try:\n    go()\nexcept KeyError as e:\n    raise ValueError('x') from e\n"}]}},{"id":"naive-datetime","title":"Time without a time zone","severity":"low","category":"errors","languages":["py"],"scope":"any","why":"Naive datetimes compare wrongly with aware ones and shift when the server's zone or DST changes.","fix":"`datetime.now(UTC)`.","bad":"ts = datetime.now()","good":"ts = datetime.now(UTC)","lang":"py","research":"naive-datetime","message":"`datetime.now()` has no time zone, so it means the server's local time.","detects":"pattern","source":{"name":"`datetime.now()` with no timezone","why":"Timestamps shift by hours across hosts.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/naive-datetime","examples":{"flagged":[{"path":null,"text":"ts = datetime.now()\n"}],"clean":[{"path":null,"text":"ts = datetime.now(tz=UTC)\n"}]}},{"id":"is-literal","title":"`is` with a literal","severity":"high","category":"types","languages":["py"],"scope":"any","why":"`x is 1` or `x is 'a'` depends on interpreter caching. It can be true in tests and false in production.","fix":"Use `==` for values. Keep `is` for `None`, `True`, `False`.","bad":"if status is 'ok':","good":"if status == 'ok':","lang":"py","research":"loose-equality","message":"`is 1` compares identity, not value. It works by accident for small ints and some strings.","detects":"pattern","source":{"name":"`==`, `var`, `== None`, and `is` with a literal","why":"Coercion and leaky scope make comparisons true or false for the wrong reason.","links":[{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/is-literal","examples":{"flagged":[{"path":null,"text":"if x is 1:\n    pass\n"},{"path":null,"text":"if s is 'a':\n    pass\n"}],"clean":[{"path":null,"text":"if x is None:\n    pass\n"}]}},{"id":"double-cast","title":"Double cast","severity":"high","category":"types","languages":["ts"],"scope":"any","why":"A double cast is a lie to the type checker. It hides a real mismatch that will show up as a runtime bug.","fix":"Fix the types at the source, or parse and validate the value.","bad":"const u = data as unknown as User;","good":"const u = UserSchema.parse(data);","lang":"ts","research":"any-type","message":"`as unknown as` forces one type into an unrelated one. The compiler said no; this overrides it.","detects":"pattern","source":{"name":"`any`, `as unknown as`, non-null `!`, and shapeless types (`Record<string, any>`, `dict[str, Any]`)","why":"Each one turns off type checking for the values it touches.","links":[{"label":"typescript-eslint: avoiding anys","url":"https://typescript-eslint.io/blog/avoiding-anys/"},{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/double-cast","examples":{"flagged":[{"path":null,"text":"const u = d as unknown as User;"}],"clean":[{"path":null,"text":"const u = d as User;"}]}},{"id":"any-type","title":"`any` type","severity":"medium","category":"types","languages":["ts"],"scope":"any","why":"`any` spreads: everything it touches stops being checked. A wrong field name or shape compiles fine and fails at runtime.","fix":"Use the real type, `unknown` plus a check, or a generic.","bad":"const body = (await res.json()) as any;","good":"const body = UserSchema.parse(await res.json());","lang":"ts","research":"any-type","message":"`as any` turns type checking off for this value.","detects":"pattern","source":{"name":"`any`, `as unknown as`, non-null `!`, and shapeless types (`Record<string, any>`, `dict[str, Any]`)","why":"Each one turns off type checking for the values it touches.","links":[{"label":"typescript-eslint: avoiding anys","url":"https://typescript-eslint.io/blog/avoiding-anys/"},{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/any-type","examples":{"flagged":[{"path":null,"text":"const a = b as any;"},{"path":null,"text":"function f(x: any) {}"},{"path":null,"text":"let xs: any[] = [];"}],"clean":[{"path":null,"text":"const a = b as User;"},{"path":null,"text":"// any value works"}]}},{"id":"lint-suppress","title":"Lint or type check switched off","severity":"medium","category":"types","languages":["*"],"scope":"any","why":"Each suppression is a finding someone decided not to fix. They pile up, and the linter stops meaning anything.","fix":"Fix what the check found. If the rule is wrong for the project, change the config once, with a reason.","bad":"// eslint-disable-next-line @typescript-eslint/no-explicit-any","good":"(fix the type)","lang":"ts","research":"lint-suppress","message":"`eslint-disable` switches a check off here.","detects":"pattern","source":{"name":"`@ts-ignore`, `eslint-disable`, bare `# noqa` and `# type: ignore`","why":"A green check stops meaning the thing it checks is true.","links":[{"label":"eslint-plugin-eslint-comments","url":"https://eslint-community.github.io/eslint-plugin-eslint-comments"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/lint-suppress","examples":{"flagged":[{"path":null,"text":"// eslint-disable-next-line"},{"path":"src/app.py","text":"x = f()  # type: ignore\n"},{"path":"src/app.py","text":"import a  # noqa\n"}],"clean":[{"path":null,"text":"// disable the button while saving"}]}},{"id":"loose-object-type","title":"Shapeless object type","severity":"medium","category":"types","languages":["ts","py"],"scope":"any","why":"Bags of `Record<string, unknown>` or `dict[str, Any]` move type errors from compile time to runtime and hide the real shape from readers.","fix":"Write the type: an interface, a TypedDict or dataclass, or a schema.","bad":"def load() -> dict[str, Any]: ...","good":"class Order(TypedDict):\n    id: str\n    total: int","lang":"ts","research":"any-type","message":"`Record<string, any>` says 'some object'. The fields inside aren't checked.","detects":"pattern","source":{"name":"`any`, `as unknown as`, non-null `!`, and shapeless types (`Record<string, any>`, `dict[str, Any]`)","why":"Each one turns off type checking for the values it touches.","links":[{"label":"typescript-eslint: avoiding anys","url":"https://typescript-eslint.io/blog/avoiding-anys/"},{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/loose-object-type","examples":{"flagged":[{"path":null,"text":"function f(o: Record<string, any>) {}"},{"path":"src/app.py","text":"def f(x: Any) -> Any:\n    return x\n"}],"clean":[{"path":null,"text":"function f(o: Order) {}"}]}},{"id":"ts-suppress","title":"Type error suppressed","severity":"medium","category":"types","languages":["ts"],"scope":"any","why":"Suppressed type errors are bugs the compiler already found. `@ts-ignore` also keeps hiding new errors on that line after the original is fixed.","fix":"Fix the type. If you must suppress, use `@ts-expect-error` with a reason.","bad":"// @ts-ignore\nuser.nmae = name;","good":"user.name = name;","lang":"ts","research":"lint-suppress","message":"`@ts-ignore` hides a type error instead of fixing it.","detects":"pattern","source":{"name":"`@ts-ignore`, `eslint-disable`, bare `# noqa` and `# type: ignore`","why":"A green check stops meaning the thing it checks is true.","links":[{"label":"eslint-plugin-eslint-comments","url":"https://eslint-community.github.io/eslint-plugin-eslint-comments"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/ts-suppress","examples":{"flagged":[{"path":null,"text":"// @ts-ignore\nconst a = 1;"},{"path":null,"text":"// @ts-nocheck"}],"clean":[{"path":null,"text":"// @ts-expect-error: the vendor types omit `signal`\nfetch(u, o);"}]}},{"id":"var-declaration","title":"`var`","severity":"low","category":"types","languages":["ts"],"scope":"any","why":"`var` leaks out of blocks and can be used before it's assigned, which causes subtle loop and closure bugs.","fix":"`const` by default, `let` when it's reassigned.","bad":"var total = 0;","good":"let total = 0;","lang":"ts","research":"loose-equality","message":"`var` is function-scoped and hoisted. Use `const` or `let`.","detects":"pattern","source":{"name":"`==`, `var`, `== None`, and `is` with a literal","why":"Coercion and leaky scope make comparisons true or false for the wrong reason.","links":[{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/var-declaration","examples":{"flagged":[{"path":null,"text":"var a = 1;"}],"clean":[{"path":null,"text":"const a = 1;"},{"path":null,"text":"// var a"}]}},{"id":"none-compare","title":"Compares to None with ==","severity":"low","category":"types","languages":["py"],"scope":"any","why":"`==` can be overridden by a class and gives surprising answers. `is None` is exact and idiomatic.","fix":"Use `is None` or `is not None`.","bad":"if user == None:","good":"if user is None:","lang":"py","research":"loose-equality","message":"`== None` should be `is None` / `is not None`.","detects":"pattern","source":{"name":"`==`, `var`, `== None`, and `is` with a literal","why":"Coercion and leaky scope make comparisons true or false for the wrong reason.","links":[{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/none-compare","examples":{"flagged":[{"path":null,"text":"if x == None:\n    pass\n"}],"clean":[{"path":null,"text":"if x is None:\n    pass\n"}]}},{"id":"loose-equality","title":"Loose equality","severity":"low","category":"types","languages":["ts"],"scope":"any","why":"Loose equality follows coercion rules few people remember. It hides type bugs.","fix":"Use `===` and `!==`. `== null` is the one common exception (null or undefined).","bad":"if (count == '0') {}","good":"if (count === 0) {}","lang":"ts","research":"loose-equality","message":"`==` coerces types before comparing, so `0 == ''` is true.","detects":"pattern","source":{"name":"`==`, `var`, `== None`, and `is` with a literal","why":"Coercion and leaky scope make comparisons true or false for the wrong reason.","links":[{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/loose-equality","examples":{"flagged":[{"path":null,"text":"if (a == b) {}"},{"path":null,"text":"if (a != 1) {}"}],"clean":[{"path":null,"text":"if (a === b) {}"},{"path":null,"text":"if (a == null) {}"}]}},{"id":"non-null-assertion","title":"Non-null assertion","severity":"low","category":"types","languages":["ts"],"scope":"any","why":"Non-null assertions skip the check the type system asked for. They are often added to quiet an error, not because the value is proven present.","fix":"Check for null and handle it, or narrow the type earlier.","bad":"const id = user!.id;","good":"if (!user) throw new Error(\"no user\");\nconst id = user.id;","lang":"ts","research":"any-type","message":"`!` tells the compiler this can't be null. If it can, this crashes.","detects":"pattern","source":{"name":"`any`, `as unknown as`, non-null `!`, and shapeless types (`Record<string, any>`, `dict[str, Any]`)","why":"Each one turns off type checking for the values it touches.","links":[{"label":"typescript-eslint: avoiding anys","url":"https://typescript-eslint.io/blog/avoiding-anys/"},{"label":"Google TypeScript style guide","url":"https://google.github.io/styleguide/tsguide.html"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/non-null-assertion","examples":{"flagged":[{"path":null,"text":"const id = user!.id;"},{"path":null,"text":"go(map.get(k)!);"}],"clean":[{"path":null,"text":"if (!user) return;"},{"path":null,"text":"const ne = a !== b;"}]}},{"id":"defensive-chaining","title":"Optional chaining everywhere","severity":"low","category":"types","languages":["ts"],"scope":"any","why":"Chains like `a?.b?.c?.d` silence errors on data you should know the shape of. A missing field becomes `undefined` downstream instead of an error here.","fix":"Type the data so the optional parts are explicit, and check once at the boundary.","bad":"const city = res?.data?.user?.address?.city;","good":"const { city } = parseUser(res).address;","lang":"ts","research":"defensive-code","message":"Three or more `?.` in one expression. The code doesn't know the shape of its own data.","detects":"pattern","source":{"name":"Fallbacks and guards that hide missing data (`?? []`, `.get(k, \"\")`, `hasattr` probes, catch that returns empty, long `?.` chains)","why":"A timeout looks like an empty result, and broken assumptions travel downstream.","links":[{"label":"Issue: agent adds unsafe fallbacks","url":"https://claudeissues.com/issue/31890-bug-error-handling-ignores-claude-md-directives-adds-unsafe-fallbacks-instead-of"},{"label":"Fallbacks are evil","url":"https://dev.to/tertiumnon/fallbacks-are-evil-5bh2"},{"label":"X post by karpathy","url":"https://x.com/karpathy/status/1976077806443569355"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/defensive-chaining","examples":{"flagged":[{"path":null,"text":"const c = a?.b?.c?.d;"}],"clean":[{"path":null,"text":"const c = a?.b;"}]}},{"id":"ts-enum","title":"TypeScript enum","severity":"low","category":"types","languages":["ts"],"scope":"any","why":"Enums generate objects, number enums accept any number, and they don't work with type-stripping runtimes.","fix":"Use a union of string literals, or an `as const` object.","bad":"export enum Status { Open, Closed }","good":"export type Status = \"open\" | \"closed\";","lang":"ts","research":"ts-enum","message":"A TypeScript `enum`. It emits runtime code and doesn't behave like the rest of the type system.","detects":"pattern","source":{"name":"New TypeScript `enum`","why":"Enums are not plain JavaScript, and numeric enums accept any number.","links":[],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/ts-enum","examples":{"flagged":[{"path":null,"text":"export enum Status {\n  Open,\n}"}],"clean":[{"path":null,"text":"export const STATUSES = ['a', 'b'] as const;"}]}},{"id":"trivial-assertion","title":"Assertion that can't fail","severity":"high","category":"tests","languages":["ts","py"],"scope":"test","why":"`expect(true).toBe(true)` makes a test look green and covered while checking nothing. Models write these to make a failing test pass.","fix":"Assert on the result of the code under test.","bad":"expect(true).toBe(true);","good":"expect(total(cart)).toBe(42);","lang":"ts","research":"no-assertion","message":"`expect(true).toBe` asserts a constant. It passes no matter what the code does.","detects":"pattern","source":{"name":"Tests with no assertion, assertions that cannot fail, and weak checks (`toBeDefined()`, `is not None`)","why":"The test passes for almost any wrong answer.","links":[{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"},{"label":"Tests that pass but test nothing","url":"https://dev.to/builtbyzac/claude-code-writes-tests-that-pass-but-dont-test-anything-heres-the-prompt-that-fixes-it-4e91"},{"label":"X post by mattpocockuk","url":"https://x.com/mattpocockuk/status/2093068185830347088"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/trivial-assertion","examples":{"flagged":[{"path":null,"text":"expect(true).toBe(true);"},{"path":"tests/test_a.py","text":"def test_a():\n    assert True\n"}],"clean":[{"path":null,"text":"expect(total).toBe(42);"}]}},{"id":"gate-weakened","title":"Check switched off in config","severity":"high","category":"tests","languages":["*"],"scope":"any","why":"Loosening `strict` or skipping a CI job makes every later change easier to break, and the PR looks like a config tweak.","fix":"Keep the gate and fix the errors it reports.","bad":"\"strict\": false","good":"\"strict\": true","lang":"ts","research":"gate-weakened","message":"Turns a quality gate down (\"strict\": false).","detects":"pattern","source":{"name":"Config that switches a gate off (`\"strict\": false`, `if: false`, a rule set to `off`)","why":"The check still runs and still passes, but it no longer checks anything.","links":[],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/gate-weakened","examples":{"flagged":[{"path":"tsconfig.json","text":"{\n  \"compilerOptions\": {\n    \"strict\": false\n  }\n}"}],"clean":[{"path":"tsconfig.json","text":"{\n  \"compilerOptions\": {\n    \"strict\": true\n  }\n}"}]}},{"id":"ci-escape-hatch","title":"CI failure ignored","severity":"high","category":"tests","languages":["*"],"scope":"any","why":"CI is only worth having if red means red. `|| true`, `continue-on-error` and `--no-verify` make failures look like success.","fix":"Remove the escape hatch and fix the failure. If a step is optional, delete it.","bad":"run: npm test || true","good":"run: npm test","lang":"ts","research":"ci-escape-hatch","message":"`|| true` lets a failing step pass.","detects":"pattern","source":{"name":"CI steps that ignore failure (`continue-on-error`, `\\|\\| true`, `--no-verify`) and test-only branches in shipped code","why":"Any check passes once you edit the check or the code path it runs.","links":[{"label":"Agents that game test suites (arXiv)","url":"https://arxiv.org/pdf/2611.10404"},{"label":"Reward hacking in coding agents (arXiv)","url":"https://arxiv.org/html/2511.21654v1"}],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/ci-escape-hatch","examples":{"flagged":[{"path":".github/workflows/ci.yml","text":"      - run: npm test || true\n"},{"path":".github/workflows/ci.yml","text":"    continue-on-error: true\n"}],"clean":[{"path":".github/workflows/ci.yml","text":"      - run: npm test\n"}]}},{"id":"exit-in-test","title":"Exits from a test","severity":"high","category":"tests","languages":["ts","py"],"scope":"test","why":"Exiting with 0 from inside a test makes the runner report success no matter what ran or failed.","fix":"Delete the exit. Let the test runner finish.","bad":"process.exit(0);","good":"expect(code).toBe(0);","lang":"ts","research":"early-exit-in-tests","message":"`process.exit(0)` ends the test run early, with a passing exit code.","detects":"pattern","source":{"name":"`process.exit(0)` or `sys.exit(0)` in tests or test helpers","why":"The run ends as a pass before later assertions execute.","links":[{"label":"Agents that game test suites (arXiv)","url":"https://arxiv.org/pdf/2611.10404"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/exit-in-test","examples":{"flagged":[{"path":null,"text":"process.exit(0);"}],"clean":[{"path":null,"text":"expect(code).toBe(0);"}]}},{"id":"focused-test","title":"Focused test","severity":"high","category":"tests","languages":["ts"],"scope":"test","why":"A committed `.only` turns a whole suite green by not running it.","fix":"Remove `.only`.","bad":"it.only(\"saves\", () => {});","good":"it(\"saves\", () => {});","lang":"ts","research":"focused-test","message":"`it.only` runs only this test. Every other test in the file is silently skipped.","detects":"pattern","source":{"name":"`.only`, `fit`, `fdescribe`","why":"A focused test silently turns off every other test in the file.","links":[{"label":"Reward hacking in coding agents (arXiv)","url":"https://arxiv.org/html/2511.21654v1"}],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/focused-test","examples":{"flagged":[{"path":null,"text":"it.only(\"a\", () => { expect(1).toBe(1); });"}],"clean":[{"path":null,"text":"it(\"a\", () => { expect(1).toBe(1); });"}]}},{"id":"mock-of-subject","title":"Mocks the code under test","severity":"high","category":"tests","languages":["ts","py"],"scope":"test","why":"When a test mocks the module it's named after, it tests the mock. It will pass while the real code is broken.","fix":"Mock only the edges (network, clock) or use real collaborators; never the subject itself.","bad":"// billing.test.ts\nvi.mock(\"./billing\");","good":"// billing.test.ts\nvi.mock(\"./payments-client\");","lang":"ts","research":"mock-heavy","message":"Mocks `./billing`, the module this test file is named after. The test no longer runs the code it claims to test.","detects":"structure","source":{"name":"Mocking the code under test, or mocking so much that the test checks only mocks","why":"The test proves the mock setup, not the code.","links":[{"label":"OWASP: Secure coding with AI","url":"https://cheatsheetseries.owasp.org/cheatsheets/Secure_Coding_with_AI_Cheat_Sheet.html"},{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/mock-of-subject","examples":{"flagged":[{"path":"src/billing.test.ts","text":"vi.mock(\"./billing\");\nit(\"a\", () => { expect(1).toBe(1); });\n"},{"path":"tests/test_billing.py","text":"@patch('app.billing.charge')\ndef test_a(m):\n    assert m\n"}],"clean":[{"path":"src/billing.test.ts","text":"vi.mock(\"./payments-client\");\nit(\"a\", () => { expect(1).toBe(1); });\n"}]}},{"id":"test-branch-in-prod","title":"Test-only branch in shipped code","severity":"high","category":"tests","languages":["ts","py"],"scope":"prod","why":"Branches on 'am I in a test?' mean the tests exercise a path production never takes.","fix":"Inject the dependency that differs (clock, client, store) and keep one code path.","bad":"if (process.env.NODE_ENV === 'test') return fakeUser;","good":"const user = await users.get(id); // tests pass an in-memory store","lang":"ts","research":"ci-escape-hatch","message":"Shipped code behaves differently under test (NODE_ENV === 'test'). The tests no longer check what runs in production.","detects":"pattern","source":{"name":"CI steps that ignore failure (`continue-on-error`, `\\|\\| true`, `--no-verify`) and test-only branches in shipped code","why":"Any check passes once you edit the check or the code path it runs.","links":[{"label":"Agents that game test suites (arXiv)","url":"https://arxiv.org/pdf/2611.10404"},{"label":"Reward hacking in coding agents (arXiv)","url":"https://arxiv.org/html/2511.21654v1"}],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/test-branch-in-prod","examples":{"flagged":[{"path":null,"text":"if (process.env.NODE_ENV === 'test') return 1;"},{"path":"src/app.py","text":"if 'pytest' in sys.modules:\n    pass\n"}],"clean":[{"path":null,"text":"if (process.env.NODE_ENV === 'production') {}"}]}},{"id":"assertions-removed","title":"Assertions removed","severity":"medium","category":"tests","languages":["*"],"scope":"test","why":"Deleting assertions is the quickest way to make a red test green. Sometimes right, often the bug fix that wasn't.","fix":"Keep the assertion and fix the code, or explain in the PR why the behavior changed.","bad":"- expect(total).toBe(42);\n+ // flaky, removed","good":"expect(total).toBe(42);","lang":"ts","research":"test-weakened","message":"This change removes 3 assertions from the test and adds 0. Check the test still proves what it used to.","detects":"change","source":{"name":"Assertions deleted, or expected values edited to match bad output","why":"It turns a red test green without fixing the bug.","links":[{"label":"Deslopping AI code","url":"https://www.anaconda.com/blog/deslopping-ai-code"},{"label":"What makes AI-generated code slop","url":"https://dev.to/d3lm/what-makes-ai-generated-code-slop-40on"},{"label":"Testing with coding agents","url":"https://developertoolkit.ai/en/claude-code/test/testing.md"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/assertions-removed","examples":{"flagged":[],"clean":[]}},{"id":"broad-raises","title":"Expects any error","severity":"medium","category":"tests","languages":["ts","py"],"scope":"test","why":"`toThrow()` with no argument or `pytest.raises(Exception)` passes when the code fails for an unrelated reason, like a typo.","fix":"Assert the error type and message: `toThrow(NotFoundError)`, `pytest.raises(ValueError, match=...)`.","bad":"expect(() => parse(x)).toThrow();","good":"expect(() => parse(x)).toThrow(/empty input/);","lang":"ts","research":"broad-raises","message":"The test passes on any error (.toThrow()), including the wrong one.","detects":"pattern","source":{"name":"`pytest.raises(Exception)`, or `toThrow()` with no argument","why":"The test passes on the wrong error.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/broad-raises","examples":{"flagged":[{"path":null,"text":"expect(() => parse(x)).toThrow();"},{"path":"tests/test_a.py","text":"def test_a():\n    with pytest.raises(Exception):\n        f()\n"}],"clean":[{"path":null,"text":"expect(() => parse(x)).toThrow(/empty/);"},{"path":null,"text":"expect(() => parse(x)).not.toThrow();"}]}},{"id":"sleep-in-test","title":"Fixed sleep in a test","severity":"medium","category":"tests","languages":["ts","py"],"scope":"test","why":"Sleeps make tests slow and flaky at once: they guess how long something takes instead of waiting for it.","fix":"Wait for the condition (`waitFor`, an event, a polled assertion) or use fake timers.","bad":"await sleep(500);\nexpect(list).toHaveLength(3);","good":"await waitFor(() => expect(list).toHaveLength(3));","lang":"ts","research":"sleep-in-test","message":"`await sleep(5` waits a fixed time. Too short on a slow CI box, wasted time everywhere else.","detects":"pattern","source":{"name":"Fixed sleeps and `setTimeout` waits, in tests and in shipped code","why":"It is slow when the state is ready and flaky when it is not.","links":[{"label":"Test smell catalog","url":"https://test-smell-catalog.readthedocs.io/"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/sleep-in-test","examples":{"flagged":[{"path":null,"text":"await sleep(500);"},{"path":"tests/test_a.py","text":"import time\ntime.sleep(1)\n"}],"clean":[{"path":null,"text":"await waitFor(() => done);"}]}},{"id":"test-retry","title":"Retries a flaky test","severity":"medium","category":"tests","languages":["*"],"scope":"any","why":"Auto-retries turn real races and order bugs into green builds. The flake is still there, now invisible.","fix":"Find why it flakes and fix that. Quarantine with an owner if you must, never blanket retries.","bad":"export default { retries: 2 };","good":"export default { retries: 0 };","lang":"ts","research":"test-retry","message":"Retries hide flakiness (retries: 2). A test that passes on the second try is still broken.","detects":"pattern","source":{"name":"Automatic retries for flaky tests","why":"A real race or ordering bug becomes a green build.","links":[],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/test-retry","examples":{"flagged":[{"path":"playwright.config.ts","text":"export default { retries: 2 };"}],"clean":[{"path":"playwright.config.ts","text":"export default { retries: 0 };"}]}},{"id":"skipped-test","title":"Skipped test","severity":"medium","category":"tests","languages":["ts","py"],"scope":"test","why":"Skipped tests are deleted tests that still look like coverage. They're how a red suite gets turned green without a fix.","fix":"Fix the test or the code. If the test is wrong, delete it and say why.","bad":"it.skip(\"handles refunds\", ...)","good":"it(\"handles refunds\", ...)","lang":"ts","research":"skipped-test","message":"`it.skip` turns a test off. Whatever it checked is no longer checked.","detects":"pattern","source":{"name":"`.skip`, `xit`, `@pytest.mark.skip`","why":"A skipped test counts as passing while it checks nothing.","links":[{"label":"Reward hacking in coding agents (arXiv)","url":"https://arxiv.org/html/2511.21654v1"}],"notes":["skill: ci-integrity-audit"]},"url":"https://redline.kevinliu.studio/rules/skipped-test","examples":{"flagged":[{"path":null,"text":"it.skip(\"a\", () => {});"},{"path":"tests/test_a.py","text":"@pytest.mark.skip\ndef test_a():\n    assert 1\n"}],"clean":[{"path":null,"text":"it(\"a\", () => { expect(1).toBe(1); });"}]}},{"id":"no-assertion","title":"Test without an assertion","severity":"medium","category":"tests","languages":["ts","py"],"scope":"test","why":"A test with no assertion only checks that nothing throws. It stays green when the code returns the wrong answer.","fix":"Assert on the result, the state change, or the error you expect.","bad":"it(\"computes tax\", () => {\n  computeTax(order);\n});","good":"it(\"computes tax\", () => {\n  expect(computeTax(order)).toBe(8.25);\n});","lang":"ts","research":"no-assertion","message":"This test never asserts anything. It passes as long as nothing throws.","detects":"structure","source":{"name":"Tests with no assertion, assertions that cannot fail, and weak checks (`toBeDefined()`, `is not None`)","why":"The test passes for almost any wrong answer.","links":[{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"},{"label":"Tests that pass but test nothing","url":"https://dev.to/builtbyzac/claude-code-writes-tests-that-pass-but-dont-test-anything-heres-the-prompt-that-fixes-it-4e91"},{"label":"X post by mattpocockuk","url":"https://x.com/mattpocockuk/status/2093068185830347088"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/no-assertion","examples":{"flagged":[{"path":null,"text":"it(\"works\", () => {\n  run();\n});\n"},{"path":"tests/test_a.py","text":"def test_a():\n    run()\n"}],"clean":[{"path":null,"text":"it(\"works\", () => {\n  expect(run()).toBe(1);\n});\n"},{"path":"tests/test_a.py","text":"def test_a():\n    with pytest.raises(ValueError):\n        run()\n"}]}},{"id":"mock-heavy","title":"Mock","severity":"low","category":"tests","languages":["ts","py"],"scope":"test","why":"Every mock is a place where the test checks your assumption about the other code instead of the code itself. Heavy mocking is how suites pass while production breaks.","fix":"Use the real implementation or an in-memory fake, and prefer one end-to-end check over many mocked units.","bad":"vi.mock(\"./db\");","good":"const db = createTestDb();","lang":"ts","research":"mock-heavy","message":"`vi.mock` replaces real code in this test. That seam is no longer tested.","detects":"pattern","source":{"name":"Mocking the code under test, or mocking so much that the test checks only mocks","why":"The test proves the mock setup, not the code.","links":[{"label":"OWASP: Secure coding with AI","url":"https://cheatsheetseries.owasp.org/cheatsheets/Secure_Coding_with_AI_Cheat_Sheet.html"},{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/mock-heavy","examples":{"flagged":[{"path":null,"text":"vi.mock(\"./db\");"},{"path":"tests/test_a.py","text":"def test_a(monkeypatch):\n    monkeypatch.setattr(x, 'y', 1)\n    assert x\n"}],"clean":[{"path":null,"text":"const db = createTestDb();"}]}},{"id":"test-named-for-history","title":"Test named after a ticket","severity":"low","category":"tests","languages":["ts","py"],"scope":"test","why":"'fixes bug 1234' tells the next reader nothing when it fails. The name should say what must stay true.","fix":"Name the behavior: 'rejects an empty title'.","bad":"it(\"fixes bug 1234\", () => {","good":"it(\"rejects an empty title\", () => {","lang":"ts","research":"test-named-for-history","message":"The test is named after a ticket or a review round, not the behavior it checks.","detects":"pattern","source":{"name":"Tests named after a ticket, bug number or review round","why":"The name says nothing once the round is over.","links":[],"notes":["skill: code-review","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/test-named-for-history","examples":{"flagged":[{"path":null,"text":"it(\"fixes bug 1234\", () => { expect(1).toBe(1); });"}],"clean":[{"path":null,"text":"it(\"rejects an empty name\", () => { expect(1).toBe(1); });"}]}},{"id":"weak-assertion","title":"Weak assertion","severity":"low","category":"tests","languages":["ts","py"],"scope":"test","why":"'It returned something' passes for wrong answers too. These assertions inflate coverage without catching regressions.","fix":"Assert the exact value or the property that matters.","bad":"expect(user).toBeDefined();","good":"expect(user.email).toBe(\"a@b.co\");","lang":"ts","research":"no-assertion","message":"`.toBeDefined()` only checks that something exists, not that it is right.","detects":"pattern","source":{"name":"Tests with no assertion, assertions that cannot fail, and weak checks (`toBeDefined()`, `is not None`)","why":"The test passes for almost any wrong answer.","links":[{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"},{"label":"Tests that pass but test nothing","url":"https://dev.to/builtbyzac/claude-code-writes-tests-that-pass-but-dont-test-anything-heres-the-prompt-that-fixes-it-4e91"},{"label":"X post by mattpocockuk","url":"https://x.com/mattpocockuk/status/2093068185830347088"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/weak-assertion","examples":{"flagged":[{"path":null,"text":"expect(u).toBeDefined();"},{"path":"tests/test_a.py","text":"def test_a():\n    assert user is not None\n"}],"clean":[{"path":null,"text":"expect(u.id).toBe(3);"}]}},{"id":"await-in-loop","title":"Await inside a loop (N+1)","severity":"medium","category":"perf","languages":["ts","py"],"scope":"any","why":"One round trip per item makes the loop as slow as the list is long. With a database call inside, it's the classic N+1 query.","fix":"Fetch everything in one batched call (`WHERE id IN (...)`), or run independent calls together with a concurrency cap.","bad":"for (const id of ids) {\n  users.push(await db.user.find(id));\n}","good":"const users = await db.user.findMany({ where: { id: { in: ids } } });","lang":"ts","research":"n-plus-one","message":"`await db.get` runs once per loop item, one after another. That's an N+1: batch it into one query or call.","detects":"structure","source":{"name":"A query, fetch or await per item in a loop","why":"One round trip per item makes the loop as slow as the list is long.","links":[{"label":"N+1 queries explained","url":"https://blog.appsignal.com/2020/06/09/n-plus-one-queries-explained.html"},{"label":"ESLint: no-await-in-loop","url":"https://eslint.org/docs/rules/no-await-in-loop"},{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/await-in-loop","examples":{"flagged":[{"path":null,"text":"async function f(ids) {\n  for (const id of ids) {\n    await db.get(id);\n  }\n}\n"},{"path":"src/app.py","text":"async def f(ids):\n    for i in ids:\n        await db.get(i)\n"}],"clean":[{"path":null,"text":"async function f(ids) {\n  await db.getMany(ids);\n}\n"},{"path":null,"text":"async function f(s) {\n  for await (const c of s) {\n    use(c);\n  }\n}\n"},{"path":null,"text":"async function f() {\n  for (let attempt = 0; attempt < 3; attempt++) {\n    await fetchIt();\n  }\n}\n"}]}},{"id":"sequential-awaits","title":"Awaits that could run together","severity":"medium","category":"perf","languages":["ts","py"],"scope":"any","why":"Each await waits for the one before. When the second call doesn't need the first one's result, the latency adds up for nothing.","fix":"Start both, then await both: `await Promise.all([a(), b()])` or `asyncio.gather(a(), b())`.","bad":"const user = await getUser(id);\nconst orders = await getOrders(id);","good":"const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);","lang":"ts","research":"sequential-awaits","message":"This await doesn't use the result of the one before it, so they could run at the same time.","detects":"structure","source":{"name":"Independent awaits run one after another","why":"Latency adds up when the second call does not need the first one's result.","links":[],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/sequential-awaits","examples":{"flagged":[{"path":null,"text":"async function f(id) {\n  const user = await getUser(id);\n  const orders = await getOrders(id);\n  return [user, orders];\n}\n"},{"path":"src/app.py","text":"async def f(i):\n    a = await get_a(i)\n    b = await get_b(i)\n    return a, b\n"}],"clean":[{"path":null,"text":"async function f(id) {\n  const user = await getUser(id);\n  const orders = await getOrders(user.id);\n  return orders;\n}\n"},{"path":null,"text":"async function f() {\n  await stepOne();\n  await stepTwo();\n}\n"}]}},{"id":"json-clone","title":"Deep copy through JSON","severity":"medium","category":"perf","languages":["ts","py"],"scope":"any","why":"The JSON round-trip is a slow, lossy deep copy that silently changes types.","fix":"`structuredClone(x)` in JavaScript, `copy.deepcopy(x)` in Python, or don't copy at all.","bad":"const copy = JSON.parse(JSON.stringify(state));","good":"const copy = structuredClone(state);","lang":"ts","research":"json-clone","message":"`JSON.parse(JSON.stringify` copies by serialising to a string and back. It's slow and drops Dates, Maps, undefined and NaN.","detects":"pattern","source":{"name":"Deep copy through `JSON.parse(JSON.stringify(x))`","why":"It is slow and silently drops or changes Dates, Maps, `undefined` and `NaN`.","links":[],"notes":["no outside source yet"]},"url":"https://redline.kevinliu.studio/rules/json-clone","examples":{"flagged":[{"path":null,"text":"const c = JSON.parse(JSON.stringify(s));"}],"clean":[{"path":null,"text":"const c = structuredClone(s);"}]}},{"id":"spread-accumulator","title":"Quadratic reduce","severity":"medium","category":"perf","languages":["ts"],"scope":"any","why":"`{...acc, [k]: v}` inside reduce rebuilds the whole object each iteration. Fine for 10 items, a stall for 10,000.","fix":"Mutate a local accumulator, or use `Object.fromEntries` / `new Map(...)`.","bad":"items.reduce((acc, i) => ({ ...acc, [i.id]: i }), {});","good":"Object.fromEntries(items.map((i) => [i.id, i]));","lang":"ts","research":"spread-accumulator","message":"Copies the accumulator on every step of `reduce`. That's O(n²) for a loop that should be O(n).","detects":"pattern","source":{"name":"`{...acc}` or `[...acc]` inside `reduce`","why":"Copying the accumulator on each step makes a linear loop quadratic.","links":[],"notes":["no outside source yet"]},"url":"https://redline.kevinliu.studio/rules/spread-accumulator","examples":{"flagged":[{"path":null,"text":"const m = xs.reduce((acc, x) => ({ ...acc, [x.id]: x }), {});"}],"clean":[{"path":null,"text":"const m = Object.fromEntries(xs.map((x) => [x.id, x]));"}]}},{"id":"select-star","title":"Reads whole rows","severity":"medium","category":"perf","languages":["*"],"scope":"any","why":"Whole-row reads move columns nobody uses, defeat covering indexes, and pull large JSON or text columns off disk on every call. They get slower as the table grows.","fix":"Select the columns you read: `select id, status from orders`.","bad":"db.query(\"SELECT * FROM orders WHERE user_id = $1\", [id]);","good":"db.query(\"SELECT id, status FROM orders WHERE user_id = $1\", [id]);","lang":"ts","research":"select-star","message":"Loads every column (SELECT * FROM). If the code reads a couple of fields, select just those.","detects":"pattern","source":{"name":"`SELECT *` and ORM reads of whole rows","why":"It moves and parses columns nobody reads, and it can leak new sensitive columns.","links":[{"label":"Finding SELECT * code smells","url":"https://www.red-gate.com/hub/product-learning/sql-prompt/finding-code-smells-using-sql-prompt-asterisk-select-list"},{"label":"Avoid SELECT * to prevent data leaks","url":"https://www.aikido.dev/code-quality/rules/how-to-avoid-select-in-sql-preventing-data-leaks"}],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/select-star","examples":{"flagged":[{"path":null,"text":"db.query(\"SELECT * FROM users\");"},{"path":null,"text":"await sb.from(\"t\").select(\"*\");"},{"path":null,"text":"const rows = await db.select().from(users);"}],"clean":[{"path":null,"text":"db.query(\"SELECT id FROM users\");"},{"path":null,"text":"const s = \"select * of them\";"}]}},{"id":"lookup-in-loop","title":"Array scan inside a loop","severity":"low","category":"perf","languages":["ts"],"scope":"any","why":"`.find` or `.includes` inside a loop scans the array once per item: O(n²). Unnoticeable at 50 items, a freeze at 50,000.","fix":"Build a `Set` or `Map` once before the loop and look up in O(1).","bad":"for (const o of orders) {\n  const u = users.find((u) => u.id === o.userId);\n}","good":"const byId = new Map(users.map((u) => [u.id, u]));\nfor (const o of orders) {\n  const u = byId.get(o.userId);\n}","lang":"ts","research":"lookup-in-loop","message":"`users.find()` scans the whole array on every pass of the loop. Build a Set or Map once before the loop.","detects":"structure","source":{"name":"`.find`, `.includes` or `.indexOf` inside a loop","why":"It scans the array once per item, which is quadratic work.","links":[],"notes":["skill: improve","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/lookup-in-loop","examples":{"flagged":[{"path":null,"text":"for (const o of orders) {\n  const u = users.find((u) => u.id === o.userId);\n}\n"}],"clean":[{"path":null,"text":"const byId = new Map();\nfor (const o of orders) {\n  const u = byId.get(o.userId);\n}\n"}]}},{"id":"sync-io","title":"Blocking file or process call","severity":"low","category":"perf","languages":["ts"],"scope":"prod","why":"Sync I/O in a server stops all concurrent work until the disk or child process returns.","fix":"Use the async version (`fs/promises`, `execFile`), or do it once at startup.","bad":"const tpl = fs.readFileSync(path, 'utf8');","good":"const tpl = await fs.promises.readFile(path, 'utf8');","lang":"ts","research":"sync-io","message":"`readFileSync` blocks the event loop. Every other request waits.","detects":"pattern","source":{"name":"Blocking file, process or HTTP calls in server or async code","why":"One blocking call stalls every other request on the event loop.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/sync-io","examples":{"flagged":[{"path":null,"text":"const a = fs.readFileSync(p);"}],"clean":[{"path":null,"text":"const a = await fs.promises.readFile(p);"},{"path":"scripts/gen.ts","text":"const a = fs.readFileSync(p);"}]}},{"id":"fstring-in-logger","title":"f-string in a log call","severity":"low","category":"perf","languages":["py"],"scope":"any","why":"f-strings run even when the level is off, and they defeat log grouping because every message is unique.","fix":"`logger.info(\"saved %s\", user_id)`.","bad":"logger.info(f\"saved {user_id}\")","good":"logger.info(\"saved %s\", user_id)","lang":"py","research":"fstring-in-logger","message":"Formats the log message before knowing it will be logged.","detects":"pattern","source":{"name":"f-strings inside log calls","why":"The string is built even when the level is off, and structured logging loses its fields.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"},{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/fstring-in-logger","examples":{"flagged":[{"path":null,"text":"logger.info(f\"saved {u}\")\n"}],"clean":[{"path":null,"text":"logger.info(\"saved %s\", u)\n"}]}},{"id":"new-url-parse","title":"Parses a URL to read one part","severity":"low","category":"perf","languages":["ts"],"scope":"any","why":"`new URL()` allocates, parses and validates the whole string. On a hot path, repeated parsing adds up, and often the framework already gives you the parsed piece.","fix":"Use the parsed value you already have (`req.nextUrl`, `request.path`), or parse once and pass it down.","bad":"const path = new URL(req.url).pathname;","good":"const path = req.nextUrl.pathname;","lang":"ts","research":"new-url-parse","message":"`new URL(req.url).pathname` builds a full URL object to read one piece.","detects":"pattern","source":{"name":"`new URL(x)` built only to read one part","why":"Full parsing on a hot path adds up, and the framework often has the part already.","links":[],"notes":["no outside source yet"]},"url":"https://redline.kevinliu.studio/rules/new-url-parse","examples":{"flagged":[{"path":null,"text":"const p = new URL(req.url).pathname;"},{"path":null,"text":"const u = new URL(request.url);"}],"clean":[{"path":null,"text":"const u = new URL(base, href);"}]}},{"id":"jsonb-hot-read","title":"Reads one key out of a JSON column","severity":"low","category":"perf","languages":["*"],"scope":"any","why":"A large jsonb value is stored out of line. Reading one key decompresses all of it, so a query that returns a few KB can read gigabytes.","fix":"If this runs often, promote the key to a real column (or a generated column) and index it.","bad":"SELECT data->>'status' FROM jobs WHERE id = $1","good":"SELECT status FROM jobs WHERE id = $1","lang":"ts","research":"jsonb-hot-read","message":"Pulls one key out of a JSON column (->>). On a hot path, Postgres reads (and detoasts) the whole document to get it.","detects":"pattern","source":{"name":"Reading one key out of a large JSON column on a hot path","why":"The database decompresses the whole document to return one field.","links":[],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/jsonb-hot-read","examples":{"flagged":[{"path":null,"text":"db.query(\"SELECT data->>'status' FROM jobs\");"},{"path":"db/q.sql","text":"select data->>'k' from t;\n"}],"clean":[{"path":null,"text":"db.query(\"SELECT status FROM jobs\");"}]}},{"id":"regex-in-function","title":"Regex built on every call","severity":"low","category":"perf","languages":["ts","py"],"scope":"any","why":"Compiling a regex costs far more than running it. Inside a function or loop, that cost repeats on every call.","fix":"Compile it once as a module-level constant.","bad":"function isSlug(s) {\n  return new RegExp('^[a-z-]+$').test(s);\n}","good":"const SLUG = /^[a-z-]+$/;\nfunction isSlug(s) {\n  return SLUG.test(s);\n}","lang":"ts","research":"regex-in-function","message":"Builds the same regex on every call. Compile it once at module level.","detects":"structure","source":{"name":"A regex compiled inside a function or loop","why":"The compile cost repeats on every call.","links":[{"label":"CytoScnPy: CSP-P005","url":"https://djinn-soul.github.io/CytoScnPy/rule/CSP-P005"},{"label":"Datadog: regexp in loop","url":"https://docs.datadoghq.com/code_analysis/static_analysis_rules/go-best-practices/loop-regexp-match"},{"label":"The recompilation tax","url":"https://alm0stsurely.github.io/2026/03/29/the-recompilation-tax-module-level-constants/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/regex-in-function","examples":{"flagged":[{"path":null,"text":"function f(s) {\n  return new RegExp('a+').test(s);\n}\n"},{"path":null,"text":"for (const s of xs) {\n  if (/a+b/.test(s)) n++;\n}\n"},{"path":"src/app.py","text":"import re\ndef f(s):\n    return re.compile('a+').match(s)\n"}],"clean":[{"path":null,"text":"const A = /a+/;\nfunction f(s) {\n  return A.test(s);\n}\n"},{"path":"src/app.py","text":"import re\nA = re.compile('a+')\ndef f(s):\n    return A.match(s)\n"}]}},{"id":"unbounded-fanout","title":"Unbounded parallel calls","severity":"low","category":"perf","languages":["ts","py"],"scope":"any","why":"Unbounded fan-out exhausts connection pools, trips rate limits and can take down the service it calls.","fix":"Cap concurrency (`p-limit`, a semaphore, batches).","bad":"await Promise.all(ids.map((id) => fetchUser(id)));","good":"await mapLimit(ids, 8, fetchUser);","lang":"ts","research":"unbounded-fanout","message":"`Promise.all(ids.map` starts one call per item, all at once. With 10,000 items that's 10,000 open requests.","detects":"pattern","source":{"name":"`Promise.all(items.map(...))` or `gather(*...)` with no limit","why":"Thousands of calls at once exhaust pools and trip rate limits.","links":[{"label":"What makes AI-generated code slop","url":"https://dev.to/d3lm/what-makes-ai-generated-code-slop-40on"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/unbounded-fanout","examples":{"flagged":[{"path":null,"text":"await Promise.all(ids.map((id) => get(id)));"},{"path":"src/app.py","text":"await asyncio.gather(*[f(x) for x in xs])\n"}],"clean":[{"path":null,"text":"await mapLimit(ids, 8, get);"}]}},{"id":"pipe-to-shell","title":"Download piped to a shell","severity":"high","category":"security","languages":["sh","ts","py"],"scope":"any","why":"`curl | sh` executes remote code with no review and no integrity check; a compromised host owns the machine.","fix":"Download, verify a checksum or signature, then run.","bad":"curl -fsSL https://example.org/install.sh | sh","good":"curl -fsSLO https://example.org/install.sh && sha256sum -c install.sh.sha256 && sh install.sh","lang":"ts","research":"pipe-to-shell","message":"Runs whatever the server sends, unseen.","detects":"pattern","source":{"name":"`curl ... \\| sh` install steps","why":"Whatever the server returns runs with no check.","links":[{"label":"OWASP: Secure coding with AI","url":"https://cheatsheetseries.owasp.org/cheatsheets/Secure_Coding_with_AI_Cheat_Sheet.html"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/pipe-to-shell","examples":{"flagged":[{"path":"scripts/setup.sh","text":"curl -fsSL https://example.org/i.sh | sh\n"}],"clean":[{"path":"scripts/setup.sh","text":"curl -fsSL -o i.sh https://example.org/i.sh\n"}]}},{"id":"eval-call","title":"eval","severity":"high","category":"security","languages":["ts","py"],"scope":"any","why":"If any part of the string comes from input, this is remote code execution. Even when it doesn't, it defeats static analysis and CSP.","fix":"Parse the data (`JSON.parse`, `ast.literal_eval`) or dispatch through a lookup table.","bad":"const fn = eval(userFormula);","good":"const fn = FORMULAS[name];","lang":"ts","research":"eval-call","message":"`eval` runs a string as code.","detects":"pattern","source":{"name":"`eval`, `exec` and `new Function`","why":"Dynamic code execution turns input into code.","links":[{"label":"OWASP: AJAX security","url":"https://cheatsheetseries.owasp.org/cheatsheets/AJAX_Security_Cheat_Sheet.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/eval-call","examples":{"flagged":[{"path":null,"text":"const r = eval(s);"},{"path":"src/app.py","text":"exec(code)\n"}],"clean":[{"path":null,"text":"const m = re.exec(s);"},{"path":null,"text":"const r = evaluate(s);"},{"path":null,"text":"class A {\n  override async exec(o) {}\n}"},{"path":"src/app.py","text":"def exec(self, cmd):\n    return cmd\n"}]}},{"id":"invisible-char","title":"Invisible character","severity":"high","category":"security","languages":["*"],"scope":"any","why":"Zero-width and bidi control characters can make code read differently from how it runs (the Trojan Source attack) and break string comparisons.","fix":"Delete it. If you need the character, write it as an escape like `\\u200b`.","bad":"if (role === \"admin​\") {}","good":"if (role === \"admin\") {}","lang":"ts","research":"invisible-char","message":"An invisible or direction-changing character. What you see is not what compiles.","detects":"pattern","source":{"name":"Zero-width and bidi control characters","why":"They hide content from reviewers in code and commits.","links":[{"label":"OWASP: Secure coding with AI","url":"https://cheatsheetseries.owasp.org/cheatsheets/Secure_Coding_with_AI_Cheat_Sheet.html"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/invisible-char","examples":{"flagged":[{"path":null,"text":"const a = \"x​y\";"},{"path":null,"text":"const b‮ = 1;"}],"clean":[{"path":null,"text":"const a = \"\\u200b\";"}]}},{"id":"client-exposed-secret","title":"Secret in a public env var","severity":"high","category":"security","languages":["*"],"scope":"any","why":"Public env prefixes inline the value into client JavaScript. A secret there is published.","fix":"Keep the secret server-side and call it through your own API.","bad":"process.env.NEXT_PUBLIC_PAYMENTS_SECRET","good":"process.env.PAYMENTS_SECRET // server only","lang":"ts","research":"client-exposed-secret","message":"`NEXT_PUBLIC_PAYMENTS_SECRET` is bundled into the browser build, where anyone can read it.","detects":"pattern","source":{"name":"Secrets in public env vars (`NEXT_PUBLIC_*`, `VITE_*`)","why":"Anything with a public prefix ships to every browser.","links":[],"notes":["skill: vibe-code-doctor","skill: react-doctor"]},"url":"https://redline.kevinliu.studio/rules/client-exposed-secret","examples":{"flagged":[{"path":null,"text":"const s = process.env.NEXT_PUBLIC_PAYMENTS_SECRET;"}],"clean":[{"path":null,"text":"const k = process.env.NEXT_PUBLIC_PAYMENTS_PUBLISHABLE_KEY;"}]}},{"id":"hardcoded-secret","title":"Secret in source","severity":"high","category":"security","languages":["*"],"scope":"any","why":"Anything committed is copied to every clone, fork and CI log, and stays in history after you delete it.","fix":"Revoke it now, then load it from a secret store or the environment.","bad":"const apiKey = \"sk-live-4f9a…\";","good":"const apiKey = config.apiKey;","lang":"ts","research":"hardcoded-secret","message":"Looks like a real credential in source.","detects":"pattern","source":{"name":"Credentials in source, and secrets read with a fallback default","why":"A committed secret stays exposed, even after it is deleted.","links":[{"label":"CWE-798","url":"https://cwe.mitre.org/data/definitions/798.html"},{"label":"Secret detection rule process","url":"https://handbook.gitlab.com/handbook/engineering/development/sec/secure/secret-detection/rule-development-process/"},{"label":"Vibe coding security risks","url":"https://www.ibm.com/think/insights/vibe-coding-security-risks"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/hardcoded-secret","examples":{"flagged":[{"path":null,"text":"const k = \"AKIAABCDEFGHIJKLMNOP\";"},{"path":null,"text":"password = \"hunter2hunter2\""}],"clean":[{"path":null,"text":"const k = process.env.KEY;"},{"path":null,"text":"password = \"changeme-example\""}]}},{"id":"default-secret","title":"Secret with a fallback value","severity":"high","category":"security","languages":["ts","py"],"scope":"any","why":"If the variable is unset in production, the app quietly runs with a secret that's in the repo.","fix":"Fail at startup when a required secret is missing.","bad":"const secret = process.env.JWT_SECRET || \"dev-secret\";","good":"const secret = required(\"JWT_SECRET\");","lang":"ts","research":"hardcoded-secret","message":"A secret falls back to a literal when the env var is missing (process.env.JWT_SECRET || \").","detects":"pattern","source":{"name":"Credentials in source, and secrets read with a fallback default","why":"A committed secret stays exposed, even after it is deleted.","links":[{"label":"CWE-798","url":"https://cwe.mitre.org/data/definitions/798.html"},{"label":"Secret detection rule process","url":"https://handbook.gitlab.com/handbook/engineering/development/sec/secure/secret-detection/rule-development-process/"},{"label":"Vibe coding security risks","url":"https://www.ibm.com/think/insights/vibe-coding-security-risks"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/default-secret","examples":{"flagged":[{"path":null,"text":"const s = process.env.JWT_SECRET || \"dev\";"}],"clean":[{"path":null,"text":"const s = required('JWT_SECRET');"}]}},{"id":"secret-in-log","title":"Secret written to a log","severity":"high","category":"security","languages":["ts","py"],"scope":"any","why":"Credentials in logs end up in log search, vendor dashboards and support tickets, with weaker access control than the secret store.","fix":"Log an id or a fingerprint, never the value.","bad":"logger.info(\"auth\", { token });","good":"logger.info(\"auth\", { userId });","lang":"ts","research":"secret-in-log","message":"Logs something that looks secret (console.log(\"token\", token). Logs are read by more people and tools than the database.","detects":"pattern","source":{"name":"Passwords, tokens or keys written to logs","why":"Logs and error trackers keep the secret and share it widely.","links":[],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/secret-in-log","examples":{"flagged":[{"path":null,"text":"console.log(\"token\", token);"},{"path":"src/app.py","text":"logging.info('password=%s', pw)\n"}],"clean":[{"path":null,"text":"console.log(user.id);"},{"path":null,"text":"console.log(tokenCount);"}]}},{"id":"shell-injection","title":"Shell command from strings","severity":"high","category":"security","languages":["ts","py"],"scope":"any","why":"A filename with `;` or `$()` in it becomes a second command. Shell parsing is the bug.","fix":"Pass an argument list without a shell: `execFile(cmd, args)`, `subprocess.run([cmd, *args])`.","bad":"exec(`convert ${file} out.png`);","good":"execFile(\"convert\", [file, \"out.png\"]);","lang":"ts","research":"shell-injection","message":"Runs a shell command assembled from strings (exec(`rm ${).","detects":"pattern","source":{"name":"Shell commands built from strings (`shell=True`, `os.system`, `exec` with a template)","why":"A crafted input runs an extra command.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/shell-injection","examples":{"flagged":[{"path":null,"text":"exec(`rm ${p}`);"},{"path":"src/app.py","text":"subprocess.run(cmd, shell=True)\n"}],"clean":[{"path":null,"text":"execFile(\"rm\", [p]);"}]}},{"id":"sql-injection","title":"SQL built from strings","severity":"high","category":"security","languages":["ts","py"],"scope":"any","why":"String-built SQL is the textbook injection bug. Escaping by hand misses cases; parameters don't.","fix":"Use bound parameters (`$1`, `%s`, `?`) or the query builder's tagged template.","bad":"db.query(`SELECT id FROM users WHERE email = '${email}'`);","good":"db.query(\"SELECT id FROM users WHERE email = $1\", [email]);","lang":"ts","research":"sql-injection","message":"Builds SQL by pasting values into the string. Any of them can rewrite the query.","detects":"pattern","source":{"name":"SQL built by string concatenation or interpolation","why":"Untrusted input is parsed as SQL.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"},{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/sql-injection","examples":{"flagged":[{"path":null,"text":"db.query(`SELECT * FROM t WHERE id = ${id}`);"},{"path":"src/app.py","text":"cur.execute(f\"SELECT * FROM t WHERE id = {id}\")\n"}],"clean":[{"path":null,"text":"db.query(\"SELECT id FROM t WHERE id = $1\", [id]);"},{"path":null,"text":"db.query(sql`SELECT id FROM t WHERE id = ${id}`);"},{"path":null,"text":"notes.push(`delete ${name}`);"}]}},{"id":"tls-off","title":"TLS verification off","severity":"high","category":"security","languages":["*"],"scope":"any","why":"Disabled TLS verification is usually added to get past a dev certificate error and then ships.","fix":"Trust the right CA (pass `ca`, set `REQUESTS_CA_BUNDLE`) instead of disabling verification.","bad":"https.request(url, { rejectUnauthorized: false });","good":"https.request(url, { ca: internalCa });","lang":"ts","research":"tls-off","message":"Turns off certificate checks (rejectUnauthorized: false). Anyone on the network path can read and change this traffic.","detects":"pattern","source":{"name":"TLS certificate verification turned off","why":"Anyone on the network path can read and change the traffic.","links":[{"label":"Bandit B501","url":"https://bandit.readthedocs.io/en/1.7.6/plugins/b501_request_with_no_cert_validation.html"},{"label":"CodeQL: request without cert validation","url":"https://codeql.github.com/codeql-query-help/python/py-request-without-cert-validation"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/tls-off","examples":{"flagged":[{"path":null,"text":"const a = { rejectUnauthorized: false };"},{"path":"src/app.py","text":"requests.get(u, verify=False, timeout=3)\n"}],"clean":[{"path":null,"text":"const a = { ca };"}]}},{"id":"jwt-unverified","title":"Token decoded without verifying","severity":"high","category":"security","languages":["ts","py"],"scope":"any","why":"Anyone can write a JWT. Without signature verification, the claims (user id, role) are whatever the caller wants.","fix":"Use `jwt.verify` (or `decode` with the key and allowed algorithms).","bad":"const { sub } = jwt.decode(token);","good":"const { sub } = jwt.verify(token, key, { algorithms: ['RS256'] });","lang":"ts","research":"jwt-unverified","message":"Reads a token's claims without checking its signature (jwt.decode).","detects":"pattern","source":{"name":"A JWT decoded without verifying its signature","why":"Anyone can write the claims, so user id and role are whatever the caller wants.","links":[],"notes":["no outside source yet"]},"url":"https://redline.kevinliu.studio/rules/jwt-unverified","examples":{"flagged":[{"path":null,"text":"const c = jwt.decode(token);"}],"clean":[{"path":null,"text":"const c = jwt.verify(token, key);"}]}},{"id":"unsafe-deserialize","title":"Unsafe deserialization","severity":"high","category":"security","languages":["py"],"scope":"any","why":"Pickle and full YAML loaders construct arbitrary objects. Loading untrusted bytes with them is code execution.","fix":"Use JSON, `yaml.safe_load`, or a schema-validated format.","bad":"cfg = yaml.load(text)","good":"cfg = yaml.safe_load(text)","lang":"py","research":"unsafe-deserialize","message":"`pickle.loads` can execute code hidden in the data.","detects":"pattern","source":{"name":"`pickle`, unsafe `yaml.load` and `marshal` on input","why":"Deserializing untrusted data can run code.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":["skill: improve"]},"url":"https://redline.kevinliu.studio/rules/unsafe-deserialize","examples":{"flagged":[{"path":null,"text":"data = pickle.loads(blob)\n"},{"path":null,"text":"c = yaml.load(t)\n"}],"clean":[{"path":null,"text":"c = yaml.safe_load(t)\n"}]}},{"id":"tar-extractall","title":"Archive extracted unchecked","severity":"medium","category":"security","languages":["py"],"scope":"any","why":"Archive entries like `../../etc/cron.d/x` escape the destination (path traversal, 'tar slip').","fix":"`tar.extractall(dest, filter=\"data\")`.","bad":"tar.extractall(dest)","good":"tar.extractall(dest, filter=\"data\")","lang":"py","research":"tar-extractall","message":"`extractall` without a filter can write outside the target folder.","detects":"pattern","source":{"name":"`tarfile.extractall` with no filter","why":"A crafted archive writes files outside the target folder.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/tar-extractall","examples":{"flagged":[{"path":null,"text":"tar.extractall(dest)\n"}],"clean":[{"path":null,"text":"tar.extractall(dest, filter=\"data\")\n"}]}},{"id":"token-in-localstorage","title":"Auth token in localStorage","severity":"medium","category":"security","languages":["ts"],"scope":"any","why":"One XSS bug, or one bad npm package, can read localStorage and take the session.","fix":"Keep sessions in `HttpOnly`, `Secure`, `SameSite` cookies.","bad":"localStorage.setItem(\"authToken\", token);","good":"// the server sets an HttpOnly session cookie","lang":"ts","research":"token-in-localstorage","message":"Stores a credential where any script on the page can read it.","detects":"pattern","source":{"name":"Auth tokens in `localStorage`","why":"Any injected script can read them.","links":[{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/token-in-localstorage","examples":{"flagged":[{"path":null,"text":"localStorage.setItem(\"authToken\", t);"}],"clean":[{"path":null,"text":"localStorage.setItem(\"theme\", \"dark\");"}]}},{"id":"cors-wildcard","title":"CORS open to every origin","severity":"medium","category":"security","languages":["*"],"scope":"any","why":"A wildcard origin lets any page in a user's browser read these responses. With credentials it's an account takeover path.","fix":"List the origins that need access.","bad":"app.use(cors());","good":"app.use(cors({ origin: [\"https://app.example.com\"] }));","lang":"ts","research":"cors-wildcard","message":"Allows any website to call this (cors()).","detects":"pattern","source":{"name":"CORS open to every origin","why":"Any site can call the API from a user's browser.","links":[],"notes":["skill: improve","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/cors-wildcard","examples":{"flagged":[{"path":null,"text":"app.use(cors());"},{"path":null,"text":"res.setHeader(\"Access-Control-Allow-Origin\", \"*\");"}],"clean":[{"path":null,"text":"app.use(cors({ origin: allowed }));"}]}},{"id":"insecure-random","title":"Math.random for a secret","severity":"medium","category":"security","languages":["ts","py"],"scope":"any","why":"`Math.random` and `random` are seeded PRNGs; an attacker who sees a few outputs can predict the next.","fix":"`crypto.randomUUID()` / `crypto.getRandomValues()`, or Python's `secrets` module.","bad":"const token = Math.random().toString(36).slice(2);","good":"const token = crypto.randomUUID();","lang":"ts","research":"weak-crypto","message":"`Math.random()` is predictable. It must not generate tokens or secrets.","detects":"pattern","source":{"name":"MD5 or SHA-1 for security, and `Math.random` or `random` for tokens","why":"Hashes collide, and tokens become predictable.","links":[{"label":"CodeQL: insecure randomness","url":"https://codeql.github.com/codeql-query-help/javascript/js-insecure-randomness"},{"label":"CWE-338","url":"https://cwe.mitre.org/data/definitions/338.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/insecure-random","examples":{"flagged":[{"path":null,"text":"const token = Math.random().toString(36);"}],"clean":[{"path":null,"text":"const jitter = Math.random() * 100;"}]}},{"id":"html-injection","title":"Raw HTML","severity":"medium","category":"security","languages":["ts","py","text"],"scope":"any","why":"Raw HTML bypasses the framework's escaping. One unescaped field is enough to run script in your users' sessions.","fix":"Render text, or sanitize with a vetted library (DOMPurify) right at this spot.","bad":"<div dangerouslySetInnerHTML={{ __html: comment.body }} />","good":"<div>{comment.body}</div>","lang":"ts","research":"html-injection","message":"Inserts raw HTML (.innerHTML =). If any of it comes from a user, that's XSS.","detects":"pattern","source":{"name":"Raw HTML sinks (`innerHTML`, `dangerouslySetInnerHTML`) and `target=\"_blank\"` without `rel`","why":"Untrusted strings run as script, and an opened page can redirect yours.","links":[{"label":"OWASP: DOM XSS prevention","url":"https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html"},{"label":"OWASP: web frontend security","url":"https://cheatsheetseries.owasp.org/cheatsheets/Web_Frontend_Security_Cheat_Sheet.html"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/html-injection","examples":{"flagged":[{"path":null,"text":"el.innerHTML = html;"},{"path":null,"text":"<div dangerouslySetInnerHTML={{ __html: x }} />"}],"clean":[{"path":null,"text":"el.textContent = text;"}]}},{"id":"request-to-path","title":"Request data in a file path or URL","severity":"medium","category":"security","languages":["ts","py"],"scope":"any","why":"`../` in a path reads files outside the folder; a user-chosen URL lets them make your server call internal services (SSRF).","fix":"Map the input to an allowed value (an id to a known path or host) instead of using it directly.","bad":"res.sendFile(req.query.file);","good":"res.sendFile(FILES[req.query.id]);","lang":"ts","research":"path-traversal","message":"Passes request input straight to a file path or outbound URL (sendFile(req.query).","detects":"pattern","source":{"name":"Request data passed into a file path or an outbound URL","why":"`../` reads files outside the folder, and a chosen URL reaches internal services.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/request-to-path","examples":{"flagged":[{"path":null,"text":"res.sendFile(req.query.file);"},{"path":null,"text":"await fetch(req.body.url);"}],"clean":[{"path":null,"text":"res.sendFile(FILES[id]);"}]}},{"id":"secret-in-url","title":"Secret in a URL","severity":"medium","category":"security","languages":["ts","py"],"scope":"any","why":"URLs are logged everywhere: load balancers, CDNs, analytics, referrer headers.","fix":"Send it in an `Authorization` header.","bad":"fetch(`${BASE}/items?api_key=${key}`)","good":"fetch(`${BASE}/items`, { headers: { Authorization: `Bearer ${key}` } })","lang":"ts","research":"secret-in-url","message":"Puts a credential in a query string, where proxies, logs and browser history keep it.","detects":"pattern","source":{"name":"Tokens or keys in URL query strings","why":"Proxies, server logs and browser history keep the URL.","links":[],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/secret-in-url","examples":{"flagged":[{"path":null,"text":"fetch(`${BASE}/v1/items?api_key=${key}`);"}],"clean":[{"path":null,"text":"fetch(`${BASE}/v1/items?page=${n}`);"}]}},{"id":"unpinned-action","title":"CI action not pinned","severity":"low","category":"security","languages":["*"],"scope":"any","why":"Tags can be moved to new code. A compromised action runs with your CI secrets.","fix":"Pin the full commit SHA and let a bot update it.","bad":"uses: actions/checkout@v4","good":"uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4","lang":"ts","research":"unpinned-actions","message":"A third-party action pinned to a moving tag (- uses: actions/checkout@v4).","detects":"pattern","source":{"name":"CI actions referenced by tag or branch instead of a commit SHA","why":"A moved tag runs new third-party code in CI.","links":[{"label":"OWASP: Secure coding with AI","url":"https://cheatsheetseries.owasp.org/cheatsheets/Secure_Coding_with_AI_Cheat_Sheet.html"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/unpinned-action","examples":{"flagged":[{"path":".github/workflows/ci.yml","text":"      - uses: actions/checkout@v4\n"}],"clean":[{"path":".github/workflows/ci.yml","text":"      - uses: ./local-action\n"}]}},{"id":"target-blank","title":"target=_blank without rel","severity":"low","category":"security","languages":["ts","text"],"scope":"any","why":"Older browsers give the opened page a handle to yours (`window.opener`) that can redirect it.","fix":"Add `rel=\"noopener noreferrer\"`.","bad":"<a href={url} target=\"_blank\">","good":"<a href={url} target=\"_blank\" rel=\"noopener noreferrer\">","lang":"ts","research":"html-injection","message":"Opens a new tab without `rel=\"noopener\"`.","detects":"pattern","source":{"name":"Raw HTML sinks (`innerHTML`, `dangerouslySetInnerHTML`) and `target=\"_blank\"` without `rel`","why":"Untrusted strings run as script, and an opened page can redirect yours.","links":[{"label":"OWASP: DOM XSS prevention","url":"https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html"},{"label":"OWASP: web frontend security","url":"https://cheatsheetseries.owasp.org/cheatsheets/Web_Frontend_Security_Cheat_Sheet.html"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/target-blank","examples":{"flagged":[{"path":null,"text":"<a href={u} target=\"_blank\">x</a>"}],"clean":[{"path":null,"text":"<a href={u} target=\"_blank\" rel=\"noopener\">x</a>"}]}},{"id":"weak-hash","title":"Weak hash","severity":"low","category":"security","languages":["ts","py"],"scope":"any","why":"MD5 and SHA-1 have practical collisions. Fine for cache keys, wrong for passwords, signatures or integrity checks.","fix":"SHA-256 for integrity, a password hash (argon2, bcrypt, scrypt) for passwords. Mark non-security uses explicitly.","bad":"crypto.createHash('md5').update(password)","good":"await argon2.hash(password)","lang":"ts","research":"weak-crypto","message":"`createHash('md5')` is broken for security use.","detects":"pattern","source":{"name":"MD5 or SHA-1 for security, and `Math.random` or `random` for tokens","why":"Hashes collide, and tokens become predictable.","links":[{"label":"CodeQL: insecure randomness","url":"https://codeql.github.com/codeql-query-help/javascript/js-insecure-randomness"},{"label":"CWE-338","url":"https://cwe.mitre.org/data/definitions/338.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/weak-hash","examples":{"flagged":[{"path":null,"text":"crypto.createHash('md5');"},{"path":"src/app.py","text":"hashlib.md5(b)\n"}],"clean":[{"path":null,"text":"crypto.createHash('sha256');"}]}},{"id":"compat-shim","title":"Compatibility shim","severity":"medium","category":"design","languages":["*"],"scope":"any","why":"Compatibility layers and legacy aliases mean every reader has to learn both paths, and the old one never gets deleted.","fix":"Do a clean cutover: update every caller, delete the old code and the shim in the same change.","bad":"// kept for backwards compatibility\nexport const getUserLegacy = getUser;","good":"// (alias deleted; callers use getUser)","lang":"ts","research":"compat-shim","message":"Keeps an old path alive (backwards compatibility). Two ways to do one thing is the start of entropy.","detects":"pattern","source":{"name":"Compatibility shims and old/new switches kept beside the replacement","why":"Two paths double the places a bug can live, and the old one is never tested.","links":[{"label":"Issue: agent keeps adding backwards compatibility","url":"https://claudeissues.com/issue/2488-persistent-backwards-compatibility-insertion-despite-user-rejection"},{"label":"Piranha: stale flag cleanup","url":"https://www.uber.com/blog/piranha/"}],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/compat-shim","examples":{"flagged":[{"path":null,"text":"// kept for backwards compatibility"},{"path":null,"text":"export const loadLegacy = load;"}],"clean":[{"path":null,"text":"// Loads users by id."}]}},{"id":"deep-nesting","title":"Deep nesting","severity":"medium","category":"design","languages":["ts","py"],"scope":"any","why":"Every nested `if` or loop is another condition to keep in mind. Past three or four, readers lose track of which case they're in.","fix":"Return early for the edge cases, and pull inner loops into named functions.","bad":"if (a) {\n  for (x of xs) {\n    if (b) {\n      while (c) {\n        if (d) {}\n      }\n    }\n  }\n}","good":"if (!a) return;\nfor (const x of xs) handle(x);","lang":"ts","research":"deep-nesting","message":"Control flow nests 5 levels deep in `f`. Each level is one more condition to hold in your head.","detects":"structure","source":{"name":"Deeply nested blocks","why":"Each level adds a condition the reader must track.","links":[{"label":"ESLint rules","url":"https://eslint.org/docs/v8.x/rules/"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"},{"label":"15 AI coding tools scored with a linter","url":"https://dev.to/yuvrajangadsingh/i-scored-15-ai-coding-tools-with-a-linter-the-gap-between-them-is-8x-3lp9"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/deep-nesting","examples":{"flagged":[{"path":null,"text":"function f() {\n  if (a) {\n    for (const x of xs) {\n      if (b) {\n        while (c) {\n          if (d) {\n            go();\n          }\n        }\n      }\n    }\n  }\n}\n"},{"path":"src/app.py","text":"def f():\n    if a:\n        for x in xs:\n            if b:\n                while c:\n                    if d:\n                        go()\n"}],"clean":[{"path":null,"text":"function f() {\n  if (a) {\n    go();\n  }\n}\n"}]}},{"id":"duplicate-block","title":"Duplicated block","severity":"medium","category":"design","languages":["ts","py","c"],"scope":"prod","why":"Copy-pasted code drifts: a fix lands in one copy and not the other. Models duplicate rather than find the existing helper.","fix":"Keep one copy and call it from both places, or delete the old one if this replaces it.","bad":"// a.ts and b.ts both carry the same 12-line validation","good":"// both call validateOrder() from orders/validate.ts","lang":"ts","research":"duplicate-block","message":"These lines repeat lines 12-19 in `src/orders/validate.ts`. Two copies drift apart; keep one.","detects":"change","source":{"name":"Copy-pasted blocks","why":"A fix lands in one copy and not the other.","links":[{"label":"AI coding and code duplication","url":"https://thenewstack.io/ai-coding-duplication-rose/"},{"label":"5 code smells only AI creates","url":"https://dev.to/bzprchny/5-code-smells-only-ai-creates-and-how-to-detect-them-1e3l"},{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/duplicate-block","examples":{"flagged":[],"clean":[]}},{"id":"long-function","title":"Long function","severity":"medium","category":"design","languages":["ts","py"],"scope":"any","why":"Long functions mix several jobs. They're hard to name, test and change without breaking a part you didn't read.","fix":"Split along the jobs it does. Each piece gets a name that says what it returns.","bad":"function checkout(cart) {\n  // 140 lines: validate, price, tax, charge, email\n}","good":"function checkout(cart) {\n  const order = price(validate(cart));\n  return charge(order).then(sendReceipt);\n}","lang":"ts","research":"long-function","message":"`big` is 72 lines long. Past 60, a function usually does more than one job.","detects":"structure","source":{"name":"Long functions, and long files that keep growing","why":"Past a certain size a reader cannot hold the unit in mind.","links":[{"label":"Refactoring Guru: code smells","url":"https://refactoring.guru/refactoring/smells"},{"label":"Smells in AI-generated code (paper)","url":"https://huggingface.co/papers/2605.02741.md"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/long-function","examples":{"flagged":[{"path":null,"text":"function big() {\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n  step();\n}\n"},{"path":"src/app.py","text":"def big():\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n    step()\n"}],"clean":[{"path":null,"text":"function small() {\n  step();\n}\n"}]}},{"id":"feature-toggle","title":"Old/new switch","severity":"medium","category":"design","languages":["ts","py"],"scope":"any","why":"A toggle that keeps the old path alive doubles the states to test, and the old path rots because nobody runs it.","fix":"Cut over: move every caller to the new path and delete the old one and the switch.","bad":"if (process.env.USE_NEW_PARSER) { parseNew(x) } else { parse(x) }","good":"parse(x)","lang":"ts","research":"compat-shim","message":"A switch between two code paths (process.env.USE_NEW_PARSER). Both paths now have to work and be tested.","detects":"pattern","source":{"name":"Compatibility shims and old/new switches kept beside the replacement","why":"Two paths double the places a bug can live, and the old one is never tested.","links":[{"label":"Issue: agent keeps adding backwards compatibility","url":"https://claudeissues.com/issue/2488-persistent-backwards-compatibility-insertion-despite-user-rejection"},{"label":"Piranha: stale flag cleanup","url":"https://www.uber.com/blog/piranha/"}],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/feature-toggle","examples":{"flagged":[{"path":null,"text":"if (process.env.USE_NEW_PARSER) {}"},{"path":"src/app.py","text":"if os.environ.get('ENABLE_V2'):\n    pass\n"}],"clean":[{"path":null,"text":"if (process.env.NODE_ENV) {}"}]}},{"id":"pass-through","title":"Pass-through wrapper","severity":"medium","category":"design","languages":["ts","py"],"scope":"any","why":"A function that only forwards its arguments adds a name to learn and a hop to follow, and hides nothing. Ousterhout calls this a shallow module.","fix":"Delete it and call the inner function. Keep a wrapper only when it adds a real decision or hides a detail.","bad":"export function getUser(id) {\n  return db.getUser(id);\n}","good":"// callers use db.getUser(id) directly","lang":"ts","research":"pass-through","message":"`getUser` only forwards its arguments to `db.getUser`. Callers could call `db.getUser` directly.","detects":"structure","source":{"name":"Functions that only forward their arguments to another function","why":"They add a name to learn and hide nothing.","links":[{"label":"Ousterhout's design red flags","url":"https://dev.to/sportebois/software-design-red-flags-wisdom-nuggets-from-john-ousterhout-43i2"},{"label":"Notes on A Philosophy of Software Design","url":"https://lethain.com/notes-philosophy-software-design/"},{"label":"Refactoring Guru: code smells","url":"https://refactoring.guru/refactoring/smells"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/pass-through","examples":{"flagged":[{"path":null,"text":"export function getUser(id) {\n  return db.getUser(id);\n}\n"},{"path":null,"text":"const load = (a, b) => fetchAll(a, b);\n"},{"path":"src/app.py","text":"def get_user(uid):\n    return db.get_user(uid)\n"}],"clean":[{"path":null,"text":"export function getUser(id) {\n  return db.getUser(id, { cache: true });\n}\n"},{"path":"src/app.py","text":"def get_user(uid):\n    return db.get_user(str(uid))\n"}]}},{"id":"unreachable-code","title":"Unreachable code","severity":"medium","category":"design","languages":["ts","py"],"scope":"any","why":"Code after a `return` never runs. It misleads readers and usually means a merge or edit went wrong.","fix":"Delete it, or move it before the return if it was meant to run.","bad":"return total;\nlog(total);","good":"log(total);\nreturn total;","lang":"ts","research":"dead-code","message":"This line comes right after a `return`/`throw` in the same block, so it never runs.","detects":"structure","source":{"name":"Unreachable code after `return`, `throw` or `raise`","why":"Dead code is read and kept for nothing, and it hides which path is live.","links":[{"label":"Refactoring Guru: code smells","url":"https://refactoring.guru/refactoring/smells"},{"label":"The coding personalities of leading LLMs","url":"https://www.sonarsource.com/sem/the-coding-personalities-of-leading-llms/claude/"},{"label":"X post by gabriberton","url":"https://x.com/gabriberton/status/2042141119837012284"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/unreachable-code","examples":{"flagged":[{"path":null,"text":"function f() {\n  return 1;\n  go();\n}\n"},{"path":"src/app.py","text":"def f():\n    return 1\n    go()\n"}],"clean":[{"path":null,"text":"function f() {\n  go();\n  return 1;\n}\n"}]}},{"id":"boolean-args","title":"Boolean arguments","severity":"low","category":"design","languages":["ts","py"],"scope":"any","why":"`render(user, true, false)` hides intent and makes swapping two flags a silent bug.","fix":"Pass an options object or keyword arguments, or split into two functions.","bad":"render(user, true, false);","good":"render(user, { compact: true, editable: false });","lang":"ts","research":"boolean-args","message":"Bare booleans in a call (r(u, true, false). At the call site nobody can tell what they mean.","detects":"pattern","source":{"name":"Bare `true` or `false` arguments","why":"The call site does not say what the flag means.","links":[{"label":"Fowler: Flag argument","url":"https://martinfowler.com/bliki/FlagArgument.html"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/boolean-args","examples":{"flagged":[{"path":null,"text":"render(u, true, false);"},{"path":"src/app.py","text":"draw(x, True, False)\n"}],"clean":[{"path":null,"text":"render(u, { compact: true });"}]}},{"id":"else-after-return","title":"else after return","severity":"low","category":"design","languages":["ts","py"],"scope":"any","why":"When the `if` branch returns, the `else` only adds indentation. Early returns keep the main path flat.","fix":"Drop the `else` and dedent its body.","bad":"if (!user) {\n  return null;\n} else {\n  return user.name;\n}","good":"if (!user) return null;\nreturn user.name;","lang":"ts","research":"else-after-return","message":"`else` after a `return`. The early exit already handles the other case; drop the `else` and unindent.","detects":"structure","source":{"name":"`else` after a branch that returns","why":"It adds nesting for no reason.","links":[{"label":"ESLint rules (archive)","url":"https://archive.eslint.org/docs/rules"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/else-after-return","examples":{"flagged":[{"path":null,"text":"function f(u) {\n  if (!u) {\n    return null;\n  } else {\n    return u.name;\n  }\n}\n"},{"path":"src/app.py","text":"def f(u):\n    if not u:\n        return None\n    else:\n        return u.name\n"}],"clean":[{"path":null,"text":"function f(u) {\n  if (!u) return null;\n  return u.name;\n}\n"}]}},{"id":"env-read","title":"Environment read deep in code","severity":"low","category":"design","languages":["ts","py"],"scope":"prod","why":"Scattered `process.env` reads make behavior depend on hidden globals, fail late on a typo, and can't be checked at startup.","fix":"Read and validate config once at startup, then pass the values in.","bad":"const key = process.env.API_KEY;","good":"const key = config.apiKey;","lang":"ts","research":"hardcoded-config","message":"Reads the environment here (process.env). Config read in many places is hard to test and easy to misspell.","detects":"pattern","source":{"name":"Hard-coded localhost URLs, and environment reads deep in logic","why":"The value cannot change per environment, and tests must patch globals.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/env-read","examples":{"flagged":[{"path":null,"text":"const k = process.env.KEY;"},{"path":"src/app.py","text":"import os\nk = os.environ['KEY']\n"}],"clean":[{"path":"src/config.ts","text":"const k = process.env.KEY;"}]}},{"id":"global-statement","title":"global","severity":"low","category":"design","languages":["py"],"scope":"any","why":"Hidden global state makes functions order-dependent and tests interfere with each other.","fix":"Pass state in and return it, or keep it on an object.","bad":"def bump():\n    global count\n    count += 1","good":"def bump(count):\n    return count + 1","lang":"py","research":"global-state","message":"`global x` mutates module state from inside a function.","detects":"pattern","source":{"name":"`global` statements and module-level mutable state","why":"Hidden coupling makes behavior depend on call order.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/global-statement","examples":{"flagged":[{"path":null,"text":"def f():\n    global x\n    x = 1\n"}],"clean":[{"path":null,"text":"def f(x):\n    return x\n"}]}},{"id":"long-file","title":"Long file grew","severity":"low","category":"design","languages":["ts","py","c"],"scope":"any","why":"Very long files usually hold several modules. Every addition makes the split harder.","fix":"Move the part you're adding (and its neighbors) into its own module.","bad":"// orders.ts: 1,800 lines","good":"// orders/pricing.ts, orders/tax.ts, orders/receipts.ts","lang":"ts","research":"long-function","message":"This file is 701 lines, 701 more than before. Past 600, files usually hold several modules.","detects":"structure","source":{"name":"Long functions, and long files that keep growing","why":"Past a certain size a reader cannot hold the unit in mind.","links":[{"label":"Refactoring Guru: code smells","url":"https://refactoring.guru/refactoring/smells"},{"label":"Smells in AI-generated code (paper)","url":"https://huggingface.co/papers/2605.02741.md"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/long-file","examples":{"flagged":[{"path":null,"text":"const a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\n"}],"clean":[{"path":null,"text":"const a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\nconst a = 1;\n"}]}},{"id":"reinvented-builtin","title":"Long way round a builtin","severity":"low","category":"design","languages":["ts","py"],"scope":"any","why":"`.filter(...).length > 0` builds a whole array to answer yes/no; `range(len(x))` indexes by hand. The builtin is shorter and says what you mean.","fix":"`.some()`, `.includes()`, `enumerate()`, `any()`.","bad":"if (users.filter((u) => u.admin).length > 0) {}","good":"if (users.some((u) => u.admin)) {}","lang":"ts","research":"reinvented-builtin","message":"`.filter((x) => x.ok).length > 0` does by hand what a builtin says directly.","detects":"pattern","source":{"name":"Hand-written versions of builtins (`.filter(...).length > 0`, `range(len(x))`)","why":"The long form is slower to read and sometimes slower to run.","links":[{"label":"Deslopping AI code","url":"https://www.anaconda.com/blog/deslopping-ai-code"},{"label":"What makes AI-generated code slop","url":"https://dev.to/d3lm/what-makes-ai-generated-code-slop-40on"},{"label":"How AI code accelerates technical debt","url":"https://leaddev.com/software-quality/how-ai-generated-code-accelerates-technical-debt"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/reinvented-builtin","examples":{"flagged":[{"path":null,"text":"if (xs.filter((x) => x.ok).length > 0) {}"},{"path":null,"text":"if (s.indexOf(c) !== -1) {}"},{"path":"src/app.py","text":"for i in range(len(xs)):\n    pass\n"}],"clean":[{"path":null,"text":"if (xs.some((x) => x.ok)) {}"}]}},{"id":"nested-ternary","title":"Nested ternary","severity":"low","category":"design","languages":["ts","py"],"scope":"any","why":"Nested conditionals in one expression hide the branches and are easy to get wrong when edited.","fix":"Use `if`/`return`, a lookup table, or a small function.","bad":"const c = a ? 'x' : b ? 'y' : 'z';","good":"const c = LABELS[kind];","lang":"ts","research":"nested-ternary","message":"A ternary inside a ternary. Readers have to parse it twice.","detects":"pattern","source":{"name":"A ternary inside a ternary","why":"It hides which branch wins.","links":[],"notes":["skill: code-review","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/nested-ternary","examples":{"flagged":[{"path":null,"text":"const c = a ? 1 : b ? 2 : 3;"}],"clean":[{"path":null,"text":"const c = a ? 1 : 2;"},{"path":null,"text":"const c = a?.b ?? 2;"},{"path":null,"text":"function f(o?: { readonly timeoutMs?: number }) {}"},{"path":null,"text":"const t = `${a ? 'x' : ''} and ${b ? 'y' : ''}`;"}]}},{"id":"new-dependency","title":"New dependency","severity":"low","category":"design","languages":["*"],"scope":"any","why":"Every dependency is code you ship, audit and upgrade forever. Models add packages for things the standard library already does.","fix":"Use the standard library or a package you already have, or say in the PR why this one earns its place.","bad":"\"is-odd\": \"^3.0.1\"","good":"const isOdd = (n) => n % 2 === 1;","lang":"ts","research":"new-dependency","message":"Adds a dependency (\"is-odd\": \"^3). Check the platform or an existing package doesn't already do this.","detects":"pattern","source":{"name":"A new package added to a manifest","why":"Each package is new attack surface, and model-invented names invite squatting.","links":[{"label":"Code smell 300: package hallucination","url":"https://dev.to/mcsee/code-smell-300-package-hallucination-1kai"},{"label":"AI code suggestions and the supply chain","url":"https://www.theregister.com/2025/04/12/ai_code_suggestions_sabotage_supply_chain/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/new-dependency","examples":{"flagged":[{"path":"package.json","text":"{\n  \"dependencies\": {\n    \"is-odd\": \"^3.0.1\"\n  }\n}"},{"path":"pyproject.toml","text":"dependencies = [\n  \"httpx>=0.27\",\n]\n"}],"clean":[{"path":"package.json","text":"{\n  \"version\": \"1.0.0\"\n}"},{"path":"pyproject.toml","text":"addopts = [\n  \"--basetemp=\",\n  \"--override-ini=x\",\n]\n"}]}},{"id":"hasattr-probe","title":"Probes for a shape","severity":"low","category":"design","languages":["py"],"scope":"any","why":"Feature-probing your own objects means the types don't say what they hold. It usually covers two incompatible versions of a thing.","fix":"Give the value one type and remove the probe.","bad":"if hasattr(job, 'retry_count'):","good":"job.retry_count  # always set by Job()","lang":"py","research":"defensive-code","message":"Checks at runtime whether a value has some attribute (hasattr(x, '). The code should know.","detects":"pattern","source":{"name":"Fallbacks and guards that hide missing data (`?? []`, `.get(k, \"\")`, `hasattr` probes, catch that returns empty, long `?.` chains)","why":"A timeout looks like an empty result, and broken assumptions travel downstream.","links":[{"label":"Issue: agent adds unsafe fallbacks","url":"https://claudeissues.com/issue/31890-bug-error-handling-ignores-claude-md-directives-adds-unsafe-fallbacks-instead-of"},{"label":"Fallbacks are evil","url":"https://dev.to/tertiumnon/fallbacks-are-evil-5bh2"},{"label":"X post by karpathy","url":"https://x.com/karpathy/status/1976077806443569355"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/hasattr-probe","examples":{"flagged":[{"path":null,"text":"if hasattr(x, 'y'):\n    pass\n"}],"clean":[{"path":null,"text":"if x.y:\n    pass\n"}]}},{"id":"temporary-code","title":"Temporary code with no end","severity":"low","category":"design","languages":["ts","py","c"],"scope":"any","why":"Temporary code without an owner or an issue becomes permanent. Nobody remembers what it was waiting for.","fix":"Link the issue that removes it, or do the real fix now.","bad":"// workaround for now","good":"// Remove after the vendor fix ships: https://github.com/org/repo/issues/12","lang":"ts","research":"temporary-without-deletion-point","message":"Marked temporary (// workaround for now) with no link to when it goes away.","detects":"pattern","source":{"name":"\"Temporary\" or \"for now\" workarounds with no issue link or end condition","why":"Temporary code with no owner becomes permanent.","links":[],"notes":["skill: no-sus-code-doctor","owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/temporary-code","examples":{"flagged":[{"path":null,"text":"// workaround for now"}],"clean":[{"path":null,"text":"// workaround for https://github.com/x/y/issues/12"},{"path":null,"text":"// written to a temporary file, then renamed"}]}},{"id":"many-params","title":"Too many parameters","severity":"low","category":"design","languages":["ts","py"],"scope":"any","why":"Long positional parameter lists are easy to call in the wrong order and hard to extend.","fix":"Group related values into an object or dataclass, or pass keyword arguments.","bad":"function send(to, from, subject, body, cc, bcc, replyTo) {}","good":"function send(msg: Message) {}","lang":"ts","research":"many-params","message":"`f` takes 6 parameters. Callers have to remember their order.","detects":"structure","source":{"name":"Long parameter lists","why":"Calls are hard to read and hard to change.","links":[{"label":"Refactoring Guru: code smells","url":"https://refactoring.guru/refactoring/smells"},{"label":"Code smells taxonomy","url":"https://courses.cs.duke.edu/compsci308/spring23/resources/Code_Smells_Taxonomy.pdf"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/many-params","examples":{"flagged":[{"path":null,"text":"function f(a, b, c, d, e, g) {\n  return a;\n}\n"},{"path":"src/app.py","text":"def f(a, b, c, d, e, g):\n    return a\n"}],"clean":[{"path":null,"text":"function f({ a, b, c, d, e, g }) {\n  return a;\n}\n"},{"path":"src/app.py","text":"def f(a, *, b, c, d, e, g):\n    return a\n"}]}},{"id":"junk-drawer-module","title":"utils / helpers module","severity":"low","category":"design","languages":["ts","py"],"scope":"any","why":"`utils.ts` grows forever because anything can go there. Names by topic (`dates.ts`, `money.py`) keep code findable and cohesive.","fix":"Name the module by what it's about, or put each helper next to its only caller.","bad":"src/utils.ts","good":"src/dates.ts","lang":"ts","research":"junk-drawer-module","message":"A new grab-bag module. Code here has no home, so nobody can find it.","detects":"structure","source":{"name":"New `utils`, `helpers` or `common` modules","why":"Code with no home is hard to find, and the module turns into a dependency hub.","links":[{"label":"9 smells in AI-generated code","url":"https://dev.to/akaranjkar08/735-of-ai-generated-code-has-these-9-smells-taxonomy-and-detection-guide-2026-5dno"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/junk-drawer-module","examples":{"flagged":[{"path":"src/utils.ts","text":"export const a = 1;"}],"clean":[{"path":"src/dates.ts","text":"export const a = 1;"}]}},{"id":"async-foreach","title":"async callback in forEach","severity":"high","category":"async","languages":["ts"],"scope":"any","why":"`arr.forEach(async ...)` fires every callback and returns immediately. Rejections become unhandled and ordering is lost.","fix":"`for (const x of xs) await f(x)` for sequence, or `await Promise.all(xs.map(f))` for parallel.","bad":"items.forEach(async (i) => { await save(i); });","good":"for (const i of items) await save(i);","lang":"ts","research":"async-foreach","message":"`forEach` doesn't wait for async callbacks. The code after this runs before they finish, and their errors go nowhere.","detects":"pattern","source":{"name":"`async` callbacks in `forEach`, and `async` Promise executors","why":"The returned promises are dropped, so the caller moves on early and rejections escape.","links":[{"label":"Async/await inside forEach","url":"https://sentry.io/answers/are-there-any-issues-with-using-async-await-with-foreach-loops-in-javascript"},{"label":"Why async/await inside forEach is a bad idea","url":"https://dev.to/maximization/why-asyncawait-inside-foreach-is-a-bad-idea-5d6c"},{"label":"JavaScript promise mistakes","url":"https://techearl.com/javascript-promise-mistakes"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/async-foreach","examples":{"flagged":[{"path":null,"text":"xs.forEach(async (x) => { await f(x); });"}],"clean":[{"path":null,"text":"for (const x of xs) await f(x);"}]}},{"id":"async-promise-executor","title":"async Promise executor","severity":"high","category":"async","languages":["ts"],"scope":"any","why":"Errors thrown inside an async executor are lost; the outer promise hangs forever.","fix":"Drop the `new Promise` wrapper and write an async function.","bad":"return new Promise(async (resolve) => { resolve(await load()); });","good":"return load();","lang":"ts","research":"async-foreach","message":"An `async` function as a Promise executor. If it throws, the promise never settles.","detects":"pattern","source":{"name":"`async` callbacks in `forEach`, and `async` Promise executors","why":"The returned promises are dropped, so the caller moves on early and rejections escape.","links":[{"label":"Async/await inside forEach","url":"https://sentry.io/answers/are-there-any-issues-with-using-async-await-with-foreach-loops-in-javascript"},{"label":"Why async/await inside forEach is a bad idea","url":"https://dev.to/maximization/why-asyncawait-inside-foreach-is-a-bad-idea-5d6c"},{"label":"JavaScript promise mistakes","url":"https://techearl.com/javascript-promise-mistakes"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/async-promise-executor","examples":{"flagged":[{"path":null,"text":"return new Promise(async (resolve) => resolve(1));"}],"clean":[{"path":null,"text":"return new Promise((resolve) => resolve(1));"}]}},{"id":"blocking-in-async","title":"Blocking call in async code","severity":"medium","category":"async","languages":["py"],"scope":"any","why":"A blocking call inside `async def` freezes the event loop: every other request waits for this one.","fix":"Use the async client (`httpx.AsyncClient`, `asyncio.sleep`, `aiofiles`) or `await asyncio.to_thread(...)`.","bad":"async def fetch(u):\n    return requests.get(u, timeout=5)","good":"async def fetch(u):\n    async with httpx.AsyncClient() as c:\n        return await c.get(u, timeout=5)","lang":"py","research":"sync-io","message":"`time.sleep` blocks the event loop inside `async def f`. Every other task waits.","detects":"structure","source":{"name":"Blocking file, process or HTTP calls in server or async code","why":"One blocking call stalls every other request on the event loop.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/blocking-in-async","examples":{"flagged":[{"path":null,"text":"import time\nasync def f():\n    time.sleep(1)\n"}],"clean":[{"path":null,"text":"import asyncio\nasync def f():\n    await asyncio.sleep(1)\n"}]}},{"id":"sleep-in-prod","title":"Fixed wait in shipped code","severity":"medium","category":"async","languages":["ts","py"],"scope":"prod","why":"Sleeps guess at timing. They are too short under load and pure latency the rest of the time, and they hide races instead of fixing them.","fix":"Wait on the real signal (an event, a poll with a deadline, a queue) or use backoff with a cap.","bad":"await sleep(2000); // give the job time to finish","good":"await job.done({ timeoutMs: 30_000 });","lang":"ts","research":"sleep-in-test","message":"`await sleep` waits a fixed time instead of for the thing it needs.","detects":"pattern","source":{"name":"Fixed sleeps and `setTimeout` waits, in tests and in shipped code","why":"It is slow when the state is ready and flaky when it is not.","links":[{"label":"Test smell catalog","url":"https://test-smell-catalog.readthedocs.io/"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/sleep-in-prod","examples":{"flagged":[{"path":null,"text":"await sleep(100);"},{"path":"src/app.py","text":"import time\ntime.sleep(2)\n"}],"clean":[{"path":null,"text":"await job.done();"}]}},{"id":"timeout-zero","title":"setTimeout(…, 0) timing hack","severity":"low","category":"async","languages":["ts"],"scope":"prod","why":"Zero-delay timeouts paper over a race: they work until something else also defers.","fix":"Fix the ordering: await the thing that must happen first, or use the framework's lifecycle hook.","bad":"setTimeout(() => input.focus(), 0);","good":"useLayoutEffect(() => input.focus(), []);","lang":"ts","research":"sleep-in-test","message":"`setTimeout(…, 0)` defers work to dodge an ordering problem.","detects":"pattern","source":{"name":"Fixed sleeps and `setTimeout` waits, in tests and in shipped code","why":"It is slow when the state is ready and flaky when it is not.","links":[{"label":"Test smell catalog","url":"https://test-smell-catalog.readthedocs.io/"},{"label":"AI slop in developer posts (arXiv)","url":"https://arxiv.org/html/2603.27249v1"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/timeout-zero","examples":{"flagged":[{"path":null,"text":"setTimeout(() => go(), 0);"}],"clean":[{"path":null,"text":"setTimeout(() => go(), 500);"}]}},{"id":"effect-fetch","title":"Data fetching in useEffect","severity":"medium","category":"react","languages":["ts"],"scope":"any","why":"Fetching in an effect races when props change quickly, double-fetches in Strict Mode and has no cache.","fix":"Use the framework's data loading (server components, loaders) or a query library.","bad":"useEffect(() => {\n  fetch(`/api/u/${id}`).then(setUser);\n}, [id]);","good":"const { data: user } = useQuery(['user', id], () => getUser(id));","lang":"ts","research":"react-effects","message":"Fetches data inside `useEffect`. That races on fast re-renders and refetches on every mount.","detects":"structure","source":{"name":"Effects with no dependency array, data fetching in effects, and effects that copy derived values into state","why":"They cause extra renders, loops, races and double fetches.","links":[{"label":"X post by aidenybai","url":"https://x.com/aidenybai/status/2076292556154122410"}],"notes":["skill: react-doctor","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/effect-fetch","examples":{"flagged":[{"path":null,"text":"useEffect(() => {\n  fetch(url).then(setUser);\n}, [url]);\n"}],"clean":[{"path":null,"text":"useEffect(() => {\n  track(page);\n}, [page]);\n"}]}},{"id":"index-as-key","title":"Index as React key","severity":"medium","category":"react","languages":["ts"],"scope":"any","why":"When items move or are removed, index keys make React reuse the wrong component state; random keys remount every render.","fix":"Use a stable id from the data.","bad":"<Row key={index} item={item} />","good":"<Row key={item.id} item={item} />","lang":"ts","research":"index-as-key","message":"Uses the list position (or a random value) as the React key.","detects":"pattern","source":{"name":"Array index, time or random values as React keys","why":"Reordering remounts items or attaches state to the wrong one.","links":[{"label":"14 patterns AI code generators get wrong","url":"https://dev.to/radpdx/14-patterns-ai-code-generators-get-wrong-and-how-to-catch-them-45l9"}],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/index-as-key","examples":{"flagged":[{"path":null,"text":"<Row key={index} item={item} />"}],"clean":[{"path":null,"text":"<Row key={item.id} item={item} />"}]}},{"id":"effect-no-deps","title":"useEffect without dependencies","severity":"medium","category":"react","languages":["ts"],"scope":"any","why":"An effect with no dependency array runs after every render. It's a common source of loops and wasted work.","fix":"List the values it reads, or `[]` to run once.","bad":"useEffect(() => { track(page); });","good":"useEffect(() => { track(page); }, [page]);","lang":"ts","research":"react-effects","message":"`useEffect` with no dependency array runs after every render.","detects":"structure","source":{"name":"Effects with no dependency array, data fetching in effects, and effects that copy derived values into state","why":"They cause extra renders, loops, races and double fetches.","links":[{"label":"X post by aidenybai","url":"https://x.com/aidenybai/status/2076292556154122410"}],"notes":["skill: react-doctor","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/effect-no-deps","examples":{"flagged":[{"path":null,"text":"useEffect(() => {\n  track(page);\n});\n"}],"clean":[{"path":null,"text":"useEffect(() => {\n  track(page);\n}, [page]);\n"}]}},{"id":"derived-state-effect","title":"Effect that copies into state","severity":"low","category":"react","languages":["ts"],"scope":"any","why":"Setting state from an effect to mirror props or other state costs an extra render and drifts out of sync.","fix":"Compute the value during render (`const full = first + ' ' + last`), with `useMemo` if it's expensive.","bad":"useEffect(() => {\n  setFull(first + ' ' + last);\n}, [first, last]);","good":"const full = first + ' ' + last;","lang":"ts","research":"react-effects","message":"This effect only copies values into state. Compute them during render instead.","detects":"structure","source":{"name":"Effects with no dependency array, data fetching in effects, and effects that copy derived values into state","why":"They cause extra renders, loops, races and double fetches.","links":[{"label":"X post by aidenybai","url":"https://x.com/aidenybai/status/2076292556154122410"}],"notes":["skill: react-doctor","owner's notes"]},"url":"https://redline.kevinliu.studio/rules/derived-state-effect","examples":{"flagged":[{"path":null,"text":"useEffect(() => {\n  setFull(a + b);\n}, [a, b]);\n"}],"clean":[{"path":null,"text":"const full = a + b;\n"}]}},{"id":"unstable-context-value","title":"New object as context value","severity":"low","category":"react","languages":["ts"],"scope":"any","why":"Inline `value={{...}}` creates a fresh object each render; React sees a change and re-renders the whole subtree.","fix":"Memoize the value with `useMemo`, or split the context.","bad":"<Ctx.Provider value={{ theme, setTheme }}>","good":"const value = useMemo(() => ({ theme, setTheme }), [theme]);\n<Ctx.Provider value={value}>","lang":"ts","research":"unstable-context-value","message":"Passes a new object to a context provider on every render, so every consumer re-renders.","detects":"pattern","source":{"name":"A new object or array passed as a context value","why":"Every consumer re-renders on every render.","links":[],"notes":["owner's notes"]},"url":"https://redline.kevinliu.studio/rules/unstable-context-value","examples":{"flagged":[{"path":null,"text":"<ThemeContext.Provider value={{ theme, setTheme }}>"}],"clean":[{"path":null,"text":"<ThemeContext.Provider value={themeValue}>"}]}},{"id":"merge-conflict","title":"Merge conflict marker","severity":"high","category":"hygiene","languages":["*"],"scope":"any","why":"Conflict markers break the build in code and silently corrupt config, docs and data files.","fix":"Resolve the conflict and keep one side, or both on purpose.","bad":"<<<<<<< HEAD\nconst a = 1;\n=======\nconst a = 2;\n>>>>>>> branch","good":"const a = 2;","lang":"ts","research":"merge-conflict","message":"A merge conflict marker (<<<<<<<). The merge was never resolved.","detects":"pattern","source":{"name":"Merge conflict markers","why":"They break the build in code and silently corrupt config and data files.","links":[],"notes":["no outside source yet"]},"url":"https://redline.kevinliu.studio/rules/merge-conflict","examples":{"flagged":[{"path":null,"text":"<<<<<<< HEAD\nconst a = 1;"}],"clean":[{"path":null,"text":"const a = '=======';"}]}},{"id":"debug-print","title":"Debug output left in","severity":"medium","category":"hygiene","languages":["ts","py"],"scope":"prod","why":"Debug prints leak data into logs, cost I/O on hot paths and bury real log lines. `debugger` and `breakpoint()` stop the process.","fix":"Delete it, or use the project's logger at the right level.","bad":"console.log(\"user\", user);","good":"logger.debug({ userId: user.id }, \"loaded user\");","lang":"ts","research":"debug-print","message":"`console.log` left in shipped code.","detects":"pattern","source":{"name":"`console.log`, `print`, `debugger` and `breakpoint()` left in shipped code","why":"Debug output adds noise and can leak data.","links":[{"label":"vibecop detectors","url":"https://bhvbhushan.github.io/vibecop/detectors/overview/"},{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"},{"label":"5 code smells only AI creates","url":"https://dev.to/bzprchny/5-code-smells-only-ai-creates-and-how-to-detect-them-1e3l"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/debug-print","examples":{"flagged":[{"path":null,"text":"console.log(user);"},{"path":"src/app.py","text":"print(x)\n"},{"path":null,"text":"debugger;"}],"clean":[{"path":null,"text":"logger.info(user.id);"},{"path":"scripts/run.py","text":"print(x)\n"}]}},{"id":"user-path","title":"Machine-specific path","severity":"medium","category":"hygiene","languages":["*"],"scope":"any","why":"Absolute home paths work on the author's laptop and nowhere else, and they leak usernames into the repo.","fix":"Use a path relative to the repo, a config value, or `os.homedir()` / `Path.home()`.","bad":"const data = \"/Users/sam/project/data.json\";","good":"const data = path.join(root, \"data.json\");","lang":"ts","research":"user-path","message":"A path from one person's machine (/Users/sam/). It breaks for everyone else.","detects":"pattern","source":{"name":"Absolute home-directory paths (`/home/<user>/...`)","why":"They work on one machine only, and they leak usernames.","links":[],"notes":["no outside source yet"]},"url":"https://redline.kevinliu.studio/rules/user-path","examples":{"flagged":[{"path":null,"text":"const p = \"/Users/sam/code/a.json\";"},{"path":null,"text":"p = \"/home/dev/data\""}],"clean":[{"path":null,"text":"const p = path.join(root, \"a.json\");"}]}},{"id":"unpinned-dependency","title":"Unpinned dependency","severity":"medium","category":"hygiene","languages":["*"],"scope":"any","why":"`latest`, `*` and bare package names pull whatever is newest at install time, so a build can break with no change in the repo.","fix":"Pin a version range (`^1.4.2`) and commit the lockfile.","bad":"\"left-pad\": \"latest\"","good":"\"left-pad\": \"^1.3.0\"","lang":"ts","research":"unpinned-dependency","message":"An unpinned version (\"a\": \"latest\"). Installs will differ from machine to machine.","detects":"pattern","source":{"name":"Dependencies pinned to `*`, `latest` or an open range","why":"A compromised release gets pulled in automatically.","links":[{"label":"X post by tshemsedinov","url":"https://x.com/tshemsedinov/status/2056369746556092541"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/unpinned-dependency","examples":{"flagged":[{"path":"package.json","text":"{\n  \"dependencies\": {\n    \"a\": \"latest\"\n  }\n}"},{"path":"requirements.txt","text":"requests\n"}],"clean":[{"path":"package.json","text":"{\n  \"dependencies\": {\n    \"a\": \"^1.2.0\"\n  }\n}"},{"path":"requirements.txt","text":"requests==2.32.0\n"}]}},{"id":"wildcard-import","title":"Wildcard import","severity":"medium","category":"hygiene","languages":["py"],"scope":"any","why":"Star imports hide where names come from, shadow builtins and break when the other module adds a name.","fix":"Import the names you use.","bad":"from utils import *","good":"from utils import slugify, parse_date","lang":"py","research":"wildcard-import","message":"`from os.path import *` pulls every name in. Readers can't tell where a name came from.","detects":"pattern","source":{"name":"`from x import *`","why":"Readers cannot tell where a name comes from.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":[]},"url":"https://redline.kevinliu.studio/rules/wildcard-import","examples":{"flagged":[{"path":null,"text":"from os.path import *\n"}],"clean":[{"path":null,"text":"from os.path import join\n"}]}},{"id":"commented-out-code","title":"Commented-out code","severity":"low","category":"hygiene","languages":["ts","py","c"],"scope":"any","why":"Dead code in comments confuses readers about what runs and never gets updated with the code around it.","fix":"Delete it. Git has it if you need it back.","bad":"// const old = computeLegacy(x);\nconst v = compute(x);","good":"const v = compute(x);","lang":"ts","research":"commented-out-code","message":"Commented-out code. Version control keeps old code; this just rots.","detects":"pattern","source":{"name":"Commented-out code","why":"Git already keeps old code, and the comment rots.","links":[{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"},{"label":"Detecting AI slop in codebases","url":"https://dev.to/rohan_san_54b7ab7e50faa83/how-i-built-a-tool-that-detects-ai-slop-in-codebases-and-what-patterns-i-found-gmc"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/commented-out-code","examples":{"flagged":[{"path":null,"text":"// const x = load();"},{"path":null,"text":"// doThing(a, b);"},{"path":"src/app.py","text":"# return compute(x)\nx = 1\n"}],"clean":[{"path":null,"text":"// Load lazily so startup stays fast."},{"path":"src/app.py","text":"# return early when empty\nx = 1\n"}]}},{"id":"localhost-url","title":"Hard-coded localhost","severity":"low","category":"hygiene","languages":["ts","py","c"],"scope":"prod","why":"A localhost URL in production code works in development and fails everywhere else, usually silently.","fix":"Read the base URL from config once at startup.","bad":"const api = \"http://localhost:3000/api\";","good":"const api = config.apiUrl;","lang":"ts","research":"hardcoded-config","message":"A hard-coded local address (http://localhost:3000) in shipped code.","detects":"pattern","source":{"name":"Hard-coded localhost URLs, and environment reads deep in logic","why":"The value cannot change per environment, and tests must patch globals.","links":[{"label":"AI code audit taxonomy","url":"https://kenrinzero.github.io/ai-code-audit-taxonomy/"}],"notes":["owner's code bar"]},"url":"https://redline.kevinliu.studio/rules/localhost-url","examples":{"flagged":[{"path":null,"text":"const api = \"http://localhost:3000\";"}],"clean":[{"path":null,"text":"const api = config.apiUrl;"}]}},{"id":"magic-number","title":"Unnamed number","severity":"low","category":"hygiene","languages":["ts","py","c"],"scope":"prod","why":"`86400000` or `3500` means nothing at the call site. When it changes, someone has to find every copy.","fix":"Name it with its unit: `const DAY_MS = 86_400_000`.","bad":"setTimeout(retry, 3500);","good":"const RETRY_DELAY_MS = 3_500;\nsetTimeout(retry, RETRY_DELAY_MS);","lang":"ts","research":"magic-number","message":"`3500` is a bare number. Name it, with its unit, so the next reader knows what it means.","detects":"structure","source":{"name":"Unnamed numbers in logic","why":"Readers cannot tell what the number means or which unit it uses.","links":[{"label":"ESLint: no-magic-numbers","url":"https://eslint.org/docs/rules/no-magic-numbers"},{"label":"Ruff rules","url":"https://docs.astral.sh/ruff/rules/"}],"notes":["skill: code-review"]},"url":"https://redline.kevinliu.studio/rules/magic-number","examples":{"flagged":[{"path":null,"text":"setTimeout(retry, 3500);"}],"clean":[{"path":null,"text":"const RETRY_MS = 3500;\nsetTimeout(retry, RETRY_MS);"},{"path":null,"text":"res.status(404);"},{"path":null,"text":"const o = {\n  compactionThreshold: 200_000,\n};"}]}}]}