Green Is Not Done

󰃭 2026-11-26

Have you ever seen a pull request that was green, and still wrong?

This is the written version of my talk Green Is Not Done at SymfonyCon Warsaw 2026 (slides). It is about harness engineering for existing Symfony applications: what happens when a coding agent runs your CI, every check passes, and the code is still wrong. And what you can do about it with the tools you already have.

The ticket

In one of the Symfony applications I’m working on, coding agents write a lot of the code. I write the tickets, and I review the pull requests.

The application fetches video details from an external API, and that API has a rate limit. When we run into it, the request fails, and whoever clicked the button is left with a broken page. So I wrote a ticket for a coding agent:

Fetching video details hits the rate limit. Handle it, so the page keeps working.

A clear ticket, a real problem, and a good fit for an agent.

The agent solved the task. And along the way, it wrote this code in a controller:

// src/UI/Http/FetchVideoDetailsController.php
try {
    $this->fetchVideoDetails($videoId);
    $this->addFlash('success', 'Video details fetched successfully');
} catch (Exception $exception) {
    $this->addFlash('danger', 'Could not fetch video details: '
        . $exception->getMessage());
}

The controller fetches the video details. If that works, the user gets a green success flash. If anything goes wrong, any exception at all, the controller catches it and shows a red flash with the exception message.

So where does this exception go? Into a red box in the browser. Not into the log, because nothing is logged here. And not to Symfony’s error handling, because nobody throws it again.

I wanted one failure handled: the rate limit. What I got handles every failure in the same way.

Imagine someone introduces a bug here next week. A null where an object should be. This is what the user sees:

Could not fetch video details: Call to a member function getTitle() on null

An internal error message in a red box. And nobody in the team finds out. No log entry, no alert in the monitoring.

The bug looks exactly like a rate limit.

The page keeps working. That is exactly what I asked for. And that is exactly the problem.

All green

The agent did not just write this code and stop. It had one clear instruction: run make ci before you say you are done, and fix every finding. Not ignore it, not add it to the baseline. Fix it.

make ci is one command that runs the whole quality gate: code style, Rector, PHPStan, deptrac, PHPUnit and Infection.

$ make ci
cs-check   ✓
rector     ✓
phpstan    ✓
deptrac    ✓
phpunit    ✓
infection  ✓

The agent ran it, and every check passed. Then it opened the pull request, and the pipeline ran the same checks. The pipeline was green too.

The agent did exactly what I had asked. It followed the process. And still, this code was wrong.

When I open a pull request, green CI means: ready for review. I still know a lot of things that no tool checks. I know our conventions. I know what we decided last month. I know what we do with exceptions. (I even gave a whole talk about exception handling in Symfony at SymfonyCon Brussels 2023.)

But for a coding agent, green means done. Green is the signal to stop.

When a coding agent writes code, your CI becomes its definition of done.

And that means: anything your checks cannot see can pass as finished.

So this story leaves two questions. Why did the agent write this code? And why could none of my checks see it?

It reads your code. Not your head.

A coding agent optimizes for completion. It looks for the smallest local change that satisfies the request. That is what it is trained for, and it only knows the part of the code that it has read.

From that point of view, the catch was a very good solution. My ticket said: keep the page working. Catching everything is the shortest way there. The change is small, it looks safe, and it is quick to check.

And there is a second reason. The agent does not only read my ticket. It reads parts of my code. And my code was full of catches like this one. So the agent did not invent anything. It did what my codebase showed it.

What the agent does not know are the rules that only exist in our heads. In my head, there is a rule: we don’t catch generic exceptions, we let them surface.

The agent cannot read my head.

Agent = Model + Harness

So how do we get those rules out of our heads? This is where harness engineering comes in.

A coding agent is more than a language model. I like this simple formula:

Agent = Model + Harness

The model generates the code and reasons about it. Everything around the model is the harness: the context it gets, the tools it can use, its permissions, the checks it runs, and the workflow it follows.

Your coding tool already brings a harness with it. But we can also build an outer harness for our own project: AGENTS.md, skills, make ci, custom PHPStan rules. That project-specific part is what this post is about.

Where the terms come from
Guides, sensors, computational, inferential and harnessability all come from Birgitta Böckeler’s article Harness Engineering for Coding Agent Users on martinfowler.com. Read it, it is worth your time.

Guides before. Sensors after.

Böckeler splits the harness into two parts.

Guides work before the agent changes the code. They describe our conventions and how we want the agent to work. Most of us have written an AGENTS.md or a skill by now. Those are guides. In control theory, this direction is called feedforward.

Sensors work after the change. They check the result and give the agent something it can act on. PHPStan is a sensor. Our tests are sensors. This direction is called feedback.

When a sensor finds something, the agent gets the finding, changes the code, and the sensor checks again. That is the feedback loop.

The short version:

A guide says what we want. A sensor checks what we got.

Computational or inferential?

There is a second distinction. Guides and sensors can be computational or inferential.

ComputationalInferential
Guidestypes, scaffoldingAGENTS.md, skills
SensorsPHPStan, tests, make cihuman review, LLM review

Computational controls are executable. They are fast and cheap, and the same input and the same rule always give the same result.

Inferential controls look at meaning and context. That is a human reviewer, or another language model. They are flexible, they can ask whether an abstraction makes sense. But they are slower, they cost more, and the answer may be different next time.

When the result of an agent is not what we wanted, most of us start in the top right corner. We write more into AGENTS.md. We write a skill.

The guidance was there

And here is the part that surprised me.

When I looked back, my project already had a skill that warned about almost exactly this pattern: a catch that turns an exception into a string hides a bug. That skill existed when the agent wrote this catch.

The guidance was there. It made a good result more likely. It did not check the result.

What found the problem was me, in the review. An inferential sensor. A reviewer can see a problem that no rule knows yet. But only a computational check makes sure it does not come back.

Harnessability

How easy is it to build sensors? That depends on the codebase. Böckeler calls this harnessability.

Some things make a codebase easier to harness:

  • types, so we can run type checks,
  • clear module boundaries, so we can check the architecture,
  • fast commands, so the agent can run them again and again,
  • honest exit codes, so the agent knows it failed,
  • clear error messages, so the agent knows what to change.

And their opposites make it harder: mixed conventions, unclear boundaries, slow tests, commands that exit 0 even when they fail, and noisy output.

A well-structured codebase sits on the easy side. New or old does not matter. A big ball of mud sits on the other side. Many legacy applications drift there over the years. But a new project can get there in a few months, too, especially when agents write most of the code.

Legacy teams face the harder problem: the harness is most needed where it is hardest to build.

Birgitta Böckeler

Many legacy Symfony applications started many Symfony versions ago. They have old patterns, half-finished migrations, and an exception to every rule. Remember all those catches the agent learned from? That is what legacy means for an agent: every old pattern is an example.

But we don’t have to clean up everything before we improve the harness. We need a way to add stronger checks without letting every old violation block today’s work.

I stopped fixing the change. I started fixing the gate.

This is the moment where I changed how I work with agents.

Before, when I found a problem in a review, I wrote a comment: please fix this. The agent fixed it. And often, a week later, the same kind of mistake came back in another pull request, and I found it again.

I was the sensor. And I am a slow and expensive sensor, and I get tired.

Now I ask a different question for every review finding: why could my gate not see this? And how can it see it next time?

A review comment fixes one change. A rule checks every future change.

So this time I did not ask for a fix. I asked for a rule.

Name the failure class

The first step is to name the failure class. Not “this controller has a bad catch”. That is just the incident. The failure class is the pattern behind it:

Catching \Exception or \Throwable hides failures.

This one sentence is the most important part of the whole process. If the sentence is too vague, the rule will be too vague. If it is too narrow, the rule only finds this one controller.

Which sensor could have seen it?

With the failure class named, the next question is: which of my sensors could have seen it? Let’s go through the gate.

  • cs-check sees formatting. The catch was nicely formatted.
  • Rector sees code that it can upgrade or refactor. There was nothing to upgrade.
  • PHPStan sees types. Exception is a perfectly valid type. The code was type-safe.
  • deptrac sees dependencies between layers. A controller may depend on Exception. Every layer may.
  • PHPUnit sees behaviour. And the behaviour looked fine: a page with a red message.
  • Infection sees whether the tests notice changes. It does not ask whether the code should exist at all.

None of them. Every sensor did its job. None of them had the job to see this.

So the question is not which sensor saw it. It is which sensor can be given a new job. PHPStan reads every statement, and it lets us write our own rules. So the new sensor became a custom PHPStan rule.

A guide that builds a sensor

Writing a PHPStan rule sounds like a lot of work. A few years ago, it was. You had to learn PHPStan’s API, the node types and the test setup.

Today, I let the agent write it. But I don’t let it improvise. I have a skill for this: phpstan-rule-writer. It is a guide that builds a sensor.

The skill’s workflow is short:

  1. Name the mistake in one sentence; check that deptrac doesn’t already cover it.
  2. Write the rule, register it.
  3. Write a fixture and a test.
  4. Run the test, fix the expected lines from the actual output.
  5. Run make ci-phpstan. The rule now runs against the real code, and against itself.
  6. Fix what it finds. Never edit a baseline by hand; regenerate it.

The rest of the skill is the knowledge I would otherwise have to repeat in every session: where the files go, how error identifiers are named, which node type fits which kind of check, and the quirks of PHPStan’s RuleTestCase. Things like “attributes count towards the reported line, doc blocks do not” or “a trailing .php in the rules: list is not rejected, the rule is just silently never executed”. Each of those lines saves the agent from rediscovering a quirk the hard way.

My part was one sentence: do not catch \Exception or \Throwable.

I learned
Writing the rule was not the hard part. The hard part was naming the mistake.

The skill

Here is the complete skill, as it lives in the project. It is written for my project: the paths, the Docker commands and the ticket numbers will look different in yours. Take the structure, not the details.

<!-- .claude/skills/phpstan-rule-writer/SKILL.md -->
---
name: phpstan-rule-writer
description: >
  Write custom PHPStan rules to catch mistakes that were discovered during a coding session.
  Use this skill whenever: (1) a coding mistake was corrected in the conversation and you want to prevent it from happening again, (2) the user asks to "add a PHPStan rule" or "codify this as a static analysis check", (3) a code review reveals a pattern that should be enforced automatically, (4) the user says "turn this mistake into a rule" or similar, (5) an existing rule under app/ci/phpstan/ has to be changed or tested. This skill ensures that lessons learned during development are permanently encoded as deterministic checks. After correcting code, offer in one sentence to codify the lesson as a rule; write it once the user accepts.
---

## Contents

- Layout
- Error identifiers: `<concern>.<invariant>`
- The rule
- Registration
- The test
- Workflow
- Context

# PHPStan Rule Writer

Turns a mistake that was just corrected into a deterministic check, so it cannot slip through again.
After any correction, ask: *could a PHPStan rule have caught this before the code was written?* If yes,
offer it in one sentence and write it once the user accepts. For layering violations check
`ci/config/deptrac.yaml` first — a PHPStan rule is only worth it when you need a more targeted message
or something deptrac cannot express.

## Layout

```
app/ci/
  config/
    phpstan.dist.neon              ← bin/ config/ public/ src/ + ci/phpstan/Rules/, level max (TABS under rules:)
    phpstan.tests.neon             ← tests/, custom ruleset + extensions, no level (4 SPACES under rules:)
    phpstan-baseline.neon          ← generated (make ci-phpstan-baseline)
    phpstan-tests-baseline.neon    ← generated
    phpstan-ignore.neon            ← hand-written, reasoned exemptions
  phpstan/
    Rules/MyCustomRule.php         ← namespace CI\PhpStan\Rules
    Tests/Rules/MyCustomRule/      ← capital T; one directory per rule, namespace follows the path
      MyCustomRuleTest.php         ← namespace CI\PhpStan\Tests\Rules\MyCustomRule
      data/my-custom-rule.php      ← the fixture, never shared with another rule's test
```

The `Rule` suffix carries through class → directory → test class. PSR-4 prefix is **`CI\PhpStan\`**
(not `App\…`) and lives in **`autoload-dev`**, so rules never ship with the runtime autoload;
lowercase `tests/` breaks the autoloader on Linux.

**Your rule is analysed too**, at level max, and by our own rules — `SingleUseVariableRule` will tell
you to inline that one-shot local. php-cs-fixer covers `ci/phpstan/` as well, so `make ci-cs-fix`
reformats it; `data/` is deliberately excluded from the fixer, because reformatting a fixture shifts
the line numbers its test asserts.

## Error identifiers: `<concern>.<invariant>`

Every error carries an `->identifier()` — never `custom.`, never a project name, never the rule class.
It is what shows up in `@phpstan-ignore` lines and baseline entries, so it has to read as an invariant.

Pick the **concern from what the rule actually inspects**, not from the ticket it was born in — a
concern claiming a narrower scope than the code has is a lie in the error output. The part after the
dot names the violated invariant, lower-camel, dropping any word the concern already carries:
`command.namePrefix`, not `command.commandNamePrefix`. One identifier per rule, shared by all of its
errors.

Read the concerns in use off the rules themselves rather than a list here, which only goes stale:

```sh
grep -ho "identifier('[^.]*" ci/phpstan/Rules/*.php | sort -u
```

A new concern is fine — check it does not collide with a PHPStan core identifier
(`grep -ao "'<concern>\.[a-zA-Z]*'" vendor/phpstan/phpstan/phpstan.phar`) and ask the user first.

## The rule

```php
<?php

declare(strict_types=1);

namespace CI\PhpStan\Rules;

use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;

/**
 * One-line description of what the rule enforces and why.
 *
 * @implements Rule<Class_>
 */
final readonly class MyCustomRule implements Rule
{
    public function getNodeType(): string
    {
        return Class_::class;
    }

    public function processNode(Node $node, Scope $scope): array
    {
        // ... your checks ...
        return [
            RuleErrorBuilder::message(\sprintf(
                'Class "%s" does X. Do Y instead.',
                $node->namespacedName?->toString() ?? 'anonymous class',
            ))->identifier('architecture.somethingSpecific')->build(),
        ];
    }
}
```

- `final readonly class`, `@implements Rule<NodeType>` matching `getNodeType()`, no `@return` docblock
  (PHPStan infers it from the interface).
- No `\assert($node instanceof …)` — PHPStan narrows `$node` from `@implements` on its own.
- No `#[AsTaggedItem('phpstan.rules.rule')]`. It looks like registration but isn't: PHPStan builds a
  Nette container and never reads Symfony attributes. Eight rules carried it inertly until DAZ-177.
- `processNode` is a short chain of named predicates (`isDoctrineAdapter`, `expectedTestPath`), no
  flag variables or `break 2` — the rule body follows `dazzhub-code-shape` like any other class.
- Messages built with `\sprintf()`, offending class in double quotes, saying what to do — not just
  what is wrong. Optionally `->tip('…')`. Chain order `->identifier()->line()->build()`.

**Node type**: `MethodCall` / `StaticCall` / `New_` / `FuncCall` for call sites, `Class_` for a class
declaration, `ClassMethod` / `Property` / `Assign` / `Return_` for members, `FunctionLike` for data
flow inside a body, `PHPStan\Node\InClassNode` when the **absence** of something matters (a missing
method, an inherited default) — it hands you `getClassReflection()` and `getOriginalNode()`.

On a `Class_` node the scope is *outside* the class, so `$scope->getClassReflection()` is null there —
use `$node->namespacedName?->toString() ?? 'anonymous class'`. Everywhere else
`$scope->getClassReflection()` is the enclosing class, and `$scope->getType($expr)` its inferred type
(match a receiver with `(new ObjectType(Foo::class))->isSuperTypeOf(…)->yes()`). Attributes live in
`$node->attrGroups[]->attrs[]`, compared via `$attr->name->toString()`; each `Node\Arg` has a nullable
`name` and a `value`, so a positional argument is `name === null` at position 0. For promoted
constructor params use `$param->isPromoted()` / `$param->isReadonly()`, and the variable is
`$param->var`, not `$param->name`.

## Registration

The rule goes into exactly **one** lane: `phpstan.dist.neon` for production code, or
`phpstan.tests.neon` for test hygiene (a test-code rule sees nothing in the dist lane). Insert
alphabetically, mind the indentation of that file, and write the class name **without** a `.php`
suffix — a trailing `.php` is not rejected, the rule is just silently never executed.

There is no autodiscovery: `phpstan.rules.rule` is PHPStan's own DI tag and works via a `services:`
entry, but Nette's `search:` section is not available (*"Found section 'search', but corresponding
extension is missing"*), so every rule needs its own line either way.

`phpunit.dist.xml` needs nothing — the "PHPStan Rules" testsuite picks up new directories recursively.

## The test

```php
<?php

declare(strict_types=1);

namespace CI\PhpStan\Tests\Rules\MyCustomRule;

use CI\PhpStan\Rules\MyCustomRule;
use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;
use PHPUnit\Framework\Attributes\CoversNothing;

/**
 * @extends RuleTestCase<MyCustomRule>
 */
#[CoversNothing]
final class MyCustomRuleTest extends RuleTestCase
{
    public function test_rule(): void
    {
        $this->analyse(
            [__DIR__ . '/data/my-custom-rule.php'],
            [
                ['Actionable error message.', 12],  // [message, line]
            ],
        );
    }

    protected function getRule(): Rule
    {
        return new MyCustomRule();
    }
}
```

`RuleTestCase` is loadable although phpstan ships as a phar — its `bootstrap.php` registers a phar
autoloader, so just `use` it and never `require_once 'phar://…'`. `#[CoversNothing]` is right here:
PHPStan rule tests are test-harness tests, not focused tests of application behavior, and the coverage
source set in `phpunit.dist.xml` is `src/` only. Test methods snake_case, `getRule()` last.

The fixture is a plain PHP file with at least one violating and one compliant case; classes it
references must be autoloadable from `vendor/`, the fixture's own classes need not be (PHPStan reads
them by path — the composer PSR-4 warning is harmless).

Quirks of `analyse()`:
- **Attributes count towards the reported line, doc blocks do not.** Run the test once and read the
  real line off the failure diff instead of counting.
- `->line($someNode->getStartLine())` overrides that. Two errors with the same message on the same
  line are indistinguishable in the output, so a rule that can fire twice per class must set it.
- Messages are matched character-for-character; sort key is `(line, message, tip)`, your array order
  doesn't matter.
- A failure diff may append *"… not found in ReflectionProvider. Configure autoload-dev …"*. **That
  is noise** — it is only appended when expected and actual already differ, so it can never turn a
  green test red. Fix the line/message mismatch and it disappears.
- No `getAdditionalConfigFiles()` and no `data/phpstan-fixtures.neon`: DAZ-153 removed a shared
  `scanFiles` neon from every test and the suite stayed green with zero `classNotFound` errors. If a
  new fixture genuinely needs one, scope it to that rule's own directory and say so — don't
  resurrect the shared file. (It must be `public static`; `protected` silently does nothing.)

## Workflow

Everything runs in the container — never `composer`, `phpunit` or `bin/console` on the host.

1. Name the mistake in one sentence; check deptrac doesn't already cover it.
2. Write the rule, register it in the right lane.
3. Write fixture + test.
4. `docker compose exec -T app vendor/bin/phpunit -c ci/config/phpunit.dist.xml --filter MyCustomRuleTest`
   (whole suite: `--testsuite="PHPStan Rules"`), fix the expected lines from the actual output.
5. `docker compose exec -T app make ci-phpstan` — the rule now runs against real code, and against
   itself.
6. Fix what it finds. **Never edit a baseline by hand — regenerate it** with
   `make ci-phpstan-baseline`; appended entries sit in the wrong group, stay green, and then move on
   the next regeneration, hiding the real change in the diff. Ask before baselining at all: if a rule
   is too noisy to fix in this ticket, narrowing or dropping it is usually the better answer.
   `phpstan-ignore.neon` is the opposite — hand-written, each entry saying why the code is right and
   the rule wrong about it.

## Context

- `phpstan/extension-installer` loads every installed extension in **both** lanes (strict-rules,
  deprecation-rules, phpunit, symfony, webmozart-assert, disallowed-calls) — never add a vendor
  include to `phpstan*.neon`. The exception is phpstan-doctrine: `extra.phpstan/extension-installer.ignore`
  in `composer.json` skips it, and both lanes include only its `extension.neon` (type inference) —
  its `rules.neon` needs an `objectManagerLoader` that boots the kernel. Details:
  `docs/ai_docs/github-ci.md` ▸ *PHPStan extensions*.
- `spaze/phpstan-disallowed-calls` (4.15) scopes constructor disallows by argument: `allowParamsAnywhereAnyValue` catches a no-arg `new DateTimeImmutable()`, `disallowParamsAnywhere` with value/typeString literal unions catches `now`/`today`/`tomorrow`; several entries per method coexist, each with its own message. No regex on string params, so other relative strings (`-30 days`) need enumerating and dynamic args escape (known locals are constant-folded).
- Rules to copy from: `NoExtendServiceEntityRepositoryRule` (simplest — `Class_::extends`),
  `CommandNameMustStartWithAppRule` (class attribute + its arguments), `DbQueryOnlyInRepositoryRule`
  (receiver type + call-site location), `SingleUseVariableRule` (`FunctionLike`, many errors per node).

The setup

All custom rules live outside of src/, under ci/phpstan/, with their own namespace CI\PhpStan\ in autoload-dev. So they never ship with the runtime autoloader.

app/ci/
├── config/
│   ├── phpstan.dist.neon          # production code, level max
│   ├── phpstan.tests.neon         # test code
│   ├── phpstan-baseline.neon      # generated, never edited by hand
│   └── phpstan-ignore.neon        # hand-written, reasoned exemptions
└── phpstan/
    ├── Rules/
    │   └── NoGenericExceptionCatchRule.php
    └── Tests/
        ├── RuleTestCoverageTest.php
        └── Rules/
            └── NoGenericExceptionCatchRule/
                ├── NoGenericExceptionCatchRuleTest.php
                └── data/
                    └── no-generic-exception-catch.php

The Rule suffix carries through from the class to the test directory to the test class. One directory per rule, one fixture per test, never shared. The agent does not need all rules in its context to know where a new one goes. The directory structure tells it.

And the rules are analysed by PHPStan too, at level max, and by our own rules. A sensor that does not follow the conventions it enforces would be a strange sensor.

Registration is one line per rule. There is no autodiscovery in PHPStan’s container:

# app/ci/config/phpstan.dist.neon
rules:
	- CI\PhpStan\Rules\NoGenericExceptionCatchRule

The rule

Here is the rule as it runs today. It looks at every catch and reports it, unless it is allowed:

// app/ci/phpstan/Rules/NoGenericExceptionCatchRule.php
namespace CI\PhpStan\Rules;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Throw_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Catch_;
use PhpParser\Node\Stmt\Expression;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ObjectType;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Retry\RetryStrategyInterface;

/**
 * Catching \Exception or \Throwable swallows failures nobody anticipated; catch the specific exception instead.
 * A catch that ends by rethrowing the caught exception, or a new one carrying it as previous, swallows nothing.
 *
 * @implements Rule<Catch_>
 */
final readonly class NoGenericExceptionCatchRule implements Rule
{
    private const array GENERIC_TYPES = ['Exception', 'Throwable'];

    private const array EXCEPTION_HANDLING_EVENTS = [
        ExceptionEvent::class,
        WorkerMessageFailedEvent::class,
        ConsoleErrorEvent::class,
    ];

    public function getNodeType(): string
    {
        return Catch_::class;
    }

    public function processNode(Node $node, Scope $scope): array
    {
        if (!$this->isApplicationCode($scope) || !$this->catchesGenericType($node) || $this->rethrows($node) || $this->isExceptionHandlingCode($scope)) {
            return [];
        }

        return [
            RuleErrorBuilder::message('Do not catch \Exception or \Throwable. Catch the specific exception you can handle and let the rest surface.')
                ->identifier('exception.genericCatch')
                ->build(),
        ];
    }

    private function isApplicationCode(Scope $scope): bool
    {
        return \str_starts_with($scope->getNamespace() ?? '', 'App\\');
    }

    private function catchesGenericType(Catch_ $catch): bool
    {
        return \array_any($catch->types, static fn (Name $type): bool => \in_array($type->toString(), self::GENERIC_TYPES, true));
    }

    private function rethrows(Catch_ $catch): bool
    {
        $thrown = $this->thrownAtEnd($catch);

        return $thrown !== null && $catch->var !== null && $this->carriesCaughtException($thrown, $catch->var);
    }

    private function thrownAtEnd(Catch_ $catch): ?Expr
    {
        $lastStatement = \array_last($catch->stmts);

        return $lastStatement instanceof Expression && $lastStatement->expr instanceof Throw_ ? $lastStatement->expr->expr : null;
    }

    private function carriesCaughtException(Expr $thrown, Variable $caught): bool
    {
        if ($thrown instanceof Variable) {
            return $thrown->name === $caught->name;
        }

        return $thrown instanceof New_
            && \array_any($thrown->args, static fn (Node $argument): bool => $argument instanceof Arg && $argument->value instanceof Variable && $argument->value->name === $caught->name);
    }

    private function isExceptionHandlingCode(Scope $scope): bool
    {
        return $this->isRetryStrategy($scope) || $this->handlesExceptionEvent($scope);
    }

    private function isRetryStrategy(Scope $scope): bool
    {
        $class = $scope->getClassReflection();

        return $class !== null && $class->is(RetryStrategyInterface::class);
    }

    private function handlesExceptionEvent(Scope $scope): bool
    {
        $function = $scope->getFunction();
        if ($function === null) {
            return false;
        }

        foreach ($function->getVariants() as $variant) {
            foreach ($variant->getParameters() as $parameter) {
                if (\array_any(self::EXCEPTION_HANDLING_EVENTS, static fn (string $event): bool => (new ObjectType($event))->isSuperTypeOf($parameter->getType())->yes())) {
                    return true;
                }
            }
        }

        return false;
    }
}

processNode() reads like the failure class: a generic catch in application code is a violation, unless it rethrows, or unless the code around it is exception handling: a Symfony exception listener or a Messenger retry strategy. Those exist to deal with arbitrary failures.

It did not look like this on the first day. I’ll come back to that.

A sensor is code. Test it like code.

A custom rule is part of the harness. If it is wrong, the agent gets wrong feedback. So I test it like production code.

A rule can go wrong in three ways:

  • A false alarm: the rule reports code that is fine.
  • A blind spot: the rule misses code that should fail.
  • A useless message: the rule is right, but the agent cannot tell what to change.

So every rule gets a test. It runs the rule against one small PHP file that holds both: code that must pass and code that must fail. And it checks the exact message and the exact line.

// app/ci/phpstan/Tests/Rules/NoGenericExceptionCatchRule/NoGenericExceptionCatchRuleTest.php
namespace CI\PhpStan\Tests\Rules\NoGenericExceptionCatchRule;

use CI\PhpStan\Rules\NoGenericExceptionCatchRule;
use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;
use PHPUnit\Framework\Attributes\CoversNothing;

/**
 * @extends RuleTestCase<NoGenericExceptionCatchRule>
 */
#[CoversNothing]
final class NoGenericExceptionCatchRuleTest extends RuleTestCase
{
    public function test_rule(): void
    {
        $message = 'Do not catch \Exception or \Throwable. Catch the specific exception you can handle and let the rest surface.';

        $this->analyse(
            [__DIR__ . '/data/no-generic-exception-catch.php'],
            [
                [$message, 23],
                [$message, 28],
                [$message, 33],
                [$message, 105],
            ],
        );
    }

    protected function getRule(): Rule
    {
        return new NoGenericExceptionCatchRule();
    }
}

The fixture is plain PHP. Every case in it is a decision about what the rule should and should not see. Here is an excerpt:

// app/ci/phpstan/Tests/Rules/NoGenericExceptionCatchRule/data/no-generic-exception-catch.php
final class Controller
{
    public function plain(): void
    {
        try {
            \strlen('x');
        } catch (\Throwable $e) {                    // fails
        }

        try {
            \strlen('x');
        } catch (YoutubeRateLimitException | \Throwable $e) {  // fails
        }
    }

    public function specific(): void
    {
        try {
            \strlen('x');
        } catch (YoutubeRateLimitException $e) {     // passes
        }
    }
}

final class Rethrower
{
    public function rethrow(): void
    {
        try {
            \strlen('x');
        } catch (\Throwable $e) {                    // passes
            \strlen('record');

            throw $e;
        }
    }

    public function wrapWithPrevious(): void
    {
        try {
            \strlen('x');
        } catch (\Exception $e) {                    // passes
            throw new \RuntimeException('wrapped', previous: $e);
        }
    }

    public function wrapWithoutPrevious(): void
    {
        try {
            \strlen('x');
        } catch (\Exception $e) {                    // fails
            throw new \RuntimeException($e->getMessage());
        }
    }
}

Look at the last case. Wrapping the exception without passing it as previous throws something, but it still loses the original stack trace. The rule treats that as hiding.

A sensor for the sensors

Forgetting that test is easy. So one more test watches for that. It fails when a rule has no test:

// app/ci/phpstan/Tests/RuleTestCoverageTest.php
namespace CI\PhpStan\Tests;

use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;
use Webmozart\Assert\Assert;

#[CoversNothing]
final class RuleTestCoverageTest extends TestCase
{
    public function test_every_rule_has_a_test(): void
    {
        $rulesDir = \dirname(__DIR__) . '/Rules';
        $testsDir = __DIR__ . '/Rules';

        $ruleFiles = \glob($rulesDir . '/*Rule.php');
        Assert::notFalse($ruleFiles);

        $missing = [];
        foreach ($ruleFiles as $ruleFile) {
            $name = \basename($ruleFile, '.php');
            if (!\is_file($testsDir . '/' . $name . '/' . $name . 'Test.php')) {
                $missing[] = $name;
            }
        }

        self::assertSame(
            [],
            $missing,
            \sprintf(
                'Missing RuleTestCase test(s) for: %s',
                \implode(', ', $missing)
            )
        );
    }
}

It does not tell me whether a test is good. But it enforces one useful rule: every PHPStan rule has its own test.

On success: silence. On failure: direction.

This is what the agent sees now when it writes that catch:

$ make ci
cs-check   ✓
rector     ✓
phpstan    ✗
  FetchVideoDetailsController.php
  Do not catch \Exception or \Throwable. Catch the specific exception
  you can handle and let the rest surface.

One short line per tool. Then PHPStan fails, and the gate stops.

The message is not written for humans. It is written for the agent that has to fix the code. It does not only say what is wrong. It says what to do instead.

For the agent, the command output becomes part of its context. So I want two things from my gate:

  • On success: silence. A short line per tool is enough. Hundreds of lines saying that everything is fine only clutter the context.
  • On failure: direction. Where is the problem, which rule failed, and what should the agent do next?

The output of a quality tool, down to a single message, is part of the harness.

The old code was full of this pattern

Then I ran the new rule against the whole application. The old code was full of this pattern. Here is one of them. It is not a controller. It is a service that asks a graph database for statistics: how many chunks, entities and relationships there are.

try {
    // ask the graph database for statistics
} catch (Throwable $e) {
    $this->logger->error('Stats query failed', [/* … */]);
    return ['chunks' => 0, 'entities' => 0, 'relationships' => 0];
}

If the query fails, it catches everything and logs the error. And then it returns zeros.

Think about what that means. The statistics now say: there is nothing. Not because the data is empty, but because the query failed. This catch does not only hide the error. It invents data.

But now we had a new problem. If we switched the rule on, the pipeline would be red before anyone changed a single line of code.

A sensor we cannot switch on does not help us yet.

The baseline

So we generated a PHPStan baseline and switched the rule on. Most of you know the baseline from raising the PHPStan level in an old project. Here it works as a ratchet:

  1. A known violation passes. make ci is green on the day we switch the rule on.
  2. A new violation fails. We accept the old problems for now. We do not allow new ones.
  3. A fixed violation has to leave the baseline, otherwise the check stays red. So the problem cannot come back unnoticed.

The baseline is generated with make ci-phpstan-baseline, never edited by hand. Hand-appended entries end up in the wrong group, stay green, and move around on the next regeneration, hiding the real change in the diff.

My rule was wrong

Then something happened that I had not planned. The rule went live, and the first thing we learned: some of them were not violations at all.

} catch (Exception $e) {
    $this->lifecycle->fail($generation, $e->getMessage());
    throw $e;
}

This one catches the exception, marks the job as failed, and then throws the exception again. The failure still surfaces. It still ends up in the log. Nothing is hidden.

The others were different. They caught the exception and then carried on: they returned zeros, showed a message, or simply continued. Those are the ones that hide failures.

So my rule was wrong. A false alarm, one of the three ways a sensor can go wrong.

And the rule was wrong because my sentence was wrong. The failure class “catching \Exception hides failures” is too broad. A condition was missing:

Catching \Exception or \Throwable without handling or rethrowing hides failures.

Catching is not the problem. Hiding is.

So I fixed the sentence first, and then the rule. The fixture got both cases: a catch that rethrows has to pass, a catch that carries on has to fail. That is the Rethrower class above.

I learned
Naming the failure class is the hard part. A false alarm is usually not a bug in the code of the rule. It is a bug in the sentence behind it.

Gone in one day

Then an agent worked through the rest. Most catches were removed completely. The failures now go where they belong: to Symfony’s error handling. The others now catch the specific exception that the call really throws.

With every fix, the baseline entry had to go. The number went down, one fix at a time. All of it happened in one afternoon. The baseline was empty that evening. I reviewed everything and merged it the next day.

I don’t open a ticket for every group of fixes anymore. Agents are good at this kind of work, and every run goes through the whole gate.

The limiting factor is not the agent anymore. It is my review attention.

When a bad change gets through

Let me take a step back. This is the method behind the story. It starts every time a bad change passes the gate:

  1. Name the failure class. The pattern, not the incident.
  2. Can the gate see it? If an existing sensor can, improve that sensor. If not, build and test the smallest new sensor that can.
  3. Does old code fail? Put it into the baseline, switch the protection on now, and clean up step by step.

And it does not matter who wrote the bad change.

Cleanup takes time. The baseline protects now.

Same method, a different review finding. An agent wrote this code, and I was not paying attention. That is how it got in.

foreach ($command->videoIds as $videoId) {
    if ($this->videoRepository->findById($videoId) === null) {
        // …
    }
}

One query to the database in every loop iteration. A classic N+1.

The failure class: no repository read calls inside a loop. The rule, NoRepositoryCallInLoopRule, found more places in the codebase.

And here is the difference to the catches. A catch is a local fix, and they were gone in one day. An N+1 needs different database queries. That takes attention, and it does not happen in an afternoon.

So most of these places are still in the baseline. And that is fine:

phpstan  ✓  # 12 in baseline since August · 0 new

The protection is on anyway: twelve entries since then, and no new ones. That is what the baseline is for. It protects you even when the cleanup stalls.

The harness grows one rule at a time

If you repeat this method, the harness grows. This is my project today:

CommandHandlerMustDispatchDomainEvent     NoIsset
CommandNameMustStartWithApp               NoMagicNumber
CompareDateTime                           NonAbstractClassMustBeFinal
ControllerMustNotExtendAbstractController NoNativeAssert
ControllerMustNotInjectRepository         NoNewDoctrineRepositoryInTests
ControllerMustResolveUserViaCurrentUser   NoNewInMemoryInTests
ControllerNameMustStartWithUseCase        NoParameterPassedByReference
CoverageAttributeMustTargetClass          NoProtectedMemberInFinalClass
DbQueryOnlyInRepository                   NoRepositoryCallInLoop
DoctrineRepositoryMustHaveTest            PreferGetServiceOverNewInTest
EntityMustBeInMappedNamespace             PreferQueryBuilderOverDql
IdValueObjectMustBeStringable             RepositoryMethodNaming
ImmutableValueObject                      ServiceMustHaveReadonlyProperties
InvokableCommandMustNotExtendCommand      SingleUseVariable
KnownRoleInIsGranted                      TestClassNameMustEndWithTest
MutationControllerMustBeGranted           TestHookMustCallParent
NoErrorSuppression                        UseCaseMustNotDependOnOtherUseCase
NoExtendServiceEntityRepository           WebTestMultiRequestMustDisableReboot
NoGenericExceptionCatch

Every name is a failure class, written as a sentence.

You don’t need mine. Most of them would not fit your project. But look where they come from. A few came from bugs and review findings, like the catch and the N+1. Most of them are conventions: things every senior in my team would say in a review.

Your team has those too. They live in your heads and in your review comments. They are just not executable yet.

And I did not start with all of them. They came one review finding at a time.

Getting started

You don’t need a new platform for any of this. Your existing CI is the starting point.

  1. One command for the whole gate. I use make ci. Composer scripts or a shell script work just as well. What matters: it never waits for input, it returns the right exit code, it is fast, and it prints only useful output. My full gate takes seconds.
  2. The agent runs it before “done”. Put it into your AGENTS.md, and tell the agent to fix every finding: not ignore it, and not add it to the baseline. Don’t make the agent wait for the remote pipeline. Let it run the same checks inside its own loop.
  3. Green but wrong? Ask a different question. You will notice that a change is wrong, because you know how your code should look. That is your experience. Your gate does not have it yet. So don’t only ask why the agent wrote it. Ask: what is invisible to my gate? Then let the agent turn your experience into a rule that a machine can check.
<!-- AGENTS.md -->
Run `make ci` before you say you are done. Fix every finding.

The bug was a sensor that could not see it

Back to the beginning. The agent did what I asked. It solved the task. It ran the gate. And every check passed.

The catch made the gap visible to me. The rule made it visible to the agent.

The bug was not the catch. The bug was a sensor that could not see it.

Green is not done. Green only means: nothing that your sensors can see is wrong. So make your sensors see more.

The agent can write the rules. Knowing which rule to write is still our job.

More sources

Slides

Enter your instance's address


More posts like this

Coding Agents Don't Scale Teams

󰃭 2026-09-18 | #ai #dim factory #guardrails #software factory #software-development #workflow

I’m watching Patrick Debois’ talk Coding Agents Don’t Scale Themselves. Neither Do Your Teams. for the third time. He describes a familiar transformation program: hackathons, lunch-and-learns, a shared Slack channel. We know these formats from Agile and DevOps.

And yet a company can run all of them and still depend on a handful of people maintaining private AI workflows.

That gap is what keeps me watching. Underneath it sits one question:

Continue reading 


The Bright Factory Needed Windows

󰃭 2026-09-08 | #agents #ai #ai engineering #claude code #langfuse #observability #orca #pi #self-hosting

TL;DR
Claude Code and Pi both produced logs, but I had no practical view across them. I self-hosted Langfuse to collect their traces in one place. Pi works end to end, while Claude Code works through transcript replay but still needs one live-hook proof. Observability helped, but it also added cost, secrets, and new failure modes.

Claude Code and Pi both kept session logs on my agent server. In theory, I could audit every run. In practice, that meant connecting to the machine, finding two different directories, and reading two different formats.

Continue reading 