Cognitive Load

Cognitive Load is a dev-only package that statically analyses your codebase for cognitive complexity and architectural markers. It parses your app's PHP with its own AST-based engine (built on nikic/php-parser), scores every class from 0 to 100, and can snapshot a baseline so a pull request that makes the code measurably messier fails your build.

It requires PHP 8.2+ and supports Laravel 12 and 13.

Installation

composer require --dev "grafite/cognitive-load"

Then publish the config:

php artisan vendor:publish --provider="Grafite\CognitiveLoad\CognitiveLoadServiceProvider"

How Scoring Works

Every class is scored on two markers, each from 0 to 100:

  • Complexity is derived from per-method metrics.
  • Architecture is derived from class-level structure.

Each metric adds nothing while it is at or below its threshold, then its penalty grows logarithmically past it. A category's accumulated penalty decays into a score with 100 * exp(-raw / k), where k comes from category_scaling. The two categories combine into a weighted overall score (60% complexity, 40% architecture by default), where 100 is the cleanest.

Complexity Metrics

Metric Default Threshold
line_count20
argument_count4
return_count3
variable_count8
property_access_count5
if_count3
if_nesting_depth2
else_count2
cyclomatic_complexity5

Architecture Metrics

Metric Default Threshold
class_loc200
method_count10
coupling_count (constructor dependencies + imports)6
inheritance_depth2

Bands

Scores map onto a grade and a risk band using one shared set of thresholds:

Score Grade Risk
80 and aboveGoodLow
60 to 79FairMedium
40 to 59PoorHigh
Below 40CriticalVeryHigh

Configuration

The published config/cognitive-load.php file controls what gets scanned and how strictly it is judged. The key sections are:

[
    // Directories/files scanned when no path is given on the CLI
    'paths' => [app_path()],

    // Regex: matched against the path, filename, and fully-qualified class name
    'exclude' => ['#/vendor/#', '#/tests/#', '#/database/migrations/#'],
    'exclude_files' => [],
    'exclude_classes' => [],

    'category_weights' => [
        'complexity' => 0.6,
        'architecture' => 0.4,
    ],

    'bands' => [
        'thresholds' => [40, 60, 80],
        'risk_labels' => ['VeryHigh', 'High', 'Medium', 'Low'],
        'grade_labels' => ['Critical', 'Poor', 'Fair', 'Good'],
    ],

    'baseline' => [
        'path' => base_path('cognitive-load-baseline.json'),
    ],

    'gate' => [
        'overall_margin' => 5.0,
        'class_margin' => 8.0,
        'fail_if_baseline_missing' => false,
    ],
]

The file also contains metrics and architecture_metrics, where each metric has a threshold and scale (and per-method metrics can be turned off with enabled), plus category_scaling, which sets how quickly each category decays from 100.

Commands

cognitive-load:analyse

Analyses the codebase and prints a report. With no path it scans config('cognitive-load.paths'), normally app/. You can pass a directory or a single file.

php artisan cognitive-load:analyse
php artisan cognitive-load:analyse app/Services --format=json --detailed

Options

Option Description
--format= Output format for the terminal report: console (default) or json.
--detailed Include a per-method breakdown table for each class.
--output= Also write the full JSON report to this file path.
--compare-baseline Load the configured baseline and report a delta against it.
--fail-on-regression Exit non-zero when the comparison fails the configured gate margins. Implies --compare-baseline.
--baseline-path= Override cognitive-load.baseline.path for this run.

cognitive-load:baseline

Snapshots the current scores as the baseline for future comparisons.

php artisan cognitive-load:baseline

Options

Option Description
--force Overwrite an existing baseline file without confirmation.
--baseline-path= Override cognitive-load.baseline.path for this run.

Baselines and CI Gating

Once a baseline exists, --fail-on-regression fails the build when any of the following happens:

  • The overall score drops by more than gate.overall_margin (default 5).
  • A class's score drops by more than gate.class_margin (default 8).
  • A class moves into a worse risk band, even if its score drop is within the margin.

Classes that aren't in the baseline yet are not gated. If no baseline file exists, the comparison is skipped, unless gate.fail_if_baseline_missing is true, in which case the run fails.

- name: Cognitive Load gate
  run: php artisan cognitive-load:analyse --compare-baseline --fail-on-regression

Commit cognitive-load-baseline.json (or your configured baseline.path) to the repo. When a regression is intentional, update it deliberately with php artisan cognitive-load:baseline --force.

Sloppiness Findings

Scores tell you code is hard to follow. cognitive-load:sloppy tells you it is sloppy: swallowed exceptions, half-finished stubs, dead dependencies, Eloquent misuse and copy-paste. It is the kind of debt AI coding agents often leave behind, and it applies equally to hand-written code. It runs as a separate, rule-based pass over the same paths and exclude* settings, and never changes the Complexity or Architecture scores.

php artisan cognitive-load:sloppy
php artisan cognitive-load:sloppy app/Services --min-severity=medium --format=json

Each finding includes a rule ID, severity, confidence, file:line, the symbol (Class::method), what is wrong, and what to do about it.

Rules

Rule Name Default Severity
SL101Swallowed exception (empty catch)high (low when the catch only holds a comment)
SL102Not implemented (throw new …('Not implemented'))high
SL103Placeholder comment (TODO/FIXME/XXX/HACK)low (medium when it is the whole body)
SL104Empty methodmedium
SL105Debug leftover (dd, dump, var_dump, ray, ->dd(), …)high
SL201Unused constructor dependencymedium
SL202Unused private methodmedium
SL203Unused private propertymedium
SL204Unused importlow
SL205Redundant boolean return (return $x ? true : false)low
SL206Constant condition (if (true), while (false))medium
SL207Commented-out codelow
SL301Query in loopmedium
SL302Filter after fetch (Model::all()->where(), ->get()->count())high
SL303Possible N+1 (relation read while looping over a query result)low
SL304env() outside config/high
SL305Fat controller (too many actions, or DB:: in a controller)medium
SL306Unvalidated mass assignment (create($request->all()))high
SL401Duplicate method body (same body after renaming variables)medium

Gating on New Findings

Gate CI on new sloppiness only. First, snapshot what exists today:

php artisan cognitive-load:sloppy-baseline
php artisan cognitive-load:sloppy --fail-on-new

Findings are fingerprinted by rule, file, symbol and the offending code, not by line number, so adding an import or moving a method doesn't make old findings look new. --fail-on-new fails only on new findings at or above sloppy.gate.fail_on (default medium). Without a baseline, every finding counts as new, unless sloppy.gate.fail_if_baseline_missing is set, in which case the run fails outright.

- name: Sloppiness gate
  run: php artisan cognitive-load:sloppy --fail-on-new

cognitive-load:sloppy Options

Option Description
--format= Output format for the terminal report: console (default) or json.
--min-severity= Only report findings at or above this severity: low, medium or high.
--output= Also write the full JSON report to this file path.
--compare-baseline Load the sloppiness baseline and report new and resolved findings.
--fail-on-new Exit non-zero when new findings reach sloppy.gate.fail_on. Implies --compare-baseline.
--baseline-path= Override cognitive-load.sloppy.baseline.path for this run.

cognitive-load:sloppy-baseline Options

Option Description
--force Overwrite an existing sloppiness baseline without confirmation.
--baseline-path= Override cognitive-load.sloppy.baseline.path for this run.

Configuring Rules

The sloppy block in config/cognitive-load.php lets you disable any rule or override its severity. A few rules take extra options:

'sloppy' => [
    'min_severity' => 'low',

    'baseline' => [
        'path' => base_path('sloppy-baseline.json'),
    ],

    'gate' => [
        'fail_on' => 'medium',
        'fail_if_baseline_missing' => false,
    ],

    'rules' => [
        'SL103' => ['severity' => 'medium'],
        'SL105' => ['enabled' => true, 'functions' => ['dd', 'ddd', 'dump', 'var_dump', 'print_r', 'var_export', 'ray']],
        'SL303' => ['enabled' => false],
        'SL305' => ['enabled' => true, 'max_actions' => 7],
        'SL401' => ['enabled' => true, 'min_statements' => 5],
        // ...
    ],

    'custom_rules' => [],
],

Custom Rules

To add your own rules, list classes implementing Grafite\CognitiveLoad\Sloppy\Rules\FileRule under custom_rules. A file rule receives one parsed file at a time. Extending AbstractRule gives you the finding() helper, which handles fingerprinting and severity overrides from config.

use Grafite\CognitiveLoad\Sloppy\FileContext;
use Grafite\CognitiveLoad\Sloppy\Rules\AbstractRule;
use Grafite\CognitiveLoad\Sloppy\Rules\FileRule;
use Grafite\CognitiveLoad\Sloppy\Severity;
use PhpParser\Node\Expr\Exit_;

class NoExitCalls extends AbstractRule implements FileRule
{
    public function id(): string
    {
        return 'APP001';
    }

    public function name(): string
    {
        return 'exit() or die() call';
    }

    public function defaultSeverity(): Severity
    {
        return Severity::High;
    }

    public function check(FileContext $context): array
    {
        $findings = [];

        foreach ($context->findInstanceOf(Exit_::class) as $node) {
            $findings[] = $this->finding(
                $context,
                $node,
                'exit() or die() is called in application code.',
                'Throw an exception or return a response instead.',
            );
        }

        return $findings;
    }
}

Register it as a class name, or as a map of class name to rule config:

'custom_rules' => [
    App\CognitiveLoad\NoExitCalls::class => ['severity' => 'medium'],
],

For checks that need every scanned file at once, such as cross-file duplication, implement ProjectRule instead. It provides checkProject(array $contexts), which receives all the FileContext objects.