8. Layer two: what clustering decides#

Terms introduced herenormalizer rule, regex

Go back to the cluster list in chapter 4 and look at the bottom of it.

c7   1 rows  PAYPAL *ETSYSELLER
c8   1 rows  PAYPAL *PATREON
c9   1 rows  PAYPAL *STEAMGAMES

Three separate one-row clusters, and the model skipped all three, correctly: one row is not evidence, and it cannot tell whether PAYPAL *PATREON is a chain it should know or one person's monthly payment to a stranger.

But you can see something the model was never shown. Those three rows share PAYPAL *. That is not a merchant, it is a payment processor stamping its name on the front, and it will be on the front of the next four hundred rows too.

The model could not see it, because the way the rows were grouped made it invisible. Every cluster contained exactly one merchant, so nothing that spans merchants could ever appear in one.

Look from the other angle#

node loop.mjs --shapes
34 rows -> 3 shape findings (noise shared across merchants)

s1   3 rows across 3 merchants   PAYPAL * ▮
      PAYPAL *STEAMGAMES / PAYPAL *PATREON / PAYPAL *ETSYSELLER
s2   4 rows across 2 merchants   ▮ COFFEE
      BLUE BOTTLE COF / PHILZ COFFEE
s3   3 rows across 2 merchants   ▮ MKT
      WHOLEFDS MKT / WHOLE FOODS MARKET

Same thirty-four rows. Different question. Instead of "which rows share a merchant", this asks "which rows share everything except the merchant".

The mechanism is twenty lines in shapes() and worth reading:

  1. Group the spans, merging variants, so one merchant's own renderings count once.
  2. For every token, count how many different merchants it appears under.
  3. A token seen under two or more merchants is not a merchant word. Keep it.
  4. Everything else becomes ▮, and consecutive blanks collapse.
  5. Group by the resulting signature. Report the ones seen across several merchants.

No model, no configuration, no list of known processors. PAYPAL * surfaced because of its distribution across the data, not because anybody knew about PayPal.

And notice this view also runs over the rows the classifier got right. A format is not a failure. It is on the confident rows too, and the residue view can never see it.

Two of those three findings are wrong#

s2 and s3 are the trap. COFFEE appears under two merchants and MKT appears under two, so the arithmetic flags them, and the arithmetic is wrong: those are parts of merchant names. Strip COFFEE and Philz Coffee becomes Philz.

This is why the shape view produces findings, not changes. Deciding whether a repeated token is bank formatting or part of a name needs to know what the words mean, which is precisely the judgement you brought a model in for. The instruction it gets is one sentence:

Only propose a normalizer rule for BANK NOISE (prefixes, processor markers, reference ids, transaction-type trailers), never to encode a merchant.

Here is that judgement being made, from a real batch report in this repo:

s6 skipped: '▮ Market' is not a noise shape. 'Market' is part of the merchant name in every example (Gus's Community Market, Hamlet Market, Kervansaray Market), so a normalizer rule would delete real merchant text.

s7 skipped: '▮ Valero' is not a noise shape: 'Valero' is the fuel brand and the variable part ('Andys', 'Hub') is the franchisee, so there is nothing to strip.

Two findings the statistics produced and a reader threw out for reasons no statistic contains. This is the division of labour the whole course is about: code finds the candidates, the model judges them, code checks the judgement.

Take the true one#

Add the rule to rules in kb.json:

{ "id": "paypal-prefix", "kind": "prefix", "match": "PAYPAL *",
  "emits": ["channel:online", "processor:paypal"] }
node classify.mjs "PAYPAL *PATREON 4029357733"
before   span="PAYPAL *PATREON"   tags: (none)
after    span="PATREON"           tags: channel:online processor:paypal

The review rate did not move, and the change was still worth making. Three things happened:

  • The prefix became two facts. processor:paypal and channel:online are now available to filters, charts and rules, on every PayPal row forever. Same as SQ * in chapter 1: the noise was the evidence.
  • The span became a name. PATREON is a thing a model can look up. PAYPAL *PATREON was not.
  • The next import will cluster correctly. Five Patreon rows across two PayPal renderings used to be five one-row clusters. Now they are one cluster of five, over the evidence threshold, and the loop can act.

That last one is the point. A stage-2 change did not fix any row. It raised the ceiling on what stage 3 is able to propose, forever.

If your agentic system is producing weak output, the highest-value work is almost never in the prompt. It is in what you compute before you ask.

Where code stops and data begins#

You just added a rule with "kind": "prefix". That word is doing a lot of work, and it is the last structural idea in this course.

The model never writes code. It writes parameters to named operators that somebody implemented once, with tests. The production knowledge base in this repo has these:

prefix      remove an anchored literal at the start        (+ emit facets)
token       remove a whole word from a small list
substring   remove or replace a literal anywhere
trailer     remove a separator and everything after it     (" : Electronic Debit")
regex       remove or replace a regex match                (rare, linted)
extract     capture a reference id or store number into a named field, then remove it
when        gate any of the above on context
merchant    a pattern, a name, a category, optionally a type
fixture     a raw description, some contexts, an expectation

Nine operators. Every improvement the loop has ever made is one of these nine plus parameters. Adding a new operator is a code change with tests, a spec entry and human review. Using one is a text edit that a gate can approve at 3am.

That line is the safety boundary, and it is also what keeps the system legible after a thousand changes. The alternative, letting the model emit small programs, gives you unbounded behaviour in your hot path and a knowledge base nobody can read.

So what happens when the model needs something the nine cannot express? It says so. From a real batch:

c10 skipped: Cannot be expressed with the available proposal schema. The correct edit is an issuer alias: attach the bank's truncated rendering "AMERICAN EXPR" to the existing issuer American Express, so those lines classify as a card payment instead of falling into the unknown bucket. Needs a tooling fix before this cluster can be resolved; no merchant, rule or fixture change should be made in the meantime.

That is a good answer to an impossible request. It names the missing operator, cites the rows it would serve, and declines to do the wrong thing in the meantime. A ticket gets filed, a human adds the operator with tests, and every future batch can use it. Design the refusal path, and give it somewhere to put what it could not do.

Three more things rules need that merchants do not#

Rules compose, which makes them harder than merchant rows in three specific ways.

A workbench, because effect depends on order. Your new rule runs after all the existing ones, on text they have already changed. So the model gets a tool that dry-runs a candidate: here is the text after the current pack, here is the text with your candidate, here is which existing rule fired first. It iterates there and only then proposes. Without it, every rule proposal is a guess about a pipeline the proposer cannot see, and the must_transform examples come out wrong.

A lint, because a regex is a program. A model-authored regex is the one place where unbounded runtime can get into a path that runs on every row of every import. Nested quantifiers and unbounded repeats on unanchored patterns are rejected at proposal time, and per-row rule time is asserted in the eval. This is the one hazard in this whole design that can take down a user's machine, so it gets a dedicated check rather than a code review.

A shadow check, because rules interact. A new rule is run against every existing rule's examples, and every existing rule is run against the new rule's examples. Any changed output is a conflict, and the proposal is rejected or has to declare an explicit ordering dependency and go to human review. Examples are never deleted, so this check gets stronger every time the loop runs.

That last property is the one to copy. Build your improvement loop so that its output makes its own checks stricter. Every merchant it adds comes with a fixture, every rule with examples that must and must not transform, and all of them are replayed on every future batch. The system gets harder to break the longer it runs, which is the opposite of how self-modifying systems usually age.


Next: 9. The real thing