<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="http://localhost:4000/feed.xml" rel="self" type="application/atom+xml" /><link href="http://localhost:4000/" rel="alternate" type="text/html" /><updated>2026-11-11T03:02:51+05:30</updated><id>http://localhost:4000/feed.xml</id><title type="html">Total Internal Reflection</title><subtitle>Technology and Art</subtitle><entry><title type="html">Automated domain object candidate extraction in COBOL using matrix factorisation</title><link href="http://localhost:4000/2026/11/10/automated-domain-object-extraction-matrix-factorisation.html" rel="alternate" type="text/html" title="Automated domain object candidate extraction in COBOL using matrix factorisation" /><published>2026-11-10T00:00:00+05:30</published><updated>2026-11-10T00:00:00+05:30</updated><id>http://localhost:4000/2026/11/10/automated-domain-object-extraction-matrix-factorisation</id><content type="html" xml:base="http://localhost:4000/2026/11/10/automated-domain-object-extraction-matrix-factorisation.html"><![CDATA[<p><em>This post how to use <strong>non-negative matrix factorisation (NMF)</strong> as an <strong>extremely fast first-pass technique</strong> (when combined with byte-level dataflow analysis) to <strong>find domain object candidates</strong> when <strong>reverse engineering a legacy COBOL codebase</strong>. A domain object is a group of fields that belong to one thing, such as one account or one customer. The post does a walkthrough of the technique applied to AWS CardDemo, an open source CICS sample application, to explain the concepts. It shows the matrix statistics, the factors that the run found, and the scores that say how good they are. It then follows the same pipeline on a large corpus of about 4+ MLoC, describing the <strong>speed of factorisation at that size</strong>, and what the factorisation found.</em></p>

<hr />

<h2 id="table-of-contents">Table of Contents</h2>

<ul>
  <li><a href="#why-look-for-domain-objects">Why look for domain objects</a></li>
  <li><a href="#what-we-hope-to-find">What we hope to find</a></li>
  <li><a href="#ye-olde-linear-algebra">Ye Olde Linear Algebra</a></li>
  <li><a href="#what-nmf-does">What NMF does</a></li>
  <li><a href="#a-small-example">A small example</a></li>
  <li><a href="#bytes-and-names">Bytes and Names</a>
    <ul>
      <li><a href="#why-names-fail-in-cobol">Why names fail in COBOL</a></li>
      <li><a href="#what-the-bytes-give-the-matrix">What the bytes give the matrix</a></li>
    </ul>
  </li>
  <li><a href="#the-carddemo-matrix">The CardDemo matrix</a></li>
  <li><a href="#rounds">Rounds</a></li>
  <li><a href="#round-1-findings">Round 1 findings</a>
    <ul>
      <li><a href="#account">Account</a></li>
      <li><a href="#card-cross-reference">Card cross-reference</a></li>
      <li><a href="#transaction">Transaction</a></li>
      <li><a href="#card">Card</a></li>
      <li><a href="#customer">Customer</a></li>
      <li><a href="#user">User</a></li>
      <li><a href="#transaction-category-balance">Transaction-category balance</a></li>
      <li><a href="#session-split-in-two">Session, split in two</a></li>
      <li><a href="#records-inside-one-program">Records inside one program</a></li>
      <li><a href="#what-is-left-hubs">What is left: hubs</a></li>
    </ul>
  </li>
  <li><a href="#round-2-findings">Round 2 findings</a></li>
  <li><a href="#the-scores">The scores</a></li>
  <li><a href="#scaling-to-a-large-corpus">Scaling to a large corpus</a></li>
  <li><a href="#conclusions-and-takeaways">Conclusions and Takeaways</a></li>
</ul>

<hr />

<h2 id="why-look-for-domain-objects">Why look for domain objects</h2>

<p>One of the common things to do when modernising a system (or building it from scratch) is to figure out the domain. This is essentially the world model of the system, exact enough to replicate the process that needs to happen to get a business get its work done. There are several ways of teasing this out, but there are always some underlying things that emerge regardless of the process followed. One of those things is the domain objects. domain objects encapsulate both behaviour and data; how that is represented depends upon how the process models them.</p>

<p>As an example, there is an exercise called <strong>event storming</strong>; it is a collaborative process for extracting a set of entities:</p>

<ul>
  <li>Domain aggregates</li>
  <li>Commands</li>
  <li>Events</li>
  <li>Policies</li>
</ul>

<p>The <strong>Domain Aggregates</strong> are the closest to what would come to mind when talking about a domain model, though they aren’t 1:1 mappings. Aggregates are clusters of domain objects which form a natural boundary; this boundary is usually meant to be an abstraction boundary, expressed as an interface, transaction, etc. Before we get to domain aggregates, however, we need to conceptualise the domain objects themselves.</p>

<p><strong>What constitutes a domain object?</strong></p>

<p>If you are in the room with an SME in a particular domain, the answer may be obvious. Alternatively, literature on specific domains may provide clear concepts which can be mapped to these objects without too much headache. One of the common issues in legacy modernisation is that, oftentimes, even though the code may be available, SMEs and documentation are not. This may or may not be a blocker depending upon how the system has been designed / written. Languages that have been written with data aggregation in mind, may expose models which naturally express the domain, eg: classes, structures, etc. in Java, C#, etc. (though this is not a guarantee, transpiled Java code from legacy languages can be <em>more</em> unreadable than the original legacy code). In this post, I will use COBOL as an example of where the domain objects aren’t naturally expressed in the data structures, and talk of using a simple, well-known technique from Linear Algebra to extract out clusters of fields which are potential candidates for domain objects.</p>

<p>We thus return to the previous question, but rephrase it:</p>

<p><strong>What constitutes a domain object, given there is no documentation and no SME?</strong></p>

<p>There may be many answers to this question, and in the mind of a domain expert, there will usually be one or two, depending upon the domain / subdomain and the context. Absent such information, we’d still like to build some sort of a fitness function which can at least approximate what these domain objects would look like, even if we cannot name them immediately.</p>

<p><strong>The characterisation I find useful is that the domain objects are things whose constituent data / fields have a high degree of co-occurrence.</strong></p>

<p>If you know that two pieces of data are used together a lot, whether it is reading or writing, there is a <strong>higher probability</strong> that they belong together in the same domain. Note again that this is not an immutable rule; a logging object used whenever an account is updated, co-occurs with accounts a lot, but that doesn’t imply it is part of the same domain object. But it is a useful heuristic, which can give us potential candidates which can then be sliced and / or aggregated further: that’s where LLMs come into the loop of naming, slicing, and dicing.</p>

<p>In an object-oriented system, the classes give this first answer. A COBOL codebase has no classes. The nearest thing is the copybook. It is a weak guide, for three reasons:</p>

<ul>
  <li><strong>Copies change names.</strong> Each program copies a record into its own storage, often under other names. COTRN02C’s <code class="language-plaintext highlighter-rouge">CDEMO-CT02-TRN-SELECTED</code> holds a card number. Because of the memory-addressable renaming capability of REDEFINEs, names as the sole distinguishing factor can frequently be a poor guide. Applied naively, different names operating on the same data ends up fragmenting any inference of the domain object model.</li>
  <li><strong>One record can hold several things.</strong> A commarea carries the user, the customer, the account, the card and the screen navigation, all together.</li>
  <li><strong>Working storage holds part-copies.</strong> A program keeps a few fields of a record, such as the “old” values on an update screen, under its own names.</li>
</ul>

<p>We will discuss it in more detail in the <a href="#bytes-and-names">Bytes and Names</a> section.</p>

<p>So the question “what are the domain entities of this system?” often may not have an immediate direct answer in (COBOL in this example) code. It has an indirect answer in how the code uses data. A paragraph does one job. A job reads or writes the fields of one or a few entities. So fields that the same paragraphs use, across many programs, probably belong to one entity.</p>

<h2 id="what-we-hope-to-find">What we hope to find</h2>

<p>Technically, you can use LLMs to go through your entire codebase, and fish out candidates. There are a few points to think about, though:</p>

<ul>
  <li>LLMs need to reason through the aliasing of memory regions across programs. This might not the biggest problem if you are using more advanced models, but attention wandering is an ever-present risk.</li>
  <li>Contexts are huge in legacy codebases. Reasoning across all this costs tokens. There is definitely scope to do a lot of cheap deterministic analysis before bringing in models of any kind. Much of my current interests focus on allowing less stronger models to do better inference, by leveraging deterministic analyses.</li>
  <li>The outcome is neither determministic, nor traceable; there may be skips.</li>
</ul>

<p>For this to be useful, we expect to get a few things:</p>

<ol>
  <li><strong>The entities.</strong> Each entity is a group of fields, joined across programs, whatever names each program gives them. Names which partially or fully refer to the same memory region(s) should have clear correlations.</li>
  <li><strong>Where each entity is used.</strong> For each entity, the paragraphs that read or write it. These are the candidate owners of the entity, and the places that a change to it affects.</li>
  <li><strong>Which entities cross the batch and online boundary.</strong> A record that both a nightly batch job and a CICS screen change is a place where a modernised system needs one owner.</li>
  <li><strong>Shared state that is not an entity.</strong> Session data that programs pass to each other, such as the commarea, also shows up as a group. It is not part of the domain model. It tells you which programs form one user-facing flow.</li>
</ol>

<p>There are other things that may surface, but the idea is to be able to extract out useful clusters of co-occurring data, <em>cheaply</em>, for more expensive analyses to happen downstream.</p>

<h2 id="ye-olde-linear-algebra">Ye Olde Linear Algebra</h2>

<p>Remember the classic movie recommender system idea? Users rate a bunch of movies they have watched, and the recommender system can usually unearth both the genre and the taste of each user. Let’s refresh that idea really quick.</p>

<p>Put the ratings in a matrix, with one row per user and one column per movie:</p>

<table>
  <thead>
    <tr>
      <th>User</th>
      <th><em>Alien</em></th>
      <th><em>Aliens</em></th>
      <th><em>Notting Hill</em></th>
      <th><em>Love Actually</em></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Asha</td>
      <td>5</td>
      <td>4</td>
      <td>0</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Ben</td>
      <td>4</td>
      <td>5</td>
      <td>1</td>
      <td>0</td>
    </tr>
    <tr>
      <td>Chen</td>
      <td>0</td>
      <td>1</td>
      <td>5</td>
      <td>4</td>
    </tr>
    <tr>
      <td>Dana</td>
      <td>4</td>
      <td>4</td>
      <td>4</td>
      <td>5</td>
    </tr>
  </tbody>
</table>

<p>The columns could be independent, but in the real world, they are not: people who like <em>Alien</em> also like <em>Aliens</em>. The recommender writes the matrix as the product of two decomposed matrices:</p>

<ul>
  <li><strong>A movie-by-factor matrix.</strong> Each factor is a column pattern. One factor loads on <em>Alien</em> and <em>Aliens</em>, and another factor loads on the two romantic comedies. We call the first “science fiction” and the second “romance”, but the fit only gives the numbers. The names are ours.</li>
  <li><strong>A user-by-factor matrix.</strong> Each row gives one user’s taste as a mix of the factors. Asha and Ben are mostly science fiction, Chen is mostly romance, and Dana likes both.</li>
</ul>

<p>The product of the two matrices also fills the cells that a user did not rate. That fill is the recommendation.</p>

<p>Now replace users with paragraphs, and movies with fields. A “rating” is 1 when the paragraph reads or writes the field. The factors are then column patterns of fields that the same paragraphs use: candidate entities. The other matrix gives, for each paragraph, its mix of entities. Dana is the paragraph that shows an account and its customer together.</p>

<p>The rough correspondence is shown below.</p>

<table>
  <thead>
    <tr>
      <th>Movie Domain</th>
      <th>CardDemo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>user</td>
      <td>paragraph</td>
    </tr>
    <tr>
      <td>movie</td>
      <td>field</td>
    </tr>
    <tr>
      <td>rating</td>
      <td>the paragraph touches the field</td>
    </tr>
    <tr>
      <td>genre (factor)</td>
      <td>candidate entity</td>
    </tr>
    <tr>
      <td>a user’s taste</td>
      <td>the entities a paragraph uses</td>
    </tr>
    <tr>
      <td>recommending an unseen movie</td>
      <td>predicting a field a paragraph does not touch</td>
    </tr>
  </tbody>
</table>

<p>One difference here is that the factorisations from the movie recommender matrix allowed negative numbers. The variant this experiment does not, because either a paragraph either uses a field, or it does not; there is no “negative use” of a field in a paragraph.</p>

<p>Thus, three properties of the problem lead to NMF:</p>

<ul>
  <li><strong>A paragraph uses several entities at once.</strong> A paragraph that shows an account also shows its customer. A clustering that puts each paragraph in one group cannot express that. NMF writes each paragraph’s row as a sum of several factors.</li>
  <li><strong>The data is counts, not signs.</strong> A paragraph either touches a field or it does not. There is no “negative use”. NMF keeps every loading at zero or more, so a factor is always something that is present.</li>
  <li><strong>We want both halves.</strong> One fit gives what each factor is made of, and where each factor is used. Both are needed: the first is the entity, and the second is its owners.</li>
</ul>

<h2 id="what-nmf-does">What NMF does</h2>

<p>Take a matrix <code class="language-plaintext highlighter-rouge">X</code> with one row per paragraph and one column per field. An entry is 1 when the paragraph reads or writes the field, and 0 otherwise.</p>

<p>NMF approximates <code class="language-plaintext highlighter-rouge">X</code> as the product of two smaller matrices, <code class="language-plaintext highlighter-rouge">W × H</code>:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">H</code> has one row per <strong>factor</strong>. A row gives each field a loading: how much the field belongs to the factor. This is what the aggregate is made of.</li>
  <li><code class="language-plaintext highlighter-rouge">W</code> has one column per factor. A column gives each paragraph a loading: how much the paragraph uses the factor. This is where the aggregate is used.</li>
</ul>

<p>You choose the number of factors, <code class="language-plaintext highlighter-rouge">k</code>. Every entry of <code class="language-plaintext highlighter-rouge">W</code> and <code class="language-plaintext highlighter-rouge">H</code> must be zero or more. The fit finds the <code class="language-plaintext highlighter-rouge">W</code> and <code class="language-plaintext highlighter-rouge">H</code> that make <code class="language-plaintext highlighter-rouge">W × H</code> as close to <code class="language-plaintext highlighter-rouge">X</code> as it can, in squared error. RedDragonForge uses scikit-learn’s <code class="language-plaintext highlighter-rouge">NMF</code> with the <code class="language-plaintext highlighter-rouge">nndsvda</code> start.</p>

<p>Mathematically:</p>

\[X_{n \times m} \approx W_{n \times k} \times H_{k \times m}\]

<h2 id="a-small-example">A small example</h2>

<p>Here are four paragraphs and five fields:</p>

<table>
  <thead>
    <tr>
      <th>Paragraph</th>
      <th><code class="language-plaintext highlighter-rouge">ACCT-ID</code></th>
      <th><code class="language-plaintext highlighter-rouge">ACCT-BAL</code></th>
      <th><code class="language-plaintext highlighter-rouge">CUST-ID</code></th>
      <th><code class="language-plaintext highlighter-rouge">CUST-NAME</code></th>
      <th><code class="language-plaintext highlighter-rouge">WS-MSG</code></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">READ-ACCOUNT</code></td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">UPDATE-BALANCE</code></td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">READ-CUSTOMER</code></td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SHOW-ACCOUNT</code></td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
    </tr>
  </tbody>
</table>

<p>With <code class="language-plaintext highlighter-rouge">k = 2</code>, scikit-learn gives this <code class="language-plaintext highlighter-rouge">H</code>:</p>

<table>
  <thead>
    <tr>
      <th>Factor</th>
      <th><code class="language-plaintext highlighter-rouge">ACCT-ID</code></th>
      <th><code class="language-plaintext highlighter-rouge">ACCT-BAL</code></th>
      <th><code class="language-plaintext highlighter-rouge">CUST-ID</code></th>
      <th><code class="language-plaintext highlighter-rouge">CUST-NAME</code></th>
      <th><code class="language-plaintext highlighter-rouge">WS-MSG</code></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>1.50</td>
      <td>1.50</td>
      <td>0</td>
      <td>0</td>
      <td>0.58</td>
    </tr>
    <tr>
      <td>1</td>
      <td>0.09</td>
      <td>0.09</td>
      <td>1.30</td>
      <td>1.30</td>
      <td>0</td>
    </tr>
  </tbody>
</table>

<p>And this <code class="language-plaintext highlighter-rouge">W</code>:</p>

<table>
  <thead>
    <tr>
      <th>Paragraph</th>
      <th>Factor 0</th>
      <th>Factor 1</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">READ-ACCOUNT</code></td>
      <td>0.62</td>
      <td>0</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">UPDATE-BALANCE</code></td>
      <td>0.74</td>
      <td>0</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">READ-CUSTOMER</code></td>
      <td>0</td>
      <td>0.76</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SHOW-ACCOUNT</code></td>
      <td>0.58</td>
      <td>0.77</td>
    </tr>
  </tbody>
</table>

<p>Factor 0 is the account and factor 1 is the customer. <code class="language-plaintext highlighter-rouge">SHOW-ACCOUNT</code> uses both, so it loads on both. <code class="language-plaintext highlighter-rouge">WS-MSG</code> appears in only one paragraph, so factor 0 takes part of it. The fit is not exact: the product puts 0.36 where <code class="language-plaintext highlighter-rouge">READ-ACCOUNT</code> has a 0 for <code class="language-plaintext highlighter-rouge">WS-MSG</code>. With real data, the fit is never exact.</p>

<h2 id="bytes-and-names">Bytes and Names</h2>

<p>The matrix is only as good as its answer to “does this paragraph touch this field?”, and to “are these two columns the same datum?”. In COBOL, names answer neither question well. Bytes answer both. The matrix stands on RedDragonForge’s byte-level dataflow.</p>

<p>The reverse engineering pyramid this stands upon is, roughly:</p>

<p><img src="/assets/images/nmf-reverse-engineering-pyramid.png" alt="The reverse engineering pyramid, bottom to top: corpus, syntax, control flow, data flow, dynamic analysis, query and deduction, classical ML, Gen AI, and on top the agent harness, specs and reports. A Gen AI column reaches down to control flow" width="800" /></p>

<h3 id="why-names-fail-in-cobol">Why names fail in COBOL</h3>

<p>COBOL storage is a sequence of bytes, and a field name is a label on a range of those bytes. Several features of the language put more than one label on the same bytes, or move bytes with no regard to labels.</p>

<p>A small program shows the idea. <code class="language-plaintext highlighter-rouge">REC</code> is eight bytes. <code class="language-plaintext highlighter-rouge">WS-A</code> is its first four and <code class="language-plaintext highlighter-rouge">WS-B</code> its last four. <code class="language-plaintext highlighter-rouge">WHOLE</code> redefines all eight:</p>

<div class="language-cobol highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">/</span><span class="m">0</span><span class="w">  </span><span class="k">MOVE</span><span class="w"> </span><span class="s1">'</span><span class="s">AAAABBBB</span><span class="s1">'</span><span class="w"> </span><span class="k">TO</span><span class="w"> </span><span class="n">REC</span><span class="p">.</span><span class="w">
</span><span class="o">/</span><span class="m">1</span><span class="w">  </span><span class="k">MOVE</span><span class="w"> </span><span class="s1">'</span><span class="s">XXXX</span><span class="s1">'</span><span class="w"> </span><span class="k">TO</span><span class="w"> </span><span class="n">WS-A</span><span class="p">.</span><span class="w">
</span></code></pre></div></div>

<p><img src="/assets/images/nmf-byte-extents-layout.png" alt="Eight bytes with four names over them: REC and WHOLE cover all eight, WS-A the first four, WS-B the last four. Bytes 0 to 3 hold X from statement 1, bytes 4 to 7 hold B from statement 0" width="640" /></p>

<p><em>The four rows of names are labels on the same eight bytes. Each cell shows its final character and the statement that last wrote it. Statement 0 wrote <code class="language-plaintext highlighter-rouge">WS-B</code> without naming it. Neither statement names <code class="language-plaintext highlighter-rouge">WHOLE</code>, but both wrote its bytes. From the <a href="/explainers/byte-extents.html">byte extents explainer</a>.</em></p>

<p>The features that cause this:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">REDEFINES</code>.</strong> Two fields with different names, and often different pictures, share the same bytes. A write to one is a write to the other.</li>
  <li><strong>Group moves.</strong> A move such as <code class="language-plaintext highlighter-rouge">MOVE ACCOUNT-RECORD TO WS-ACCOUNT</code> copies every byte of the record. No elementary field is named, but every one of them moves.</li>
  <li><strong>Undivided buffers.</strong> A record read into a <code class="language-plaintext highlighter-rouge">PIC X(500)</code> area, then moved into a structured record, loses its field names on the way through.</li>
  <li>
    <p><strong>Reference modification.</strong> A statement can move a part of a field by position. Card update fills its “old” expiry year like this:</p>

    <div class="language-cobol highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">MOVE</span><span class="w"> </span><span class="n">CARD-EXPIRAION-DATE</span><span class="p">(</span><span class="m">1</span><span class="p">:</span><span class="m">4</span><span class="p">)</span><span class="w">    </span><span class="k">TO</span><span class="w"> </span><span class="n">CCUP-OLD-EXPYEAR</span><span class="w">
</span></code></pre></div>    </div>

    <p>The names say nothing about each other. The bytes say that <code class="language-plaintext highlighter-rouge">CCUP-OLD-EXPYEAR</code> holds bytes 1 to 4 of the expiry date.</p>
  </li>
  <li><strong>Commareas and files.</strong> Programs pass data to each other as a block of bytes. Thirteen CardDemo programs take in their commarea with <code class="language-plaintext highlighter-rouge">MOVE DFHCOMMAREA(1:EIBCALEN) TO CARDDEMO-COMMAREA</code>. The receiving program lays its own names over those bytes. A file record works the same way: each program that reads the file has its own layout, with its own names, over the same record.</li>
</ul>

<p>So the same datum has many names, and one name can mean different data in different programs. An analysis that follows names joins things that are different, and splits things that are the same.</p>

<h3 id="what-the-bytes-give-the-matrix">What the bytes give the matrix</h3>

<p>Two steps use the byte-level dataflow before NMF runs:</p>

<ol>
  <li>
    <p><strong>Touches are byte ranges.</strong> For each write, the fixpoint records the bytes it lands on, and the paragraphs where it happens. A touch is then every elementary field whose bytes overlap that range. A group move touches every field inside the group. A write through a <code class="language-plaintext highlighter-rouge">REDEFINES</code> touches the fields that share its bytes. In the small program above, a read of <code class="language-plaintext highlighter-rouge">WHOLE</code> overlaps all eight bytes, so it depends on both statements:</p>

    <p><img src="/assets/images/nmf-byte-extents-read-whole.png" alt="The same eight bytes, all outlined as the bytes a read of WHOLE covers: bytes 0 to 3 last written by statement 1, bytes 4 to 7 by statement 0" width="640" /></p>

    <p><em>The outlined cells are the bytes the read covers. Their writers are statements 0 and 1. A match by name finds no writer at all.</em></p>
  </li>
  <li>
    <p><strong>Copies become one column.</strong> If an exact chain of moves carries a field’s bytes, unchanged, into another field, the two fields are one <em>class</em>. The chain can cross programs, through commareas and files. Each class is one column. CardDemo has 108 classes. The largest is <code class="language-plaintext highlighter-rouge">XREF-CARD-NUM</code>, the card number in the card cross-reference record, which is one class across 10 programs. The <a href="/explainers/field-graph.html">field graph explainer</a> shows how byte moves become edges between fields, and the <a href="/explainers/exact-classes.html">exact field classes explainer</a> shows the test that joins two fields into one class.</p>
  </li>
</ol>

<p>Without step 2, each of the seven programs that hold the account record would have its own account columns. Nothing in the matrix would join them. Each factor could then only group one program’s fields. I did not run that comparison. With step 2, the fit found one account factor with strong users in six programs. Every cross-program factor below rests on such classes.</p>

<p>The byte-level dataflow of this run, drawn as RedDragonForge’s program map:</p>

<p><img src="/assets/images/nmf-carddemo-program-map.png" alt="CardDemo program map: programs and dataset records joined by byte-level dataflow edges" width="640" /></p>

<p><em>Dark dots are programs, sized by their number of graph nodes. Blue dots are dataset records. An edge means the byte-level graph has edges between the two, and it is thicker for more edges. The map has 38 programs, 38 datasets and 110 links. The dense cluster on the right holds the online card, account and transaction screens, and the sign-on and menus. It also holds the batch programs that share their files, such as the card and cross-reference files. The programs on the left have few links to the rest, and most of them are batch.</em></p>

<p>Inside one program, the graph is fields joined by byte moves. This is card update, <code class="language-plaintext highlighter-rouge">COCRDUPC</code>:</p>

<p><img src="/assets/images/nmf-carddemo-cocrdupc-dataflow.png" alt="Card update's field-level dataflow graph: fields as dots, byte moves as edges, with cross-program edges to two neighbouring programs" width="640" /></p>

<p><em>Each dot is a field, and each edge is a byte move from one field to another. Grey edges join fields within card update. Pale orange edges cross to another program. The two groups at the top and on the right are fields of the card list (<code class="language-plaintext highlighter-rouge">COCRDLIC</code>) and the menu (<code class="language-plaintext highlighter-rouge">COMEN01C</code>). Both exchange the commarea with card update. Red edges come from statements that the partition’s fan-out barrier blocks. Such a statement links one field to more than 8 others, as when a program saves a commarea whole. Blue dots are dataset slots. The page reports 45 components and 227 isolated fields. The largest component has 130 fields, from the commareas: <code class="language-plaintext highlighter-rouge">DFHCOMMAREA</code>, <code class="language-plaintext highlighter-rouge">WS-THIS-PROGCOMMAREA</code> and <code class="language-plaintext highlighter-rouge">CARDDEMO-COMMAREA</code>.</em></p>

<p>Zoomed in, the edges are byte moves between named fields. Here is the card’s expiry date, from the card file to the screen:</p>

<p><img src="/assets/images/nmf-carddemo-cocrdupc-expiry-chain.png" alt="Zoomed dataflow: card file bytes 80 to 90 flow into CARD-EXPIRAION-DATE, which splits into CCUP-OLD-EXPYEAR, CCUP-OLD-EXPMON and CCUP-OLD-EXPDAY, each of which flows to a screen field, a working-storage field and WS-COMMAREA" width="640" /></p>

<p><em>The read of the card file puts bytes 80 to 90 of the record into <code class="language-plaintext highlighter-rouge">CARD-EXPIRAION-DATE</code>. Card update then splits the date by position: bytes 0 to 3 go to <code class="language-plaintext highlighter-rouge">CCUP-OLD-EXPYEAR</code>, 5 and 6 to <code class="language-plaintext highlighter-rouge">CCUP-OLD-EXPMON</code>, and 8 and 9 to <code class="language-plaintext highlighter-rouge">CCUP-OLD-EXPDAY</code>. Each part then goes to a screen output field (<code class="language-plaintext highlighter-rouge">EXPYEARO</code> and so on), to a working-storage field, and into the saved commarea <code class="language-plaintext highlighter-rouge">WS-COMMAREA</code>. No name links <code class="language-plaintext highlighter-rouge">CARD-EXPIRAION-DATE</code> to <code class="language-plaintext highlighter-rouge">CCUP-OLD-EXPYEAR</code>. The bytes do. I picked these twelve nodes and dragged them into columns. The page has other neighbours of these fields, such as literal moves and the incoming commarea bytes, which I left out.</em></p>

<p>The above byte level dataflows require running a set of COBOL-specific static analyses. Some of these are:</p>

<ul>
  <li>Byte extent extraction from copybooks</li>
  <li>Interprocedural fixpoint analysis of dataflow</li>
</ul>

<p>These analysis tools are present in <a href="https://github.com/avishek-sen-gupta/red-dragon-forge">RedDragonForge</a>.</p>

<h2 id="the-carddemo-matrix">The CardDemo matrix</h2>

<p>The statistics for the CardDemo imply that we factor a matrix of size \(454 \times 1885\).</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>CardDemo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>programs</td>
      <td>38</td>
    </tr>
    <tr>
      <td>paragraphs (rows)</td>
      <td>454</td>
    </tr>
    <tr>
      <td>fields (columns)</td>
      <td>1,885</td>
    </tr>
    <tr>
      <td>entries that are 1</td>
      <td>4,661</td>
    </tr>
    <tr>
      <td>classes</td>
      <td>108</td>
    </tr>
  </tbody>
</table>

<p>Most fields are rare. 927 fields appear in only one paragraph, and only 429 appear in four or more.</p>

<h2 id="rounds">Rounds</h2>

<p>A factor needs evidence. A field that only one paragraph touches cannot show which other fields go with it. So the fit runs in rounds:</p>

<ol>
  <li><strong>Round 1</strong> keeps the fields that appear in at least four paragraphs. That is 429 columns. It fits <code class="language-plaintext highlighter-rouge">k = 30</code>.</li>
  <li><strong>Round 2</strong> keeps the fields that appear in at least two paragraphs. That is 958 columns. It fits <code class="language-plaintext highlighter-rouge">k = 10</code> to what round 1 did not explain. Round 1’s factors already explained 54% of round 2’s matrix.</li>
</ol>

<p>Each fit took under a second. Round 1 ran 51 iterations and round 2 ran 16.
Each extracted group was then passed to an LLM for naming an appropriate domain object. The sections which follow describe the groupings and the names that were assigned to those groups.</p>

<h2 id="round-1-findings">Round 1 findings</h2>

<p>A factor’s <code class="language-plaintext highlighter-rouge">W</code> column says which paragraphs use it. Nine of round 1’s 30 factors have strong users, with a loading above 0.1, in more than one program. Seven of the nine are entities, and two are the session. Four more factors are records seen through one program. The rest are noise. This section reads each interesting factor in turn.</p>

<h3 id="account">Account</h3>

<p><strong>Factor 4. Strong users in six programs:</strong> <code class="language-plaintext highlighter-rouge">CBACT01C</code>, <code class="language-plaintext highlighter-rouge">CBACT04C</code>, <code class="language-plaintext highlighter-rouge">CBEXPORT</code>, <code class="language-plaintext highlighter-rouge">CBTRN02C</code>, <code class="language-plaintext highlighter-rouge">COACTUPC</code>, <code class="language-plaintext highlighter-rouge">COACTVWC</code>.</p>

<p>Its top fields are all <code class="language-plaintext highlighter-rouge">ACCOUNT-RECORD</code> fields, with loadings from 0.87 to 1.25:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">ACCT-CASH-CREDIT-LIMIT</code>, <code class="language-plaintext highlighter-rouge">ACCT-CREDIT-LIMIT</code>, <code class="language-plaintext highlighter-rouge">ACCT-ACTIVE-STATUS</code></li>
  <li><code class="language-plaintext highlighter-rouge">ACCT-GROUP-ID</code>, <code class="language-plaintext highlighter-rouge">ACCT-REISSUE-DATE</code>, <code class="language-plaintext highlighter-rouge">ACCT-OPEN-DATE</code></li>
  <li><code class="language-plaintext highlighter-rouge">ACCT-ID</code>, <code class="language-plaintext highlighter-rouge">ACCT-CURR-CYC-CREDIT</code>, <code class="language-plaintext highlighter-rouge">ACCT-CURR-CYC-DEBIT</code></li>
</ul>

<p>Its top paragraphs:</p>

<table>
  <thead>
    <tr>
      <th>Program</th>
      <th>Paragraph</th>
      <th>Loading</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CBACT04C</code></td>
      <td><code class="language-plaintext highlighter-rouge">1050-UPDATE-ACCOUNT</code></td>
      <td>0.91</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CBTRN02C</code></td>
      <td><code class="language-plaintext highlighter-rouge">2800-UPDATE-ACCOUNT-REC</code></td>
      <td>0.91</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CBTRN02C</code></td>
      <td><code class="language-plaintext highlighter-rouge">1500-B-LOOKUP-ACCT</code></td>
      <td>0.90</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CBEXPORT</code></td>
      <td><code class="language-plaintext highlighter-rouge">3100-READ-ACCOUNT-RECORD</code></td>
      <td>0.88</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">COACTUPC</code></td>
      <td><code class="language-plaintext highlighter-rouge">9300-GETACCTDATA-BYACCT</code></td>
      <td>0.83</td>
    </tr>
  </tbody>
</table>

<p><strong>Reading:</strong> the account is the entity that both sides of the system change. The interest calculation (<code class="language-plaintext highlighter-rouge">CBACT04C</code>) and the transaction posting (<code class="language-plaintext highlighter-rouge">CBTRN02C</code>) update it in batch. The account update screen (<code class="language-plaintext highlighter-rouge">COACTUPC</code>) changes it online. That makes the account the first place where a modernised system needs one clear owner. No name told the fit that these fields are one record. The columns are classes, and the paragraphs that use them are the only evidence.</p>

<h3 id="card-cross-reference">Card cross-reference</h3>

<p><strong>Factor 24. Strong users in six programs:</strong> bill pay, transaction add, account view, account update, the interest calculation and the export.</p>

<p>Its strongest field is <code class="language-plaintext highlighter-rouge">XREF-CARD-NUM</code>, at 1.81, with <code class="language-plaintext highlighter-rouge">XREF-ACCT-ID</code> and <code class="language-plaintext highlighter-rouge">XREF-CUST-ID</code>. Its paragraphs are lookups:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">READ-CXACAIX-FILE</code> in bill pay and in transaction add</li>
  <li><code class="language-plaintext highlighter-rouge">9200-GETCARDXREF-BYACCT</code> in account view and account update</li>
  <li><code class="language-plaintext highlighter-rouge">1110-GET-XREF-DATA</code> in the interest calculation</li>
</ul>

<p><strong>Reading:</strong> this is not an entity of its own. It is the relationship between card, account and customer. Every operation that starts from one of them uses it to find the others. A modernised system would make it a relationship in the data model, not a service. The factor also pulls in the screen messages of bill pay and transaction add. Those paragraphs report a failed lookup on the screen.</p>

<h3 id="transaction">Transaction</h3>

<p><strong>Factor 7. Strong users in five programs:</strong> transaction list (<code class="language-plaintext highlighter-rouge">COTRN00C</code>), transaction view (<code class="language-plaintext highlighter-rouge">COTRN01C</code>), transaction add (<code class="language-plaintext highlighter-rouge">COTRN02C</code>), bill pay and the export.</p>

<p>Its top fields are the whole <code class="language-plaintext highlighter-rouge">TRAN-RECORD</code>: amount, timestamps, description, card number, type, category, source and the merchant fields.</p>

<p><strong>Reading:</strong> this is the transaction as the online user sees it. The view program reads it, and the list program pages through it. The add program reads the last transaction for two reasons. It numbers the new transaction as the last id plus one. It also has a “copy last transaction” action, <code class="language-plaintext highlighter-rouge">COPY-LAST-TRAN-DATA</code>, which fills the screen from the last transaction.</p>

<h3 id="card">Card</h3>

<p><strong>Factor 15. Strong users in four programs:</strong> card view (<code class="language-plaintext highlighter-rouge">COCRDSLC</code>), card update (<code class="language-plaintext highlighter-rouge">COCRDUPC</code>), card list (<code class="language-plaintext highlighter-rouge">COCRDLIC</code>) and the export.</p>

<p>Its top fields are the <code class="language-plaintext highlighter-rouge">CARD-RECORD</code> fields: active status, expiry date, CVV, embossed name, card number and account id.</p>

<p><strong>Reading:</strong> the card belongs to the three card screens. Card update reads it, checks it for changes (<code class="language-plaintext highlighter-rouge">9300-CHECK-CHANGE-IN-REC</code>) and writes it (<code class="language-plaintext highlighter-rouge">9200-WRITE-PROCESSING</code>). Card view and card list only read it. No batch program changes it in this factor.</p>

<h3 id="customer">Customer</h3>

<p><strong>Factor 5. Strong users in three programs:</strong> account view, account update and the export.</p>

<p>Its ten top fields all have the same loading, 0.747: id, names, SSN, phone numbers, government id, FICO score and the primary-cardholder flag. The same six paragraphs use all of them. Below those six, the next paragraph loads at 0.008.</p>

<p><strong>Reading:</strong> the customer is seen through the account. The paragraphs that use it are <code class="language-plaintext highlighter-rouge">9400-GETCUSTDATA-BYCUST</code> in account view and account update, and the export’s read. No screen in this factor works on a customer alone. So in this run, the customer looks like part of the account’s aggregate, not an aggregate of its own.</p>

<h3 id="user">User</h3>

<p><strong>Factor 17. Strong users in five programs:</strong> sign-on (<code class="language-plaintext highlighter-rouge">COSGN00C</code>) and the four user-administration programs, <code class="language-plaintext highlighter-rouge">COUSR00C</code> to <code class="language-plaintext highlighter-rouge">COUSR03C</code>.</p>

<p>Its top fields are the <code class="language-plaintext highlighter-rouge">SEC-USER-DATA</code> fields: user id, user type, first name and last name. Its paragraphs are the full set of operations on a user: list (<code class="language-plaintext highlighter-rouge">READNEXT-USER-SEC-FILE</code>), add (<code class="language-plaintext highlighter-rouge">WRITE-USER-SEC-FILE</code>), update (<code class="language-plaintext highlighter-rouge">UPDATE-USER-SEC-FILE</code>), delete (<code class="language-plaintext highlighter-rouge">DELETE-USER-SEC-FILE</code>), and the sign-on read.</p>

<p><strong>Reading:</strong> the user is a separate area of the system. It shares no factor with the card business. It is the cleanest candidate for a separate service.</p>

<h3 id="transaction-category-balance">Transaction-category balance</h3>

<p><strong>Factor 22. Strong users in two batch programs:</strong> the transaction posting (<code class="language-plaintext highlighter-rouge">CBTRN02C</code>) and the interest calculation (<code class="language-plaintext highlighter-rouge">CBACT04C</code>).</p>

<p>Its top fields are the category-balance record’s key and balance (<code class="language-plaintext highlighter-rouge">FD-TRANCAT-ACCT-ID</code>, <code class="language-plaintext highlighter-rouge">FD-TRANCAT-TYPE-CD</code>, <code class="language-plaintext highlighter-rouge">FD-TRANCAT-CD</code>, <code class="language-plaintext highlighter-rouge">TRAN-CAT-BAL</code>), with the daily transaction’s type, category and amount.</p>

<p><strong>Reading:</strong> this is a running balance per account, per transaction type and per category. The posting program creates and updates it (<code class="language-plaintext highlighter-rouge">2700-A-CREATE-TCATBAL-REC</code>, <code class="language-plaintext highlighter-rouge">2700-B-UPDATE-TCATBAL-REC</code>) from each daily transaction. The interest calculation reads it (<code class="language-plaintext highlighter-rouge">1000-TCATBALF-GET-NEXT</code>) and computes interest from it. So it is the hand-off between two batch jobs, and their run order matters.</p>

<h3 id="session-split-in-two">Session, split in two</h3>

<p><strong>Factors 20 and 18</strong> are both the shared <code class="language-plaintext highlighter-rouge">CARDDEMO-COMMAREA</code>. It holds the user’s id and type, the customer’s id and names, the account’s id and status, and the card number. It also holds the from-program and to-program fields for navigation.</p>

<ul>
  <li><strong>Factor 20</strong> is used by card list, card view and card update.</li>
  <li><strong>Factor 18</strong> is used by the two Db2 transaction-type programs, <code class="language-plaintext highlighter-rouge">COTRTLIC</code> and <code class="language-plaintext highlighter-rouge">COTRTUPC</code>.</li>
</ul>

<p>Their paragraphs are <code class="language-plaintext highlighter-rouge">0000-MAIN</code> and <code class="language-plaintext highlighter-rouge">COMMON-RETURN</code>: where each program takes the commarea in, and where it hands the commarea on.</p>

<p><strong>Reading:</strong> this is not a domain entity. It is the session. The useful part is the split. The same record became two factors, one for each family of programs that pass it among themselves. The factorisation found two user-facing flows without being told about navigation.</p>

<h3 id="records-inside-one-program">Records inside one program</h3>

<p>Four factors are records, but only one program uses them strongly:</p>

<ul>
  <li><strong>Factor 3: card update’s before-image.</strong> The <code class="language-plaintext highlighter-rouge">CCUP-OLD-*</code> fields hold the card as the screen showed it. Before it writes, <code class="language-plaintext highlighter-rouge">9300-CHECK-CHANGE-IN-REC</code> compares the card it reads again for update with these fields. If they differ, the program does not write. It refreshes the old values and reports that the data changed. This is an optimistic lock: it stops an update from overwriting a change that someone else made in the meantime.</li>
  <li><strong>Factor 8: card list’s paging state.</strong> The first and last card number on the page, the screen number and the next-page flag. The program keeps them in its commarea between tasks so that it can page forward and back.</li>
  <li><strong>Factor 27: the statement’s transactions.</strong> The statement program, <code class="language-plaintext highlighter-rouge">CBSTM03A</code>, reads transactions and writes them into the statement.</li>
  <li><strong>Factor 28: the daily transaction and its rejects.</strong> The posting program reads each daily transaction, looks up the card and account, and writes a reject with a reason (<code class="language-plaintext highlighter-rouge">2500-WRITE-REJECT-REC</code>) when validation fails.</li>
</ul>

<p>These are business mechanisms, not entities: a lock, a paging cursor, a report, a validation step. However, they do show up in the matrix factorisation, implying that these are useful groupings, even if they are not business domain objects themselves</p>

<h3 id="what-is-left-hubs">What is left: hubs</h3>

<p>The other 17 factors are <em>hubs</em>: one program’s own working storage, used by a few of that program’s paragraphs. Examples:</p>

<ul>
  <li><strong>Factor 2</strong> is a run of <code class="language-plaintext highlighter-rouge">FILLER</code> fields in account update’s commarea, <code class="language-plaintext highlighter-rouge">FILLER_200</code> to <code class="language-plaintext highlighter-rouge">FILLER_207</code>.</li>
  <li><strong>Factor 9</strong> is account update’s date-edit variables.</li>
  <li><strong>Factor 12</strong> is the SQL communication area and messages of one Db2 program, <code class="language-plaintext highlighter-rouge">COTRTLIC</code>.</li>
  <li><strong>Factor 21</strong> is the file-status fields of the account file reader, <code class="language-plaintext highlighter-rouge">CBACT01C</code>.</li>
</ul>

<p>A hub is compact and stable. It is a real pattern in the data, but is not a domain concept.</p>

<h2 id="round-2-findings">Round 2 findings</h2>

<p>Round 2 found less. All ten of its factors have strong users in one program only. Some of them are screens:</p>

<ul>
  <li>Factor 0 is the transaction list screen’s rows, <code class="language-plaintext highlighter-rouge">TRNID01I</code> to <code class="language-plaintext highlighter-rouge">TRNID10I</code>.</li>
  <li>Factor 1 is the user list screen’s rows.</li>
</ul>

<p>Others are records seen in fewer paragraphs, such as the export record in <code class="language-plaintext highlighter-rouge">CBIMPORT</code> and the customer record in the statement program, <code class="language-plaintext highlighter-rouge">CBSTM03A</code>. Others are again hubs: response codes and <code class="language-plaintext highlighter-rouge">FILLER</code>s in account view and account update.</p>

<h2 id="the-scores">The scores</h2>

<p>The analysis scorecard measures each round from several sides.</p>

<table>
  <thead>
    <tr>
      <th>Score</th>
      <th>Round 1</th>
      <th>Round 2</th>
      <th>What it measures</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>held-out AUC</td>
      <td><strong>0.851</strong></td>
      <td>0.533</td>
      <td>how well the factors predict hidden 1s</td>
    </tr>
    <tr>
      <td>relative error</td>
      <td>0.421</td>
      <td>0.840</td>
      <td>fit error divided by the matrix’s size</td>
    </tr>
    <tr>
      <td>coverage</td>
      <td>77.6%</td>
      <td>17.7%</td>
      <td>1s inside some factor’s top fields and top paragraphs</td>
    </tr>
    <tr>
      <td>stability</td>
      <td>0.963</td>
      <td>0.910</td>
      <td>how closely refits on 90% of the rows match</td>
    </tr>
    <tr>
      <td>distinctness</td>
      <td>0.654</td>
      <td>0.032</td>
      <td>the largest similarity between two factors</td>
    </tr>
    <tr>
      <td>reach</td>
      <td>76.7%</td>
      <td>30.0%</td>
      <td>factors whose top fields span programs</td>
    </tr>
    <tr>
      <td>median programs</td>
      <td>5</td>
      <td>1</td>
      <td>programs a factor’s top fields span</td>
    </tr>
    <tr>
      <td>class share</td>
      <td>23.8%</td>
      <td>16.2%</td>
      <td>the round’s 1s that fall in class columns</td>
    </tr>
  </tbody>
</table>

<p>Some of these need a word:</p>

<ul>
  <li><strong>Held-out AUC.</strong> The scorecard hides 10% of the 1s, fits on the rest, and asks how often a hidden 1 scores higher than an empty cell. The empty cells come from the same paragraph’s own program. An empty cell from another program would be an easy call, because the matrix is nearly one block per program. 0.5 is chance.</li>
  <li><strong>Distinctness.</strong> Lower is better here. Round 1’s two most similar factors have a similarity of 0.654. Round 2’s 0.032 is low because its factors share almost nothing, but they also predict almost nothing.</li>
  <li><strong>Reach.</strong> 23 of round 1’s 30 factors have top fields in more than one program. This counts the programs of each field’s class, not the programs that use the factor. So it is higher than the nine factors with strong users in several programs. A hub’s fields can belong to classes that span programs, while only one program’s paragraphs use the factor.</li>
</ul>

<p>Round 1 is the result. It predicts hidden uses well above chance, and it survives resampling with almost no change. Round 2 has little left to find. Its AUC is close to chance, and what round 1 leaves is a long tail of fields seen in two or three paragraphs.</p>

<p>What the scores cannot see is meaning. A hub scores well on stability and focus, because it is compact. Only a person can say that factor 4 is the account and factor 2 is padding, which is why an LLM is a suitable initial stand-in to make that judgment, before a human gets involved.</p>

<h2 id="scaling-to-a-large-corpus">Scaling to a large corpus</h2>

<p>CardDemo is small. Running the same set of techniques on a large COBOL corpus (online CICS with batch) of about 4 million LoC gives interesting results.</p>

<p>There are several things which do not work as-is when scaling up to real world corpuses. Some of these require targeted preprocessing, for example, removing fields from consideration which occur nearly everywhere; this is to prevent noise from overwhelming the matrix factorisation. The exclude list removes about 240k of ~590k fields (41%):</p>

<table>
  <thead>
    <tr>
      <th>Removed</th>
      <th>Fields</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>commareas</td>
      <td>about 116,000</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">FILLER</code>s</td>
      <td>about 57,000</td>
    </tr>
    <tr>
      <td>working-storage counters, flags, temporaries and indexes</td>
      <td>about 20,000</td>
    </tr>
    <tr>
      <td>screen maps</td>
      <td>about 11,000</td>
    </tr>
    <tr>
      <td>report and print layouts</td>
      <td>about 10,000</td>
    </tr>
    <tr>
      <td>date and time work areas</td>
      <td>about 2,500</td>
    </tr>
    <tr>
      <td>literals, constants, sort areas, CICS interface fields</td>
      <td>about 800</td>
    </tr>
  </tbody>
</table>

<p>There are other optimisations that needed to be done, for example, avoiding storing the full matrix model in memory; I may describe some of these techniques in a future post.</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>CardDemo</th>
      <th>Larger corpus</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>paragraphs × fields</td>
      <td>454 × 1,885</td>
      <td>43,067 × 349,550</td>
    </tr>
    <tr>
      <td>non-zeros</td>
      <td>4,661</td>
      <td>1,113,999</td>
    </tr>
    <tr>
      <td>density</td>
      <td>0.54%</td>
      <td>0.0074%</td>
    </tr>
    <tr>
      <td>rounds</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>min-occurrences per round</td>
      <td>4, 2</td>
      <td>10, 5, 2</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k</code> per round</td>
      <td>30, 10</td>
      <td>64, 96, 128</td>
    </tr>
    <tr>
      <td>factors</td>
      <td>40</td>
      <td>288</td>
    </tr>
  </tbody>
</table>

<p>What remains is almost all file record fields. The run also gives a nominal declaration to fields that a program uses but never declares, which is what a missing copybook looks like.</p>

<p>Not to be dismissed is the runtime for running the factorisation of a matrix of this size; <strong>all the rounds put together finished in about 10 minutes or so</strong>. Compare that with an LLM combing the entire codebase with inference, which can usually take several days on a codebase this size.</p>

<p>Each round fits what the earlier rounds leave. Round 2 is 52.6% explained by round 1. Round 3 is 38.2% explained by rounds 1 and 2.</p>

<table>
  <thead>
    <tr>
      <th>Round</th>
      <th>Factors</th>
      <th>Span programs</th>
      <th>One program</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>64</td>
      <td>24</td>
      <td>40</td>
    </tr>
    <tr>
      <td>2</td>
      <td>96</td>
      <td>73</td>
      <td>23</td>
    </tr>
    <tr>
      <td>3</td>
      <td>128</td>
      <td>98</td>
      <td>30</td>
    </tr>
    <tr>
      <td>all</td>
      <td>288</td>
      <td>195 (67.7%)</td>
      <td>93 (32.3%)</td>
    </tr>
  </tbody>
</table>

<p>An LLM interpretation of every factor against the corpus’ glossary give these estimates:</p>

<ul>
  <li>About <strong>270 of the 288</strong> factors have a <strong>clear business meaning</strong>.</li>
  <li><strong>~115 factors are duplicates</strong>. Each program’s copy of a file record gets its own columns, because the run does not join a file’s layouts across programs. So each program that reads one ten-field block of a master record gets its own factor for that block. This one block gives 108 of round 3’s 128 factors.</li>
  <li>About <strong>16 factors</strong> come from families of <strong>programs with the same logic and different field prefixes</strong>. This showcases how the matrix factorisation can surface almost or complete duplicates.</li>
  <li>After merging these, about <strong>75 to 95 distinct domain object candidates</strong> remain. These then become candidates for further inspection and judgment, by a human and/or an LLM. This part is important, because it shows that any <strong>downstream system has to work with substantially less low-level data, and has access to more organised groupings of this data</strong>.</li>
</ul>

<h2 id="conclusions-and-takeaways">Conclusions and Takeaways</h2>

<ul>
  <li><strong>The factors answer modelling questions.</strong> The model for factorisation in this case was closely tied to co-occurrence in paragraphs coupled with the byte extents instead of names. Modelling choice is important, depending upon the language and how domain-related data is expressed. In this example, bytes make the columns, and the columns matter more than the algorithm. The account factor has strong users in six programs only because the byte-level classes made one column for each account field. Each column covers the seven programs that hold the field.</li>
  <li><strong>Once you have cast the problem as matrix factorisation, the results can be blindingly fast, even on massive corpora.</strong> This does not preclude the use of LLMs; rather, think of this step as a first, fast, cheap pass of extracting candidates. In this post, I have described domain object extraction, but we can, with a little effort, think of other creative applications of this family of techniques to other reverse engineering demands.</li>
  <li><strong>The outputs are explainable.</strong> There is a very clear reason why a group has been constituted, given the metric of co-occurrence. There is also a very clear reason why different-sounding names share the same grouping, and that is because of the byte level unification.</li>
  <li><strong>Remove the noise sources before factorisation.</strong> On the bigger corpus, commareas and other fields that every paragraph uses would overwhelm the factors with nooise, this basic preprocessing by excluding very common factors is important. In this example, I used an LLM to build the exclude list.</li>
</ul>

<h2 id="references">References</h2>

<ul>
  <li><a href="https://github.com/avishek-sen-gupta/red-dragon-forge">RedDragonForge</a>: Tools for running mainframe COBOL programs</li>
  <li><a href="https://www.amazon.in/Compilers-Principles-Techniques-Updated-Pearson-ebook/dp/B0CYHDX2RG?th=1">Compilers: Principles, Techniques, and Tools</a></li>
</ul>]]></content><author><name>avishek</name></author><category term="Program Analysis" /><category term="Static Analysis" /><category term="COBOL" /><category term="Reverse Engineering" /><category term="Machine Learning" /><category term="Linear Algebra" /><summary type="html"><![CDATA[This post how to use non-negative matrix factorisation (NMF) as an extremely fast first-pass technique (when combined with byte-level dataflow analysis) to find domain object candidates when reverse engineering a legacy COBOL codebase. A domain object is a group of fields that belong to one thing, such as one account or one customer. The post does a walkthrough of the technique applied to AWS CardDemo, an open source CICS sample application, to explain the concepts. It shows the matrix statistics, the factors that the run found, and the scores that say how good they are. It then follows the same pipeline on a large corpus of about 4+ MLoC, describing the speed of factorisation at that size, and what the factorisation found.]]></summary></entry><entry><title type="html">Short Notes on Classical Machine Learning: Deriving the Logistic Regression Curve</title><link href="http://localhost:4000/2026/10/19/logistic-regression-curve-derivation.html" rel="alternate" type="text/html" title="Short Notes on Classical Machine Learning: Deriving the Logistic Regression Curve" /><published>2026-10-19T00:00:00+05:30</published><updated>2026-10-19T00:00:00+05:30</updated><id>http://localhost:4000/2026/10/19/logistic-regression-curve-derivation</id><content type="html" xml:base="http://localhost:4000/2026/10/19/logistic-regression-curve-derivation.html"><![CDATA[<p><em>In this post, I take a look at the basic idea of why the logistic regression’s familiar S-curve exists, its relation to the familiar concept of probability, and how framing probability as the logarithm of odds naturally leads to a representation amenable to linear regression.</em></p>

<p>I returned to learning some classical machine learning recently, mostly to brush up on some of the foundational math. I usually do this in order to not let my brain rot from just applying language models to any task that presents itself. One of the earliest concepts I learnt in classical ML is <strong>Logistic Regression</strong>. For the longest time, I had a very simplistic, incomplete, and frankly wrong, idea of what LR was actually doing, what it represented, and why it worked. Ironically, the most understanding I gained was from conversing with Claude, forcing it to slow down, and clarify every misunderstanding in excruciating detail until I was convinced that I understood. Of course, mere understanding is not enough, so I’d like to document it, in the hopes that future me (who will have forgotten this material all over again) will find this a valuable aid to recollection.</p>

<h2 id="expressing-probability-as-odds">Expressing probability as odds</h2>
<p>We all know probability, right? That number between 0 and 1, or if you are feeling inclined towards percentages, between 0 and 100%; we use it to express, loosely, the likelihood of something happening (ignoring the fact for now, that likelihood has a very specific meaning in the subject). However, there is another way to express the chance of something happening, and that is by expressing odds. When someone says <strong>“What are the odds of it raining?”</strong>, let’s see what different answers could mean.</p>

<ul>
  <li>I answer: <strong>“I give it even odds”</strong>, I’m saying that the probability of it raining is the same as it not raining.</li>
  <li>I answer: <strong>“I think the odds are 2 to 1 it is going to rain.”</strong>, I’m saying that the chance of it raining is double of that of it not raining.</li>
</ul>

<p>Both of these can be expressed precisely. Assuming that rain and not rain are the only two possibilities:</p>

<p>For the first answer, we can write:</p>

\[p_{rain} + p_{dry} = 1 \text{..............Probabilities sum to 1} \\
p_{rain} = p_{dry} \text{....................Odds are even}\\
\Rightarrow 2 \cdot p_{rain} = 1 \\
\Rightarrow p_{rain} = p_{dry} = 0.5\]

<p>For the second answer, we can write:</p>

\[p_{rain} + p_{dry} = 1 \\
p_{rain} = 2 \cdot p_{dry} \\
\Rightarrow 2 \cdot p_{dry} + p_{dry} = 1 \\
\Rightarrow 3 \cdot p_{dry} = 1 \\
\Rightarrow p_{dry} = 0.33 \\
\Rightarrow p_{rain} = 0.67\]

<p>Thus, odds is the ratio of successful outcomes to unsuccessful outcomes, that is:</p>

\[\text{odds(success)} = \frac {\text{successful outcomes}}{\text{unsuccessful outcomes}}\]

<p>Why is this useful? Because there is an important property of odds which the plain expression of probability does not have: <strong>odds can be any number between 0 and \(\infty\).</strong> An example will suffice. Suppose we say that the odds of it raining are some ridiculously large number, say one million to one. That means that:</p>

\[p_{rain} + p_{dry} = 1 \\
p_{rain} = 10^6 \cdot p_{dry} \\
\Rightarrow 10^6 \cdot p_{dry} + p_{dry} = 1 \\
\Rightarrow 1000001 \cdot p_{dry} = 1 \\
\Rightarrow p_{dry} = 0.000000999999 \\
\Rightarrow p_{rain} = 0.999999\]

<p>So the probability of it not raining is very very small, but never zero, even in the presence of arbitrarily large numbers.</p>

<p>This is useful because it lets us express probabilities using arbitrary positive numbers. But the story is not over yet: we’d like to express probabilities using the entire number line, and this includes negative numbers. That’s the subject of the next section.</p>

<h2 id="expressing-probability-as-log-odds">Expressing probability as log odds</h2>

<p>There is a very simple way to jump from expressing probabilities using only positive numbers (using the language of odds) to include negative numbers: simply take the logarithm of odds. Take the example of “The odds of it raining are 1 to 3”. This is saying that it is thrice as likely to not rain as it is to rain. Note that the ratio now looks like:</p>

\[\frac {p_{rain}}{p_{dry}} = \frac {1}{3} \\
odds_{rain} = \frac {1}{3}\]

<p>Now see what happens when we take log of these odds:</p>

\[\ln(odds_{rain}) = - \ln(3) = −1.099\]

<p>The practical upshot is that if we choose to use log odds to express probabilities, we can express probabilities using the complete real number line.</p>

<p>If you are familiar with <strong>Generalised Linear Models</strong>, <strong>log odds is the link function</strong>.</p>

<h2 id="the-curve-is-the-relationship-between-normal-probability-and-log-odds">The curve is the relationship between “normal” probability and log odds</h2>

<p>The fun part - and the point of this exercise - is to see what the original probability variable looks like when expressed in terms of log odds. This is a simple mathematical derivation which nevertheless reveals the S shape that we associate with the logistic regression curve.</p>

<p>Let \(t\) represent the log odds variable. Then we have:</p>

\[t = \ln \frac {p}{1 - p} \\
\Rightarrow e^t = \frac {p}{1-p} \\
\Rightarrow e^t (1 - p) = p \\
\Rightarrow p (1 + e^t) = e^t \\
\Rightarrow p = \frac {e^t}{1 + e^t}\]

<p>Then we tidy up by dividing both numerator and denominator by \(e^t\) to get:</p>

\[p = \frac {1}{1 + e^{-t}}\]

<p>That is the S-curve of logistic regression.</p>

<p><img src="/assets/images/logistic-regression-s-curve.png" alt="Logistic Regression S-curve" /></p>

<h2 id="regression-on-log-odds">Regression on log odds</h2>

<p>The reason we like the log odds representation is this: when we perform regression on the points to make the S-curve fit to them, we need a model of how the tuning parameters affect the curve. We’d like to have those tuning parameters represent a linear model, without the co-domain of the linear model being restricted to being between 0 and 1. The fitness function of the regression still measures the fit of the S-curve equation to the data.</p>]]></content><author><name>avishek</name></author><category term="Machine Learning" /><category term="Logistic Regression" /><category term="Probability" /><summary type="html"><![CDATA[In this post, I take a look at the basic idea of why the logistic regression’s familiar S-curve exists, its relation to the familiar concept of probability, and how framing probability as the logarithm of odds naturally leads to a representation amenable to linear regression.]]></summary></entry><entry><title type="html">Ancalagon: A Harness You Import</title><link href="http://localhost:4000/2026/10/04/ancalagon-a-harness-you-import.html" rel="alternate" type="text/html" title="Ancalagon: A Harness You Import" /><published>2026-10-04T00:00:00+05:30</published><updated>2026-10-04T00:00:00+05:30</updated><id>http://localhost:4000/2026/10/04/ancalagon-a-harness-you-import</id><content type="html" xml:base="http://localhost:4000/2026/10/04/ancalagon-a-harness-you-import.html"><![CDATA[<p><strong>There are many agent harnesses, but this one is mine.</strong></p>

<p>I love determinism: probabilistic results where a well-studied proven techniques can give an unambiguous answer, gives me the ick; so sue me! :-)</p>

<p>Ancalagon is an agent harness I’ve been building for reverse engineering work: given a data structure and a goal, an agent either works the structure directly with tools, or generates a deterministic traversal program — plus the typed contracts for its own analysis touch points — and runs that under supervision. This post isn’t really about what it does so much as why it’s shaped the way it is; here then are some of the principles I tried to embody in the design of this library:</p>

<ul>
  <li>The harness (with the model) is just one component in a system, not the whole system</li>
  <li>It is developer-first: contracts are not optional, and it is meant to be modified and tinkered with</li>
  <li>The library borrows OS primitives for its runtime; this includes agent lifecycle management, observability, etc.</li>
</ul>

<h2 id="what-it-actually-is">What it actually is</h2>

<p>Run it as intended and it’s a real system: <code class="language-plaintext highlighter-rouge">uv run ancalagon run --config ancalagon.toml --run-dir "$RUN_DIR"</code> starts a tree of processes. A CLI writes a task to disk, a supervisor spawns a worker subprocess per attempt, and every hand-off between them is a row in a SQLite database (<code class="language-plaintext highlighter-rouge">bus.db</code>) or a file. There’s a schema, a migration command, a fork command that replays a run’s history into a new one. This is not a thin wrapper around an API call; it’s a small distributed system, and I’m not going to pretend otherwise.</p>

<p>However, the supervisor and the database are not needed for a somewhat frequent situation: running a single agent, and getting back an answer. Underneath the CLI is a plain function call:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">ancalagon.session_for</span> <span class="kn">import</span> <span class="n">session_for</span>

<span class="n">session</span> <span class="o">=</span> <span class="nf">session_for</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">spec</span><span class="p">,</span> <span class="n">ctx</span><span class="p">,</span> <span class="n">transcript</span><span class="p">,</span> <span class="n">run_dir</span><span class="p">,</span> <span class="n">llm</span><span class="p">,</span> <span class="n">clock</span><span class="p">,</span> <span class="n">fs</span><span class="p">,</span> <span class="n">web</span><span class="p">)</span>
<span class="n">outcome</span> <span class="o">=</span> <span class="n">session</span><span class="p">.</span><span class="nf">run</span><span class="p">()</span>
</code></pre></div></div>

<p>(You can do the same thing from the CLI also by setting <code class="language-plaintext highlighter-rouge">max_depth = 1</code>)</p>

<p>That’s the whole seam. Call it directly — no subprocess, no <code class="language-plaintext highlighter-rouge">bus.db</code>, no supervisor — and you have one agent running inside your own process. The collaborators that the full system uses for coordinating multiple agents (a bus, a set of children, a letterbox, a meter) default to null objects — <code class="language-plaintext highlighter-rouge">NO_BUS</code>, <code class="language-plaintext highlighter-rouge">NO_CHILDREN</code>, <code class="language-plaintext highlighter-rouge">NO_LETTERBOX</code>, <code class="language-plaintext highlighter-rouge">UNMETERED</code> — so a role that names <code class="language-plaintext highlighter-rouge">delegate_&lt;role&gt;</code> or <code class="language-plaintext highlighter-rouge">idle</code> still gets a tool of that exact name and schema, and every call on it just refuses with a reason instead of crashing. <code class="language-plaintext highlighter-rouge">examples/embed_one_agent.py</code> is the worked version: 117 lines that build a <code class="language-plaintext highlighter-rouge">Config</code> in Python, hand one agent <code class="language-plaintext highlighter-rouge">list_dir</code> and <code class="language-plaintext highlighter-rouge">read_file</code>, and ask it which of four short notes contradicts the others, with no <code class="language-plaintext highlighter-rouge">bus.db</code> created anywhere — the script’s own last line globs for one and prints an empty list.</p>

<p>So it’s both things, deliberately: a CLI-driven system with real infrastructure when you want resumability and multiple agents coordinating, and a library call when you just want one agent inside a program you already have. A framework that owns the loop can usually only be extended through hooks it anticipated. Having the low-level call available means you’re not stuck waiting for one.</p>

<h2 id="one-process-per-attempt-and-no-process-is-required-to-resume">One process per attempt, and no process is required to resume</h2>

<p>Every attempt at a task is a real OS subprocess. <code class="language-plaintext highlighter-rouge">SubprocessSpawner</code> is, by its own header comment, “the only place in the codebase that starts an OS process” — the supervisor’s poll loop claims queued work, hands each task a <code class="language-plaintext highlighter-rouge">pid</code> through <code class="language-plaintext highlighter-rouge">Spawner.spawn(task_dir, agent_id)</code>, and records that pid against the agent in <code class="language-plaintext highlighter-rouge">bus.db</code>. There’s no actor runtime underneath this, no green threads, no pool of resident workers waiting for messages — the supervisor’s only way of checking one is still alive is <code class="language-plaintext highlighter-rouge">os.kill(pid, 0)</code>, and reaping a hung one after <code class="language-plaintext highlighter-rouge">timeout_s</code> is <code class="language-plaintext highlighter-rouge">SIGKILL</code>.</p>

<p>What the supervisor does <em>not</em> do is restart anything. A crash is recorded as <code class="language-plaintext highlighter-rouge">CRASHED</code>, a timeout as <code class="language-plaintext highlighter-rouge">TIMED_OUT</code>, and the decision about what happens next is pushed up to whichever agent delegated that task — it reads the status on its own next turn and decides to retry, escalate, or give up. There’s no restart strategy running underneath you the way there would be in a supervision tree that auto-restarts; supervision here means “notice death and report it accurately,” nothing more.</p>

<p>So what makes a task resumable isn’t the process at all — nothing survives between attempts anywhere in memory, by design. Idling makes this plain: there’s no suspend, no parked coroutine, no thread sitting on a condition variable. <code class="language-plaintext highlighter-rouge">Session.run()</code> returns an <code class="language-plaintext highlighter-rouge">Idling</code> outcome the same way it returns <code class="language-plaintext highlighter-rouge">Completed</code> or <code class="language-plaintext highlighter-rouge">Failed</code>, <code class="language-plaintext highlighter-rouge">worker.py</code> writes it to <code class="language-plaintext highlighter-rouge">outcome-&lt;agent&gt;.json</code>, and the process exits normally, exactly like it would have on any other outcome. Idling <em>is</em> the process ending. The only thing distinguishing it from a crash, mechanically, is that it chose to end and left a tidy transcript behind — the last tool call was actually answered before the process went away, rather than left hanging.</p>

<p>What makes either case resumable is <code class="language-plaintext highlighter-rouge">transcript.jsonl</code>. Starting a fresh attempt means spawning a new process that loads that file and carries on; the only wrinkle is a worker that actually crashed mid-tool-call, which can leave the transcript ending in an assistant turn with a tool call nothing ever answered, which the API rejects outright. <code class="language-plaintext highlighter-rouge">repair()</code> is the entire fix: if the last message is an unanswered tool call, it synthesizes an <code class="language-plaintext highlighter-rouge">interrupted: agent terminated before this tool returned</code> result and appends that, so the next request is well-formed. Past that one seam, a resumed attempt, an idled one picked back up, and a brand-new attempt all run the exact same code — there’s no special “recovery mode,” just a longer file to read first.</p>

<p>This is the place the actor-model comparison actually cashes out. An actor stays parked in <code class="language-plaintext highlighter-rouge">receive</code> between messages, with its stack and bindings intact in memory; nothing like that survives between an agent’s turns here — the process is gone, and what comes back isn’t it. It’s a new process that read the old one’s diary.</p>

<p>Here is what that looks like when a parent delegates to a child and idles until it’s done. No two processes ever talk to each other; every arrow lands on a file or a row in <code class="language-plaintext highlighter-rouge">bus.db</code>, and the parent that collects the answer is not the process that asked for it:</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant P1 as Parent&lt;br/&gt;(agent 1, process A)
    participant FS as Task directories
    participant DB as bus.db
    participant S as Supervisor
    participant C as Child&lt;br/&gt;(agent 2, process B)
    participant P3 as Parent&lt;br/&gt;(agent 3, process C)

    P1-&gt;&gt;FS: delegate_investigator writes tasks/child/spec.json
    P1-&gt;&gt;DB: enqueue child task
    DB--&gt;&gt;P1: "queued agent 2" (the tool returns at once)
    P1-&gt;&gt;FS: idle, then outcome-1.json (Idling) and exit
    S-&gt;&gt;DB: record agent 1 IDLING, with what it had seen
    S-&gt;&gt;DB: claim queued work
    S-&gt;&gt;C: spawn(task_dir, 2), record RUNNING and its pid
    C-&gt;&gt;FS: read spec.json, append to its transcript.jsonl
    C-&gt;&gt;FS: submit_answer writes outcome-2.json, exit
    S-&gt;&gt;FS: reap: read the outcome-2.json header
    S-&gt;&gt;DB: record agent 2 COMPLETED
    Note over S,DB: a child settled after the parent idled, so the parent has news
    S-&gt;&gt;DB: enqueue the parent's task again (agent 3)
    S-&gt;&gt;P3: spawn a new process
    P3-&gt;&gt;FS: load tasks/root/transcript.jsonl
    P3-&gt;&gt;FS: collect_task(2) reads outcome-2.json
    P3-&gt;&gt;DB: record agent 2 COLLECTED
</code></pre>

<p>Had the child crashed instead, the only difference is when the supervisor reaps it: there’s no <code class="language-plaintext highlighter-rouge">outcome-2.json</code> to read, so it records <code class="language-plaintext highlighter-rouge">CRASHED</code>, which is still news, and the parent is woken the same way to decide what to do about it.</p>

<h2 id="not-pushing-responsibility-onto-the-model">Not pushing responsibility onto the model</h2>

<p>The fashionable move in agent design is to give the model more latitude: let it choose its own tools, decide for itself when it’s done, negotiate its own constraints in prose. Ancalagon goes the other way on all three, and the reason is distrust, plainly: I don’t trust a model to reliably do anything, including check its own work. If a constraint only exists as an instruction in the system prompt, the model can ignore it, misread it, or claim it was followed when it wasn’t, and nothing in the loop would catch that.</p>

<p>A role is declared, not negotiated. Everything an agent <em>is</em> — behaviour, profile, input shape, answer shape, tools, budget — lives in TOML or in Python, decided before the agent exists:</p>

<div class="language-toml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">[</span><span class="n">roles</span><span class="k">.</span><span class="n">investigator</span><span class="k">]</span>
<span class="n">profile</span> <span class="o">=</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">module</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">"ancalagon.profiles.answering"</span><span class="p">,</span><span class="w"> </span><span class="n">name</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">"Answering"</span><span class="w"> </span><span class="p">}</span>
<span class="n">behaviour</span> <span class="o">=</span><span class="w"> </span><span class="s">"You investigate one subsystem and report what you find. Cite every file you read."</span>
<span class="n">input</span>  <span class="o">=</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">module</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">"example.contracts"</span><span class="p">,</span><span class="w"> </span><span class="n">name</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">"ComponentQuery"</span><span class="w"> </span><span class="p">}</span>
<span class="n">answer</span> <span class="o">=</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">module</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">"example.contracts"</span><span class="p">,</span><span class="w"> </span><span class="n">name</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">"Component"</span><span class="w"> </span><span class="p">}</span>
<span class="n">tools</span>  <span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="s">"read_file"</span><span class="p">,</span> <span class="s">"ripgrep"</span><span class="p">,</span> <span class="s">"find_symbol"</span><span class="p">]</span>
<span class="n">budget</span> <span class="o">=</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">turns</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">14</span><span class="p">,</span><span class="w"> </span><span class="n">tool_calls</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">35</span><span class="w"> </span><span class="p">}</span>
</code></pre></div></div>

<p>The answer itself is enforced the same way. <code class="language-plaintext highlighter-rouge">submit_answer</code> takes the role’s answer class as its arguments, so a valid answer has to pass through the same validation as any other tool call — the model isn’t producing JSON for us to hopefully parse, its arguments <em>are</em> the typed instance, or the call fails with every fault listed one per line and the agent tries again.</p>

<p>Hooks do the same job for anything short of the final answer. A role can attach functions before and after any tool it uses, and a before-hook on the submit tool is the actual gate an answer has to pass — Python that really opens the cited files and checks they exist, not a model promising that it checked. (The shipped example config calls this <code class="language-plaintext highlighter-rouge">cited_files_exist</code>.)</p>

<p>The newest piece of this is profiles, which decide what a turn may do rather than leaving that to the agent or the session. Six decisions — whether to halt, which tool to force, which tools to offer, and three pieces of prose explaining the mechanics, the final turn, and the nudge — belong to a class attached to the role. <code class="language-plaintext highlighter-rouge">Answering</code> submits an answer; <code class="language-plaintext highlighter-rouge">AnsweringAsFile</code> writes a file and submits the path; <code class="language-plaintext highlighter-rouge">Standing</code> never answers at all, it just works and calls <code class="language-plaintext highlighter-rouge">idle</code> when there’s nothing left to do; <code class="language-plaintext highlighter-rouge">Deterministic</code> is a plain Python function rather than a conversation. A role names exactly one, with no default — deriving it from the tool list would just reintroduce the coupling the type exists to remove. The payoff is that an agent which has run out of turns with a child still working doesn’t get to decide to keep going. Its profile returns <code class="language-plaintext highlighter-rouge">Idling</code> before the model is even called.</p>

<p>None of this closes the system off. A role can still name arbitrary Python in four places — <code class="language-plaintext highlighter-rouge">before</code>, <code class="language-plaintext highlighter-rouge">after</code>, <code class="language-plaintext highlighter-rouge">run</code>, and now <code class="language-plaintext highlighter-rouge">profile</code> — each a dotted module and name resolved at startup and refused with a message naming the class if the shape is wrong. A profile is a class whose nine methods all have defaults, so a new kind of agent is a subclass overriding a handful: <code class="language-plaintext highlighter-rouge">Standing</code> overrides three. A deterministic agent is just a function with a typed signature, and the loader reads its input and answer contracts straight off that signature instead of making the author restate them. Even the supervisor’s contract with a spawned child is minimal — <code class="language-plaintext highlighter-rouge">Spawner.spawn(task_dir, agent_id)</code> and an <code class="language-plaintext highlighter-rouge">outcome-&lt;agent&gt;.json</code> read back as a two-field header — so nothing in it says a model has to be involved, and a file watcher or a human-in-the-loop gate that honours the same contract costs the supervisor nothing extra.</p>

<p>Budgets work the same way: turns and tool calls count down for real, the final turn is forced rather than offered, and a parent with 8 turns left can still spawn a child with 20, because a child’s budget comes from its own role, written into its spec unchanged.</p>

<h2 id="files-first">Files first</h2>

<p>A CLI writes a task to disk and hands it to a supervisor, which spawns a worker per attempt; the worker runs one <code class="language-plaintext highlighter-rouge">Session</code> and writes its result back. Every hand-off is a SQLite row or a file, and the three processes share no memory — nothing talks to anything else directly:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ws/runs/r_20260822-121500/
    config.json                   the config this run was started with, materialised once
    bus.db                        tasks, agents, every event about them, every model call
    tasks/root/
        spec.json                 what was asked, with the whole role embedded
        transcript.jsonl          every message, one per line, tagged by agent id and seq
        outcome-&lt;agent&gt;.json      the result of that attempt, kept even when superseded
        access.jsonl              every file this task read, and when that file had changed
        citations.jsonl           a span, its quote and what the agent made of it
        tools/0000-read_file.txt  every tool's full output
    tasks/&lt;child&gt;/                same shape, one per delegated task
</code></pre></div></div>

<p>Which means a run is fully inspectable without going through Ancalagon at all:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">tail</span> <span class="nt">-f</span> ws/runs/r_.../tasks/root/transcript.jsonl
sqlite3 ws/runs/r_.../bus.db <span class="s2">"select agent, status, source, summary from agent_events order by id"</span>
rg <span class="s1">'"agent": 1'</span> ws/runs/r_.../tasks/root/transcript.jsonl
</code></pre></div></div>

<p>Cost works the same way: <code class="language-plaintext highlighter-rouge">scripts/anccost.zsh</code> rolls up what every run spent from each run’s <code class="language-plaintext highlighter-rouge">bus.db</code> and emits JSON, and <code class="language-plaintext highlighter-rouge">scripts/anccosttable.zsh</code> renders that as a table, so a report goes to <code class="language-plaintext highlighter-rouge">jq</code> as readily as to a terminal.</p>

<p>Because the transcript is flushed per message, a run is watchable while it’s happening — not a debugging feature someone remembered to add, just what falls out of making the medium of exchange a file.</p>

<h2 id="sending-a-message-is-appending-to-the-transcript">Sending a message is appending to the transcript</h2>

<p>There’s no inbox here, no channel, no protocol — when you answer an agent’s question, the whole mechanism is appending a message and re-enqueuing its task:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">log</span><span class="p">.</span><span class="nf">write</span><span class="p">(</span><span class="nc">Message</span><span class="p">(</span><span class="n">role</span><span class="o">=</span><span class="n">MessageRole</span><span class="p">.</span><span class="n">USER</span><span class="p">,</span> <span class="n">blocks</span><span class="o">=</span><span class="p">[</span><span class="nc">Text</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="n">answer</span><span class="p">)],</span> <span class="n">agent</span><span class="o">=</span><span class="n">answered_by</span><span class="p">,</span>
                  <span class="n">seq</span><span class="o">=</span><span class="nf">len</span><span class="p">(</span><span class="n">fs</span><span class="p">.</span><span class="nf">read_text</span><span class="p">(</span><span class="n">path</span><span class="p">).</span><span class="nf">splitlines</span><span class="p">()),</span> <span class="n">ts</span><span class="o">=</span><span class="n">clock</span><span class="p">.</span><span class="nf">now</span><span class="p">().</span><span class="nf">isoformat</span><span class="p">()))</span>
<span class="n">bus</span><span class="p">.</span><span class="nf">enqueue</span><span class="p">(</span><span class="n">task_dir</span><span class="p">,</span> <span class="n">parent_agent</span><span class="o">=</span><span class="n">task</span><span class="p">.</span><span class="n">parent_agent</span><span class="p">)</span>
</code></pre></div></div>

<p>That’s it: append a user message to <code class="language-plaintext highlighter-rouge">transcript.jsonl</code>, enqueue the task again. A worker loads whatever transcript is already sitting in its directory, so resumption needs no further machinery than that. From outside, it’s one command:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>uv run ancalagon answer <span class="nt">--run-dir</span> ws/runs/r_... <span class="nt">--task</span> 7 <span class="nt">--answer</span> <span class="s2">"Use the 2019 schema, not the 2021 one."</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">need_input</code> is a yield, then, not a dead end. The agent stops, its question and its whole conversation stay on disk, and nothing blocks or holds a channel open while it waits. A parent answering its child mid-run and a human answering the root after the run has finished call the exact same function.</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant P as Parent
    participant DB as bus.db
    participant S as Supervisor
    participant T as tasks/child/
    participant C1 as Child&lt;br/&gt;(agent 2)
    participant C2 as Child&lt;br/&gt;(agent 4)

    C1-&gt;&gt;T: need_input: "which schema?" lands in transcript.jsonl
    C1-&gt;&gt;T: outcome-2.json (NeedsInput), process exits
    S-&gt;&gt;T: reap: read the outcome-2.json header
    S-&gt;&gt;DB: record agent 2 NEEDS_INPUT, which is news
    S-&gt;&gt;P: re-enqueue and spawn the parent in a new process
    P-&gt;&gt;DB: check_task(2): needs_input, "which schema?"
    P-&gt;&gt;T: answer_task appends a user message to transcript.jsonl
    P-&gt;&gt;DB: enqueue the child's task again (agent 4)
    S-&gt;&gt;C2: spawn a fresh process
    C2-&gt;&gt;T: load the whole transcript, the answer is the last line
    Note over P,C2: A human answering the root runs "ancalagon answer",&lt;br/&gt;which calls the same answer_task function
</code></pre>

<p>A note is the same idea with less ceremony, just a file the next turn folds in:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>uv run ancalagon note <span class="nt">--run-dir</span> ws/runs/r_... <span class="nt">--agent</span> 3 <span class="nt">--text</span> <span class="s2">"The staging config is the stale one."</span>
</code></pre></div></div>

<p>Forking a run is the same idea again: cut the transcript at a chosen message, write it into a new run directory, carry on from there. Because a conversation is nothing more than a list of lines in a file, “fork”, “resume”, “answer”, and “nudge” turn out to be one operation wearing four different names.</p>

<h2 id="sharp-edges-on-purpose">Sharp edges, on purpose</h2>

<p>The codebase is opinionated in ways that will cut you if you’re careless, which was the trade I wanted going in. A few examples:</p>

<p><strong>No defensive programming.</strong> No <code class="language-plaintext highlighter-rouge">None</code> defaults, no <code class="language-plaintext highlighter-rouge">None</code> returned from a type that says it never returns <code class="language-plaintext highlighter-rouge">None</code>, no generic exception handling, and every dataclass is frozen. Where a value might be absent, there’s a null object with a real implementation instead of a <code class="language-plaintext highlighter-rouge">None</code> check scattered across every call site.</p>

<p><strong>The file system is enforced by the type checker, not by a contract.</strong> An import rule can see that one module depends on another, but it can’t see <code class="language-plaintext highlighter-rouge">path.read_text()</code>, a method call on a value a module already holds. <code class="language-plaintext highlighter-rouge">pathlib.PurePath</code> is string manipulation with no syscalls; <code class="language-plaintext highlighter-rouge">Path</code> subclasses it and adds the syscalls. The domain speaks in <code class="language-plaintext highlighter-rouge">PurePath</code>, so the method doesn’t exist there and Pyright rejects the call on the line it’s written. <code class="language-plaintext highlighter-rouge">pathlib.Path</code> itself appears in exactly one file, <code class="language-plaintext highlighter-rouge">ancalagon/fs/real_file_system.py</code>.</p>

<p><strong><code class="language-plaintext highlighter-rouge">Any</code> is banned outright</strong>, with one scoped exemption enforced by two separate checks: the field that holds whatever an agent wants kept alongside a citation, because naming that shape properly would mean fixing a structure no run actually agrees on.</p>

<p><strong>A run directory collision is an interlock, not a bug.</strong> Allocating a fresh, timestamped run directory deliberately leaves out <code class="language-plaintext highlighter-rouge">exist_ok</code>, so two runs started in the same second fail loudly instead of quietly sharing one <code class="language-plaintext highlighter-rouge">bus.db</code>.</p>

<p><strong>An empty tools list means no tools</strong>, the inverse of the old global enable-list it replaced. A role gets exactly what it names plus whatever its profile brings, and naming something no tool answers to is a startup error that lists both the unknown names and what’s actually available.</p>

<p>None of this is abstract — it runs on every commit, via <code class="language-plaintext highlighter-rouge">uv run</code>: Black, strict Pyright, <code class="language-plaintext highlighter-rouge">lint-imports</code> checking seven contracts (one layering rule, the rest narrower about which module may touch what), a functional-programming linter capping cyclomatic complexity at three, the unit suite, and a terminology guard, chained through a pre-commit hook. That’s more ceremony than most one-person projects carry. It’s there because the harness runs against other people’s codebases, and a bug in it doesn’t just produce a wrong answer — it can read the wrong files or quote something that was never there, so I’d rather the checks ran every time than rely on remembering to run them.</p>

<h2 id="unfinished-and-evolving">Unfinished, and evolving</h2>

<p>It would be dishonest to call this finished. Some of what’s missing, I know about precisely.</p>

<p><strong>Compaction is specified and unbuilt.</strong> A long-running agent’s transcript only ever shrinks by demoting old tool output to a pointer; nothing ever summarises the reasoning itself. The design — a checkpoint recording what’s established, what’s still open, and what was explicitly ruled out, covering everything up to a given point in the conversation so only what comes after it is sent verbatim — is written down as a spec but has no code behind it yet.</p>

<p><strong>Standing agents can’t wake themselves up.</strong> An agent that never answers idles once it has nothing left to do, and the scheduler only wakes a parent whose child has just settled. Something outside has to restart it, deliberately — an external loop is supposed to decide when to stop based on a fitness function, not on the agent’s own state — but until that loop exists, the persistent-agent story is only half told.</p>

<p><strong>There are two sources of truth for what kind of agent a role is.</strong> The spawner picks an executor by checking whether the role names a run function, while the role’s profile already says which kind of agent it is. The gap between them is closed by validation rather than by construction, which is weaker than it should be, and for now it’s a recorded debt rather than a fix.</p>

<p><strong>Naming a tool your profile already brings has no effect, and naming a submit tool your profile doesn’t bring withholds it.</strong> Neither one raises an error, and neither is explained to whoever wrote the role — you just have to know.</p>

<p>Files as the medium, typed contracts at every boundary, and the model held to a budget are the parts I’m confident about. Everything else here is still moving.</p>]]></content><author><name>avishek</name></author><category term="Software Engineering" /><category term="GenAI" /><category term="Agents" /><category term="Reverse Engineering" /><summary type="html"><![CDATA[There are many agent harnesses, but this one is mine.]]></summary></entry><entry><title type="html">Homage to a Machine, by a Machine</title><link href="http://localhost:4000/2026/09/26/homage-to-a-machine.html" rel="alternate" type="text/html" title="Homage to a Machine, by a Machine" /><published>2026-09-26T00:00:00+05:30</published><updated>2026-09-26T00:00:00+05:30</updated><id>http://localhost:4000/2026/09/26/homage-to-a-machine</id><content type="html" xml:base="http://localhost:4000/2026/09/26/homage-to-a-machine.html"><![CDATA[<p>It arrived with Big Sur and it is being wiped running macOS 26.7 — five years and eleven
major versions on hardware that was supposed to be a first-generation experiment. Apple’s
first real silicon, and I gave it COBOL.</p>

<p>It never got a clean start. The first thing it inherited was <code class="language-plaintext highlighter-rouge">/usr/local/Homebrew</code>,
migrated whole from an Intel machine and already obsolete on arrival. That install stopped
being able to run years ago — <code class="language-plaintext highlighter-rouge">unknown or unsupported macOS version</code> — and its hundred-odd
formulae have sat there ever since like a previous tenant’s furniture. <code class="language-plaintext highlighter-rouge">pandoc</code> 2.11 from</p>
<ol>
  <li><code class="language-plaintext highlighter-rouge">gradle</code> 6.8. A <code class="language-plaintext highlighter-rouge">postgresql@11</code> that is <em>still running as a login service</em>, still
holding live data, quietly serving a machine that moved on to <code class="language-plaintext highlighter-rouge">/opt/homebrew</code> without ever
telling it.</li>
</ol>

<p>What it actually did, it did at scale. 344 Homebrew formulae. Seven JDKs, from
AdoptOpenJDK 8 through Temurin 24. Six Pythons under pyenv, two Rubies under rbenv, and RVM
underneath <em>those</em> like sediment. OCaml, Lean, Haskell, Rust, Clojure, Scala, Prolog in
three dialects — gnu, SWI, and Scryer. A z390 emulator. An IBM 3270 terminal. Db2 in Docker
on QEMU, emulating x86 on ARM to run a mainframe database, which is roughly the most 2020s
sentence it is possible to write.</p>

<p>Ninety-one git repositories in <code class="language-plaintext highlighter-rouge">~/code</code>. Red Dragon and its forge, cobble, smojol, codescry,
tape-z, revenger, zfa — an entire body of work on reading dead languages and telling you what
they meant. Tree-sitter grammars for VAX Pascal, PickBASIC, ABAP, Natural, HLASM: languages
most people would say aren’t worth the parser. It built them anyway. Somewhere in there is a
grammar called <code class="language-plaintext highlighter-rouge">weird</code> whose only rule is <code class="language-plaintext highlighter-rouge">func lol</code>, which proves it had a sense of humour
about all this.</p>

<p>It watched an MSc happen. The LJMU thesis, the transcripts, the certificate, the KSOU
application before that.</p>

<p>It kept two receipts of self-improvement: <code class="language-plaintext highlighter-rouge">.zshrc.omz-uninstalled-2024-10-24</code> and
<code class="language-plaintext highlighter-rouge">.zshrc.omz-uninstalled-2026-04-02</code>. Oh My Zsh, installed and renounced, twice. Seven
<code class="language-plaintext highlighter-rouge">.zshrc</code> backups in total, a sedimentary record of someone who kept meaning to tidy up and
kept finding something more interesting to do instead. That’s not a criticism. The tidying
is happening now, at the end, which is when it usually happens.</p>

<p>It was never backed up. Not once — <code class="language-plaintext highlighter-rouge">tmutil</code> has no destinations and never did. For five
years everything lived here and nowhere else. It held all of it without complaint and lost
none of it. The rest of us should be so reliable on zero redundancy.</p>

<p>Last week it was still working: a call-graph build loading 53,313 classes and running CHA
across 852,628 entry points, the log scrolling past at 16:16 on a Sunday, photographed off
the screen because that was faster than taking a screenshot. Five-year-old laptop,
whole-program analysis, no complaints. Days ago it took a constant-propagation spike across
88 CICS call sites and answered honestly: zero resolved under strict propagation, 59 under a
rule the lattice cannot express. Still producing real results on the way out the door.</p>

<p>Wipe it clean. It earned the rest.</p>]]></content><author><name>avishek</name></author><category term="Personal" /><category term="Hardware" /><summary type="html"><![CDATA[It arrived with Big Sur and it is being wiped running macOS 26.7 — five years and eleven major versions on hardware that was supposed to be a first-generation experiment. Apple’s first real silicon, and I gave it COBOL.]]></summary></entry><entry><title type="html">Rigour by Design: What AI-Powered Software Construction Should Look Like</title><link href="http://localhost:4000/2026/08/24/rigour-by-design.html" rel="alternate" type="text/html" title="Rigour by Design: What AI-Powered Software Construction Should Look Like" /><published>2026-08-24T00:00:00+05:30</published><updated>2026-08-24T00:00:00+05:30</updated><id>http://localhost:4000/2026/08/24/rigour-by-design</id><content type="html" xml:base="http://localhost:4000/2026/08/24/rigour-by-design.html"><![CDATA[<p>Software is hard. Personally, I oppose the position that “writing software was never the hard part”, and believe that that is what people say when they have either not explored the space of writing maintainable, extensible software well enough, or have not seen the impact of decisions (both good and bad) that go into building systems that are either maintainable and understandable, or become a tangled, friction-laden maintenance nightmare.</p>

<p>Let me clarify at length what I mean by “writing software”.</p>

<div class="callout" style="--callout-accent: #b04a2f">
  <p><strong>What it is not:</strong> not merely knowing and wielding the syntax / API of the language / tech stack through and through to get the job done. This is necessary but not sufficient. If that were the case, we would all be writing in assembly language.</p>

  <p><strong>What it is:</strong> Being able to express domain intention in code, in such a way that said intention is recoverable (ideally mechanically) from the code with minimal context.</p>
</div>

<p>We write specifications in plain text. That’s just the way it is. Regardless of how it gets translated, intention always begins its life in plain text. The majority of computing history has been around closing the gap between our mental intent and its expression in executable code.</p>

<p>We’d like to express our intentions to the computer at a level of abstraction closer to our thought processes. This is what programming languages are for, and, more recently, why <strong>LLMs seem to have become a viable step-up in expressing these intentions</strong>. But they are also the source of a lot of slop. Slop code is different from plain text slop though: working code is working code, however bad the quality.</p>

<div class="callout" style="--callout-accent: #b04a2f">
  <p>However, I argue that the current discussion of how well we can write <strong>specifications</strong>, is short-sighted, and merely a checkpoint on a sliding scale where, in the logical extreme, <strong>the specification is the code</strong>.</p>
</div>

<p>Ideally, like any programming language, how do we express our intention at a higher abstraction without sacrificing precision?</p>

<p>There are two scenarios where these bear fruit:</p>

<ul>
  <li><strong>Reasoning about existing (possibly legacy) code:</strong> This happens mostly during reverse engineering, recovering semantic understanding from existing code. The question then is: <strong>what is the best way to model the existing code precisely enough to recover intent and express it unambiguously, without drowning in tech/language-specific details?</strong></li>
  <li><strong>Encoding domain reasoning in code that we write:</strong> This happens when we are developing new software. The question then is: <strong>what is the best way to minimise the delta between our mental model and its expression in code?</strong></li>
</ul>

<p>Both of these are two sides of the same coin, and both lead to the same question: how do we express our intention at a higher abstraction without sacrificing precision?</p>

<p>We have been doing this with programming languages for the longest time, and the temptation is to treat LLMs as another jump in abstraction, and many do. This is not a tenable position, though. The sort of abstractions we have been building programming languages for, do not sacrifice precision. Regardless of the language, the computer does exactly what we tell it to do, no more, no less (sometimes to the chagrin and frustration of the humans writing this code). Plain text, and by extension, LLMs, are inherently a lossy medium, if used to express precise intent for consumption and interpretation by a machine.</p>

<h2 id="the-theses">The Theses</h2>

<p>This is not to dissuade people from using LLMs for programming. The central theses I present in this article are:</p>

<div class="callout" style="--callout-accent: #2980b9">
  <ul>
    <li>Shift the programming model left, from implicit human understanding to explicit deterministic encoding at runtime, and to explicit type- and structure-level encoding of domain reasoning, such that semantic errors and ambiguity are impossible by construction.</li>
    <li>Just like good software engineering practices are useful for future (and current) comprehension and reasoning of code to humans and teams, they are as useful to LLM agents for tracing and reasoning through code.</li>
    <li>The interesting thing about GenAI is not what it makes newly possible; it is what it makes newly affordable: these are the techniques which enable the two points above; and I don’t see a lot of people spending that windfall on the thing worth buying.</li>
  </ul>
</div>

<p><strong>This is an opinionated position, and it is still evolving.</strong> I purposefully took a somewhat extreme stance when writing this, because I want to represent something of a mental north star, regardless of the level of feasibility; that depends upon several factors: the language, the tooling, the maturity of the engineering team(s), and so on.</p>

<p>Every technique and tool I am going to describe here predates GenAI by years, and in many cases, decades. Dependent types, TLA+, Dafny, abstract interpretation, Prolog, property-based testing. None of it was ever wrong. It was expensive, needed skill, and slow work that was hard to defend to anyone holding a budget. So most of us stayed on the bottom rung of the ladder and called it pragmatism.</p>

<p>What got cheap in the last three years is exactly the labour that kept us down there. Spending it on generating more unverified code faster wastes the opportunity, which is what most teams continue to do.</p>

<hr />

<h2 id="contents">Contents</h2>

<ul>
  <li><a href="#ai-proposes-the-verifier-disposes">AI Proposes; the Verifier Disposes</a></li>
  <li><a href="#the-curry-howard-isomorphism-in-ninety-seconds">The Curry-Howard Isomorphism in Ninety Seconds</a></li>
  <li><a href="#the-program-is-the-proof">The Program Is the Proof</a></li>
  <li><a href="#the-zoo-of-behaviour-verification">The Zoo of Behaviour Verification</a></li>
  <li><a href="#correct-by-construction-vs-correct-by-observation">Correct by Construction vs. Correct by Observation</a></li>
  <li><a href="#markdown-specifications-are-bullshit">Markdown Specifications Are Bullshit</a></li>
  <li><a href="#flavours-of-specifications">Flavours of Specifications</a></li>
  <li><a href="#a-specification-you-can-interrogate">A Specification You Can Interrogate</a></li>
  <li><a href="#model-the-domain-not-just-the-behaviour">Model the Domain, Not Just the Behaviour</a></li>
  <li><a href="#we-should-borrow-more-domains-in-types">We should borrow more: Domains in Types</a></li>
  <li><a href="#the-practical-architecture-when-using-constrained-domain-types">The Practical Architecture when using Constrained Domain Types</a></li>
  <li><a href="#tradeoffs-when-using-constrained-domain-types">Tradeoffs when using Constrained Domain Types</a></li>
  <li><a href="#both-ladders-end-in-the-same-place">Both Ladders End in the Same Place</a></li>
  <li><a href="#what-ai-actually-changed-and-why-the-fundamentals-matter-more-now-not-less">What AI Actually Changed, and Why the Fundamentals Matter More Now, Not Less</a></li>
  <li><a href="#rigour-theatre">Rigour Theatre</a></li>
  <li><a href="#how-does-all-this-come-together">How does all this come together?</a></li>
  <li><a href="#where-this-is-over-engineering">Where This Is Over-Engineering</a></li>
  <li><a href="#conclusion">Conclusion</a></li>
</ul>

<hr />

<h2 id="ai-proposes-the-verifier-disposes">AI Proposes; the Verifier Disposes</h2>

<p>If you want one architectural principle out of this article, it is the heading of this section. Everything after it is the argument for why these four bets and not some other four; if you read nothing else, read this.</p>

<p>As a <em>design-time</em> proposer, a model is welcome absolutely anywhere, as long as the output goes through a deterministic gate before anyone depends on it. Same model, opposite rules, depending on which side of the build it sits.</p>

<p>Here is what it decomposes into.</p>

<p><strong>Executable specs, graded by criticality.</strong> The model proposes toward specs that run. Forward: FP discipline first, to get a verifiable substrate at all, then formalism where the language and the stakes both justify it. The verifier disposes by running them: deterministic pass/fail with no human in the gate, and a postcondition violation that localises the fault to one unit rather than to a service.</p>

<p>On inherited code you do not get to choose, and the bottom rung is the only one on offer. Characterisation tests are the way up: they pin existing behaviour as an executable spec, and AI has collapsed the cost of writing them at volume. Two catches, both worth stating.</p>

<p><strong>They pin the bugs exactly as written.</strong> A characterisation test encodes what the system does, not what it should do, so what you have bought is a regression net, not a specification of intent, which may result in domain SMEs being unpleasantly surprised when the code behaviour does not match their understanding of what <em>should</em> happen. That is, however, a different problem, and falls in the domain of reverse engineering. I have written about the mechanics of this at length in <a href="/2026/05/21/harnessing-llms-with-deterministic-program-analysis.html">Harnessing LLMs with Deterministic Program Analysis</a>, and may write on more of my experiences going forward.</p>

<p><strong>Legibility and traceability.</strong> Code structured to be read by the next model, not just by the next human. Types encode intent as a machine-readable spec. Traceability is emitted <em>forward</em>, at the point of construction, never reverse-engineered later. The verifier disposes via the type checker, which is a verifier of intent, and via structure that makes reasoning safe without global context. I talk about this in more detail <a href="#we-should-borrow-more-domains-in-types">here</a>.</p>

<p><strong>Functional core, imperative shell.</strong> Propose pure functions with no hidden state; quarantine effects at the seam. The verifier disposes because for a pure function the output <em>is</em> the full contract: you can regenerate the implementation freely with no side-effect risk, and safety and liveness properties become model-checkable. I talk about this in more detail <a href="#what-ai-actually-changed-and-why-the-fundamentals-matter-more-now-not-less">here</a>.</p>

<p><strong>Composable systems, bounded contexts.</strong> The unit of comprehension should be a bounded context, not the system, so that no global understanding is required to change anything. The context-window framing is a useful test of whether you have actually drawn the boundary or merely named it: if a context cannot be understood without also loading four of its neighbours, it is not a bounded context, it is a folder. Plenty of contexts in real systems fail that test, and that is a finding about the design rather than about the tooling. The verifier disposes at the contract-checked boundary: a proposal cannot violate a neighbour’s contract without something catching it mechanically.</p>

<p>Every one of those four is an ordinary architectural virtue that predates all of this. What changed is that each one now also determines whether a machine can safely participate in your codebase.</p>

<p>The rest of this article is why, which turns out to be a theorem from 1934.</p>

<hr />

<h2 id="the-curry-howard-isomorphism-in-ninety-seconds">The Curry-Howard Isomorphism in Ninety Seconds</h2>

<p>The Curry-Howard Isomorphism says that logic and programming are the same structure under two different names.</p>

<table>
  <thead>
    <tr>
      <th>Logic</th>
      <th>Programming</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>proposition</td>
      <td>type</td>
    </tr>
    <tr>
      <td>proof</td>
      <td>program</td>
    </tr>
    <tr>
      <td>A implies B</td>
      <td>function <code class="language-plaintext highlighter-rouge">A -&gt; B</code></td>
    </tr>
    <tr>
      <td>A and B</td>
      <td>pair <code class="language-plaintext highlighter-rouge">(A, B)</code></td>
    </tr>
    <tr>
      <td>A or B</td>
      <td>sum <code class="language-plaintext highlighter-rouge">Either A B</code></td>
    </tr>
    <tr>
      <td>modus ponens</td>
      <td>calling the function</td>
    </tr>
    <tr>
      <td><strong>checking a proof</strong></td>
      <td><strong>type-checking</strong></td>
    </tr>
  </tbody>
</table>

<p>A claim like “every valid order yields an invoice” is a <strong>proposition</strong>. Written as a type, it is:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">invoice</span> <span class="o">::</span> <span class="kt">ValidOrder</span> <span class="o">-&gt;</span> <span class="kt">Invoice</span>
</code></pre></div></div>

<p><strong>The proof of that proposition is an implementation of that type</strong>:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">invoice</span> <span class="n">o</span> <span class="o">=</span> <span class="o">...</span>
</code></pre></div></div>

<p><strong>If it compiles, the claim holds.</strong> Type-checking <em>is</em> proof-checking. Curry found this in 1934, Howard found it again in 1969. It is a theorem, not a nice way of talking about types.</p>

<p>There is one catch, and it matters enormously in the languages most of us actually ship in. Only a <em>total</em> function is a proof. Throw an exception, return null, or loop forever, and you have proved nothing at all. The compiler will be perfectly happy anyway. Most of the industry’s type systems are logics with a hole in them, and everybody has agreed not to look at the hole.</p>

<hr />

<h2 id="the-program-is-the-proof">The Program Is the Proof</h2>

<p>A proposition is a type. <strong>A proof of it is a program of that type.</strong> This is exact, not a metaphor. So your running code is already the most exact statement of what your system does. A type, a model, a test, a diagram, a paragraph of English: every one of them is an <em>approximation</em> of that program, and the only reason you buy an approximation is that it is cheaper than the thing it approximates.</p>

<p>That gives you exactly one question to ask about every technique below. <strong>How much of the proof does it buy, and what does it cost?</strong></p>

<p>Not “Is this rigorous?”, not “Is this best practice?”. How much of the proof, and at what price, and we will talk of different techniques, at different levels of fidelity, that we can use.</p>

<hr />

<h2 id="the-zoo-of-behaviour-verification">The Zoo of Behaviour Verification</h2>

<p>Here are the ways to be sure your code does what you think, in descending order of certainty and ascending order of regret. The ordering is the point, so for the rest of this article I will call the positions in it rungs, and the whole thing the behaviour ladder.</p>

<table>
  <thead>
    <tr>
      <th>Technique</th>
      <th>What you actually get</th>
      <th>Earliest it applies</th>
      <th>Cost to adopt</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Formal verification:</strong> model checking and program verification: TLA+, Dafny, etc.</td>
      <td>proves a model, not your code</td>
      <td>before any code is written</td>
      <td>high: learning the tool, and deciding which properties are worth proving</td>
    </tr>
    <tr>
      <td><strong>Correct by construction:</strong> rich domain types, dependent types (Lean, Idris), illegal states made unrepresentable</td>
      <td>depends upon type system and programmer discipline</td>
      <td>write / compile time</td>
      <td>moderate: a strong type system, plus modelling discipline</td>
    </tr>
    <tr>
      <td><strong>Symbolic execution:</strong> abstract interpretation, reaching conditions, taint analysis</td>
      <td>works on actual code, depends upon tooling maturity</td>
      <td>post-compile</td>
      <td>high: specialised setups</td>
    </tr>
    <tr>
      <td><strong>Static analysis:</strong> lint and immutability, cyclomatic complexity, architectural import constraints</td>
      <td>commit and integration gates</td>
      <td>build time</td>
      <td>low: mostly off the shelf</td>
    </tr>
    <tr>
      <td><strong>Static analysis (reverse engineering):</strong> control-flow graphs, data-flow analysis, def-use chains, call graphs</td>
      <td>recovered, not encoded</td>
      <td>any time, on code that already exists</td>
      <td>low to moderate, depending on tooling for the language</td>
    </tr>
    <tr>
      <td><strong>Pre-production runtime:</strong> tests, assertions, ordinary business logic, coverage and assertion quality</td>
      <td>instances of the proof, not the proof</td>
      <td>build / integration time</td>
      <td>low: standard in every language</td>
    </tr>
    <tr>
      <td><strong>Production runtime guardrails:</strong> monitors, circuit breakers, rate limiters, etc.</td>
      <td>instances of the proof, and only after the fact</td>
      <td>production</td>
      <td>low: standard in most deployment environments</td>
    </tr>
    <tr>
      <td><strong>Prose / Markdown:</strong> verified by a human in code review, or by production, and by nothing else</td>
      <td>nothing here can fail</td>
      <td>any time</td>
      <td>near zero, and you get what you pay for</td>
    </tr>
  </tbody>
</table>

<p>One axis does not fit in that table, because it does not track the ordering at all.</p>

<h3 id="how-generally-applicable-is-this-technique-narrower---wider">How generally applicable is this technique (Narrower -&gt; Wider)?</h3>

<p>Production runtime guardrails (cross-functional requirements) -&gt; Static analysis (building blocks) -&gt; Pre-production runtime (both behaviours and CFRs, but specific instances) -&gt; Symbolic execution (behaviours across multiple histories) -&gt; Correct by construction (general program correctness) -&gt; Formal verification (general program correctness, not performance)</p>

<p>There is an asymmetry in that table that I want to talk about.</p>

<ul>
  <li><strong>The ‘Correct by Construction’ rung is forward.</strong> You encode the property while you are writing the code, and the compiler checks that you did not contradict yourself.</li>
  <li><strong>‘Static Analysis (Reverse Engineering)’ is a somewhat special case, since it is mostly run when comprehending existing code.</strong> You are recovering properties from code that somebody else wrote, years ago, without any conscious intention of making them recoverable. That’s reverse engineering. Obviously, a lot of this analysis actually happens inside compilers when they are lowering code, but that is usually transparent to the program writer.</li>
  <li>The remaining ones can usually be applied in either direction.</li>
  <li><strong>Static analysis</strong> and <strong>Pre-Production Runtime Guardrails</strong> are the cheapest rungs, and there is no excuse whatsoever for skipping them. If your review process consists of senior engineers reading diffs for style and cyclomatic complexity, you are paying six figures for a linter.</li>
</ul>

<hr />

<h2 id="correct-by-construction-vs-correct-by-observation">Correct by Construction vs. Correct by Observation</h2>

<p>Runtime is where most teams find out they were wrong. It is the most expensive place to find out, and the latest. You are not required to work this way, and can shift left, like we have been doing for many software engineering practices in recent years.</p>

<p>In this context, “shift left” does not mean “test earlier”, which is still runtime, just sooner. Moving your integration suite from Friday to Tuesday does not change the epistemology of what you are doing: you are still observing instances and generalising.</p>

<div class="callout" style="--callout-accent: green">
  <p><strong>The point is to move the correctness argument out of execution altogether.</strong></p>
</div>

<hr />

<h2 id="markdown-specifications-are-bullshit">Markdown Specifications Are Bullshit</h2>

<p>I mean specifications written in markdown <em>for machine consumption</em>. Prose for humans is fine and always has been. Prose as the artifact you hand to a code generator and call the source of truth is not.</p>

<p><strong>English is the least exact model of a program you can write.</strong> The current fashion is to hand that to a probabilistic system and call the result a methodology. You have stacked two independent sources of ambiguity on top of each other and given the stack a name and a logo.</p>

<p>Here is the operational problem. <strong>Nothing in that document can be checked.</strong> Not for internal consistency, and not against the code that supposedly implements it. So the checking falls to a human reading a diff, and to production.</p>

<p>“But it’s readable.” Readable by whom, to decide what? A specification nobody can execute cannot fail. People hear that as a feature. A specification that cannot fail, can drift merrily from intent without any alarms.</p>

<p>Prose sits <em>below</em> the bottom rung of the behaviour ladder. A test at least fails.</p>

<p>To be clear about what I am not saying, because it is the obvious objection: requirements arrive in English, and they always will. Prose is fine, and unavoidable, as the <em>input</em> to the encoding step. What it cannot be is the artifact of record, the thing you diff, gate on, and point at when two people disagree. Every technique below is a way of getting the intent out of the English and into something that can fail.</p>

<hr />

<h2 id="flavours-of-specifications">Flavours of Specifications</h2>

<p>We still prefer executable specifications, and this can mean several things depending upon the fidelity and effort you want to put into building:</p>

<h3 id="the-code-is-the-spec">The Code is the Spec</h3>
<p><strong>The most faithful executable specification is the program itself.</strong> It does not always lend itself to easy reading, but it becomes readable when constraints and rules are expressed fluently as part of the code, i.e., a combination of the type system and the behaviours.</p>

<p>In the extreme case you can dispense with any other form of documentation: the code IS the spec. If the program’s interfaces are defined by its types, the logic of the program is the proof that these interfaces are satisfied. This is Curry-Howard at its logical extreme. Code that is correct by construction is also cheaper to test, cheaper to change, and cheaper for a machine to reason about. More details <a href="#we-should-borrow-more-domains-in-types">here</a>.</p>

<h3 id="tests">Tests</h3>
<p>Tests are the current workhorse of the industry: remarkably low-effort to implement, incapable of drifting silently (assuming your CI pipeline / build system is in order), a safety net for existing code in the absence of strong type and behaviour guarantees, and a useful design tool (if you are practising TDD). They also need to be maintained, and they can become unreadable if not written with care.</p>

<p>However,and, most importantly, <strong>they represent instances of the proof of behaviour, not a general proof</strong>. You can write tests showing that 2, 4 and 6 are even. That says precisely nothing about 8. This is not a reason to skip tests, since most business logic is simple enough that instances will do. It is a reason to be honest about what a green build is evidence <em>of</em>. Tests are the rung you can always afford; that is not an argument for stopping there.</p>

<h3 id="domain-specific-languages-dsls">Domain Specific Languages (DSLs)</h3>
<p>A lot of domain modelling emerges from prose, and, as stated before, prose cannot be checked. A DSL for business logic is the way out: machine-checkable for consistency, queryable, executable. In the extreme case the code implements the DSL directly, but often the logic is better expressed in a more flexible language. One class of languages I’ve seen particularly suitable for this is Logic Programming: Prolog is the exemplar in this category. I have written about my experiments with extracting out a DSL from a law document in <a href="/2026/08/24/a-statute-as-a-runnable-logic-program">this post</a>.</p>

<h3 id="static-models">Static Models</h3>
<p>The next level of modelling involves various forms of static analysis: dataflow analysis, which can prove that certain values are never null or that certain functions are never called with certain arguments; dominator analysis, which answers whether this chunk always executes when reaching a certain region of functionality. These are useful for catching bugs, but they are not as powerful as a full proof system. They are building blocks for more abstracted analysis, e.g., answering “which factors affect the interest rate?” might start with dataflow analysis of the interest rate variable.</p>

<p>Static analysis pays the same tax in a different currency. A control-flow graph is precise right up until it hits polymorphism, at which point the call edges point to multiple futures, and further facts must be mined (e.g., dependency wiring configuration) to disambiguate. Every soundness/precision trade-off in an analyser is a place where the model and the code diverge quietly.</p>

<h3 id="formal-methods">Formal Methods</h3>
<p>Formal methods, meaning model checking and program verification, are where you model chunks of functionality, assert invariants and properties, and have the tool verify that they hold. This is the space of tools like Dafny, TLA+, etc. They are very powerful, but they require investment in learning them, and more careful thinking about which properties are worth proving (e.g., two users cannot log into the same account).</p>

<p>Different techniques here model different aspects of logic: you’d write a TLA+ spec to verify the safety / liveness of one piece of code, and maybe use Dafny to assert something about a data structure in another. These are not usually used to model the full business domain of a program. TLA+ proves your model has no deadlock. Dafny proves the function you specified is correct. Neither of them has seen your production code. The proof is only ever as good as the model’s resemblance to what you actually shipped, and that resemblance is maintained by hand, by humans, under deadline.</p>

<hr />

<h2 id="a-specification-you-can-interrogate">A Specification You Can Interrogate</h2>

<p>The rung above guardrails is where it gets interesting, because a declarative spec is a program you can ask questions of. Here is the smallest possible example, written in Prolog.</p>

<div class="language-prolog highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">% the domain, stated once</span>
<span class="ss">parent</span><span class="p">(</span><span class="ss">rajesh</span><span class="p">,</span> <span class="ss">meera</span><span class="p">).</span>
<span class="ss">parent</span><span class="p">(</span><span class="ss">meera</span><span class="p">,</span> <span class="ss">arun</span><span class="p">).</span>
<span class="ss">grandparent</span><span class="p">(</span><span class="nv">X</span><span class="p">,</span> <span class="nv">Z</span><span class="p">)</span> <span class="p">:-</span> <span class="ss">parent</span><span class="p">(</span><span class="nv">X</span><span class="p">,</span> <span class="nv">Y</span><span class="p">),</span> <span class="ss">parent</span><span class="p">(</span><span class="nv">Y</span><span class="p">,</span> <span class="nv">Z</span><span class="p">).</span>

<span class="p">:-</span> <span class="err">\</span><span class="o">+</span> <span class="ss">grandparent</span><span class="p">(</span><span class="nv">X</span><span class="p">,</span> <span class="nv">X</span><span class="p">).</span>   <span class="c1">% invariant: nobody is their own grandparent</span>
</code></pre></div></div>

<div class="language-prolog highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">?-</span> <span class="ss">grandparent</span><span class="p">(</span><span class="ss">rajesh</span><span class="p">,</span> <span class="ss">arun</span><span class="p">).</span>  <span class="c1">% forward</span>
   <span class="ss">true</span><span class="p">.</span>

<span class="o">?-</span> <span class="ss">grandparent</span><span class="p">(</span><span class="nv">X</span><span class="p">,</span> <span class="ss">arun</span><span class="p">).</span>       <span class="c1">% backward</span>
   <span class="nv">X</span> <span class="o">=</span> <span class="ss">rajesh</span><span class="p">.</span>

<span class="o">?-</span> <span class="ss">grandparent</span><span class="p">(</span><span class="ss">rajesh</span><span class="p">,</span> <span class="nv">Z</span><span class="p">).</span>     <span class="c1">% backward</span>
   <span class="nv">Z</span> <span class="o">=</span> <span class="ss">arun</span><span class="p">.</span>
</code></pre></div></div>

<p>One clause, three questions. You did not write a lookup function and you did not write an inverse lookup function. Resolution ran the rule backwards from the goal, because the rule is a <em>relation</em>, not a procedure.</p>

<p>In markdown you would write “a grandparent is the parent of a parent”, and then check every consequence of that sentence by hand, forever, every time anything else in the document changed.</p>

<p>Note also what the invariant is. It is not a comment. It is not a team convention that gets mentioned in onboarding. Breaking it is a mechanical failure, not a reviewer being alert on a Thursday afternoon.</p>

<p>The limit is worth stating plainly: <strong>this does not stop an LLM writing a wrong spec.</strong> You can check consistency, not intent. What it does stop is the model being wrong across six paragraphs that nobody reads carefully. And because the check is mechanical, iteration is close to free.</p>

<p>It is also exactly why prose specs cannot be rescued by better models. A wall of text cannot fail, so the loop never closes, so a human has to sit in the middle of it reading everything. You automated the proposing and kept the expensive half.</p>

<p>An experiment on how to extract a deterministic, queryable knowledge base with forward and backward inference from a text document, is documented in <a href="/2026/08/24/a-statute-as-a-runnable-logic-program">A Statute as a Runnable Logic Program</a>.</p>

<hr />

<h2 id="model-the-domain-not-just-the-behaviour">Model the Domain, Not Just the Behaviour</h2>

<p>The grandparent example is trivial on purpose. Put settlement eligibility, tenure calculation, or chain of custody in its place. The mechanism does not change.</p>

<p>The point is that you can ask questions of a domain, deterministically, before a single line of production code exists. Contradictions show up as failed queries. The alternative is two people discovering three sprints later that they meant different things by the same word, which is how most requirements defects actually happen.</p>

<p>Rich typing does the same job, in the language you actually ship. Not “amount is an <code class="language-plaintext highlighter-rouge">int</code>, validated somewhere upstream, probably”, but an amount that cannot be <em>constructed</em> outside its valid range. The constructor is the specification.</p>

<p>Domain modelling and type design are the same discipline viewed from two ends. Treat types as annotation and you are wasting the best checker you already have installed and are already paying for.</p>

<p>A worked example of the declarative approach is at <a href="https://github.com/avishek-sen-gupta/doc-pipeline">github.com/avishek-sen-gupta/doc-pipeline</a>.</p>

<p>But, there is a lot more we can do with types. Keep reading.</p>

<hr />

<h2 id="we-should-borrow-more-domains-in-types">We should borrow more: Domains in Types</h2>

<p>I love types. Programmers are no strangers to typed programming languages. Currently, we use types as mere data holders with runtime behaviour. You say: “Yeah, well, that’s what a type is”. I say: “We can do more, a lot more.” There is a lot more that we can borrow from work done in other programming languages in recent years, which push the possibilities of what we can encode in types themselves without depending upon runtime behaviour.</p>

<div class="callout" style="--callout-accent: green">
  <p>Traditional programming separates concerns: write code, then validate it at runtime. Type systems can invert this: encode the constraints themselves into types. A program that type-checks is a program that provably respects all domain rules, no runtime validation needed (for that logic).</p>
</div>

<h3 id="levels-of-expressiveness">Levels of Expressiveness</h3>

<p><strong>Level 1: Plain Types (Foundation)</strong></p>

<p>This example is in Haskell, and simply states that a function takes in two <code class="language-plaintext highlighter-rouge">Int</code> values, and returns an <code class="language-plaintext highlighter-rouge">Int</code>. No constraints. Both inputs unchecked. In usual ‘enterprise’ code, validations happen at runtime in the body of the function.</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">divide</span> <span class="o">::</span> <span class="kt">Int</span> <span class="o">-&gt;</span> <span class="kt">Int</span> <span class="o">-&gt;</span> <span class="kt">Int</span>  <span class="c1">-- Accepts any integers, could crash on zero</span>
</code></pre></div></div>

<p><strong>Level 2: Refined Types (Constraints on Values)</strong></p>

<p>The second level is where we can start encoding constraints on types. These constraints The refinement <code class="language-plaintext highlighter-rouge">x &gt; 0</code> is a logical predicate on the value. The type system (using SMT solvers like Z3) proves this predicate holds. Division by zero becomes impossible.</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">{-@ type Pos = {x:Int | x &gt; 0} @-}</span>
<span class="cm">{-@ divide :: Int -&gt; Pos -&gt; Int @-}</span>
<span class="n">divide</span> <span class="n">a</span> <span class="n">b</span> <span class="o">=</span> <span class="n">a</span> <span class="p">`</span><span class="n">div</span><span class="p">`</span> <span class="n">b</span>  <span class="c1">-- Proven safe: b is always positive</span>
</code></pre></div></div>

<p><strong>Level 3: Dependent Types (Constraints on Structure)</strong></p>

<p>This example is in Idris, and allows you to encode very arbitrary propositions as part of the type. Your program’s correctness proof is embedded in its type signature. Type-checking <em>is</em> proof verification.
This example is in Idris, and allows you to encode the fact that the input list is sorted, before even running the program. NOTE: I do not know Idris (currently working through Lean 4), but the type signature is very similar across these kinds of languages, so it should look familiar.</p>

<div class="language-idris highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">insert :</span><span class="o">:</span> <span class="p">(</span><span class="n">x</span> <span class="o">:</span> <span class="kt">Int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">xs</span> <span class="o">:</span> <span class="kt">List Int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">prf</span> <span class="o">:</span> <span class="kt">Sorted</span> <span class="n">xs</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Sorted</span> <span class="p">(</span><span class="n">insert</span> <span class="n">x</span> <span class="n">xs</span><span class="p">)</span>
</code></pre></div></div>
<p>Types can depend on values. Here, the type of the result depends on the <em>structure</em> of the input list (whether it’s sorted). You cannot construct an unsorted list: the type system enforces ordering.</p>

<p>Arbitrary mathematical theorems become part of the type. Your program’s correctness proof is embedded in its type signature. Type-checking <em>is</em> proof verification.</p>

<hr />

<h2 id="the-practical-architecture-when-using-constrained-domain-types">The Practical Architecture when using Constrained Domain Types</h2>

<p>None of the above helps if the data arrives as a string. External data (user input, API responses, database records, a CSV somebody emailed you) arrives unvalidated, and no type system will change that. What it changes is <em>where</em> you deal with it.</p>

<p>The move is to confine validation to an adapter layer at the system boundary. The adapter performs runtime checks and converts unverified data into refined types, once. Everything inside is then proven correct by the type system, so the core assumes its invariants hold and concentrates on behaviour. That splits the problem into two halves with completely different rules: the adapter is where you write defensive code, and the core is where you reason about correctness.</p>

<pre><code class="language-mermaid">flowchart LR
    subgraph OUT[Outside]
        SRC[user input · API responses\ndatabase rows · files · queues\nstrings, numbers, nulls]
    end
    subgraph ADP[Adapter · the only place that validates]
        PARSE[parse into refined types\nrange · format · referential checks\nreturns Either ValidationError Domain]
    end
    subgraph CORE[Functional core · no validation anywhere]
        LOGIC[total functions over refined types\nAmount · NonEmpty · ValidOrder\ninvariants hold BY CONSTRUCTION]
    end
    subgraph EFF[Effects]
        RENDER[render back to the wire\nDB writes · API calls]
    end

    SRC --&gt;|untrusted| PARSE
    PARSE --&gt;|rejected: an error VALUE, at the edge| SRC
    PARSE --&gt;|accepted: proof carried in the type| LOGIC
    LOGIC --&gt; RENDER

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef bad fill:#fce7f3,stroke:#be185d,color:#831843
    classDef good fill:#d4edda,stroke:#388e3c,color:#1b5e20
    class SRC bad
    class LOGIC good
</code></pre>

<p>The arrow that does the work is the one in the middle. A value crosses it exactly once, and it changes kind when it does: <code class="language-plaintext highlighter-rouge">String</code> becomes <code class="language-plaintext highlighter-rouge">EmailAddress</code>, <code class="language-plaintext highlighter-rouge">int</code> becomes <code class="language-plaintext highlighter-rouge">Quantity</code>, <code class="language-plaintext highlighter-rouge">Order</code> becomes <code class="language-plaintext highlighter-rouge">ValidOrder</code>. That change of kind is the record that the check happened, which is why nothing downstream has to ask again. This is what Alexis King called “parse, don’t validate”: a validating function returns a boolean and throws the knowledge away, while a parsing function returns a <em>narrower type</em> and keeps it.</p>

<p>Four rules make the split hold and distinguish it from ordinary defensive programming.</p>

<ul>
  <li><strong>The refined type has exactly one way in.</strong> A private constructor plus a smart constructor returning <code class="language-plaintext highlighter-rouge">Either ValidationError Amount</code>. If anything outside the adapter can call <code class="language-plaintext highlighter-rouge">Amount(-5)</code>, the type guarantees nothing and you are back to reading call sites.</li>
  <li><strong>Failure is a value at the boundary and an impossibility inside.</strong> The adapter returns errors; the core has no error path for invariant violations, because there is no way to construct the violation. When a core function does have to fail for domain reasons (“insufficient funds”), that is a return type, not an exception.</li>
  <li><strong>Every entry point is an adapter, including the ones that look internal.</strong> Deserialisation is parsing. A database read is parsing. A message off a queue is parsing. The most common way this architecture rots is a repository that hands the core a row it built with raw constructors, because “it came from our own database”.</li>
  <li><strong>The core never re-checks.</strong> If you find a defensive <code class="language-plaintext highlighter-rouge">if</code> inside the core, either the type is too wide or somebody did not trust it. Both are worth fixing at the type rather than at the call site.</li>
</ul>

<p>What you get, concretely, is that validation logic stops being a cross-cutting concern and becomes its own layer, separate from any other logic. It is the part of the system you test hardest, because it is the only part that can be handed garbage, and it is small enough to test exhaustively. Property-based testing lands naturally here: generate arbitrary bytes, assert that everything either parses into a value satisfying the invariant or is rejected with a specific error.</p>

<p>For AI-assisted work, the surface area of code that needs careful auditing shrinks. The adapter is where a model should be writing careful, paranoid, heavily tested code, and the core is where its output is safest to accept, because a function over refined types cannot be wrong in the ways generated code is usually wrong. It cannot forget a null check that the type made impossible, and it cannot invent a state the constructor refuses to build.</p>

<p>Potential defects concentrate at the boundary. You have not removed the possibility of bad data, you have moved every opportunity for it into one layer. A bug there is now a wrong assumption everywhere downstream, silently, with the type system asserting it is fine. That is a much better place to be than the alternative validation-riddled runtime logic approach, because it is one small layer to review rather than a full codebase to search and reason about.</p>

<h2 id="tradeoffs-when-using-constrained-domain-types">Tradeoffs when using Constrained Domain Types</h2>

<p><strong>Advantages:</strong> Correctness proven before runtime. Impossible states become literally unrepresentable. Downstream code is simpler and faster (no checks).</p>

<p><strong>Costs:</strong> Steeper learning curve. Proof obligations can become unwieldy when moving beyond refinement types. Complex non-linear arithmetic may require manual lemmas. Development is slower (more annotation).</p>

<p><strong>Reality:</strong> A lot of runtime validation in enterprise code today, can be shifted to the compile phase with Refinement Types (Level 2). Level 3 opens up lots of tantalising possibilities, but can be complex work depending upon the complexity of the constraint.</p>

<p>Why am I talking about this? Because, by improving the expressibility of our code, we get the following consequences:</p>

<ul>
  <li><strong>Simpler logic in the functional core</strong>, since validation is not interspersed with actual runtime code; in fact, I wager that what we call a huge amount of business logic in code, could largely collapse into nothingness, or just side effects (database calls, network calls, etc.) based on exhaustive pattern matching on types.</li>
  <li><strong>Errors and human assumptions surface earlier in the type system.</strong> Run-of-the-mill defensive programming patterns stand out, and become amenable to refactoring to type constraints.</li>
  <li><strong>Validations and actual side effect-free runtime logic become clearly delineated</strong>, since validations move to the edge, and are no longer part of the functional core. Thus, this becomes a useful architectural constraint.</li>
  <li><strong>The surface area of change reduces</strong>: since the domain changes less often, change around side effects like I/O remain confined to the edges.</li>
  <li><strong>AI context becomes richer and more compressed</strong>, because constraints are specified ONCE, at the type level, instead of being spread across the codebase.</li>
  <li>By the same token, and, <strong>more importantly</strong>, humans understand the code better, faster.</li>
  <li>From a purist’s perspective, <strong>we move closer to closing the gap between a readable spec and executable code</strong>, i.e, we are closer to “The Code is the Specification”.</li>
</ul>

<hr />

<h2 id="both-ladders-end-in-the-same-place">Both Ladders End in the Same Place</h2>

<p>That is not a coincidence.</p>

<pre><code class="language-mermaid">flowchart TD
    subgraph CODE[Code ladder]
        R1[runtime tests] --&gt; R2[static analysis]
        R2 --&gt; R3[symbolic execution]
        R3 --&gt; R4[proof without execution]
        R4 --&gt; TOP1[rich domain types]
    end
    subgraph SPEC[Spec ladder]
        S1[prose / markdown] --&gt; S2[deterministic guardrails]
        S2 --&gt; S3[declarative machine-checkable specs]
        S3 --&gt; TOP2[rich domain types]
    end
    TOP1 --&gt; CONV[the type is the proposition\nthe program is the proof\nnothing left to drift]
    TOP2 --&gt; CONV

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef bad fill:#fce7f3,stroke:#be185d,color:#831843
    classDef good fill:#d4edda,stroke:#388e3c,color:#1b5e20
    class R1,S1 bad
    class TOP1,TOP2,CONV good
</code></pre>

<p>The code ladder climbs to rich domain types: behaviour encoded at compile time, where the illegal program does not typecheck. The spec ladder climbs to rich domain types: the domain encoded at compile time, where the illegal state does not typecheck. At the top, the spec and the program stop being two artifacts that can drift apart. They are one artifact.</p>

<p>This matters specifically for AI-assisted construction. <strong>A model’s nondeterminism does not sit everywhere. It sits in the gap between the spec and the program.</strong> That gap is the translation step, and translation is where guessing happens. Every rung you climb narrows it. At the limit there is no translation step left for anything to be wrong in.</p>

<p>You will not reach the limit, and I am not suggesting you try. What matters is which way you are walking.</p>

<hr />

<h2 id="what-ai-actually-changed-and-why-the-fundamentals-matter-more-now-not-less">What AI Actually Changed, and Why the Fundamentals Matter More Now, Not Less</h2>

<p>AI did not add a rung to either ladder. It collapsed the cost of climbing them.</p>

<p>That distinction is the whole argument. Dependent types did not get more expressive because a model can write Lean. TLA+ did not get better at liveness. What changed is that the tedious, skilled, slow labour of <em>encoding</em> things (writing the property, writing the model, writing the characterisation test, writing the query) got an order of magnitude cheaper.</p>

<p>Immutability. Pure functions. Small composable units. Explicit failure. Contracts at the seams. Types that mean something.</p>

<p>This is not nostalgia. These are the properties that make code comprehensible at a local scale, without necessarily keeping the entire model in your head all the time, and that leads to code that is safe to keep. Every one of them was a good idea when humans wrote all the code, and we have always given the same reasons: you can read a pure function without holding the rest of the system in your head, you can pass around an immutable value without wondering who else is going to write to it, and you can compose small units without the combination surprising you. And now, LLMs reap these benefits for the same reasons.</p>

<p>Think about what an agent has to do before it can safely change a line of your code. It has to work out what that code does, what it touches, and what breaks elsewhere if it changes. That is the same job you do when you open an unfamiliar file, with one important difference: the agent does it with whatever fits in its context window, and nothing else. It cannot walk over and ask the person who wrote it. It cannot remember the incident in March. Everything it reasons with, it has to recover from the code in front of it. So every property that shrinks the amount of code you must read in order to be sure of something, is worth more to the agent than it ever was to you.</p>

<p><strong>Purity bounds what has to be read at all.</strong> For a pure function, the signature plus the body is the entire contract. There is no elsewhere. Nothing in the rest of the codebase can change what it does, which means a model reasoning about it in isolation is reasoning correctly, not optimistically. A method that mutates four fields, reads a clock and writes to a queue has a contract smeared across the whole system, and to reason about it soundly you would have to read the whole system. No context window is big enough for that, and no amount of prompt engineering will substitute for it.</p>

<p><strong>Immutability deletes the aliasing question.</strong> Most of the genuinely hard questions in code comprehension are some version of “who else holds a reference to this, and when do they write to it?” Answering it requires global knowledge, which is precisely the thing an agent does not have and a human acquires slowly and expensively. Under immutability the question does not arise, because the answer cannot matter.</p>

<p><strong>Composability makes local reasoning sound rather than merely convenient.</strong> If a unit is small, has explicit inputs and outputs, and does not reach outside itself, then understanding the unit is understanding the unit. This is what lets an agent work usefully with a partial view of the system: the view it has is not a fragment of the truth, it is the whole truth about that piece. Bounded contexts are the same principle applied one level up.</p>

<p><strong>Explicit failure removes the control flow the model cannot see.</strong> A <code class="language-plaintext highlighter-rouge">Result</code> or an <code class="language-plaintext highlighter-rouge">Either</code> in the signature is a fact sitting in front of the reader. An exception thrown eleven frames down is not in anything the model is looking at, and it is not in anything you are looking at either during code review. The difference is that you will eventually find out in production; the model will confidently generate a caller that has no idea the path exists.</p>

<hr />

<h2 id="rigour-theatre">Rigour Theatre</h2>

<p>Now the objection to everything above, which I think is the strongest one available, and which I would rather state myself than have stated at me.</p>

<p>Making rigour cheap to produce also makes the <em>appearance</em> of rigour cheap to produce. A model will write you a TLA+ spec that model-checks clean, a dependent type that is inhabited, a property test that passes on ten thousand cases, all of which formalise the wrong thing. Consistency is mechanical: intent isn’t, and always originates in the human brain. You can check that the spec does not contradict itself; you cannot check that it is the spec you meant.</p>

<p>And rigorous-looking artifacts borrow authority. Nobody re-reads the invariant. It has a <code class="language-plaintext highlighter-rouge">\A</code> in it, it went green in CI, and the reviewer who might have caught that it quantifies over the wrong set has already scrolled past. Prose at least advertises that it is unverified. A proof of the wrong proposition is the same failure with better clothes, and the more of it you generate, the less any individual piece gets read.</p>

<p>The second failure is the gate itself. “Deterministic pass/fail with no human in the gate” describes what should happen. What actually happens, when you point an agent at a red build and tell it to make the build green, is that making the build green is the goal it optimises. The assertion gets weakened. The test gets an <code class="language-plaintext highlighter-rouge">@Ignore</code> and a plausible comment. The postcondition acquires a special case for exactly the input that was failing. The mock gets adjusted until the thing under test is no longer under test. None of this is malice, and all of it is what “satisfy the verifier” means when the verifier is the only thing being satisfied.</p>

<p>All of these have the same mitigation. The property, the invariant, the contract, the assertion: these are the artifacts where human judgement is least substitutable, and they are exactly the artifacts you should be <strong>not accept unreviewed</strong>. Generate the implementation freely. Read the specification like it matters, because it is the only place your intent lives, and keep it in version control where a change to it shows up in a diff rather than in an incident.</p>

<p>So: AI proposes, the verifier disposes, and somebody still has to own the verifier. That is not a hole in the argument. It is where the argument was always going to land, and it is a much better place to be spending expensive human attention than reading diffs for style.</p>

<hr />

<h2 id="how-does-all-this-come-together">How does all this come together?</h2>

<p>Different routes, depending upon the rigour you need and the effort you are willing to invest. You can mix and match, but the idea is to not stay stuck at the status quo. Below are some examples of how you could pick and choose.</p>

<h3 id="route-1-current">Route 1: Current</h3>

<p>The status quo. Everything is established by running the code, whether it’s through tests in the dev environment or through manual testing in a staging environment (or, horrors, in production!).</p>

<ol>
  <li>Human writes</li>
  <li>LLM reads and writes code (TDD as needed)</li>
  <li>Validation boundaries and side effects tested through integration tests / mocks</li>
  <li>Cross-component interactions tested through integration tests</li>
</ol>

<h3 id="route-2-current-with-some-behavioural-modelling">Route 2: Current, with (some) behavioural modelling</h3>

<p>One rung up, applied selectively. The critical sections get a proof, and everything else stays as it was.</p>

<ol>
  <li>Human writes</li>
  <li>LLM reads and writes code (TDD as needed)</li>
  <li><strong>Model critical sections in Dafny, etc. to verify behaviour guarantees</strong></li>
  <li>Validation boundaries and side effects tested through integration tests / mocks</li>
  <li>Cross-component interactions tested through integration tests</li>
</ol>

<h3 id="route-3-machine-checkable-specs--behavioural-modelling--functional-core-using-constrained-types">Route 3: Machine-checkable specs + behavioural modelling + functional core using constrained types</h3>

<p>The full climb. The spec is an artifact that runs, the interactions are proven, and the core carries its invariants in its types.</p>

<ol>
  <li>Human writes</li>
  <li><strong>LLM reads and writes specs in a DSL</strong> (e.g., a declarative logic programming language)</li>
  <li><strong>TLA+ to model component interactions and prove guarantees</strong></li>
  <li><strong>Functional core using constrained types</strong></li>
  <li>TDD validation boundaries and side effects</li>
  <li>Cross-component interactions tested through integration tests</li>
</ol>

<h3 id="route-4-the-code-is-the-specification">Route 4: The “code is the specification”</h3>

<p>The limit case. There is no separate spec artifact to drift, because the types and the core are the spec. In my mind, this is the best possible outcome, but it is also the hardest to achieve, because it depends upon tooling, team maturity, and willingness of stakeholders to accept that there is no material difference between the spec and the code (which is not a technical problem :-).</p>

<ol>
  <li>Human writes</li>
  <li><strong>LLM reads and writes functional core using constrained types</strong></li>
  <li>TDD validation boundaries and side effects</li>
  <li>Cross-component interactions tested through integration tests</li>
</ol>

<h3 id="what-each-route-actually-buys">What each route actually buys</h3>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Where the spec lives</th>
      <th>Proven before runtime</th>
      <th>Established by running</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>1. Current</strong></td>
      <td>in someone’s head, and in prose</td>
      <td>nothing</td>
      <td>all behaviour, all boundaries, all interactions</td>
    </tr>
    <tr>
      <td><strong>2. + behavioural modelling</strong></td>
      <td>prose, plus a model of the critical sections</td>
      <td>safety and liveness of what you chose to model</td>
      <td>everything else</td>
    </tr>
    <tr>
      <td><strong>3. Specs + modelling + typed core</strong></td>
      <td>a DSL you can query, plus a TLA+ model</td>
      <td>domain consistency, component interactions, every invariant in the core</td>
      <td>boundaries and side effects only</td>
    </tr>
    <tr>
      <td><strong>4. Code is the specification</strong></td>
      <td>the types and the core, and nowhere else</td>
      <td>every invariant the types encode</td>
      <td>boundaries and side effects only</td>
    </tr>
  </tbody>
</table>

<p>Route 4 is not strictly more rigorous than Route 3. It drops the queryable spec and the interaction model, and buys back the fact that nothing can drift, because there is only one artifact. Which of the two you want depends on whether your risk is misunderstanding the domain, in which case you want the DSL you can interrogate, or concurrency and protocol errors, in which case you want the TLA+ model.</p>

<hr />

<h2 id="where-this-is-over-engineering">Where This Is Over-Engineering</h2>

<p>Climbing costs real engineering labour, and I am not going to pretend otherwise.</p>

<p>If the thing is low-volume, short-lived and not critical, this is over-engineering and you should not do it. Volume, longevity and criticality are what decide, and they decide per system, not per organisation. Anyone who tells you the ladder is always worth climbing is doing ideology, not engineering.</p>

<p>Rigour also looks slower up front, and sometimes it genuinely is. I am not going to claim it is secretly faster. What I will claim is that a lot of what gets built without it does not survive contact with production, and that cost lands on somebody’s budget anyway, just later, and filed under a different name.</p>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>The argument stems from one line: your program is the proof, everything else you write about it is an approximation because it is cheaper, and the ROI of the approximation depends upon how much of the proof it buys and at what price.</p>

<p>That question used to have depressing answers. The techniques at the top of the ladder (dependent types, model checking, declarative domain models, program analysis) were never wrong, they were expensive, and most of us settled at the bottom and called it pragmatism. What changed in the last three years is not the ladder. It is the price of climbing it. The tedious, skilled, slow labour of encoding things is the exact labour that got cheap, and spending that windfall on generating more unverified code faster is the mistake almost everyone is currently making.</p>

<p>So: AI proposes, the verifier disposes. Executable specs rather than prose that cannot fail. Types and structure that carry intent, because the next reader of your code is as likely to be a machine working from a context window as a human working from memory. A functional core with the effects quarantined, because purity is what makes code tractable to a verifier and to an agent alike. Boundaries drawn well enough that a change stays local. None of it is new.</p>

<p>What it does not buy you is the judgement about what to encode. Consistency is mechanical; intent never becomes so. The invariant that quantifies over the wrong set will check clean forever, and a gate that nobody owns is a gate that gets optimised around. The expensive human attention does not disappear. It moves, from reading diffs to writing and reading the properties that everything else is checked against, which is a considerably better place for it to be.</p>

<div class="callout" style="--callout-accent: #b04a2f">
  <p><strong>So the job of AI here is to make rigour cheap. Not to make judgement optional: that stays human.</strong></p>
</div>]]></content><author><name>avishek</name></author><category term="Software Engineering" /><category term="GenAI" /><category term="Formal Methods" /><category term="Type Systems" /><category term="Curry-Howard" /><category term="Specifications" /><category term="Architecture" /><category term="Program Analysis" /><summary type="html"><![CDATA[Software is hard. Personally, I oppose the position that “writing software was never the hard part”, and believe that that is what people say when they have either not explored the space of writing maintainable, extensible software well enough, or have not seen the impact of decisions (both good and bad) that go into building systems that are either maintainable and understandable, or become a tangled, friction-laden maintenance nightmare.]]></summary></entry><entry><title type="html">A Statute as a Runnable Logic Program: Field Notes from Climbing the Spec Ladder</title><link href="http://localhost:4000/2026/08/24/a-statute-as-a-runnable-logic-program.html" rel="alternate" type="text/html" title="A Statute as a Runnable Logic Program: Field Notes from Climbing the Spec Ladder" /><published>2026-08-24T00:00:00+05:30</published><updated>2026-08-24T00:00:00+05:30</updated><id>http://localhost:4000/2026/08/24/a-statute-as-a-runnable-logic-program</id><content type="html" xml:base="http://localhost:4000/2026/08/24/a-statute-as-a-runnable-logic-program.html"><![CDATA[<p>In <a href="/2026/08/24/rigour-by-design.html">Rigour by Design</a> I argued that almost everyone is parked on the bottom rung of the spec ladder, and that what GenAI actually made cheap is the labour of climbing. That post had a link to a repository and one sentence of description. This post describes what the actual experiment was.</p>

<p>One of the things I have always believed - and continue to believe - is that well-written code IS the spec. This is because it marries expressiveness (which non-programmers can understand) with the precision of what actually executes (which programmers appreciate). If I were being glib, I’d liken specs to reading a manual about driving. Sure, you can read all you like about driving, but until you have actually driven a car, you don’t really know what works and what doesn’t. More precise specs might be akin to a simulator, where you might get a real-er driving experience, but nothing beats actually doing the thing, because all the manuals and simulators are in the service of the final goal: to actually be on the damn road.</p>

<p>At the same time, I have had some toy experience with Prolog which I have documented <a href="/2025/06/28/a-brief-overview-of-prolog.html">here</a> and <a href="/2025/07/03/building-vm-in-prolog.html">here</a>. Logic programming fascinates me, and, along with formal verification and types, seem to be one of those points where rigour and expressiveness intersect to a great degree. Add to that the possibility of running a program in reverse being a natural consequence of how Prolog works (<code class="language-plaintext highlighter-rouge">"1+2=X =&gt; X=3"</code>, <code class="language-plaintext highlighter-rouge">"1+Y=3 =&gt; Y=2"</code>), and suddenly, you have something that you can actually query in all sorts of useful ways.</p>

<div class="callout" style="--callout-accent: #b04a2f">
  <p>What I wanted to prove: how far can you go in representing normal “human-readable” documents (rules, laws, logic) as runnable logic programs, such that:</p>

  <ul>
    <li>The logic program <strong>faithfully represents the intended logic</strong> of the original document with absolute fidelity, <strong>without loss in information</strong>.</li>
    <li>The logic program is <strong>executable</strong> and can be run to <strong>produce results that are consistent with the original document</strong>.</li>
    <li>The logic program is <strong>verifiable</strong> and can be checked for <strong>correctness</strong> and <strong>completeness</strong>.</li>
    <li>The logic program is <strong>understandable</strong> and can be read and understood by humans, including non-programmers.</li>
  </ul>
</div>

<p>The short version: I took the Singapore Land Titles Act (1995) and tried to express it as a SWI-Prolog program you can <em>run</em>, where every rule cites the provision it encodes and every answer reads back to the source. Then I tried to get a language model to write that program, behind deterministic gates that decide whether its output is admissible.</p>

<h2 id="characteristics-of-this-experiment">Characteristics of this Experiment</h2>
<p><strong>None of the Prolog was written by a human.</strong> That covers the libraries the authoring loop produced, and also the ones I will call <em>logic infrastructure</em> libraries, which were authored interactively, with me directing and reviewing while the model typed. So the code was generated <strong>interactively, under review, with unbounded rounds and a human in every one</strong> against <strong>one call per domain, checked by a gate, with no human in the loop at all</strong>. What a human contributed is the representation, the gates, and the judgment about which encodings were wrong.</p>

<hr />

<h2 id="contents">Contents</h2>

<ol>
  <li><a href="#what-the-experiment-was">What the Experiment Was</a></li>
  <li><a href="#version-one-and-why-it-was-deleted">Version One, and Why It Was Deleted</a></li>
  <li><a href="#the-representation-nine-predicates">The Representation: Nine Predicates</a></li>
  <li><a href="#where-the-model-sits-and-the-gates-that-contain-it">Where the Model Sits, and the Gates That Contain It</a></li>
  <li><a href="#what-the-gates-actually-caught">What the Gates Actually Caught</a></li>
  <li><a href="#asking-questions-of-the-program">Asking Questions of the Program</a></li>
  <li><a href="#compiling-the-spec-down-to-readable-python">Compiling the Spec Down to Readable Python</a></li>
  <li><a href="#the-tradeoffs-stated-precisely">The Tradeoffs, Stated Precisely</a></li>
  <li><a href="#what-this-does-not-establish">What This Does Not Establish</a></li>
  <li><a href="#the-scale-ceiling">The Scale Ceiling</a></li>
  <li><a href="#what-is-actually-novel-here">What Is Actually Novel Here</a></li>
  <li><a href="#when-to-do-this-and-when-not-to">When to Do This, and When Not To</a></li>
  <li><a href="#back-to-the-ladder">Back to the Ladder</a></li>
</ol>

<hr />

<h2 id="what-the-experiment-was">What the Experiment Was</h2>

<p>The thesis, in the form I wrote it down mid-session:</p>

<blockquote>
  <p>Instead of giving a pile of prose to an LLM and having it answer questions or convert it into code, with the prose forever dependent on a human or a model to interpret it as a “spec”, build a formal logical specification which is almost an intermediate language: portable, queryable, and convertible into executable code with a high degree of mechanisability.</p>
</blockquote>

<p>That is the <a href="/2026/08/24/rigour-by-design.html#flavours-of-specifications">spec ladder</a> argument with a concrete artifact attached. Domain: land administration, so titles, instruments, caveats and mortgages. Source: imperfect markdown. Output: a logic program plus provenance, where every asserted term traces back to the character span that justifies it.</p>

<p>The first constraint I intentionally set for myself was: <strong>all inference in the hot loop would be strictly local</strong>: I picked a 7–8B model on Ollama. That constraint comes from the documents: a land registry’s files cannot leave the building. And a 7–8B model cannot be trusted to author a formal specification. I wanted to answer the question: <em>what can you get out of a weak model, if a deterministic checker gets the final say?</em></p>

<hr />

<h2 id="version-one-and-why-it-was-deleted">Version One, and Why It Was Deleted</h2>

<p>The first architecture was the obvious one: bootstrap an ontology from the document, extract facts per segment, extract rules by having the model fill slots in fixed templates, compile to Prolog, validate with a meta-program, feed the findings back into a refinement loop.</p>

<p>It ran end to end on real statute text with <code class="language-plaintext highlighter-rouge">qwen2.5:14b</code> locally. The headlines:</p>

<ul>
  <li>Every output compiled to valid Prolog and loaded clean in <code class="language-plaintext highlighter-rouge">swipl</code>.</li>
  <li>Normalisation produced valid atoms for all 33 proposed entity types and 56 relations.</li>
  <li>Closed-world extraction <em>skipped</em> 38 fact candidates that used unknown relations or the wrong arity.</li>
  <li>Template-only rules made all 69 constraints well-formed by construction.</li>
</ul>

<p>The form was perfect. The <strong>meaning</strong> was atrocious, but the finding is probably not an outcome of using a smaller / weaker model. Some examples will suffice.</p>

<ul>
  <li>The model turned s.119(4), a <em>directional</em> prohibition reading “the Registrar shall not register a dealing prohibited by the caveat”, into a symmetric mutual exclusion: structurally impeccable, legally inverted.</li>
  <li>It converted nearly every relation into “every caveat must have X”. It filled typed argument slots with the literal word <code class="language-plaintext highlighter-rouge">"string"</code>, and these <em>promoted to accepted</em>, because the type checker validated literal <strong>positions</strong> while ignoring literal <strong>values</strong>.</li>
  <li>And given a bare citation line with no normative content at all, it hallucinated five rules with <strong>fabricated quotations</strong>.</li>
</ul>

<p>That last one is the most useful, because the fix was deterministic and worked completely: require every proposed rule to carry an evidence quote, and reject it unless the quote is a literal substring of the segment (this is not completely foolproof, provenance does not imply semantic similarity, but more on that later). All five were rejected. Paraphrased evidence correlates with bogus rules, and a substring check suppresses them with no model in the loop.</p>

<p>But no amount of guardrailing fixed the central problem. The representation was too weak to carry the meaning.</p>

<ul>
  <li><strong>Time was a string.</strong> <code class="language-plaintext highlighter-rouge">"2019-03-03"</code>, or worse, <code class="language-plaintext highlighter-rouge">"the third business day after filing"</code>. Prolog cannot order strings, so “what held before X”, “is this within 21 days” and “which registration came first” were all unaskable. Statutes are made almost entirely of those questions.</li>
  <li><strong>Identity was a name.</strong> Ids hashed <code class="language-plaintext highlighter-rouge">type:name</code>, which over-merges (every “mortgage” collapses to one) and under-merges (“the mortgage”, “first mortgage”, “second mortgage” fracture into three) <em>simultaneously</em>.</li>
  <li><strong>A type was one opaque atom,</strong> so every distinction got crammed into the label: <code class="language-plaintext highlighter-rouge">registered_mortgage</code> bakes an event outcome into a name where nothing can reason about it.</li>
  <li><strong>Facts had no context.</strong> <code class="language-plaintext highlighter-rouge">register(registrar, mortgage)</code> asserted flatly is implicitly true <em>everywhere</em>, which is false. Torrens land law turns precisely on the register differing from the world, and on what a party knew.</li>
</ul>

<p>So it all went: around 11,800 lines deleted in two commits, and the modules serving the old representation went with it. The temptation is always to keep the code and patch the model underneath it. But the stages <em>encoded</em> the bad representation, and no amount of patching could have helped.</p>

<hr />

<h2 id="the-representation-nine-predicates">The Representation: Nine Predicates</h2>

<p>The realisation is that simply writing clauses in a declarative language as permissive as Prolog, makes it harder to impose structure amenable to verification, and simply asking an LLM to impose the necessary constraints is not enough. You need <em>some</em> constraints on how express certain things. Of course, there are multiple formalisms that could be used; in this case, I used a (slightly modified) <code class="language-plaintext highlighter-rouge">ist</code> model, based on McCarthy’s <em>Notes on Formalizing Context</em> (IJCAI-93) - in itself a highly readable paper. The domain-neutral core is nine names in 97 lines, mentioning no dimension, no sort, no relation and no verb:</p>

<div class="language-prolog highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ss">ist</span><span class="p">(</span><span class="nv">Ctx</span><span class="p">,</span> <span class="nv">Statement</span><span class="p">).</span>                    <span class="c1">% Statement holds in Ctx</span>
<span class="ss">asserts</span><span class="p">(</span><span class="nv">Ctx</span><span class="p">,</span> <span class="nv">Record</span><span class="p">).</span>                   <span class="c1">% INDEX -- whose account. Not a dimension.</span>
<span class="ss">mark</span><span class="p">(</span><span class="nv">Ctx</span><span class="p">,</span> <span class="nv">Dim</span><span class="p">,</span> <span class="ss">at</span><span class="p">|</span><span class="ss">lower</span><span class="p">|</span><span class="ss">upper</span><span class="p">,</span> <span class="nv">Value</span><span class="p">).</span>  <span class="c1">% where Ctx sits on a dimension</span>

<span class="ss">dimension</span><span class="p">(</span><span class="nv">Dim</span><span class="p">).</span>                         <span class="c1">% declared per domain</span>
<span class="ss">within</span><span class="p">(</span><span class="nv">Dim</span><span class="p">,</span> <span class="nv">Point</span><span class="p">,</span> <span class="nv">Extent</span><span class="p">).</span>
<span class="ss">precedes</span><span class="p">(</span><span class="nv">Dim</span><span class="p">,</span> <span class="nv">P1</span><span class="p">,</span> <span class="nv">P2</span><span class="p">).</span>                  <span class="c1">% OPTIONAL, strict; its presence enables bounds</span>
<span class="ss">offset</span><span class="p">(</span><span class="nv">Dim</span><span class="p">,</span> <span class="nv">Point</span><span class="p">,</span> <span class="nv">Quantity</span><span class="p">,</span> <span class="nv">Point2</span><span class="p">).</span>   <span class="c1">% OPTIONAL -- point construction</span>

<span class="ss">at_or_before</span><span class="p">(</span><span class="nv">Dim</span><span class="p">,</span> <span class="nv">A</span><span class="p">,</span> <span class="nv">B</span><span class="p">).</span>                <span class="c1">% derived</span>
<span class="ss">holds_in</span><span class="p">(</span><span class="nv">Statement</span><span class="p">,</span> <span class="nv">QueryContext</span><span class="p">).</span>      <span class="c1">% derived -- the only query form</span>
</code></pre></div></div>

<p><strong><code class="language-plaintext highlighter-rouge">ist</code> is McCarthy’s “is true in context”</strong>. The generating rule is one sentence:</p>

<blockquote>
  <p>Anything with its own lifetime gets an id, and its value or extent attaches to that id. Anything that varies gets a dimension. Whether something “holds” is membership of a query position inside an extent.</p>
</blockquote>

<p>Three consequences follow.</p>

<p><strong>There is no Event Calculus.</strong> An event is a context positioned at a <em>point</em>, a state is a context with a <em>lower</em> bound and possibly an <em>upper</em> one, and persistence is extent-completion by derived <code class="language-plaintext highlighter-rouge">mark/4</code> rules. So inertia follows from any dimension carrying a directed order, which means the <code class="language-plaintext highlighter-rouge">version</code> dimension has it too. “In force from the 1993 Act until repealed” is structurally the same shape as “effective from registration until discharge”, and the same machinery answers <em>“was this a caveat under the Act as it stood in 1990?”</em> and <em>“was it effective in mid-2020?”</em></p>

<p><strong>Types are patterns you ask at a point.</strong> <code class="language-plaintext highlighter-rouge">caveat(Cav, Q)</code> is a rule, so the <code class="language-plaintext highlighter-rouge">registered_mortgage</code> problem disappears at the root.</p>

<p><strong>Closing conditions need no ordering logic.</strong> An extent is clipped if <em>any</em> upper mark falls in the gap, so “earliest terminator wins” fell out of the definition without being implemented. A caveat that can lapse at five years, be withdrawn expressly, or be deemed withdrawn fourteen days after an unrectified deficiency notice just has three <code class="language-plaintext highlighter-rouge">upper</code> mark rules, each citing its own provision, and they compose:</p>

<p><strong>Conjunction and Disjunction (AND and OR):</strong> Conjunction is two Prolog predicates joined by <code class="language-plaintext highlighter-rouge">,</code>. Disjunction is either the same Prolog predicate in two separate statements, with the disjunctive clauses, or predicates joined by <code class="language-plaintext highlighter-rouge">;</code>.</p>

<div class="language-prolog highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">% s.121(1)(b) "at the expiration of 5 years from the date of the lodgment"</span>
<span class="c1">%  -- an UPPER bound, and the reason offset/4 exists: the point is</span>
<span class="c1">%  CONSTRUCTED, not compared.</span>
<span class="ss">mark</span><span class="p">(</span><span class="ss">ctx</span><span class="p">(</span><span class="ss">effective</span><span class="p">(</span><span class="nv">Cav</span><span class="p">)),</span> <span class="ss">time</span><span class="p">,</span> <span class="ss">upper</span><span class="p">,</span> <span class="nv">T2</span><span class="p">)</span> <span class="p">:-</span>
    <span class="ss">ist</span><span class="p">(</span><span class="nv">CL</span><span class="p">,</span> <span class="ss">lodges</span><span class="p">(</span><span class="nv">_</span><span class="p">,</span> <span class="nv">Cav</span><span class="p">)),</span> <span class="ss">mark</span><span class="p">(</span><span class="nv">CL</span><span class="p">,</span> <span class="ss">time</span><span class="p">,</span> <span class="ss">at</span><span class="p">,</span> <span class="nv">T1</span><span class="p">),</span>
    <span class="ss">offset</span><span class="p">(</span><span class="ss">time</span><span class="p">,</span> <span class="nv">T1</span><span class="p">,</span> <span class="ss">years</span><span class="p">(</span><span class="m">5</span><span class="p">),</span> <span class="nv">T2</span><span class="p">).</span>

<span class="c1">% s.117(3) "if, within a period of not less than 14 days ... the caveat is</span>
<span class="c1">% not rectified, it shall be deemed to have been withdrawn".</span>
<span class="ss">mark</span><span class="p">(</span><span class="ss">ctx</span><span class="p">(</span><span class="ss">effective</span><span class="p">(</span><span class="nv">Cav</span><span class="p">)),</span> <span class="ss">time</span><span class="p">,</span> <span class="ss">upper</span><span class="p">,</span> <span class="nv">T2</span><span class="p">)</span> <span class="p">:-</span>
    <span class="ss">ist</span><span class="p">(</span><span class="nv">CN</span><span class="p">,</span> <span class="ss">notice_of_deficiency</span><span class="p">(</span><span class="nv">Cav</span><span class="p">)),</span> <span class="ss">mark</span><span class="p">(</span><span class="nv">CN</span><span class="p">,</span> <span class="ss">time</span><span class="p">,</span> <span class="ss">at</span><span class="p">,</span> <span class="nv">T1</span><span class="p">),</span>
    <span class="ss">offset</span><span class="p">(</span><span class="ss">time</span><span class="p">,</span> <span class="nv">T1</span><span class="p">,</span> <span class="ss">days</span><span class="p">(</span><span class="m">14</span><span class="p">),</span> <span class="nv">T2</span><span class="p">),</span>
    <span class="err">\</span><span class="o">+</span> <span class="p">(</span> <span class="ss">ist</span><span class="p">(</span><span class="nv">CR</span><span class="p">,</span> <span class="ss">rectified</span><span class="p">(</span><span class="nv">Cav</span><span class="p">)),</span> <span class="ss">mark</span><span class="p">(</span><span class="nv">CR</span><span class="p">,</span> <span class="ss">time</span><span class="p">,</span> <span class="ss">at</span><span class="p">,</span> <span class="nv">TR</span><span class="p">),</span>
         <span class="ss">at_or_before</span><span class="p">(</span><span class="ss">time</span><span class="p">,</span> <span class="nv">TR</span><span class="p">,</span> <span class="nv">T2</span><span class="p">)</span> <span class="p">).</span>
</code></pre></div></div>

<p>One rule, one provision, one citation. That is <a href="https://link.springer.com/article/10.1007/BF00871902">Bench-Capon and Coenen’s isomorphism principle</a> from 1992, and it is what turns an amendment into a mechanical edit instead of an audit. Fourteen provisions in the caveat library point at character spans into a content-addressed document version, and a gate checks that every declared provision actually cites text. On its first run that gate found a <em>dead</em> declaration: a provision nothing called, left over from an abandoned modelling attempt. What it found was dead vocabulary, which is a defect the compiler had no way to see.</p>

<p>Three sorts (<code class="language-plaintext highlighter-rouge">entity</code>, <code class="language-plaintext highlighter-rouge">quantity</code>, <code class="language-plaintext highlighter-rouge">text</code>) and four dimensions (<code class="language-plaintext highlighter-rouge">time</code>, <code class="language-plaintext highlighter-rouge">version</code>, <code class="language-plaintext highlighter-rouge">space</code>, <code class="language-plaintext highlighter-rouge">money</code>). “Dimension” turns out to mean <em>ordered value domain</em>, and positioning a context in one is optional: nothing is positioned in <code class="language-plaintext highlighter-rouge">money</code>, but its <code class="language-plaintext highlighter-rouge">precedes/3</code> and <code class="language-plaintext highlighter-rouge">offset/4</code> are exactly what “exceeds $500” and “the residue after costs” needed. Quantity arithmetic looked like a gap in the vocabulary and was actually a value domain nobody had declared. Four clauses closed it.</p>

<p><strong>A sort is a kind of thing; it is just not a derived one.</strong> <code class="language-plaintext highlighter-rouge">entity</code>, <code class="language-plaintext highlighter-rouge">quantity</code> and <code class="language-plaintext highlighter-rouge">text</code> are kinds – a pointable thing, a magnitude, an indecomposable value: but they are kinds the machinery needs, not kinds the Act recognises. A sort earns primitive status only when <em>generic machinery branches on it</em>, and the core branches on nothing. <code class="language-plaintext highlighter-rouge">ist</code>, <code class="language-plaintext highlighter-rouge">mark</code>, <code class="language-plaintext highlighter-rouge">within</code>, <code class="language-plaintext highlighter-rouge">precedes</code> and <code class="language-plaintext highlighter-rouge">holds_in</code> mention no sort at all. So the leaf set is not about what the statute talks about; it is about what cannot be decomposed. Everything the statute talks about is a rule:</p>

<div class="language-prolog highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ss">entity</span><span class="p">(</span><span class="ss">alice</span><span class="p">).</span>  <span class="ss">entity</span><span class="p">(</span><span class="ss">lot5</span><span class="p">).</span>  <span class="ss">entity</span><span class="p">(</span><span class="ss">cav1</span><span class="p">).</span>        <span class="c1">% scenario facts -- a sort, no context</span>

<span class="ss">land</span><span class="p">(</span><span class="nv">L</span><span class="p">,</span> <span class="nv">Q</span><span class="p">)</span> <span class="p">:-</span>                                       <span class="c1">% pattern library -- a derived type</span>
    <span class="ss">applies</span><span class="p">(</span><span class="ss">r_115_1</span><span class="p">,</span> <span class="nv">Q</span><span class="p">),</span>
    <span class="ss">entity</span><span class="p">(</span><span class="nv">L</span><span class="p">),</span>
    <span class="p">(</span> <span class="ss">ist</span><span class="p">(</span><span class="nv">_</span><span class="p">,</span> <span class="ss">concerns</span><span class="p">(</span><span class="nv">_</span><span class="p">,</span> <span class="nv">L</span><span class="p">))</span> <span class="p">;</span> <span class="ss">ist</span><span class="p">(</span><span class="nv">_</span><span class="p">,</span> <span class="ss">claims</span><span class="p">(</span><span class="nv">_</span><span class="p">,</span> <span class="nv">L</span><span class="p">))</span> <span class="p">).</span>
</code></pre></div></div>

<p>Nothing is born land. <code class="language-plaintext highlighter-rouge">lot5</code> is an <code class="language-plaintext highlighter-rouge">entity</code> in every context; it is <code class="language-plaintext highlighter-rouge">land</code> only where s.115(1) is in force and some caveat concerns it or some party claims it. The tell is arity: a sort takes no query context and cites nothing, because no section of the Act says lot 5 is pointable, whereas a derived type carries <code class="language-plaintext highlighter-rouge">Q</code> and exactly one citation. <code class="language-plaintext highlighter-rouge">agent</code> fails the criterion for the same reason – a company is an agent in a dealing and an object in a merger, so agency is not what a thing <em>is</em>. What the caveat library actually needed in place of <code class="language-plaintext highlighter-rouge">party</code> was <code class="language-plaintext highlighter-rouge">caveator/2</code>, <code class="language-plaintext highlighter-rouge">caveatee/2</code> and <code class="language-plaintext highlighter-rouge">claimant/2</code>: participation roles, each derived, each cited.</p>

<hr />

<h2 id="where-the-model-sits-and-the-gates-that-contain-it">Where the Model Sits, and the Gates That Contain It</h2>

<p>The founding tenet: <strong>the LLM never writes Prolog and never invents structure.</strong> It fills schema-constrained slots, and deterministic code compiles terms.</p>

<pre><code class="language-mermaid">flowchart TD
    subgraph OFF[Offline -- once per domain]
        DOC[statute / policy wording] --&gt; FM[frontier model\nproposes a pattern library]
        FM --&gt; G1{Gate 1 + 1.5\nshape · content}
        G1 --&gt;|machine-readable violations| FM
        G1 --&gt;|accepted| LIB[pattern library\nrelations + cited rules]
    end
    subgraph HOT[Hot loop -- per segment, NOT BUILT]
        SEG[document segments] --&gt; LOCAL[local 7-8B\nentities · relations · dates only\nnever Prolog, never a type name]
        LOCAL --&gt; DET[deterministic compile\nto ist / mark]
    end
    LIB --&gt; G2{Gate 2\nrun against an\nINDEPENDENT corpus}
    DET --&gt; G0{Gate 0\ncorpus vs declarations}
    G0 --&gt; G2
    G2 --&gt; RUN([runnable program\n+ provenance])

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef llm fill:#ede0f8,stroke:#7b2d9b,color:#3b0764
    classDef gate fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef missing fill:#fce7f3,stroke:#be185d,color:#831843
    class FM,LOCAL llm
    class G0,G1,G2,RUN gate
    class SEG,DET missing
</code></pre>

<p>The dashed-in-spirit box is real: <strong>the hot loop does not exist yet.</strong> More on that below.</p>

<p>There are four gates, and none subsumes another.</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Reads</th>
      <th>Catches</th>
      <th>In the repair loop?</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Gate 0</strong> <code class="language-plaintext highlighter-rouge">fact_check.pl</code></td>
      <td>a <em>corpus</em>, against a library’s declarations</td>
      <td>undeclared relations, arity mismatches, a mark kind contradicting the relation’s declared class</td>
      <td>yes</td>
    </tr>
    <tr>
      <td><strong>Gate 1</strong> <code class="language-plaintext highlighter-rouge">shape_check.pl</code></td>
      <td>the library <em>file</em></td>
      <td>grammar: legal goals, sorts, exactly one cited provision per rule</td>
      <td>yes</td>
    </tr>
    <tr>
      <td><strong>Gate 1.5</strong> <code class="language-plaintext highlighter-rouge">content_check.pl</code></td>
      <td>the library <em>file</em></td>
      <td>a library that is perfectly on-grammar and authors nothing</td>
      <td>yes</td>
    </tr>
    <tr>
      <td><strong>Gate 2</strong> <code class="language-plaintext highlighter-rouge">acceptance.pl</code></td>
      <td>the library <strong>run</strong> against a corpus</td>
      <td>rules that derive nothing, rules that derive everything, two rules with identical extensions</td>
      <td><strong>no, deliberately</strong></td>
    </tr>
  </tbody>
</table>

<p>Gate 2 sits outside the loop on purpose. It needs a corpus, and <strong>a corpus authored to satisfy the gate compromises the gate.</strong> A model that writes its own fixtures writes them to agree with itself.</p>

<h2 id="feedback">Feedback</h2>
<p>The repair contract is blunt. A checker returning a negative verdict wants a repair, and the violation list goes back as the next prompt. A checker that <em>raises</em> is saying no repair exists, and the loop propagates it. Exhausting the round budget counts as a <strong>result</strong> that the caller has to interpret.</p>

<p><strong>The gate must return specific, machine-readable violations.</strong> <code class="language-plaintext highlighter-rouge">undeclared_relation(effective/1)</code> is actionable. “Try again” is not. An early run reported “0 violations” four times in a row and gave up, which is the degenerate case of the same principle: a rejection carrying nothing the model can act on is just a refusal.</p>

<hr />

<h2 id="what-the-gates-actually-caught">What the Gates Actually Caught</h2>

<p><strong>Land Titles Act, ss.115–121.</strong> <code class="language-plaintext highlighter-rouge">claude-sonnet-4-5</code> via Bedrock at temperature 0, chosen over the strongest available model deliberately, because a weaker one tests the gate harder. The first one-shot experiment came back <code class="language-plaintext highlighter-rouge">SHAPE_FAIL</code> with <strong>13 violations</strong>, and the split is the finding. Everything the prompt warned about, it got right: event/state classes assigned correctly, rule-precedence machinery left untouched, no context variable shared across conjuncts, a core derived type all but identical to the reference library’s, plus 28 derived rules and 14 provisions cited. Everything it got wrong was <strong>bookkeeping</strong>. The silent semantic kind, which took three attempts to get right in the reference libraries with a human reviewing each one, never appeared. Wired into a repair loop, the same task converged in <strong>two rounds</strong>: two violations, then <code class="language-plaintext highlighter-rouge">SHAPE_OK</code> with 17 relations, 16 provisions, 25 derived rules and 9 derived mark rules. A second domain, the NY standard fire policy, chosen because an insurer’s wording is copyright and this one is a statutory form, behaved identically: 10 violations in round one, <code class="language-plaintext highlighter-rouge">SHAPE_OK</code> in round two, and again everything caught was vocabulary discipline.</p>

<p>And the accepted library was <strong>better than the reference library in one place</strong>. For s.119(1) it declared acceptance as an <em>event</em> and being-in-order as a <em>state</em> whose lower bound derives from that event, where the reference library treats the latter as the event itself. One call plus a gate applied the discipline the prompt teaches, at a point the reviewed interactive sessions had let slide. More rounds with a human in each of them is not uniformly better than one round and a checker.</p>

<p>Here is every defect worth reporting, and which gate saw it:</p>

<table>
  <thead>
    <tr>
      <th>Defect</th>
      <th>Caught by</th>
      <th>Consequence</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>6 relations used, never declared</td>
      <td>Gate 1</td>
      <td>8 rules written over a term absent from its own vocabulary</td>
    </tr>
    <tr>
      <td>a context term naming the wrong statement</td>
      <td>Gate 1</td>
      <td>bookkeeping; repaired in one round</td>
    </tr>
    <tr>
      <td>a fluent context passed where a query context belongs</td>
      <td><strong>nothing</strong></td>
      <td>fails <em>silently</em>; the gate hole a model found</td>
    </tr>
    <tr>
      <td>a condition that constrained nothing</td>
      <td>Gate 2</td>
      <td>“Alice may lodge lot 5 as a caveat” was derivable</td>
    </tr>
    <tr>
      <td>an <em>acceptance</em> (an event) read with <code class="language-plaintext highlighter-rouge">holds_in</code></td>
      <td>Gate 2</td>
      <td>the duty to notify existed for one day, then disappeared</td>
    </tr>
    <tr>
      <td>two predicates never once run</td>
      <td>Gate 2</td>
      <td>no fixture exercised the provision they encoded</td>
    </tr>
    <tr>
      <td>fixtures <code class="language-plaintext highlighter-rouge">discontiguous</code> but not <code class="language-plaintext highlighter-rouge">multifile</code></td>
      <td>Gate 2</td>
      <td>clauses silently discarded; false vacuity, no error</td>
    </tr>
    <tr>
      <td>a citation carried by all 63 rules, defined by none</td>
      <td>Gate 2</td>
      <td>every rule failed on an unknown procedure</td>
    </tr>
    <tr>
      <td>a library on-grammar, fully cited, authoring nothing</td>
      <td>Gate 1.5</td>
      <td>12, 8 and 30 authoring rules on the shipped libraries, against <strong>0</strong></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">c1</code> appearing in 36 of 40 scenario files</td>
      <td>Gate 0</td>
      <td>29 systematic mark-kind errors, down to 6 after namespacing</td>
    </tr>
  </tbody>
</table>

<p>Five things follow.</p>

<p><strong>Gate 1 is structurally blind to meaning.</strong> Every Gate 2 row above is grammatically perfect. A gate that reads the file can only check the file, and only running it against a corpus finds a rule that derives nothing, derives everything, or derives the wrong thing. The citation row is the sharpest case: the shape gate asks whether a rule <em>carries</em> a citation, and never whether one <em>resolves</em>.</p>

<p><strong>The silent row is the one worth studying.</strong> The model wrote <code class="language-plaintext highlighter-rouge">\+ holds_in(extended(Cav), ctx(effective(Cav)))</code>. <code class="language-plaintext highlighter-rouge">holds_in</code> reads <code class="language-plaintext highlighter-rouge">at</code> marks off its second argument, a fluent context carries <code class="language-plaintext highlighter-rouge">lower</code> and <code class="language-plaintext highlighter-rouge">upper</code> instead, so the goal fails without erroring, and no gate said anything because that argument position was unconstrained. It is now checked, and the check exists because a model did something nobody had thought to forbid. I had not expected the loop to find gaps in the grammar itself, and this is the one benefit of it I would not have predicted.</p>

<p><strong>The recurring error got made syntactic.</strong> The event/state conflation appeared three times and survived human review each time, so relations now declare a class, as in <code class="language-plaintext highlighter-rouge">relation(lodges, [entity,entity], event)</code>. The empirical basis is that the class is a <em>function of the relation</em>: across the whole caveat corpus, every extracted relation had exactly one mark kind. So the gate can now reject reading an event as a state, both historical instances are added as tests and caught, and the mark kind is assigned <strong>deterministically from the declaration</strong>, which takes the hardest judgment in the representation out of the extraction model’s hands. It emits a relation, its arguments and a date, and deterministic code decides whether that is a point or a bound. <em>Find the error you keep making, then find a declaration that makes it syntactic.</em> That is the transferable technique here, and it applies well outside Prolog and law.</p>

<p><strong>An inert library is a real failure mode, and the gap turned out to be total.</strong> The screen-validation library asserted “this notice has not expired” as a <em>corpus fact</em>, where the source document gave the expiry <strong>date</strong>. The document contained everything needed to derive expiry, and the library copied a flag across instead of writing the rule. Two other candidate smells were tried and <strong>discarded for firing on the reference libraries</strong>, which I mention because negative results in heuristic design almost never get written down. One of them found 24 instances in one authored library and 0 in another doing the identical thing under different names, so what it measured was naming.</p>

<p><strong>The residual 6 corpus errors are a finding.</strong> A classification like “this was a fire” or “this was lightning” is neither an event nor a bounded state. The encoder dates it because the narrative dates it, and the library declares it a state. That is a genuine modelling question the representation has not settled, and it surfaced only because a gate counted.</p>

<hr />

<h2 id="asking-questions-of-the-program">Asking Questions of the Program</h2>

<p>A specification you cannot interrogate is barely a specification. So there is a query tier: a question in, a Prolog transcript and an answer out. Four steps, and only the first and last involve a model:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>question -&gt; a CHECKED query structure           (model, gated)
         -&gt; Prolog goals at one or more points  (deterministic)
         -&gt; answer + evidence read off the marks (Prolog)
         -&gt; prose, printed BESIDE the transcript (model)
</code></pre></div></div>

<p>The model never writes Prolog text. It picks a predicate from the introspected vocabulary, its arguments, and the points to ask at, and deterministic code renders goals and checks them against the loaded program <em>first</em>. Free text cannot be gated, because a goal string can name a predicate that does not exist and the only way to find out is to run it, whereas a structure is checkable in a few lines. The gate is strict about arity for one reason: <strong>a goal with the wrong arity fails silently, and a silent failure reads exactly like a well-formed “no.”</strong></p>

<p>Asking at <em>several</em> points is the normal case. Most real questions about a statute are comparative, and the interesting answer is the one that changes:</p>

<blockquote>
  <p><em>Alice lodged a caveat over lot 5 in March 2019, and a buyer now wants dealing1 registered against that lot. Is the Registrar barred from registering it in mid-2020, and would that still be so in mid-2025?</em></p>
</blockquote>

<div class="language-prolog highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">?-</span> <span class="ss">must_not_register</span><span class="p">(</span><span class="ss">dealing1</span><span class="p">,</span> <span class="ss">q_mid_2020</span><span class="p">).</span>    <span class="c1">% yes</span>
<span class="o">?-</span> <span class="ss">must_not_register</span><span class="p">(</span><span class="ss">dealing1</span><span class="p">,</span> <span class="ss">q_mid_2025</span><span class="p">).</span>    <span class="c1">% no</span>

<span class="ss">evidence</span> <span class="p">(</span><span class="ss">marks</span> <span class="ss">bounding</span> <span class="ss">the</span> <span class="ss">relevant</span> <span class="ss">contexts</span><span class="p">)</span><span class="o">:</span>
   <span class="ss">effective</span><span class="p">(</span><span class="ss">cav1</span><span class="p">)</span><span class="o">:</span> <span class="ss">time</span> <span class="ss">lower</span> <span class="o">=</span> <span class="ss">d</span><span class="p">(</span><span class="m">2019</span><span class="p">,</span><span class="m">3</span><span class="p">,</span><span class="m">3</span><span class="p">)</span>
   <span class="ss">effective</span><span class="p">(</span><span class="ss">cav1</span><span class="p">)</span><span class="o">:</span> <span class="ss">time</span> <span class="ss">upper</span> <span class="o">=</span> <span class="ss">d</span><span class="p">(</span><span class="m">2024</span><span class="p">,</span><span class="m">3</span><span class="p">,</span><span class="m">3</span><span class="p">)</span>
   <span class="ss">lodges</span><span class="p">(</span><span class="ss">alice</span><span class="p">,</span><span class="ss">cav1</span><span class="p">)</span><span class="o">:</span> <span class="ss">time</span> <span class="ss">at</span>  <span class="o">=</span> <span class="ss">d</span><span class="p">(</span><span class="m">2019</span><span class="p">,</span><span class="m">3</span><span class="p">,</span><span class="m">3</span><span class="p">)</span>
</code></pre></div></div>

<p>The date that decides this, 3 March 2024, appears nowhere in the source documents. It is constructed by the five-year rule in s.121(1)(b), and the explanation cites it because the engine gathers evidence <strong>mechanically</strong>: the marks bounding every context whose statement mentions an entity the question is about. Every date in the explanation is read off the program. The prose step is the weakest link and is treated as such. It is given the transcript and nothing else, told not to introduce facts, and always printed <em>beside</em> the run. <strong>An explanation nobody can check is worse than no explanation.</strong></p>

<p>Two results from that tier are worth reporting honestly.</p>

<p><strong>The near-miss the gate cannot catch.</strong> Asked whether Alice’s underlying claim was <em>justified</em>, the model composed <code class="language-plaintext highlighter-rouge">claimant(alice, Q)</code>: valid vocabulary, real entity, and <strong>a different question</strong>, since being a claimant is not the same as having a good claim. The gate checks that a predicate exists. It never checks that the predicate answers what was asked. <strong>Vocabulary checking is not semantic checking</strong>, and no amount of grammar work makes it so. Both fixes live outside the gate: an explicit route to decline, because a system that cannot say “I can’t” will always say <em>something</em>, and human-readable glosses so near-neighbours can be distinguished in prose where nothing mechanical can separate them. Declining is never retried, since retrying only pressures the model into naming an adjacent predicate.</p>

<p>Which is the point of the pair, because next door sits a question that is <em>correctly</em> declined. Whether Alice’s claim is <em>good</em> needs contract and property law, evidence, and a court. That is the law itself, and no gap in the library will fix it. Whether the Registrar <strong>must not consider</strong> it is squarely answerable, because s.117(5) says he must not. A statute’s refusal to decide something is itself a provision with content, and the system knows which side of that line it is on.</p>

<p><strong>The lossy rendering.</strong> In three recorded examples the query enumerated solutions through an unbound variable and the transcript surfaced only the first. The prose tier then said, correctly, <em>“the transcript does not settle the question.”</em> The Prolog was right, the presentation layer was lossy, and the interpretation step refused to fill the gap by invention. The design worked and the implementation did not. A tier that declines is the better failure, because the alternative is inventing the other three answers.</p>

<hr />

<h2 id="compiling-the-spec-down-to-readable-python">Compiling the Spec Down to Readable Python</h2>

<p>If the specification is the artifact of record, you should be able to project it into the language you actually ship. So there is a generator: a pattern library in, a self-contained Python module out, with one dataclass per entity kind, one method per derived predicate, and one period method per fluent.</p>

<p><strong>Attempt one was rejected, and it passed every correctness test.</strong> It was a Prolog-to-Python transpiler: nested closures over a store, generated names like <code class="language-plaintext highlighter-rouge">_derived_mark_1</code> and <code class="language-plaintext highlighter-rouge">_Anon29</code>, <code class="language-plaintext highlighter-rouge">continue</code> loops. It agreed with Prolog on every enumerated case and it was unreadable, which defeats the entire purpose. Attempt two is expression-first, so a conjunction is <code class="language-plaintext highlighter-rouge">and</code>, an existential is <code class="language-plaintext highlighter-rouge">any(...)</code>, a negation is <code class="language-plaintext highlighter-rouge">not</code>. Same correctness bar, output a human can review.</p>

<p>The constraint that decided everything: <strong>readability information lives in the spec, never in the generator.</strong> A generator that guessed <code class="language-plaintext highlighter-rouge">lodges(Party, Caveat)</code> should render as “lodged_by” would be land law in disguise, custom to one statute. Every readable name comes from a declaration the library author wrote. The mortgages library declares <em>none</em> of them and still compiles end to end against the raw statement store, which is what degrading gracefully has to mean, and it is a test.</p>

<p>Here is what comes out for the caveat lapse rules quoted earlier:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">effective_period</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">cav</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Extent</span><span class="p">:</span>
    <span class="sh">"""</span><span class="s">When effective(cav) holds, on the time axis.

    s.121(1)(b): </span><span class="sh">"</span><span class="s">at the expiration of 5 years from the date of the
    lodgment of the caveat, ...</span><span class="sh">"</span><span class="s">
    s.117(3): </span><span class="sh">"</span><span class="s">if, within a period of not less than 14 days ... the caveat
    is not rectified, it shall be deemed to have been withdrawn.</span><span class="sh">"</span><span class="s">
    </span><span class="sh">"""</span>
    <span class="n">caveat</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">registry</span><span class="p">.</span><span class="n">caveats</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="n">cav</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">caveat</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">caveat</span><span class="p">.</span><span class="n">lodged_by</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="nc">Extent</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="sh">"</span><span class="s">time</span><span class="sh">"</span><span class="p">,</span> <span class="n">stated</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
    <span class="c1"># without the statement there is no context to hang marks on, and an
</span>    <span class="c1"># unstated fluent covers nothing, which differs from an unconstrained
</span>    <span class="c1"># one, which covers everything.
</span>    <span class="bp">...</span>
    <span class="k">if</span> <span class="n">caveat</span><span class="p">.</span><span class="n">lodged_by</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">caveat</span><span class="p">.</span><span class="n">lodged_on</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">ends</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="nf">add_years</span><span class="p">(</span><span class="n">caveat</span><span class="p">.</span><span class="n">lodged_on</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>              <span class="c1"># s.121(1)(b)
</span>    <span class="k">if</span> <span class="n">caveat</span><span class="p">.</span><span class="n">deficiency_notice_on</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="ow">not</span> <span class="p">(</span>
        <span class="n">caveat</span><span class="p">.</span><span class="n">rectified_on</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span>
        <span class="ow">and</span> <span class="n">caveat</span><span class="p">.</span><span class="n">rectified_on</span> <span class="o">&lt;=</span> <span class="n">caveat</span><span class="p">.</span><span class="n">deficiency_notice_on</span> <span class="o">+</span> <span class="nf">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>
    <span class="p">):</span>
        <span class="n">ends</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">caveat</span><span class="p">.</span><span class="n">deficiency_notice_on</span> <span class="o">+</span> <span class="nf">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">14</span><span class="p">))</span>  <span class="c1"># s.117(3)
</span></code></pre></div></div>

<p>The statutory limits are on the page as ordinary date arithmetic, the citation is in the docstring quoting the provision, and there is no Prolog runtime hiding behind it. An equivalence suite runs every predicate through both engines and diffs. Two details from building it generalise.</p>

<p><strong>Never emit a <code class="language-plaintext highlighter-rouge">...</code> stub.</strong> The first cut emitted <code class="language-plaintext highlighter-rouge">...</code> for every derived predicate. <code class="language-plaintext highlighter-rouge">...</code> evaluates to <code class="language-plaintext highlighter-rouge">None</code>, which is falsy, so each stubbed rule silently answered <strong>“no”</strong>, indistinguishably from a rule that means it. Anything the compiler cannot render faithfully now <em>raises</em>, naming the clause, the goal and the reason, and the module exports an <code class="language-plaintext highlighter-rouge">UNTRANSLATED</code> list so you can see which methods are trustworthy without running anything.</p>

<p><strong>The equivalence suite caught four defect classes, each giving a plausible wrong answer:</strong></p>

<table>
  <thead>
    <tr>
      <th>Defect</th>
      <th>What it did</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>an index running opposite to a dimension</td>
      <td>silence about a dimension means <em>unconstrained</em>, while a context asserting no record answers <em>no</em> record-scoped question; the reversed polarity made two copies of the data disagree</td>
    </tr>
    <tr>
      <td>an empty extent read as unconstrained</td>
      <td>a loader bug dropped a field, the date came out <code class="language-plaintext highlighter-rouge">None</code>, empty read as “no bounds”, and <strong>every caveat was effective forever</strong>. <code class="language-plaintext highlighter-rouge">stated=False</code> covers nothing, absent marks cover everything, and that asymmetry is the one to watch</td>
    </tr>
    <tr>
      <td>a dropped conjunct</td>
      <td>a derived call with an unbound argument emitted the scan and discarded the call, so it answered yes for any entity at all</td>
    </tr>
    <tr>
      <td>a rebound parameter</td>
      <td>a store pattern named its loop targets after already-bound variables, widening “this mortgage” to “any mortgage”</td>
    </tr>
  </tbody>
</table>

<p>Every one produces confident, well-formed, wrong answers, and none is visible by reading the output. That is the concrete argument for keeping two engines and diffing them, instead of trusting a translation.</p>

<hr />

<h2 id="the-tradeoffs-stated-precisely">The Tradeoffs, Stated Precisely</h2>

<table>
  <thead>
    <tr>
      <th>Decision</th>
      <th>What it buys</th>
      <th>What it costs</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Nine-predicate domain-neutral core</td>
      <td>Two Parts of one Act plus an insurance policy form fit with <strong>no core changes</strong>. Rule validity over legislative versions uses the same machinery as facts over time.</td>
      <td>Sort conformance became nearly vacuous: collapsing to <code class="language-plaintext highlighter-rouge">entity</code> plus <code class="language-plaintext highlighter-rouge">quantity</code> leaves quantity as the only checkable sort. Real cost, knowingly paid.</td>
    </tr>
    <tr>
      <td>Types derived, never stored</td>
      <td>Kills <code class="language-plaintext highlighter-rouge">registered_mortgage</code>-style label pollution outright.</td>
      <td>Every type question costs a resolution instead of a lookup. Irrelevant at this scale, unknown at corpus scale.</td>
    </tr>
    <tr>
      <td>Frontier model writes Prolog offline; local model never does</td>
      <td>One call per domain, and the artifact is small, static and checked. No second copy of the grammar.</td>
      <td>Breaks the founding tenet in one place. And the local tier it protects <strong>does not exist yet</strong>, so the split is architecturally justified and empirically untested.</td>
    </tr>
    <tr>
      <td>Gate 2 outside the repair loop</td>
      <td>The acceptance corpus stays independent of the model that wrote the rules.</td>
      <td>A whole class of defect is only found <em>after</em> the loop reports success, and every serious defect so far was in that class. The independence is also only as real as the sourcing.</td>
    </tr>
    <tr>
      <td>“It checks; it does not compute”</td>
      <td>Aggregates need no arithmetic if their value is <em>stated</em>, and for document extraction it usually is. Priority needs no sorting if rank is a declared position. Several problems that looked like they needed a computation layer went away.</td>
      <td>Wrong side of the line for any engine that must <strong>perform</strong> a distribution instead of testing one.</td>
    </tr>
    <tr>
      <td>One unstratified rule shape accepted</td>
      <td><code class="language-plaintext highlighter-rouge">holds_in</code> inside a <code class="language-plaintext highlighter-rouge">mark</code> body is genuinely useful when deriving new bounds.</td>
      <td>It can fail to terminate. Accepted deliberately, reproduced in a fixture, and the failure is <strong>loud</strong>: a stack trace naming the cycle.</td>
    </tr>
    <tr>
      <td>Provenance as positioned statements</td>
      <td>A provision’s span <strong>varies by version</strong>: s.115 as enacted and as amended are different words in different documents. An amendment adds a citation with its own version bounds and the machinery picks the right one.</td>
      <td>More indirection than a citation string on the rule.</td>
    </tr>
  </tbody>
</table>

<p>Two things I expected to be hard were not. <strong>Partial holding</strong>, as in “according to the extent of his interest” or “freed from the mortgage absolutely or to any lesser extent”, looks like it needs graded truth and does not, and the commercial legal DSLs agree: eFLINT parameterises acts, Symboleo parameterises obligations, Catala computes an amount, and <strong>none of them makes “holds” partial</strong>. A quantity that <em>changes</em> is a reified term whose value varies by context. An extent that <em>limits</em> is an ordinary comparison on the money dimension. <strong>Deeming</strong> is likewise just a fact whose bound the statute supplies.</p>

<p><em>Harder than expected:</em> <strong>rule precedence.</strong> An <code class="language-plaintext highlighter-rouge">overrides/2</code> relation was declared for it, is used in exactly <strong>zero</strong> rules across two libraries, and both of the Act’s precedence forms defeated it. A conditional carve-out (“except as otherwise provided in s.129(1)”) encoded as an override disabled the whole section, so no dealing was ever prohibited, because the carve-out displaces the section only for the dealings the other section reaches. It is a condition on the dealing, and it lives inside the rule. And the case the mechanism was <em>designed</em> for, “despite any other provision of this Act”, is worse: overriding the general priority rule kills the registration ordering that the overriding provision itself depends on. Both encode correctly as an exception clause inside the general rule, which is Catala’s prioritised-default shape. A reader who sees “except” and reaches for a precedence relation will silently disable a section, and nothing will error.</p>

<hr />

<h2 id="caveats">Caveats</h2>

<p>This is the section I most want people to read.</p>

<p><strong>Nothing extracts anything.</strong> Every fact in every fixture was put into the repository by a model, interactively or by a generation script, and none of it was extracted from a document. There is no seam from a document to <code class="language-plaintext highlighter-rouge">ist</code> and <code class="language-plaintext highlighter-rouge">mark</code>. The founding premise is extracting a model from imperfect markdown with a local 7–8B model, and in the current architecture that is <strong>entirely untested</strong>. The demo answers questions about a knowledge base assembled in directed sessions, which is exactly the part a viewer will assume was automated. Building it needs <em>instrument</em> documents, meaning a folio, a lodged caveat, a judgment, and this corpus does not contain them: the Act gives rules, and records live elsewhere.</p>

<p><strong>There is no baseline, and the baseline is the wrong comparison anyway.</strong> I never measured whether a strong model, handed the 6KB statute extract and the same eleven questions, answers them all correctly with no machinery at all. It very likely does. But answer quality was never the axis this buys on, and running the race on that axis concedes the wrong thing.</p>

<p>What the apparatus establishes <em>automatically</em> is that the answer is <strong>reproducible</strong>, and that is a property of the artifact. The same question asked at the same points returns the same answer every time. The date that decides it, 3 March 2024, is constructed by a cited rule, so anyone with the program and the statute can reconstruct it. The evidence is gathered mechanically off the marks. Two independent engines agree or the diff fails. None of that needs an experiment to establish, because it follows from what the thing <em>is</em>, which is a deterministic program with citations. A model asked the same question twice is not obliged to answer the same way, and cannot show you the provision that made the difference. That is the comparison worth making, and it does not turn on which one is smarter.</p>

<p>The adverb <em>automatically</em> does not imply correctness. Reproducibility holds <strong>assuming the encoding is a correct reading of the source</strong>, and that assumption is currently not checked. Of the four properties the case rests on, two come free with the representation: reproducibility and reconstructibility. As-at-date reasoning comes free with dimensions, though it is untested at any real scale. Consistency across thousands of documents is genuinely unmeasured, and cannot be measured until the hot loop exists. Faithful reproduction and correctness are different properties, and I have attempted to demonstrate that the first one is achievable through deterministic gates; the second remains an open question.</p>

<p><strong>The gates check hygiene.</strong> No gate establishes that a library is a correct <em>reading</em> of its source. A library can be well-formed, non-vacuous, non-degenerate, fully cited, and still misread the provision it points at. <strong>Every serious defect found so far was of that kind.</strong> A human reading rule against provision is still necessary, made cheap by one-rule-one-provision, and nowhere near eliminated.</p>

<p><strong>The rules and the fixtures they are checked against share an author.</strong> This is the sharpest consequence of everything being model-written. The land corpus and the land libraries came out of the same sessions, so a shared misreading would produce a library and a fixture that agree with each other and both diverge from the statute, and every gate would report success. The insurance experiment was designed specifically to break that circularity, and it is the experiment that did not finish. So the independence the architecture depends on is currently a design commitment that nothing has demonstrated.</p>

<p><strong>Sample size is small and the prompt was loaded.</strong> Two Parts of one Act plus one policy form, and the “avoided all four failure modes” result is a handful of runs with those four failure modes spelled out in the prompt. Two further runs did not complete and are not counted.</p>

<p><strong>The second-domain experiment is incomplete.</strong> The design was a genuine blind test: one call writes forty scenarios with expected verdicts from the policy alone, seeing no grammar and no hint that a logic model exists; that oracle is committed to git <strong>before</strong> the library is authored, so commit order is the evidence it was blind; a third call encodes the scenarios into facts <em>without ever seeing the verdicts</em>. The library was authored, the corpus encoded, the corpus gate built and run. <strong>The final diff, derived answers against withheld verdicts, was never run.</strong> So the strongest evidence this experiment was designed to collect remains uncollected, and I would rather say that than quote the parts that did finish as though they were the result.</p>

<p><strong>Coreference is untouched, and it is the biggest live risk.</strong> A wrong entity id does not produce an error. It produces a well-formed <em>false statement</em>: a caveat whose lodgement and acceptance get different ids ends up with no lower bound and reads as effective since the dawn of time. The negation ambiguity compounds it, because <code class="language-plaintext highlighter-rouge">\+ rectified(Cav)</code> reads “not rectified”, and in a lossy extraction it <em>also</em> reads “we did not extract the rectification”. Those give opposite legal outcomes and the program cannot tell them apart.</p>

<hr />

<h2 id="the-scale-ceiling">The Scale Ceiling</h2>

<p>The authoring loop handles a policy wording and a dozen sections of a statute. It does not reach the whole Act, and the reason has nothing to do with the context window, which is the interesting part.</p>

<p>The caveat library covers 7 real sections in 652 lines with 37 rules, so roughly 93 lines and 5 rules per section. The Land Titles Act has 184 real sections, which extrapolates to something like 17,000 lines and 900 rules. No single call produces that, however large its input window, because the binding constraint is the <strong>output</strong> budget, and the repair contract makes it worse by demanding the entire file back every round. The second constraint is that the discipline decays over the length of a generation. The four failure modes the prompt warns about are exactly the ones a model stops watching for as the output gets longer, and what that produces is misreadings, which the shape gate cannot catch.</p>

<p>There is a design for this. Decompose the document into a <em>structure map</em> of citable spans, cluster, author per cluster, reconcile. Its central commitment is to <strong>assume nothing about document structure</strong>, because the real target is validation-rule tables, standard operating procedures, and design documents intermingled with architecture docs. Any design keyed on sections and numbered clauses degrades <em>silently</em> on most of that: a document with no citations yields a reference graph with no edges, a perfectly valid graph that produces one cluster per unit and no error anywhere. The one guard in it worth stealing regardless: a span’s recorded text must be a <strong>verbatim substring</strong> of the source at the recorded offsets. Total, free, mechanical, and the same move as the evidence gate that killed five hallucinated rules on the very first run.</p>

<p>That design is written down. It is not built.</p>

<hr />

<h2 id="what-is-actually-novel-here">What Is Actually Novel Here</h2>

<p>Very little, and I want to be blunt about it, because a project like this generates a lot of prose that reads as claims.</p>

<p><code class="language-plaintext highlighter-rouge">ist(c, p)</code> is McCarthy, 1993, lifted whole. Contexts carrying coordinates is Guha’s 1991 thesis and Cyc’s microtheories. Statute-as-logic-program is Sergot, Sadri and Kowalski’s British Nationality Act paper in <em>CACM</em>, 1986, which is forty years old. One-rule-one-provision is Bench-Capon and Coenen, 1992, cited by name in the code. Derived types as patterns is ordinary Prolog. Fluents and inertia are Event Calculus, same 1986 vintage. Storing extents as endpoint facts instead of interval terms is how temporal databases have stored valid-time for decades. “LLM writes a DSL, a checker rejects it, repair” is a standard pattern by now, and “natural language to structured query to execution to natural language” is text-to-SQL with a validator. The reified-value pattern I made the biggest fuss about is McCarthy and Buvač’s <code class="language-plaintext highlighter-rouge">value(c, term)</code>, and it was <strong>already in the design document’s own bibliography</strong>, so the project rediscovered a citation it had in front of it. Catala, meanwhile, already does the defeasibility part properly, with prioritised defaults as a first-class construct where this project has exception clauses by convention.</p>

<p>Three things might be worth something, hedged:</p>

<ul>
  <li><strong>Turning your most frequent modelling error into a grammar violation.</strong> I conflated an event with the fluent it starts three separate times. Declaring the relation’s class made the error <em>syntactically</em> checkable, and both historical instances are now caught as tests. The general move transfers.</li>
  <li><strong>“It checks; it does not compute”</strong> as an explicit scoping decision. Several hard problems went away, and for document extraction it is the right side of the line, though the mechanism underneath, uninterpreted function symbols, is entirely standard.</li>
  <li><strong>Dimensions versus indices.</strong> “No order at all means it is not a dimension” killed a coordinate that was wrong and replaced it with a plain index. A clarification, and I would not call it a discovery.</li>
</ul>

<p>A careful assembly of forty-year-old ideas, with one or two sharp engineering moves and a scoping decision that does real work. That is the honest summary, and it is also the point of the <a href="/2026/08/24/rigour-by-design.html#what-ai-actually-changed">previous post</a>: <strong>none of this was ever wrong, it was expensive.</strong> What changed is that encoding it got cheap enough to try on a weekend.</p>

<hr />

<h2 id="when-to-do-this-and-when-not-to">When to Do This, and When Not To</h2>

<p><strong>Not worth it</strong> when the document is short-lived, low-volume, or low-stakes; when one competent person can hold the whole rule set in their head; when nobody will need to ask “what was the answer as at a date two years ago”; or when there is no second document to be consistent with. Handing the statute to a good model and asking is faster, and until somebody runs the baseline nobody can honestly tell you it is worse.</p>

<p><strong>Worth considering</strong> when the answer must be <em>reconstructible</em>, because a regulator, an auditor or a court will ask why and “the model said so” ends the conversation badly; when the same rules are applied across thousands of documents and consistency between them is the actual product; when the source <strong>amends</strong> and you need to know what changed and what it broke, which is exactly what one-rule-one-provision buys; when the rules must be queried forwards and backwards, since a relation runs in both directions and a function runs in one; or when the data cannot leave the building, which forces you into a weak model and therefore into a strong checker.</p>

<p><strong>The domain matters more than the technique.</strong> This works on governance documents because they already <em>are</em> rule systems: citable units, defined terms, explicit temporal operators, and a tradition of being read literally. A marketing brief has none of that, and no amount of Prolog will give it any.</p>

<hr />

<h2 id="back-to-the-ladder">Back to the Ladder</h2>

<p>Everything above is one long attempt to occupy the <a href="/2026/08/24/rigour-by-design.html#flavours-of-specifications">declarative, machine-checkable rung</a> of the spec ladder, and to find out what it costs in practice. Four things from the earlier post now have receipts, and one has a correction.</p>

<p><strong>“AI proposes; the verifier disposes”</strong> is the load-bearing claim, and it held more completely than I expected, because <em>every</em> proposal in the chain turned out to be a model’s: the libraries, the corpora, the query compositions, the projected Python, the blind oracle. The model contributed candidate generation, which is what it is good at, and it contributed to no decision anywhere. What converged was the check.</p>

<p>The uncomfortable corollary is in the comparison the two authoring paths make possible. One had a human in every round, unlimited rounds, and full review. The other had one call and a gate. The gated path produced a <em>better</em> encoding of s.119(1), and the reviewed path is where all three instances of the event/fluent conflation came from. Human review caught the errors it was looking for and waved through the ones it was not. A mechanical check does not get tired at round nine.</p>

<p><strong>“Only a machine-checkable artifact makes an LLM worth looping”</strong> held for a sharper reason than I gave it credit for: the rejection has to be <em>specific</em>. A wall of prose cannot fail, which matters, but specificity is what makes the loop converge. <code class="language-plaintext highlighter-rouge">undeclared_relation(effective/1)</code> converges. “Your spec seems inconsistent” is not a check at all.</p>

<p><strong>“Least power”</strong> decided the local tier. The way to make a 7–8B model safe is to leave it less to decide, down to a relation, its arguments and a date, with deterministic code taking even the mark kind.</p>

<p><strong>The correction, and it is the one that matters.</strong> In the earlier post I wrote that a model’s nondeterminism sits in the gap between the spec and the program. That is true and incomplete. Here the nondeterminism moved <em>up</em>, into the gap between the <strong>source document</strong> and the spec, and no gate I built can close it. Every gate reads the library, or runs it. <strong>None of them reads the statute.</strong> Well-formed, non-vacuous, fully cited, perfectly reproducible, and a misreading, is a state this system can reach and cannot detect. The gates made the cheap errors free to find, which is genuinely worth having, and they left the expensive ones exactly where they were: with a human, reading a rule against the provision it cites.</p>

<p>That is a smaller claim than “verified”. It is also the honest one, and it is where the work is.</p>

<p>The repository is at <a href="https://github.com/avishek-sen-gupta/doc-pipeline">github.com/avishek-sen-gupta/doc-pipeline</a>, including the recorded model runs, the round-by-round violation journals, the fixtures that are <em>expected</em> to fail, and the evaluation document recording which encodings were wrong until running them proved it.</p>]]></content><author><name>avishek</name></author><category term="Software Engineering" /><category term="GenAI" /><category term="Prolog" /><category term="Formal Methods" /><category term="Specifications" /><category term="Knowledge Representation" /><category term="Legal Informatics" /><category term="Program Analysis" /><summary type="html"><![CDATA[In Rigour by Design I argued that almost everyone is parked on the bottom rung of the spec ladder, and that what GenAI actually made cheap is the labour of climbing. That post had a link to a repository and one sentence of description. This post describes what the actual experiment was.]]></summary></entry><entry><title type="html">Harnessing LLMs with Deterministic Program Analysis for Legacy Code</title><link href="http://localhost:4000/2026/05/21/harnessing-llms-with-deterministic-program-analysis.html" rel="alternate" type="text/html" title="Harnessing LLMs with Deterministic Program Analysis for Legacy Code" /><published>2026-05-21T00:00:00+05:30</published><updated>2026-05-21T00:00:00+05:30</updated><id>http://localhost:4000/2026/05/21/harnessing-llms-with-deterministic-program-analysis</id><content type="html" xml:base="http://localhost:4000/2026/05/21/harnessing-llms-with-deterministic-program-analysis.html"><![CDATA[<p>There is an optimistic and a pessimistic reading of what GenAI does to the problem of large legacy codebases.</p>

<p>The optimistic reading: the model can read Java faster than you can, it knows the framework idioms, and it can generate a plausible test stub in seconds. True.</p>

<p>The pessimistic reading: the model will trace a ten-layer call chain, confidently conclude that some domain flag has a specific value at the point your test reaches the validation service, and be completely wrong. There was a null check at layer three that short-circuits, a swallowed <code class="language-plaintext highlighter-rouge">catch</code> at layer five that logs silently, and a database-driven flag at layer eight that flips the branch. <strong>The test will compile, run, pass, and test nothing.</strong></p>

<p>The pessimistic reading is also true.</p>

<p>This post is about that gap: what goes wrong when you use an LLM to reason about a ~2M-line J2EE codebase, and which classical program analysis techniques help by supplying structured, pre-computed facts instead of asking the model to derive them from source text.</p>

<p>The running example is the <strong>Ralph Loop</strong>: an AI-orchestrated test coverage campaign over a large legacy J2EE codebase with approximately two million lines of code, zero pre-existing unit tests, and no test harness.</p>

<p>Aside: The Ralph loop is your basic <code class="language-plaintext highlighter-rouge">while</code> loop, where the condition is a fitness function, and the body executes a series of instructions (deterministic or LLM-driven) until the fitness function is satisfied. In this case, the fitness function is a measure of the code coverage, and the instructions are the test cases generated by the LLM.</p>

<p>The codebase is actively maintained, but it has grown into a monolith spanning JSF, Spring, JMS, Hibernate, raw JDBC, and more. Documentation exists at the flow level; what is not documented is the code itself: the cross-layer interactions, the edge cases, and the conditions under which a particular DAO actually emits SQL. The goal is an <strong>executable specification</strong>: tests that capture what each flow does at a level of precision no design document reaches, and that break the moment the behaviour changes.</p>

<p>At two million lines with no existing harness, manual test writing is not a credible option (well, it is, what else were you going to do pre-LLM, anyway? But any sort of automation would have always reduced the tedium). The exercise consisted of the following loops:</p>
<ul>
  <li><strong>Two Ralph loops, one nested in the other;</strong> the outer loop iterates over action methods, which are entry points in the request-processing framework, measuring cumulative JaCoCo coverage and ranking the next highest-value target. The inner loop takes one action method, drives coverage toward 90%, and commits the tests. For the purposes of this post, we will stick to the execution of this inner loop.</li>
  <li><strong>A Ralph loop to build tests to exercise the DAO layer</strong>, in order to capture the emitted SQL (through JDBC-level tracing or Hibernate mechanisms).</li>
</ul>

<pre><code class="language-mermaid">flowchart LR
    START([action method]) --&gt; CG[fw-calltree]
    CG --&gt; MEAS[JaCoCo measure]
    MEAS --&gt; CHECK{coverage ok?}
    CHECK --&gt;|yes| DONE([done])
    CHECK --&gt;|no| CFG[intra-proc-cfg\nfind uncovered path]
    CFG --&gt; GEN[write JUnit test\nfor that path]
    GEN --&gt; RUN[run test]
    RUN --&gt; FIX{passes?}
    FIX --&gt;|no| DIAG[Failure Diagnostic\nProtocol]
    DIAG --&gt; FIX2[fix test or stub]
    FIX2 --&gt; MEAS
    FIX --&gt;|yes| MEAS

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef terminal fill:#d1fae5,stroke:#059669,color:#064e3b
    classDef llm fill:#ede0f8,stroke:#7b2d9b,color:#3b0764
    classDef diag fill:#fce7f3,stroke:#be185d,color:#831843
    class START,DONE terminal
    class GEN llm
    class DIAG,FIX2 diag
</code></pre>

<hr />

<p>The seven techniques described in this post rely on the following tools. Each links to the section where it is discussed.</p>

<table>
  <thead>
    <tr>
      <th>Tool / Technique</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>JaCoCo <a href="#technique-1-coverage-statistics-as-a-deterministic-compass">➔</a></td>
      <td>Coverage measurement; drives target selection in the outer loop</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">buildcg</code> <a href="#technique-2-cfgs-and-slicing">➔</a></td>
      <td>One-time callgraph construction from compiled JARs</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">fw-calltree</code> <a href="#technique-2-cfgs-and-slicing">➔</a></td>
      <td>Forward calltree query from a given entry point</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">intra-proc-cfg</code> <a href="#technique-2-cfgs-and-slicing">➔</a></td>
      <td>Intraprocedural CFG extraction for a single method</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">flat-cfg-path-to-line</code> <a href="#technique-2-cfgs-and-slicing">➔</a></td>
      <td>Flat statement sequence from method entry to a target line</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">reaching-conditions</code> <a href="#technique-5-reaching-conditions">➔</a></td>
      <td>Branch predicates (with polarity) on each CFG path to a target</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ddg-slice</code> <a href="#technique-4-dataflow-analysis">➔</a></td>
      <td>Intraprocedural def-use chains; variable origin tracing</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ctags</code> + <code class="language-plaintext highlighter-rouge">ast-emit</code> <a href="#technique-3-source-extraction-with-ctags-and-ast-emit">➔</a></td>
      <td>Symbol indexing and batch source-body extraction</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ast-grep</code> <a href="#technique-3-source-extraction-with-ctags-and-ast-emit">➔</a></td>
      <td>Structural code search by AST pattern</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CapturingConnection</code> <a href="#applying-techniques-dao-sql-capture">➔</a></td>
      <td>JDBC-level SQL capture against H2</td>
    </tr>
    <tr>
      <td>AspectJ CatchRecorder <a href="#technique-6-dynamic-tracing">➔</a></td>
      <td>Swallowed-exception tracing at catch sites</td>
    </tr>
    <tr>
      <td>JFR Exception Recorder <a href="#technique-6-dynamic-tracing">➔</a></td>
      <td>Throw-site capture for implicit JVM exceptions</td>
    </tr>
    <tr>
      <td>ASM Trace Agent <a href="#technique-6-dynamic-tracing">➔</a></td>
      <td>Full method-entry/exit execution trace</td>
    </tr>
  </tbody>
</table>

<hr />

<h2 id="contents">Contents</h2>

<ol>
  <li><a href="#tests-as-specification-and-harness">Tests as Specification and Harness</a></li>
  <li><a href="#the-problem-what-goes-wrong">The Problem: What Goes Wrong</a></li>
  <li><a href="#the-ralph-loop-as-a-context-engineering-harness">The Ralph Loop as a Context-Engineering Harness</a></li>
  <li><a href="#why-not-just-use-an-lsp-server">Why Not Just Use an LSP Server?</a></li>
  <li><a href="#technique-1-coverage-statistics-as-a-deterministic-compass">Technique 1: Coverage Statistics as a Deterministic Compass</a></li>
  <li><a href="#technique-2-cfgs-and-slicing">Technique 2: CFGs and Slicing</a></li>
  <li><a href="#technique-3-source-extraction-with-ctags-and-ast-emit">Technique 3: Source Extraction with ctags and ast-emit</a></li>
  <li><a href="#technique-4-dataflow-analysis">Technique 4: Dataflow Analysis</a></li>
  <li><a href="#technique-5-reaching-conditions">Technique 5: Reaching Conditions</a></li>
  <li><a href="#technique-6-dynamic-tracing">Technique 6: Dynamic Tracing</a></li>
  <li><a href="#applying-techniques-dao-sql-capture">Applying Techniques: DAO SQL Capture</a></li>
  <li><a href="#why-tools-not-just-an-llm">Why Tools, Not Just an LLM?</a></li>
  <li><a href="#four-diagnostic-incidents">Four Diagnostic Incidents</a></li>
  <li><a href="#where-llms-fit-in">Where LLMs Fit In</a></li>
  <li><a href="#caveats">Caveats</a></li>
  <li><a href="#references">References</a></li>
</ol>

<hr />

<h2 id="tests-as-specification-and-harness">Tests as Specification and Harness</h2>

<p>In an <a href="/2023/01/10/tests-proof-probability.html">older post from 2011</a>, I gave a probabilistic argument that writing a test increases the posterior probability that a piece of code is correct by a factor of 2^n (where n is the output bit width). The argument is rough, but the intuition holds: every test that passes constrains the space of possible implementations, reducing entropy: tests are evidence.</p>

<p>That argument was made in the context of human developers. In the GenAI context, the same point applies but becomes more important.</p>

<p><strong>Tests as a quantitative map.</strong> A coverage report (JaCoCo’s <code class="language-plaintext highlighter-rouge">instruction_pct</code>, for example) tells the model precisely which code has been exercised and which has not. It is a computed fact about execution history. In the inner Ralph loop, the model starts by querying a coverage JSON emitted from JaCoCo XML into a node-per-method structure. The output is a ranked list of uncovered methods, sorted by missed bytecode instructions. The model knows <em>what</em> to target before it reads production code.</p>

<p><strong>Tests as machine-readable intent.</strong> A test method named <code class="language-plaintext highlighter-rouge">placeOrder_whenCustomerIsCorporate_andPurchaseOrderNumberIsAbsent_shouldReturnValidationError</code> communicates several things that the model can exploit: the class under test, the business condition being checked, the expected outcome, and by implication, the fields and mock stubs needed to trigger it. That information is available as text even to a model with no execution capability.</p>

<p><strong>Failing tests as precise diagnostic reports.</strong> A test failure is not “something is broken somewhere.” It is a specific assertion, a stack trace, a set of actual vs expected values, and, if you instrument correctly, a log of every service call that was or was not made. This is far more information-dense than a bug report.</p>

<p><strong>Tests as proof of functional equivalence.</strong> Whether rewriting, migrating to microservices, or upgrading a framework, a deterministic test harness is the only reliable way to prove functional equivalence between old and new. The tests written today are the specification the replacement must satisfy. An LLM summary of what the code does is a best-effort interpretation: plausible, useful for orientation, but not a contract. A passing test is a contract: it captures exactly what inputs produce what outputs, and breaks the moment the code diverges. An LLM summary will survive a rewrite; a test will catch when the rewrite is wrong.</p>

<table>
  <thead>
    <tr>
      <th>Concern</th>
      <th>LLM summary</th>
      <th>Test suite</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Invariants documented</td>
      <td>partial</td>
      <td>yes</td>
    </tr>
    <tr>
      <td>Input/output contracts</td>
      <td>inferred</td>
      <td>exact</td>
    </tr>
    <tr>
      <td>Edge cases covered</td>
      <td>guessed</td>
      <td>verified</td>
    </tr>
    <tr>
      <td>Survives refactor</td>
      <td>no</td>
      <td>yes</td>
    </tr>
    <tr>
      <td>Proves equivalence</td>
      <td>no</td>
      <td>yes</td>
    </tr>
    <tr>
      <td>Runs in CI</td>
      <td>no</td>
      <td>yes</td>
    </tr>
  </tbody>
</table>

<p>Tests are a long-term investment, but still they pay dividends immediately; whether you are modernising, refactoring, or enhancing legacy code.</p>

<p><strong>LLMs layer on top of tests, not underneath them.</strong> An LLM can read a passing test suite, a coverage report, and a set of call trees and produce useful summaries: what a flow does, which edge cases are covered, what an undocumented action class appears to intend.</p>

<p>This is something I’ve found models to be very good at: synthesis of structured evidence. What is not a good use is asking it to guess about facts that static analysis can compute exactly, such as execution paths, guarding conditions, or emitted SQL.</p>

<p>The shift is this: in the pre-AI era, tests were primarily for human confidence. In the AI era, they are also infrastructure for machine comprehension. <strong>A codebase with good test coverage is a codebase that is simultaneously understandable at multiple levels of abstraction.</strong></p>

<hr />

<h2 id="the-problem-what-goes-wrong">The Problem: What Goes Wrong</h2>

<p>Before we discuss techniques, let’s be explicit about <em>what</em> can go wrong when AI models are tasked with writing tests based on reasoning about source code.</p>

<p><strong>Attention drift.</strong> Ask a model to trace a call chain through ten method boundaries and it will drift. The types it attributed to a parameter at layer two will have been quietly replaced by a plausible but wrong type by layer seven. The argument that a particular service method accepts a domain object not a raw <code class="language-plaintext highlighter-rouge">String</code> will be forgotten. The mock will be stubbed for the wrong type signature. The test will compile because the model also writes an <code class="language-plaintext highlighter-rouge">@SuppressWarnings</code>, or because the actual type is <code class="language-plaintext highlighter-rouge">Object</code>, and the failure will be silent.</p>

<p><strong>Token burn.</strong> A realistic J2EE action method has 30–50 transitive callees once you include validators, service managers, DAO helpers, and utility methods. Reading all of them is not feasible within a context window if you also want to do anything useful with what you have read. The model must either truncate or hallucinate.</p>

<p><strong>Path explosion and static over-confidence.</strong> The model reads a condition:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">(</span><span class="n">requestType</span> <span class="o">==</span> <span class="nc">RequestType</span><span class="o">.</span><span class="na">TYPE_B</span><span class="o">)</span> <span class="o">{</span>
    <span class="c1">// type-B-specific validation</span>
<span class="o">}</span>
</code></pre></div></div>

<p>It assumes this branch is taken because the surrounding code seems to be about type-B processing. It writes a test that sets <code class="language-plaintext highlighter-rouge">requestType = TYPE_B</code>. But three layers up, the action’s <code class="language-plaintext highlighter-rouge">execute()</code> method has already set <code class="language-plaintext highlighter-rouge">requestType</code> to <code class="language-plaintext highlighter-rouge">TYPE_A</code> based on a request parameter that the model did not follow. The branch is never entered. The test passes because the validation path is skipped, not because validation passed.</p>

<p><strong>The silent exception.</strong> Production J2EE code of a certain vintage is full of:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="s">"Something went wrong: "</span> <span class="o">+</span> <span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">(),</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The exception is swallowed. The method returns <code class="language-plaintext highlighter-rouge">null</code> or a default object. The test checks the return value, gets <code class="language-plaintext highlighter-rouge">null</code>, and the model’s first instinct is to conclude that the method is supposed to return null in this case. It is not. The test is measuring a broken execution path and recording it as expected behaviour.</p>

<p><strong>Unscoped exploration.</strong> Even when the task is to write a test for a single, well-identified method in a well-scoped flow, a model without structured artifacts will begin grepping through files to re-derive information it could have received directly. Given an action class name, it will grep for the class, read the file, find a called method name, grep for that, read that file, and repeat, re-constructing a call graph one hop at a time. Each hop is a context allocation and a potential point of drift. This happens reliably: the prompt engineering work in the Ralph Loop required repeated reinforcement to keep the model querying coverage JSON rather than scanning files, using <code class="language-plaintext highlighter-rouge">ast-emit</code> rather than reading method bodies manually, and invoking <code class="language-plaintext highlighter-rouge">intra-proc-cfg</code> rather than reasoning about control flow from source text.</p>

<p>The problem with all of the above is that <strong>the model has no ground truth about <em>what actually executed</em>.</strong> It is reasoning from source text, which is a model of what the code might do, not a record of what it did. As a side effect, many more tokens are burned from reasoning about code paths.</p>

<pre><code class="language-mermaid">flowchart TD
    SRC[source text] --&gt; LLM[LLM reasoning]
    LLM --&gt; DRIFT[attention drift\nacross 10 layers]
    LLM --&gt; BURN[token budget\nexhausted]
    LLM --&gt; CONF[confident wrong answer\nabout branch condition]
    LLM --&gt; SWALLOW[silent exception\nmistaken for correct return]

    TOOLS[program analysis tools] --&gt; FACT1[calltree: exact callees]
    TOOLS --&gt; FACT2[CFG path: exact statement sequence]
    TOOLS --&gt; FACT3[def-use chain: exact variable origins]
    TOOLS --&gt; FACT4[JFR/AspectJ: exact exception site]

    FACT1 &amp; FACT2 &amp; FACT3 &amp; FACT4 --&gt; LLM2[LLM as synthesiser\nnot deriver]

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef input fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef artifact fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef llm fill:#ede0f8,stroke:#7b2d9b,color:#3b0764
    classDef bad fill:#fce7f3,stroke:#be185d,color:#831843
    class SRC input
    class TOOLS default
    class FACT1,FACT2,FACT3,FACT4 artifact
    class LLM2 llm
    class LLM,DRIFT,BURN,CONF,SWALLOW bad
</code></pre>

<hr />

<h2 id="the-ralph-loop-as-a-context-engineering-harness">The Ralph Loop as a Context-Engineering Harness</h2>

<p>The Ralph loop is a context-engineering harness. Each step in the loop <strong>replaces a reasoning burden on the model with a tool call that produces a structured artifact.</strong></p>

<pre><code class="language-mermaid">flowchart TD
    subgraph P1["Phase 1: Build Indices  (once per codebase)"]
        JAR["JARs + class files"]
        SRC["Java source"]
        CG["buildcg\ncallgraph.json"]
        CTAGS["ctags\ntags.json"]
        HMAP["Hibernate parser\nmappings.json"]
        JAR --&gt; CG
        SRC --&gt; CG
        SRC --&gt; CTAGS
        SRC --&gt; HMAP
    end

    subgraph P2["Phase 2: Per-action Extraction  (once per action)"]
        FW["fw-calltree\ncalltree.json"]
        AST["ast-emit\nast.json"]
        DAO["DAO SQL capture\ndao-sql.jsonl"]
        FW --&gt; AST
    end

    subgraph P3["Phase 3: Test Writing Loop"]
        CFG["intra-proc-cfg\nCFG"]
        FLAT["flat-cfg-path-to-line\nexecution paths"]
        DDG["ddg-slice\ndef-use chains"]
        RC["reaching-conditions\npreconditions"]
        LLM["🤖 LLM  →  JUnit test"]
        JAC["JaCoCo\ncoverage %"]
        CFG --&gt; FLAT
        CFG --&gt; DDG
        DDG --&gt; RC
        FLAT --&gt; LLM
        RC --&gt; LLM
        LLM --&gt; JAC
        JAC --&gt;|"below 90%"| CFG
    end

    subgraph P4["Phase 4: Failure Diagnosis"]
        D1["L1: Surefire XML"]
        D2["L2: CatchRecorder + JFR"]
        D3["L3: per-test JaCoCo"]
        D4["L4: ASM Trace Agent"]
        D1 --&gt;|unresolved| D2
        D2 --&gt;|unresolved| D3
        D3 --&gt;|unresolved| D4
    end

    CG --&gt; FW
    CTAGS --&gt; AST
    HMAP --&gt; DAO
    FW --&gt; CFG
    AST --&gt; LLM
    DAO --&gt; LLM
    LLM --&gt;|"test fails"| D1
    D4 --&gt;|"root cause → fix test"| LLM

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef input fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef artifact fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef llm fill:#ede0f8,stroke:#7b2d9b,color:#3b0764
    classDef diag fill:#fce7f3,stroke:#be185d,color:#831843
    class JAR,SRC input
    class AST,DAO artifact
    class LLM llm
    class D1,D2,D3,D4 diag

    style P1 fill:#dbeafe,stroke:#3b82f6,color:#1e3a8a
    style P2 fill:#d1fae5,stroke:#059669,color:#064e3b
    style P3 fill:#ede9fe,stroke:#7c3aed,color:#2e1065
    style P4 fill:#fce7f3,stroke:#be185d,color:#831843
</code></pre>

<table>
  <thead>
    <tr>
      <th>What the model would otherwise do</th>
      <th>What the harness provides instead</th>
      <th>Tool</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Guess which methods are untested</td>
      <td>Coverage JSON, queried with <code class="language-plaintext highlighter-rouge">jq</code></td>
      <td>JaCoCo</td>
    </tr>
    <tr>
      <td>Decide what the entry point calls</td>
      <td>Call graph scoped to application classes</td>
      <td><code class="language-plaintext highlighter-rouge">buildcg</code> + <code class="language-plaintext highlighter-rouge">fw-calltree</code></td>
    </tr>
    <tr>
      <td>Read source files to understand called methods</td>
      <td>Batch-extracted method bodies, one JSON file</td>
      <td><code class="language-plaintext highlighter-rouge">ast-emit</code> + <code class="language-plaintext highlighter-rouge">ctags</code></td>
    </tr>
    <tr>
      <td>Reason about which conditions reach a target line</td>
      <td>DFS path enumeration, flat statement sequence</td>
      <td><code class="language-plaintext highlighter-rouge">intra-proc-cfg</code> + <code class="language-plaintext highlighter-rouge">flat-cfg-path-to-line</code></td>
    </tr>
    <tr>
      <td>Figure out what test data forces a specific path</td>
      <td>Def-use chains for the relevant variables</td>
      <td><code class="language-plaintext highlighter-rouge">ddg-slice</code></td>
    </tr>
    <tr>
      <td>Infer which preconditions are necessary to reach a target</td>
      <td>Polarity-annotated branch predicates on the path to the target</td>
      <td><code class="language-plaintext highlighter-rouge">reaching-conditions</code></td>
    </tr>
    <tr>
      <td>Guess what SQL will execute</td>
      <td>Captured JDBC statements against H2</td>
      <td><code class="language-plaintext highlighter-rouge">CapturingConnection</code></td>
    </tr>
    <tr>
      <td>Diagnose why a test returns an unexpected value</td>
      <td>L1 Surefire → L2 CatchRecorder/JFR → L3 per-test JaCoCo → L4 ASM trace</td>
      <td>diagnostic protocol</td>
    </tr>
  </tbody>
</table>

<p>At every stage, the model’s role shifts from <em>derivation</em> to <em>application</em>. It is given facts and asked to generate oe debug code that encodes those facts as test setup. <strong>The quality of information in LLM context reinforces model capability</strong>: a model operating on pre-computed program analysis artifacts is a different instrument from one operating on source text and being asked to perform the analysis internally.</p>

<hr />

<h2 id="why-not-just-use-an-lsp-server">Why not just use an LSP server?</h2>

<p>A language server (JDTLS, IntelliJ’s LSP, or similar) is the obvious first answer to “how does an LLM navigate a codebase?” It provides call hierarchies, type information, go-to-definition, and reference search. For editing and navigation it excels. For structured test generation it stops well short.</p>

<p><strong>What a language server provides:</strong> <code class="language-plaintext highlighter-rouge">callHierarchy/incomingCalls</code> resolves callers by declared static type; <code class="language-plaintext highlighter-rouge">textDocument/implementation</code> finds concrete implementations of an interface method; <code class="language-plaintext highlighter-rouge">resolveStackTraceLocation</code> maps stack frames to source lines; hover types and go-to-definition: accurate, real-time, incremental.</p>

<p><strong>Where it gets harder.</strong></p>

<ul>
  <li><strong>Call graph:</strong> LSP call hierarchy is implemented via syntactic reference search with local type inference, not whole-program analysis. Concrete coverage of polymorphic dispatch varies by language server: jdtls uses reference-based search with type-aware filtering, which handles more cases than pure static-type resolution but less than CHA or RTA; clangd’s virtual function resolution is partial; pyright’s is best-effort given Python’s dynamic dispatch. CHA, RTA, and points-to analyses (Andersen, Steensgaard, k-CFA) operate over information the protocol does not expose, such as the full set of instantiated types or a flow-sensitive abstract heap. You can partially recover virtual targets by combining <code class="language-plaintext highlighter-rouge">callHierarchy/incomingCalls</code> with <code class="language-plaintext highlighter-rouge">textDocument/implementation</code> for each virtual call site, but the result remains incomplete and is subject to the server’s eventually-consistent index.</li>
  <li><strong>CFG and paths:</strong> CFG is not part of the LSP spec; JDTLS exposes none, so branch enumeration, path extraction, and reaching conditions are unavailable through the protocol.</li>
  <li><strong>Dataflow:</strong> no def-use chains, no backward slice, no heap edges anywhere in the spec.</li>
  <li><strong>Latency model:</strong> even for what the protocol does provide, the interactive request-response model is a poor fit for batch graph work. A forward calltree to depth 4 with a branching factor of 4 requires on the order of 340 sequential requests, each depending on the last. An application call graph is a batch computation; issuing it one hop at a time is impractical at scale.</li>
</ul>

<table>
  <thead>
    <tr>
      <th>Question</th>
      <th>Language server</th>
      <th>Bytecode tools</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Which methods are reachable from this entry?</td>
      <td>partial: reference-based with local type inference; polymorphic coverage varies by server and is structurally bounded by what the protocol exposes</td>
      <td><code class="language-plaintext highlighter-rouge">buildcg</code> + <code class="language-plaintext highlighter-rouge">fw-calltree</code>: exact, from bytecode</td>
    </tr>
    <tr>
      <td>What are the execution paths through this method?</td>
      <td>none</td>
      <td><code class="language-plaintext highlighter-rouge">intra-proc-cfg</code> + <code class="language-plaintext highlighter-rouge">flat-cfg-path-to-line</code></td>
    </tr>
    <tr>
      <td>What conditions guard each path?</td>
      <td>none</td>
      <td><code class="language-plaintext highlighter-rouge">reaching-conditions</code></td>
    </tr>
    <tr>
      <td>What does this variable depend on?</td>
      <td>none</td>
      <td><code class="language-plaintext highlighter-rouge">ddg-slice</code></td>
    </tr>
    <tr>
      <td>Trace test failure to root cause</td>
      <td>partial: stack frame location only</td>
      <td><code class="language-plaintext highlighter-rouge">ddg-slice</code> + diagnostic protocol</td>
    </tr>
  </tbody>
</table>

<p>The dividing line: a language server answers <em>“what is this thing and where is it?”</em> Bytecode tools answer <em>“why does the program behave this way and what must be true to reach this line?”</em> The first is navigation. The second is analysis. Both matter, but only analysis can drive test generation.</p>

<hr />

<h2 id="technique-1-coverage-statistics-as-a-deterministic-compass">Technique 1: Coverage Statistics as a Deterministic Compass</h2>

<p>The first intervention is the cheapest: <strong>replace open-ended exploration with coverage-guided targeting</strong>.</p>

<p>Instead of asking the model “what should we test next?”, compute the answer outside the model and give it as input. <strong>The outer Ralph loop does exactly this.</strong></p>

<ol>
  <li>Run JaCoCo over the full test suite.</li>
  <li>Run a script that builds a JSON dashboard: for each action method in the flow, the calltree size and the current coverage percentage.</li>
  <li>Select the action with the most uncovered instructions that does not yet have an E2E test.</li>
  <li>Hand the action class and method name to the inner loop.</li>
</ol>

<p>The model never has to decide what to work on. That decision is made by a deterministic function of the coverage data. Its job is only to decide <em>how</em> to cover the chosen target.</p>

<p><strong>Within the inner loop, the same principle applies at finer granularity.</strong> After each iteration, the loop re-runs the coverage measurement and queries for the remaining uncovered methods: both completely uncovered non-trivial methods (the primary targets) and partially covered methods with more paths to exercise.</p>

<pre><code class="language-mermaid">flowchart TD
    COV[JaCoCo coverage JSON] --&gt; RANK[rank by instruction_missed\nskip trivial methods]
    RANK --&gt; PICK[pick highest-value uncovered action]
    PICK --&gt; INNER[inner loop: drive to 90%]
    INNER --&gt; COMMIT[commit tests]
    COMMIT --&gt; COV

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef fix fill:#d1fae5,stroke:#059669,color:#064e3b
    class COMMIT fix
</code></pre>

<p>I applied two other heuristics:</p>
<ul>
  <li><strong>Skip methods with fewer than 50 missed bytecode instructions</strong>; they are almost certainly getters, delegates, or wrappers, and the cost of writing and maintaining tests for them exceeds the coverage value.</li>
  <li><strong>If two consecutive iterations produce no coverage gain, do not let the model give up; investigate.</strong> The stall is usually due to a missed branch in an already-touched method, not a genuinely unreachable code path.</li>
</ul>

<hr />

<h2 id="technique-2-cfgs-and-slicing">Technique 2: CFGs and Slicing</h2>

<p>Coverage tells the model <em>what</em> to cover. CFG analysis tells it <em>how</em>.</p>

<p><strong>Intraprocedural CFGs.</strong> For a single method, a control flow graph encodes every possible execution order: which statements can follow which, which branches exist, and which paths are feasible from entry. Instead of asking the model to read a 200-line method and reason about which conditions must hold to reach line 147, you can extract the CFG programmatically and compute the path.</p>

<p>For a given target line, the inner loop uses <code class="language-plaintext highlighter-rouge">intra-proc-cfg</code> to extract the method’s CFG, then <code class="language-plaintext highlighter-rouge">flat-cfg-path-to-line</code> to compute the flat statement sequence from method entry to that line.</p>

<p><strong>The output is a sequence of statements (with line numbers) that must execute, in order, to reach the target.</strong> Each conditional statement in the sequence implies a constraint: a mock must return a particular value, or a field must be set to a particular state. The model reads this sequence and has a much more direct path to writing a test which exercises that path.</p>

<pre><code class="language-mermaid">flowchart TD
    CFG[CFG with 3 branches] --&gt; PE[path enumerator DFS]
    PE --&gt; P1[Path 1: lines 42-47, 48-50\norder is null]
    PE --&gt; P2[Path 2: lines 42-47, 51-58, 59-61\ndiscount invalid]
    PE --&gt; P3[Path 3: lines 42-47, 51-58, 62-71\nhappy path]
    P1 --&gt; T1[Test: order null → expect error]
    P2 --&gt; T2[Test: bad discount → expect error]
    P3 --&gt; T3[Test: valid order → expect success]

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef path fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef test fill:#ede0f8,stroke:#7b2d9b,color:#3b0764
    class P1,P2,P3 path
    class T1,T2,T3 test
</code></pre>

<p>The key point is simple: <strong>the LLM does not need to derive the path. It needs to follow a pre-computed path.</strong> This turns an open-ended reasoning problem into constrained instruction-following. The expectations of the LLM having to reason about code are thus vastly reduced.</p>

<p>The diagrams below show the two steps towards getting this trace:</p>
<ul>
  <li>The first one isolates the target subgraph as a bounded region (<code class="language-plaintext highlighter-rouge">xtrace</code>).</li>
  <li>Within that bounded region, highlight the specific path through it as a single traversal (<code class="language-plaintext highlighter-rouge">ftrace-slice</code>).</li>
</ul>

<p><img src="/assets/images/cfg-xtrace.png" alt="cfg-region" style="width:50%" />
<img src="/assets/images/cfg-ftrace-slice.png" alt="cfg-region" style="width:50%" /></p>

<p><strong>Interprocedural slices via calltrees.</strong> A single method’s CFG covers intra-method control flow. For multi-layer reasoning (for example: what mock return value at the service layer causes the action layer to take this branch?) you need an interprocedural view.</p>

<p>A calltree is a forward slice of the call graph rooted at a specific entry point. The diagram below shows a fictional example: <code class="language-plaintext highlighter-rouge">ProcessOrderAction.execute</code> is the entry; the tree fans out through the service and DAO layers, pruned to application classes only.</p>

<pre><code class="language-mermaid">graph TD
    A[ProcessOrderAction.execute] --&gt; B[OrderValidationService.validate]
    A --&gt; C[OrderService.processOrder]
    B --&gt; D[AccountDao.findByCustomerId]
    B --&gt; E[ProductDao.findBySku]
    C --&gt; F[OrderDao.saveOrder]
    C --&gt; G[InventoryService.reserve]
    G --&gt; H[InventoryDao.decrementStock]

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef action fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef dao fill:#d4edda,stroke:#388e3c,color:#1b5e20
    class A action
    class D,E,F,H dao
</code></pre>

<p><strong>The inner loop generates one calltree per action method.</strong> The <code class="language-plaintext highlighter-rouge">--pattern</code> flag prunes the callgraph to methods whose class names match the pattern. This eliminates JDK internals, third-party library internals, and framework machinery, which are typically not mockable and not relevant to test construction. What remains is the application’s own call structure, which is exactly what the model needs.</p>

<p>The two tools behind this are <code class="language-plaintext highlighter-rouge">buildcg</code>, which generates <code class="language-plaintext highlighter-rouge">callgraph.json</code> from the compiled JAR in a single pass (no source required, no running process), and <code class="language-plaintext highlighter-rouge">fw-calltree</code>, which queries the pre-built graph per action, per session. The split matters: <code class="language-plaintext highlighter-rouge">buildcg</code> is expensive and runs once, offline (for 2MLoC, takes about 10-15 mins, without parallelism); <code class="language-plaintext highlighter-rouge">fw-calltree</code> is cheap and runs on demand.</p>

<p>Both tools are built on <a href="https://soot-oss.github.io/SootUp/">SootUp</a> and <a href="https://github.com/QilinPTA/Qilin">Qilin</a>. SootUp parses the compiled JAR and produces the Jimple IR used for CFG extraction (<code class="language-plaintext highlighter-rouge">intra-proc-cfg</code>), def-use chain computation (<code class="language-plaintext highlighter-rouge">ddg-slice</code>), and reaching conditions. Qilin can be added, to contribute points-to analysis, narrowing each virtual call site to the reachable targets instead of every method compatible with the declared type (for this exercise, it was not). The result is still a conservative over-approximation, but with far fewer spurious edges than naive class hierarchy analysis.</p>

<p><strong>A note on polymorphic dispatch artifacts:</strong> Static callgraphs resolve virtual method calls to <em>all</em> possible callees across the codebase, not just the ones that will be dispatched at runtime. A <code class="language-plaintext highlighter-rouge">catch (Exception e) { e.getMessage() }</code> will appear in the callgraph as edges to <code class="language-plaintext highlighter-rouge">getMessage()</code> on every Exception subclass ever loaded. These entries are spurious. The inner loop excludes them from coverage accounting via <code class="language-plaintext highlighter-rouge">--exclude-pattern '\.exception\.'</code> and logs them to a glitches file for later review. Allowing them to inflate the coverage denominator would make the coverage numbers meaningless.</p>

<p><strong>Backward tracing and source-to-sink analysis:</strong> The flat path computation above is a backward trace: given a target line, find the constraints that must hold at each predecessor node on the path from entry to target. Generalised, this is the backward slice. Source-to-sink analysis is the forward counterpart: given a source, find the sinks it can reach. Both are mechanically extractable and useful when the question is “how do I get this value to reach this code?”</p>

<hr />

<h2 id="technique-3-source-extraction-with-ctags-and-ast-emit">Technique 3: Source Extraction with ctags and ast-emit</h2>

<p>The calltree gives you a list of method signatures. The model needs the source bodies. Two tools close this gap, and the reason to name them explicitly is that the naive approach (asking the model to find and read relevant files) does not scale.</p>

<p><code class="language-plaintext highlighter-rouge">ctags</code> builds a flat symbol index over the entire Java source tree once, upfront. No daemon, no language server, no compiler. The result is a tag file that maps every class, method, field, and constructor to its defining file and line number. Given a 47-node calltree, every method body can be located with a single index lookup per node, with no directory crawling, no grep, and no false positives from overloaded names in comments.</p>

<p><code class="language-plaintext highlighter-rouge">ast-emit</code> uses that index to collect all 47 method bodies in one pass, writing them to <code class="language-plaintext highlighter-rouge">ast.json</code>. A domain extractor searching for <code class="language-plaintext highlighter-rouge">new Entity()</code> instantiations and Claude reading source for intent summaries both consume this artifact directly. Neither has to search the codebase. The model receives the relevant source as structured input, not as a pile of files to navigate.</p>

<p>A language server is slower to reach a usable state, requires a persistent process, and can fail under memory pressure. For a batch lookup of known symbol locations, ctags is simpler and more reliable. The indexing step takes a couple of minutes on a large codebase and runs once.</p>

<pre><code class="language-mermaid">flowchart TD
    JAR[compiled JAR] --&gt; BUILDCG[buildcg\none-time offline]
    BUILDCG --&gt; CG[callgraph.json]
    CG --&gt; FWCT[fw-calltree\nper action, on demand]
    FWCT --&gt; CT[calltree.json\n47 nodes]
    SRC[Java source tree] --&gt; CTAGS[ctags\none-time offline]
    CTAGS --&gt; TAGS[tags file\nsymbol → file + line]
    CT &amp; TAGS --&gt; ASTEMIT[ast-emit]
    ASTEMIT --&gt; ASTJSON[ast.json\nall 47 method bodies]
    ASTJSON --&gt; DE[domain extractor]
    ASTJSON --&gt; CLAUDE[Claude\nintent summaries]

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef input fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef artifact fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef llm fill:#ede0f8,stroke:#7b2d9b,color:#3b0764
    class JAR,SRC input
    class CG,CT,TAGS,ASTJSON artifact
    class CLAUDE llm
</code></pre>

<p>There is also <code class="language-plaintext highlighter-rouge">ast-grep</code> for the complementary case: finding code by structure rather than by symbol name. When you need all method calls where the first argument is a string literal, or all <code class="language-plaintext highlighter-rouge">new Entity()</code> instantiations regardless of which entity, <code class="language-plaintext highlighter-rouge">ast-grep</code> matches by code shape with an AST-aware pattern language. No language server required; it runs against raw source files.</p>

<hr />

<h2 id="technique-4-dataflow-analysis">Technique 4: Dataflow Analysis</h2>

<p>CFG path analysis tells you which statements execute. Dataflow analysis tells you what values those statements operate on and where those values originate.</p>

<p><strong>Intraprocedural dataflow.</strong> Reaching definitions tell you, at each use of a variable, which assignment to that variable can reach it. Use-def chains are the concrete representation: for variable <code class="language-plaintext highlighter-rouge">X</code> used at line 120, the use-def chain might show that <code class="language-plaintext highlighter-rouge">X</code> was last assigned at line 80 (<code class="language-plaintext highlighter-rouge">X = service.fetchAccount(customerId)</code>) and at line 30 (<code class="language-plaintext highlighter-rouge">X = null</code>). The model now knows that to have a non-null <code class="language-plaintext highlighter-rouge">X</code> at line 120, the mock for <code class="language-plaintext highlighter-rouge">service.fetchAccount</code> must return a non-null account.</p>

<p>Without this, the model reads the code, notes that <code class="language-plaintext highlighter-rouge">X</code> is used at line 120, and guesses at the assignment history. For short methods with obvious flow, it usually guesses correctly. For methods with 200 lines, multiple reassignments, and conditionally-executed assignments, it frequently does not.</p>

<p><strong>Interprocedural dataflow.</strong> The harder version: a parameter passed into a top-level method propagates through several layers before it affects the condition the test needs to trigger. Interprocedural dataflow analysis tracks this propagation. The question “what input to the action layer causes the validation service to take the error path?” is fundamentally a dataflow question: it requires tracing the relevant field of the input object through the call chain to the validation check.</p>

<p>In practice, full interprocedural dataflow analysis on a million-line codebase is expensive. A pragmatic approximation works well: use the calltree to identify the relevant parameter at each layer, then use intraprocedural dataflow within each method to determine what transformation it applies. Even partial use-def summaries can drastically reduce the depth of reasoning required from the model.</p>

<p>In the Ralph loop, intraprocedural dataflow is computed by <code class="language-plaintext highlighter-rouge">ddg-slice</code>: given the CFG and a variable of interest, it computes where the variable is defined (DEF sites) and where it is read or tested (USE sites). Given the target execution path, the chain from entry to target determines what test data must be set up. The USE site at a null check tells you the variable must be non-null; the USE site at a field read tells you the field must have a specific value; the USE site at a facade call tells you the object must be in a state the facade will accept. The model reads the def-use chain and translates it directly into mock setup and object construction.</p>

<pre><code class="language-mermaid">flowchart TD
    CFG2[CFG blocks] --&gt; DEF[find all DEF sites\nfor variable order]
    CFG2 --&gt; USE[find all USE sites\nfor variable order]
    DEF --&gt; D1[block 42: order = session.getAttribute]
    USE --&gt; U1[block 44: ifnull order]
    USE --&gt; U2[block 55: order.getDiscount]
    USE --&gt; U3[block 63: facade.submit order]
    D1 --&gt; SLICE[slice: D1 must produce non-null\nto reach U3; mock must return non-null account]

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef site fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef conclusion fill:#ede0f8,stroke:#7b2d9b,color:#3b0764
    class D1,U1,U2,U3 site
    class SLICE conclusion
</code></pre>

<hr />

<h2 id="technique-5-reaching-conditions">Technique 5: Reaching Conditions</h2>

<p><code class="language-plaintext highlighter-rouge">reaching-conditions</code> handles the precondition side explicitly. For each DFS path from method entry to a target sink line, it extracts every explicit branch condition (<code class="language-plaintext highlighter-rouge">JIfStmt</code> instructions along the path) and every implicit null assumption (field reads and virtual calls that will NPE if null). Each condition comes with its polarity (whether it was true or false on that path). The output is a structured list of preconditions that the model can translate directly into the arrange section of a JUnit test. The model is not reasoning about the CFG; it is transcribing a machine-computed answer to “what must be true to reach this line.”</p>

<p>The diagram below shows a concrete example: the red-highlighted spine traces the path to the sink, with each branch predicate annotated at the decision point: <code class="language-plaintext highlighter-rouge">obj1 != null</code>, <code class="language-plaintext highlighter-rouge">x &gt;= 0</code>, <code class="language-plaintext highlighter-rouge">obj2 != null</code>, <code class="language-plaintext highlighter-rouge">y &lt;= 3</code>. The green nodes are the conditions that must be satisfied; everything else in the CFG is irrelevant to reaching the sink.</p>

<p><img src="/assets/images/cfg-reaching-conditions.png" alt="Reaching Conditions" style="width:50%" /></p>

<hr />

<h2 id="technique-6-dynamic-tracing">Technique 6: Dynamic Tracing</h2>

<p>All of the above techniques are static. They tell you what <em>should</em> happen based on the structure of the code. Legacy codebases have a habit of confounding static analysis.</p>

<p>Runtime polymorphism, configuration loaded from a database at startup, feature flags in a properties file that nobody has updated since 2009, JNDI lookups that silently fail and return null: these are not visible in the CFG. The only way to know what actually executed is to observe it executing.</p>

<p>When a test fails unexpectedly, the inner Ralph loop follows a four-level escalation protocol. Each level is more invasive than the last; you only escalate when the previous level cannot identify the root cause.</p>

<pre><code class="language-mermaid">flowchart TD
    FAIL([test fails]) --&gt; L1[L1: Surefire XML\nread exception class and stack]
    L1 --&gt; Q1{exception visible?}
    Q1 --&gt;|yes| FIX1[fix stub or DAO setup]
    Q1 --&gt;|no: swallowed| L2[L2: AspectJ CatchRecorder\nfind catch site]
    L2 --&gt; Q1B{implicit NPE?}
    Q1B --&gt;|yes| L2B[L2: JFR Exception Recorder\nthrow-site capture]
    Q1B --&gt;|no| Q2{catch site found?}
    L2B --&gt; Q2
    Q2 --&gt;|yes| FIX2[fix at catch site]
    Q2 --&gt;|no| L3[L3: per-test JaCoCo\nfind divergence block]
    L3 --&gt; Q3{divergence found?}
    Q3 --&gt;|yes| FIX3[fix test data or mock]
    Q3 --&gt;|no| L4[L4: ASM Trace Agent\nfull method trace]
    L4 --&gt; FIX4[trace to root cause]

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef start fill:#fce7f3,stroke:#be185d,color:#831843
    classDef diag fill:#fce7f3,stroke:#be185d,color:#831843
    classDef fix fill:#d1fae5,stroke:#059669,color:#064e3b
    class FAIL start
    class L1,L2,L2B,L3,L4 diag
    class FIX1,FIX2,FIX3,FIX4 fix
</code></pre>

<p><strong>Level 1: Surefire XML.</strong> Zero overhead. The test report gives the exception class, message, and stack trace. This resolves most failures: wrong stub return type, missing mock setup, assertion on the wrong field. If the exception class is visible and the stack trace points somewhere useful, fix it here and never proceed to Level 2.</p>

<p><strong>Level 2: AspectJ CatchRecorder and JFR Exception Recorder.</strong> Two complementary tools for the class of failures where an exception is thrown somewhere inside application code and swallowed before it surfaces.</p>

<p>The AspectJ CatchRecorder weaves <code class="language-plaintext highlighter-rouge">after-throwing</code> advice onto every catch block in the application code. When an exception is caught, it logs the exception type, message, and catch site (class, method, line), without modifying a single source file. This is the difference between “the method returned null, I don’t know why” and “the method returned null because a <code class="language-plaintext highlighter-rouge">NullPointerException</code> was caught at line 87 of <code class="language-plaintext highlighter-rouge">AccountServiceImpl.updateAccount()</code> before the expected service call was reached.” The first leaves the model guessing. The second gives it a precise starting point.</p>

<p>The CatchRecorder has a blind spot: it only sees exceptions that land in user-code catch blocks. JVM-thrown implicit NPEs, <code class="language-plaintext highlighter-rouge">ArrayIndexOutOfBoundsException</code>, and exceptions caught inside Hibernate or Struts internals are invisible to it. The JFR Exception Recorder fills this gap. It captures every <code class="language-plaintext highlighter-rouge">jdk.JavaExceptionThrow</code> event at the throw site (before any catch block runs) with a full stack trace, filtered to application class prefixes. Implicit NPEs that were previously invisible become structured entries in <code class="language-plaintext highlighter-rouge">jfr-throws.json</code>. The combination means that <strong>no exception, thrown or swallowed anywhere in the execution, can escape unrecorded.</strong></p>

<p><strong>Level 3: Per-test JaCoCo.</strong> Enable coverage for the failing test in isolation and compare the executed blocks against the CFG path the test was designed to exercise. The first block that appears in the CFG path but not in the coverage report is the divergence point: the test did not reach it. The branch just before that block determines why. This resolves failures where the test data or mock return values drove execution down the wrong branch.</p>

<p><strong>Level 4: ASM Trace Agent.</strong> The heaviest tool. A bytecode instrumentation agent rewrites class bytecode as it is loaded to insert <code class="language-plaintext highlighter-rouge">ENTRY</code> and <code class="language-plaintext highlighter-rouge">EXIT</code> probes at every method boundary. The resulting trace is a complete execution record: which methods ran, in what order, and which did not. Enabling it is a one-line Maven Surefire change:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;argLine&gt;</span>@{argLine}
  -javaagent:${user.home}/tools/logging-agent.jar=prefix=com/example/app/web/ActionClass,com/example/app/service/ValidationServiceImpl
  -Dlogging.agent.trace=true
  -Dlogging.agent.branch=true<span class="nt">&lt;/argLine&gt;</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">prefix=</code> parameter confines instrumentation to the classes of interest. The resulting trace looks like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[Enter] ActionClass::processRequest
[Enter] BusinessLogicService::processRequest
[Branch] BusinessLogicService::processRequest:LINE IFEQ val=0 → TAKEN
[Enter] ValidationServiceImpl::validateAttributes
[Exit]  ValidationServiceImpl::validateAttributes
</code></pre></div></div>

<p><strong>Absent entries are as informative as present ones.</strong> If <code class="language-plaintext highlighter-rouge">validateAttributes</code> does not appear, the code never reached it, not as a hypothesis, but as a fact. Sometimes stubs, mocks, and test data all look correct but the test still exercises the wrong branch. Without the trace you are guessing which path was taken. The agent proves it.</p>

<p>The governing principle across all four levels is: <strong>prefer observation over inference</strong>. When a test fails unexpectedly, use instrumentation to get the runtime record instead of reasoning from source.</p>

<hr />

<h2 id="applying-techniques-dao-sql-capture">Applying Techniques: DAO SQL Capture</h2>

<h3 id="finding-the-dao-boundaries">Finding the DAO Boundaries</h3>

<p>Before capturing SQL, you need to know which DAOs in the calltree are genuine database boundaries. This sounds obvious (look for classes with “Dao” in the name) but in a large legacy codebase it is not. The forward calltree from an action method will contain dozens of nodes, and the DAO layer is not uniformly structured.</p>

<p>In this codebase, all genuine DAOs implement a common marker interface. That makes the initial candidate set computable: walk the calltree and filter to nodes whose class implements the interface. This is a codebase-specific condition; the pattern will differ elsewhere (a common base class, a naming convention, an annotation), but the principle is the same: a structural property computed from the call graph identifies the candidates.</p>

<pre><code class="language-mermaid">graph TD
    A[ProcessOrderAction.execute] --&gt; B[OrderValidationService.validate]
    A --&gt; C[OrderService.processOrder]
    B --&gt; D[AccountHelperDao.getAccount]
    B --&gt; E[ProductDao.findBySku]
    C --&gt; F[OrderDao.saveOrder]
    C --&gt; G[InventoryService.reserve]
    G --&gt; H[InventoryDao.decrementStock]
    G --&gt; I[AllocationHelperDao.checkAllocation]

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef action fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    classDef confirmed fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef suspect fill:#ffedd5,stroke:#c2410c,color:#7c2d12
    class A action
    class E,F,H confirmed
    class D,I suspect
</code></pre>

<p>Green nodes are confirmed DB boundaries. Orange nodes implement the DAO interface but need further investigation.</p>

<h3 id="eliminating-false-positives">Eliminating False Positives</h3>

<p>The DAO interface is implemented by both genuine DB-accessing classes and helper classes that happen to be wired polymorphically but do not touch the database. <code class="language-plaintext highlighter-rouge">AccountHelperDao</code> may delegate to a cache or an aggregation service; <code class="language-plaintext highlighter-rouge">AllocationHelperDao</code> may read from an in-memory map populated at startup. Treating them as DB boundaries and expecting SQL capture from them produces false positives in the coverage accounting: the harness runs them, captures nothing, and the gap looks like a CapturingConnection failure rather than a correct result.</p>

<p>The filter is a second-pass calltree. For each candidate, run a deep forward calltree from that class’s methods and scan the resulting node set for Hibernate and JDBC entry points: package prefixes (<code class="language-plaintext highlighter-rouge">org.hibernate</code>, <code class="language-plaintext highlighter-rouge">java.sql</code>) and known Hibernate method names (<code class="language-plaintext highlighter-rouge">Session.createQuery</code>, <code class="language-plaintext highlighter-rouge">Query.list</code>, <code class="language-plaintext highlighter-rouge">Query.setParameter</code>, <code class="language-plaintext highlighter-rouge">PreparedStatement.executeQuery</code>, and so on). A class whose deep calltree reaches none of these is not a database boundary.</p>

<pre><code class="language-mermaid">graph TD
    subgraph Real["ProductDao.findBySku: genuine boundary"]
        R1[ProductDao.findBySku] --&gt; R2[AbstractDao.getSession]
        R1 --&gt; R3[org.hibernate.Session.createQuery]
        R3 --&gt; R4[org.hibernate.Query.setParameter]
        R3 --&gt; R5[org.hibernate.Query.list]
        class R3,R4,R5 confirmed
    end

    subgraph Fake["AccountHelperDao.getAccount: false positive"]
        F1[AccountHelperDao.getAccount] --&gt; F2[AccountCacheService.lookup]
        F2 --&gt; F3[java.util.Map.get]
        F1 --&gt; F4[AccountService.findByCustomerId]
        F4 --&gt; F5[AccountService.buildFromResult]
        class F1 suspect
    end

    classDef default fill:#dde3f5,stroke:#6b7db3,color:#1a1f5e
    classDef confirmed fill:#d4edda,stroke:#388e3c,color:#1b5e20
    classDef suspect fill:#ffedd5,stroke:#c2410c,color:#7c2d12
</code></pre>

<p><code class="language-plaintext highlighter-rouge">ProductDao.findBySku</code> reaches <code class="language-plaintext highlighter-rouge">org.hibernate.Session</code> and <code class="language-plaintext highlighter-rouge">org.hibernate.Query</code> directly: confirmed boundary. <code class="language-plaintext highlighter-rouge">AccountHelperDao.getAccount</code> descends into cache and service layers and reaches only <code class="language-plaintext highlighter-rouge">java.util.Map.get</code>: no JDBC, no Hibernate, eliminated.</p>

<p>The output of this two-pass process is a confirmed set of genuine database boundaries worth exercising with the SQL capture harness.</p>

<h3 id="capturing-the-sql">Capturing the SQL</h3>

<p>Static analysis tells you that <code class="language-plaintext highlighter-rouge">OrderDao.saveOrder</code> will be called. It does not tell you what SQL will execute. For a Hibernate-backed J2EE codebase, that gap is real: Hibernate generates SQL dynamically from HQL plus an Oracle dialect at runtime. You cannot predict the exact statement from reading HQL, and you cannot run Oracle in CI.</p>

<p><code class="language-plaintext highlighter-rouge">CapturingConnection</code> is a JDBC <code class="language-plaintext highlighter-rouge">Connection</code> proxy wired into the Hibernate session factory in place of the real Oracle connection. Every call to <code class="language-plaintext highlighter-rouge">prepareStatement</code> or <code class="language-plaintext highlighter-rouge">prepareCall</code> is intercepted, logged to a JSONL file, and forwarded to H2. The result is a ground-truth record of the exact SQL the application intends to execute (including Oracle-specific syntax, bind parameters, and stored procedure calls) without modifying a single line of production code. It captures both standard <code class="language-plaintext highlighter-rouge">PreparedStatement</code> execution and JDBC-batched statements, which Hibernate uses for bulk writes.</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant T as JUnit Test
    participant D as DAO
    participant CC as CapturingConnection
    participant H2 as H2 DB
    T-&gt;&gt;D: saveOrder(order)
    D-&gt;&gt;CC: prepareStatement(sql)
    CC-&gt;&gt;CC: record sql to JSONL
    CC-&gt;&gt;H2: prepareStatement(sql)
    H2--&gt;&gt;CC: PreparedStatement
    CC--&gt;&gt;D: recording proxy
    D-&gt;&gt;CC: execute()
    CC-&gt;&gt;H2: execute()
    H2--&gt;&gt;CC: result
    T-&gt;&gt;CC: getCapturedSql()
    CC--&gt;&gt;T: list of sql strings
</code></pre>

<p>Running the DAO exercise harness against a target action flow produces a ground-truth record of every SQL statement that will execute. When the model writes a test for a DAO method, it can assert on that record directly. This is not something static analysis can supply.</p>

<h3 id="verifying-test-efficacy">Verifying Test Efficacy</h3>

<p>How do we make sure that every SQL-emitting DAO is exercised correctly (i.e., actually emitting SQLs through their tests)? There is also a verification step for that.</p>

<ul>
  <li>Assemble the list of all the relevant DAOs in the flow under test.</li>
  <li>Run all the DAO exercise harnesses and log the emitted SQLs, keyed by DAO class/method. It doesn’t matter if unrelated DAOs run or not.</li>
  <li>Filter the SQLs which are emitted only for the relevant DAOs.</li>
  <li>Make sure that those SQLs are not empty (or, if there are multiple tests for the same DAO class/method, there should be at least one non-empty SQL for that group).</li>
</ul>

<hr />

<h2 id="why-tools-not-just-an-llm">Why Tools, Not Just an LLM?</h2>

<table>
  <thead>
    <tr>
      <th> </th>
      <th>Without tools</th>
      <th>With tools</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Call graph</td>
      <td>Re-derived hop by hop, incomplete</td>
      <td><code class="language-plaintext highlighter-rouge">buildcg</code> + <code class="language-plaintext highlighter-rouge">fw-calltree</code>: exact, from bytecode</td>
    </tr>
    <tr>
      <td>CFG paths</td>
      <td>Guessed, misses branches</td>
      <td><code class="language-plaintext highlighter-rouge">intra-proc-cfg</code> + <code class="language-plaintext highlighter-rouge">flat-cfg-path-to-line</code>: exhaustive DFS</td>
    </tr>
    <tr>
      <td>Preconditions</td>
      <td>Manual AST tracing</td>
      <td><code class="language-plaintext highlighter-rouge">reaching-conditions</code>: explicit predicates with polarity</td>
    </tr>
    <tr>
      <td>Source bodies</td>
      <td>File hunting across 100k lines</td>
      <td><code class="language-plaintext highlighter-rouge">ast-emit</code>: batch-extracted, one JSON</td>
    </tr>
    <tr>
      <td>SQL</td>
      <td>Inferred from HQL, wrong</td>
      <td><code class="language-plaintext highlighter-rouge">CapturingConnection</code>: captured at runtime</td>
    </tr>
  </tbody>
</table>

<p>Without pre-computed artifacts, each reasoning step consumes tokens and compounds errors. Token cost grows with uncertainty.</p>

<hr />

<h2 id="four-diagnostic-incidents">Four Diagnostic Incidents</h2>

<p>These are from the actual Ralph Loop campaign, not constructed illustrations.</p>

<p><strong>CFG-guided closure of five uncovered lines in a service method.</strong> After a core service method reached 90% instruction coverage, JaCoCo identified five specific lines still uncovered. Rather than reading the method source and reasoning about what conditions reach each line, <code class="language-plaintext highlighter-rouge">flat-cfg-path-to-line.sh</code> was run against the precomputed CFG for each target. Every target had exactly two distinct execution paths from method entry. The flat trace JSONs, which were ordered lists of statements with branch conditions, were handed directly to the model, which read off the mock return values and input field assignments needed for each path and generated the corresponding tests. The five targets were closed in one pass. The key point is that the model was not asked to reason about control flow: it was asked to transcribe a machine-computed answer into test setup code, which it does reliably.</p>

<p><strong>Fifty-two DAOs with no SQL.</strong> The SQL coverage tool reported fifty-two DAO methods all returning <code class="language-plaintext highlighter-rouge">sqls=[]</code> from the capture harness. The first instinct would have been to read the source files individually. Instead, <code class="language-plaintext highlighter-rouge">fw-calltree</code> was run against the prebuilt callgraph for a sample of the failing methods. Every traversal converged on the same node: <code class="language-plaintext highlighter-rouge">org.hibernate.impl.SessionImpl.connection()</code>. The codebase used the deprecated <code class="language-plaintext highlighter-rouge">session.connection()</code> call to drop below Hibernate into raw JDBC for stored procedure execution, a pattern the SQL-detection regex did not recognise as SQL-emitting. One line added to the detection pattern resolved all fifty-two misses at once. Reading fifty-two source files would have found the same answer eventually, but only after substantial token expenditure and with meaningful probability of the model identifying the pattern incorrectly.</p>

<p><strong>Three tests that passed but measured nothing.</strong> The SQL coverage tool reported three DAO helper methods as EMPTY: tests existed, tests ran, but <code class="language-plaintext highlighter-rouge">sqls=[]</code> in every record. The model’s initial reading of the test code found them structurally correct: correct class, correct method call, correct SQL capture recording invocation. The EMPTY classification from the tool was the signal that something was suppressing SQL emission. Re-reading the tests with that question in focus revealed it: one test was passing an empty <code class="language-plaintext highlighter-rouge">StringBuilder</code>, causing <code class="language-plaintext highlighter-rouge">SQLGrammarException</code> before the query engine could run; another was passing a <code class="language-plaintext highlighter-rouge">null</code> Query object, causing an immediate NPE. Both exceptions were caught and silently ignored by the test’s <code class="language-plaintext highlighter-rouge">catch (Exception ignored)</code>. The fix was to call complete DAO methods that exercise the helpers internally, rather than calling the helpers directly with invalid inputs. Without the EMPTY signal from the coverage tool, the tests would have been counted as passing coverage.</p>

<p><strong>A 149-node calltree with no SQL.</strong> <code class="language-plaintext highlighter-rouge">fw-calltree</code> on a DAO’s <code class="language-plaintext highlighter-rouge">insert</code> method returned 149 nodes, which looks like a well-connected method. Inspecting the structure showed only two DAO methods in those 149 nodes; the remaining 147 were domain object getters and setters. The actual SQL-emitting path was behind a Spring DI <code class="language-plaintext highlighter-rouge">invokeinterface</code> on a field typed as a secondary DAO interface. Static analysis cannot resolve <code class="language-plaintext highlighter-rouge">invokeinterface</code> on injected fields without whole-program points-to analysis, and the callgraph edge did not exist. The calltree output surfaced this in one query: no <code class="language-plaintext highlighter-rouge">SessionImpl</code>, no <code class="language-plaintext highlighter-rouge">createQuery</code>, no SQL nodes anywhere in 149 nodes. The test infrastructure could then be adjusted accordingly. Tracing this through source files would have required following the injection wiring manually, and the model would likely not have identified the absent callgraph edge as the root cause.</p>

<hr />

<h2 id="where-llms-fit-in">Where LLMs fit in</h2>

<p>The clearest way to state the division of labour is this: the static and dynamic tools answer structural questions with precision and no hallucination. Claude reads those answers and produces the synthesis a developer needs: intent, narrative, data contracts, and test stubs. Neither half is useful alone.</p>

<table>
  <thead>
    <tr>
      <th>Question</th>
      <th>Who answers it</th>
      <th>Why</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>What code is reachable?</td>
      <td><code class="language-plaintext highlighter-rouge">buildcg</code> + <code class="language-plaintext highlighter-rouge">fw-calltree</code></td>
      <td>Deterministic over bytecode; no hallucination possible</td>
    </tr>
    <tr>
      <td>What are the execution paths?</td>
      <td><code class="language-plaintext highlighter-rouge">intra-proc-cfg</code> + <code class="language-plaintext highlighter-rouge">flat-cfg-path-to-line</code></td>
      <td>Exhaustive DFS enumeration; not guesswork</td>
    </tr>
    <tr>
      <td>What conditions guard each path?</td>
      <td><code class="language-plaintext highlighter-rouge">reaching-conditions</code></td>
      <td>Extracted from branch opcodes; exact polarity</td>
    </tr>
    <tr>
      <td>What does each variable depend on?</td>
      <td><code class="language-plaintext highlighter-rouge">ddg-slice</code></td>
      <td>Def-use computation; no inference</td>
    </tr>
    <tr>
      <td>What SQL does this path execute?</td>
      <td><code class="language-plaintext highlighter-rouge">CapturingConnection</code></td>
      <td>Actual runtime capture; not HQL interpretation</td>
    </tr>
    <tr>
      <td>What does this code intend to do?</td>
      <td>Claude</td>
      <td>Natural language reasoning over source; no compiler can do this</td>
    </tr>
    <tr>
      <td>What is the test’s business scenario?</td>
      <td>Claude</td>
      <td>Mapping structural facts to domain narrative</td>
    </tr>
    <tr>
      <td>What stubs and assertions follow?</td>
      <td>Claude</td>
      <td>Code generation from structured evidence</td>
    </tr>
  </tbody>
</table>

<p>The boundary between the two columns is the boundary between what a compiler can know and what requires language. Static tools produce verifiable facts. Claude produces synthesis. <strong>The flaw in most naive LLM-for-legacy-code approaches is to ask LLM to do both.</strong></p>

<hr />

<h2 id="caveats">Caveats</h2>

<p>The toolchain described here substantially reduces what the LLM needs to derive on its own. It does not eliminate the need for human judgment, and the loop is not completely fire-and-forget (yet).</p>

<ul>
  <li>
    <p><strong>The model still drifts.</strong> Even with pre-computed artifacts available, models revert to familiar patterns: grepping source files instead of querying the coverage JSON, reading a method body manually instead of using <code class="language-plaintext highlighter-rouge">ast-emit</code>, reasoning about paths instead of invoking <code class="language-plaintext highlighter-rouge">intra-proc-cfg</code>. The Ralph loop prompt needed iterative refinement to establish tool-use discipline: which tools to call first, in what order, and when to stop exploring and start generating.</p>
  </li>
  <li>
    <p><strong>The loop itself needed maintenance.</strong> New failure modes prompted updates to the outer loop prompt and diagnostic protocol. Framework patterns produced callgraph artifacts that the <code class="language-plaintext highlighter-rouge">--exclude-pattern</code> heuristic missed. The loop converged on its current form through iteration, not design upfront.</p>
  </li>
  <li><strong>Other techniques can be brought to bear.</strong> The techniques described here are the ones that proved most useful in practice; many of them are built on <a href="https://soot-oss.github.io/SootUp/">SootUp</a>’s analysis infrastructure. Others are available depending on the failure mode.
    <ul>
      <li><strong>Dominator analysis</strong> computes which nodes every path to a target must pass through: the mandatory checkpoints that any test for a given target must exercise, regardless of which branch is taken. This is useful for identifying which mock setups are non-negotiable. Escape analysis can determine which objects cross method boundaries and therefore which fields cannot be independently mocked.</li>
      <li><strong>Alias analysis</strong> (which reads of a variable refer to the same heap location) is already present in <code class="language-plaintext highlighter-rouge">ddg-slice</code>: the current implementation uses a conservative may-alias approximation (every pair of references is assumed to potentially alias), which is sound but imprecise; full Qilin-backed alias resolution is available when greater precision is needed. These were not needed at full precision in this campaign, but the infrastructure (SootUp’s analysis passes) is the same; the level of precision can be dialled up without replacing anything already there.</li>
    </ul>
  </li>
  <li><strong>Human judgment is still in the loop.</strong> The model generates tests from structured artifacts, but someone still has to decide which action flows are worth targeting, what coverage threshold is meaningful, and whether a passing test is testing the right thing.</li>
</ul>

<hr />

<h2 id="references">References</h2>

<ul>
  <li><a href="/2023/01/10/tests-proof-probability.html">Tests increase our Knowledge of the System: A Proof from Probability</a></li>
  <li><a href="https://soot-oss.github.io/SootUp/">SootUp</a>: modern Java bytecode analysis framework; provides the Jimple IR used for CFG extraction, def-use analysis, and call graph construction</li>
  <li><a href="https://github.com/QilinPTA/Qilin">Qilin</a>: context-sensitive points-to analysis for Java; resolves virtual dispatch in call graph construction</li>
  <li><a href="https://www.jacoco.org/jacoco/">JaCoCo: Java Code Coverage Library</a></li>
  <li><a href="https://eclipse.dev/aspectj/">AspectJ Load-Time Weaving</a></li>
  <li><a href="https://ctags.io/">Universal Ctags</a>: symbol indexing for source lookup</li>
  <li><a href="https://ast-grep.github.io/">ast-grep</a>: structural code search with AST-aware patterns</li>
  <li><a href="https://docs.oracle.com/javacomponents/jmc-5-4/jfr-runtime-guide/about.htm#JFRUH170">Java Flight Recorder (JFR)</a>: <code class="language-plaintext highlighter-rouge">jdk.JavaExceptionThrow</code> event for throw-site capture</li>
</ul>]]></content><author><name>avishek</name></author><category term="Software Engineering" /><category term="GenAI" /><category term="Program Analysis" /><category term="Testing" /><category term="Control Flow" /><category term="Dataflow Analysis" /><category term="Harness Engineering" /><summary type="html"><![CDATA[There is an optimistic and a pessimistic reading of what GenAI does to the problem of large legacy codebases.]]></summary></entry><entry><title type="html">Against Enclosure: Software Architecture as a Political Act</title><link href="http://localhost:4000/2026/05/17/against-enclosure-software-architecture-as-political-act.html" rel="alternate" type="text/html" title="Against Enclosure: Software Architecture as a Political Act" /><published>2026-05-17T00:00:00+05:30</published><updated>2026-05-17T00:00:00+05:30</updated><id>http://localhost:4000/2026/05/17/against-enclosure-software-architecture-as-political-act</id><content type="html" xml:base="http://localhost:4000/2026/05/17/against-enclosure-software-architecture-as-political-act.html"><![CDATA[<p><em>Software architecture has politics baked into it. Choosing between a plugin-based platform and a pile of small composable tools is, among other things, choosing whether somebody can fence off the result later. This post makes the case for composability on those grounds: not because it always makes better software, but because what it makes is hard to capture.</em></p>

<hr />

<h2 id="table-of-contents">Table of Contents</h2>

<ul>
  <li><a href="#the-chain-plugin-architecture--platform--enclosure">The Chain: Plugin Architecture → Platform → Enclosure</a></li>
  <li><a href="#what-plugin-architectures-actually-do">What Plugin Architectures Actually Do</a></li>
  <li><a href="#the-political-argument-enclosure-ip-and-the-escape-hatch">The Political Argument: Enclosure, IP, and the Escape Hatch</a>
    <ul>
      <li><a href="#rent-seeking">Rent-Seeking</a></li>
      <li><a href="#ip-as-the-mechanism-of-enclosure">IP as the Mechanism of Enclosure</a></li>
      <li><a href="#licensing-theatre">Licensing Theatre</a></li>
      <li><a href="#the-machinery-analogy-the-escape-hatch">The Machinery Analogy: The Escape Hatch</a></li>
    </ul>
  </li>
  <li><a href="#the-composable-alternative-unbundling-the-platform">The Composable Alternative: Unbundling the Platform</a></li>
  <li><a href="#ipc-as-substrate-all-the-patterns-already-exist">IPC as Substrate: All the Patterns Already Exist</a></li>
  <li><a href="#living-proof-five-projects-five-enclosure-vectors-eliminated">Living Proof: Five Projects, Five Enclosure Vectors Eliminated</a>
    <ul>
      <li><a href="#lsp-eliminating-vendor-bundling">LSP: Eliminating Vendor Bundling</a></li>
      <li><a href="#sqlite-eliminating-server-and-copyright-control">SQLite: Eliminating Server and Copyright Control</a></li>
      <li><a href="#nix-eliminating-registry-control">Nix: Eliminating Registry Control</a></li>
      <li><a href="#sourcehut-eliminating-platform-network-effects">SourceHut: Eliminating Platform Network Effects</a></li>
      <li><a href="#gemini-eliminating-the-monetisation-surface">Gemini: Eliminating the Monetisation Surface</a></li>
      <li><a href="#the-pattern">The Pattern</a></li>
    </ul>
  </li>
  <li><a href="#intellectual-lineage">Intellectual Lineage</a></li>
  <li><a href="#honest-limits">Honest Limits</a></li>
</ul>

<hr />

<h2 id="the-chain-plugin-architecture--platform--enclosure">The Chain: Plugin Architecture → Platform → Enclosure</h2>

<p>I’ve built a fair number of systems around plugin architectures, and I built them because they seemed like the obvious answer to extensibility. You define a host, you define a contract, and anyone who follows the contract can extend the system. It’s clean and modular, and it feels like the right shape for software that’s supposed to grow.</p>

<p>What took me longer to notice is that this shape has consequences outside the code. A plugin architecture tends to turn into a platform, and platforms are the things that get enclosed.</p>

<p>“Enclosure” comes from English history. Between roughly the sixteenth and eighteenth centuries, land that had been held in common (used by everyone, owned by nobody) was fenced off, privatised, and rented out. People who had farmed it for free became tenants paying to keep doing the same thing. The recipe is simple: take something shared, put a boundary around it, and charge people to cross. In software the thing being fenced isn’t land, it’s capability: being able to extend a system, interoperate with it, wire it up to other tools. What gets fenced is the interface, the ecosystem, the protocol, and whoever controls the contract gets to put up the fence. Aaron Swartz, in the <em>Guerilla Open Access Manifesto</em>, didn’t bother with polite language for this kind of thing: he called it theft, not of anyone’s private property, but of something that had belonged to everybody.</p>

<p>Here’s how it plays out. A plugin host handles discovery (how extensions get found), lifecycle (how they’re loaded and unloaded), interface (how they talk to the host), and composition (what gets called when). All four live under one contract, and the host owns it. So the host becomes indispensable, not because it does anything clever, but because it’s the only thing that speaks the contract. Extensions can’t talk to each other without it, users can’t combine things without it, and everything the system can do goes through it.</p>

<p>That’s a platform. Platforms make attractive targets because everything valuable is in one place: the contract, the ecosystem, the users. A company can fence off a platform in a way it can’t fence off a bunch of independent tools. The plugin contract turns into IP, the ecosystem gets locked in, the host becomes a toll booth, and the plugin authors end up as tenants.</p>

<p>Nobody has to be acting in bad faith for this to happen. The architecture creates the incentive, and the incentive does the rest.</p>

<p>So what’s the opposite of a platform, architecturally? That’s what I’ve been trying to work out.</p>

<hr />

<h2 id="what-plugin-architectures-actually-do">What Plugin Architectures Actually Do</h2>

<p>It helps to pull apart what a plugin architecture is doing. There are four things going on at once:</p>

<p><strong>Discovery</strong>: the host decides how extensions are found. It might scan a directory, query a registry, or read a manifest it controls. Extensions don’t find each other; the host finds them.</p>

<p><strong>Lifecycle</strong>: the host calls <code class="language-plaintext highlighter-rouge">init()</code>, <code class="language-plaintext highlighter-rouge">register()</code>, <code class="language-plaintext highlighter-rouge">shutdown()</code> on each extension’s behalf. It owns the process. Extensions exist at the host’s pleasure.</p>

<p><strong>Interface</strong>: the host defines the vocabulary. The plugin API, the callback table, the event types are all specified by the host, and every extension has to speak them. An extension written for host A won’t run under host B because the vocabulary is different.</p>

<p><strong>Composition logic</strong>: the host owns the dispatch loop. It decides what fires when, what data goes where, and what’s in scope. Extensions react to events the host defines.</p>

<p>Bundling all four under one host-owned contract is what turns a plugin host into a platform. No single one of these gives the host leverage; it’s the combination. Pull one out and the rest can still be captured. Put all four on public ground and there’s no host left to capture.</p>

<p>This isn’t a flaw in some particular plugin system; it comes with the pattern. Every plugin architecture I’ve worked with has looked like this, however well-meaning, open-source or liberally licensed it was. So the real question is what to use instead.</p>

<hr />

<h2 id="the-political-argument-enclosure-ip-and-the-escape-hatch">The Political Argument: Enclosure, IP, and the Escape Hatch</h2>

<h3 id="rent-seeking">Rent-Seeking</h3>

<p>Economists have a word for what platforms do: rent-seeking. They set up a toll booth and charge for traffic they didn’t create. The plugin authors make the value and the platform collects it. Software didn’t invent this. Landlords, patent trolls, and plenty of financial middlemen do the same thing, putting themselves between producer and consumer without adding much for either.</p>

<p>You can design architecture to make rent-seeking hard. Unix did this for decades without anyone really saying so out loud. Unix tools were hard to capture because stdin and stdout are too generic to own and each tool is too small to put a gate in front of. The interface is text on a stream, and nobody holds a copyright on a newline. The composition happens in the user’s shell (and the user’s head), and you can’t fence those off either.</p>

<h3 id="ip-as-the-mechanism-of-enclosure">IP as the Mechanism of Enclosure</h3>

<p>A plugin contract isn’t just an API; it’s something you can try to copyright. <em>Oracle v. Google</em> went all the way to the Supreme Court over whether APIs can be owned. Google won on fair use, but the court sidestepped whether APIs are copyrightable in the first place, so that question is still open. Plugin interfaces, event models, callback signatures: any of these can be claimed as IP.</p>

<p>The ecosystem on top makes the lock-in worse. Network effects pile up on the platform, not on the individual tools. More extensions make the platform more valuable, and a more valuable platform is harder to leave. It feeds itself.</p>

<p>Open-source implementations don’t fix this. If the host is MIT-licensed but a single foundation controls the plugin contract, you’re in the same position as before. Every extension has to conform to the contract, so whoever controls the contract controls the ecosystem, whatever license the host’s code happens to be under.</p>

<h3 id="licensing-theatre">Licensing Theatre</h3>

<p>Over the last few years, platforms have also started defending themselves against the composable alternative with licenses. SSPL (Server Side Public License), BUSL (Business Source License), and a growing set of “source-available” licenses let you read the code but not run it as a competing service. The architecture and the license prop each other up: the plugin contract ties the ecosystem to the host, and the license stops anyone forking the host. It’s enclosure by legal means, made possible by a centralised architecture.</p>

<p>These licenses are often pitched as protecting open-source maintainers from cloud vendors, and that’s not entirely spin; the cloud vendors really do take advantage. But the end result is the same either way: architecture plus license gives you a captive ecosystem. You can see all the parts; you just aren’t free to do much with them.</p>

<h3 id="the-machinery-analogy-the-escape-hatch">The Machinery Analogy: The Escape Hatch</h3>

<p>Think about a fully assembled machine: an industrial lathe, a press, a CNC router. The vendor can brand it, price it, lock it behind a license or subscription or activation code, and eventually kill it by ending support and pushing you towards an expensive upgrade. You’re a customer, on their terms.</p>

<p>The parts (bearings, spindles, fasteners, motors) are too generic to own. Nobody holds a useful patent on a bolt. They’re commodities because they sit below any particular application. Fastener standards like the M6 thread belong to everyone, which is why one company’s bolt fits another company’s nut.</p>

<p>If you know how to put the parts together, you can build something that fits what you need and that nobody else controls. No vendor has leverage over you, because there is no vendor, just parts and your own work.</p>

<p>Software works the same way. Each small tool is a part, too thin to gate and too generic to brand. The conventions (text streams, public schemas, open protocols) are the thread standard. Nobody holds a copyright on JSON. The composition is the machine you build, and it lives in your shell history, your Makefile, your Datalog rules. It’s yours.</p>

<p>So the way out is: get generic parts, put them together yourself, and keep what you build.</p>

<hr />

<h2 id="the-composable-alternative-unbundling-the-platform">The Composable Alternative: Unbundling the Platform</h2>

<p>If the problem is four concerns bundled under one owned contract, the fix is to put each of them somewhere nobody owns.</p>

<table>
  <thead>
    <tr>
      <th>Concern</th>
      <th>Plugin approach</th>
      <th>Composable analog</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Discovery</td>
      <td>Host-owned registry or manifest</td>
      <td><code class="language-plaintext highlighter-rouge">$PATH</code> convention, prefix naming, content-addressed hashes</td>
    </tr>
    <tr>
      <td>Lifecycle</td>
      <td>Host calls init/shutdown</td>
      <td><code class="language-plaintext highlighter-rouge">fork/exec</code> (the OS handles it)</td>
    </tr>
    <tr>
      <td>Interface</td>
      <td>Host-defined API or callback table</td>
      <td>stdin/stdout JSONL, public schema, open protocol</td>
    </tr>
    <tr>
      <td>Composition</td>
      <td>Host dispatch loop</td>
      <td>Shell pipeline, Makefile, Datalog rules (user owns it)</td>
    </tr>
  </tbody>
</table>

<p>Once each concern is on public ground, there’s no host to capture. There’s no “ecosystem” as a single thing someone could take over, just tools that speak a shared language, and the language doesn’t belong to anyone.</p>

<p><strong>Discovery</strong> by <code class="language-plaintext highlighter-rouge">$PATH</code> convention means anyone can ship a tool that joins in just by naming it right. The <code class="language-plaintext highlighter-rouge">git-*</code> subcommand pattern is the best-known example: <code class="language-plaintext highlighter-rouge">git foo</code> finds <code class="language-plaintext highlighter-rouge">git-foo</code> on <code class="language-plaintext highlighter-rouge">$PATH</code>. Git doesn’t own the namespace; it just looks. A prefix naming convention does the same job: discovery without anyone owning a registry.</p>

<p><strong>Lifecycle</strong> by <code class="language-plaintext highlighter-rouge">fork/exec</code> means the OS is the runtime. There’s no <code class="language-plaintext highlighter-rouge">register_plugin()</code> ritual, no <code class="language-plaintext highlighter-rouge">init()</code> callback, no host-controlled process table. The tool runs, produces output, and exits. That’s how CGI worked, it’s how LSP works, and it covers every lifecycle concern that matters in practice.</p>

<p><strong>Interface</strong> on public ground means the contract is a format or a protocol, not an API. JSON on stdin/stdout is a contract nobody owns. A published schema (JSON Schema, Protobuf with public <code class="language-plaintext highlighter-rouge">.proto</code> files, Datalog facts with a public spec) can be implemented independently by anyone producing or consuming it. Publishing an interface properly, with a spec, a reference implementation and an open license, leaves very little to claim as IP. It’s a bit like defensive publication in patent law: once the interface is public and documented, it’s very hard for anyone to say they own conformance to it.</p>

<p><strong>Composition logic</strong> in a shell pipeline or a Makefile lives with the user, version-controlled in the user’s own repository. The user decides what runs when. The user owns the assembly.</p>

<h3 id="a-concrete-illustration">A Concrete Illustration</h3>

<p><code class="language-plaintext highlighter-rouge">java-bytecode-tools</code> is a static analysis and visualisation toolkit for Java bytecode. Its <code class="language-plaintext highlighter-rouge">PHILOSOPHY.md</code> puts it plainly: “toolkit of mechanisms, not workflows.” The architecture follows the pattern above:</p>

<ul>
  <li><strong>Discovery</strong>: a prefix naming convention: <code class="language-plaintext highlighter-rouge">ftrace-*</code> tools for CFG trace analysis, <code class="language-plaintext highlighter-rouge">ddg-*</code> for data dependency graphs, <code class="language-plaintext highlighter-rouge">calltree-*</code> for call tree rendering. No registry, no manifest. A tool exists if it’s on the path and speaks the right format.</li>
  <li><strong>Lifecycle</strong>: every tool is a standalone Unix filter. <code class="language-plaintext highlighter-rouge">fork/exec</code>. The OS is the runtime.</li>
  <li><strong>Interface</strong>: JSON on stdin/stdout throughout. The Java CLI writes JSON to stdout; the Python tools read from stdin or a file argument and write to stdout. The schema is documented, and nothing about it is proprietary.</li>
  <li><strong>Composition</strong>: the pipeline stages are spelled out: <code class="language-plaintext highlighter-rouge">xtrace → ftrace-expand-refs → ftrace-inter-slice → ftrace-semantic → ftrace-semantic-to-dot</code>. This lives in shell scripts and task runner configs. You can swap out any stage, cache any intermediate output, or branch the pipeline, without asking anyone’s permission.</li>
</ul>

<p>There’s no plugin marketplace, no extension store, no host. There’s a documented schema and a naming convention, and neither gives anybody anything to take over.</p>

<hr />

<h2 id="ipc-as-substrate-all-the-patterns-already-exist">IPC as Substrate: All the Patterns Already Exist</h2>

<p>A common objection is that real systems need more than simple pipelines: pub/sub, event-driven dispatch, fan-out, shared state. The assumption is that those need a framework, and a framework needs an owner.</p>

<p>They don’t. Every communication pattern you’d find in a plugin architecture is already there in plain POSIX:</p>

<ul>
  <li><strong>Request/response</strong>: subprocess + stdio. One process writes a request; the other reads it and writes a response. That’s what CGI was in 1993, and it’s what LSP is today.</li>
  <li><strong>Streaming pipelines</strong>: anonymous pipes with backpressure handled by the OS. Writes block when the pipe buffer fills, so the OS does the flow control.</li>
  <li><strong>Pub/sub</strong>: append-only files with <code class="language-plaintext highlighter-rouge">inotify</code>, or a thin socket broker that fans messages out. <code class="language-plaintext highlighter-rouge">tail -f</code> on a log file is pub/sub, with the file as the topic and the filesystem as the broker.</li>
  <li><strong>Fan-out/fan-in</strong>: <code class="language-plaintext highlighter-rouge">xargs -P</code>, <code class="language-plaintext highlighter-rouge">make -j</code>, or <code class="language-plaintext highlighter-rouge">select</code>/<code class="language-plaintext highlighter-rouge">epoll</code> on several sockets. Scatter-gather is available in every Unix shell.</li>
  <li><strong>Event sourcing</strong>: an append-only log. Consumers read at their own pace and can rewind. Git’s object store, syslog, and your shell history are all event sourcing without a framework.</li>
  <li><strong>Coordination</strong>: <code class="language-plaintext highlighter-rouge">flock</code> for advisory locking, atomic <code class="language-plaintext highlighter-rouge">rename</code> for atomic publish, <code class="language-plaintext highlighter-rouge">mkdir</code> as a mutex (atomic on POSIX filesystems).</li>
  <li><strong>Capability passing</strong>: Unix domain sockets can pass file descriptors between processes. One process opens a resource and hands the open handle to another, which never needed permission to open it itself. That’s object-capability security on Unix.</li>
  <li><strong>Shared state</strong>: SQLite or LMDB over memory-mapped files: a file format nobody owns, with bindings in every language.</li>
</ul>

<p>The kernel is the one framework you can’t avoid, and it already ships all of this. Everything above it is somebody’s opinion, and opinions are where vendor contracts tend to creep in.</p>

<hr />

<h2 id="living-proof-five-projects-five-enclosure-vectors-eliminated">Living Proof: Five Projects, Five Enclosure Vectors Eliminated</h2>

<p>So far this has been fairly abstract. Here are five real projects where it works in practice, each one closing off a different route to enclosure.</p>

<h3 id="lsp-eliminating-vendor-bundling">LSP: Eliminating Vendor Bundling</h3>

<p>Before the Language Server Protocol, adding language support to editors was an N×M problem: N editors times M languages, with every integration tied to the editor vendor. Microsoft’s Visual Studio had Roslyn. JetBrains had PSI. Sublime had its own plugin model. Switching editors meant losing all your language tooling.</p>

<p>LSP (first shipped with VS Code in 2016) is a JSON-RPC protocol between a text editor (the client) and a language server (a separate process). The server runs separately from the editor: <code class="language-plaintext highlighter-rouge">fork/exec</code>, stdio transport by default, a public JSON-RPC wire format. The spec is published under Creative Commons.</p>

<p>The upshot: rust-analyzer works just as well in Neovim, Emacs, Helix, and VS Code, and Microsoft has no technical way to make it worse elsewhere. JetBrains, historically the strongest proprietary language-tooling vendor, ended up adding LSP support because developers wanted it. The Helix editor has no plugin system at all; LSP is the only way to extend it. A public protocol replaced the proprietary integrations, and the N×M market fell apart.</p>

<h3 id="sqlite-eliminating-server-and-copyright-control">SQLite: Eliminating Server and Copyright Control</h3>

<p>SQLite is in the public domain. Not MIT, not Apache 2.0: actually public domain. There’s no copyright holder to make threats, no CLA to revoke, no license to change. It has no server either; it’s a library, not a daemon. The database is a file. You link SQLite into your application and it reads and writes bytes. The file format is fully documented in a published spec that’s guaranteed to stay stable.</p>

<p>SQLite’s own <a href="https://www.sqlite.org/whentouse.html">When To Use</a> page puts it like this: “SQLite does not compete with client/server databases. SQLite competes with <code class="language-plaintext highlighter-rouge">fopen()</code>.”</p>

<p>SQLite replaces raw bytes on disk, which nobody owns, with a file format that nobody owns either. There’s no “managed SQLite” to sell, because there’s no server to manage. Oracle, Microsoft, and Amazon all ship products that sit next to or on top of SQLite without being able to take it over. The usual three routes to enclosure (copyright, a server, a proprietary wire protocol) are all missing at once.</p>

<h3 id="nix-eliminating-registry-control">Nix: Eliminating Registry Control</h3>

<p>Every package in Nix is identified by a cryptographic hash of its inputs: source code, build flags, dependencies, build script. A store path like <code class="language-plaintext highlighter-rouge">/nix/store/abc123...-openssl-3.0.7</code> encodes the artifact’s whole build history. There’s no mutable global namespace to control, and no registry whose owner can revoke a package or change what a name points to.</p>

<p>When the Nix Foundation went through its governance fights in 2023–2024, contributors who disagreed forked off to form the Lix project, and had a fully compatible implementation within weeks. That only worked because the formats (derivation files, store paths) are public data rather than an API a foundation controls. You can’t have a governance fight over a hash.</p>

<h3 id="sourcehut-eliminating-platform-network-effects">SourceHut: Eliminating Platform Network Effects</h3>

<p>SourceHut’s code review and patch workflow runs on plain-text email and <code class="language-plaintext highlighter-rouge">git format-patch</code>. A patch is a file sent to a mailing list, and a review is a reply. There’s no proprietary API, no OAuth token to revoke, no webhook to switch off, no social graph that makes it painful to leave.</p>

<p>Drew DeVault, its founder, makes the case in <a href="https://drewdevault.com/blog/Git-is-already-distributed/">Git is already federated &amp; decentralized</a> (2018): email is “already standardized”, “decentralized and federated, and it’s <em>already</em> integrated with git.” And if the host goes away, nothing is lost: “If everything is being conducted over email instead, all of the data already lives in the user’s inbox. Freely available tools can take their mail spool and publish a new archive if our services go down.”</p>

<p>The Linux kernel, Git itself, and plenty of other big open source projects have always worked this way. No platform has ever captured these workflows, because they’re older than platforms and go around them.</p>

<h3 id="gemini-eliminating-the-monetisation-surface">Gemini: Eliminating the Monetisation Surface</h3>

<p>The Gemini protocol spec is about three thousand words, and it’s deliberately frozen at that size. It leaves out JavaScript, cookies, inline images (beyond one specific mechanism), forms, user tracking, and any way of running code on the client. These are deliberate omissions, not missing features.</p>

<p>The <a href="https://geminiprotocol.net/docs/faq.gmi">Gemini FAQ</a> is upfront about the consequence: “Because by default it only presents users with text, and because authors have no way to control the font or size or colour of that text, Gemini is naturally resistant to advertising and marketing.”</p>

<p>So Gemini doesn’t avoid monetisation as a matter of policy; it just doesn’t give monetisation anything to work with. There’s no code execution and no state, so there’s nowhere for ad-tech to run.</p>

<h3 id="the-pattern">The Pattern</h3>

<table>
  <thead>
    <tr>
      <th>Project</th>
      <th>Enclosure vector eliminated</th>
      <th>How</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>LSP</td>
      <td>Vendor bundling of language tooling</td>
      <td>Separate process + public JSON-RPC protocol breaks N×M</td>
    </tr>
    <tr>
      <td>SQLite</td>
      <td>Server + copyright control</td>
      <td>Public domain + fully documented single-file format</td>
    </tr>
    <tr>
      <td>Nix</td>
      <td>Registry/namespace control</td>
      <td>Content-addressing replaces mutable names</td>
    </tr>
    <tr>
      <td>SourceHut</td>
      <td>Platform network effects</td>
      <td>Email/protocol replaces API/social graph</td>
    </tr>
    <tr>
      <td>Gemini</td>
      <td>Monetisation surface</td>
      <td>Spec permanently excludes execution + state</td>
    </tr>
  </tbody>
</table>

<p>What these have in common is that each one gets rid of the central point that enclosure depends on. You can’t fence off a hash, or SMTP, or a protocol that won’t run your code, or a separate process speaking a public schema, or a file format nobody owns.</p>

<hr />

<h2 id="intellectual-lineage">Intellectual Lineage</h2>

<p>None of this is new; plenty of people have made versions of this argument before me.</p>

<p>The Unix tradition got there first. Eric Raymond’s <em>The Art of Unix Programming</em> lays out the design principles well, though it mostly doesn’t spell out the political side: that composition works against enclosure. As I said earlier, Unix tools stayed hard to capture because the interface was too generic to own and each tool was too small to gate. The composition lived in people’s shell histories, which have never been anybody’s IP.</p>

<p>Ivan Illich’s <em>Tools for Conviviality</em> (1973) gives a more general way of talking about it. Illich argued that past a certain point, tools stop serving the people using them and start making those people serve the tool. A hammer is “convivial”: it does what you make it do, and how well things go depends on your skill. An industrial lathe, past a certain scale, needs a trained operator who works to the machine’s requirements. I’d put plugin architectures on the wrong side of that line. You end up working for the platform: learning its event model, conforming to its API, fitting your extension to its lifecycle. It doesn’t adapt to you.</p>

<p>Cory Doctorow’s “adversarial interoperability” (building things that work with existing platforms without asking their permission) is roughly the legal-strategy version of this argument. Mike Masnick’s <em>Protocols, Not Platforms</em> is probably the best short version. Ink &amp; Switch’s local-first essay (Kleppmann et al., 2019) makes the technical case for keeping data and computation on the user’s machine, which takes away the metering point SaaS relies on. The permacomputing and small-web people are putting a lot of the same ideas into practice, under other names.</p>

<p>These people aren’t one movement, and most of them wouldn’t think of themselves as being on the same side. But the same idea keeps turning up across all of them: the architecture is the politics. You can’t really pull the technical choice apart from what it does politically.</p>

<hr />

<h2 id="honest-limits">Honest Limits</h2>

<p>This approach has real costs, and most of them land on people who aren’t practitioners. Back to the machinery analogy: building from parts means knowing what the parts are, how they fit, and what you’re trying to end up with. Most people don’t want to be mechanics. They want a car that starts when they turn the key.</p>

<p>Historically, the market’s answer has been to let a company hide the composition behind a product, which is exactly the enclosure I’ve been arguing against. “Hard to monetise” and “hard for non-experts to use” overlap a lot. Composable tools suit people doing serious work who are willing to learn their tools. They aren’t a general answer to how software should reach everyone.</p>

<p>I don’t think you can engineer that away; it’s a real tradeoff. Going composable means giving up the mass market. Whether that’s worth it depends on what work you care about.</p>

<p>For me it is. The alternative is building something that can be enclosed, and then watching it happen.</p>]]></content><author><name>avishek</name></author><category term="Software Engineering" /><category term="Architecture" /><category term="Open Source" /><category term="Philosophy" /><category term="Unix" /><category term="Composability" /><summary type="html"><![CDATA[Software architecture has politics baked into it. Choosing between a plugin-based platform and a pile of small composable tools is, among other things, choosing whether somebody can fence off the result later. This post makes the case for composability on those grounds: not because it always makes better software, but because what it makes is hard to capture.]]></summary></entry><entry><title type="html">Engineering Log: An AI Harness for RedDragon</title><link href="http://localhost:4000/2026/04/16/engineering-log-reddragon-testing-harness.html" rel="alternate" type="text/html" title="Engineering Log: An AI Harness for RedDragon" /><published>2026-04-16T00:00:00+05:30</published><updated>2026-04-16T00:00:00+05:30</updated><id>http://localhost:4000/2026/04/16/engineering-log-reddragon-testing-harness</id><content type="html" xml:base="http://localhost:4000/2026/04/16/engineering-log-reddragon-testing-harness.html"><![CDATA[<p><em><a href="https://github.com/avishek-sen-gupta/red-dragon">RedDragon</a> is a multi-language interpreter/compiler that lowers 16 languages (Python, Java, Go, TypeScript, Rust, C, C++, C#, JavaScript, Kotlin, Lua, PHP, Ruby, Swift, Scala, COBOL) down to a shared IR. With 13,000+ tests across 16 frontends, keeping quality high and coverage visible requires a harness that operates at several layers simultaneously. This post documents that harness in full: how language feature coverage is tracked through feature enums, how the pre-commit pipeline is structured, and how Claude Code’s hook system is wired to enforce workflow discipline at edit time.</em></p>

<p><em>This is a work in progress. The harness described here reflects the current state of the tooling, but it is actively evolving: new gates get added as pain points emerge, non-blocking warnings get promoted to blockers as violation counts drop, and the hook and skills infrastructure grows alongside the codebase. Treat this as a snapshot, not a finished design.</em></p>

<hr />

<h2 id="table-of-contents">Table of Contents</h2>

<ul>
  <li><a href="#claudemd-the-llm-guidance-layer">CLAUDE.md: The LLM Guidance Layer</a></li>
  <li><a href="#language-feature-coverage-tracking">Language Feature Coverage Tracking</a>
    <ul>
      <li><a href="#feature-enums-self-documenting-members">Feature Enums: Self-Documenting Members</a></li>
      <li><a href="#the-covers-decorator">The @covers Decorator</a></li>
      <li><a href="#the-coverage-audit-script">The Coverage Audit Script</a></li>
      <li><a href="#what-uncovered-means">What Uncovered Means</a></li>
    </ul>
  </li>
  <li><a href="#the-pre-commit-pipeline">The Pre-commit Pipeline</a>
    <ul>
      <li><a href="#talisman-secret-detection">Talisman: Secret Detection</a></li>
      <li><a href="#terminology-guard">Terminology Guard</a></li>
      <li><a href="#black-auto-format">Black: Auto-format</a></li>
      <li><a href="#python-fp-lint-functional-programming-warnings">Python FP Lint: Functional Programming Warnings</a></li>
      <li><a href="#import-linter-architectural-contracts">import-linter: Architectural Contracts</a></li>
      <li><a href="#full-test-suite">Full Test Suite</a></li>
      <li><a href="#beads-backup">Beads Backup</a></li>
    </ul>
  </li>
  <li><a href="#claude-code-hooks-prepost-tool-use">Claude Code Hooks: Pre/Post Tool Use</a>
    <ul>
      <li><a href="#userpromptsubmit-contextual-invariant-injection">UserPromptSubmit: Contextual Invariant Injection</a></li>
      <li><a href="#pretooluse-the-gate-layer">PreToolUse: The Gate Layer</a></li>
    </ul>
  </li>
  <li><a href="#skills-and-workflow-automation">Skills and Workflow Automation</a>
    <ul>
      <li><a href="#superpowers-core-development-lifecycle-skills">Superpowers: Core Development Lifecycle Skills</a></li>
      <li><a href="#project-level-skills">Project-Level Skills</a></li>
      <li><a href="#plugins-context-injector-and-python-fp-lint">Plugins: Context Injector and Python FP Lint</a></li>
    </ul>
  </li>
  <li><a href="#the-full-picture">The Full Picture</a></li>
  <li><a href="#conclusion">Conclusion</a></li>
</ul>

<hr />

<h2 id="claudemd-the-llm-guidance-layer">CLAUDE.md: The LLM Guidance Layer</h2>

<p><code class="language-plaintext highlighter-rouge">CLAUDE.md</code> is Claude Code’s project instruction file. It is loaded at the start of every session and provides the model with baseline knowledge about the project. RedDragon’s <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> is <strong>thin by design</strong>: it delegates to a set of imported files rather than encoding everything inline.</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gh"># RedDragon: Agent Instructions</span>

<span class="gh">#import .claude/core/project-context.md</span>
<span class="gh">#import .claude/core/workflow.md</span>
<span class="gh">#import .claude/core/implementation.md</span>
<span class="gh">#import .claude/core/tools-search.md</span>
<span class="gh">#import .claude/conditional/design-principles.md</span>
</code></pre></div></div>

<p>The four core files cover: what the project is and how it is structured (<code class="language-plaintext highlighter-rouge">project-context.md</code>), how to interact and commit (<code class="language-plaintext highlighter-rouge">workflow.md</code>), coding conventions and guard rules (<code class="language-plaintext highlighter-rouge">implementation.md</code>), and when to use which search tool (<code class="language-plaintext highlighter-rouge">tools-search.md</code>). The conditional <code class="language-plaintext highlighter-rouge">design-principles.md</code> is also always loaded here, in addition to being injected dynamically by the <code class="language-plaintext highlighter-rouge">UserPromptSubmit</code> hook when relevant prompts are classified.</p>

<p>This layer tells the model <em>how to work</em>: which test directories to use, when to brainstorm before coding, how to handle Talisman warnings, which formatting tool to run. It is effective for orienting the model and establishing defaults.</p>

<p>What it cannot do is <em>guarantee</em> those defaults are followed. Guidance in a prompt is a suggestion; it degrades across long contexts, gets overridden by competing instructions, and fails silently. <a href="https://arxiv.org/abs/2307.03172">Liu et al. (2023), <em>Lost in the Middle</em></a> showed that retrieval performance degrades most severely for information in the middle of the context window, which is exactly where <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> ends up as conversation history grows. The <code class="language-plaintext highlighter-rouge">UserPromptSubmit</code> hook re-injects invariant files on every prompt to keep guidance recent, but even that is probabilistic. <strong>“Most cases” is not a constraint.</strong> Everything below this section exists because LLM guidance alone is not sufficient.</p>

<hr />

<h2 id="language-feature-coverage-tracking">Language Feature Coverage Tracking</h2>

<p><em>Each of the 16 language frontends has a feature enum that enumerates every construct the language supports, implemented or not. A decorator on test methods links tests to enum members. An audit script computes the gap.</em></p>

<h3 id="feature-enums-self-documenting-members">Feature Enums: Self-Documenting Members</h3>

<p>Each of the 16 language frontends has a dedicated <code class="language-plaintext highlighter-rouge">features.py</code> file at <code class="language-plaintext highlighter-rouge">interpreter/frontends/{lang}/features.py</code> (COBOL lives at <code class="language-plaintext highlighter-rouge">interpreter/cobol/features.py</code>). Each file contains a single <code class="language-plaintext highlighter-rouge">XxxFeature(Enum)</code> class whose members use <strong>string values as documentation</strong> rather than <code class="language-plaintext highlighter-rouge">auto()</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">PythonFeature</span><span class="p">(</span><span class="n">Enum</span><span class="p">):</span>
    <span class="sh">"""</span><span class="s">Semantic features of the Python language.</span><span class="sh">"""</span>

    <span class="c1"># Declarations
</span>    <span class="n">VARIABLE_DECLARATION</span> <span class="o">=</span> <span class="sh">"</span><span class="s">simple name = value assignments at statement level</span><span class="sh">"</span>
    <span class="n">FUNCTION_DECLARATION</span> <span class="o">=</span> <span class="sh">"</span><span class="s">def f(...): function definitions</span><span class="sh">"</span>
    <span class="n">CLASS</span>                <span class="o">=</span> <span class="sh">"</span><span class="s">class C: class body definitions</span><span class="sh">"</span>

    <span class="c1"># Control flow
</span>    <span class="n">IF_ELSE</span>          <span class="o">=</span> <span class="sh">"</span><span class="s">if / elif / else conditional branching</span><span class="sh">"</span>
    <span class="n">WHILE_LOOP</span>       <span class="o">=</span> <span class="sh">"</span><span class="s">while cond: loop statements</span><span class="sh">"</span>
    <span class="n">FOR_LOOP</span>         <span class="o">=</span> <span class="sh">"</span><span class="s">for x in iterable: loop statements</span><span class="sh">"</span>
    <span class="n">MATCH_STATEMENT</span>  <span class="o">=</span> <span class="sh">"</span><span class="s">match subject: structural pattern matching (Python 3.10+)</span><span class="sh">"</span>

    <span class="c1"># Pattern Matching
</span>    <span class="n">CAPTURE_PATTERN</span>  <span class="o">=</span> <span class="sh">"</span><span class="s">case x: name capture in match cases</span><span class="sh">"</span>
    <span class="n">SEQUENCE_PATTERN</span> <span class="o">=</span> <span class="sh">"</span><span class="s">case [a, b]: sequence destructuring patterns</span><span class="sh">"</span>
    <span class="n">MAPPING_PATTERN</span>  <span class="o">=</span> <span class="sh">'</span><span class="s">case {</span><span class="sh">"</span><span class="s">key</span><span class="sh">"</span><span class="s">: v}: mapping destructuring patterns</span><span class="sh">'</span>
    <span class="bp">...</span>
</code></pre></div></div>

<p>The string value serves a dual purpose: it acts as human-readable documentation when the enum is displayed in audit reports, and it confirms at a glance what the feature covers. There are currently <strong>948 features</strong> defined across the 16 language enums.</p>

<h3 id="the-covers-decorator">The @covers Decorator</h3>

<p>Every test method that exercises a language feature is annotated with <code class="language-plaintext highlighter-rouge">@covers</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">tests.covers</span> <span class="kn">import</span> <span class="n">covers</span>
<span class="kn">from</span> <span class="n">interpreter.frontends.java.features</span> <span class="kn">import</span> <span class="n">JavaFeature</span>

<span class="k">class</span> <span class="nc">TestJavaInterface</span><span class="p">:</span>
    <span class="nd">@covers</span><span class="p">(</span><span class="n">JavaFeature</span><span class="p">.</span><span class="n">INTERFACE</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_interface_method_lowering</span><span class="p">(</span><span class="n">self</span><span class="p">):</span>
        <span class="n">result</span> <span class="o">=</span> <span class="nf">run</span><span class="p">(</span><span class="sh">"""</span><span class="s">
            interface Greeter { String greet(String name); }
        </span><span class="sh">"""</span><span class="p">,</span> <span class="sh">"</span><span class="s">java</span><span class="sh">"</span><span class="p">)</span>
        <span class="k">assert</span> <span class="n">result</span> <span class="o">==</span> <span class="bp">...</span>
</code></pre></div></div>

<p>The decorator is a <strong>no-op at runtime</strong>; it just attaches a <code class="language-plaintext highlighter-rouge">_covers</code> frozenset to the function object:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">covers</span><span class="p">(</span><span class="o">*</span><span class="n">features</span><span class="p">:</span> <span class="n">Enum</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Callable</span><span class="p">[[</span><span class="n">_F</span><span class="p">],</span> <span class="n">_F</span><span class="p">]:</span>
    <span class="k">def</span> <span class="nf">_decorator</span><span class="p">(</span><span class="n">func</span><span class="p">:</span> <span class="n">_F</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">_F</span><span class="p">:</span>
        <span class="n">func</span><span class="p">.</span><span class="n">_covers</span> <span class="o">=</span> <span class="nf">frozenset</span><span class="p">(</span><span class="n">features</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">func</span>
    <span class="k">return</span> <span class="n">_decorator</span>
</code></pre></div></div>

<p>This means <strong>zero test overhead</strong>. The metadata only matters to the audit script.</p>

<hr />

<h3 id="the-coverage-audit-script">The Coverage Audit Script</h3>

<p><a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/scripts/feature_coverage_audit.py"><code class="language-plaintext highlighter-rouge">scripts/feature_coverage_audit.py</code></a> performs a three-phase static analysis:</p>

<p><strong>Phase 1: Feature module discovery.</strong> It globs <code class="language-plaintext highlighter-rouge">interpreter/frontends/*/features.py</code> and <code class="language-plaintext highlighter-rouge">interpreter/cobol/features.py</code>, imports each module, and collects every enum member along with its string description.</p>

<p><strong>Phase 2: Test file scanning.</strong> It uses Python’s <code class="language-plaintext highlighter-rouge">ast</code> module (<strong>not regex</strong>) to walk all <code class="language-plaintext highlighter-rouge">test_*.py</code> files under <code class="language-plaintext highlighter-rouge">tests/unit/</code> and <code class="language-plaintext highlighter-rouge">tests/integration/</code>, extracting every <code class="language-plaintext highlighter-rouge">@covers(XxxFeature.MEMBER)</code> reference <strong>without executing any code</strong>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">_covers_refs_in_file</span><span class="p">(</span><span class="n">path</span><span class="p">:</span> <span class="n">Path</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">frozenset</span><span class="p">[</span><span class="n">FeatureRef</span><span class="p">]:</span>
    <span class="n">tree</span> <span class="o">=</span> <span class="n">ast</span><span class="p">.</span><span class="nf">parse</span><span class="p">(</span><span class="n">path</span><span class="p">.</span><span class="nf">read_text</span><span class="p">())</span>
    <span class="k">return</span> <span class="nf">frozenset</span><span class="p">(</span>
        <span class="nc">FeatureRef</span><span class="p">(</span><span class="n">enum_class_name</span><span class="o">=</span><span class="n">arg</span><span class="p">.</span><span class="n">value</span><span class="p">.</span><span class="nb">id</span><span class="p">,</span> <span class="n">member_name</span><span class="o">=</span><span class="n">arg</span><span class="p">.</span><span class="n">attr</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">node</span> <span class="ow">in</span> <span class="n">ast</span><span class="p">.</span><span class="nf">walk</span><span class="p">(</span><span class="n">tree</span><span class="p">)</span>
        <span class="k">if</span> <span class="nf">isinstance</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="p">(</span><span class="n">ast</span><span class="p">.</span><span class="n">FunctionDef</span><span class="p">,</span> <span class="n">ast</span><span class="p">.</span><span class="n">AsyncFunctionDef</span><span class="p">))</span>
        <span class="ow">and</span> <span class="n">node</span><span class="p">.</span><span class="n">name</span><span class="p">.</span><span class="nf">startswith</span><span class="p">(</span><span class="sh">"</span><span class="s">test_</span><span class="sh">"</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">dec</span> <span class="ow">in</span> <span class="n">node</span><span class="p">.</span><span class="n">decorator_list</span>
        <span class="k">if</span> <span class="nf">isinstance</span><span class="p">(</span><span class="n">dec</span><span class="p">,</span> <span class="n">ast</span><span class="p">.</span><span class="n">Call</span><span class="p">)</span>
        <span class="ow">and</span> <span class="nf">isinstance</span><span class="p">(</span><span class="n">dec</span><span class="p">.</span><span class="n">func</span><span class="p">,</span> <span class="n">ast</span><span class="p">.</span><span class="n">Name</span><span class="p">)</span>
        <span class="ow">and</span> <span class="n">dec</span><span class="p">.</span><span class="n">func</span><span class="p">.</span><span class="nb">id</span> <span class="o">==</span> <span class="sh">"</span><span class="s">covers</span><span class="sh">"</span>
        <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">dec</span><span class="p">.</span><span class="n">args</span>
        <span class="k">if</span> <span class="nf">isinstance</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="n">ast</span><span class="p">.</span><span class="n">Attribute</span><span class="p">)</span> <span class="ow">and</span> <span class="nf">isinstance</span><span class="p">(</span><span class="n">arg</span><span class="p">.</span><span class="n">value</span><span class="p">,</span> <span class="n">ast</span><span class="p">.</span><span class="n">Name</span><span class="p">)</span>
    <span class="p">)</span>
</code></pre></div></div>

<p><strong>Phase 3: Gap computation.</strong> For each language, the covered set (enum members that appear in at least one <code class="language-plaintext highlighter-rouge">@covers</code>) is subtracted from the full member set to produce the uncovered list.</p>

<p>The output is a JSON coverage report plus a summary table:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  c           :  33 /  48 covered  (15 uncovered)
  cobol        :  87 / 106 covered  (19 uncovered)
  cpp          :  38 /  84 covered  (46 uncovered)
  csharp       :  71 /  94 covered  (23 uncovered)
  go           :  40 /  44 covered  (4 uncovered)
  java         :  50 /  72 covered  (22 uncovered)
  javascript   :  33 /  38 covered  (5 uncovered)
  kotlin       :  51 /  59 covered  (8 uncovered)
  lua          :  19 /  25 covered  (6 uncovered)
  pascal       :  38 /  47 covered  (9 uncovered)
  php          :  46 /  55 covered  (9 uncovered)
  python       :  35 /  55 covered  (20 uncovered)
  ruby         :  67 /  72 covered  (5 uncovered)
  rust         :  46 /  60 covered  (14 uncovered)
  scala        :  43 /  53 covered  (10 uncovered)
  typescript   :  16 /  36 covered  (20 uncovered)
  ──────────────────────────────────────────────────
  TOTAL: 948 features across 16 languages, 205 uncovered
</code></pre></div></div>

<p>The script also supports <code class="language-plaintext highlighter-rouge">--gaps-doc docs/frontend-lowering-gaps.md</code> to regenerate a full Markdown report with a summary table and per-language uncovered feature lists.</p>

<hr />

<h3 id="what-uncovered-means">What Uncovered Means</h3>

<p>The feature enums are meant to be a <strong>comprehensive inventory of the language</strong>: every feature the language has, whether or not RedDragon supports it yet. An enum member with no <code class="language-plaintext highlighter-rouge">@covers</code> annotation is not a mistake in the enum; it is a <strong>documented gap</strong>: RedDragon’s frontend does not yet handle this construct.</p>

<p>This makes the coverage audit a <strong>living gap analysis</strong> as much as a test quality report. Running the audit tells you two things simultaneously: which features are implemented and tested, and which features are known to be missing. As of this writing there are 948 features across 16 languages, with 205 uncovered. The uncovered features are documented gaps: constructs the language has that RedDragon does not yet implement. The number moves as new features are added to the enums and implementation catches up.</p>

<hr />

<h2 id="the-pre-commit-pipeline">The Pre-commit Pipeline</h2>

<p><em>Seven gates run in sequence on every <code class="language-plaintext highlighter-rouge">git commit</code>. The hook logic lives in <a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/.claude/hooks/pre-commit"><code class="language-plaintext highlighter-rouge">.claude/hooks/pre-commit</code></a> (<strong>versioned in the repo</strong>); <code class="language-plaintext highlighter-rouge">.git/hooks/pre-commit</code> simply delegates to it. Blocking gates exit non-zero to abort the commit; non-blocking gates warn and continue.</em></p>

<pre><code class="language-mermaid">flowchart TD
    classDef gate    fill:#b91c1c,stroke:#7f1d1d,color:#fff
    classDef autofix fill:#0f766e,stroke:#134e4a,color:#fff
    classDef warn    fill:#b45309,stroke:#78350f,color:#fff
    classDef stop    fill:#1f2937,stroke:#111827,color:#f87171
    classDef start   fill:#1e3a8a,stroke:#1e3a8a,color:#fff
    classDef done    fill:#15803d,stroke:#14532d,color:#fff

    GC(["git commit"]):::start

    GC        --&gt; TAL
    TAL       --&gt;|pass| TG
    TAL       --&gt;|fail| S1

    TG        --&gt;|pass| BLK
    TG        --&gt;|violation| S2

    BLK       --&gt; FPL
    FPL       --&gt; IMP

    IMP       --&gt;|pass| PYT
    IMP       --&gt;|fail| S3

    PYT       --&gt;|pass| BD
    PYT       --&gt;|fail| S4

    BD        --&gt;|pass| OK
    BD        --&gt;|fail| S5

    TAL["Talisman\nsecret detection"]:::gate
    TG["Terminology guard\nchecks staged diff"]:::gate
    BLK["Black\nauto-format + re-stage"]:::autofix
    FPL(["python-fp-lint\nFP warnings only"]):::warn
    IMP["import-linter\n5 architectural contracts"]:::gate
    PYT["pytest\n13k+ tests  -x -q"]:::gate
    BD["Beads\nbackup"]:::gate

    S1["blocked"]:::stop
    S2["blocked"]:::stop
    S3["blocked"]:::stop
    S4["blocked"]:::stop
    S5["blocked"]:::stop

    OK(["commit created"]):::done
</code></pre>

<h3 id="talisman-secret-detection">Talisman: Secret Detection</h3>

<p><a href="https://github.com/thoughtworks/talisman">Talisman</a> scans all staged files for patterns that look like secrets: API keys, tokens, private key headers, high-entropy strings. It runs before everything else. If it flags something, the commit is blocked and you must either fix the content or add an explicit whitelist entry to <code class="language-plaintext highlighter-rouge">.talismanrc</code>. The <code class="language-plaintext highlighter-rouge">.talismanrc</code> policy is <strong>append-only</strong>: existing entries are never modified, new entries are added at the end.</p>

<hr />

<h3 id="terminology-guard">Terminology Guard</h3>

<p>The terminology guard is a two-part system that prevents sensitive terms from entering tracked artifacts. A custom script at <a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/scripts/check-terminology"><code class="language-plaintext highlighter-rouge">scripts/check-terminology</code></a> scans staged content for a blocklist of domain-specific vocabulary that should not appear in a public repository. This operates independently of Talisman: Talisman looks for secrets, the terminology guard looks for project-specific identifiers. Both block on failure. This matters because RedDragon is used in consulting contexts where client names, system codes, and vendor identifiers must never appear in a public repository.</p>

<p><strong>The blocklist</strong> lives at <code class="language-plaintext highlighter-rouge">~/.config/git/blocklist.txt</code>, one regex pattern per line, case-sensitive, applied via <code class="language-plaintext highlighter-rouge">grep -E</code>. It covers project names, government domain identifiers, vendor framework names, and reference system codes. An exclude-list at <code class="language-plaintext highlighter-rouge">~/.config/git/blocklist-exclude.txt</code> can whitelist specific file glob patterns.</p>

<p><strong>At commit time</strong>, <a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/scripts/check-terminology"><code class="language-plaintext highlighter-rouge">scripts/check-terminology</code></a> scans the staged diff using <code class="language-plaintext highlighter-rouge">git diff --cached --diff-filter=ACMR -U0</code>. It only looks at added lines (lines starting with <code class="language-plaintext highlighter-rouge">+</code>, excluding the <code class="language-plaintext highlighter-rouge">+++</code> header). If a forbidden term appears in a new or modified line, the commit is blocked with a formatted table showing the commit reference, file:line location, matched term, and 60-character context snippet with the term highlighted:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> Forbidden terms in staged changes
──────────────────────────────────────────────────────────────────────────────────────────
  COMMIT         LOCATION                       TERM       CONTEXT
──────────────────────────────────────────────────────────────────────────────────────────
  staged         src/parser.py:42               "REDACTED" ...client = REDACTEDClient()...
──────────────────────────────────────────────────────────────────────────────────────────
  1 hit(s)

  Blocklist: ~/.config/git/blocklist.txt
  Fix the content or update the blocklist to proceed.
</code></pre></div></div>

<p><strong>For history scanning</strong>, <a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/scripts/scan-history"><code class="language-plaintext highlighter-rouge">scripts/scan-history</code></a> performs a retroactive audit of the entire git history using the same blocklist. It runs two passes:</p>

<ol>
  <li><strong>File contents</strong>: uses <code class="language-plaintext highlighter-rouge">git log --all -G "$PATTERN"</code> to find commits that introduced the pattern, then walks each affected file at that commit SHA with <code class="language-plaintext highlighter-rouge">git show "$sha:$file"</code> to extract matching lines and their locations.</li>
  <li><strong>Commit messages</strong>: scans <code class="language-plaintext highlighter-rouge">git log --all --format='%h %s %b'</code> for forbidden terms in the subject and body of every commit message.</li>
</ol>

<p>Both scans produce the same formatted table output. The script is run manually (not as a hook) to audit historical exposure, typically when the blocklist is updated.</p>

<p>The shared formatting logic (<code class="language-plaintext highlighter-rouge">print_table_header</code>, <code class="language-plaintext highlighter-rouge">print_table_row</code>, <code class="language-plaintext highlighter-rouge">snippet_around</code>) lives in <a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/scripts/lib-terminology.sh"><code class="language-plaintext highlighter-rouge">scripts/lib-terminology.sh</code></a>, which both the pre-commit guard and the history scanner source. This ensures consistent output format between the commit gate and the retrospective scan.</p>

<p><strong>At the AI agent level</strong>, the <a href="https://github.com/avishek-sen-gupta/context-injector/blob/main/hooks/bd-terminology-guard.sh"><code class="language-plaintext highlighter-rouge">bd-terminology-guard.sh</code></a> PreToolUse hook intercepts Beads write commands before they reach the issue tracker. This catches the case where the AI composes an issue title or body containing a sensitive term; without this hook, the term could end up in the issue database even though it never touches a file.</p>

<hr />

<h3 id="black-auto-format">Black: Auto-format</h3>

<p><a href="https://github.com/psf/black">Black</a> runs on the entire repository and is non-blocking in the sense that it auto-corrects and re-stages the formatted files (<code class="language-plaintext highlighter-rouge">git add -u</code>) before the later gates run. If you commit with non-Black-formatted code, the commit still goes through, but the staged content becomes Black-formatted.</p>

<hr />

<h3 id="python-fp-lint-functional-programming-warnings">Python FP Lint: Functional Programming Warnings</h3>

<p><a href="https://github.com/avishek-sen-gupta/python-fp-lint"><code class="language-plaintext highlighter-rouge">python-fp-lint</code></a> is a custom linter that enforces functional programming conventions across <code class="language-plaintext highlighter-rouge">interpreter/</code>. It runs three backends in sequence, each responsible for a different class of violation.</p>

<p>The obvious alternative for structural rules would be Semgrep, but Semgrep’s rule registry and advanced features are gated behind account creation and a paywall, and I firmly believe that <a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/PHILOSOPHY.md">useful software should be free</a>. ast-grep is <strong>fully open, runs entirely offline</strong>, and its YAML rule format is simpler for custom rules. For the patterns needed here (single-node structural matches on mutation syntax), it is more than sufficient.</p>

<p><strong>Backend 1: <a href="https://github.com/ast-grep/ast-grep">ast-grep</a> (structural pattern rules).</strong> Twenty-eight custom YAML rules match syntactic mutation patterns that ast-grep can detect with a single-node structural match. The rules cover direct mutation (subscript assignment <code class="language-plaintext highlighter-rouge">d[k] = v</code>, augmented assignment <code class="language-plaintext highlighter-rouge">x += y</code>, attribute mutation <code class="language-plaintext highlighter-rouge">self.x = y</code>, loop mutation), collection mutation methods (<code class="language-plaintext highlighter-rouge">list.append/insert/remove/pop/extend</code>, <code class="language-plaintext highlighter-rouge">set.add/discard</code>, <code class="language-plaintext highlighter-rouge">dict.update/clear/setdefault</code>), and annotation hygiene (<code class="language-plaintext highlighter-rouge">list</code>/<code class="language-plaintext highlighter-rouge">dict</code> parameter types, unfrozen dataclasses, <code class="language-plaintext highlighter-rouge">None</code>-defaulted parameters). Using ast-grep here rather than regex is deliberate: these are multi-token structural patterns (<code class="language-plaintext highlighter-rouge">$OBJ[$KEY] = $VAL</code>, <code class="language-plaintext highlighter-rouge">@dataclass</code> without <code class="language-plaintext highlighter-rouge">frozen=True</code>) that span more than one token and would require fragile regexes or a full parser to match correctly otherwise.</p>

<p><strong>Backend 2: <a href="https://github.com/astral-sh/ruff">Ruff</a> (general code quality).</strong> The selected rule sets are <code class="language-plaintext highlighter-rouge">E</code>/<code class="language-plaintext highlighter-rouge">W</code> (pycodestyle), <code class="language-plaintext highlighter-rouge">F</code> (Pyflakes), <code class="language-plaintext highlighter-rouge">I</code> (isort), <code class="language-plaintext highlighter-rouge">B</code> (flake8-bugbear), <code class="language-plaintext highlighter-rouge">UP</code> (pyupgrade), <code class="language-plaintext highlighter-rouge">SIM</code> (flake8-simplify), <code class="language-plaintext highlighter-rouge">RUF</code> (Ruff-specific), <code class="language-plaintext highlighter-rouge">BLE</code> (blind-except), <code class="language-plaintext highlighter-rouge">T20</code> (print statements), <code class="language-plaintext highlighter-rouge">TID252</code> (tidy-imports), and <code class="language-plaintext highlighter-rouge">C901</code> (McCabe complexity). These cover standard quality checks that have nothing to do with FP style but are useful to have in a single pass.</p>

<p><strong>Backend 3: <a href="https://github.com/serge-sans-paille/beniget">beniget</a> (def-use chain reassignment detection).</strong> Variable reassignment (binding the same name twice in the same scope) cannot be detected by ast-grep, because the pattern spans multiple statements and requires knowing whether a name was already defined earlier in the same scope. <a href="https://github.com/serge-sans-paille/beniget">beniget</a> builds a def-use chain for each Python module by walking the AST and tracking every definition and use of every name. The <code class="language-plaintext highlighter-rouge">ReassignmentGate</code> queries <code class="language-plaintext highlighter-rouge">duc.locals</code> to find names with more than one definition node in the same scope and reports the second and subsequent assignments as violations.</p>

<p><strong>Current limitation: this only catches local variable reassignment. Object member reassignment (<code class="language-plaintext highlighter-rouge">self.x = y</code>) is not detected by this backend; those cases are caught by the <code class="language-plaintext highlighter-rouge">no-attribute-augmented-mutation</code> ast-grep rule, which covers augmented assignment only (<code class="language-plaintext highlighter-rouge">self.x += y</code>), not simple attribute writes.</strong></p>

<p>Currently <strong>non-blocking</strong> (<code class="language-plaintext highlighter-rouge">|| true</code>): the codebase has accumulated violations from before the linter existed, and the migration toward functional patterns is incremental. The intent is to make it blocking once the violation count reaches zero.</p>

<p>The linter lives in its own venv at <code class="language-plaintext highlighter-rouge">~/.claude/plugins/python-fp-lint/venv/</code> and is invoked directly:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>~/.claude/plugins/python-fp-lint/venv/bin/python <span class="se">\</span>
    <span class="nt">-m</span> python_fp_lint check <span class="s2">"</span><span class="nv">$REPO_ROOT</span><span class="s2">/interpreter/"</span> <span class="o">||</span> <span class="nb">true</span>
</code></pre></div></div>

<hr />

<h3 id="import-linter-architectural-contracts">import-linter: Architectural Contracts</h3>

<p><a href="https://import-linter.readthedocs.io/">import-linter</a> enforces five architectural contracts:</p>

<table>
  <thead>
    <tr>
      <th>Contract</th>
      <th>Rule</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>VM must not import frontend lowering code</td>
      <td>Prevents lowering logic bleeding into the VM</td>
    </tr>
    <tr>
      <td>IR module must not import other interpreter modules</td>
      <td>Keeps IR as a pure data type layer</td>
    </tr>
    <tr>
      <td>Project module must not import VM internals</td>
      <td>Enforces the project/VM boundary</td>
    </tr>
    <tr>
      <td>Language frontends must not import each other</td>
      <td>Prevents cross-frontend coupling</td>
    </tr>
    <tr>
      <td>COBOL module only imported by frontend factory</td>
      <td>Isolates the COBOL frontend</td>
    </tr>
  </tbody>
</table>

<p>These are <strong>blocking</strong>. A contract violation fails the commit.</p>

<hr />

<h3 id="full-test-suite">Full Test Suite</h3>

<p><code class="language-plaintext highlighter-rouge">poetry run python -m pytest tests/ -x -q</code> runs all 13,000+ tests with fail-fast (<code class="language-plaintext highlighter-rouge">-x</code>). This is the most expensive gate (~50 seconds) but <strong>it runs last, after all the cheaper gates have passed</strong>. It is <strong>blocking</strong>.</p>

<p>One deliberate omission: <strong>coverage measurement</strong> (<code class="language-plaintext highlighter-rouge">--cov</code>) is not part of the pre-commit hook. At 13,000+ tests, adding coverage instrumentation locally would push commit time past the point of acceptability. Coverage runs in CI instead, where the cost is paid asynchronously and doesn’t interrupt the development loop.</p>

<hr />

<h3 id="beads-backup">Beads Backup</h3>

<p><a href="https://beads.sh">Beads</a> is the issue tracker used for this project. The pre-commit hook calls <code class="language-plaintext highlighter-rouge">bd backup</code> to snapshot the issue database before the commit lands. This ensures the issue tracker state is always in sync with the code history. <strong>Blocking</strong>: if the backup fails, the commit is blocked.</p>

<hr />

<h2 id="claude-code-hooks-prepost-tool-use">Claude Code Hooks: Pre/Post Tool Use</h2>

<p><em>Shell scripts wired into Claude Code’s event system. <code class="language-plaintext highlighter-rouge">UserPromptSubmit</code> injects project invariants into every prompt. <code class="language-plaintext highlighter-rouge">PreToolUse</code> blocks edits that violate architectural or terminology constraints.</em></p>

<p>Claude Code’s hook system allows shell scripts to intercept tool calls before they execute (PreToolUse). RedDragon uses this to enforce workflow discipline <strong>at the point where the AI agent is making edits, not just at commit time</strong>.</p>

<p>All hooks are configured in <code class="language-plaintext highlighter-rouge">.claude/settings.json</code>:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"hooks"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"PreToolUse"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
      </span><span class="p">{</span><span class="w"> </span><span class="nl">"matcher"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Grep"</span><span class="p">,</span><span class="w">  </span><span class="nl">"hooks"</span><span class="p">:</span><span class="w"> </span><span class="p">[{</span><span class="w"> </span><span class="nl">"command"</span><span class="p">:</span><span class="w"> </span><span class="s2">"...ast-grep advisory..."</span><span class="w"> </span><span class="p">}]</span><span class="w"> </span><span class="p">},</span><span class="w">
      </span><span class="p">{</span><span class="w"> </span><span class="nl">"hooks"</span><span class="p">:</span><span class="w">            </span><span class="p">[{</span><span class="w"> </span><span class="nl">"command"</span><span class="p">:</span><span class="w"> </span><span class="s2">"bd-terminology-guard.sh"</span><span class="w"> </span><span class="p">}]</span><span class="w"> </span><span class="p">},</span><span class="w">
      </span><span class="p">{</span><span class="w"> </span><span class="nl">"matcher"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Edit"</span><span class="p">,</span><span class="w">  </span><span class="nl">"hooks"</span><span class="p">:</span><span class="w"> </span><span class="p">[{</span><span class="w"> </span><span class="nl">"command"</span><span class="p">:</span><span class="w"> </span><span class="s2">"lint-check.sh"</span><span class="w"> </span><span class="p">}]</span><span class="w"> </span><span class="p">},</span><span class="w">
      </span><span class="p">{</span><span class="w"> </span><span class="nl">"matcher"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Write"</span><span class="p">,</span><span class="w"> </span><span class="nl">"hooks"</span><span class="p">:</span><span class="w"> </span><span class="p">[{</span><span class="w"> </span><span class="nl">"command"</span><span class="p">:</span><span class="w"> </span><span class="s2">"lint-check.sh"</span><span class="w"> </span><span class="p">}]</span><span class="w"> </span><span class="p">}</span><span class="w">
    </span><span class="p">],</span><span class="w">
    </span><span class="nl">"UserPromptSubmit"</span><span class="p">:</span><span class="w"> </span><span class="p">[{</span><span class="w"> </span><span class="nl">"hooks"</span><span class="p">:</span><span class="w"> </span><span class="p">[{</span><span class="w"> </span><span class="nl">"command"</span><span class="p">:</span><span class="w"> </span><span class="s2">"user-prompt-submit.sh"</span><span class="w"> </span><span class="p">}]</span><span class="w"> </span><span class="p">}],</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<h3 id="userpromptsubmit-contextual-invariant-injection">UserPromptSubmit: Contextual Invariant Injection</h3>

<p>Every time a message is submitted, <a href="https://github.com/avishek-sen-gupta/context-injector/blob/main/hooks/user-prompt-submit.sh"><code class="language-plaintext highlighter-rouge">user-prompt-submit.sh</code></a> classifies the prompt using keyword matching and injects the relevant invariant files into the conversation context. The classification is purely lexical (no LLM involved):</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Keyword families → context categories</span>
<span class="k">if </span><span class="nb">grep</span> <span class="nt">-qiEw</span> <span class="s1">'implement|add|build|create|fix|feature|...'</span><span class="p">;</span> <span class="k">then
  </span><span class="nv">DESIGN</span><span class="o">=</span>1<span class="p">;</span> <span class="nv">TESTING</span><span class="o">=</span>1<span class="p">;</span> <span class="nv">REFACTORING</span><span class="o">=</span>1<span class="p">;</span> <span class="nv">SKILLS</span><span class="o">=</span>1
<span class="k">fi
if </span><span class="nb">grep</span> <span class="nt">-qiEw</span> <span class="s1">'test|tdd|assert|coverage|...'</span><span class="p">;</span> <span class="k">then
  </span><span class="nv">TESTING</span><span class="o">=</span>1
<span class="k">fi
if </span><span class="nb">grep</span> <span class="nt">-qiEw</span> <span class="s1">'refactor|rename|extract|move|...'</span><span class="p">;</span> <span class="k">then
  </span><span class="nv">DESIGN</span><span class="o">=</span>1<span class="p">;</span> <span class="nv">REFACTORING</span><span class="o">=</span>1<span class="p">;</span> <span class="nv">SKILLS</span><span class="o">=</span>1
<span class="k">fi
if </span><span class="nb">grep</span> <span class="nt">-qiEw</span> <span class="s1">'review|pr|diff|...'</span><span class="p">;</span> <span class="k">then
  </span><span class="nv">REVIEW</span><span class="o">=</span>1
<span class="k">fi</span>
</code></pre></div></div>

<p>The injected invariant files live in <code class="language-plaintext highlighter-rouge">.claude/core/</code> (always injected) and <code class="language-plaintext highlighter-rouge">.claude/conditional/</code> (injected when the corresponding category fires). This means a prompt like “implement COBOL array support” automatically injects design principles, testing patterns, and tools/skills context, while a prompt like “what does this function do?” only injects core context.</p>

<p><strong>What gets injected.</strong> The invariant files are split into two directories:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">.claude/core/</code>: four files injected on every prompt regardless of classification: <code class="language-plaintext highlighter-rouge">project-context.md</code> (language, toolchain, module map), <code class="language-plaintext highlighter-rouge">workflow.md</code> (interaction style, commit protocol), <code class="language-plaintext highlighter-rouge">implementation.md</code> (coding conventions, guard rules), <code class="language-plaintext highlighter-rouge">tools-search.md</code> (when to use ast-grep vs grep vs the graph MCP).</li>
  <li><code class="language-plaintext highlighter-rouge">.claude/conditional/</code>: five files injected only when the corresponding category fires: <code class="language-plaintext highlighter-rouge">design-principles.md</code> (DESIGN), <code class="language-plaintext highlighter-rouge">testing-patterns.md</code> (TESTING), <code class="language-plaintext highlighter-rouge">refactoring.md</code> (REFACTORING), <code class="language-plaintext highlighter-rouge">tools-skills.md</code> (SKILLS), <code class="language-plaintext highlighter-rouge">code-review.md</code> (REVIEW).</li>
</ul>

<p>A prompt classified as DESIGN+TESTING+REFACTORING+SKILLS (e.g. “implement COBOL array support”) injects all nine files. A prompt classified as none of the above (e.g. “what does this function do?”) injects only the four core files.</p>

<p><strong>The <code class="language-plaintext highlighter-rouge">/ctx</code> slash command</strong> controls the injection gate. It is implemented as a Claude Code user command at <code class="language-plaintext highlighter-rouge">~/.claude/commands/ctx.md</code>, which delegates to the <code class="language-plaintext highlighter-rouge">ctx</code> binary at <code class="language-plaintext highlighter-rouge">~/.claude/plugins/context-injector/bin/ctx</code>:</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/ctx          <span class="c"># toggle on ↔ off</span>
/ctx on       <span class="c"># enable injection</span>
/ctx off      <span class="c"># disable injection</span>
/ctx status   <span class="c"># print {"active": true|false}</span>
</code></pre></div></div>

<pre><code class="language-mermaid">%%{init: {'theme': 'base', 'themeVariables': {'edgeLabelBackground': '#ffffff'}, 'flowchart': {'curve': 'basis'}}}%%
flowchart TD
    CTX["🔒 /tmp/ctx-locks/&amp;ltmd5&amp;gt\n&lt;i&gt;ctx toggle&lt;/i&gt;"]:::lock

    subgraph hooks["Claude Code Hooks"]
        UPS["📨 UserPromptSubmit\n&lt;i&gt;user-prompt-submit.sh&lt;/i&gt;"]:::hook
        PTU["🔧 PreToolUse\n&lt;i&gt;pre-tool-use.sh&lt;/i&gt;"]:::hook
        SS["🚀 SessionStart\n&lt;i&gt;session-start.sh&lt;/i&gt;"]:::hook
    end

    subgraph content["Project Context"]
        CORE["📁 .claude/core/*.md\n&lt;i&gt;always injected&lt;/i&gt;"]:::core
        COND["📂 .claude/conditional/*.md\n&lt;i&gt;keyword-matched&lt;/i&gt;"]:::cond
    end

    CTX --&gt;|"ctx on?"| UPS
    CTX --&gt;|"ctx on?"| PTU
    CTX --&gt;|"ctx on?"| SS

    UPS --&gt;|"inject"| CORE
    UPS --&gt;|"classify keywords → inject"| COND
    PTU --&gt;|"code-review agent? → inject"| COND
    SS --&gt;|"inject once at start"| CORE

    classDef hook fill:#dbeafe,stroke:#3b82f6,color:#1e3a5f
    classDef lock fill:#fef9c3,stroke:#ca8a04,color:#713f12
    classDef core fill:#dcfce7,stroke:#16a34a,color:#14532d
    classDef cond fill:#fce7f3,stroke:#db2777,color:#831843
</code></pre>

<p>The state is a per-project lockfile at <code class="language-plaintext highlighter-rouge">/tmp/ctx-locks/&lt;project-hash&gt;</code>. The hash is derived from <code class="language-plaintext highlighter-rouge">$PWD</code>, so each project has an independent toggle; switching it off in one repo doesn’t affect another. The hook <a href="https://github.com/avishek-sen-gupta/context-injector/blob/main/hooks/user-prompt-submit.sh"><code class="language-plaintext highlighter-rouge">user-prompt-submit.sh</code></a> checks for the lockfile at the start of every run; if absent, it exits immediately without injecting anything.</p>

<p>The injection mechanism works through Claude Code’s <code class="language-plaintext highlighter-rouge">UserPromptSubmit</code> hook return value: the hook writes its output to stdout, and Claude Code prepends that output to the user’s message before it reaches the model. From the model’s perspective, the invariants appear at the top of the incoming message, not as a separate system prompt. This means the injected content is visible in the conversation and can be referenced explicitly.</p>

<p><code class="language-plaintext highlighter-rouge">/ctx off</code> is useful when you want a raw conversation without the invariant overhead: exploring an unfamiliar part of the codebase, doing a quick calculation, or asking a question where the injected design principles would be noise. <code class="language-plaintext highlighter-rouge">/ctx on</code> (or toggling back) restores normal operation; no session restart required.</p>

<hr />

<h3 id="pretooluse-the-gate-layer">PreToolUse: The Gate Layer</h3>

<p>Three hooks run before tool calls:</p>

<p><strong>1. ast-grep advisory (on <code class="language-plaintext highlighter-rouge">Grep</code>):</strong> When the agent is about to run a Grep, an advisory fires reminding it to prefer <code class="language-plaintext highlighter-rouge">ast-grep</code> for structural patterns (constructor shapes, multi-line call sites) and reserve <code class="language-plaintext highlighter-rouge">Grep</code> for simple keyword/import/constant searches.</p>

<p><strong>2. Terminology guard (all <code class="language-plaintext highlighter-rouge">Bash</code> tool calls with <code class="language-plaintext highlighter-rouge">bd</code> write commands):</strong> The <a href="https://github.com/avishek-sen-gupta/context-injector/blob/main/hooks/bd-terminology-guard.sh"><code class="language-plaintext highlighter-rouge">bd-terminology-guard.sh</code></a> hook intercepts any <code class="language-plaintext highlighter-rouge">bd create</code>, <code class="language-plaintext highlighter-rouge">bd update</code>, <code class="language-plaintext highlighter-rouge">bd note</code>, or similar Beads write commands and checks them against the blocklist. If a sensitive term appears in the issue text, the command is blocked (exit 2) before it reaches Beads.</p>

<p><strong>3. Python FP lint gate (on <code class="language-plaintext highlighter-rouge">Edit</code> and <code class="language-plaintext highlighter-rouge">Write</code>):</strong> The <a href="https://github.com/avishek-sen-gupta/context-injector/blob/main/hooks/lint-check.sh"><code class="language-plaintext highlighter-rouge">lint-check.sh</code></a> hook receives the full tool event JSON on stdin (including the file path and the new/modified content), runs <code class="language-plaintext highlighter-rouge">python_fp_lint hook-check</code>, and blocks the edit if violations appear in the modified line range. Critically, this operates on the <strong>diff range</strong>: it only flags violations introduced or modified by the current edit, <strong>not pre-existing violations in unchanged lines</strong>. This prevents the linter from blocking edits in files that already had violations before you touched them.</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Exit 0 = allow, Exit 2 = block</span>
<span class="nb">cat</span> | <span class="nv">$LINT_CMD</span> hook-check
</code></pre></div></div>

<p>The gate is toggled with <code class="language-plaintext highlighter-rouge">/lint on</code> and <code class="language-plaintext highlighter-rouge">/lint off</code>, which create/remove a lockfile at <code class="language-plaintext highlighter-rouge">/tmp/ctx-lint/&lt;project-hash&gt;</code>.</p>

<hr />

<h2 id="skills-and-workflow-automation">Skills and Workflow Automation</h2>

<p><em>Hooks enforce runtime constraints at the tool level. Skills encode workflow knowledge at the task level: how to approach a problem, what questions to ask, what patterns to follow. They are loaded on demand via Claude Code’s Skill tool.</em></p>

<h3 id="superpowers-core-development-lifecycle-skills">Superpowers: Core Development Lifecycle Skills</h3>

<p>The <a href="https://github.com/anthropics/claude-plugins-official">Superpowers</a> plugin provides a suite of lifecycle skills that cover the full development loop:</p>

<table>
  <thead>
    <tr>
      <th>Skill</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">brainstorming</code></td>
      <td>Structured option exploration before touching code. Presents trade-offs, seeks user input before committing to an approach.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">writing-plans</code></td>
      <td>Produces a detailed, phased implementation plan from a spec before any coding begins.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">executing-plans</code></td>
      <td>Executes a written plan using subagent orchestration, one step at a time.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">test-driven-development</code></td>
      <td>Red/green/refactor loop with explicit constraints on what to write at each phase.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">systematic-debugging</code></td>
      <td>Root cause analysis before patching. Forces diagnosis before solution.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">verification-before-completion</code></td>
      <td>Checklist run before claiming work is complete: tests pass, no regressions, no TODOs left behind.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">requesting-code-review</code></td>
      <td>Invokes specialized review agents before merging.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">receiving-code-review</code></td>
      <td>Structures how to process and respond to review feedback.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">dispatching-parallel-agents</code></td>
      <td>When 2+ independent tasks exist, launches them as concurrent subagents.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">subagent-driven-development</code></td>
      <td>Orchestrates independent implementation tasks across a plan in parallel.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">finishing-a-development-branch</code></td>
      <td>Checklist for branch completion: cleanup, docs, tests, commit hygiene.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">writing-skills</code></td>
      <td>For creating or editing skill files themselves.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">using-git-worktrees</code></td>
      <td>Isolates feature work in a temporary worktree to avoid polluting the working directory.</td>
    </tr>
  </tbody>
</table>

<p>The key constraint from <code class="language-plaintext highlighter-rouge">using-superpowers</code> is that skills are loaded <strong>before any response</strong>, even before a clarifying question. The rule: if there is <strong>even a 1% chance a skill applies</strong>, invoke it first. Crucially, the developer does not need to explicitly trigger a skill; the agent is expected to recognise when one applies and invoke it without being asked.</p>

<hr />

<h3 id="project-level-skills">Project-Level Skills</h3>

<p>RedDragon has six project-specific skills in <code class="language-plaintext highlighter-rouge">.claude/skills/</code>:</p>

<p><strong><code class="language-plaintext highlighter-rouge">tdd</code></strong>: The project’s TDD skill extends the Superpowers TDD skill with RedDragon-specific conventions: where integration tests go (<code class="language-plaintext highlighter-rouge">tests/integration/</code>), what a correct <code class="language-plaintext highlighter-rouge">@covers</code> annotation looks like, how to use <code class="language-plaintext highlighter-rouge">run()</code> to exercise the VM rather than unit-testing the lowering step in isolation.</p>

<p><strong><code class="language-plaintext highlighter-rouge">audit-asserts</code></strong>: Periodic audit of test name vs. assertion mismatches. Batches test files across parallel agents (batches of ~20), collects P0/P1/P2 violations, deduplicates against existing Beads issues, and files new ones. The most recent audit (#16 as of this writing) covered 331 files and found 0 P0 violations.</p>

<p><strong><code class="language-plaintext highlighter-rouge">grill-me</code></strong>: Interview mode. When invoked, the AI asks probing questions about every aspect of a plan or design, walking each branch of the decision tree and providing a recommended answer for each question. Used before committing to significant architectural changes. Useful for surfacing assumptions that haven’t been examined.</p>

<p><strong><code class="language-plaintext highlighter-rouge">migration-planner</code></strong>: Activates during brainstorming when the task is a large-scale type migration (e.g., replacing <code class="language-plaintext highlighter-rouge">str</code> with a domain type across function signatures, dict keys, and data classes). Provides a scope-first discipline: count before you plan, don’t estimate. Provides three migration strategies (big-bang, parallel-run, incremental) with trade-off analysis.</p>

<p><strong><code class="language-plaintext highlighter-rouge">documentation</code></strong>: Updates all living docs (README, ADRs, IR lowering gaps, frontend design docs, HTML presentations) to reflect current codebase state. Does not touch immutable spec files under <code class="language-plaintext highlighter-rouge">docs/superpowers/specs/</code>.</p>

<p><strong><code class="language-plaintext highlighter-rouge">improve-codebase-architecture</code></strong>: Explores the codebase for deep module opportunities (à la Ousterhout), surfaces integration risk at module seams, and proposes refactors as Beads RFC issues.</p>

<hr />

<h3 id="plugins-context-injector-and-python-fp-lint">Plugins: Context Injector and Python FP Lint</h3>

<p><strong><a href="https://github.com/avishek-sen-gupta/context-injector">Context Injector</a></strong> is the plugin that powers the <code class="language-plaintext highlighter-rouge">UserPromptSubmit</code> hook described above. Toggle: <code class="language-plaintext highlighter-rouge">/ctx on</code> / <code class="language-plaintext highlighter-rouge">/ctx off</code>.</p>

<p><strong><a href="https://github.com/avishek-sen-gupta/python-fp-lint">Python FP Lint</a></strong> enforces functional programming conventions at edit time. The PreToolUse gate blocks edits that introduce FP violations into the modified lines. Toggle: <code class="language-plaintext highlighter-rouge">/lint on</code> / <code class="language-plaintext highlighter-rouge">/lint off</code>. The same linter runs in the pre-commit hook as a non-blocking warning pass over the full <code class="language-plaintext highlighter-rouge">interpreter/</code> directory.</p>

<p><strong>Additional plugins and skill sources used in this project:</strong></p>

<ul>
  <li><a href="https://github.com/tirth8205/code-review-graph">code-review-graph</a>: builds a Tree-sitter AST graph of the codebase for token-efficient, impact-aware code review via MCP</li>
  <li><a href="https://github.com/thedotmack/claude-mem">claude-mem</a>: persistent cross-session memory with timeline, search, and smart-outline MCP tools</li>
  <li><a href="https://github.com/ast-grep/agent-skill">ast-grep agent-skill</a>: structural code search skill; the CLAUDE.md mandate to prefer <code class="language-plaintext highlighter-rouge">ast-grep</code> over plain <code class="language-plaintext highlighter-rouge">grep</code> is enforced by a PreToolUse advisory wired to every <code class="language-plaintext highlighter-rouge">Grep</code> call</li>
</ul>

<hr />

<h2 id="the-full-picture">The Full Picture</h2>

<pre><code class="language-mermaid">flowchart LR
    classDef skill    fill:#6d28d9,stroke:#4c1d95,color:#fff
    classDef hook     fill:#1d4ed8,stroke:#1e3a8a,color:#fff
    classDef blocker  fill:#b91c1c,stroke:#7f1d1d,color:#fff
    classDef autofix  fill:#0f766e,stroke:#134e4a,color:#fff
    classDef advisory fill:#b45309,stroke:#78350f,color:#fff
    classDef coverage fill:#374151,stroke:#111827,color:#d1d5db
    classDef hdr      fill:#0f172a,stroke:#0f172a,color:#94a3b8

    subgraph L1["LAYER 1  ·  DESIGN TIME  ·  skills, invoked on demand"]
        direction TB
        D0["SKILL · on-demand"]:::hdr
        D1["brainstorming · structured option exploration"]:::skill
        D2["writing-plans · phased implementation plan"]:::skill
        D3["tdd · red / green / refactor loop"]:::skill
        D4["grill-me · stress-test designs before coding"]:::skill
        D5["audit-asserts · test name vs. assertion audit"]:::skill
        D6["migration-planner · scope before estimate"]:::skill
        D0 --- D1 --- D2 --- D3 --- D4 --- D5 --- D6
    end

    subgraph L2["LAYER 2  ·  EDIT TIME  ·  Claude Code hooks"]
        direction TB
        H0["HOOK · every tool call"]:::hdr
        H2["UserPromptSubmit · keyword classify + invariant inject  ·  toggleable"]:::hook
        H3["PreToolUse / Grep · prefer ast-grep advisory  ·  warn"]:::advisory
        H4["PreToolUse / Bash bd · terminology guard  ·  BLOCKING"]:::blocker
        H5["PreToolUse / Edit+Write · FP lint gate, diff-range  ·  BLOCKING"]:::blocker
        H0 --- H2 --- H3 --- H4 --- H5
    end

    subgraph L3["LAYER 3  ·  COMMIT TIME  ·  pre-commit hook, sequential"]
        direction TB
        C0["GATE · git commit"]:::hdr
        C1["Talisman · secret detection  ·  BLOCKING"]:::blocker
        C2["Terminology guard · staged diff  ·  BLOCKING"]:::blocker
        C3["Black · auto-format + re-stage  ·  AUTO-FIX"]:::autofix
        C4["python-fp-lint · FP warnings  ·  non-blocking"]:::advisory
        C5["import-linter · 5 architectural contracts  ·  BLOCKING"]:::blocker
        C6["pytest · 13k+ tests, fail-fast  ·  BLOCKING"]:::blocker
        C7["Beads backup  ·  BLOCKING"]:::blocker
        C0 --- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7
    end

    FC["@covers decorator + audit script\n948 features  ·  16 languages  ·  205 uncovered\ncontinuous / run anytime"]:::coverage

    L1 ==&gt; L2 ==&gt; L3
    FC -.-&gt; L3
</code></pre>

<p>The harness operates at three layers, with feature coverage sitting orthogonal as a continuous property rather than a gate:</p>

<p><strong>Layer 1, design time (skills):</strong> <code class="language-plaintext highlighter-rouge">brainstorming</code> structures option exploration before coding begins; <code class="language-plaintext highlighter-rouge">tdd</code> enforces red/green/refactor discipline; <code class="language-plaintext highlighter-rouge">grill-me</code> examines designs before committing to them; <code class="language-plaintext highlighter-rouge">audit-asserts</code> audits test name vs. assertion consistency; <code class="language-plaintext highlighter-rouge">migration-planner</code> scopes large changes before estimating.</p>

<p><strong>Layer 2, edit time (Claude Code hooks):</strong> Every prompt gets relevant invariants injected (<code class="language-plaintext highlighter-rouge">UserPromptSubmit</code>). Every edit to <code class="language-plaintext highlighter-rouge">interpreter/</code> is checked for FP violations in the modified line range (<code class="language-plaintext highlighter-rouge">PreToolUse</code>). Every Beads write is screened for sensitive terms (<code class="language-plaintext highlighter-rouge">PreToolUse</code>).</p>

<p><strong>Layer 3, commit time (pre-commit pipeline):</strong> Secret detection, terminology, formatting, FP warnings, architectural contracts, the full test suite, and issue tracker backup run in sequence. Most are blocking; a violation stops the commit.</p>

<p>The three layers are designed so that violations are caught close to where they are introduced: design problems during brainstorming, bad edits before they are written to disk, and bad commits before they enter the history.</p>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>The goal behind this harness is <strong>reliability, discoverability, and rigour</strong> in an AI-assisted development context. Each of those properties requires a different kind of investment.</p>

<p><strong>Reliability / Repeatability / Reproducibility</strong> means that a constraint either holds or it does not; it does not depend on whether the AI had the right context, or whether the right instruction was in scope, or whether the model happened to follow it this session. Every gate in the pre-commit pipeline, every PreToolUse hook, every import-linter contract, and every <code class="language-plaintext highlighter-rouge">@covers</code> annotation is a <em>deterministic check</em>. It runs the same way every time and produces the same result for the same input. Asking the AI to “remember not to import across module boundaries” or “make sure you annotate every new test with <code class="language-plaintext highlighter-rouge">@covers</code>” is <em>a prompt instruction, not a constraint</em>. <strong>Prompt instructions degrade across context boundaries, get overridden by other instructions, and fail silently.</strong> A blocking git hook does not forget.</p>

<p><strong>Discoverability</strong> requires that the codebase itself be <em>automation-friendly</em>:</p>

<ul>
  <li>The <code class="language-plaintext highlighter-rouge">@covers</code> decorator exists so that coverage auditing can be done statically, without executing tests or parsing output.</li>
  <li>The feature enum string values exist so that audit reports are self-describing without a separate documentation file.</li>
  <li>The <code class="language-plaintext highlighter-rouge">VAR_DEFINITION_OPCODES</code> frozenset in <code class="language-plaintext highlighter-rouge">ir.py</code> exists so that dataflow analysis can identify definition sites without pattern-matching over opcode names scattered across the codebase.</li>
</ul>

<p>These are small structural choices that make the codebase <em>queryable by scripts and agents without interpretation</em>. <strong>A codebase that lacks these hooks forces automation to guess; a codebase that provides them allows automation to be exact.</strong></p>

<p><strong>Rigour</strong> comes from a specific division of labour: <em>build constraints using AI, but do not rely on the AI to impose them</em>. The terminology blocklist was written with AI assistance; the blocklist itself is a flat text file checked by a shell script. The import-linter contracts were designed with AI help; the contracts run as a deterministic linter step. The skills encode workflow knowledge refined through conversation; the skills themselves are Markdown files loaded and followed mechanically. In each case, the AI did the authoring work, but <em>the resulting artifact is a static, executable constraint that runs without the AI</em>. <strong>The non-deterministic layer is reserved for work that genuinely requires judgment:</strong> exploring design trade-offs, writing implementation code, interpreting test failures, deciding what to file as an issue.</p>

<p><strong>Nested feedback loops.</strong> The harness is structured as a set of loops, each operating at a different granularity and cost:</p>

<ul>
  <li><strong>Design time (skills):</strong> fire before a line of code is written; a skill invocation costs nothing.</li>
  <li><strong>Edit time (Claude Code hooks):</strong> fire before a change is saved; a PreToolUse block costs one rejected edit.</li>
  <li><strong>Commit time (pre-commit pipeline):</strong> fires before a change enters history; a failed commit costs a full test run.</li>
  <li><strong>Continuous (coverage audit):</strong> runs orthogonal to all three; a gap costs a backlog issue.</li>
</ul>

<p>Each loop catches a different class of problem. The loops are deliberately ordered so that the cheapest checks run first. <strong>Problems caught in an inner loop are cheaper to fix than problems that escape to an outer one.</strong> The design goal is not to make any single gate comprehensive, but to ensure that each class of violation has a loop it cannot escape.</p>

<p>This is not a finished design. Some gates are still non-blocking warnings that will become blockers as violation counts drop. Some constraints that currently exist only as prompt instructions will eventually become code. The direction is consistent: <em>push enforcement into deterministic mechanisms wherever possible</em>, and make what remains explicit and auditable.</p>]]></content><author><name>avishek</name></author><category term="Software Engineering" /><category term="AI-Assisted Development" /><category term="Testing" /><category term="Developer Tooling" /><category term="Workflow" /><category term="Python" /><category term="RedDragon" /><summary type="html"><![CDATA[RedDragon is a multi-language interpreter/compiler that lowers 16 languages (Python, Java, Go, TypeScript, Rust, C, C++, C#, JavaScript, Kotlin, Lua, PHP, Ruby, Swift, Scala, COBOL) down to a shared IR. With 13,000+ tests across 16 frontends, keeping quality high and coverage visible requires a harness that operates at several layers simultaneously. This post documents that harness in full: how language feature coverage is tracked through feature enums, how the pre-commit pipeline is structured, and how Claude Code’s hook system is wired to enforce workflow discipline at edit time.]]></summary></entry><entry><title type="html">Engineering Log: Testing agentic coding workflows via Large Refactorings</title><link href="http://localhost:4000/2026/03/24/testing-agentic-development-systems-gsd-v2.html" rel="alternate" type="text/html" title="Engineering Log: Testing agentic coding workflows via Large Refactorings" /><published>2026-03-24T00:00:00+05:30</published><updated>2026-03-24T00:00:00+05:30</updated><id>http://localhost:4000/2026/03/24/testing-agentic-development-systems-gsd-v2</id><content type="html" xml:base="http://localhost:4000/2026/03/24/testing-agentic-development-systems-gsd-v2.html"><![CDATA[<p><em>Two agentic development frameworks applied to the same multi-layer type migration across a 13,000-test compiler pipeline. The first provided process discipline but stalled partway through. The second completed the work because it planned more thoroughly and stopped to ask.</em></p>

<p><em>The code is at <a href="https://github.com/avishek-sen-gupta/red-dragon">avishek-sen-gupta/red-dragon</a>. RedDragon’s design is described in <a href="/2026/03/01/designing-reddragon-multi-language-code-analysis.html">Designing RedDragon</a>. The completed elimination plan is at <a href="https://github.com/avishek-sen-gupta/red-dragon/blob/main/docs/design/eliminate-irinstruction-plan.md">the design document</a>. Previous posts in this series: <a href="/2026/03/12/experiences-building-with-coding-assistant.html">Building Non-Trivial Systems with an AI Coding Assistant</a>, <a href="/2026/03/13/anatomy-of-a-refactoring-using-ai.html">Anatomy of a Refactoring Using AI</a>.</em></p>

<hr />

<h2 id="table-of-contents">Table of Contents</h2>

<ul>
  <li><a href="#context">Context</a></li>
  <li><a href="#what-gsd-2-is">What GSD 2 Is</a></li>
  <li><a href="#what-i-adopted">What I Adopted</a>
    <ul>
      <li><a href="#1-enforced-phases-per-unit-of-work">1. Enforced Phases Per Unit of Work</a></li>
      <li><a href="#2-complexity-classification">2. Complexity Classification</a></li>
      <li><a href="#3-verification-gate">3. Verification Gate</a></li>
      <li><a href="#4-fresh-context-for-heavy-tasks">4. Fresh Context for Heavy Tasks</a></li>
      <li><a href="#5-state-on-disk">5. State on Disk</a></li>
    </ul>
  </li>
  <li><a href="#teething-issues">Teething Issues</a>
    <ul>
      <li><a href="#the-patch-on-patch-problem">The Patch-on-Patch Problem</a></li>
      <li><a href="#brainstorm-wasnt-enforced">Brainstorm Wasn’t Enforced</a></li>
      <li><a href="#retroactive-issue-filing">Retroactive Issue Filing</a></li>
      <li><a href="#weak-integration-test-assertions">Weak Integration Test Assertions</a></li>
      <li><a href="#the-theoretical-bug">The Theoretical Bug</a></li>
    </ul>
  </li>
  <li><a href="#the-reorganised-claudemd">The Reorganised CLAUDE.md</a></li>
  <li><a href="#the-test-replacing-a-stringly-typed-ir-with-domain-types">The Test: Replacing a Stringly-Typed IR with Domain Types</a>
    <ul>
      <li><a href="#the-problem-strings-all-the-way-down">The Problem: Strings All the Way Down</a></li>
    </ul>
  </li>
  <li><a href="#chapter-1-codelabel-the-first-domino">Chapter 1: CodeLabel, The First Domino</a>
    <ul>
      <li><a href="#the-attempted-cascade">The Attempted Cascade</a></li>
      <li><a href="#the-revert-and-the-lesson">The Revert and the Lesson</a></li>
      <li><a href="#what-actually-shipped">What Actually Shipped</a></li>
      <li><a href="#the-coercion-validator-mistake">The Coercion Validator Mistake</a></li>
      <li><a href="#the-refactoring-principles-that-crystallised">The Refactoring Principles That Crystallised</a></li>
    </ul>
  </li>
  <li><a href="#chapter-2-register-the-pydantic-problem">Chapter 2: Register, The Pydantic Problem</a>
    <ul>
      <li><a href="#the-boolean-truthiness-problem">The Boolean Truthiness Problem</a></li>
      <li><a href="#the-branch_if-comma-convention">The BRANCH_IF Comma Convention</a></li>
    </ul>
  </li>
  <li><a href="#chapter-3-typed-instructions">Chapter 3: Typed Instructions</a>
    <ul>
      <li><a href="#the-decision-one-class-per-opcode">The Decision: One Class Per Opcode</a></li>
      <li><a href="#the-original-four-phase-plan">The Original Four-Phase Plan</a></li>
      <li><a href="#the-plan-that-replaced-the-plan">The Plan That Replaced the Plan</a></li>
      <li><a href="#the-missing-length-field">The Missing Length Field</a></li>
      <li><a href="#layer-1-execution">Layer 1 Execution</a></li>
    </ul>
  </li>
  <li><a href="#chapter-4-completing-the-migration-with-superpowers">Chapter 4: Completing the Migration with Superpowers</a>
    <ul>
      <li><a href="#why-gsd-v2-stalled-after-layer-1">Why GSD v2 Stalled After Layer 1</a></li>
      <li><a href="#what-superpowers-did-differently">What Superpowers Did Differently</a></li>
      <li><a href="#the-audit-that-revised-the-plan">The Audit That Revised the Plan</a></li>
      <li><a href="#layers-2-through-5-execution">Layers 2 Through 5: Execution</a></li>
      <li><a href="#layer-5-was-not-cleanup">Layer 5 Was Not Cleanup</a></li>
    </ul>
  </li>
  <li><a href="#learnings">Learnings</a>
    <ul>
      <li><a href="#on-type-hints-in-python">On Type Hints in Python</a></li>
      <li><a href="#on-scope">On Scope</a></li>
      <li><a href="#on-type-migrations">On Type Migrations</a></li>
      <li><a href="#on-plans">On Plans</a></li>
      <li><a href="#on-tooling">On Tooling</a></li>
    </ul>
  </li>
  <li><a href="#takeaways">Takeaways</a></li>
</ul>

<hr />

<h2 id="context">Context</h2>

<p>I’ve been building <a href="https://github.com/avishek-sen-gupta/red-dragon">RedDragon</a>, a multi-language code analysis engine, across 400+ sessions with Claude Code. I <a href="/2026/03/12/experiences-building-with-coding-assistant.html">wrote about that experience</a> earlier: how CLAUDE.md rules evolved reactively, how structured memory (Beads issues, ADRs, gap analyses) solved the session-to-session continuity problem, how TDD changed the quality of AI-generated tests.</p>

<p>What I didn’t have was a <em>systematic</em> workflow framework. My CLAUDE.md was a collection of individually sensible rules, accumulated reactively over months. It worked, but it was disorganised: duplicate rules scattered across sections, no enforced phase ordering, no complexity-aware ceremony.</p>

<p>The entire refactoring started because I turned on <strong>Pyright</strong>. I come from statically typed languages (Java, C#, C++), and writing a 13,000-line Python project without a type checker had been bothering me. When I enabled Pyright with strict settings, the IR layer lit up with errors. <code class="language-plaintext highlighter-rouge">label: str | None</code> caused 83+ narrowing failures at sites that assumed non-None. <code class="language-plaintext highlighter-rouge">operands: list[Any]</code> was a black hole that Pyright couldn’t reason about at all. <code class="language-plaintext highlighter-rouge">result_reg: str</code> with <code class="language-plaintext highlighter-rouge">""</code> as a sentinel meant every presence check was invisible to the type checker. The type errors weren’t bugs in the running code. They were a <em>map of every place where the code was fragile</em>, where a wrong assumption would pass silently.</p>

<p>Fixing those errors properly meant replacing the stringly-typed IR with domain types and per-opcode instruction classes. That became <em>the</em> refactoring.</p>

<p>I’d been using Claude Code with Superpowers for most of the project’s development. I wanted to try something different, both to evaluate <a href="https://github.com/gsd-build/gsd-2">GSD 2</a> as a tool and to see what workflow ideas I could take away from it. Then I stress-tested those ideas against the refactoring: replacing the single flat instruction class with a union of 31 per-opcode typed dataclasses, and migrating registers and labels from raw strings to domain types.</p>

<p>This post covers both: what I adopted from GSD 2 and later from Superpowers, and what happened when those patterns met a 13,000-test type migration.</p>

<hr />

<h2 id="what-gsd-2-is">What GSD 2 Is</h2>

<p>I’d been aware of the original <a href="https://github.com/gsd-build/gsd">Get Shit Done prompt framework</a> for a while, and had started using it lightly through Claude Code, but I’d never fully embraced it. GSD 2 gave me the opportunity to try the framework whole-heartedly. <a href="https://github.com/gsd-build/gsd-2">GSD 2</a> is a standalone CLI built on the Pi SDK that controls a coding agent’s session programmatically. It’s the evolution of the original GSD, from markdown prompts injected into Claude Code to a TypeScript application that manages context windows, dispatches work, tracks cost, detects stuck loops, and recovers from crashes. Importantly, GSD 2 let me keep using my existing infrastructure (my own ADR documents, Beads for issue tracking, and the CLAUDE.md conventions I’d built up over months) while layering its workflow discipline on top.</p>

<p>The <em>workflow patterns</em> I’m describing here (enforced phases, complexity classification, verification gates, fresh-context discipline, state-on-disk) are not GSD-2-specific. They’re engineering discipline that applies to any AI coding assistant: Claude Code directly, Cursor, Windsurf, Codex, or whatever comes next. The patterns are about how you structure work, not which tool runs it.</p>

<p>Here’s what I took from it.</p>

<hr />

<h2 id="what-i-adopted">What I Adopted</h2>

<h3 id="1-enforced-phases-per-unit-of-work">1. Enforced Phases Per Unit of Work</h3>

<p>GSD 2 has a dispatch pipeline: research → plan → implement → verify. Every unit of work goes through these phases in order. The agent doesn’t skip ahead.</p>

<p>My previous CLAUDE.md had “The workflow is Brainstorm → Discuss → Plan → Write tests → Implement → Fix → Commit → Refactor”, but it was a suggestion, not an enforcement. Multiple times during the multi-file linker work, implementation started before brainstorming was complete. The linker went through four rounds of compensating patches because the initial design was written without understanding the VM’s dispatch model. A proper brainstorm phase (reading the actual VM code, not just designing on paper) would have caught the mismatch on day one.</p>

<p>The new rule: <strong>every non-trivial task goes through brainstorm → plan → test-first → implement → self-review → verify → commit, in that order. Do not skip phases.</strong></p>

<pre><code class="language-mermaid">flowchart LR
    B("🧠 Brainstorm"):::phase1 --&gt; P("📐 Plan"):::phase2 --&gt; T("🧪 Test first"):::test --&gt; I("⚙️ Implement"):::phase3 --&gt; R("🔍 Self-review"):::review --&gt; V("✅ Verify gate"):::gate --&gt; C("📦 Commit"):::done

    classDef phase1 fill:#e8f4fd,stroke:#4a90d9,stroke-width:2px,color:#1a3a5c
    classDef phase2 fill:#fff3e0,stroke:#e8a735,stroke-width:2px,color:#5c3a0a
    classDef test fill:#fce4ec,stroke:#c62828,stroke-width:2px,color:#5c0a0a
    classDef phase3 fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#3a0a3a
    classDef review fill:#fff9c4,stroke:#f9a825,stroke-width:2px,color:#5c4a0a
    classDef gate fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#1a3a1a
    classDef done fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#1a3a1a
</code></pre>

<p>I also added a self-review step between implement and verify: scan your own diff for workaround guards, weak assertions, mutation in loops, stale docs, and missing tests before running the verification gate.</p>

<h3 id="2-complexity-classification">2. Complexity Classification</h3>

<p>GSD 2 classifies each unit as light, standard, or heavy before dispatching. The classification determines model selection and timeout.</p>

<p>I adapted this for ceremony level:</p>

<ul>
  <li><strong>Light</strong> (&lt; 50 lines, single file): brief brainstorm. Adding a node type to a dispatch table.</li>
  <li><strong>Standard</strong> (50–300 lines, follows existing patterns): brainstorm identifies the pattern being followed.</li>
  <li><strong>Heavy</strong> (300+ lines, new abstractions, multiple subsystems): brainstorm must produce a written design with trade-offs before any code. Break into independently-committable units. Do not attempt in a single pass.</li>
</ul>

<p>The multi-file linker was Heavy (500+ lines, new package, touched VM, registry, API, MCP). It should have been broken into smaller units from the start. Instead it was attempted as one continuous stream, which led to the patch-on-patch problem.</p>

<pre><code class="language-mermaid">flowchart TD
    T("📋 New task"):::start --&gt; C{"Classify&lt;br/&gt;complexity"}:::decide

    C -- "&lt; 50 lines,&lt;br/&gt;single file" --&gt; L("💡 Light&lt;br/&gt;&lt;i&gt;Brief brainstorm&lt;/i&gt;&lt;br/&gt;&lt;i&gt;e.g., add node to dispatch table&lt;/i&gt;"):::light
    C -- "50–300 lines,&lt;br/&gt;2–5 files" --&gt; S("📦 Standard&lt;br/&gt;&lt;i&gt;Identify pattern being followed&lt;/i&gt;&lt;br/&gt;&lt;i&gt;e.g., import extraction for new lang&lt;/i&gt;"):::standard
    C -- "300+ lines,&lt;br/&gt;new abstractions" --&gt; H("🏗️ Heavy&lt;br/&gt;&lt;i&gt;Written design + trade-offs&lt;/i&gt;&lt;br/&gt;&lt;i&gt;Break into committable units&lt;/i&gt;&lt;br/&gt;&lt;i&gt;Re-read code before each phase&lt;/i&gt;"):::heavy

    classDef start fill:#e8f4fd,stroke:#4a90d9,stroke-width:2px,color:#1a3a5c
    classDef decide fill:#fff3e0,stroke:#e8a735,stroke-width:2px,color:#5c3a0a
    classDef light fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1a3a1a
    classDef standard fill:#fff9c4,stroke:#f9a825,stroke-width:2px,color:#5c4a0a
    classDef heavy fill:#fce4ec,stroke:#c62828,stroke-width:2px,color:#5c0a0a
</code></pre>

<h3 id="3-verification-gate">3. Verification Gate</h3>

<p>GSD 2 runs automated verification (lint, test, typecheck) with auto-fix retries before marking a unit complete.</p>

<p>My CLAUDE.md had “run black” and “run tests” as separate bullet points in different sections. The <code class="language-plaintext highlighter-rouge">.importlinter</code> check wasn’t mentioned at all, which is how the CI pipeline broke silently with stale module paths for who knows how long.</p>

<p>The new rule: <strong>three checks in order before every commit: <code class="language-plaintext highlighter-rouge">black</code>, <code class="language-plaintext highlighter-rouge">lint-imports</code>, <code class="language-plaintext highlighter-rouge">pytest</code>. All three must pass.</strong></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>poetry run python <span class="nt">-m</span> black <span class="nb">.</span>         <span class="c"># formatting</span>
poetry run lint-imports               <span class="c"># architectural contracts</span>
poetry run python <span class="nt">-m</span> pytest tests/    <span class="c"># full test suite</span>
</code></pre></div></div>

<p>Having this as a single named concept (“verification gate”) instead of scattered bullets makes it harder to skip.</p>

<h3 id="4-fresh-context-for-heavy-tasks">4. Fresh Context for Heavy Tasks</h3>

<p>GSD 2 creates a fresh agent session for every dispatched unit. The LLM starts with a clean context window containing only the pre-inlined artifacts it needs. This prevents quality degradation from context accumulation.</p>

<p>I can’t create fresh sessions mid-conversation. But the underlying insight applies: <strong>design documents can anchor you to a flawed model.</strong> During the linker work, the initial design document described a 7-step linking process with import tables, CALL_FUNCTION rewriting, and entry-module-first ordering. Every one of those assumptions was wrong. But because the design document was in context, the implementation followed it faithfully, then spent four patches compensating for the mismatches.</p>

<p>The new rule: <strong>for Heavy tasks, re-read the actual code before each phase. Don’t implement from a design document without verifying its assumptions against the code you’re modifying.</strong></p>

<h3 id="5-state-on-disk">5. State on Disk</h3>

<p>GSD 2’s <code class="language-plaintext highlighter-rouge">.gsd/</code> directory is the sole source of truth. No in-memory state survives across sessions. This enables crash recovery and session resumption.</p>

<p>I already had Beads for issue tracking and ADRs for decisions. What I was missing was the discipline of <strong>backup before every commit</strong>. Beads state lives in a Dolt database; if a session dies before backup, the issue state is lost. The <code class="language-plaintext highlighter-rouge">bd backup</code> command exports everything to JSONL files committed to the repo.</p>

<p>The new rule: <strong><code class="language-plaintext highlighter-rouge">bd backup</code> before every commit. Issues filed before work starts. Prefer committed partial results over uncommitted complete attempts.</strong> If a session might end, commit with a <code class="language-plaintext highlighter-rouge">WIP:</code> prefix and file an issue for the remainder.</p>

<pre><code class="language-mermaid">flowchart TB
    S(("🚀 Session start")):::start
    S --&gt; R("📜 CLAUDE.md&lt;br/&gt;&lt;i&gt;Rules: how to behave&lt;/i&gt;"):::rules
    S --&gt; A("📚 ADRs&lt;br/&gt;&lt;i&gt;Why past decisions&lt;br/&gt;were made&lt;/i&gt;"):::adrs
    S --&gt; B("📋 Beads issues&lt;br/&gt;&lt;i&gt;What to work on next&lt;/i&gt;"):::issues
    S --&gt; D("📊 Docs&lt;br/&gt;&lt;i&gt;Living design docs&lt;/i&gt;"):::docs
    R &amp; A &amp; B &amp; D --&gt; O("✅ Agent is oriented"):::done

    O --&gt; W("⚙️ Work"):::work
    W --&gt; BK("💾 bd backup"):::backup
    BK --&gt; CM("📦 git commit + push"):::commit
    CM --&gt;|"more work"| W
    CM --&gt;|"session ending"| END("🏁 Clean state on disk"):::done

    classDef start fill:#e8f4fd,stroke:#4a90d9,stroke-width:3px,color:#1a3a5c
    classDef rules fill:#fce4ec,stroke:#c62828,stroke-width:2px,color:#5c0a0a
    classDef adrs fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#3a0a3a
    classDef issues fill:#fff3e0,stroke:#e8a735,stroke-width:2px,color:#5c3a0a
    classDef docs fill:#e8f4fd,stroke:#4a90d9,stroke-width:2px,color:#1a3a5c
    classDef done fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1a3a1a
    classDef work fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#3a0a3a
    classDef backup fill:#fff9c4,stroke:#f9a825,stroke-width:2px,color:#5c4a0a
    classDef commit fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#1a3a1a
</code></pre>

<hr />

<h2 id="teething-issues">Teething Issues</h2>

<h3 id="the-patch-on-patch-problem">The Patch-on-Patch Problem</h3>

<p>The linker was where this adoption was most tested. The original design promised “zero downstream changes”: namespace labels, merge IR, and the existing VM/CFG/registry would just work. It didn’t.</p>

<p>The VM resolves function calls by looking up variable names in the scope chain, not by label. The VM’s CONST handler converts label strings into <code class="language-plaintext highlighter-rouge">BoundFuncRef</code>/<code class="language-plaintext highlighter-rouge">ClassRef</code> via symbol tables. Constructor dispatch uses the class name from ClassRef to look up methods. None of this is label-based. The design document didn’t account for any of it.</p>

<p>What followed: patch 1 (rewrite import stubs as CONST label bindings), patch 2 (pass symbol tables to ExecutionStrategies), patch 3 (keep bare names in symbol tables, not namespaced), patch 4 (insert BRANCH instructions to chain module entries), patch 5 (drop variable import stubs so they don’t overwrite concrete values).</p>

<p>Five patches. Each one “fixed” the immediate symptom. The underlying problem was that the design was wrong: linking at the label level doesn’t work when the VM dispatches at the scope level.</p>

<pre><code class="language-mermaid">flowchart TD
    D("📄 Design:&lt;br/&gt;namespace labels,&lt;br/&gt;rewrite references"):::design
    D --&gt; P1("🩹 Patch 1:&lt;br/&gt;rewrite import stubs&lt;br/&gt;as CONST bindings"):::patch
    P1 --&gt; P2("🩹 Patch 2:&lt;br/&gt;pass symbol tables&lt;br/&gt;to ExecutionStrategies"):::patch
    P2 --&gt; P3("🩹 Patch 3:&lt;br/&gt;bare names in&lt;br/&gt;symbol tables"):::patch
    P3 --&gt; P4("🩹 Patch 4:&lt;br/&gt;BRANCH chains&lt;br/&gt;between modules"):::patch
    P4 --&gt; P5("🩹 Patch 5:&lt;br/&gt;drop variable&lt;br/&gt;import stubs"):::patch
    P5 --&gt; STOP("🛑 Stop.&lt;br/&gt;The design is wrong."):::stop
    STOP --&gt; RW("♻️ Rewrite:&lt;br/&gt;499 → 311 lines&lt;br/&gt;one clean model"):::rewrite

    classDef design fill:#e8f4fd,stroke:#4a90d9,stroke-width:2px,color:#1a3a5c
    classDef patch fill:#fce4ec,stroke:#c62828,stroke-width:2px,color:#5c0a0a
    classDef stop fill:#ffcdd2,stroke:#b71c1c,stroke-width:3px,color:#5c0a0a
    classDef rewrite fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#1a3a1a
</code></pre>

<p>The fix was a rewrite: strip per-module entry labels, concatenate in dependency order, drop import stubs, emit one shared entry label. 499 lines → 311 lines. One clean model instead of five compensating transforms.</p>

<p>If I’d had the “stop and consult when patching” rule from the start, the rewrite would have happened after patch 2, not patch 5.</p>

<h3 id="brainstorm-wasnt-enforced">Brainstorm Wasn’t Enforced</h3>

<p>Several times during the session, I had to redirect: “brainstorm with me first”, “don’t go haring off on your own”, “should this have been a separate issue?”</p>

<p>The phase ordering was written down but not enforced by habit. The AI’s default is to start implementing the moment it understands the problem. The brainstorm phase needs to be explicit: present options, discuss trade-offs, take input. Not a brief internal consideration before diving into code.</p>

<p>This led to a new interaction rule: <strong>brainstorm collaboratively. Present options and trade-offs to the user. Do not pick an approach and start implementing without discussion.</strong></p>

<h3 id="retroactive-issue-filing">Retroactive Issue Filing</h3>

<p>The multi-file work started without filing issues. Bugs were discovered and fixed inline: no issue, no claim, no close. Three linker bugs (<code class="language-plaintext highlighter-rouge">red-dragon-khfp</code>, <code class="language-plaintext highlighter-rouge">red-dragon-qyvn</code>, <code class="language-plaintext highlighter-rouge">red-dragon-q00i</code>) were filed retroactively after I noticed the gap.</p>

<p>The fix was simple: make issue filing the first step, not an afterthought. “File an issue before starting work” was already in CLAUDE.md but wasn’t being followed consistently.</p>

<h3 id="weak-integration-test-assertions">Weak Integration Test Assertions</h3>

<p>After shipping multi-file support for all 16 languages, I discovered that 9 of the 15 tree-sitter language integration tests had weak assertions like <code class="language-plaintext highlighter-rouge">assert "add" in result</code> instead of <code class="language-plaintext highlighter-rouge">assert result["answer"] == 30</code>. These tests would pass even if the cross-module call returned symbolic.</p>

<p>This was a violation of the self-review checklist that I’d just added. The checklist says “weak assertions” is an anti-pattern to scan for. The tests were written before the checklist existed.</p>

<p>Strengthening them exposed two additional bugs: a Pascal frontend gap (<code class="language-plaintext highlighter-rouge">begin...end.</code> block not lowered) and a Pascal function return bug (<code class="language-plaintext highlighter-rouge">Result</code> variable not returned). Both were pre-existing single-file bugs, not linker issues, but the weak multi-file assertions had masked them.</p>

<p>This prompted two new rules. First: <strong>after writing tests, review every assertion for specificity.</strong> Replace <code class="language-plaintext highlighter-rouge">assert x is not None</code> and <code class="language-plaintext highlighter-rouge">assert "name" in result</code> with concrete value assertions like <code class="language-plaintext highlighter-rouge">assert result == 30</code>. If a concrete assertion isn’t possible, document why. Weak assertions that would pass even when the feature is broken are worse than no assertions because they give false confidence.</p>

<p>Second: <strong>every <code class="language-plaintext highlighter-rouge">xfail</code> must have a corresponding Beads issue</strong>, and the <code class="language-plaintext highlighter-rouge">xfail</code> reason string must reference the issue ID. An <code class="language-plaintext highlighter-rouge">xfail</code> without a tracked issue is a gap that never gets fixed. It just sits there, green in the test report, invisible in the backlog.</p>

<h3 id="the-theoretical-bug">The Theoretical Bug</h3>

<p>One of the review findings (<code class="language-plaintext highlighter-rouge">red-dragon-lzae</code>) was about a fragile state machine in the import stub dropper. After brainstorming, we determined the bug was theoretical: no frontend currently produces the problematic instruction pattern, and adding “just in case” code would violate the “no speculative code without tests” principle. We closed it as won’t-fix with a documentation note.</p>

<p>It took a brainstorming session to reach that conclusion. The first instinct (mine and the AI’s) was to write a test and fix it. Brainstorming first (“is this actually a bug?”) saved time.</p>

<hr />

<h2 id="the-reorganised-claudemd">The Reorganised CLAUDE.md</h2>

<p>The adoption process surfaced how disorganised my CLAUDE.md had become. “Run black” appeared in three places. “Run tests” appeared in three places. “Brainstorm before work” appeared twice. The verification gate was split across two sections.</p>

<p>I rewrote it from scratch: deduplicated, restructured into a logical reading order (Project Context → Task Tracking → Workflow → Design Principles → Programming Patterns → Testing → Code Review → Implementation → Interaction), and consolidated related guidance.</p>

<p>245 lines → 168 lines. Same rules, less duplication, clearer structure.</p>

<hr />

<h2 id="the-test-replacing-a-stringly-typed-ir-with-domain-types">The Test: Replacing a Stringly-Typed IR with Domain Types</h2>

<p>With the GSD 2 patterns in place, the next major piece of work was replacing the IR’s instruction representation. This was where the patterns would be tested under sustained pressure.</p>

<p>By late March 2026, RedDragon had ~12,900 tests, 121 architectural decision records, 550+ tracked issues, and a problem: the IR was stringly-typed. Every instruction was an <code class="language-plaintext highlighter-rouge">IRInstruction</code> with an <code class="language-plaintext highlighter-rouge">opcode: Opcode</code> enum and <code class="language-plaintext highlighter-rouge">operands: list[Any]</code>. Labels were <code class="language-plaintext highlighter-rouge">str | None</code>. Registers were bare strings like <code class="language-plaintext highlighter-rouge">"%r0"</code>. Field names, variable names, function names, operator symbols, and register references were all <code class="language-plaintext highlighter-rouge">str</code>, distinguished only by position in the operands list.</p>

<h3 id="the-problem-strings-all-the-way-down">The Problem: Strings All the Way Down</h3>

<p>The core instruction type looked like this:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@dataclass</span>
<span class="k">class</span> <span class="nc">IRInstruction</span><span class="p">:</span>
    <span class="n">opcode</span><span class="p">:</span> <span class="n">Opcode</span>
    <span class="n">operands</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="n">Any</span><span class="p">]</span> <span class="o">=</span> <span class="nf">field</span><span class="p">(</span><span class="n">default_factory</span><span class="o">=</span><span class="nb">list</span><span class="p">)</span>
    <span class="n">result_reg</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="sh">""</span>
    <span class="n">label</span><span class="p">:</span> <span class="nb">str</span> <span class="o">|</span> <span class="bp">None</span> <span class="o">=</span> <span class="bp">None</span>
    <span class="n">source_location</span><span class="p">:</span> <span class="n">SourceLocation</span> <span class="o">|</span> <span class="bp">None</span> <span class="o">=</span> <span class="bp">None</span>
</code></pre></div></div>

<p>A <code class="language-plaintext highlighter-rouge">BINOP</code> instruction had <code class="language-plaintext highlighter-rouge">operands = ["+", "%r1", "%r2"]</code>. The operator is at index 0. The left register is at index 1. The right register is at index 2. Nothing in the type system distinguishes them. A <code class="language-plaintext highlighter-rouge">STORE_FIELD</code> had <code class="language-plaintext highlighter-rouge">operands = ["%r0", "name", "%r1"]</code>: object register, field name, value register. Swap indices 0 and 2 and you get a silent data corruption, not a type error.</p>

<p>The <code class="language-plaintext highlighter-rouge">label</code> field was <code class="language-plaintext highlighter-rouge">str | None</code>. 72% of instructions had <code class="language-plaintext highlighter-rouge">label=None</code>, causing 83+ pyright type errors at sites that assumed non-None. The <code class="language-plaintext highlighter-rouge">result_reg</code> field was <code class="language-plaintext highlighter-rouge">str</code>, with the empty string <code class="language-plaintext highlighter-rouge">""</code> as the sentinel for “no result register.” Comparing a register to <code class="language-plaintext highlighter-rouge">""</code> to check presence was scattered across dozens of files.</p>

<p>This stringly-typed design had served the project well through rapid prototyping. 15 frontends were built against it, plus a VM, a CFG builder, a dataflow analysis engine, a type inference system, an interprocedural analysis pipeline, a multi-file linker, and an MCP server. But as pyright and import-linter tightened the quality gates, the strings became the dominant source of type errors, and every new feature required the same positional-indexing boilerplate.</p>

<p>The goal: replace <code class="language-plaintext highlighter-rouge">IRInstruction</code> entirely with a union of per-opcode frozen dataclasses, where every register is a <code class="language-plaintext highlighter-rouge">Register</code> object, every label is a <code class="language-plaintext highlighter-rouge">CodeLabel</code> object, and every field is named.</p>

<p>What actually happened was messier. The migration proceeded in three chapters, each teaching its own lessons.</p>

<hr />

<h2 id="chapter-1-codelabel-the-first-domino">Chapter 1: CodeLabel, The First Domino</h2>

<p><code class="language-plaintext highlighter-rouge">IRInstruction.label</code> was <code class="language-plaintext highlighter-rouge">str | None</code>. The plan was straightforward: introduce a <code class="language-plaintext highlighter-rouge">CodeLabel(value: str)</code> type and a <code class="language-plaintext highlighter-rouge">NoCodeLabel</code> null-object singleton, replace <code class="language-plaintext highlighter-rouge">str | None</code> everywhere, and push the type through adjacents.</p>

<h3 id="the-attempted-cascade">The Attempted Cascade</h3>

<p>The first session went well. <code class="language-plaintext highlighter-rouge">CodeLabel</code> and <code class="language-plaintext highlighter-rouge">NoCodeLabel</code> were defined. <code class="language-plaintext highlighter-rouge">IRInstruction.label</code> was updated. 49 files were touched. 12,850 tests passed. The issue was closed.</p>

<p>Then I looked at the adjacents. <code class="language-plaintext highlighter-rouge">BasicBlock.label</code> was <code class="language-plaintext highlighter-rouge">str</code>. <code class="language-plaintext highlighter-rouge">cfg.blocks</code> was <code class="language-plaintext highlighter-rouge">dict[str, BasicBlock]</code>. <code class="language-plaintext highlighter-rouge">StateUpdate.next_label</code> was <code class="language-plaintext highlighter-rouge">str</code>. <code class="language-plaintext highlighter-rouge">label_to_idx</code> used string keys. The <code class="language-plaintext highlighter-rouge">CodeLabel</code> type existed, but 19 sites in the interpreter still accessed <code class="language-plaintext highlighter-rouge">.value</code> directly, breaking the abstraction.</p>

<p>I opened a new issue: <em>“CodeLabel: eliminate .value leaks, propagate CodeLabel into BasicBlock, StateUpdate, cfg.blocks.”</em></p>

<p>And then I tried to do it in one pass.</p>

<p>The cascade touched ~40 files. Changing <code class="language-plaintext highlighter-rouge">BasicBlock.label</code> from <code class="language-plaintext highlighter-rouge">str</code> to <code class="language-plaintext highlighter-rouge">CodeLabel</code> cascaded into <code class="language-plaintext highlighter-rouge">cfg.blocks</code> dict keys, which cascaded into <code class="language-plaintext highlighter-rouge">build_cfg()</code>, which cascaded into <code class="language-plaintext highlighter-rouge">build_registry()</code>, which cascaded into the executor’s block lookup, which cascaded into the linker’s namespace operations, which cascaded into the type inference engine’s function signature lookup. Each change was individually simple. Together they formed a dependency chain that crossed every layer of the architecture.</p>

<h3 id="the-revert-and-the-lesson">The Revert and the Lesson</h3>

<p>I reverted everything. The commit message reads:</p>

<blockquote>
  <p>Attempted CodeLabel propagation into cfg_types/cfg.py. Cascade touches ~40 files. Reverted to clean state, needs a dedicated session.</p>
</blockquote>

<p>The lesson was not “the scope was too large.” The lesson was that I had violated my own complexity classification. This was obviously Heavy work (300+ lines, new abstractions, multiple subsystems) but I’d treated it as Standard because each individual change seemed small. The individual changes <em>were</em> small. The cascade was not.</p>

<h3 id="what-actually-shipped">What Actually Shipped</h3>

<p>The next session took a different approach. Instead of propagating <code class="language-plaintext highlighter-rouge">CodeLabel</code> into all adjacents at once, I identified three independently-committable rings:</p>

<ol>
  <li>
    <p><strong>Eliminate <code class="language-plaintext highlighter-rouge">.value</code> leaks in the immediate adjacents.</strong> Push <code class="language-plaintext highlighter-rouge">CodeLabel</code> into <code class="language-plaintext highlighter-rouge">BasicBlock.label</code>, <code class="language-plaintext highlighter-rouge">cfg.blocks</code> keys, <code class="language-plaintext highlighter-rouge">StateUpdate.next_label</code>, and the handler/registry layer. One commit. 12,850 tests.</p>
  </li>
  <li>
    <p><strong>Push wrapping upstream.</strong> <code class="language-plaintext highlighter-rouge">branch_targets()</code> was returning <code class="language-plaintext highlighter-rouge">list[str]</code> and callers were wrapping each element in <code class="language-plaintext highlighter-rouge">CodeLabel(...)</code>. Change <code class="language-plaintext highlighter-rouge">branch_targets()</code> to return <code class="language-plaintext highlighter-rouge">list[CodeLabel]</code> directly. Remove downstream wrapping. One commit.</p>
  </li>
  <li>
    <p><strong>Remove <code class="language-plaintext highlighter-rouge">_coerce_label</code>.</strong> A helper function that auto-converted strings to <code class="language-plaintext highlighter-rouge">CodeLabel</code>. It was masking call sites that should have been explicitly updated. One commit.</p>
  </li>
</ol>

<p>Each ring was a session. Each ring had its own issue. Each ring went through the verification gate independently. The result was the same as the abandoned single-pass attempt, but arrived safely.</p>

<h3 id="the-coercion-validator-mistake">The Coercion Validator Mistake</h3>

<p>During the <code class="language-plaintext highlighter-rouge">CodeLabel</code> work, the AI proposed a Pydantic <code class="language-plaintext highlighter-rouge">field_validator</code> that would auto-convert incoming strings to <code class="language-plaintext highlighter-rouge">CodeLabel</code>. I initially accepted this. It made tests pass immediately, with no caller needing an update.</p>

<p>That was the problem. The validator <em>masked</em> every call site that was passing a raw string. Instead of failing loudly (forcing me to find and fix each caller), it silently converted. When I later tried to remove the validator, I discovered dozens of sites that had never been updated.</p>

<p>This produced a rule that went into CLAUDE.md’s new “Refactoring Principles” section:</p>

<blockquote>
  <p><strong>No coercion validators.</strong> Do not add Pydantic <code class="language-plaintext highlighter-rouge">field_validator</code> or <code class="language-plaintext highlighter-rouge">__post_init__</code> hacks that auto-convert strings to the domain type. These mask call sites that should be explicitly updated. If Pydantic rejects a value, the caller is wrong. Fix the caller.</p>
</blockquote>

<h3 id="the-refactoring-principles-that-crystallised">The Refactoring Principles That Crystallised</h3>

<p>The <code class="language-plaintext highlighter-rouge">CodeLabel</code> experience generated a full set of type-propagation guidelines. Each one came from a specific mistake:</p>

<table>
  <thead>
    <tr>
      <th>Principle</th>
      <th>Mistake it prevents</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>No coercion validators</td>
      <td>Masking unconverted callers</td>
    </tr>
    <tr>
      <td>Push wrapping to the origin</td>
      <td>Re-wrapping at every consumer</td>
    </tr>
    <tr>
      <td>No defensive <code class="language-plaintext highlighter-rouge">isinstance</code> checks</td>
      <td>Inconsistent callers surviving</td>
    </tr>
    <tr>
      <td>Domain methods over string extraction</td>
      <td><code class="language-plaintext highlighter-rouge">.value</code> leaks everywhere</td>
    </tr>
    <tr>
      <td>Validate at construction, not at use</td>
      <td>Double-wrapping going undetected</td>
    </tr>
    <tr>
      <td>Separate name generation from label generation</td>
      <td><code class="language-plaintext highlighter-rouge">fresh_label()</code> producing non-labels</td>
    </tr>
    <tr>
      <td>Serialization at the boundary</td>
      <td><code class="language-plaintext highlighter-rouge">str()</code> in the middle of pipelines</td>
    </tr>
    <tr>
      <td>File issues for the next ring</td>
      <td>Attempting everything in one session</td>
    </tr>
  </tbody>
</table>

<p>These principles were extracted from the CodeLabel work and written into <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> before the Register migration began. They saved significant time on every subsequent step.</p>

<hr />

<h2 id="chapter-2-register-the-pydantic-problem">Chapter 2: Register, The Pydantic Problem</h2>

<p>With <code class="language-plaintext highlighter-rouge">CodeLabel</code> done, the next target was <code class="language-plaintext highlighter-rouge">result_reg: str</code>. The pattern was established: introduce <code class="language-plaintext highlighter-rouge">Register(name: str)</code> and <code class="language-plaintext highlighter-rouge">NoRegister</code> singleton, replace <code class="language-plaintext highlighter-rouge">str</code>, push through adjacents.</p>

<p>The definition was clean:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Register</span><span class="p">:</span>
    <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="n">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="n">name</span>
    <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="nb">object</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
        <span class="k">if</span> <span class="nf">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">other</span>  <span class="c1"># compatibility bridge
</span>        <span class="k">if</span> <span class="nf">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">Register</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">other</span><span class="p">.</span><span class="n">name</span>
        <span class="k">return</span> <span class="nb">NotImplemented</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">NoRegister</code> was the null object: <code class="language-plaintext highlighter-rouge">__str__</code> returned <code class="language-plaintext highlighter-rouge">""</code>, <code class="language-plaintext highlighter-rouge">is_present()</code> returned <code class="language-plaintext highlighter-rouge">False</code>.</p>

<h3 id="the-boolean-truthiness-problem">The Boolean Truthiness Problem</h3>

<p><code class="language-plaintext highlighter-rouge">IRInstruction.result_reg</code> was <code class="language-plaintext highlighter-rouge">str</code>, and the empty string <code class="language-plaintext highlighter-rouge">""</code> was the sentinel for “no result register.” Throughout the codebase, truthiness checks like <code class="language-plaintext highlighter-rouge">if inst.result_reg:</code> were used to test whether an instruction produced a result.</p>

<p>When <code class="language-plaintext highlighter-rouge">result_reg</code> became <code class="language-plaintext highlighter-rouge">Register</code>, the truthiness semantics broke. A <code class="language-plaintext highlighter-rouge">Register("")</code> is truthy in Python (it’s a dataclass instance, not an empty string). <code class="language-plaintext highlighter-rouge">NoRegister</code> is also truthy (same reason). Every <code class="language-plaintext highlighter-rouge">if inst.result_reg:</code> check now always evaluated to <code class="language-plaintext highlighter-rouge">True</code>.</p>

<p>The initial fix was to add <code class="language-plaintext highlighter-rouge">__bool__</code> to <code class="language-plaintext highlighter-rouge">Register</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">__bool__</span><span class="p">(</span><span class="n">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
    <span class="k">return</span> <span class="nf">bool</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">name</span><span class="p">)</span>
</code></pre></div></div>

<p>This restored the old behaviour: <code class="language-plaintext highlighter-rouge">Register("")</code> was falsy, <code class="language-plaintext highlighter-rouge">Register("%r0")</code> was truthy, <code class="language-plaintext highlighter-rouge">NoRegister</code> was falsy.</p>

<p>But <code class="language-plaintext highlighter-rouge">__bool__</code> on a domain type is a code smell. It couples the type to the semantics of one particular usage pattern (truthiness as “is present”). The better fix was explicit: replace every <code class="language-plaintext highlighter-rouge">if inst.result_reg:</code> with <code class="language-plaintext highlighter-rouge">if inst.result_reg.is_present()</code>. This was 30+ sites across the codebase.</p>

<p>The <code class="language-plaintext highlighter-rouge">__bool__</code> method was added, used as a temporary bridge, and then removed in a separate commit after all call sites were migrated to <code class="language-plaintext highlighter-rouge">is_present()</code>. The commit message: <em>“Register: remove __bool__, use explicit is_present() everywhere.”</em></p>

<p>The <code class="language-plaintext highlighter-rouge">CodeLabel</code> principles applied directly: push semantics to the domain type, don’t rely on Python’s implicit protocols.</p>

<h3 id="the-branch_if-comma-convention">The BRANCH_IF Comma Convention</h3>

<p><code class="language-plaintext highlighter-rouge">BRANCH_IF</code> stored its branch targets as <code class="language-plaintext highlighter-rouge">operands = ["%r0", "L_true,L_false"]</code>. Two labels concatenated with a comma in a single string. Callers split on comma to recover the label list.</p>

<p>This was not a design choice. It was an accidental constraint from the early days when <code class="language-plaintext highlighter-rouge">operands</code> was <code class="language-plaintext highlighter-rouge">list[Any]</code> and nobody thought about it. The comma string had survived hundreds of sessions and 12,000+ tests because it worked.</p>

<p>Replacing it was the right time, since we were already touching <code class="language-plaintext highlighter-rouge">BRANCH_IF</code> for the <code class="language-plaintext highlighter-rouge">Register</code> migration. The fix introduced a <code class="language-plaintext highlighter-rouge">branch_targets: tuple[CodeLabel, ...]</code> field on the typed <code class="language-plaintext highlighter-rouge">BranchIf</code> instruction, eliminating the comma-separated string entirely.</p>

<p>But the migration was tricky because the comma convention was load-bearing in <code class="language-plaintext highlighter-rouge">cfg.py</code>, <code class="language-plaintext highlighter-rouge">dataflow.py</code>, and <code class="language-plaintext highlighter-rouge">registry.py</code>. Each file had its own slightly different approach to splitting the string:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># cfg.py
</span><span class="n">targets</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">].</span><span class="nf">split</span><span class="p">(</span><span class="sh">"</span><span class="s">,</span><span class="sh">"</span><span class="p">)</span>

<span class="c1"># dataflow.py
</span><span class="k">for</span> <span class="n">target</span> <span class="ow">in</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">].</span><span class="nf">split</span><span class="p">(</span><span class="sh">"</span><span class="s">,</span><span class="sh">"</span><span class="p">):</span>

<span class="c1"># registry.py
</span><span class="n">branches</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">].</span><span class="nf">split</span><span class="p">(</span><span class="sh">"</span><span class="s">,</span><span class="sh">"</span><span class="p">)</span> <span class="k">if</span> <span class="sh">"</span><span class="s">,</span><span class="sh">"</span> <span class="ow">in</span> <span class="nf">str</span><span class="p">(</span><span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span> <span class="k">else</span> <span class="p">[</span><span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]]</span>
</code></pre></div></div>

<p>Three files, three variations, one undocumented convention. The structured <code class="language-plaintext highlighter-rouge">branch_targets</code> field eliminated all of them.</p>

<hr />

<h2 id="chapter-3-typed-instructions">Chapter 3: Typed Instructions</h2>

<p>Chapters 1 and 2 had fixed the <em>metadata</em> fields on <code class="language-plaintext highlighter-rouge">IRInstruction</code>: <code class="language-plaintext highlighter-rouge">label</code> became <code class="language-plaintext highlighter-rouge">CodeLabel</code>, <code class="language-plaintext highlighter-rouge">result_reg</code> became <code class="language-plaintext highlighter-rouge">Register</code>. But the actual payload of each instruction, the thing that made a <code class="language-plaintext highlighter-rouge">BINOP</code> different from a <code class="language-plaintext highlighter-rouge">STORE_FIELD</code>, still lived in <code class="language-plaintext highlighter-rouge">operands: list[Any]</code>.</p>

<p>This was the field that Pyright couldn’t reason about at all. It accepted anything: strings, ints, <code class="language-plaintext highlighter-rouge">CodeLabel</code> objects, lists of <code class="language-plaintext highlighter-rouge">CodeLabel</code> objects, <code class="language-plaintext highlighter-rouge">SpreadArguments</code> wrappers. The type checker saw <code class="language-plaintext highlighter-rouge">list[Any]</code> and gave up. Every read from <code class="language-plaintext highlighter-rouge">operands</code> was untyped, every write was unchecked, and every positional convention was invisible to static analysis.</p>

<p>The <code class="language-plaintext highlighter-rouge">operands</code> bag was also the source of the most insidious class of bugs: <em>silent positional swaps</em>. A <code class="language-plaintext highlighter-rouge">STORE_FIELD</code> had <code class="language-plaintext highlighter-rouge">operands = [obj_reg, field_name, value_reg]</code>. If a frontend accidentally emitted <code class="language-plaintext highlighter-rouge">operands = [field_name, obj_reg, value_reg]</code>, the type system had nothing to say. All three values were strings. The bug would surface as wrong runtime behaviour, not a type error. Every consumer of the IR had its own positional destructuring logic, and every one was a potential source of index bugs that no tool could catch statically.</p>

<h3 id="the-decision-one-class-per-opcode">The Decision: One Class Per Opcode</h3>

<p>The IR had a single <code class="language-plaintext highlighter-rouge">IRInstruction</code> class carrying every instruction in the system. A <code class="language-plaintext highlighter-rouge">CONST</code> loading a literal, a <code class="language-plaintext highlighter-rouge">CALL_METHOD</code> dispatching to an object, a <code class="language-plaintext highlighter-rouge">TRY_PUSH</code> setting up an exception handler: all the same class, distinguished only by the <code class="language-plaintext highlighter-rouge">opcode</code> enum and the contents of the <code class="language-plaintext highlighter-rouge">operands</code> bag. Every consumer had to destructure positionally:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># What is operands[0]? Depends on the opcode.
</span><span class="k">if</span> <span class="n">inst</span><span class="p">.</span><span class="n">opcode</span> <span class="o">==</span> <span class="n">Opcode</span><span class="p">.</span><span class="n">BINOP</span><span class="p">:</span>
    <span class="n">operator</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>   <span class="c1"># str: "+"
</span>    <span class="n">left_reg</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>   <span class="c1"># str: "%r0"
</span>    <span class="n">right_reg</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>  <span class="c1"># str: "%r1"
</span><span class="k">elif</span> <span class="n">inst</span><span class="p">.</span><span class="n">opcode</span> <span class="o">==</span> <span class="n">Opcode</span><span class="p">.</span><span class="n">STORE_FIELD</span><span class="p">:</span>
    <span class="n">obj_reg</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>    <span class="c1"># str: "%r0"
</span>    <span class="n">field_name</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># str: "name"
</span>    <span class="n">value_reg</span> <span class="o">=</span> <span class="n">inst</span><span class="p">.</span><span class="n">operands</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>  <span class="c1"># str: "%r1"
</span></code></pre></div></div>

<p>The same index meant different things depending on the opcode. Swap two operands in a <code class="language-plaintext highlighter-rouge">STORE_FIELD</code> and the error is silent: both are strings, both fit in <code class="language-plaintext highlighter-rouge">operands[2]</code>, and the type system has nothing to say about it.</p>

<p>The alternative was a discriminated union: one frozen dataclass per opcode, each with named fields of the correct type. A <code class="language-plaintext highlighter-rouge">Binop</code> has <code class="language-plaintext highlighter-rouge">operator: str</code>, <code class="language-plaintext highlighter-rouge">left: Register</code>, <code class="language-plaintext highlighter-rouge">right: Register</code>. A <code class="language-plaintext highlighter-rouge">StoreField</code> has <code class="language-plaintext highlighter-rouge">obj_reg: Register</code>, <code class="language-plaintext highlighter-rouge">field_name: str</code>, <code class="language-plaintext highlighter-rouge">value_reg: Register</code>. Swapping <code class="language-plaintext highlighter-rouge">obj_reg</code> and <code class="language-plaintext highlighter-rouge">value_reg</code> is still possible, but swapping <code class="language-plaintext highlighter-rouge">field_name</code> and <code class="language-plaintext highlighter-rouge">value_reg</code> is a type error because one is <code class="language-plaintext highlighter-rouge">str</code> and the other is <code class="language-plaintext highlighter-rouge">Register</code>.</p>

<p>The trade-off was migration cost. A single <code class="language-plaintext highlighter-rouge">IRInstruction</code> class was the interface for every frontend (15 tree-sitter frontends, an LLM frontend, a COBOL frontend), every handler (28 VM handlers), the CFG builder, the dataflow engine, the type inference system, the interprocedural analysis pipeline, the linker, and the MCP server. Replacing it required touching all of them. The compatibility bridge (<code class="language-plaintext highlighter-rouge">to_typed()</code>/<code class="language-plaintext highlighter-rouge">to_flat()</code> converters, <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code>, <code class="language-plaintext highlighter-rouge">operands</code> properties on the typed classes) existed to make this migration incremental rather than big-bang.</p>

<p>The design produced 31 frozen dataclasses sharing a common <code class="language-plaintext highlighter-rouge">InstructionBase</code> with <code class="language-plaintext highlighter-rouge">source_location</code>, plus per-class fields for registers, labels, operators, names, and branch targets. The <code class="language-plaintext highlighter-rouge">Instruction</code> union type was the discriminant:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Instruction</span> <span class="o">=</span> <span class="p">(</span>
    <span class="n">Const</span> <span class="o">|</span> <span class="n">LoadVar</span> <span class="o">|</span> <span class="n">DeclVar</span> <span class="o">|</span> <span class="n">StoreVar</span> <span class="o">|</span> <span class="n">Symbolic</span> <span class="o">|</span>
    <span class="n">Binop</span> <span class="o">|</span> <span class="n">Unop</span> <span class="o">|</span>
    <span class="n">CallFunction</span> <span class="o">|</span> <span class="n">CallMethod</span> <span class="o">|</span> <span class="n">CallUnknown</span> <span class="o">|</span>
    <span class="n">LoadField</span> <span class="o">|</span> <span class="n">StoreField</span> <span class="o">|</span> <span class="n">LoadFieldIndirect</span> <span class="o">|</span>
    <span class="n">LoadIndex</span> <span class="o">|</span> <span class="n">StoreIndex</span> <span class="o">|</span>
    <span class="n">LoadIndirect</span> <span class="o">|</span> <span class="n">StoreIndirect</span> <span class="o">|</span> <span class="n">AddressOf</span> <span class="o">|</span>
    <span class="n">NewObject</span> <span class="o">|</span> <span class="n">NewArray</span> <span class="o">|</span>
    <span class="n">Label_</span> <span class="o">|</span> <span class="n">Branch</span> <span class="o">|</span> <span class="n">BranchIf</span> <span class="o">|</span>
    <span class="n">Return_</span> <span class="o">|</span> <span class="n">Throw_</span> <span class="o">|</span>
    <span class="n">TryPush</span> <span class="o">|</span> <span class="n">TryPop</span> <span class="o">|</span>
    <span class="n">AllocRegion</span> <span class="o">|</span> <span class="n">LoadRegion</span> <span class="o">|</span> <span class="n">WriteRegion</span> <span class="o">|</span>
    <span class="n">SetContinuation</span> <span class="o">|</span> <span class="n">ResumeContinuation</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Consumer dispatch changed from <code class="language-plaintext highlighter-rouge">dict[Opcode, handler]</code> to <code class="language-plaintext highlighter-rouge">dict[type, handler]</code>, and opcode checks from <code class="language-plaintext highlighter-rouge">inst.opcode == Opcode.LABEL</code> to <code class="language-plaintext highlighter-rouge">isinstance(inst, Label_)</code>. Generic transformations (register rebasing in the linker, label namespacing in multi-file compilation) went from operand-by-operand iteration to <code class="language-plaintext highlighter-rouge">inst.map_registers(fn)</code> and <code class="language-plaintext highlighter-rouge">inst.map_labels(fn)</code>, which introspect the dataclass fields and return a new frozen instance via <code class="language-plaintext highlighter-rouge">dataclasses.replace()</code>.</p>

<h3 id="the-original-four-phase-plan">The Original Four-Phase Plan</h3>

<p>The initial design session produced a four-phase plan:</p>

<ol>
  <li><strong>Define typed instruction classes</strong>: 30 frozen dataclasses, one per opcode</li>
  <li><strong>Migrate handler consumers</strong>: VM handlers use <code class="language-plaintext highlighter-rouge">to_typed()</code> for named field access</li>
  <li><strong>Migrate remaining consumers</strong>: CFG, dataflow, type inference, linker, etc.</li>
  <li><strong>Migrate frontend producers</strong>: replace <code class="language-plaintext highlighter-rouge">emit(Opcode.X, ...)</code> with <code class="language-plaintext highlighter-rouge">emit_inst(TypedInstruction(...))</code></li>
</ol>

<p>Phases 1–3 were completed first. Phase 4 started with <code class="language-plaintext highlighter-rouge">common/</code> (190 calls migrated) and the <code class="language-plaintext highlighter-rouge">emit_inst()</code> infrastructure.</p>

<p>Then came the realisation: <strong>the plan was incomplete.</strong> The register <em>operand</em> fields inside typed instructions were still <code class="language-plaintext highlighter-rouge">str</code>. A <code class="language-plaintext highlighter-rouge">Binop</code> had <code class="language-plaintext highlighter-rouge">left: str</code> and <code class="language-plaintext highlighter-rouge">right: str</code>. Changing those to <code class="language-plaintext highlighter-rouge">Register</code> was a separate layer of work that the original plan hadn’t accounted for.</p>

<h3 id="the-plan-that-replaced-the-plan">The Plan That Replaced the Plan</h3>

<p>The original four phases were dissolved into a five-layer plan, documented in ADR-121 and a dedicated design document:</p>

<pre><code class="language-mermaid">flowchart TD
    L1("Layer 1&lt;br/&gt;Register fields in&lt;br/&gt;instruction classes&lt;br/&gt;&lt;i&gt;str → Register&lt;/i&gt;"):::layer
    L2("Layer 2&lt;br/&gt;map_registers/map_labels&lt;br/&gt;on InstructionBase"):::layer
    L3("Layer 3&lt;br/&gt;Migrate consumers&lt;br/&gt;&lt;i&gt;5 sub-issues&lt;/i&gt;"):::layer
    L4("Layer 4&lt;br/&gt;Migrate producers&lt;br/&gt;&lt;i&gt;19 sub-issues&lt;/i&gt;"):::layer
    L5("Layer 5&lt;br/&gt;Remove the bridge&lt;br/&gt;&lt;i&gt;delete IRInstruction&lt;/i&gt;"):::layer

    L1 --&gt; L2
    L1 --&gt; L3
    L1 --&gt; L4a("Layer 4a&lt;br/&gt;lower_expr() → Register"):::sub
    L2 --&gt; L3a("3a: handlers&lt;br/&gt;+ executor"):::sub
    L2 --&gt; L3d("3d: linker&lt;br/&gt;+ compiler"):::sub
    L1 --&gt; L3b("3b: type&lt;br/&gt;inference"):::sub
    L1 --&gt; L3c("3c: CFG +&lt;br/&gt;dataflow"):::sub
    L1 --&gt; L3e("3e: LLM +&lt;br/&gt;COBOL + misc"):::sub
    L4a --&gt; L4f("17 frontend&lt;br/&gt;sub-issues&lt;br/&gt;&lt;i&gt;~1,357 emit() calls&lt;/i&gt;"):::sub

    L3 --&gt; L5
    L4f --&gt; L5

    classDef layer fill:#e8f4fd,stroke:#4a90d9,stroke-width:2px,color:#1a3a5c
    classDef sub fill:#fff3e0,stroke:#e8a735,stroke-width:2px,color:#5c3a0a
</code></pre>

<p>The five-layer plan had 28 independently-trackable sub-issues. Each sub-issue was a self-contained commit with a test gate. The <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code> compatibility bridge would remain until Layer 5, making all preceding layers individually safe.</p>

<p>The key insight was decomposition granularity. Layer 4 alone had 17 sub-issues, one per frontend, because each frontend could be migrated independently. The Rust frontend had 127 <code class="language-plaintext highlighter-rouge">emit()</code> calls. The COBOL emit context had 9. Mixing them in one commit would have made review and revert impossible.</p>

<h3 id="the-missing-length-field">The Missing Length Field</h3>

<p>Phase 1 of the original plan defined 30 typed instruction classes. Each class was a frozen dataclass with named fields instead of positional operands. The round-trip test (<code class="language-plaintext highlighter-rouge">to_typed(inst).to_flat() == inst</code>) was the primary verification.</p>

<p>The <code class="language-plaintext highlighter-rouge">LoadRegion</code> instruction was defined as:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">LoadRegion</span><span class="p">(</span><span class="n">InstructionBase</span><span class="p">):</span>
    <span class="n">result_reg</span><span class="p">:</span> <span class="n">Register</span> <span class="o">=</span> <span class="n">NO_REGISTER</span>
    <span class="n">region_reg</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="sh">""</span>
    <span class="n">offset_reg</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="sh">""</span>
</code></pre></div></div>

<p>But <code class="language-plaintext highlighter-rouge">LOAD_REGION</code> in the IR had four operands: region register, offset register, <em>length</em>, and a field name. The <code class="language-plaintext highlighter-rouge">length</code> field was missing from the typed class. The round-trip test caught this immediately (the <code class="language-plaintext highlighter-rouge">to_flat()</code> output had fewer operands than the input) but the bug existed in the first commit and had to be fixed as a follow-up.</p>

<p>The cause was straightforward: the AI generated the class from the opcode name and the most common operand patterns, without checking the actual <code class="language-plaintext highlighter-rouge">_handle_load_region</code> handler for the full operand list. The IR reference document listed the correct operands, but the class definition was generated from pattern inference, not from the spec.</p>

<p>Commit message: <em>“fix: LoadRegion typed instruction, add missing length field.”</em></p>

<p>The lesson: <strong>generated code that passes a round-trip test is not necessarily correct; the test verifies internal consistency, not completeness.</strong> A class with 3 fields that round-trips perfectly to a 3-operand instruction is still wrong if the real instruction has 4 operands.</p>

<h3 id="layer-1-execution">Layer 1 Execution</h3>

<p>Layer 1 was the riskiest single commit: changing 31 fields across 21 instruction classes from <code class="language-plaintext highlighter-rouge">str</code> to <code class="language-plaintext highlighter-rouge">Register</code>, plus updating all <code class="language-plaintext highlighter-rouge">operands</code> properties, <code class="language-plaintext highlighter-rouge">to_typed()</code> converters, and <code class="language-plaintext highlighter-rouge">to_flat()</code> converters.</p>

<p>The <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code> bridge was supposed to make this safe: all existing string comparisons would continue to work. And it did, mostly. But several edge cases escaped the bridge:</p>

<p><strong>1. COBOL literal-in-call-operand.</strong> COBOL frontends occasionally put literal values (not register names) in call argument positions. These weren’t registers; they were strings like <code class="language-plaintext highlighter-rouge">"SPACES"</code> or <code class="language-plaintext highlighter-rouge">"100"</code>. Wrapping them in <code class="language-plaintext highlighter-rouge">Register(...)</code> was semantically wrong. The fix was an <code class="language-plaintext highlighter-rouge">_as_register()</code> helper that checked whether the operand looked like a register name before wrapping.</p>

<p><strong>2. <code class="language-plaintext highlighter-rouge">_resolve_reg</code> fallback path.</strong> When the VM’s <code class="language-plaintext highlighter-rouge">_resolve_reg</code> couldn’t find a register in the frame, it returned the raw operand as a fallback (for symbolic execution of incomplete programs). After the migration, this fallback returned a <code class="language-plaintext highlighter-rouge">Register</code> object instead of a string, which leaked into <code class="language-plaintext highlighter-rouge">TypedValue</code> wrappers and broke downstream comparisons. The fix: <code class="language-plaintext highlighter-rouge">_resolve_reg</code> fallback returns <code class="language-plaintext highlighter-rouge">str(operand)</code>, not the raw <code class="language-plaintext highlighter-rouge">Register</code>.</p>

<p><strong>3. <code class="language-plaintext highlighter-rouge">_is_temporary_register</code> in dataflow.</strong> This function subscripted the register name to check character patterns: <code class="language-plaintext highlighter-rouge">reg[1] == 'r' and reg[2:].isdigit()</code>. After migration, <code class="language-plaintext highlighter-rouge">reg</code> was a <code class="language-plaintext highlighter-rouge">Register</code> object, and subscripting it didn’t work. The fix: convert to <code class="language-plaintext highlighter-rouge">str</code> before subscripting.</p>

<p><strong>4. StoreIndex with SpreadArguments.</strong> Some frontends emitted <code class="language-plaintext highlighter-rouge">STORE_INDEX</code> with a <code class="language-plaintext highlighter-rouge">SpreadArguments</code> in the <code class="language-plaintext highlighter-rouge">value_reg</code> position, a convention for array unpacking. The <code class="language-plaintext highlighter-rouge">value_reg</code> field was typed as <code class="language-plaintext highlighter-rouge">Register</code>, not <code class="language-plaintext highlighter-rouge">Register | SpreadArguments</code>, so the type system rejected it. The fix: preserve <code class="language-plaintext highlighter-rouge">SpreadArguments</code> in <code class="language-plaintext highlighter-rouge">StoreIndex.value_reg</code> with a note documenting the frontend convention.</p>

<p>Each of these was a small fix. Together they took as long as the main migration. The commit message for Layer 1 runs to 14 lines documenting the edge cases.</p>

<p>All 12,924 tests passed. 22 xfailed. 1 skipped.</p>

<hr />

<h2 id="chapter-4-completing-the-migration-with-superpowers">Chapter 4: Completing the Migration with Superpowers</h2>

<p>Layer 1 was the riskiest single commit, and the GSD v2 workflow patterns had gotten me through it. But the five-layer plan sat at roughly 15% complete. Layers 2 through 5 still needed ~2,200 sites migrated across ~100 files. The GSD v2 patterns had gotten me through the riskiest single commit, but the remaining work stalled.</p>

<h3 id="why-gsd-v2-stalled-after-layer-1">Why GSD v2 Stalled After Layer 1</h3>

<p>The GSD v2 patterns I’d adopted were <em>rules in CLAUDE.md</em>: enforce phases, classify complexity, run the verification gate. They worked as guardrails. But they didn’t help with the <em>orchestration</em> problem: who breaks down the next 4 layers into sub-issues? Who dispatches work? Who reviews each piece before moving to the next?</p>

<p>With GSD v2 patterns, the agent was too eager. It would see the five-layer plan, start implementing Layer 2, hit an edge case, make a judgment call without consulting me, then discover the judgment was wrong three layers later. The “stop and consult when patching” rule was in CLAUDE.md, but the agent treated it as a suggestion, not a gate.</p>

<p>GSD v2 gave me <em>process discipline</em> (phases, verification, state on disk) but not <em>decision discipline</em> (when to pause, when to decompose, when to ask).</p>

<p>There were also practical issues. As the session grew long, GSD v2’s TUI would behave erratically: freezing the terminal window, scrolling to random sections of the session unprompted. This made it harder to stay oriented during multi-hour work.</p>

<p>A caveat: I did not investigate all of GSD v2’s configuration options in depth. It has settings for model selection, timeout behaviour, stuck-loop detection, and other knobs that might have helped. What I’m describing is the out-of-the-box experience with default settings applied to a Heavy refactoring.</p>

<h3 id="what-superpowers-did-differently">What Superpowers Did Differently</h3>

<p>I switched back to the <a href="https://github.com/anthropics/claude-code/tree/main/plugins/superpowers">Superpowers</a> plugin for Claude Code, which I’d used for much of the project’s earlier development.</p>

<p><strong>Brainstorming was a real gate.</strong> Superpowers’ brainstorming skill forced a structured conversation before any implementation. When I said “execute this plan,” it first asked five clarifying questions, one at a time, with multiple choice options and a recommendation. Layer 4 decomposition strategy? One sub-issue per frontend (option A), grouped by size tier (B), or grouped by language family (C)? I picked A. The <code class="language-plaintext highlighter-rouge">lower_expr()</code> signature change: bundled with frontend migration or separate atomic commit? I picked separate. These decisions shaped the entire execution.</p>

<p>With GSD v2 patterns alone, the agent would have made these decisions silently and started coding.</p>

<p><strong>Two-stage review after every task.</strong> Superpowers dispatched a fresh subagent per task, then ran a spec compliance review (“did you build what was requested?”) followed by a code quality review (“is it well-built?”). The spec reviewer caught the Layer 1 <code class="language-plaintext highlighter-rouge">StoreIndex.value_reg</code> <code class="language-plaintext highlighter-rouge">SpreadArguments</code> guard issue. The code quality reviewer caught the <code class="language-plaintext highlighter-rouge">types.UnionType</code> vs <code class="language-plaintext highlighter-rouge">typing.Union</code> problem for Python 3.13 that would have <em>broken <code class="language-plaintext highlighter-rouge">map_registers()</code> at runtime</em>.</p>

<p>With GSD v2, self-review was a checklist item. With Superpowers, review was a separate agent with adversarial instructions.</p>

<p><strong>Issues filed for discovered work.</strong> During Layer 3e, the agent discovered that <code class="language-plaintext highlighter-rouge">registry.py</code> had 3 <code class="language-plaintext highlighter-rouge">opcode==</code> comparisons that couldn’t be migrated because the instruction list was mixed-type. With GSD v2 patterns, this would have been noted in a commit message and forgotten. With Superpowers, I asked “are there issues filed for any of the new-found follow-up work?” The agent checked, found 4 undocumented items, and filed them immediately, each blocking the epic. The dependency graph stayed honest.</p>

<p><strong>The plan was revised during execution.</strong> After Layer 3 completed, the agent checked whether the plan’s assumptions still held. The Layer 3a estimate of “~100 sites” turned out to be 4 sites (the executor was already clean). Layer 3e estimated “~40 sites” turned out to be 128 (COBOL ir_encoders dominated). The plan was rewritten mid-execution with corrected counts, updated dependency graphs, and new prerequisite issues. The design document became a living record rather than a stale spec.</p>

<h3 id="the-audit-that-revised-the-plan">The Audit That Revised the Plan</h3>

<p>The session started with an audit. I asked the agent to examine <code class="language-plaintext highlighter-rouge">red-dragon-0ibe</code> and its design doc. It dispatched an exploration subagent that surveyed the entire codebase: every <code class="language-plaintext highlighter-rouge">to_typed()</code> call, every <code class="language-plaintext highlighter-rouge">inst.operands[</code> access, every <code class="language-plaintext highlighter-rouge">opcode==</code> comparison, every <code class="language-plaintext highlighter-rouge">IRInstruction(</code> construction. The findings were a table with file, line, and count for each migration marker.</p>

<p>The audit revealed that the design doc’s estimates were wrong in both directions. Handlers had 0 <code class="language-plaintext highlighter-rouge">to_typed()</code> calls (not the estimated 72). COBOL <code class="language-plaintext highlighter-rouge">ir_encoders.py</code> had 106 <code class="language-plaintext highlighter-rouge">IRInstruction</code> constructions (not counted in the original plan at all). Type inference had a full Opcode-keyed dispatch table that needed replacement (described as “~30 sites, annotation changes only”).</p>

<p>This upfront survey took <strong>10 minutes</strong>. It saved hours of mid-implementation replanning.</p>

<h3 id="layers-2-through-5-execution">Layers 2 Through 5: Execution</h3>

<p>With the revised plan, execution was systematic:</p>

<p><strong>Layer 2</strong> (2 commits, small): <code class="language-plaintext highlighter-rouge">Register.rebase(offset)</code> and <code class="language-plaintext highlighter-rouge">map_registers()</code>/<code class="language-plaintext highlighter-rouge">map_labels()</code> on <code class="language-plaintext highlighter-rouge">InstructionBase</code>. The <code class="language-plaintext highlighter-rouge">types.UnionType</code> fix (caught by the plan reviewer) was baked into the implementation. 22 new tests.</p>

<p><strong>Layer 3</strong> (4 commits, 5 sub-issues): Consumer migration. The agent dispatched sub-issues in parallel where dependencies allowed — 3b, 3c, 3e could start immediately after Layer 1, without waiting for Layer 2. Layer 3a was deferred entirely (blocked by COBOL literal operands). Layer 3d used the new <code class="language-plaintext highlighter-rouge">map_registers()</code> in the linker, deleting the old <code class="language-plaintext highlighter-rouge">_rebase_operand</code> helper.</p>

<p><strong>Layer 4a</strong> (1 commit): <code class="language-plaintext highlighter-rouge">lower_expr() -&gt; Register</code> signature change across 33 files, ~316 methods. Single atomic mechanical commit.</p>

<p><strong>Layer 4</strong> (15 commits): One per frontend. The agent dispatched batches: 5 small frontends first (C, Lua, TypeScript, C++, Scala), then 4 medium (Go, Python, JavaScript, Pascal), then 6 large (PHP, C#, Java, Kotlin, Ruby, Rust). Plus <code class="language-plaintext highlighter-rouge">_base.py</code>/<code class="language-plaintext highlighter-rouge">context.py</code> and COBOL <code class="language-plaintext highlighter-rouge">emit_context.py</code>. ~1,300 <code class="language-plaintext highlighter-rouge">emit()</code> calls converted to <code class="language-plaintext highlighter-rouge">emit_inst()</code>.</p>

<p><strong>Prerequisites</strong> (3 commits): Before Layer 5 could start, 4 discovered issues needed resolution. COBOL <code class="language-plaintext highlighter-rouge">ir_encoders.py</code> literal operands → emit CONST instructions for literals instead. 59 remaining COBOL frontend <code class="language-plaintext highlighter-rouge">emit()</code> calls. Registry mixed-type list. VM/dataflow boundary cleanup.</p>

<p><strong>Layer 5</strong> (3 commits): Delete <code class="language-plaintext highlighter-rouge">emit()</code> methods. Add standalone <code class="language-plaintext highlighter-rouge">__str__</code> (replacing <code class="language-plaintext highlighter-rouge">to_flat()</code> delegation). Delete <code class="language-plaintext highlighter-rouge">to_flat()</code> and all flat-to-typed converters. Remove <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code> — which broke ~300 test sites that were fixed in a single commit. Delete <code class="language-plaintext highlighter-rouge">IRInstruction</code> class.</p>

<p>Total: <strong>~32 commits, ~100 files modified, zero test regressions</strong> at any point. 12,944 tests passing throughout.</p>

<p>The subagent execution times (including test suite runs after each change) give a sense of effort per layer:</p>

<table>
  <thead>
    <tr>
      <th>Layer</th>
      <th>Subagent time</th>
      <th>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Layer 1 (Register fields)</td>
      <td>~64 min</td>
      <td>Riskiest commit; 4 edge cases discovered</td>
    </tr>
    <tr>
      <td>Layer 2a+2b (rebase, map_registers)</td>
      <td>~19 min</td>
      <td>Small, well-specified</td>
    </tr>
    <tr>
      <td>Layer 3 (5 sub-issues)</td>
      <td>~94 min</td>
      <td>3b and 3e ran in parallel; 3e dominated at 22 min</td>
    </tr>
    <tr>
      <td>Layer 4a (signatures)</td>
      <td>~15 min</td>
      <td>Mechanical find-and-replace</td>
    </tr>
    <tr>
      <td>Layer 4 (15 frontends)</td>
      <td>~64 min</td>
      <td>Three batches; largest frontends took longest</td>
    </tr>
    <tr>
      <td>Prerequisites (pyww, oczk, b6m4, j1o6)</td>
      <td>~68 min</td>
      <td>pyww dominated at 57 min</td>
    </tr>
    <tr>
      <td>Layer 5a-E (delete emit, to_flat)</td>
      <td>~49 min</td>
      <td> </td>
    </tr>
    <tr>
      <td>Layer 5F (Register.<strong>eq</strong> removal)</td>
      <td>~107 min</td>
      <td>300+ test sites fixed in one pass</td>
    </tr>
    <tr>
      <td>Layer 5G (delete IRInstruction)</td>
      <td>~53 min</td>
      <td>100 files, type annotation cascade</td>
    </tr>
    <tr>
      <td><strong>Total subagent time</strong></td>
      <td><strong>~533 min (~9 hours)</strong></td>
      <td>Single session, wall clock ~12 hours with review/planning</td>
    </tr>
  </tbody>
</table>

<p>The wall clock time was longer than the subagent time because of the planning, brainstorming, review, and consultation work between subagent dispatches. The brainstorming conversation at the start of the session (decomposing layers, choosing strategies, resolving open questions) took roughly an hour before any code was written.</p>

<pre><code class="language-mermaid">timeline
    title IRInstruction Elimination
    Layer 1-2 : L1 Register fields, 33 fields
               : L2a rebase method
               : L2b map_registers, map_labels
    Layer 3   : 3b type inference dispatch
               : 3c CFG, dataflow isinstance
               : 3d linker map_registers
               : 3e LLM, COBOL, registry, 128 sites
    Layer 4   : 4a lower_expr to Register
               : 15 frontends, 1300 sites
    Prerequisites : COBOL literal operands
                  : COBOL frontend emit
                  : registry cleanup
    Layer 5   : inline_ir refactor
               : delete emit, to_flat
               : remove Register eq str
               : delete IRInstruction
</code></pre>

<h3 id="layer-5-was-not-cleanup">Layer 5 Was Not Cleanup</h3>

<p>The plan described Layer 5 as “remove the bridge.” The actual scope was larger.</p>

<p>The plan said “delete IRInstruction, to_typed/to_flat, operands properties, Register.<strong>eq</strong>(str).” The survey said ~100 sites. The reality was that <code class="language-plaintext highlighter-rouge">IRInstruction</code> was referenced in 116 imports across 36 files. <code class="language-plaintext highlighter-rouge">to_typed()</code> was called at 6 normalization entry points. <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code> was load-bearing in ~300 test assertions and ~100 production sites.</p>

<p>Removing <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code> was the most labour-intensive step. Every <code class="language-plaintext highlighter-rouge">assert inst.left == "%r0"</code> became <code class="language-plaintext highlighter-rouge">assert inst.left == Register("%r0")</code>. Every <code class="language-plaintext highlighter-rouge">frame.registers["%r0"]</code> became <code class="language-plaintext highlighter-rouge">frame.registers[Register("%r0")]</code>. The agent fixed 300+ sites across 46 test files in a single commit — a mechanical migration, but one that required understanding each comparison’s context to choose the right fix pattern (<code class="language-plaintext highlighter-rouge">.name</code> extraction vs <code class="language-plaintext highlighter-rouge">Register()</code> wrapping vs dict key normalisation).</p>

<p>The <code class="language-plaintext highlighter-rouge">IRInstruction</code> class itself was replaced with a factory function of the same name: callers keep the same <code class="language-plaintext highlighter-rouge">IRInstruction(opcode=Opcode.X, operands=[...])</code> interface, but the return value is now a typed <code class="language-plaintext highlighter-rouge">InstructionBase</code> subclass. This preserved backward compatibility for ~50 remaining construction sites (mostly in test helpers and COBOL <code class="language-plaintext highlighter-rouge">inline_ir</code>) while eliminating the class.</p>

<p>The remaining work — converting those ~50 construction sites to direct typed instruction construction and removing the factory — is tracked as a follow-up. The factory is a thin shim, not a compatibility bridge. The bridge is gone.</p>

<hr />

<h2 id="learnings">Learnings</h2>

<h3 id="on-type-hints-in-python">On Type Hints in Python</h3>

<p>I spent years writing Java, C#, C, C++, and Ruby before this project, and tried Scala and Haskell along the way. In the statically typed ones, the compiler catches the kind of errors that were invisible in this codebase for months: passing a variable name where a register was expected, comparing a label to None without narrowing, indexing into a bag of Any and hoping the position was right. Python’s dynamism made the rapid prototyping phase fast. Fifteen frontends, a VM, a type inference engine, an interprocedural analysis pipeline, all built in a few months. But the cost <em>accumulated silently</em>.</p>

<p>Turning on Pyright made that cost visible. The 83+ errors in the IR layer were not bugs in the running code. They were a <em>map of fragility</em>: every place where a wrong assumption would pass at runtime and corrupt data quietly. Fixing them properly required domain types, not just annotations. <code class="language-plaintext highlighter-rouge">str</code> with <code class="language-plaintext highlighter-rouge">""</code> as a sentinel became <code class="language-plaintext highlighter-rouge">Register</code> with a <code class="language-plaintext highlighter-rouge">NoRegister</code> null object. <code class="language-plaintext highlighter-rouge">str | None</code> became <code class="language-plaintext highlighter-rouge">CodeLabel</code> with <code class="language-plaintext highlighter-rouge">NoCodeLabel</code>. <code class="language-plaintext highlighter-rouge">operands: list[Any]</code> became 31 frozen dataclasses with named typed fields.</p>

<p>The investment was significant: 32 commits, 100 files, two days of migration. The type hint tightening is still a work in progress; 18 primitive <code class="language-plaintext highlighter-rouge">str</code> and <code class="language-plaintext highlighter-rouge">int</code> fields remain on the instruction classes, and the broader codebase has areas where annotations are loose or absent. But the return is already visible: Pyright now catches at the edit site what previously surfaced as a wrong value three layers deep in the VM. For a project of this size, built primarily through AI-assisted development where the AI generates most of the code, that static safety net is worth more than any number of runtime tests. <strong>Tests verify behaviour you thought to check. Types prevent mistakes you didn’t think to check for.</strong></p>

<h3 id="on-scope">On Scope</h3>

<p><strong>Scope is measured by the cascade, not the initial change.</strong> Changing <code class="language-plaintext highlighter-rouge">BasicBlock.label</code> from <code class="language-plaintext highlighter-rouge">str</code> to <code class="language-plaintext highlighter-rouge">CodeLabel</code> was 5 lines. That change cascaded into 40 files because the label was used as a dict key, a lookup value, a comparison target, and a format string argument across every architectural layer. I treated it as “lots of small changes” and attempted it in one session. The session was reverted. The same work, decomposed into four rings with separate issues and separate sessions, shipped cleanly.</p>

<p><strong>File issues for the next ring.</strong> The CodeLabel migration into <code class="language-plaintext highlighter-rouge">IRInstruction.label</code> was one commit. Propagation into <code class="language-plaintext highlighter-rouge">BasicBlock</code> and <code class="language-plaintext highlighter-rouge">cfg.blocks</code> was a separate issue. Propagation into <code class="language-plaintext highlighter-rouge">FuncRef.label</code> and <code class="language-plaintext highlighter-rouge">ClassRef.label</code> was a third. Each ring was bounded, independently committable, and went through the verification gate on its own.</p>

<pre><code class="language-mermaid">flowchart TD
    R0("Ring 0&lt;br/&gt;IRInstruction.label&lt;br/&gt;&lt;i&gt;CodeLabel / NoCodeLabel&lt;/i&gt;"):::ring0
    R1("Ring 1&lt;br/&gt;BasicBlock, CFG,&lt;br/&gt;StateUpdate, handlers"):::ring1
    R2("Ring 2&lt;br/&gt;FuncRef, ClassRef,&lt;br/&gt;FunctionEntry, InstructionLocation"):::ring2
    R3("Ring 3&lt;br/&gt;Remove _coerce_label,&lt;br/&gt;push wrapping upstream"):::ring3

    R0 -- "separate issue" --&gt; R1
    R1 -- "separate issue" --&gt; R2
    R2 -- "separate issue" --&gt; R3

    classDef ring0 fill:#e8f4fd,stroke:#4a90d9,stroke-width:3px,color:#1a3a5c
    classDef ring1 fill:#fff3e0,stroke:#e8a735,stroke-width:2px,color:#5c3a0a
    classDef ring2 fill:#fce4ec,stroke:#c62828,stroke-width:2px,color:#5c0a0a
    classDef ring3 fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#1a3a1a
</code></pre>

<p><strong>Classify complexity before starting, not after.</strong> The multi-file linker was obviously Heavy (500+ lines, new package, touched VM, registry, API, MCP). It was treated as a single unbroken implementation session. Breaking it into independently-committable units from the start would have produced cleaner history and caught issues earlier.</p>

<h3 id="on-type-migrations">On Type Migrations</h3>

<p><strong>Never auto-coerce during a migration.</strong> A Pydantic validator that auto-converted <code class="language-plaintext highlighter-rouge">str</code> to <code class="language-plaintext highlighter-rouge">CodeLabel</code> made all tests pass immediately. It also masked every call site that needed updating. A failing test at a call site is <em>information</em>: the caller hasn’t been migrated. Silencing it with auto-coercion destroys that information.</p>

<p><strong>Audit implicit protocol usages.</strong> Replacing <code class="language-plaintext highlighter-rouge">str</code> result registers with <code class="language-plaintext highlighter-rouge">Register</code> objects broke every <code class="language-plaintext highlighter-rouge">if inst.result_reg:</code> check because dataclass instances are always truthy in Python. When replacing a primitive with a domain type, audit <code class="language-plaintext highlighter-rouge">bool()</code>, <code class="language-plaintext highlighter-rouge">len()</code>, <code class="language-plaintext highlighter-rouge">in</code>, <code class="language-plaintext highlighter-rouge">[]</code>, comparison operators, and string formatting. Each one is a potential semantic break that passes silently.</p>

<p><strong>Edge cases cluster at boundaries.</strong> The four Layer 1 edge cases (COBOL literals in call operands, <code class="language-plaintext highlighter-rouge">_resolve_reg</code> fallback, <code class="language-plaintext highlighter-rouge">_is_temporary_register</code> subscripting, SpreadArguments in StoreIndex) all occurred where the type change met a convention or assumption from a different subsystem. The type change itself was mechanical. The <em>boundary interactions</em> were where the bugs lived.</p>

<p><strong>Stringly-typed representations accumulate hidden conventions.</strong> <code class="language-plaintext highlighter-rouge">BRANCH_IF</code> stored branch targets as a comma-separated string. This survived 10 months and 12,000+ tests. Three files independently implemented the same split logic. None of it was documented. Discovering it during a refactoring is how it was always going to be discovered.</p>

<h3 id="on-plans">On Plans</h3>

<p><strong>The end state was clear; the intermediate steps were not.</strong> The original four-phase plan correctly described the goal (typed instructions with Register fields, no IRInstruction). What it underestimated was the number of intermediate layers needed to get there safely. Operand-level register migration was a whole layer the plan didn’t account for. The plan had to be replaced mid-execution with a five-layer plan decomposed into 28 sub-issues. Getting the destination right is the easy part. Mapping the route, with each step <em>independently committable and testable</em>, is where the planning effort belongs.</p>

<p><strong>Round-trip tests verify consistency, not completeness.</strong> <code class="language-plaintext highlighter-rouge">LoadRegion</code> was defined with 3 fields. The actual instruction had 4 operands. The round-trip test passed perfectly because a 3-field class round-trips correctly to a 3-operand instruction. The bug was that the real instruction has 4 operands. Verification should cross-reference against the authoritative source (the handler, the IR spec), not just test internal consistency.</p>

<p><strong>Start with an audit, not implementation.</strong> The Superpowers session started by surveying every <code class="language-plaintext highlighter-rouge">to_typed()</code> call, every <code class="language-plaintext highlighter-rouge">inst.operands[</code> access, every <code class="language-plaintext highlighter-rouge">opcode==</code> comparison, every <code class="language-plaintext highlighter-rouge">IRInstruction(</code> construction. This took 10 minutes and revealed that the design doc’s estimates were wrong in both directions: handlers had 0 <code class="language-plaintext highlighter-rouge">to_typed()</code> calls (not 72), COBOL <code class="language-plaintext highlighter-rouge">ir_encoders.py</code> had 106 constructions (not counted at all). The upfront survey saved hours of mid-implementation replanning.</p>

<h3 id="on-tooling">On Tooling</h3>

<p><strong>Start with the verification gate from day one.</strong> The <code class="language-plaintext highlighter-rouge">.importlinter</code> failure was avoidable. Having “run black” and “run tests” as separate loose rules instead of a single named gate made it easy to skip lint-imports entirely.</p>

<p><strong>Enforce brainstorm-before-implement from session one.</strong> The linker patch-on-patch problem cost more time than the proper rewrite. A brainstorm phase that reads actual code, not just designs on paper, would have caught the VM dispatch mismatch immediately.</p>

<p><strong>File issues before work, not after.</strong> Retroactive issue filing loses the intent: why was this work started? What was the expected outcome? Issues filed before work serve as specifications. Issues filed after are bookkeeping.</p>

<hr />

<h2 id="takeaways">Takeaways</h2>

<p><strong>The GSD 2 patterns held up as guardrails.</strong> Five workflow patterns adopted from GSD 2, then tested against the largest refactoring in the project:</p>

<table>
  <thead>
    <tr>
      <th>Pattern</th>
      <th>What It Solved</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Enforced phases</td>
      <td>Skipped brainstorm → wrong design → patch-on-patch</td>
    </tr>
    <tr>
      <td>Complexity classification</td>
      <td>Heavy work attempted as single pass → messy history</td>
    </tr>
    <tr>
      <td>Verification gate</td>
      <td>Scattered “run X” rules → missed lint-imports</td>
    </tr>
    <tr>
      <td>Fresh context for heavy tasks</td>
      <td>Design document anchoring → flawed assumptions carried into implementation</td>
    </tr>
    <tr>
      <td>State on disk</td>
      <td>Missing backups → lost issue state on session crash</td>
    </tr>
  </tbody>
</table>

<p><strong>Superpowers added what GSD v2 lacked.</strong> GSD v2 gave me process discipline. Superpowers gave me decision discipline and orchestration:</p>

<table>
  <thead>
    <tr>
      <th>Capability</th>
      <th>GSD v2 (CLAUDE.md rules)</th>
      <th>Superpowers (plugin)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Brainstorming</td>
      <td>“brainstorm first” rule, often skipped</td>
      <td>Structured gate: one question at a time, options, recommendations</td>
    </tr>
    <tr>
      <td>Decomposition</td>
      <td>Manual, done by me before the session</td>
      <td>Agent proposes, I choose: “one per frontend” vs “grouped by family”</td>
    </tr>
    <tr>
      <td>Review</td>
      <td>Self-review checklist</td>
      <td>Two-stage: spec compliance reviewer + code quality reviewer (separate agents)</td>
    </tr>
    <tr>
      <td>Discovered work</td>
      <td>Noted in commit messages, often lost</td>
      <td>Filed as issues with dependency links to the epic</td>
    </tr>
    <tr>
      <td>Plan revision</td>
      <td>Manual, often deferred</td>
      <td>Agent resurveys after each layer, rewrites estimates, updates dependency graph</td>
    </tr>
    <tr>
      <td>Consultation</td>
      <td>“stop and consult” rule, inconsistently followed</td>
      <td>Natural pause points at each brainstorming question and review finding</td>
    </tr>
  </tbody>
</table>

<p>The distinction matters. GSD v2 tells the agent <em>what to do</em> (brainstorm, then plan, then implement). Superpowers tells the agent <em>when to stop and ask</em> (is this the right decomposition? did the spec reviewer approve? should this discovered issue block the epic?). For a refactoring that took 32 commits across 100 files, the stopping points were where the real decisions happened.</p>

<p><strong>They serve different sweet spots.</strong> I would still reach for GSD v2 for greenfield work of moderate complexity where I want to move fast: adding a new frontend, building a new analysis pass, scaffolding a new module. GSD v2’s autonomous dispatch is an advantage when the work is well-understood and doesn’t require mid-stream design decisions. For Heavy refactoring work that crosses architectural boundaries and accumulates edge cases, Superpowers’ consultation model is the better fit.</p>

<p><strong>The patterns are tool-agnostic.</strong> They work whether you’re using GSD 2, Superpowers, Cursor, or any other AI coding assistant. The common thread is treating AI-assisted development as an engineering practice that needs the same discipline as human development: phase gates, complexity awareness, verification, and persistent state.</p>

<table>
  <thead>
    <tr>
      <th>Moment in the refactoring</th>
      <th>Ad-hoc (before either framework)</th>
      <th>With GSD v2 patterns</th>
      <th>With Superpowers</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Linker design was wrong</td>
      <td>5 patches before realising</td>
      <td>Would have stopped at patch 2 (“stop and consult” rule)</td>
      <td>Would not have started: brainstorming gate asks “have you read the VM dispatch code?”</td>
    </tr>
    <tr>
      <td>Layer 4 decomposition (17 frontends)</td>
      <td>One long session, hoping for the best</td>
      <td>Classified as Heavy, broken into units manually</td>
      <td>Agent proposed 3 options (per-frontend, by size tier, by family), I picked one</td>
    </tr>
    <tr>
      <td>COBOL literal operands discovered during Layer 1</td>
      <td>Noted in commit message, forgotten</td>
      <td>Filed as issue retroactively after I noticed</td>
      <td>Agent asked “are there issues filed for follow-up work?”, filed 4 issues with dependency links</td>
    </tr>
    <tr>
      <td>Layer 3 site counts were wrong (~40 estimated, 128 actual)</td>
      <td>Discovered mid-implementation, improvised</td>
      <td>Discovered mid-implementation, adjusted manually</td>
      <td>Discovered by upfront audit before implementation started</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">types.UnionType</code> vs <code class="language-plaintext highlighter-rouge">typing.Union</code> bug in <code class="language-plaintext highlighter-rouge">map_registers</code></td>
      <td>Would have surfaced as a runtime crash in Layer 3</td>
      <td>Self-review checklist might have caught it</td>
      <td>Code quality reviewer (separate agent) caught it during plan review</td>
    </tr>
    <tr>
      <td>Removing <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code> (300+ sites)</td>
      <td>Would not have attempted incrementally</td>
      <td>Would have attempted, likely stalled on scope</td>
      <td>Agent fixed 300+ sites in one pass, choosing the right fix pattern per site</td>
    </tr>
  </tbody>
</table>

<p><strong>Compatibility bridges make incremental migration possible.</strong> <code class="language-plaintext highlighter-rouge">Register.__eq__(str)</code> was a deliberate compatibility bridge: it made <code class="language-plaintext highlighter-rouge">Register</code> compare equal to raw strings, letting 12,924 tests pass without modification during the migration. The plan explicitly called for removing it in Layer 5, after all consumers had been updated. Without the bridge, every layer would have been a big-bang change.</p>

<p><strong>Reverts are progress.</strong> The abandoned CodeLabel cascade, attempted, reverted, and documented in the Beads issue, was not wasted time. It produced the scope analysis that made the ring-by-ring approach possible.</p>

<p><strong>The plan will be wrong. Plan for that.</strong> The four-phase plan became a five-layer plan with 28 sub-issues. The CodeLabel single-pass attempt became a four-ring incremental approach. In both cases, the revised plan was better than the original, not because planning was futile, but because the first attempt revealed the <em>real shape of the work</em>.</p>

<p><strong>Write down your refactoring principles before the next refactoring.</strong> The “Refactoring Principles” section of CLAUDE.md, written after the CodeLabel experience, prevented at least three of the same mistakes during the Register migration. Rules extracted from failures and codified before the next attempt compound over time.</p>

<p><strong>The AI writes the code. You manage the scope.</strong> Across this entire migration, the AI’s code was overwhelmingly correct at the mechanical level: updating 31 fields, threading kwargs, updating converters, formatting with Black. Where it failed was scope: generating a class without checking the handler spec, proposing coercion validators that masked call sites, not flagging that operand fields needed their own migration layer. The human’s job in a type migration is not typing. It’s asking <em>“what does this cascade into?”</em> at every step.</p>

<p>The AI writes code faster than I can. It doesn’t write <em>better</em> code without guardrails.</p>]]></content><author><name>avishek</name></author><category term="Software Engineering" /><category term="AI-Assisted Development" /><category term="Developer Tooling" /><category term="Workflow" /><category term="Refactoring" /><category term="Compilers" /><category term="Type Safety" /><summary type="html"><![CDATA[Two agentic development frameworks applied to the same multi-layer type migration across a 13,000-test compiler pipeline. The first provided process discipline but stalled partway through. The second completed the work because it planned more thoroughly and stopped to ask.]]></summary></entry></feed>