Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ All notable changes will be documented in this file.
## [Unreleased]

### Added
- **The slop index is back, on three axes.** Every rule belongs to one: Noise (information utility), Lies (information quality) or Soul (style and taste). The summary ends with a score per axis and a total, and the JSON report adds `slopIndex` plus an `axis` on every issue and `byType` entry. Unlike the 1.x point total, the scores are per 1,000 lines of application code, so repositories of different sizes compare, and each rule counts logarithmically (`weight × ln(1 + findings per 1,000 lines)`), so one pattern repeated hundreds of times cannot outweigh several different kinds of slop. Package-age warnings from `package.json` are reported but not scored. `customPatterns` take an optional `axis` (default `soul`). `--help` lists each rule's axis.
- `--report=<path>` writes the JSON report somewhere other than `./ai-slop-report.json`, and `--no-report` skips it, so a scan no longer has to leave a file in the working tree.
- `swallowed_error` (medium): a `catch` block whose only statements are `console` calls. The error is logged and the code carries on as if the operation succeeded. A comment in the block explaining why that is safe, a rethrow, or any other statement (such as `setError(e)`) means it is not reported, and so does a fallback after the `try`, as for `empty_catch`.

Expand Down
53 changes: 35 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
[![npm downloads](https://img.shields.io/npm/dt/karpeslop.svg)](https://www.npmjs.com/package/karpeslop)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

A linter for the mistakes AI coding tools tend to leave in TypeScript and JavaScript.
A slop index for TypeScript and JavaScript. KarpeSlop finds the mistakes AI coding tools tend to leave and scores them on three axes: **noise**, **lies** and **soul**.

```bash
npx karpeslop@latest
Expand All @@ -14,17 +14,34 @@ npx karpeslop@latest

## Why

AI tools write code fast, and some of it looks finished when it isn't. Common examples:
AI tools write code fast, and some of it looks finished when it isn't. The idea for KarpeSlop comes from Andrej Karpathy's call for a "slop index": a number that says how much of a codebase is slop, and what kind. KarpeSlop sorts slop into three kinds:

- importing a function the library never had
- importing a package that isn't on npm
- a function body that is just a TODO and `return true`
- `// ... rest of the code` where real code should be
- `catch {}` that hides an error
- reading `res.json()` without checking `res.ok`
- `as any` and other casts that switch off type checking
- **Noise** (information utility): text that adds length without information. Comments that repeat the next line, doc comments that restate parameter names, leftover `console.log`.
- **Lies** (information quality): code that claims to do something it doesn't. A function the library never exported, a package that isn't on npm, a body that is just `return true`, `// ... rest of the code` where real code should be, a `catch {}` that hides the error, `as any` telling the compiler something nobody checked.
- **Soul** (style and taste): shortcuts that show no judgment behind the code. `any`, casts and `!` used to get past the type checker, blanket `eslint-disable`, TODOs nobody is tracking.

ESLint and `tsc` catch some of this. KarpeSlop looks for the rest, so you can find it before it ships.
ESLint and `tsc` catch some of this. KarpeSlop looks for the rest and tells you which kind it is, so you can find it before it ships.

## The slop index

Every run ends with a score for each axis. This is a 210,000-line Next.js app:

```
Slop index (application code, higher is worse):
Noise information utility 0.6 restating_comment, production_console_log, filler_comment
Lies information quality 7.8 unsafe_object_assertion, unsafe_double_type_assertion, unsafe_array_assertion
Soul style and taste 3.5 type_assertion, non_null_assertion, any_type_usage
Total 11.9
```

KarpeSlop's own source has no findings and scores 0.

Each rule adds `weight × ln(1 + findings per 1,000 lines)` to its axis, with weights of 8, 4, 2 and 1 for critical, high, medium and low. The scores use findings in application source files only, not tests or `package.json` (so `fresh_package_version` is reported but not scored), and:

- are per 1,000 lines, so a large repository and a small one can be compared
- grow with the logarithm of each rule's count, so one pattern repeated 500 times can't outweigh five different kinds of slop

The rules that add the most to each axis are listed next to its score. The JSON report has the full breakdown under `slopIndex`.

## Usage

Expand Down Expand Up @@ -73,14 +90,13 @@ Add a step to your workflow:

## What it checks

| Severity | Rules |
| Axis | Rules |
| --- | --- |
| critical | Imports of names a module doesn't export, files that don't exist, and packages that aren't on npm |
| high | Packages missing from `package.json`, placeholder bodies, elided-code comments, placeholder values like `"YOUR_API_KEY"`, empty `catch` blocks, `as any` and other unsafe casts |
| medium | Errors that are logged and dropped, other casts, `any`, `@ts-ignore`, blanket `eslint-disable`, unchecked `fetch` responses, dependency versions published in the last few days |
| low | `!` assertions, hedging and filler comments, TODOs without an issue link, `console.log` in app code |
| Lies | Imports of names a module doesn't export, files that don't exist, and packages that aren't on npm (critical). Packages missing from `package.json`, placeholder bodies, elided-code comments, placeholder values like `"YOUR_API_KEY"`, empty `catch` blocks, `as any` and other unsafe casts (high). Errors that are logged and dropped, `@ts-ignore`, unchecked `fetch` responses (medium) |
| Soul | Other casts, `any`, blanket `eslint-disable`, dependency versions published in the last few days (medium). `!` assertions, TODOs without an issue link (low) |
| Noise | Hedging, filler and restating comments, `console.log` in app code (low) |

`npx karpeslop@latest --help` lists every rule by name. Test, fixture and example folders are skipped by rules meant for app code.
`npx karpeslop@latest --help` lists every rule with its severity and axis. Test, fixture and example folders are skipped by rules meant for app code.

## Configuration

Expand All @@ -100,7 +116,8 @@ Add a `.karpesloprc.json` to your project root:
"id": "banned_import",
"pattern": "from\\s+['\"]lodash['\"]",
"message": "Use lodash-es",
"severity": "medium"
"severity": "medium",
"axis": "soul"
}
]
}
Expand All @@ -110,7 +127,7 @@ Add a `.karpesloprc.json` to your project root:
- `ignorePaths` skips files that match these globs.
- `minPackageAgeDays` sets how new a dependency version has to be before it gets flagged.
- `blockOnCritical` acts like `--strict` on every run.
- `customPatterns` adds your own regex rules, matched one line at a time.
- `customPatterns` adds your own regex rules, matched one line at a time. `axis` is `noise`, `lies` or `soul` (the default, since a custom pattern usually records your team's taste).

There are no inline comments to silence a finding. Changes go in this file so they show up in code review.

Expand Down
112 changes: 106 additions & 6 deletions ai-slop-detector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ import path from 'path';
import { glob } from 'glob';
import { fileURLToPath } from 'url';
import {
AXES,
RULES,
analyzeSource,
findUnsafeAssertions,
getRule,
isExamplePath,
isFixturePath,
isNonProductionPath,
type Axis,
type Severity,
type UnsafeAssertionFinding
} from './rules.ts';
Expand All @@ -33,9 +35,12 @@ const SEVERITIES: readonly Severity[] = ['critical', 'high', 'medium', 'low'];
const OVERRIDE_SEVERITIES: ReadonlyArray<Severity | 'off'> = [...SEVERITIES, 'off'];
/** Every rule id KarpeSlop reports itself. fresh_package_version comes from the registry check, not RULES. */
const BUILT_IN_RULE_IDS: ReadonlySet<string> = new Set([...RULES.map(rule => rule.id), 'fresh_package_version']);
/** Installing a version days after it was published is a judgment call, not a defect in the code. */
const FRESH_PACKAGE_AXIS: Axis = 'soul';

interface AISlopIssue {
type: string;
axis: Axis;
file: string;
line: number;
column: number;
Expand All @@ -47,6 +52,7 @@ interface AISlopIssue {

interface ConsolidatedIssue {
type: string;
axis: Axis;
file: string;
code: string;
message: string;
Expand All @@ -59,6 +65,7 @@ interface DetectionPattern {
pattern: RegExp;
message: string;
severity: Severity;
axis: Axis;
fix?: string;
learnMore?: string;
}
Expand All @@ -68,6 +75,8 @@ interface CustomPatternConfig {
pattern: string;
message: string;
severity: Severity;
/** Which axis of the slop index the pattern scores on. Defaults to soul: a custom pattern usually encodes a team's taste. */
axis?: Axis;
description?: string;
fix?: string;
learnMore?: string;
Expand All @@ -88,6 +97,10 @@ interface ScanSummary {
applicationLinesScanned: number;
}

function isAxis(value: unknown): value is Axis {
return AXES.some(axis => axis.id === value);
}

function isSeverity(value: unknown): value is Severity {
return SEVERITIES.some(severity => severity === value);
}
Expand Down Expand Up @@ -188,6 +201,54 @@ export function exitCodeFor(issues: ReadonlyArray<Pick<AISlopIssue, 'type' | 'se
return issues.some(issue => issue.type !== 'fresh_package_version' && SEVERITIES.indexOf(issue.severity) <= threshold) ? 1 : 0;
}

const SEVERITY_WEIGHTS: Record<Severity, number> = { critical: 8, high: 4, medium: 2, low: 1 };

export interface SlopIndexRule {
type: string;
findings: number;
points: number;
}

export interface SlopIndex {
/** Lines of application code the scores are relative to. */
applicationLines: number;
axes: Array<{ axis: Axis; score: number; rules: SlopIndexRule[] }>;
total: number;
}

/**
* Scores application-code findings on the three axes. Each rule adds
* `weight(severity) * ln(1 + findings per 1,000 lines)` to its axis: per 1,000
* lines so repositories of different sizes compare, and logarithmic so one
* rule repeated hundreds of times cannot outweigh several different kinds of
* slop. A rule's weight is that of its most severe finding.
*/
export function slopIndex(
findings: ReadonlyArray<Pick<AISlopIssue, 'type' | 'axis' | 'severity'>>,
applicationLines: number
): SlopIndex {
const byRule = new Map<string, { axis: Axis; findings: number; weight: number }>();
for (const finding of findings) {
const entry = byRule.get(finding.type) ?? { axis: finding.axis, findings: 0, weight: 0 };
entry.findings++;
entry.weight = Math.max(entry.weight, SEVERITY_WEIGHTS[finding.severity]);
byRule.set(finding.type, entry);
}
const round = (n: number) => Math.round(n * 100) / 100;
const axes = AXES.map(({ id }) => {
const rules = [...byRule.entries()]
.filter(([, entry]) => entry.axis === id)
.map(([type, entry]) => ({
type,
findings: entry.findings,
points: applicationLines > 0 ? round(entry.weight * Math.log1p((entry.findings * 1000) / applicationLines)) : 0
}))
.sort((a, b) => b.points - a.points || a.type.localeCompare(b.type));
return { axis: id, score: round(rules.reduce((sum, rule) => sum + rule.points, 0)), rules };
});
return { applicationLines, axes, total: round(axes.reduce((sum, axis) => sum + axis.score, 0)) };
}

/** A path.relative() result outside the root: `../x`, or on Windows a path on another drive (`D:\\x`). */
export function leavesRoot(relativePath: string): boolean {
return relativePath === '..' || /^\.\.[\\/]/.test(relativePath) || path.isAbsolute(relativePath);
Expand Down Expand Up @@ -366,6 +427,9 @@ class AISlopDetector {
if (!isSeverity(severity)) {
throw new Error(`customPatterns[${i}].severity must be one of: ${SEVERITIES.join(', ')}`);
}
if (pattern.axis !== undefined && !isAxis(pattern.axis)) {
throw new Error(`customPatterns[${i}].axis must be one of: ${AXES.map(axis => axis.id).join(', ')}`);
}
try {
new RegExp(source, 'gi');
} catch {
Expand All @@ -376,6 +440,7 @@ class AISlopDetector {
pattern: source,
message,
severity,
axis: isAxis(pattern.axis) ? pattern.axis : undefined,
description: optionalString(pattern.description),
fix: optionalString(pattern.fix),
learnMore: optionalString(pattern.learnMore)
Expand Down Expand Up @@ -450,6 +515,7 @@ class AISlopDetector {
? `${customPattern.message} (${customPattern.description})`
: customPattern.message,
severity: customPattern.severity,
axis: customPattern.axis ?? 'soul',
fix: customPattern.fix,
learnMore: customPattern.learnMore
});
Expand Down Expand Up @@ -639,10 +705,14 @@ class AISlopDetector {
return uniqueRealFiles(resolved);
}

private record(issue: Omit<AISlopIssue, 'severity'>, defaultSeverity: Severity): void {
private record(issue: Omit<AISlopIssue, 'severity' | 'axis'>, defaultSeverity: Severity): void {
const severity = this.severityOf(issue.type, defaultSeverity);
if (severity === 'off') return;
this.issues.push({ ...issue, severity });
this.issues.push({ ...issue, severity, axis: this.axisOf(issue.type) });
}

private axisOf(ruleId: string): Axis {
return getRule(ruleId)?.axis ?? this.customPatterns.find(pattern => pattern.id === ruleId)?.axis ?? FRESH_PACKAGE_AXIS;
}

/**
Expand Down Expand Up @@ -964,17 +1034,39 @@ class AISlopDetector {
const counts = SEVERITIES.map(severity => `${this.issues.filter(issue => issue.severity === severity).length} ${severity}`);
const files = new Set(this.issues.map(issue => issue.file)).size;
const { applicationLinesScanned } = this.summary;
const applicationFindings = this.issues.filter(issue => this.lineCounts.has(issue.file) && !this.isNonProductionFile(issue.file)).length;
const applicationFindings = this.applicationIssues().length;
const density = applicationLinesScanned > 0
? `, ${((applicationFindings / applicationLinesScanned) * 1000).toFixed(1)} per 1,000 lines of application code`
: '';
console.log(`${this.issues.length} finding${this.issues.length === 1 ? '' : 's'} (${counts.join(', ')}) in ${files} file${files === 1 ? '' : 's'}${density}.`);
if (hasOnlyFreshPackageWarnings(this.issues)) {
console.log('Only package-age warnings were found.');
}
if (applicationLinesScanned > 0) this.printSlopIndex();
console.log('To turn a rule off or change its severity, use severityOverrides in .karpesloprc.json.');
}

/** Findings in application code: the ones finding density and the slop index count. */
private applicationIssues(): AISlopIssue[] {
return this.issues.filter(issue => this.lineCounts.has(issue.file) && !this.isNonProductionFile(issue.file));
}

getSlopIndex(): SlopIndex {
return slopIndex(this.applicationIssues(), this.summary.applicationLinesScanned);
}

private printSlopIndex(): void {
const index = this.getSlopIndex();
console.log('\nSlop index (application code, higher is worse):');
const names = new Map(AXES.map(entry => [entry.id, entry]));
for (const { axis, score, rules } of index.axes) {
const { name, label } = names.get(axis) ?? { name: axis, label: '' };
const top = rules.slice(0, 3).map(rule => rule.type).join(', ');
console.log(` ${name.padEnd(6)} ${label.padEnd(20)} ${score.toFixed(1).padStart(6)}${top ? ` ${top}` : ''}`);
}
console.log(` ${'Total'.padEnd(27)} ${index.total.toFixed(1).padStart(6)}\n`);
}

/**
* Get the current configuration
*/
Expand Down Expand Up @@ -1012,6 +1104,7 @@ class AISlopDetector {
} else {
issueMap.set(key, {
type: issue.type,
axis: issue.axis,
file: issue.file,
code: issue.code,
message: issue.message,
Expand Down Expand Up @@ -1053,8 +1146,10 @@ class AISlopDetector {
uniqueIssues: consolidatedIssues.length,
totalOccurrences: countOccurrences(consolidatedIssues),
bySeverity,
slopIndex: this.getSlopIndex(),
byType: Array.from(byTypeMap.entries()).map(([type, issues]) => ({
type,
axis: issues[0].axis,
occurrences: countOccurrences(issues),
uniqueIssues: issues.length,
sample: issues.slice(0, 3).map(issue => ({
Expand Down Expand Up @@ -1082,7 +1177,8 @@ export function splitCliArgs(args: readonly string[]): { flagArgs: string[]; tar
}

function printHelp(): void {
const ruleLines = RULES.map(rule => ` ${rule.id.padEnd(30)} ${rule.severity.padEnd(9)} ${rule.message}`);
const ruleLines = RULES.map(rule => ` ${rule.id.padEnd(30)} ${rule.severity.padEnd(9)} ${rule.axis.padEnd(6)} ${rule.message}`);
const axisLines = AXES.map(axis => ` ${axis.id.padEnd(6)} ${axis.name} (${axis.label})`);
console.log(`
Usage: karpeslop [options] [path...]

Expand All @@ -1105,9 +1201,13 @@ Exit codes:
1 - Findings at the --fail-on severity (default high) or above
2 - Critical findings (--strict only)

Rules:
Slop index:
Findings in application code are scored on three axes, per 1,000 lines:
${axisLines.join('\n')}

Rules (id, severity, axis):
${ruleLines.join('\n')}
${'fresh_package_version'.padEnd(30)} ${'medium'.padEnd(9)} Dependency version was published very recently.
${'fresh_package_version'.padEnd(30)} ${'medium'.padEnd(9)} ${FRESH_PACKAGE_AXIS.padEnd(6)} Dependency version was published very recently.

Inline suppression comments are not supported. Change a rule's severity, or
turn it off, with severityOverrides in .karpesloprc.json.
Expand Down
2 changes: 1 addition & 1 deletion codemeta.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"@context": "https://raw.githubusercontent.com/codemeta/codemeta/2.0/codemeta.jsonld",
"@type": "SoftwareSourceCode",
"name": "KarpeSlop",
"description": "A linter for the mistakes AI coding tools leave in TypeScript and JavaScript: imports that don't exist, missing packages, placeholder code, swallowed errors and unsafe casts.",
"description": "A slop index for TypeScript and JavaScript: finds the mistakes AI coding tools leave (imports that don't exist, placeholder code, swallowed errors, unsafe casts) and scores them on three axes: noise, lies and soul.",
"version": "2.0.0",
"license": "https://spdx.org/licenses/MIT.html",
"codeRepository": "https://github.com/CodeDeficient/karpeslop",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "karpeslop",
"version": "2.0.0",
"description": "A linter for the mistakes AI coding tools leave in TypeScript and JavaScript: imports that don't exist, missing packages, placeholder code, swallowed errors and unsafe casts.",
"description": "A slop index for TypeScript and JavaScript: finds the mistakes AI coding tools leave (imports that don't exist, placeholder code, swallowed errors, unsafe casts) and scores them on three axes: noise, lies and soul.",
"type": "module",
"packageManager": "npm@10.9.7",
"bin": {
Expand Down
Loading
Loading