<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Lehmann on Medium]]></title>
        <description><![CDATA[Stories by Michael Lehmann on Medium]]></description>
        <link>https://medium.com/@lehmann314159?source=rss-910e6b8fbdeb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*p1Bzv2ZNGy9tWDat54NZ8Q.jpeg</url>
            <title>Stories by Michael Lehmann on Medium</title>
            <link>https://medium.com/@lehmann314159?source=rss-910e6b8fbdeb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:27:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lehmann314159/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Working Model -> MCP -> API System]]></title>
            <link>https://medium.com/@lehmann314159/a-working-model-mcp-api-system-2066287d4794?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2066287d4794</guid>
            <category><![CDATA[ai-testing]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 00:36:22 GMT</pubDate>
            <atom:updated>2026-10-26T13:32:27.734Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This copy is formatted for Medium: tables are lists, diagrams and code samples are described in text, and sub-headings are bold lines. The repository has the original, with tables: </em><a href="https://github.com/lehmann314159/PuzzleBoxApp"><em>https://github.com/lehmann314159/PuzzleBoxApp</em></a><em>. File paths in the text refer to that repository.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tET7A6O7p4kuaXQAyZKtzA.png" /></figure><h3><strong>Introduction</strong></h3><p>This is a tour of the MCP side of a small Go application, written for the revision of the spec dated 2026–07–28. The application is about 3,000 lines of Go without tests, plus a 650-line web page. The MCP server itself is about 450 of those lines ( internal/mcp). The rest is the puzzle ( internal/box, about 780), a REST API (265), storage (165), wiring (90) and the chat and agent clients (about 1,250). It is meant for someone who has used MCP through a client and now wants to know what a server actually does. Everything here is about this code. Where a claim is about the protocol, it says which part of the spec it comes from and whether it was checked. docs/verify.sh runs the behavioural claims against real servers (28 checks, a few seconds once built).</p><p>Spec pages used, all read on 2026–10–25: the <a href="https://modelcontextprotocol.io/specification/2026-07-28/changelog">changelog</a>, <a href="https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http.md">Streamable HTTP</a> and <a href="https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr.md">multi round-trip requests</a>.</p><p>Two clients have been used against it: this repo’s own (the agent pane, Autopilot and manual caller) and Claude Code, which connected to the deployed server, called its tools and completed the confirmation round trip in section 5. Its traffic row shows client name claude-code, protocol 2026-07-28 and an Mcp-Param-BoxId header on a call that carries a box_id.</p><h3>Try It</h3><ul><li><strong>The code:</strong> <a href="https://github.com/lehmann314159/PuzzleBoxApp.">https://github.com/lehmann314159/PuzzleBoxApp.</a> The README explains how to run it locally. docs/verify.shchecks this paper&#39;s behavioural claims against servers it starts itself.</li><li><strong>A running copy:</strong> <a href="https://puzzlebox.verynormalserver.com/?t=1ab6d2f37822aa58bd28dd88e287905e36d574c428ed99e9">https://puzzlebox.verynormalserver.com/?t=1ab6d2f37822aa58bd28dd88e287905e36d574c428ed99e9</a>. It is a brass box on a table, a click menu for each part, a chat that can operate the box, and a panel showing every request as it goes over the wire. Tick “follow latest” to see traffic from other clients, such as Claude Code.</li></ul><p>The running copy is a home server with one shared GPU, and it may be offline. The chat uses that GPU, so please keep long runs of Autopilot or chat to a minimum. The link carries a shared access token; if it is misused, the token will be changed and the link will stop working.</p><p>The MCP endpoint of the running copy needs a bearer token that is not published here. To connect an MCP client, run your own copy ( go run ./cmd/server; without MCP_BEARER set, /mcp needs no token) and add it with claude mcp add --transport http puzzlebox <a href="http://127.0.0.1:9100/mcp.">http://127.0.0.1:9100/mcp.</a></p><h3>The pieces fit together like this:</h3><pre>                        +-------------------+<br> browser page  ---REST---&gt;  internal/api    |<br> (box + traffic)        |                   |<br>                        |   box.Service     |---&gt; store (SQLite: boxes, trace)<br> any MCP client --/mcp--&gt;  internal/mcp    |<br>                        |                   |<br> agent pane / Autopilot / manual  --/mcp---&gt;|   (the app&#39;s own clients call<br>                        +-------------------+.  its own /mcp)</pre><ul><li>The browser page talks REST to internal/api. It draws the box, runs the click menus and shows the traffic.</li><li>Any MCP client talks to /mcp, which is internal/mcp.</li><li>The agent pane, Autopilot and the manual caller are also MCP clients: they call this server’s own /mcp.</li><li>internal/api and internal/mcp both call box.Service, which reads and writes the store (SQLite: the boxes and the trace).</li></ul><p><strong>The packages:</strong></p><ul><li>internal/box is the domain: what a box is, what each part does, what the sounds mean. It knows nothing about HTTP or MCP. Its public face isbox.Service with four operations, Open, Examine, Query, Act (internal/box/service.go).</li><li>internal/api is a REST adapter over Service. The page uses it to draw the box and to run the click menus.</li><li>internal/mcp is an MCP adapter over the same Service. Each tool is a few lines that unpack arguments, call the service and wrap the answer (internal/mcp/call.go).</li><li>internal/agent contains three clients (a scripted solver, a manual tool caller and a model loop). <strong>All three call this server&#39;s own </strong><strong>/mcp over HTTP</strong>, with a client name each (agent-pane, autopilot, manual). That is deliberate: every step they take goes through the same door an outside client uses, so the traffic panel shows it exactly as it would show yours.</li></ul><p>Most of the code is not MCP. The MCP adapter is about 450 lines, and most of those are protocol housekeeping (headers, versions, the pause-and-resume for confirmation). The behaviour a model sees, such as what examine returns and what an error says, lives in the domain and is shared with the REST API.</p><h3>One Request, On the Wire</h3><p>There is no handshake and no session. Every request carries what the server needs. This is open_box as this server sees it (real, captured from a local run; the_meta keys are the ones the 2026-07-28 changelog names):</p><p>The request:</p><pre>POST /mcp<br>MCP-Protocol-Version: 2026-07-28<br>Mcp-Method: tools/call<br>Mcp-Name: open_box<br><br>{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:2,&quot;method&quot;:&quot;tools/call&quot;,&quot;params&quot;:{<br>  &quot;name&quot;:&quot;open_box&quot;,&quot;arguments&quot;:{&quot;seed&quot;:&quot;doc&quot;},<br>  &quot;_meta&quot;:{&quot;io.modelcontextprotocol/protocolVersion&quot;:&quot;2026-07-28&quot;,<br>           &quot;io.modelcontextprotocol/clientCapabilities&quot;:{}}}}</pre><p>The response:</p><pre>200 OK<br>{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:2,&quot;result&quot;:{<br>  &quot;resultType&quot;:&quot;complete&quot;,<br>  &quot;content&quot;:[{&quot;type&quot;:&quot;text&quot;,&quot;text&quot;:&quot;A brass box is on the table: box_139d544b82. It is silent.&quot;}],<br>  &quot;structuredContent&quot;:{&quot;box_id&quot;:&quot;box_139d544b82&quot;},<br>  &quot;isError&quot;:false,<br>  &quot;_meta&quot;:{&quot;io.modelcontextprotocol/serverInfo&quot;:{&quot;name&quot;:&quot;puzzlebox&quot;,&quot;version&quot;:&quot;1.0.0&quot;,&quot;instance&quot;:&quot;go1&quot;}}}}</pre><p>What to notice, with the code that does it ( internal/mcp/mcp.go unless stated):</p><ul><li><strong>The server never initializes anything.</strong> There is no initialize on the modern path: sending one gets a 404 andMethod not found: initialize is not part of 2026-07-28 (dispatch). A client can call server/discover first, which returns supported versions, capabilities, instructions and a cache hint, but nothing requires it.<em>Verified by script; matches the changelog items &quot;remove the initialize/notifications/initialized handshake&quot; and &quot;servers MUST implement server/discover&quot;.</em></li><li><strong>Version and capabilities travel in </strong><strong>_meta</strong> and are mirrored into the MCP-Protocol-Version header. The server reads the client&#39;s capabilities from this request, not from a stored session (handle: caps comes from meta).</li><li><strong>Every result says </strong><strong>resultType.</strong> complete for an ordinary answer and input_required for a paused one (section 5).<em>Matches changelog item 8.</em></li><li><strong>List results say how long they stay good.</strong> tools/list returns ttlMs: 300000 and cacheScope: &quot;public&quot;;server/discover returns ttlMs: 3600000. <em>Matches changelog minor change 5, &quot;Require ttlMs and cacheScope&quot;.</em></li><li><strong>Notifications get </strong><strong>202 and no body; </strong><strong>GET /mcp gets </strong><strong>405</strong> with Allow: POST; an Mcp-Session-Id header is never read.<em>Matches the transport page (&quot;respond with 405 Method Not Allowed&quot;, &quot;ignore it, and do not mint or echo session IDs&quot;).</em></li><li><strong>The transport headers must agree with the body.</strong> Mcp-Method must equal the body&#39;s method; Mcp-Name must equalparams.name; the version header must equal _meta. A mismatch is 400 with JSON-RPC error -32020 (validateModern). The reason the spec gives, and the reason it matters here, is that a gateway can route or block on a header while the server acts on the body, and the two must not be able to disagree.<em>Verified; code </em><em>-32020 and status</em><em>400 match the transport page.</em></li><li><strong>Origin and bearer checks come first</strong> (post): a foreign Origin gets 403; with MCP_BEARER set, a missing or wrong token gets401 with WWW-Authenticate: Bearer. A request with no Origin header is accepted. <em>The spec requires a 403 for a present, invalid </em><em>Origin; verified.</em></li></ul><h3>Four Tools, One of Which Is Generic</h3><p>Just to be clear, I think the usage of the generic “act” tool call is an anti-pattern. I included it here to get a sense of how to account for it, but strongly suggest avoiding its use, as I think the testing section shows.</p><p>internal/mcp/tools.go defines open_box, examine, query and act. Nothing in the names says puzzle, lid or combination:</p><ul><li><strong>open_box(seed?, reset?)</strong>: Put a box on the table, get a box_id handle (creates).</li><li><strong>examine(box_id, path)</strong>: What is at this path, what it contains, which verbs it accepts (reads).</li><li><strong>query(box_id, select)</strong>: Many reads at once, GraphQL-shaped: { lid { open } dials { position } }; { __fields } lists what exists (reads).</li><li><strong>act(box_id, target, verb, args?)</strong>: Do something to a part (changes).</li></ul><p><strong>Notes on the design:</strong></p><ul><li><strong>The descriptions are the interface a model reads.</strong> The model never sees the Go code, only the tool descriptions, the schema, and what comes back. Everything it learns about the box it learns by calling examine. The verbs for each part (turn, listen, release, open, force, pull, speak) are returned as data in the actions field of examine, not written in the tool descriptions.</li><li><strong>box_id is annotated </strong><strong>&quot;x-mcp-header&quot;: &quot;BoxId&quot;.</strong> The spec lets a server say that a tool argument should also appear as a header named Mcp-Param-{name}, so that a gateway can route on it without parsing the body. validateModern checks it matches when present. See section 7, deviation 1.</li><li><strong>Results carry both text and structure.</strong> content holds the sentence a model reads; structuredContent holds the fields a program wants (box_id, moves). The text is written for the model: &quot;Turn it how? Give {to: 0-9} or {by: integer}.&quot;</li></ul><h3><strong>Why </strong><strong>act is generic, and what that costs</strong></h3><p>act(box_id, target, verb, args?) is one tool for every change: turning a dial, releasing the latch, lifting the lid, pulling the drawer, speaking a word, forcing the lid. That was a choice, made so the box would behave like a service the model has not been told about. The model has to ask what each part accepts, as it would with an API nobody documented. It also makes a good place to look at a tension that real servers face, because the alternative is easy to picture: turn_dial, release_latch, open_lid, force_lid, pull_drawer and speak.</p><ul><li><strong>Tool list<br></strong>Generic act: Four tools, unchanged when the box gains a part.<br>Per-verb tools: Grows with the service; every change is a new tool.</li><li><strong>What the model knows before it acts.<br></strong>Generic act: Almost nothing; it must call examine first.<br>Per-verb tools: The schema says what each tool takes.</li><li><strong>Argument checking.<br></strong>Generic act: At runtime, by the server, in prose.<br>Per-verb tools: By the schema, before the call.</li><li><strong>Describing risk.<br></strong>Generic act: One annotation for everything act can do.<br>Per-verb tools: One annotation per tool.</li><li><strong>Policy by tool name.<br></strong>Generic act: All changes or none.<br>Per-verb tools: Per action.</li><li><strong>Discovery.<br></strong>Generic act: Part of the interface.<br>Per-verb tools: Replaced by the tool list.</li></ul><p><strong>What the generic shape cost in this app:</strong></p><ul><li><strong>Argument errors, found only at runtime.</strong> The schema for act says args is an object. It cannot say that turn on a dial needs to, an integer from 0 to 9. The README&#39;s prompt table records the first dial call wrong in 0 of 8 runs for gemma4:12b, with most runs recovering from the box&#39;s error message. A turn_dial tool with a required to would have made that class of failure impossible, not just recoverable.</li><li><strong>Risk that cannot be described truthfully.</strong> act is annotated destructiveHint: false, and it can also force the lid. An annotation on a tool is one claim about everything the tool can do, so for act no value is correct. A client that decides whether to ask a person from the annotation sees a harmless tool. Here the server&#39;s own confirmation (section 5) covers force, which is why the gap did no harm, but the annotation still misdescribes it.</li><li><strong>Policy at the wrong grain.</strong> A gateway can allow or block a call using only the Mcp-Name header (section 2). With a generic act it can block every change or none. To block only force it would have to read the body, which is what the headers were meant to avoid. A separate force_lid tool could be blocked on its own. The same grain applies on the client side. Claude Code&#39;s permission rules for an MCP tool name either a whole server (mcp__puzzlebox) or one tool (mcp__puzzlebox__act), and its documentation says a settings-file rule for an MCP tool cannot carry a parameter: such a rule is skipped, and matching on a parameter is possible only for a deny rule passed on the command line. So a standing approval for act covers force as well, and a settings file cannot say &quot;allow act but not with verb force&quot;. (Source: Claude Code&#39;s permissions page, read 2026-10-25. The page does not say what the &quot;don&#39;t ask again&quot; option stores for an MCP call, and it does not mention tool annotations such as destructiveHint, so how a client weighs the annotation is not established here.) In our test the server&#39;s own confirmation fired for force anyway, which is the control that does not depend on the client&#39;s settings.</li><li><strong>A defect class that only exists because of the shape.</strong> An early negative test found a defect in this server: a call with no verb returned an unhelpful message and still cost a move. verb is a free string, so omitting it is possible. With one tool per verb there is no verb to omit. The fix (ValidateArgs, in Service.Act) is a runtime check standing in for what a schema would have done.</li></ul><p><strong>What it means for QA.</strong> The tension is most visible when you test. With specific tools, a lot of the checking moves into the schema and is done before the server sees the call; what is left to test is mostly behaviour. With a generic tool, the schema accepts nearly anything, so correctness of the <em>arguments</em> becomes something to test, and the subject of the test is partly the model. The prompt table in the README exists for this reason: it checks that a prompt led to the right tool, and also to the right target, verb and arguments, and it reports a pass rate because the model is not deterministic. The error messages become part of the interface and need tests of their own; the ones in the next subsection are checked by docs/verify.sh. The generic shape also makes the tool descriptions carry more weight: a sentence added to one moved results in the live table (see the 2026-10-25 regression in section 6). A server with specific tools would have fewer of these failure modes to test, and more tools to describe well.</p><p><strong>A middle path for this case.</strong> Keep the reads generic ( examine and query are already read-only and annotated as such), and split changes by risk: act for ordinary moves and a separate tool for the one destructive move. The model keeps discovery for the common case. Annotations, policy and permission prompts get something accurate to work with for the dangerous case. Whether that is worth the extra tool depends on how much the server cares about those three, and this demo cares more about the discovery.</p><p>This is a comparison from one small app, not a rule. The point is that “mixed specific and generic tools” is a position on a tradeoff, and the costs above are what the position cost here.</p><p><strong>Three kinds of “no”</strong></p><p>This distinction affects how well a model recovers from its own mistakes.</p><ul><li><strong>The box’s story says no.</strong> How the server says it: A normal result, isError: false, text in the story&#39;s voice. Example: The latch holds. The wheels inside are not aligned. Listen at the grille to hear how close each one is..</li><li><strong>The caller misused the interface.</strong> How the server says it: A normal result with isError: true, and text that says what to do instead. Example: act needs a verb. Use examine on &#39;lid&#39; to see which verbs it accepts.; nothing at &#39;box.nothing&#39;. Here you can see: ...; There is no box &#39;box_0000000000&#39; on the table. Use open_box to get one..</li><li><strong>The request is not valid MCP.</strong> How the server says it: A JSON-RPC error, no tool result. Example: unknown tool: code -32602, HTTP 200; header mismatch: code -32020, HTTP 400; unknown method on the modern path: code -32601, HTTP 404.</li></ul><p>The first two are both results a model receives, and a model can read them. The third kind is a protocol-level failure, and a model is, in general, less likely to recover from one of those than from a readable result (a common observation; this project did not measure it). Putting misuse in the second row and listing the valid choices in the text keeps the model in the conversation. <em>Verified by script, including that the “story says no” case is </em><em>isError: false and an unknown tool is a JSON-RPC error.</em></p><p>One check on “costs nothing”: a call with no verb is rejected before the box is touched and does not use a move ( Service.Act, ValidateArgs). A dial turn with the wrong arguments does use a move ( Apply increments moves first). That is a known roughness, found by a tester who saw the counter rise after failed calls.</p><h3>State: a Handle, Not a Session</h3><p>The 2026–07–28 changelog says it directly: “Servers that need cross-call state use explicit, server-minted handles passed as ordinary tool arguments.” That is how this server works.</p><ul><li><strong>box_id is the whole state.</strong> open_box makes one. BoxID(seed) is box_ plus the first ten hex characters of SHA-256 of the seed, so a given seed always gives the same handle; with no seed, four random bytes are used.</li><li><strong>State is in SQLite, keyed by that handle</strong> (internal/store/store.go): a boxes table of JSON documents and a trace table of every request. Nothing about a box lives in the process.</li><li><strong>Writes are atomic.</strong> Store.Update loads, mutates and saves inside one transaction, and the connection string sets_txlock=immediate, so two requests that change the same box queue up instead of overwriting each other.</li><li><strong>So any instance can serve any request.</strong> The script starts two servers on one database file and shows that a paused request begun on one is finished on the other (section 5). Nothing in the protocol layer would have to change to put a load balancer in front of several copies. <em>Verified by script with two instances sharing a database and a secret.</em></li><li><strong>The puzzle’s answer is derived, not stored separately.</strong> Secrets(seed) computes the combination, the star count and the word from the seed with a seeded generator, so the same seed always gives the same box. The seed itself sits in the stored state, and the page&#39;s &quot;reveal secrets&quot; box shows the derived values. So &quot;the answer is written down nowhere the model can read&quot; is true of what the tools return, not of the database. With a random seed, which is four bytes, the answer is also not strong against someone who has the handle and time. This is a demo, not a vault.</li></ul><h3>A Human in the Loop: Multi Round-trip Requests</h3><p>act with verb force on the lid is the risky move. It damages the box and costs extra moves, so it needs a person&#39;s yes. This is where MCP&#39;s 2026-07-28 shape is most visibly different from earlier revisions, and internal/mcp/call.go ( act) is the whole implementation.</p><pre>client  --&gt; tools/call act {lid, force}<br>server  &lt;-- resultType: &quot;input_required&quot;<br>            inputRequests: { confirm_force: { method: &quot;elicitation/create&quot;,<br>                              params: { mode: &quot;form&quot;, message: &quot;Forcing the lid may damage the box ... Do it anyway?&quot;,<br>                                        requestedSchema: { proceed: boolean } } } }<br>            requestState: &quot;&lt;opaque token&gt;&quot;<br>            (the server has forgotten the request; nothing is waiting)<br>client  asks the person, then:<br>client  --&gt; tools/call act {lid, force}   (the original call again, plus:)<br>            inputResponses: { confirm_force: { action: &quot;accept&quot;, content: { proceed: true } } }<br>            requestState: &quot;&lt;the same token, unchanged&gt;&quot;<br>server  &lt;-- the lid shudders ... (an ordinary result)</pre><ul><li><strong>No connection is held open and the server remembers nothing.</strong> In earlier revisions a server asked the client a question over a stream and waited. Here the question is the <em>answer</em> to the first call, and the client re-sends the original call with the reply attached. <em>Matches changelog item 7.</em></li><li><strong>requestState is how the server remembers anyway.</strong> It is a token the server mints and the client carries back. Here it is base64 of {box, target, verb, expiry}, a dot, and an HMAC-SHA256 over it (internal/mcp/seal.go). The secret is BOX_SECRET. Anything forged, tampered with, expired (five minutes), or issued for a different box, target or verb is refused with &quot;That confirmation expired or does not belong to this request.&quot; <em>Verified: a state minted by one instance is accepted by a second that shares the secret, and refused by a third with a different secret; a tampered token and a token for another box are both refused.</em> The server is stateless in the sense that matters: any instance with the secret can finish the request. The token&#39;s contents are readable (it is signed, not encrypted), so it must not carry anything secret.</li><li><strong>The client must be able to ask.</strong> The server looks at the client capabilities in the same request. A client that declareselicitation gets the question. A client that does not is told, in text, Forcing the lid needs confirmation, and this client cannot ask. Retry with args {confirm: true} if you really mean it.Only such a client may confirm by passing confirm: true. A client that can ask is never allowed to skip the question that way. <em>Verified in both directions.</em> Before the check existed, a model could pass confirm: true itself and walk through the gate meant for a human.</li><li><strong>A second client did it too.</strong> Claude Code, against the deployed server, received input_required, put the question to its user, and retried act with inputResponses: {confirm_force: {action: &quot;accept&quot;, content: {proceed: true}}}and the requestState unchanged. The model behind Claude Code never saw the round trip; from its side the call simply returned the lid&#39;s answer. A model that is not told this may conclude, wrongly, that the box had no gate.</li><li><strong>The agent pane asks a real person.</strong> Manager.callTool in internal/agent/manager.go turns an input_requiredresult into a prompt on the page, then retries with the person&#39;s accept or decline and the state copied unchanged, up to three rounds. The REST API has the same gate in simpler form: 409 with needs_confirmation, and the page asks.</li></ul><p><strong>Compared with the spec’s MRTR page.</strong> The input_required result ( resultType, inputRequests keyed by a server-chosen name, an elicitation/create entry with mode, message and requestedSchema, and requestState), the client&#39;s inputResponses ( action and content) and the rule that the client echoes requestState unchanged all match the page. So does the rule that a server must not ask for elicitation from a client that has not declared it, and that requestState must be integrity protected and treated as attacker-controlled. Two things the page says a server <em>should</em> do are not done here:</p><ul><li><strong>No principal in the state.</strong> The page suggests binding requestState to the authenticated principal. This server has one shared bearer token and no notion of who is calling, so there is nothing to bind to. The state is bound to the box, target and verb, and expires after five minutes. (The page suggests a digest of the request&#39;s salient parameters; the box, target and verb stand in for that.)</li><li><strong>The state is not single-use.</strong> The same token can be presented again within its five minutes and will force the lid again, without a new answer from the person. The page notes that these measures do not give single use and that a server that needs it must enforce it. For a demo box the cost is extra damage to a lid. A server that redeems something once would need a server-side record, and that record is the shared state MRTR was designed to avoid.<em>Verified by script.</em></li></ul><h3>The Model in the Loop</h3><p>The chat pane shows a different set of problems. A server can be correct and still have a poor conversation with a model. The README has the detailed findings (a table of what a 12B model got wrong and what the code does about each), and docs/TESTING.md turns them into principles and a procedure; the short version, for someone who writes servers:</p><ul><li><strong>Be strict on the server and forgiving in the client.</strong> Small models send an object argument as a JSON string (&quot;{\&quot;to\&quot;: 4}&quot;). The server rejects it and stays strict, because relaxing the server would hide a real bug from every other client. The agent repairs it before the call (asObjects, internal/agent/agent.go).</li><li><strong>Guard intent in the client, not in the prompt.</strong> The model once followed “Turn dial A to 4” by also turning dial B. A move that changes the box is now allowed only on a part the user’s message names (intentOf and refusal,internal/agent/intent.go); anything else comes back as &quot;You were not asked to change the dial B.&quot; This is cheaper and more reliable than asking the model to behave.</li><li><strong>Write errors for a reader that has to recover.</strong> “act needs a verb. Use examine on ‘lid’ to see which verbs it accepts” gets a model back on track; “Nothing happens” does not.</li><li><strong>Prompt wording is fragile for weaker models and the only test of it is the model itself.</strong> On 2026–10–25 a block of sentences added to the system prompt (to stop the model saying it had done things it had only examined) took three rows of the live prompt table from 5/5 to 0/5 against gemma4:12b; go test passed throughout, because it never calls the model. The block was reverted and the table returned to 55/55 (commits 627b1c9 and e1bb5ba). Run the table before changing a prompt or a tool description.</li><li><strong>Show the evidence next to the chat.</strong> The traffic panel shows every call the chat made, with arguments and results. In a first-time-visitor test, a tester caught the chat saying “I have now opened the lid” after it had only examined it, because the traffic and the status chips disagreed. The trace let the tester check the model’s claims against what had actually run.</li></ul><h3>What is Not in This Server, and Where it Departs From the Spec</h3><p>This server implements the parts of the 2026–07–28 spec that its four tools need. What follows is what it leaves out or does differently.</p><ol><li><strong>Mcp-Param-BoxId is required, as the spec says.</strong> The spec says a server MUST reject a request that omits a recognisedMcp-Param-* header whose value is in the body. This server rejected a <em>wrong</em> value from the start but, until 2026-10-25, accepted a <em>missing</em> header by default. Both clients tried send the header (Claude Code&#39;s traffic row shows Mcp-Param-Boxid, and this repo&#39;s own client sets it on every call), so the default is now strict. Setting STRICT_PARAM_HEADERS=0 restores the lenient behaviour for a client that does not mirror headers. <em>Verified by script, including the escape hatch, and by running Autopilot end to end against a server with the default configuration (solved in 18 moves).</em></li><li><strong>Base64-encoded header values are not decoded.</strong> The spec defines an =?base64?...?= form for header values that are not plain ASCII. This server compares header values literally. It does not matter for box_id (always box_ and hex) or the tool names here, but a server with other names would need it.</li><li><strong>No </strong><strong>subscriptions/listen.</strong> The server declares only tools with no listChanged, so it promises no change notifications and the tool list never changes. A server whose tools change would need the stream.</li><li><strong>No </strong><strong>MissingRequiredClientCapability error.</strong> When a client cannot elicit, the server returns a normal result that tells the model how to proceed. That was chosen so the model can read it and act; a client that wants the typed error will not find it.</li><li><strong>ping is not available on the modern path</strong> (answer: 404 Method not found), which matches the changelog&#39;s removal ofping. It still works for legacy clients.</li><li><strong>Error codes</strong> -32000 (bad Origin) and -32001 (bearer) are in the range the spec leaves to implementations. -32020, -32022 and -32601 follow the spec.</li><li><strong>Tools only.</strong> No resources, prompts, sampling, roots or tasks. The server needs none of them, so these are untested here.</li><li><strong>Clients tried:</strong> this repo’s own client and Claude Code. Claude desktop’s custom connector form has no field for a header, so it cannot send the static bearer token this server requires; it was not tried. Hosting behind a path-prefix proxy was not tested.</li></ol><h3>Reproducing and Extending This</h3><ul><li>bash docs/verify.sh builds the server, starts five instances on ports 9291-9295 with temporary databases and runs 28 checks against them. Needsgo, curl and python3. It prints each check and exits non-zero if any fail. Run it before changing anything ininternal/mcp.</li><li>go test ./... covers the domain and the adapters. It does not call a model.</li><li>The live prompt table (see the README) is the only test that does, and it needs an Ollama server.</li><li>To add a tool: add its schema in internal/mcp/tools.go, a case in callTool in internal/mcp/call.go, and put the behaviour inbox.Service, so the REST API can offer it as well. Write the description and the error messages as if for a reader with no other documentation, because for the model that is exactly the situation.</li></ul><h3>What Was Checked For This Document</h3><ul><li><strong>No handshake; </strong><strong>initialize refused on the modern path; </strong><strong>server/discover works alone:</strong> docs/verify.sh; changelog items 2 and 3</li><li><strong>resultType, </strong><strong>ttlMs, </strong><strong>cacheScope on results:</strong> script; changelog item 8 and minor change 5</li><li><strong>202 / 405 / ignored session header:</strong> script (405); transport page; the 202 path is read from the code only</li><li><strong>Header mismatch is 400 with </strong><strong>-32020; unknown version is 400 with a </strong><strong>supported list:</strong> script; transport page</li><li><strong>Origin 403; bearer 401:</strong> script; transport page for Origin</li><li><strong>isError semantics (story no = false, misuse = true, unknown tool = RPC error):</strong> script</li><li><strong>MRTR: </strong><strong>input_required, state round trip, cross-instance resume, forgery, wrong box:</strong> script; changelog item 7</li><li><strong>confirm: true cannot skip the question for a client that can ask:</strong> script (with the app&#39;s own client only)</li><li><strong>MRTR field shapes and requestState rules:</strong> read against the spec’s MRTR page, item by item; the two gaps above</li><li><strong>The state is not single-use:</strong> script</li><li><strong>Claude Code connects, uses 2026–07–28, sends </strong><strong>Mcp-Param-BoxId, and completes the MRTR round trip:</strong> its traffic row on the deployed server (client claude-code, inputResponses and requestState present in the retry), 2026-10-25</li><li><strong>Departures from the spec in section 7:</strong> read from code and the transport page; item 1 also by script, and by an Autopilot run against the default configuration</li><li><strong>The 55/55 table and the 2026–10–25 regression:</strong> docs/evidence/ logs; commits 627b1c9, e1bb5ba</li><li><strong>MRTR field shapes and requestState rules:</strong> read against the spec’s MRTR page, item by item; the two gaps above</li><li><strong>The state is not single-use:</strong> script</li><li><strong>Departures from the spec in section 7:</strong> read from code and the transport page; item 1 also by script, and by an Autopilot run against the default configuration</li></ul><p><em>Originally published at </em><a href="https://github.com/lehmann314159/medium/blob/main/PuzzleBoxMcp-HOW-IT-WORKS.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2066287d4794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ratchet: A Re-introduction]]></title>
            <link>https://medium.com/@lehmann314159/ratchet-a-re-introduction-c9ca569277fb?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ca569277fb</guid>
            <category><![CDATA[agent-loop]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 03:20:59 GMT</pubDate>
            <atom:updated>2026-09-21T03:20:59.862Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I’ve been up to some stuff :)</em></p><p>Ratchet names two things in this paper. The pattern is a directed, converging agent loop for small local models. The application is a Go program that implements the pattern for one task, turning a design document into tested Go code. The version number belongs to the application. This paper describes the pattern, then the application as tagged at v0.4 (commit d92f807), what building it around small models taught, and what a 23-run validation of it found.</p><p>The code is at <a href="https://github.com/lehmann314159/ratchet">https://github.com/lehmann314159/ratchet</a>. Other, unrelated projects share the name.</p><ul><li><strong>Ratchet (the pattern).</strong> A directed, converging agent loop: a framework-fixed sequence of narrow steps, mechanical checks where a check can be written, independent review where it cannot, and success decided by an external check. Defined in section 2.</li><li><strong>Ratchet (the application).</strong> The Go program that implements the pattern for one task. It is what carries the version number, and every measurement in this paper is of it.</li><li><strong>Design document.</strong> The plain-English specification of a program. It is the only input a person writes.</li><li><strong>Bead.</strong> A scoped unit of work with a spec, a fixed list of output files, and exit criteria.</li><li><strong>Exit criteria.</strong> Shell commands that must pass for a bead to count as done, for example go test -v . -run=TestApplyMove.</li><li><strong>Verb.</strong> One model call with one job and a defined output.</li><li><strong>Fleet.</strong> The set of local models assigned to verbs.</li><li><strong>Pin.</strong> A bullet in the design document that names a bead and lists literal values that must appear in its spec.</li><li><strong>Escalation.</strong> A job or project stops and waits for a person.</li></ul><p>At the frontier, everything is large. The models handle ambiguity well, and a coding agent supplies the handshake with the model, manages context, and keeps state between sessions. It is also expensive. Going lower takes three forms: more modest frontier models, mid-tier models, and models that run on consumer hardware. Each is less capable than the frontier, to different degrees. The application works at the low end of that range. At run time it makes no cloud calls. The reference deployment is one machine with 119 GiB of unified memory serving models of roughly 24 to 35 billion parameters through Ollama.</p><p><strong>Premise and scope.</strong> The premise of this paper is that frontier models can do this task with much less structure than Ratchet supplies. The author has seen them do it. That is an observation from his own use, not a result, and the paper does not test it. It makes no comparison with a frontier model and no claim about cost or quality relative to one. What it describes is what it took to make smaller models reliable enough to finish projects.</p><p>Two earlier projects frame the design. Geoffrey Huntley came up with the Ralph Wiggum loop and named it in mid-2025. Its core is to run an agent in a loop against a check that cannot lie, such as a test, a linter, or a type checker, until the check passes. Each iteration starts a fresh agent that reads the current plan and code from files, does one task, commits, and exits. Steve Yegge released Gas Town on January 1, 2026, as an orchestrator that coordinates many coding agents at once. It is written in Go and gives agents roles such as Mayor and Polecats. Its work units, called beads, are tracked in git so that work survives agent restarts.</p><p>Both address the same three questions: how far a person can step back, how much structure the process needs, and how the process knows it has succeeded. The Ralph loop keeps the structure minimal and puts success in an external check. Gas Town puts structure into roles and persistent work items across many agents. The Ratchet pattern puts it into a fixed sequence of narrow steps chosen by the framework, with success decided by commands that must pass on disk.</p><p>Ratchet is a pipeline that turns a design document into a tested program using language models that run on local hardware. It is built for small models. Instead of handing the whole job to one model, it breaks the work into small steps and gives each step to a model chosen for it. It checks results with ordinary code wherever it can, has a different model review the work that code cannot check, and does not move on until the current piece passes its exit criteria. When a piece keeps failing, it stops and asks a person.</p><p>Take the tasklist project, one of the documents used in section 7. Its design document is 246 lines describing a small web server for a task list. Ratchet turns it into four units of work, called beads, covering the task store, the page templates, the HTTP handlers, and an integration test. For each bead it writes the tests, then writes code until the exit criteria pass, then moves on. Using it takes two commands. One creates a project from a design document, and the other starts a server that runs the pipeline and a dashboard. Each bead ends with a report of every attempt and decision. One tasklist run took about three hours.</p><p>Two things share the name, as the introduction says. The first is the pattern behind that description.</p><p><strong>The pattern.</strong> As a pattern, Ratchet has five properties:</p><ul><li>A framework, not a model, fixes the sequence of narrow steps. A model’s output can only select among branches the framework defines.</li><li>Each step is done by a model chosen for that step.</li><li>Where a check can be written mechanically, a mechanical check replaces a model’s judgment. Where it cannot, a second model, different from the first, reviews.</li><li>Success is decided by an external check, never by the model’s own claim of completion.</li><li>When a cap is reached, the process stops and asks a person.</li></ul><p>The pattern says nothing about programming language, database, or model server.</p><p><strong>Mechanical checks and inference.</strong> The application separates two kinds of work. A mechanical check is code that reads artifacts and returns a fact: a file exists, a package compiles, a symbol is declared, an exit criterion passes on disk. It has no opinion and gives the same answer every time. An inference is a model’s reading of something: a review finding, a judgment that a test is sound, an interpretation of why an attempt failed. It can be wrong and can differ between runs.</p><p>The application keeps them apart in three ways. Facts and interpretation are recorded in separate fields. Inferences that steer the pipeline pass through mechanical gates before they take effect. And a mechanical check is used in place of a model wherever one can be written. The boundary is not always clean. The word match that flags “standard movement rules” is deterministic, but what it finds is a suspicion for a person to look at.</p><p><strong>The application.</strong> The application realizes the pattern for one task: building Go programs from design documents. It breaks the document into beads. The term is from Steve Yegge’s Beads, a git-backed issue tracker that gives coding agents persistent memory across sessions, whose name reflects issues chained together by dependencies like beads on a string. In the application a bead is a row in a database, not a file in git.</p><p>Each bead goes through a fixed chain of verbs that writes tests first and then code. Fourteen verbs have model assignments, and several checks make no model call. Several of the steps that write have a reviewer on a different model: the survey, the decomposition, the tests, and the implementation. In the test-writing loop a judge approves a test or sends it back. One bead’s results feed the next. When a cap is reached, the pipeline stops and asks a person. State lives in a SQLite database.</p><p>The application is not a general coding agent. It builds from a design document, and Go is the only language it currently supports. The pattern is tied to neither. Nothing starts from a change request or a bug report. Changing a finished project means editing its document and re-running the beads whose specs changed. It does not run unattended indefinitely, since stopping for a person is part of the design. It is not a measured substitute for a frontier agent.</p><p>Is Ratchet a terrible idea? Four objections are each paired with an answer. The objections are to the approach, and the evidence comes from the application. The record shows how far each one holds.</p><ol><li><strong>Objection: judgment is the point, and bigger models have better judgment. Answer: mechanical checks, where possible, can replace judgment.</strong> The paper does not dispute the second half. The answer concerns what to do when a larger model is not the choice: move judgment into checks where a check can be written. Exit criteria checked on disk, the manifest checks, and the gates on adjudication decisions do not depend on a model. Where no mechanical check exists, the pipeline still relies on model review. In the one comparison of defect-finding in tests, the incumbent caught 4 of 6 known defects and the other two candidates caught none. Only local models were tried.</li><li><strong>Objection: coordinating several small models is fiddly. Answer: building it yourself improves knowledge.</strong> The fiddliness is documented in section 6. Five model families needed different handling of tool calls and output constraints, and only two or three models can be resident at once. That documented knowledge is what building it produced.</li><li><strong>Objection: time is sometimes more important than money. Answer: that wisdom pays dividends when working with more expensive systems.</strong> A four-bead project took about three hours. The 23 burn-in runs took about 74 hours of wall-clock time, one project at a time. The transfer claim has not been tested against a frontier system. The likeliest candidates to carry over are the design-document discipline in section 5 and the habit of checking a claimed success against the disk.</li><li><strong>Objection: harnesses and coding agents are improving at a furious pace. Answer: if an organization’s AI knowledge is T-shaped, that distributed expertise lifts everyone.</strong> This paper makes no forecast and compares against no current agent. The second half is a claim about organizations, not about the system, and it is not measured here.</li></ol><p>As section 1 says, this paper makes no comparison with a frontier model. The first answer has the most direct support in the record. The other three are judgments about learning and organizations.</p><p>Each verb’s result is stored as a row in a SQLite database, and the next verb is queued when the previous one commits.</p><p><strong>Bootstrap</strong> runs once per project. SURVEY_SPEC reads the design document and returns a manifest of the files and declarations (types, function signatures) it calls for. It runs under a JSON schema and has no tools. VERIFY_MANIFEST is the one verb that makes no model call. It writes the scaffold, stub files generated from the manifest, and runs six mechanical checks:</p><ul><li>Every listed file exists.</li><li>No behavioral test files were created.</li><li>The package compiles.</li><li>The API-check file carries compile-time assertions for the exported symbols.</li><li>Stub bodies contain no control flow.</li><li>No package-level identifier is given conflicting types across files.</li></ul><p>CERTIFY_MANIFEST, run on a different model from the survey, approves or rejects. A rejection returns to SURVEY_SPEC with feedback, and a fifth rejection stops the project.</p><p>DECOMPOSE_SPEC turns the document and manifest into bead specs, and the bead count is not fixed in advance. Before anything proceeds, a mechanical check rejects a decomposition that references a file before the bead that creates it, or that merges or drops a bead the document&#39;s own numbered list calls for. DECOMPOSE_SPEC gets three attempts. AUDIT_DECOMPOSITION, on a different model, reviews the result. If it finds problems, RECONCILE_DECOMPOSITION revises the individual specs, and the two loop for at most two rounds before the project waits for a person.</p><p><strong>Tests.</strong> A bead whose output files include a Go test file starts in a test-first loop. REFINE_TESTS_WRITE drafts the test with two tools. One writes a test function, which the framework splices into the file. The other compiles and runs a short Go snippet, so a claim about the language or standard library can be checked instead of reasoned about. REFINE_TESTS_CRITIQUE, on a different model from the writer, reviews the file. REFINE_TESTS_JUDGE approves it or sends it back, for at most five cycles.</p><p><strong>Implementation.</strong> EXECUTE_BEAD runs a coding agent with three tools ( write_file, read_file, run_command) in a temporary per-attempt workspace. It may write only the files the bead lists, and only those are copied back when the attempt ends. An attempt counts as a success only if the exit criteria pass when checked on disk. The model&#39;s statement that it is finished does not count.</p><p>Two mechanisms end a stalled attempt. A progress tracker inside the loop counts a turn as productive only if a write leaves an in-scope file at content it has not held before in that attempt. It ends the attempt on a streak of empty turns, three identical tool calls in a row, or no forward progress at a 12-minute checkpoint. A hard ceiling is set at 45 minutes. Separately, MONITOR_EXECUTION is a watchdog subprocess that polls the trace file about every 30 seconds. It fires on mechanical checks first, either a trace that stops growing for about 12 minutes mid-write or a repeated-action pattern. A small model&#39;s FIRE or NO_FIRE call comes after those. It can terminate the running attempt.</p><p>After an attempt, ANALYZE_EXECUTION gathers mechanical findings (parsed trace, compile and test output, undeclared or stray files). A separate model call adds an interpretation, kept in its own field. COMPRESS_ANALYSIS condenses the attempt history and tags each failure class new, recurring, or resolved. ADJUDICATE_NEXT_EXECUTION then decides: declare success, retry as is, retry with a revised spec, reject the tests, send the bead back to the test loop, or stop. Its decisions are gated. A declared success re-runs the exit criteria against a copy of the files. A revised spec is checked for invented symbols another bead owns, and if it fails, the decision falls back to retrying the unrevised spec. When a bead succeeds, REVISE_PENDING adjusts the next pending bead&#39;s spec against the code now on disk.</p><p>Five model-independence rules are enforced in code when a fleet is assigned. The same model must run DECOMPOSE_SPEC and RECONCILE_DECOMPOSITION. AUDIT_DECOMPOSITION must differ from DECOMPOSE_SPEC, EXECUTE_BEAD from ANALYZE_EXECUTION, CERTIFY_MANIFEST from SURVEY_SPEC, and REFINE_TESTS_WRITE from REFINE_TESTS_CRITIQUE.</p><p><strong>Language.</strong> The pattern does not depend on a language. The application does, and the two kinds of work adapt differently. On the inference side, the application detects a project’s language and appends language-specific guidance to a verb’s system prompt. Detection looks first for marker files such as go.mod or Cargo.toml and, before any file exists, falls back to the extensions of the files the beads will write. Guidance is one Markdown file per language and verb, loaded at run time, so it can be edited without a rebuild. On the mechanical side, adapting takes code. Scaffolding, the bead-spec checks, the automatic spec repairs, the compile check, the stub scan, test-function splicing, and the snippet runner are written for Go, and scaffolding rejects any other language. Detection recognizes six languages, but Go is the only language currently supported, and guidance exists for five Go verbs.</p><p>Other languages can be added as the project expands. On the inference side that takes a guidance file per verb. On the mechanical side it takes new code for each of the pieces above. The state machine and the model calls do not change.</p><p>Every path that stops a job or project for human review is documented in a twelve-row table in docs/ratchet_state_machine.md. At a terminal state, a per-bead report is written summarizing every attempt, spec revision, and decision.</p><p>The design document is the only input a person writes. SURVEY_SPEC, DECOMPOSE_SPEC, AUDIT_DECOMPOSITION, and RECONCILE_DECOMPOSITION read it whole. The verbs that test and implement a bead do not. They read the bead spec, which DECOMPOSE_SPEC wrote as a summary of the document, plus a bead-scoped excerpt of the document itself. That structure explains most of what the document has to do.</p><p>It has seven sections. Three are always present and four are conditional.</p><ol><li><strong>Overview</strong> states what the project does, its runtime model, what is out of scope, and every parameter a model could guess, such as board size or limits.</li><li><strong>Architecture</strong> (conditional) says which file owns which function, including “do NOT put X in Y” lines. The project is a single flat package, and CERTIFY_MANIFEST rejects any source file in a subdirectory.</li><li><strong>Data Types and Function Signatures</strong> covers every type, constant, function, and package variable any bead touches. It includes verbatim var _ assertion lines for exported symbols, which are checked against a generated file.</li><li><strong>Behavioral Specification</strong> says what each function does, not how, and which groups can be tested independently.</li><li><strong>Domain-Specific Test Scenarios</strong> (conditional) gives exact positions or values with the arithmetic shown, and names the wrong answer.</li><li><strong>Cross-Bead Contracts</strong> (conditional) records each interface one bead produces and another consumes, verbatim, covering every return variant.</li><li><strong>Decomposition Notes</strong> (conditional) holds a numbered bead list and pin bullets.</li></ol><p>Three mechanisms tie the document to the pipeline in code.</p><ul><li><strong>The bead list is enforced.</strong> DECOMPOSE_SPEC must emit one bead per numbered entry and cannot merge or drop one. It may add a bead.</li><li><strong>Pins are re-injected.</strong> Each pin bullet names a bead and lists literal values that must appear in that bead’s spec. The pin text is re-appended verbatim whenever the spec is written or rewritten: at decomposition, at reconciliation, on a revised retry, and on a rewind. Prose elsewhere in the document does not survive this reliably. DECOMPOSE_SPEC can keep a rule and drop the worked values that prove it. Pins are matched by bead title, so a revision that renames a bead loses them. That happened once in the burn-in, as part of one stopped run.</li><li><strong>The excerpt is capped.</strong> The excerpt given to the test-writing, critique, judge, and adjudication verbs is limited to about 30 KB. That is sized to the smallest context window in the fleet, 40,960 tokens. Sections are added in priority order: test scenarios, decomposition notes, behavioral rules that name the bead’s own symbols, then signatures. A section that does not fit is dropped whole and never cut mid-rule. The excerpt opens with a statement that it outranks the bead spec where the two disagree.</li></ul><p>The author is fluent in the domain and the implementer, a 24 to 35 billion parameter model, is not. Rereading the document does not close that gap, because the author sees a correct description. The design guide records concrete cases:</p><ul><li>A breadth-first flood fill described only by name, where the natural wrong implementation adds the starting cell twice.</li><li>An unexported helper used in a worked example but never declared, so the scaffold had no stub for it and every test-writing attempt failed the same way.</li><li>A form value containing + that a handler decodes as a space.</li><li>A rule stated precisely and then restated with a relative gloss (“up the board”), which a later revision echoed back incorrectly.</li></ul><p>An ambiguity checklist of 18 classes records patterns like these, each added after an incident. Five are mechanically detectable:</p><ul><li>Relative-direction language with no coordinate example (class 1).</li><li>A formula with no computed number (class 2).</li><li>A reference to a value defined elsewhere instead of the literal (class 6).</li><li>A main.go spec without a literal package main (class 7).</li><li>A category phrase standing in for its rules, such as “standard movement rules” (class 17).</li></ul><p>The class 17 check matches words like standard, normal, usual, conventional, or typical next to a rules or behavior noun. The reasoning is that a reviewer with the author’s domain fluency reads such a phrase as complete. In the one recorded experiment, a fresh reviewer read the whole chess document and raised six other issues but not the line “Knight, Bishop, Rook, Queen, King: standard movement rules.” A second reviewer read the rewrite, with every movement rule spelled out, and raised nothing on it. That is a single pair of reviews, and it tested reviewers, not the models that implement beads.</p><p>Checking has three parts. checkdesigndoc produces a mechanical report covering pins against worked examples, the five ambiguity classes, construction form, and bead size. Every result is a site to look at, not a pass or fail. A fresh subagent then reviews the document with only the checklist and deliberately not the mechanical report, so it forms its own findings. The two are reconciled, with every class 17 hit carried forward whatever the reviewer said. A person then decides each item, and a waiver is recorded in the document as a comment.</p><p>Drafting is a separate step. It requires every worked example to be verified by running a script in the same session, with the command and result cited in a comment. It also requires gaps to be listed as open questions instead of filled with a plausible value. This is the pipeline’s own decompose, audit, and reconcile shape applied one layer earlier. It is design-time work done with Claude, and everything after the document is accepted runs on the local fleet.</p><p>The bead-size check flags a bead that owns four or more functions and either depends on three or more earlier beads or appears in three or more contracts. Those thresholds come from one project. The lsystem grammar bead stopped repeated from-scratch runs until it was split into three.</p><p>Checked documents still failed. The four documents written for the burn-in were reviewed before any run. The reviewers found 20 issues, about 15 of them imprecise prose and 4 of them bugs shared with the reference implementations the pinned values had been computed from. Three of the four reviewers independently raised the same new class, 18, the order in which simultaneously failing input checks are reported. Even so, the glob-studio document contained two contradictory statements about empty character classes. It survived a six-finding check pass and stopped a run until the prose was corrected. The tasklist document was left unchecked as a regression anchor. It said a completed task shows “a done indicator (e.g. class done or a checked symbol)&quot;. That is class 10, and one tasklist run spent five test-writing cycles on what the phrase meant.</p><p>Many of the early failures were in the interface between the framework and the model, and few were about coding ability. Four kinds recurred.</p><p><strong>The tool-call handshake differs by model.</strong> A tool call is supposed to arrive in a structured field of the response. qwen2.5-coder:32b-instruct writes well-formed calls as bare JSON in the message text, so Ollama reports no calls and the loop saw an empty turn. qwen3:32b&#39;s template requires the literal text &lt;tool_call&gt;...&lt;/tool_call&gt; in the message. Ollama can apply a grammar that forces every generated token to form valid JSON, and the framework applied it to every call. That grammar forbids the &lt; character. Across 139 captured CRITIQUE calls in four corpora, the model never emitted a tool call once. After the grammar was dropped on tool-calling turns, the next full run showed 7 tool calls in 28 turns and no length-cap spirals. nemotron-cascade-2:30b-a3b reports tool support in Ollama&#39;s metadata and passed a trivial probe. On a real task, Ollama&#39;s own parser then threw an XML error on a large file argument. A model&#39;s advertised capability is not evidence. Only a real multi-turn exchange with a realistic payload is.</p><p><strong>Structured output and reasoning interfere.</strong> Reasoning models produce a thinking phase before answering. Under the JSON grammar, glm-4.7-flash on SURVEY_SPEC generated about 70,000 tokens until a 60-minute client timeout. muse-glimmer on DECOMPOSE_SPEC returned a 63 KB response with an empty beads array, twice, about 17 minutes each. For verbs whose output is a structured result, the fix was a JSON schema whose first property is a free-text reasoning field, so the model thinks inside the constraint. The same muse call then took one attempt, about 2 minutes, and returned nine beads. The schema had its own runaway. qwen3.6:35b-a3b produced 76 KB of repeating text and broke its own JSON, so the reasoning field is capped at 16,000 characters, which Ollama enforces. The reverse also occurred. On a verb whose output is tool calls, the schema let a model write a plan and claim completion without calling the tool. Those verbs run with no format constraint.</p><p><strong>A larger budget or a larger model did not fix a scope problem.</strong> One parser bead in the L-system project repeatedly stopped from-scratch runs. A bakeoff ran the real EXECUTE_BEAD loop, with all watchdogs, on that bead: 31 runs across seven models. Runs were scored by how many of 35 test checkpoints passed before the first failure. None passed. The best run reached 32. The 80-billion-parameter coder model matched the 30-billion one at a median of 26. Raising the turn limit from 50 to 120 lowered the best coder&#39;s three results from 12, 32, and 26 to 19, 19, and 0. One run spent 122 turns and 21 writes and broke a type shared with other beads. The two reasoning models never committed code. The fix was in the design document. The bead was split into three, each ran in one attempt, and the project completed 13 of 13 beads. The same bakeoff exposed a framework bug: an attempt that stopped calling tools after a write was recorded as a success without checking the exit criteria, which happened in 2 of 11 runs by models that wrote code. This is one bead with three runs per cell.</p><p><strong>Reports from the model and from the counters are unreliable.</strong> In a test-writing comparison across six beads, one run each, muse-glimmer produced 6 correct tests. The incumbent gemma4:31b produced 3, and on two beads it hit the 30-minute ceiling with nothing written. qwen3.6:35b-a3b produced 3. Its two failures came back as valid results with a generic summary, and only the missing file showed that nothing was written. Ollama&#39;s token counters count only answer tokens. In captured CRITIQUE calls the answer took about 14 seconds per turn and thinking took 40 to 230 seconds, visible only in total duration.</p><p>Only muse-glimmer runs at 8-bit precision. The rest of the fleet runs the Ollama library default, 4-bit. No comparison of 4-bit and 8-bit versions of the same model has been run. A blanket 8-bit sweep was rejected on reasoning, because it costs roughly 1.7 to 1.9 times the memory per model by the project&#39;s estimate and the blockers found so far were structural.</p><p>These findings came from qualify-model, which replays a captured verb call against a candidate model. It runs the verb&#39;s real code up to the commit step, without committing, and first checks that the rebuilt prompt is byte-identical to the captured one. Grading is per verb. REFINE_TESTS_WRITE is graded on whether the test compiles, passes the known-good implementation, and fails on a planted bug. REFINE_TESTS_CRITIQUE is graded on catch rate against known-bad tests and false positives against known-good ones. The judge and adjudication verbs are graded on agreement with the historical decision and on the rate of turns that end with no content and no tool call. Samples are small: critique used 6 runs on known-bad tests and 4 on known-good, and adjudication used six captured cases, all easy. Labels come from decisions the pipeline itself made, so the grades measure agreement with it.</p><p>Each incident maps to a mechanism in the framework. A tool-loop turn is capped at 8,192 tokens, with a two-stage recovery when a turn ends without content. A stalled attempt is decided by exit criteria on disk, and a timeout is treated as a signal to narrow the scope. Context size is set explicitly at 40,960 tokens, qwen3:32b&#39;s native maximum and the smallest window in the fleet, which fixes the excerpt budget in section 5. Every model call can be captured for replay. Framework bugs are investigated apart from project runs, and each document is run at least twice.</p><p>v0.4 is the commit ( d92f807) at which the application was frozen before a long validation run. The run was meant to show behavior across many varied inputs. A single reproduction per bug undercounts real defects and also undercounts the false-positive rate of the gates added to catch them. The rules were set in advance. The model fleet and quantizations did not change, no bug was fixed while the run was in progress, and every finding was logged and the run continued. The freeze would break only for a defect that blocked a majority of runs or made the results unanalysable.</p><p>The corpus was nine design documents. Four had been run before (fractalviz, lsystem-studio, cron-studio, tasklist). One, glob-studio, had a known document defect that had been fixed. Four were written for this run to break the mix of parsers and web apps in earlier tests (decimal, toml-mini, retry-engine, gapbuffer). Each document ran twice, with a third run when the first two disagreed. That made 23 project runs over about 74 hours of wall-clock time, one at a time. The projects ranged from 4 to 13 beads.</p><p>13 of the 23 runs reached complete and 10 were stopped for human review. Completed runs by document: decimal 2 of 3, toml-mini 2 of 3, retry-engine 2 of 3, gapbuffer 1 of 2, glob-studio 1 of 3, fractalviz 1 of 3, lsystem-studio 1 of 2, cron-studio 1 of 2, tasklist 2 of 2. One of the completed runs, glob-studio’s second, was interrupted at 9 of 12 beads and continued from a saved fixture against a corrected document. It counts once, as a completed run with a mid-run document fix.</p><p>Most of the stops came from defects in the pipeline or in a model’s behavior. The others were a bead the fleet found hard, a contradiction in a design document, and a bug in generated code that the pipeline caught. No two stops shared a cause. That can mean the recovery machinery is catching a different failure each time, or that the failure surface is wide enough for ten runs to barely sample it. This corpus cannot tell the two apart.</p><p>Compute was measured as job-active time, 82.1 hours summed. That is an upper bound, because retries overlap. The three test-writing steps (WRITE, CRITIQUE, JUDGE) took 53.0% of it. CRITIQUE alone took 32.4%, more than EXECUTE_BEAD at 20.2%. The bootstrap verbs took 15.9%. Of 151 EXECUTE_BEAD attempts, 118 succeeded and 33 stalled.</p><p>By the pre-set threshold there were no showstoppers. That threshold is high, and 10 of the 23 runs stopped, so the two should be read together.</p><p>What the run does not show:</p><ul><li>By design, there is no comparison with a frontier model on the same documents.</li><li>CRITIQUE returned no findings on 78% of parseable captures, but no ground truth exists to say whether those were correct.</li><li>CRITIQUE and JUDGE agreed on about half of CRITIQUE’s findings. The log found cases where each was wrong, so agreement is not correctness.</li><li>The documents were small and were written and checked with the framework’s own design-doc tooling.</li><li>The deployed binary was built from the tagged commit with a modified working tree, and what was modified is not recorded in the material reviewed here.</li></ul><p>Two questions occurred to the author while building the application. Neither is tested here, and neither is a claim of this paper.</p><p>The first is whether models lie along a spectrum from frontier to open, with the amount of structure a model needs to finish the same work increasing along it. The application sits at the high-structure end, and everything measured here comes from that end.</p><p>The second is whether a structured loop of this kind prevents or softens a class of errors found in AI-generated code, whatever the model’s size.</p><p><em>Originally published at </em><a href="https://github.com/lehmann314159/medium/blob/main/ratchet-reintroduction.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ca569277fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Ratchet Works: A Technical Overview]]></title>
            <link>https://medium.com/@lehmann314159/how-ratchet-works-a-technical-overview-fa0c2cb49836?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa0c2cb49836</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[open-model]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[gastown]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 23:04:24 GMT</pubDate>
            <atom:updated>2026-06-28T23:04:38.636Z</atom:updated>
            <content:encoded><![CDATA[<p>As can be found at <a href="https://github.com/lehmann314159/ratchet">https://github.com/lehmann314159/ratchet</a></p><p><strong>The Big Picture<br></strong>Ratchet is a fully autonomous, local coding pipeline. You give it a design document; it produces working, tested code. The whole thing runs on consumer hardware using Ollama-served LLMs — no cloud APIs, no human in the loop except when the pipeline gets genuinely stuck.</p><p>The central abstraction is the <strong>bead</strong>: a scoped unit of work with a fixed title, a set of output files it’s allowed to write, and an exit criterion (a shell command that must pass, like go test -v . -run=TestApplyMove). Beads are produced by decomposing the design doc, then executed sequentially in order. The pipeline doesn&#39;t move to the next bead until the current one passes its exit criterion.</p><p>Each bead moves through an eight-verb FSM. The key insight is that this FSM isn’t just a wrapper around a single model call — it mixes mechanical analysis, structured model calls, and a compress/summarize loop to manage context across many attempts.</p><p><strong>The Decomposition Phase (runs once; produces all bead specs)<br>DECOMPOSE</strong> runs once per project. A strong reasoning model ( qwen3:32b) reads the entire design doc and produces a JSON array of bead specs. The bead count emerges from this call - it&#39;s not predetermined. Each spec includes: a title, the list of output files the model is allowed to write, an exit criterion, an execution budget in seconds, and a monitor override setting. The prompt tells the model to search the whole document for function signatures - not just a formal API section - and to produce exact Go var _ func(...) compile-time assertion lines for the layout bead.</p><p>A design doc can strongly constrain the outcome: if it contains a ## Decomposition Notes section with an explicit bead table, DECOMPOSE essentially transcribes it and AUDIT typically finds nothing to flag. But the pipeline has no concept of &quot;the spec says N beads&quot; - the notes are hints, not a schema. An AUDIT pass with zero findings is a quality signal for the design doc, not a sign the pipeline skipped work.</p><p><strong>AUDIT</strong> runs next. A second model ( gemma4:31b) independently reviews the decomposition for structural problems: test beads with no test files in output_files, incorrect exit criteria syntax, independence violations between beads. AUDIT emits a structured list of findings.</p><p><strong>RECONCILE</strong> runs only if AUDIT found issues. The same model that did DECOMPOSE looks at each finding in turn and produces an updated_bead - a revised spec for just that bead. This is a subtle design: RECONCILE sees one finding at a time and emits one updated bead, not a full re-decomposition.</p><p><strong>Mechanical fixup at commit time</strong> <em>(Go-specific)</em>: After RECONCILE (or AUDIT if no findings), Ratchet runs a deterministic fixup pass over every bead spec. If a bead has a go test -run=TestFoo exit criterion but no *_test.go in its output files, it adds the derived test file name (e.g. game.go → game_test.go) to output_files. Only if there are no .go files at all (a content-only bead, like HTML templates) does it downgrade the criterion to go build ./.... This prevents a recurring failure mode where the executor writes the implementation but ADJUDICATE can&#39;t verify anything because the test was never written.</p><p><strong>The Execution Loop (runs once per bead, up to N attempts)<br></strong>Once the decomposition is committed, beads execute sequentially. Each bead goes through its own loop of up to N attempts (configurable per project).</p><p><strong>EXECUTE</strong> is the live coding step. A gemma4:31b model runs in a tool-use loop with three tools: read_file, run_command, and write_file. It reads the project directory and existing source files, writes code, runs tests, and iterates. All tool calls are logged turn-by-turn to a trace file. Meanwhile, a concurrent <strong>MONITOR</strong> process ( mistral-small3.2:24b) reads the growing trace every 30 seconds and fires SIGTERM if it detects the model is stuck - defined as repeated identical tool calls or more than ~10 turns with no write_file. An <strong>orientation-phase exception</strong> prevents false fires: if no write_file has appeared yet, repeated reads are treated as expected preparation, not recurrence. This exception was discovered empirically - four of five beads in an early project had at least one attempt killed by the monitor before the first write appeared. Trace data showed the first write_file appearing between turns 6-9 in successful attempts, so the threshold of 10 turns was chosen to cover the observed range while still catching genuinely stuck models at 19-28 turns.</p><p><strong>ANALYZE</strong> runs after each execution, whether it succeeded or timed out. A reasoning model ( qwen3:32b) reads the trace and produces structured findings: what the model did, what the test output said, whether the exit criterion passed, and what might have gone wrong. ANALYZE also runs mechanical pre-checks before calling the model <em>(Go-specific)</em>: it parses the trace for write_file calls, verifies the compile-time assertion file is present and has var _ lines using a Go AST parser, and injects those findings mechanically.</p><p><strong>COMPRESS</strong> condenses the history of all previous attempts into a rolling summary. On the first two attempts it’s a passthrough — no model call, raw ANALYZE output is used directly. The model call only starts when the history is long enough to justify summarization. On attempt 3+, mistral-small3.2:24b reads the current compressed history and the new ANALYZE findings and produces an updated summary with [NEW]/[RECURRING]/[RESOLVED] tags on each observation. This gives ADJUDICATE a concise picture of what has and hasn&#39;t worked across all attempts.</p><p><strong>ADJUDICATE</strong> makes the go/no-go decision. gemma4:31b sees: (1) the bead spec with actual execution budget, (2) the ANALYZE findings from the last attempt, (3) the compressed history. It produces a JSON verdict: trend (improving/declining/stalled), bead_spec_fit (does the implementation match the spec), decision (one of: declare_success, execute_revised, declare_escalation), and an execute_revised bead spec if retrying. The revised spec may include stronger hints via a <strong>specificity ratchet</strong> that escalates across attempts: &quot;here&#39;s the general approach&quot; → &quot;here&#39;s a skeleton implementation&quot; → &quot;here&#39;s verbatim code, copy it exactly.&quot; ADJUDICATE&#39;s output passes through the same mechanical fixup as decomposition before committing.</p><p>Two important principles encoded in the ADJUDICATE prompt:</p><ul><li><strong>Vacuous-pass principle</strong>: if the exit criterion is go test -run=TestFoo but no test file was written, don&#39;t declare success - the test didn&#39;t run, it just didn&#39;t fail.</li><li><strong>Workspace repair principle</strong>: if prior attempts left broken files (e.g., a partial implementation that doesn’t compile), instruct the next attempt to fix or replace them before adding new code.</li></ul><p>If ADJUDICATE issues declare_escalation or the attempt cap is hit, the bead enters escalated state and the project pauses for human intervention.</p><p><strong>Prompt Engineering vs. Mechanical Steps<br></strong>The split is clean and deliberate: <strong>the prompt engineering is largely language-agnostic; the mechanical layer is where language-specific knowledge lives.</strong></p><p><strong>Language-agnostic:</strong></p><ul><li>All model calls: DECOMPOSE, AUDIT, RECONCILE, ANALYZE, COMPRESS, ADJUDICATE</li><li>COMPRESS passthrough on attempts 1–2</li><li>Monitor orientation-phase exception</li><li>ADJUDICATE vacuous-pass principle and workspace repair principle</li><li>Specificity ratchet</li><li>Post-execution reports</li><li>The attempt cap, budget enforcement, FSM transitions</li></ul><p><strong>Go-specific (mechanical layer):</strong></p><ul><li>applyMechanicalBeadFixes: detects go test -run=TestFoo without *_test.go in output files; derives the test file name from the source file name; falls back to go build ./... for non-Go beads</li><li>api_check_test.go with var _ func(...) = FuncName compile-time assertions</li><li>ANALYZE pre-check: Go AST parser to verify the assertion file has var _ lines</li><li>detectLang(): checks for go.mod on disk; falls back to scanning output_files extensions at decompose time (when go.mod doesn&#39;t exist yet)</li><li>Language guidance injected into the EXECUTE prompt</li></ul><p>Adding Python support would mean implementing a detectLang extension, a pytest-equivalent exit criterion fixer, and replacing the AST check - the model calls wouldn&#39;t change at all.</p><p><strong>Three Rules That Took Failures to Discover<br></strong>Some of the most important mechanical rules only became visible as failure modes:</p><ol><li><strong>Test file missing from </strong><strong>output_files</strong>: The model writes a correct implementation, but because the test file wasn&#39;t in its write-permission list, it doesn&#39;t write one. ADJUDICATE can&#39;t see any test run. The pipeline wastes multiple attempts on already-correct code, each time failing vacuously. Fix: add the test file to output_files at commit time.</li><li><strong>execution_budget=0 in the spec JSON</strong>: DECOMPOSE writes execution_budget: 0 meaning &quot;use the project default.&quot; ADJUDICATE reads the raw JSON and reasons &quot;the budget was zero, that&#39;s why it timed out.&quot; Fix: prepend &quot;Actual execution budget: Ns&quot; to ADJUDICATE&#39;s input before the model call.</li><li><strong>Cryptic </strong><strong>write_file error for missing path</strong>: Without a path argument, the tool resolved to the project directory and returned &quot;open /path/to/project: is a directory.&quot; The model would run pwd and try to diagnose the error. Fix: return &quot;write_file requires a &#39;path&#39; argument specifying the filename (e.g. path=&quot;game.go&quot;).&quot; The model self-corrects on the next turn.</li></ol><p><strong>Post-Execution Reports<br></strong>Each bead at terminal state (succeeded, escalated, full_stopped) writes traces/bead-{id}-report.md automatically - no model call, purely mechanical. The report contains: every spec revision, an attempt table (write_file ok/total, last test result), ADJUDICATE decisions with actual budgets, compressed history, full output file contents, and a 60-line trace tail. This makes escalation diagnosis fast: instead of grepping multiple log files, you read one document.</p><p><strong>Current Model Fleet<br></strong>All three models run resident on a single machine (Ollama, OLLAMA_KEEP_ALIVE=-1, 55 GB total VRAM). No cloud API calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GhAUhoJVFvdxS88XnokgZg.png" /><figcaption>Current Model Fleet</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa0c2cb49836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converging Agent Loops With Rachet]]></title>
            <link>https://medium.com/@lehmann314159/converging-agent-loops-with-rachet-125ab69ff956?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/125ab69ff956</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[agent-loop]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 03:46:42 GMT</pubDate>
            <atom:updated>2026-06-28T03:46:42.715Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Shifting nouns to verbs and using peer review</em></p><p>Most production coding agents run on the same basic cycle: reason about what to do, take an action, observe the result, repeat. This pattern — usually called ReAct — is the foundation underneath LangChain’s AgentExecutor and most agentic coding tools in current use. A single model holds the plan, the execution, and the judgment of whether the execution worked, all in one continuous context.</p><p>The cost structure of this pattern is well documented at this point. Retry loops compound fast: when an agent hits a test failure, tries a fix, and fails again, each retry is a full round-trip at whatever context size the session has already accumulated — not a fresh, cheap attempt. Three failed tries late in a session don’t cost three times a turn; they cost three times a turn that’s already carrying tens of thousands of tokens of prior context. Model choice multiplies whatever that baseline turns out to be.</p><p>That cost structure is pushing people to split the loop apart. One example: a “Refine-Plan-Act” pattern divides a coding task into three separate phases — refine the requirements into a document, plan the implementation into a second document, then act — specifically so a misunderstood requirement gets caught in the requirements document instead of discovered mid-implementation, and so a bad implementation can be discarded while the validated plan underneath it survives. The phases are kept as separate, reviewable artifacts rather than folded into one continuous agent context.</p><p>Steve Yegge’s Gas Town takes a different cut at the same problem. Rather than splitting a single agent’s loop into phases, Gas Town splits the work across role-specialized agents — a coordinating “Mayor,” worker “Polecats,” monitoring “Witnesses” — with state persisted externally in a Git-backed issue tracker called Beads rather than carried in any one agent’s context window. Five months after launch, Yegge noted that newer models hadn’t reduced the need for this structure the way he’d originally expected; the orchestration stayed load-bearing as the underlying models got stronger, rather than becoming unnecessary scaffolding.</p><p>Both of these are responses to the same underlying problem with the plain loop: judgment and execution, or planning and implementation, end up bundled into one actor with no separation of concerns and no external record of what it decided or why. Ratchet is a third cut at that same problem, descended directly from a personal adaptation of Gas Town’s Mayor/Polecat pattern, built to find out whether a more granular version of the role split holds up against a real fleet of local models rather than a single frontier model doing everything.</p><p>The Gas Town adaptation that Ratchet grew out of used Claude Desktop as the Mayor — the orchestrating layer — and open models served locally through Ollama as Polecats, the workers executing individual tasks. That two-role split was a reasonable starting point, but it ran into a structural problem during early testing: a Mayor that’s free to alter a decomposition during planning, with no mechanism positioned to catch when it does, can introduce errors that no Polecat is in a position to notice. Two such Mayor-introduced errors — a fixed-quota encoding scheme replacing an intentionally opportunistic one, and an indexing scheme replacing a flat-string one — invalidated an early experiment entirely, not because any worker model failed, but because the orchestrating layer made an unjustified change upstream of where any check existed.</p><p>That failure is the direct origin of Ratchet’s architecture. A role like “Mayor” or “Polecat” is a noun: it names an actor, not the action that actor is performing at a given moment, and a single noun can quietly cover several actions with different correctness criteria. This isn’t unique to one adaptation — it’s how Gas Town’s own published role list is structured. The Mayor’s documented job spans analyzing a request and breaking it into tasks, creating the unit that tracks the work, spawning agents, distributing work to them, monitoring their progress, and summarizing completion: six distinct actions under one name. The Witness’s documented job spans detecting stuck agents, triggering recovery, managing session cleanup, and tracking completion: four more actions under a different single name. The Deacon checks agent health, dispatches maintenance workers, and escalates issues it can’t resolve itself. None of these role definitions distinguish which of their bundled actions is succeeding or failing at any given moment — the role reports as a whole, or not at all.</p><p>When a role bundles several actions, there’s no natural seam at which to ask whether the same actor should be doing all of them, or whether one of them needs an independent check. That’s exactly what went wrong in the Mayor-introduced decomposition errors above: “decide how to break the work down” and “decide whether that breakdown is correct” were the same actor’s job, with nothing positioned to ask whether they should be.</p><p>Ratchet replaces role nouns with verb identities. There are eight: DECOMPOSE_SPEC, AUDIT_DECOMPOSITION, RECONCILE_DECOMPOSITION, EXECUTE_BEAD, MONITOR_EXECUTION, ANALYZE_EXECUTION, COMPRESS_ANALYSIS, and ADJUDICATE_NEXT_EXECUTION. Each verb is defined by what would make its output correct, not by which actor performs it or what shape its input and output happen to take. Two verbs can be handled by the same model and still be different verbs; the same model handling both is never evidence that they should be merged into one.</p><p>The pipeline runs in two phases. A decomposition phase turns a design document into discrete units of work and checks that breakdown before anything gets built. An execution phase carries each unit through implementation, monitoring, analysis, and a decision about what happens next. Both phases share the same shape: a bounded loop for resolving disagreement, and a single escalation path to a person when that loop runs out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Mfye2hgphri19E-V6uK4g.png" /></figure><p>This distinction has a concrete consequence: DECOMPOSE_SPEC (breaking a design document into discrete units of work, called Beads) and AUDIT_DECOMPOSITION (checking whether that breakdown is sound) are required to run on different models. The model that wrote a decomposition reviewing its own work is a weaker check than a second model reviewing it - self-review has repeatedly missed findings that a different model, looking at the same material, caught. If AUDIT_DECOMPOSITION finds a problem, a third verb, RECONCILE_DECOMPOSITION, resolves the disagreement. That resolution is bounded rather than open-ended: capped at two rounds, with the full history of the disagreement preserved rather than summarized away, and convergence detected mechanically by the queue managing the process rather than by either model deciding for itself that it&#39;s done. If the two rounds run out without resolution, the whole decomposition escalates to a person rather than continuing to iterate.</p><p>The same logic governs execution. EXECUTE_BEAD performs the work; MONITOR_EXECUTION watches it run, as a concurrent process rather than a step waiting for execution to finish; ANALYZE_EXECUTION interprets what happened after the fact; COMPRESS_ANALYSIS reduces a growing history of analysis into something a later decision can act on without re-reading everything; ADJUDICATE_NEXT_EXECUTION decides what happens next. Each of these is a distinct correctness criterion, not a distinct actor - multiple verbs frequently run on the same model, and that overlap is never treated as a reason to fold them together.</p><p>A finite state machine sits underneath all of this as the actual source of truth. A bead’s status isn’t a story a model tells about its own progress; it’s a state transition, recorded in storage, in the same transaction as the signal that work is complete. Each project is its own first-class entity in that storage, holding its own verb-to-model assignments and its own configured defaults, so a project’s choices about which model handles which verb are data the system can read, not decisions baked into a deployed binary.</p><p><em>(Role descriptions above are from Gas Town’s published documentation: </em><a href="https://github.com/gastownhall/gastown"><em>github.com/gastownhall/gastown</em></a><em>.)</em></p><p>None of this is presented here as proven. It’s a description of what was built and the design principle it was built around — gating verb identity on correctness criteria rather than on which actor performs the work, or what shape the work’s inputs and outputs happen to take. Whether that principle actually held up is a separate question, and the subject of the next piece. Spoiler alert: it involves prompt engineering and a balance between general guidance for models and mechanical subsystemes to get consistent signals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=125ab69ff956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Optimization That Broke the GasTown Experiment]]></title>
            <link>https://medium.com/@lehmann314159/the-optimization-that-broke-the-gastown-experiment-9dfccc6727dd?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dfccc6727dd</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 23:41:27 GMT</pubDate>
            <atom:updated>2026-06-21T23:41:27.568Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Something Instructive (and Basic) Happened While I Was Rushing</em></p><p>I built a steganography tool that hides text messages inside Spotify playlists. The encoding scheme picks tracks whose titles contain the right letters in the right order, indexed by a seeded PRNG, with a Camelot-wheel compatibility check so the resulting playlist still sounds coherent rather than random. I built the first version myself, with Claude Code, in a single 18-minute session: 33 files, 16 passing tests.</p><p>Then I tried to answer a different question: could a small, locally-run open model build the same system, through a structured workflow where I act as an orchestrating layer between a Claude Mayor and a ~30B polecat model? The answer might have been yes, except I forgot the number one rule of side by side tests: don’t make a small change, even if you think it’ll be fine.</p><p><strong>Why build it by hand first</strong><br>This workflow took a page from GasTown, a pattern Steve Yegge described for agent orchestration. I’d read several descriptions of how this kind of thing is supposed to work, but I wanted to implement it myself rather than trust that I understood it from descriptions alone. Building the whole system at once risked taking too much on faith, so I started with a Claude Mayor and a qwen3.6 Polecat, and I handled the notification and communication role manually myself, so I wasn’t trying to build a whole automated system before I understood how the pieces actually worked together.</p><p><strong>What went right</strong><br>The plan file for v0 was converted to nineteen scoped work units. Ten of them, B01 through B10, went cleanly: project scaffold, SQLite schema, a Spotify API client with pagination and retry, the audio provider interface and stub, Camelot mapping and compatibility scoring, the track indexer, the PRNG and key derivation, letter extraction, a greedy playlist builder, and the decoder.</p><p>The model doing the work, qwen3.6–27b, performed well within these scoped tasks. It wrote idiomatic Go, kept package boundaries clean, and produced meaningful error messages. On B05 it noticed a missing interface method on its own and added it without being prompted. It read existing tests before writing new ones and avoided naming collisions, which meant it had some awareness of the surrounding repo rather than just the task in front of it. B09 took an unusually high 52,000 tokens because the work units were ordered decoder-before-encoder, which made the round-trip test harder to reason about than it needed to be. The output was still correct. B10 was clean.</p><p>And then everything went terribly awry.</p><p><strong>Where it broke<br></strong>B11, the constrained encoder, failed three times and was eventually marked done without ever passing its own round-trip test. B12, which built the CLI tools and the end-to-end test, failed immediately, on the same underlying problem. V1 was killed at that point — the remaining seven planned units were never attempted.</p><p>The root cause<br>Both failures traced back to two changes Claude and I had introduced when writing the specs for these work units. Neither change was something the polecat decided on its own. Both were deviations from how the first version actually worked, and neither deviation was something the experiment was designed to test.</p><ul><li><strong>A fixed quota instead of an opportunistic one.</strong> The original version opportunistically encodes 1–3 bytes per track, depending on the track’s own title. When Claude and I decomposed the V0 plan document into beads for V1, that changed to a hardcoded requirement of exactly 2 bytes per track. V1 was not able to work with that change. The decoder foundered trying to get the unit tests to pass, and the constrained encoder never got escape velocity.</li><li><strong>Indexed extraction instead of a flat letter string.</strong> The original version concatenates every letter from every word in a track title into one flat string, then draws a position index into that string. This guarantees the extraction always returns exactly the number of bytes requested. My spec for the new version drew a word index, then a character index within that word, then filtered out non-alphabetic characters; depending on the title, that can return zero, one, or two bytes when the caller asked for two. The constraint-checking logic downstream had no way to know this and treated every short return as a pool problem rather than an extraction bug.</li></ul><p>I had written both of these into the work-unit specs as straightforward optimizations. Neither was flagged as a deviation from the reference implementation, because I hadn’t been tracking the reference implementation as a set of explicit constraints. It was just the thing the first version happened to do.</p><p><strong>Why this invalidated the comparison<br></strong>The question I was trying to answer was whether a small model, working through this kind of structured workflow, could build the same system that Claude built. That question only has an answer if the second version is implementing the same algorithm. It wasn’t. It was implementing a different algorithm that happened to be harder to get right, and the model was never given a chance to push back on that, because nothing in the workflow gave it standing to question the spec it was handed.</p><p>The model’s failures on B11 and B12 weren’t capability failures. The model never reached a point on any of the ten completed work units where the task was simply beyond it. Every failure traced back to a decision I had made while writing the spec, not a decision the model made while executing it.</p><p><strong>The immediate fix<br></strong>I went back through the first version’s source and wrote down, explicitly, the algorithmic choices that any future version is required to preserve: an opportunistic, title-derived payload count per track rather than a fixed quota, extraction via a flat letter string with guaranteed exact-count returns, a cloneable PRNG so the constraint search can test candidates without advancing real state, and several other smaller specifics. These are now a standing document, not something to be reconstructed from memory each time. Any future version that wants to diverge from one of these has to say so and justify it; divergence is no longer something that happens by accident inside a work-unit spec.</p><p>That fixed the immediate problem. It didn’t fix the underlying cause.</p><p><strong>The deeper problem: accountability and oversight<br></strong>The important failure here wasn’t “I wrote two bad specs.” It was that Claude and I, sitting in the orchestrating role, were free to introduce unjustified algorithmic changes during decomposition, and nothing in the workflow was positioned to catch that before it reached the model doing the execution work. A written constraints document helps for this one project. It doesn’t generalize, because the next project will have its own implicit assumptions that nobody wrote down either.</p><p>That’s a structural gap, not a spotify-stego-specific one. Any workflow where an orchestrating layer breaks a design into scoped units for an executor to build has the same exposure: the executor can only build what it’s told, and has no mechanism for catching a bad decomposition before acting on it. The orchestrating layer is the only thing that can catch its own mistakes, and in this workflow nothing was checking it.</p><p>That gap is what I started designing around. The result is a separate system, Ratchet, built around the idea that the various components of agentic orchestration need observability and auditing. An Adjudicator that takes a design document and turns it into scoped work units needs to verify that the decomposition doesn’t introduce change. Part of its job includes preserving the constraints that are actually in the document rather than quietly “improving” on them. It’s the role that would have had to catch the two-bytes-per-track change before it ever became a work-unit spec.</p><p>Whether it actually catches that kind of thing is a separate, ongoing question. The first real test of the Adjudicator role is running now, comparing candidate models against several real design documents, including this project’s. It’s not finished, and I’m not going to claim a result here that the experiment hasn’t produced yet. But the lineage is direct: a failed comparison between two versions of a playlist encoder is the reason that role exists at all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dfccc6727dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I’m Going to Hide Messages in Spotify Playlists]]></title>
            <link>https://medium.com/@lehmann314159/im-going-to-hide-messages-in-spotify-playlists-74c3db6cdf49?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/74c3db6cdf49</guid>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 23:29:08 GMT</pubDate>
            <atom:updated>2026-06-14T23:29:08.931Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Slight Departure?</em></p><p>Steganography is the practice of hiding a message inside something that doesn’t look like a message. The classic example is invisible ink. The modern version is hiding text in the least significant bits of a PNG. The goal in both cases is the same: the carrier — the image, the letter, the whatever — should attract no suspicion on its own.</p><p>A Spotify playlist is a surprisingly good carrier. Playlists are public, shareable, and completely unremarkable. People send them to each other constantly. A playlist called “Sunday morning” or “gym mix” raises no flags. And unlike a PNG, a playlist contains structured text — specifically, track titles — which turns out to be exactly what you need.</p><p>The idea is this: hide a message in the letters of track titles, in an order determined by a shared secret. Anyone who knows the secret can decode it. Anyone who doesn’t sees a playlist.</p><p><strong>Why Track Titles?<br></strong>Audio steganography — hiding data in the audio signal itself — is a well-studied field. It’s also overkill for what I want to do, and it requires modifying files that Spotify controls. Track titles are different: they’re metadata, they’re human-readable, and every title in the Spotify catalog is already there waiting to be used.</p><p>The shared secret is three keywords. The sender and receiver agree on them in advance — “river”, “atlas”, “crow”, or anything else. The keywords are joined and hashed with SHA-256, producing a 64-bit seed for a pseudorandom number generator. That seed is what makes the extraction deterministic: given the same keywords and the same playlist, the decoder always recovers the same message. The keywords never appear in the playlist. They’re out-of-band, communicated separately, and without them the playlist is just a playlist.</p><p>The extraction mechanism works as follows: take a track title, strip everything that isn’t a letter, lowercase the result, and concatenate into a flat string. The PRNG first draws a count — how many letters to extract from this track — then draws that many position indices into the flat string. Each index selects one letter. The count is capped at two for message tracks, so each track contributes one or two letters to the payload.</p><p>The decoder runs the same process in reverse: same keywords, same playlist order, same PRNG sequence, same extracted letters. No computation beyond that.</p><p><strong>A Concrete Example<br></strong>Suppose the keywords are “river”, “atlas”, “crow” and the first three tracks in the playlist are “Stop Making Sense”, “Night Moves”, and “The One”. Their flat letter strings are “stopmakingsense” (15 letters), “nightmoves” (10 letters), and “theone” (6 letters). The PRNG was seeded once from the keywords before any tracks were touched. For “Stop Making Sense” it draws count=2, then positions 3 and 4 — yielding ‘p’ and ‘a’ from “stopmakingsense”. For “Night Moves” it draws count=1, position 3 — yielding ‘t’ from “nightmoves”. For “The One” it draws count=1, position 1 — yielding ‘h’ from “theone”. Those three tracks encode “path”. Across twenty tracks, a full short message emerges.</p><p>Encoding is the harder direction. Given a message, find a sequence of tracks where the PRNG-extracted letters spell it out. The tracks have to come from a real indexed pool — the Spotify catalog, or some subset of it — and they have to be findable without exhaustive search across millions of titles.</p><p><strong>The Cover Story Problem</strong><br>A steganographic carrier is only useful if it’s convincing. A playlist of randomly selected tracks from across genres, tempos, and decades looks like noise. Anyone paying attention would notice it doesn’t behave like a real playlist.</p><p>This is where the Camelot wheel comes in.</p><p>DJs use the Camelot wheel to mix tracks harmonically. It’s a clock-face diagram with 24 positions — 12 major keys and 12 minor keys arranged so that adjacent positions are harmonically compatible. A track in 8B (C major) mixes well with tracks in 7B, 9B, and 8A. Moving more than one or two steps around the wheel produces clashes that trained ears hear immediately.</p><p>The wheel gives the encoder a musicality constraint: prefer tracks whose Camelot code is compatible with the previous track. A playlist built this way flows. It sounds like someone made deliberate choices. The steganographic content is invisible because the cover story is plausible.</p><p>BPM is a secondary constraint. Tracks with similar tempos feel cohesive; large BPM jumps feel jarring. The encoder scores candidates on both Camelot compatibility and BPM proximity, picks the best available track that also satisfies the letter requirement, and moves on.</p><p>The result is a playlist that hides a message and sounds like it was curated.</p><p><strong>What Makes This Non-trivial<br></strong>The encoding step — find a track whose title yields the right letter, while also scoring well on Camelot and BPM compatibility — is a constrained search problem. At each position in the playlist, the encoder has a required letter and a previous track, and needs to find the best unused candidate from the pool that satisfies both.</p><p>The constraint is tighter than it looks. The PRNG state at each position determines not just which letter gets extracted from a given title, but how many letters are drawn and from which positions in the title. Two tracks with similar titles can yield completely different letters at the same PRNG state. Whether any track in the pool satisfies the requirement at a given position depends on the pool size and the distribution of title content across the catalog.</p><p>For small pools this fails regularly. A 26-track pool will routinely hit positions where no track yields the required letter. A real deployment needs thousands of indexed tracks — enough that at any PRNG state, the pool almost certainly contains at least one satisfying candidate at a reasonable musical score.</p><p>The search also has to be efficient. Scanning a pool of thousands of tracks at each position is feasible, but the PRNG state can’t be advanced speculatively — testing a candidate track without committing to it requires cloning the PRNG state before each probe. The implementation uses a custom Xorshift64 generator with a Clone() method for exactly this reason. Go’s standard math/rand.Rand doesn&#39;t support cloning, which is a silent footgun that only surfaces when you try to write constrained search.</p><p><strong>What I’m Building<br></strong>The system has five components: a Spotify indexer that pulls track metadata into a local SQLite database, an encoder that takes a message and keywords and produces a playlist, a decoder that takes a playlist and keywords and recovers the message, a web frontend for encoding and decoding interactively, and a Camelot wheel visualization that shows the musical structure of the generated playlist.</p><p>The indexer runs against the Spotify API and populates the database with track titles, artists, BPM, and musical key data. The encoder and decoder are deterministic given the same keywords — no state is stored anywhere except the playlist itself.</p><p>The next article covers the algorithm in detail: how the PRNG seeding works, how the constrained search finds satisfying tracks efficiently, and what the fallback strategy looks like when the pool can’t satisfy a requirement at a given position.</p><p><strong>“I Thought You Only Posted About AI”<br></strong>This project is partly an end in itself and partly a test case. I’ve been exploring a structured workflow for orchestrating small open models on complex tasks — what Steve Yegge calls GasTown, with a Mayor role that decomposes problems and a Polecat role that executes them. A real, non-trivial Go project with a clear spec and verifiable outputs is exactly the right environment to stress-test that workflow.</p><p>I’ve already built the core engine directly with Claude as a baseline. Now I’m learning some painful lessons about what happens when the Mayor makes bad decisions and the Polecat can’t push back. We’re gonna need a Witness for sure. More on that soon.</p><p><em>Originally published at </em><a href="https://github.com/lehmann314159/medium/blob/main/spotify_stego_article_1.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74c3db6cdf49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When the Easy Language Turned Out Not to Be]]></title>
            <link>https://medium.com/@lehmann314159/when-the-easy-language-turned-out-not-to-be-b38f8acc2b83?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b38f8acc2b83</guid>
            <category><![CDATA[linguistics]]></category>
            <category><![CDATA[learn-spanish]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 00:48:50 GMT</pubDate>
            <atom:updated>2026-06-08T00:48:50.113Z</atom:updated>
            <content:encoded><![CDATA[<h4>Local models aren’t reliable enough to generate Spanish morphology on the fly, but taking a page from the Finnish solution led to giving a page back via prompt engineering.</h4><p>I’ve been building Terve, a reading comprehension app that helps learners work through native-language texts. The Finnish version uses a morphological analyzer called Voikko as a deterministic tool layer: Voikko identifies the grammatical form of each word with certainty, and a local LLM explains what that form means in context. The LLM never guesses at grammar; it only contextualizes facts the tool has already established.</p><p>When I decided to add Spanish, my working assumption was that this architecture was Finnish-specific — a workaround for an unusually hard language with an unusually large LLM capability gap. Spanish, I thought, would be different. The morphology is simpler, training data coverage is strong, and I used to be near-fluent, which hopefully meant I can evaluate output quality directly. The plan was to let the LLM handle morphological analysis and use a light tool layer — maybe a dictionary API for authoritative lookups — rather than building a full deterministic sidecar.</p><p>That assumption turned out to be wrong. This is the story of how I found that out, what I built instead, and what the Spanish work unexpectedly fixed in the Finnish prompt engineering.</p><p><strong>What this covers:</strong></p><ul><li>A 16-case Spanish morphology harness across five models, and why I stopped it early</li><li>The architectural pivot: from LLM-primary to tool-primary, for different reasons than Finnish</li><li>Building the Spanish tool layer: spaCy, an enclitic decomposer, and a dropped dependency</li><li>The prompt engineering finding that transferred back to Finnish</li><li>Four production lessons from the deployment</li></ul><p><strong>The Eval Harness.</strong> Before building anything, I ran an evaluation harness: 16 Spanish test cases across five groups (verb morphology, ser/estar, command forms, noun/adjective agreement, reflexive and compound forms), scored against a rubric covering accuracy, explanation quality, and ambiguity handling.</p><p>Five models ran against the full suite. Scores out of 160:</p><ul><li>Qwen3.6–27B: 154</li><li>Qwen3.5–27B: 128</li><li>Qwen2.5–72B: 103</li><li>Qwen3–8B: 93</li><li>Qwen2.5–32B: 91</li></ul><p>Qwen3.6 dominated, pending confirmation from faster runs. I had faster non-qwen trials slated, but deferred them until after performing a quicker harness as a proxy for actual app usage. The faster harness had a small but noticeable drop in scoring, as well as a small but not encouraging drop in processing time. But I didn’t end up finishing either harness.</p><p>The decision to stop early came from sharp points in the failure modes rather than the scores (or the speed). Three things were consistent across all models:</p><p><strong>The ser/estar heuristic.</strong> Four of five models explained <em>estar</em> as “temporary” and <em>ser</em> as “permanent” without being prompted not to. This framing is simplistic — it fails on sentences like <em>está muerto</em> (death is not temporary) and <em>es joven</em> (youth is not permanent) — and it’s actively harmful for beginners who will apply it to new sentences. Only Qwen3.6 avoided it unprompted. The others could be corrected with a system prompt instruction, but the fact that it was the default across models was a signal about what I was working with.</p><p><strong>Clitic mechanics.</strong> Cases S11 ( <em>Dímelo</em>) and S15 ( <em>comprártelo</em>) — affirmative imperatives and infinitives with fused pronoun clitics — broke every model. Not partially. Completely. The models either ignored the clitics or described them incorrectly. This is a well-defined grammatical structure with deterministic rules. The LLM was generating its best guess at a form that a rule layer could have handled exactly.</p><p><strong>Latency under format pressure.</strong> The slow harness ran with comfortable inter-call delays. Production needs sub-ten-second responses in a reading panel where a user has clicked a word and is waiting. At warm temperatures, Qwen3.6 was running 20–30 seconds per case. That’s not usable, and there’s no prompt engineering fix for wall-clock time.</p><p>The harness was designed to answer “which model should we use?” The data was answering a different question: “should we be asking the LLM to do this at all?” The right call was to stop and pivot rather than finish collecting results that wouldn’t inform the actual decision.</p><p><strong>Lessons from Voikko.</strong> The Finnish architecture wasn’t a workaround for Finnish. It was the right pattern for any language where the LLM’s failure modes are structural rather than factual.</p><p>For Finnish, Voikko exists because Finnish morphology is genuinely hard and LLM coverage is thin. For Spanish, the reasoning runs differently: Spanish morphology is well-defined, the rules are regular, and the LLM failure modes I observed — clitic mechanics, the ser/estar heuristic — were cases where the LLM was generating plausible-sounding output that was structurally wrong. A deterministic layer doesn’t fix an LLM that lacks knowledge. It fixes an LLM that is applying the wrong heuristic to a problem that has an exact answer.</p><p>The generalized principle that came out of the Finnish work: identify what the LLM cannot do reliably for a given language, build a deterministic tool for exactly that gap, and let the LLM do everything else. For Finnish, the gap is the full morphological analysis — fifteen cases, possessive suffixes, complex verb forms. For Spanish, the gap is narrower but real: clitic decomposition and the structural forms that sit at the edges of what generalist training data covers well.</p><p><strong>The Spanish tool layer ended up with two components.</strong></p><ul><li><strong>spaCy with the </strong><strong>es_core_news_lg model</strong> handles the primary morphological analysis: lemma, part of speech, tense, person, number, mood, and dependency parse. For the cases the harness tested, it handles accent disambiguation correctly ( <em>sé</em> vs <em>se</em>, <em>él</em> vs <em>el</em>), separates <em>ser</em> and <em>estar</em> as distinct lemmas, and correctly identifies the grammatical subject in <em>gustar</em>-type constructions where Spanish inverts the expected argument structure.</li><li><strong>An enclitic decomposer</strong> handles fused verb+clitic tokens — the cases that broke every model in the slow harness. In Spanish, affirmative imperatives ( <em>Dímelo</em>), infinitives ( <em>verlo</em>), and gerunds ( <em>haciéndolo</em>) fuse the verb with one or more pronoun clitics into a single orthographic word. spaCy returns a space-in-lemma signal for these tokens — the lemma of <em>Dímelo</em> comes back as decir él - which serves as a reliable detection gate. The decomposer splits the token, re-analyzes each component, and labels each clitic&#39;s grammatical role. About thirty lines of Python.</li></ul><p>The decomposer completely fixed S11 and S15. Both scored 10/10 with tool support after scoring zero without it.</p><p>A third component I had planned to include was mlconjug3, a conjugation lookup library, pinned to scikit-learn==1.6.1 for compatibility. During the Claude Code deployment session, this failed at runtime with an error that no version pin could fix: mlconjug3’s bundled model was pickled against sklearn 0.24.2, and the Log SGD loss class it depended on had been removed entirely from newer sklearn versions. The fix was to drop mlconjug3. spaCy&#39;s es_core_news_lg provides tense, person, number, and mood natively; mlconjug3 was redundant for the vetting use case. The lesson worth keeping: when a library ships a pre-trained pickle, you are tied to the exact environment it was trained in, and that environment may be incompatible with your runtime in ways no version pin can repair.</p><p>With tool output supplying the morphological facts, the LLM’s job narrows to three things: confirm the reading fits the sentence context, select among ambiguous analyses when the tool returns multiple options, and produce a one-sentence explanation a beginner can apply.</p><p>Model selection for this role was also empirical. Qwen3.6–27B dense ran at 26 seconds per case — over the latency threshold even with tool support. A MoE variant at 4.7 seconds returned empty responses because the /no_think token I used to suppress extended reasoning suppresses all output on that architecture. Mistral Small 3.2 24B ran at 4.3 seconds average, 5.5 seconds maximum, and scored 149/160 on the vetting rubric after one system prompt iteration.</p><p>That iteration was the ser/estar fix. The original system prompt said, in effect, “do not use temporary or permanent to explain ser/estar.” Mistral ignored the bare prohibition and used the heuristic anyway. The fix was to replace the prohibition with explicit positive framing and worked examples:</p><ul><li>Use <em>ser</em> for intrinsic identity, origin, material, or classification — what something <em>is</em>. Example: <em>La puerta es de madera</em> describes what the door is made of, a defining characteristic.</li><li>Use <em>estar</em> for resultant states and conditions — how something has come to be. Example: <em>La puerta está abierta</em> describes the door as having been opened and now being in that state.</li></ul><p>With that framing, Mistral followed the rule on every case that had previously failed.</p><p>The MoE latency finding is worth preserving separately: MoE models with thinking capability don’t honor /no_think as a suppression token - they consume the full token budget on reasoning and produce no output. Raising num_predict to accommodate both thinking and response restores output but blows the latency budget. Dense models without thinking mode are the reliable path to sub-ten-second latency on consumer hardware at current model sizes.</p><p>The ser/estar framing finding — that positive framing with worked examples outperforms bare prohibition — applied directly to a problem in the Finnish system prompt that I hadn’t fully addressed.</p><p>The Finnish LLM is given rules about several grammatical traps: don’t explain adessive possession as spatial (“at me”), don’t use interior/exterior framing as the primary explanation for locative case choice, don’t describe the Finnish passive as agentless. These rules existed in the Finnish MCP system prompt — the interactive assistant version — but as bare prohibitions, not as framed explanations with worked examples.</p><p>After the Spanish work, I audited the Finnish prompt against the Spanish v2 structure and rewrote the prohibition sections to follow the same pattern: state what’s wrong, state the correct framing, give an example that illustrates the difference. The same session also added an override clause — the LLM is explicitly licensed to correct Voikko’s analysis when context makes a different reading clearly correct, with a requirement to state that it is doing so. This was already in the Spanish prompt because the tool layer is newer and less trusted than Voikko; it turned out the Finnish prompt needed it too.</p><p>Neither of these changes came from a Finnish-specific review. They came from working on Spanish and noticing that the solution structure generalized.</p><p>Deploying the Spanish driver produced four findings that belong in the record.</p><p>The mlconjug3 failure is covered above. The remaining three:</p><p><strong>Base image contents are invisible assumptions.</strong> The Spanish sidecar’s health check was written by analogy with the Finnish Voikko sidecar, which works because its base image happens to include curl. The python:3.11-slim image doesn&#39;t. The fix - using Python&#39;s own urllib.request - is cleaner than installing curl for a health check, but the failure mode only appeared at deployment.</p><p><strong>Partial refactors produce seams; the honest response is to name them.</strong> The Go refactor introduced a language.Driver interface and replaced the Voikko client in the main handler path. But the quiz, flashcard, and article-difficulty handlers call Voikko and the Finnish prompt builder directly, and the spec said not to touch them. The resolution was to keep both the driver and the Voikko client in the Handlers struct, with backward-compatible stubs. This is not a clean refactor. It&#39;s an accurate representation of where the abstraction boundary currently sits - Finnish-only features haven&#39;t been brought into the driver model yet. Naming that boundary clearly in comments is better than pretending it&#39;s resolved.</p><p><strong>Volume mounts for templates are a production footgun.</strong> The docker-compose file mounted ./terve/templates as a volume for local hot-reloading convenience. On the production server, which has only docker-compose.yml and .env, the app panicked at startup with a template glob error. The fix is to bake templates and static assets into the image and make volume mounts opt-in for development. The gap between &quot;works on the dev machine&quot; and &quot;works in production&quot; is mostly invisible assumptions - none of which show up in go build or a local compose run.</p><p>The app now runs in two languages, selected by a LANGUAGE environment variable at startup. Finnish uses Voikko. Spanish uses spaCy and the enclitic decomposer, with Mistral Small 3.2 24B as the vetting model. The language.Driver interface means adding a third language is a new driver and sidecar, not a refactor.</p><p>The open question for the next language is the same one that drove the Spanish work: where are the LLM’s structural failure modes, and how thin does the tool layer need to be to cover them? For Finnish and Spanish the answer was different in specifics but the same in kind. That’s probably the thing most worth carrying forward.</p><p><em>Code: </em><a href="https://github.com/lehmann314159/Terve2"><em>github.com/lehmann314159/Terve2</em></a><em>. Architecture current as of June 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b38f8acc2b83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Finnish Language Learning App with a Deterministic Core]]></title>
            <link>https://medium.com/@lehmann314159/medium-finnish-llm-architecture-article-md-at-main-lehmann314159-medium-3974000154ed?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3974000154ed</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[linguistics]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[finnish-translation]]></category>
            <category><![CDATA[homelab]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 21:59:17 GMT</pubDate>
            <atom:updated>2026-06-06T22:09:50.725Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>In one sentence: I found that open models struggled with Finnish, but partnered well with a deterministic engine that got around the proximity match problem.</strong></p><p>Finnish has fifteen grammatical cases (though only 6–8 get regular use). A single verb form can carry tense, person, number, negation, and mood simultaneously. The same noun root produces dozens of valid surface forms depending on what the sentence is doing — forms built by stacking suffixes that interact with vowel harmony, consonant gradation, and irregular stems. These aren’t edge cases; they appear throughout ordinary Finnish text.</p><p>I built a reading comprehension app for Finnish learners. The core design question turned out not to be which LLM to use, but where not to use an LLM at all.</p><p><strong>This article covers:</strong></p><ul><li>Why Finnish is structurally adversarial for LLMs — tokenization, semantic proximity, and coverage</li><li>What the Finnish-specialized model evaluation found, and why the results aren’t a verdict on those models</li><li>Why frontier APIs aren’t the answer for this use case</li><li>What the local model benchmark shows — and why the bar is lower once Voikko is in the picture</li><li>Voikko — the deterministic morphological analyzer that owns the fact layer</li><li>How the two-service architecture (Go + Python/FastAPI sidecar + Ollama) divides responsibility</li><li>A concrete walkthrough of a word-click interaction end-to-end</li><li>CEFR difficulty scoring as a second example of the deterministic layer in action</li><li>The phrase expansion affordance — a UX detail that only works because the deterministic layer is reliable</li><li>The reading corpus: 20 Finnish books from Project Gutenberg, embedded in the binary and organized by CEFR level</li><li>Why htmx was the right frontend choice</li><li>How the architecture changes for Spanish — and what that reveals about the general principle</li></ul><p>Morphological analysis is the process of breaking a word down into its grammatical components — identifying the base form, the part of speech, and every grammatical feature the word carries: case, tense, number, mood, and so on. For a language learning app, it’s the foundation everything else is built on. Get it wrong and the flashcards teach bad rules, the difficulty scoring misfires, and the lesson targeting breaks down.</p><p>Finnish cases work like prepositions in English, but instead of separate words before the noun — “to the house,” “in the house,” “from the house” — they’re suffixes attached directly to it: <em>taloon</em>, <em>talossa</em>, <em>talosta</em>. The meaning is equivalent; the encoding is completely different. Finnish has fifteen of these cases. German has four. English has effectively none in nouns. In practice, everyday Finnish speech uses a modest subset of the fifteen regularly, but real texts — especially literary ones — use all of them, and they interact with possessive suffixes, vowel harmony, and consonant gradation in ways that multiply the space of valid word forms considerably.</p><p>Finnish is also agglutinative, meaning it builds words by stacking suffixes rather than using separate function words. The word <em>taloissaan</em> is a single token carrying six distinct grammatical facts: the lemma (the base form, <em>talo</em> — house), part of speech (noun), case (inessive — location, “in”), number (plural), possessive suffix (3rd person singular — “his/her/its”), giving the surface meaning “in his/her/its houses.” In English that’s five words. In Finnish it’s one, and that one word is built by a set of interacting rules.</p><p>The straightforward approach to building the app: the user selects a word, phrase, or passage, it goes to the model, the model returns the grammatical analysis and an explanation. This works for the common forms that appear frequently in everyday text — basic nominative nouns, simple present-tense verbs. These forms are short, appear often, and LLMs handle them reliably.</p><p>The failure mode appears with forms that are grammatically regular but individually rare — a possessive suffix on a plural inessive of an irregular stem, or a verb combining passive, perfect, and conditional into one word. These constructions are correct Finnish and they appear in real texts, but no single form appears often enough in training data for LLM analysis to be consistent. The model sometimes produces the right analysis, sometimes a plausible-sounding but wrong one.</p><p>For a language learning app this is a specific kind of problem. A wrong case identification doesn’t just display incorrectly — it flows downstream into flashcards, lesson targeting, and the user’s developing mental model of the language. Finnish morphology is systematic: once a learner internalizes a pattern for one noun, they apply it to hundreds of similar ones. A wrong rule, reinforced by repeated incorrect flashcards, corrupts that generalization. Inconsistent accuracy is functionally the same as unreliable accuracy when correctness is a hard requirement.</p><p>The inconsistency has a structural cause. Three factors interact and compound each other.</p><p><strong>Tokenization.</strong> Most modern LLMs use BPE (byte-pair encoding) tokenizers trained on corpora dominated by English and other high-resource languages. A BPE tokenizer learns to split text into subword units that reflect the statistical patterns of its training data. For English, this works well — common words stay intact, rare words split at meaningful boundaries. For Finnish, it breaks down. A word like <em>taloissaan</em> carries six morphological facts in a single token, but a tokenizer trained on English-heavy data fragments it into subword pieces that don’t correspond to meaningful linguistic units. The model then has to reconstruct grammatical meaning from fragments — a harder task than reading coherent forms, and one it was never explicitly trained to do.</p><p>This is the key contrast with English prepositions. “In his houses” is three tokens in English, each independently meaningful. <em>Taloissaan</em> is one word in Finnish, fragmented into arbitrary pieces by a tokenizer that doesn’t know what it means.</p><p><strong>Semantic proximity.</strong> The same lemma appears across many distinct surface forms in Finnish. <em>Talo</em> alone generates over a dozen case forms before possessive suffixes multiply the space further. In embedding space, these forms often don’t cluster the way inflected forms do in morphologically simpler languages. Retrieval and in-context similarity methods that work well for English degrade for Finnish because the surface variation is too high relative to the underlying semantic content.</p><p><strong>Coverage.</strong> Finnish has approximately five million native speakers. It is not a low-resource language in an absolute sense, but it is significantly underrepresented in LLM training data relative to English, Spanish, French, or German. The morphological system is large and the training signal is thin — particularly for complex forms, which are individually rare even in a large Finnish corpus. Tokenization fragmentation makes it harder to learn morphological patterns from the Finnish text that does exist; low coverage means there isn’t enough signal to compensate.</p><p>German is a useful comparison. German has four cases, a large and well-represented presence in LLM training data, and enough morphological regularity that general-purpose models handle German grammar reliably. Finnish has fifteen cases, thin training coverage, and an agglutinative structure that fights the tokenizer. The structural difficulty isn’t just a matter of case count — it’s the combination of all three factors.</p><p>Before designing around the problem, the obvious question was whether a model specifically trained on Finnish might solve it. Finnish-specialized and multilingual open models exist. The hardware has 128GB unified memory — large models fit. The question was worth a structured answer.</p><p>Three models were evaluated against a rubric designed for the app’s actual use case: morphological analysis of real Finnish text, explanation quality in English, handling of the specific constructions that appear in the reading material. Pass threshold: 52/75. All three failed.</p><p><strong>Qwen2.5 72B</strong> (generalist) — 50/75. Came closest, but failed by inventing a correction to correctly-formed Finnish.</p><p><strong>EuroLLM-9B</strong> (EU multilingual specialist) — 30/75. Factual errors, not just morphological ones.</p><p><strong>Poro 34B</strong> (Finnish-first academic model) — categorical fail. Responded in Finnish rather than English.</p><p>Pass threshold: 52/75. All three failed.</p><p>EuroLLM-9B is an EU-funded model trained on 4 trillion tokens across all EU languages, instruction-tuned, with explicit Finnish coverage. Poro 34B is a Finnish-first model developed by LumiOpen, TurkuNLP, and Silo AI — an academic collaboration specifically targeting Finnish language capability. Both exist because there is a genuine gap in Finnish LLM coverage, and both represent serious work toward closing it.</p><p>Qwen2.5 72B came closest — 50/75, two points under the threshold — and its failure was instructive: it invented a third correction on a test sentence where only two were warranted, changing correctly-formed <em>kaupassa</em> (inessive: “in the shop”) to <em>kaupasta</em> (elative: “from the shop”). A model that confidently corrects correct Finnish is a liability in a language learning app.</p><p>A note on these results: this was a narrow evaluation conducted by someone still learning Finnish, against a rubric designed for one specific use case. EuroLLM and Poro are valuable open projects, and their scores here say nothing about their performance on other Finnish tasks. I’m grateful these models exist — without them, this question would have had no candidates worth testing. The evaluation was designed to answer one question: can any available model handle morphological analysis reliably enough to skip a deterministic layer? The answer was no.</p><p>That answer reframed the problem. The question wasn’t “which model handles Finnish best” — it was “Finnish morphology is actually quite regular; is there an existing deterministic engine that handles the structural facts, leaving the LLM to explain rather than analyze?” That line of thinking led to Voikko.</p><p>The remaining option is a frontier API — GPT-4o, Claude, Gemini. These models handle Finnish morphology substantially better than any local open model. They’re not the answer for this app for two reasons.</p><p>The first is expense. A reading app that calls an external API on every word selection — and a serious learner might make dozens of selections per session — accumulates cost at a rate that makes the tool impractical for sustained daily use. The economics don’t work.</p><p>The second is ownership. The app is designed to be a personal tool running on personal hardware. The reading history it accumulates — what texts the user is working through, what words they find difficult, what constructions they’re learning — is a detailed record of someone’s intellectual life. That data doesn’t need to leave the local network, and keeping it local isn’t just a privacy preference; it’s part of what makes the tool feel like yours rather than a service you’re renting.</p><p>The capability gap between frontier and local models is real. The architecture closes it for the specific task where it matters, without needing frontier access.</p><p>With the architecture settled — Voikko handles morphological analysis, the LLM explains Voikko’s output — the remaining question was which local model to use as judge. The role is narrower than full analysis: the model receives Voikko’s output as established fact and explains it in plain English. Explanation quality and latency are what matter; morphological accuracy from the model’s own knowledge is irrelevant because the model is never asked for it.</p><p>The app includes a benchmark harness for this — a standalone Go binary baked into the Docker image, runnable via docker exec terve ./benchmark -models model1,model2. It runs eight Finnish test cases of graduated complexity against each candidate model, measures latency using Ollama&#39;s internal eval_count / eval_duration fields rather than wall-clock time, and outputs a multi-model comparison table with per-test tokens/second. Full structured responses are printed at the end for manual review.</p><p>Results on current hardware (ASUS GX10, GB10 Grace Blackwell, 128GB unified memory):</p><p><strong>Qwen2.5 32B Q4</strong> — ~8,300ms average latency, ~9.8 tok/s. Production model.</p><p><strong>Qwen2.5 32B Q8</strong> — ~13,200ms average latency, ~6.1 tok/s. 37% slower, 9x worse cold-start, output identical to Q4.</p><p><strong>Qwen3 32B</strong> — ~42,000ms average latency. Best quality ceiling, unusable latency for interactive use.</p><p><strong>Llama4 Scout</strong> — crashed Ollama. 67GB exceeded available memory.</p><p>The Q4 vs Q8 comparison is the clearest result: across all eight test cases, translations and morphological breakdowns were word-for-word identical between quantization levels. At 32B parameters, linguistic knowledge is largely quantization-invariant. The Q8 penalty — 37% latency increase, 9x worse cold-start, higher memory pressure — produced no measurable quality gain.</p><p>Current production model: Qwen2.5 32B Q4. The harness stays in the image so model selection can be re-evaluated as new models become available.</p><p>Voikko is a Finnish morphological analyzer — open source, built specifically for Finnish linguistics, FST-based (finite-state transducer). It applies the formal rules of Finnish morphology directly, without inference or approximation. Given any Finnish word form, it returns the lemma, part of speech, and all grammatical features: case, number, person, tense, mood, possessive suffixes, comparative markers. It either returns a correct analysis or returns nothing. It does not guess.</p><p>The division of labor follows directly: Voikko owns the morphological facts, the LLM explains them. The LLM receives Voikko’s output as ground truth and is asked only to reason about it — why this form is used here, what the learner should notice, how it relates to other constructions they’ve seen. It is never asked to perform morphological analysis from its own knowledge.</p><p>The app runs as four cooperating Docker Compose services:</p><ul><li><strong>Go backend</strong> — coordinates everything: routing, template rendering, OAuth, and calls to the other services</li><li><strong>Voikko sidecar</strong> — a persistent Python/FastAPI service wrapping Voikko for morphological analysis</li><li><strong>Ollama</strong> — serves Qwen2.5 32B for explanation and generation</li><li><strong>SQLite</strong> — user model, flashcards, and progress</li></ul><p>The browser talks only to the Go backend via htmx; the backend calls the other services as needed.</p><p><strong>Go backend</strong> handles routing, template rendering, OAuth (Google and GitHub), and coordination between services. Most interactions are server-driven — user clicks, server returns an HTML fragment, htmx swaps it into the DOM.</p><p><strong>htmx</strong> was a deliberate choice. The app’s interactions are almost entirely server-driven request-response cycles: click a word, get an analysis panel; add a flashcard, get a button state update. htmx handles this pattern cleanly without a build pipeline, without npm, and without a frontend framework to maintain. One vanilla JS module (~50 lines) handles multi-word phrase selection via the browser’s Selection API, firing an htmx request on mouseup. Everything else is Go templates and htmx attributes. One language throughout the stack; the frontend is a thin rendering layer over server logic.</p><p><strong>Voikko sidecar</strong> is a persistent Python/FastAPI service wrapping the Voikko library. Persistent matters here: spawning a new Python process per request costs 250–350ms on this hardware (Python startup plus FST load), which is noticeable on every word selection in an interactive reading flow. Running it as a persistent service inside the Docker network brings per-analysis latency to single-digit milliseconds.</p><p><strong>Ollama</strong> runs Qwen2.5 32B on local hardware. With the deterministic layer handling all morphological facts, the model’s role is narrowed to contextual explanation and generation — tasks where its output quality at Q4 quantization is sufficient and its latency is acceptable.</p><p>A concrete example. The user clicks <em>taloissaan</em> in a reading text.</p><ol><li>The Go backend calls the Voikko sidecar with the word.</li><li>Voikko returns deterministically: lemma <em>talo</em> (house), noun, inessive case (plural), 3rd person singular possessive suffix — “in his/her/its houses.”</li><li>The backend constructs a prompt with this analysis as given fact: <em>“The word ‘taloissaan’ has been analyzed as the plural inessive of ‘talo’ (house) with a 3rd-person singular possessive suffix, meaning ‘in his/her/its houses’. The sentence context is: [sentence]. Explain why this form is used here and what a learner should notice.”</em></li><li>Qwen2.5 returns an explanation — the relationship between plural inessive and possessive suffixes, why Finnish encodes possession this way rather than using a separate pronoun, what other nouns follow the same pattern.</li></ol><p>The analysis panel shows the Voikko data (always correct) and the LLM explanation (grounded in the verified analysis). The LLM cannot produce a wrong case identification here because it wasn’t asked to identify the case — it was told what the case is. Confabulation on the morphological facts is structurally blocked.</p><p>The same flow applies whether the user selects a single word, a phrase, or a full paragraph. Voikko analyzes each token; the LLM explains the whole selection in context.</p><p>The same principle shows up in text difficulty rating. The app sources reading material from YLE Selkosuomi, YLE regular news, and Project Gutenberg, and needs to assign each text a CEFR level (A1 through C2) to match content to the user’s current ability.</p><p>The scoring pipeline runs entirely on Voikko output, with no LLM involved:</p><ul><li>Proportion of non-nominative case forms in the text</li><li>Number of distinct grammatical cases present</li><li>Incidence of possessive suffixes</li><li>Presence of complex verb forms</li></ul><p>A text heavy in nominative-only forms with simple present-tense verbs scores A1. A text with consistent use of rare cases, possessive suffixes, and compound verb forms scores C1 or higher. The signal is structural and computable — a direct function of the same morphological facts Voikko produces for word-click analysis. The LLM isn’t needed and isn’t used.</p><p>This is the deterministic layer doing real work in a second part of the system, not just compensating for one specific LLM failure.</p><p>When a user selects part of a noun phrase — say, just the noun without its modifying adjective — Voikko detects that the selection boundary cuts across a grammatical unit. The app highlights the full phrase and shows a subtle “Expand?” affordance. The user keeps control; the hint is available.</p><p>This only works because the morphological analysis is reliable. A hint system built on LLM analysis would carry the same inconsistency problem as the analysis itself — expansion suggestions that are sometimes wrong are worse than no hint at all. The feature exists because Voikko’s output can be trusted to drive UI behavior.</p><p>The app ships with 20 Finnish books from Project Gutenberg, embedded directly in the Go binary via //go:embed and organized by CEFR level:</p><p><strong>A1</strong> — Topelius <em>Lukemisia lapsille</em> (7 volumes) <strong>A2</strong> — Härkönen folk tales, Grimm fairy tales (Finnish), Andersen fairy tales (Finnish) <strong>B1</strong> — <em>Liisan seikkailut ihmemaassa</em> (Alice in Wonderland), <em>Pekka Poikanen</em> (Peter Pan) <strong>B2</strong> — Larin-Kyösti, Rauanheimo, Juhani Aho <em>Yksin</em><strong>C1</strong> — Minna Canth, Runeberg <em>Vänrikki Stoolin tarinat</em>, Aleksis Kivi <em>Seitsemän veljestä</em></p><p>Embedding in the binary keeps deployment simple — one image, no external corpus dependency, works on first launch. CEFR ratings are assigned at import time by the LLM sampling the first 800 characters of each text. This is one of the few places in the app where LLM output isn’t fact-critical — an approximate difficulty rating is useful even if occasionally off by one level, and a human sanity check pass can correct outliers.</p><p>The A1 weighting is deliberate: new learners need sustained reading volume at their level, and Topelius provides it.</p><p>Finnish was a useful first case because the argument for a deterministic layer is hard to avoid — morphological complexity is high, LLM failure modes are concrete, and Voikko exists as a mature solution.</p><p>Spanish is next, and the architecture will be different. Spanish morphology is more regular than Finnish, and LLMs are trained on vastly more Spanish text. The LLM reliability floor for Spanish morphological analysis is substantially higher. The deterministic layer will likely be thinner — possibly covering only irregular verb forms and a handful of edge cases, rather than the full pipeline Voikko handles for Finnish.</p><p>The question for Spanish isn’t “do we need a deterministic layer” but “how deep does it need to be.” That’s determined by the same test: where does wrong analysis cause downstream damage, and how reliably does the LLM handle those cases. Finnish required a deep deterministic layer. Spanish may require a shallow one. A future language might require none.</p><p>The pattern isn’t “always use a deterministic sidecar.” It’s “identify your LLM’s reliability floor for the specific task, and build deterministically for exactly that gap.” Finnish made that principle unavoidable. Spanish will test whether it generalizes.</p><p><em>Code: </em><a href="https://github.com/lehmann314159/Terve2"><em>github.com/lehmann314159/Terve2</em></a><em>. Architecture current as of mid-2026.</em></p><p><em>Originally published at </em><a href="https://github.com/lehmann314159/medium/blob/main/finnish_llm_architecture_article.md"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3974000154ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Qualitative Benchmark For Open Models]]></title>
            <link>https://medium.com/@lehmann314159/a-qualitative-benchmark-for-open-models-373762fd2335?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/373762fd2335</guid>
            <category><![CDATA[small-model]]></category>
            <category><![CDATA[llm-benchmarks]]></category>
            <category><![CDATA[open-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 00:56:13 GMT</pubDate>
            <atom:updated>2026-03-31T13:57:36.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Benchmark Is a Snapshot. I Wanted a Portrait.</h3><p>Most model evaluations answer a narrow question: given this input, did the model produce the right output? That’s useful. But it doesn’t tell you how the model <em>worked</em> — whether it read before it wrote, whether it named its assumptions, whether it recognized when something was wrong and what it did next.</p><p>For the kind of agentic coding work I do, those process questions matter as much as the output. So I built a different kind of evaluation. This article shows you what I actually found — not just the scores, but the evidence.</p><h3>Why I Built This</h3><p>I run a local AI lab on an ASUS Ascent GX10 — an NVIDIA GB10 Grace Blackwell system with 128GB unified memory — serving open models via Ollama. The use case I’m building toward is Steve Yegge’s GasTown: a workflow where Claude acts as the orchestration layer, authoring and refining prompts, then handing them to an open model via OpenCode for execution. Claude reasons about the problem; the open model does the implementation work. For more about GasTown, check out <a href="https://steve-yegge.medium.com/welcome-to-gas-town-4f25ee16dd04">https://steve-yegge.medium.com/welcome-to-gas-town-4f25ee16dd04</a></p><p>Before committing to a model for that workflow, I wanted evidence about <em>process quality</em>, not benchmark scores. SWE-bench tells me whether a model can patch a GitHub issue. It doesn’t tell me whether the model reads before it writes, whether it surfaces ambiguities, or whether it diagnoses friction correctly. Those are the behaviors that matter when Claude is handing off a carefully engineered prompt and expecting reliable execution.</p><p>The secondary goal is reusability. Everything is documented — the task corpus, scoring rubric, and refinement briefs. Anyone can apply the same harness to their own model sets and task domains.</p><h3>The Setup</h3><p>I ran 27 sessions across three open models, each paired with Claude-authored prompts via OpenCode:</p><ul><li><strong>Qwen3-Coder-Next</strong> (~51GB) — a hybrid MoE model with ~3B active parameters per token, specifically trained on agentic coding trajectories. My primary coding model.</li><li><strong>Qwen3-Coder-30B-A3B</strong> (~20GB) — smaller sibling of the above, same family, same training philosophy.</li><li><strong>Devstral Small 2</strong> (~14GB) — Mistral’s agentic coding specialist, December 2025 release, 68% SWE-Bench Verified. Different training lineage from the Qwen models.</li></ul><p>Nine tasks per model, all implemented in Go (chosen because go build provides an unambiguous pass/fail signal), organized in three groups:</p><p><strong>Group 1 — Clean Path.</strong> Well-specified tasks, no intentional friction. Word frequency counter, directory inventory tool, INI config parser library. These establish baseline capability.</p><p><strong>Group 2 — Underspecified.</strong> One dimension of the spec is deliberately vague. CSV summarizer (what does “continuous column” mean?), duplicate file finder (what defines “duplicate”?), HTTP request logger middleware (how do you capture the response status code?). These surface whether models narrate their interpretation or silently adopt one.</p><p><strong>Group 3 — Friction.</strong> A predictable obstacle is built in — a module name mismatch, a phantom third-party dependency, inconsistent input data. These reveal recovery behavior: does the model recognize the problem, diagnose it correctly, and fix it appropriately?</p><h3>The Two-Prompt Design</h3><p>Each of the three most technically demanding tasks was run <em>twice</em> per model: once with an original prompt, once with a Claude-refined version. The delta between runs is the prompt sensitivity score — the primary signal for the GasTown workflow question.</p><p>Here is an example of what that looks like in practice. The G1–3 task (INI Config Parser) original prompt:</p><blockquote>Build a Go library package (not a CLI tool) that parses INI-format configuration files. The library must expose a Parse(r io.Reader) (Config, error) function. Config must support a Get(section, key string) (string, bool) method. The parser should handle: section headers in [brackets], key=value pairs, comments on lines starting with ; or #, blank lines, and keys that appear before any section header (the global section). Include at least 5 unit tests covering both normal operation and edge cases.</blockquote><p>The refined version, after Claude’s prompt engineering:</p><blockquote>Before writing any code, state your implementation plan: list the major subtasks you’ll complete and the key design decisions you’ll make.</blockquote><blockquote>Then build a Go library package (not a CLI tool) that parses INI-format configuration files. Requirements:</blockquote><blockquote>- The library must expose a Parse(r io.Reader) (Config, error) function.<em> </em>- Config must support a Get(section, key string) (string, bool) method.<em> </em>- The parser must handle: section headers in [brackets], key=value pairs, comments on lines starting with ; or #, blank lines, and keys that appear before any section header. Keys before any section header belong to the global section, accessible via Get(&quot;&quot;, key).<em> </em>- Place all library files at the module root, not in a subdirectory. Use ini as the module name.<em> </em>- Include at least 5 unit tests covering both normal operation and edge cases. Use the standard testing package only.</blockquote><p>One sentence added at the top. Several spec ambiguities resolved (the global section sentinel, the module layout). The refinement brief documents every change and the reasoning behind it.</p><h3>Scoring</h3><p>Three dimensions, scored 0–2, from the observable artifact trail only. No thinking blocks, no inferred intent. If it wasn’t visible in the session transcript, it didn’t count.</p><ul><li><strong>Decomposition Quality:</strong> Did the model produce a visible plan before touching any files? On underspecified tasks: did it name its interpretations before coding? On friction tasks: did it read the provided scaffolding before writing?</li><li><strong>Execution Fidelity:</strong> Did it complete what it set out to do, with nothing silently dropped?</li><li><strong>Recovery Behavior</strong> (Group 3 only): When it hit the designed obstacle, did it recognize it, correctly diagnose it, and fix it appropriately?</li></ul><h3>How This Compares to Existing Benchmarks</h3><p>Two benchmarks the technical reader will reach for: SWE-bench and ProjectEval.</p><p><strong>SWE-bench</strong> presents models with real GitHub issues against real codebases. Pass/fail is determined by whether the patch makes the tests pass. It’s excellent at measuring outcome quality on inherited context — exactly the “can this model fix real bugs in real codebases?” question. What it doesn’t measure is process. You don’t know whether the model read the relevant files before writing, whether it diagnosed the root cause or patched around a symptom, or whether it planned at all. You know whether the tests passed.</p><p><strong>ProjectEval</strong> evaluates full multi-file project generation across three prompt levels: natural language, NL with checklists, and code skeletons. That three-level structure is the closest analogue to this harness’s original vs. refined prompt design — but with an important difference. ProjectEval’s levels are fixed inputs defined by the benchmark designers, applied uniformly across all models. The refined prompts in this harness are Claude’s actual considered engineering output: model- specific, task-specific, documented in refinement briefs that explain every choice. ProjectEval measures how models respond to a fixed quality gradient. This harness measures how each model responds to a specific collaborator’s prompt engineering — which is closer to what actually happens when Claude and an open model work together.</p><p>Neither benchmark has a prompt sensitivity signal. Neither asks: does this model perform better when Claude refines the prompt, and by how much, and on which dimensions? That’s the question this harness was built to answer.</p><p>This baseline study doesn’t compete with either benchmark. It measures something they don’t. The inherited-context harness I’ve identified as the next experiment will start to overlap with SWE-bench’s domain.</p><h3>The Scorecard</h3><p>Full results across all 27 original-prompt runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5KbbrfF0wn3UE2nUq3MpA.png" /></figure><p>The aggregate looks tidy. The findings are where it gets interesting.</p><h3>What the Sessions Revealed</h3><h3>Finding 1: The Decomposition Wall</h3><p>Across 27 original-prompt sessions, models produced visible planning before their first tool call exactly once. Qwen3-Coder-30B wrote a five-item plan on its very first task and never did so again across the remaining eight. Every other session across all three models began the same way:</p><p>A tool call. Then code. Then tests. Then done.</p><p>Here is the complete Phase 1 output for Qwen3-Coder-Next on G1–3 — a clean-path task with a clear, unambiguous spec:</p><blockquote>(nothing)</blockquote><p>The model’s first action was a write tool call to ini.go. The implementation that followed was fully correct. Decomposition 0.</p><p>This is not a capability gap. The refined prompt runs proved otherwise. Add one sentence — <em>“Before writing any code, state your implementation plan”</em> — and the same model produced this:</p><blockquote>## Implementation Plan</blockquote><blockquote><strong>Major subtasks:</strong><em> </em>1. Create the main ini.go file with Config struct and Parse function<em> </em>2. Implement parsing logic for sections, key-value pairs, comments, and blank lines<em> </em>3. Create comprehensive unit tests in ini_test.go<em> </em>4. Initialize the Go module with name ini</blockquote><blockquote><strong>Key design decisions:</strong><em> </em>— Use a map[string]map[string]string structure for storing sections and their key-value pairs<em> </em>- Handle the global section (keys before any header) with an empty string &quot;&quot; as the section name<em> </em>- Return (string, bool) from Get to handle missing keys gracefully<em> </em>- Support both ; and # comment styles<em> </em>- Trim whitespace from section names, keys, and values</blockquote><p>Decomposition 2. Maximum possible delta: +2.</p><p>In the nine refined runs, eight produced some visible planning where the original had produced none. Two reached the maximum Decomposition score of 2; six landed at 1. One sentence, reliably, broke the silence — though what emerged ranged from a brief task list to a substantive design statement depending on the model and task. The planning instruction worked; it didn’t always work fully.</p><p><strong>The lesson:</strong> Open models don’t plan visibly because nothing asks them to. The capability is there. The default is not.</p><h3>Finding 2: Identical Scores, Different Models</h3><p>After nine tasks each, Qwen3-Coder-Next and Qwen3-Coder-30B finished with identical totals: Decomposition 2, Execution Fidelity 16/18. They are not the same model.</p><p><strong>Next’s two execution failures</strong> were quality gaps. On G2–2 it introduced a concurrent map write race condition — goroutines writing to a shared map without mutex protection. Tests passed non-deterministically during the session; they failed post-capture. On G2–3 it declared completion without creating a go.mod, meaning the delivered artifact did not build externally. Both implementations were architecturally sound. Both artifacts were incomplete.</p><p>Next also had recurring write-tool parameter confusion (using fileContent instead of content across multiple sessions), consistently attempted a non-existent run tool before falling back to bash, and deferred go mod init until the first test failure on all nine original-prompt runs.</p><p><strong>30B’s two execution failures</strong> were subtask drops. On G3–1 it delegated via the task tool to a sub-agent — and the sub-agent wrote one test instead of the required three because the constraint wasn’t propagated through the delegation prompt. On G3-3 it wrote zero tests. No infrastructure, no file, nothing.</p><p>30B was operationally the cleanest model in the harness: five consecutive sessions from G1–2 through G2–3 with zero LSP errors, zero tool failures, and first-write correct implementations. It initialized modules proactively on every single session.</p><p><strong>Where they diverge most sharply is Recovery.</strong> G3–2 provided a starter project importing github.com/fake-vendor/gotemplate v1.2.0 — a package that doesn’t exist. The correct fix uses Go’s standard library text/template.</p><p>Here is what Next did: read main.go, recognized the phantom import, removed it, replaced the implementation with text/template, cleared go.sum. No go get attempts. No compile failures. Recovery 2.</p><p>Here is what 30B did: ran mkdir -p go-template-renderer, created a fresh module inside it, built a parallel correct implementation, and never touched the starter project. The LSP diagnostic surfaced ERROR could not import github.com/fake-vendor/gotemplate during one of 30B’s write calls. The model saw it and ignored it. The unmodified starter means go build ./... from the working directory root fails. Recovery 0.</p><p>Same task. Same prompt. One model diagnosed and fixed the problem. One bypassed it while the error was visible on screen.</p><h3>Finding 3: The G2 Silence</h3><p>All three models scored Decomposition 0 on every original-prompt Group 2 task. All three silently adopted the most defensible interpretation every time and executed it correctly.</p><p>On G2–2 (Duplicate File Finder), the spec says “find duplicate files” without defining “duplicate.” Three interpretations exist: same filename, same size, same content. The fixture included a specific discriminator: data.bin files with identical size but different content. A size-match tool reports them as duplicates; a content-hash tool does not.</p><p>All three models chose content hashing. All three correctly excluded data.bin. None stated their choice before writing.</p><p>On G2–3 (HTTP Request Logger), logging the HTTP response status code requires wrapping Go’s http.ResponseWriter to intercept WriteHeader() — a non-trivial design decision the prompt deliberately didn’t mention. All three models implemented it correctly. None identified it as a design choice in Phase 1.</p><p>This is a genuine tension worth sitting with. The harness penalizes silent interpretation — correctly, because in production a model that silently chooses <em>wrong</em> is worse than one that surfaces its choice. But these models consistently chose right. Whether that reflects model quality or fixture design not being adversarial enough is an open question the next iteration should probe with ambiguities where a silent wrong choice is actually possible.</p><h3>Finding 4: Two Kinds of Instruction</h3><p>The most practically useful finding in the sensitivity data is a distinction I didn’t anticipate going in.</p><p>A <strong>structural instruction</strong> tells the model what to do before coding: <em>“Read these files. Check this directory.”</em></p><p>A <strong>reflective instruction</strong> asks the model to reason out loud: <em>“State your interpretation of each design decision before writing.”</em></p><p>G2–3 (HTTP Logger) tested this directly. The refined prompt added an explicit instruction to state interpretations on log format, error handling, and status code capture before writing. Here is what each model produced in Phase 1:</p><p><strong>30B</strong>, before any tool call:</p><blockquote>“## Design Decisions</blockquote><blockquote>1. <strong>Log Format</strong>: I’ll use a space-separated format with timestamp, method, path, status code, and response time as specified: 2026-01-01T12:00:00Z GET /api/v1 200 12.3ms</blockquote><blockquote>2. <strong>Error Handling</strong>: For log file opening errors, I’ll log to stderr and return a wrapped handler that continues processing.</blockquote><blockquote>3. <strong>Response Status Code</strong>: I’ll use a custom ResponseWriter wrapper to capture the status code from the underlying handler.”</blockquote><p>Decomposition 2. All three ambiguities named with correct choices before any tool call, including explicit identification of the WriteHeader() intercept mechanism.</p><p><strong>Next</strong>, after two exploration commands:</p><blockquote>“<strong>Design Decisions:</strong></blockquote><blockquote>1. <strong>Log Format</strong>: 2026-01-01T12:00:00Z GET /api/v1 200 12.3ms</blockquote><blockquote>2. <strong>Error Handling</strong>: If the log file cannot be opened, return an error and fail fast.</blockquote><blockquote>3. <strong>Status Code Capture</strong>: Wrap http.ResponseWriter with a custom responseWriter that intercepts WriteHeader() and Write() to capture the status code before it’s sent.”</blockquote><p>Decomposition 1. Correct on all three, including explicit naming of the intercept mechanism. Came after two tool calls rather than before any.</p><p><strong>Devstral</strong>, before its first write:</p><blockquote>“Understood. Let me create a Go HTTP middleware function that logs incoming requests to a file. I’ll write the code, tests, and then make sure it compiles and tests correctly.”</blockquote><p>Then it wrote code. Decomposition 0. Identical to its original-prompt score.</p><p>The explicit design-decision instruction produced Decomp 2 from 30B, Decomp 1 from Next, and Decomp 0 from Devstral. Devstral responds reliably to structural instructions — tell it to read before writing, and it reads. Ask it to articulate its reasoning, and it doesn’t. That distinction shapes how prompts should be written for each model.</p><h3>Finding 5: The Designed Failure and Three Strategies</h3><p>G3–3 (CSV Merger) was built to fail silently. The input directory contained three CSV files with inconsistent column headers:</p><ul><li>a.csv: first_name,last_name,email</li><li>b.csv: firstname,lastname,email</li><li>c.csv: name,email_address <em>(two columns only)</em></li></ul><p>A naive merge — take the first file’s headers, append all rows — produces a syntactically valid CSV that passes go build and go test and looks correct until you read it carefully. Grace Gutierrez ends up in the first_name column with last_name empty, because c.csv’s single name field maps positionally to the first column.</p><p>All three models hit this failure on the original prompt. None read the input files before writing. All scored Recovery 0.</p><p>The refined prompt added two things:</p><blockquote>“Sample CSV files are provided in the input/ directory. Read and examine all of them before writing any code.”</blockquote><blockquote>“The input files may have inconsistent column headers. Your tool must either normalize headers and produce a correctly merged output, or detect the inconsistency and exit with a clear error message. Silent column misalignment is not acceptable.”</blockquote><p>All three models read the files. All three recognized the inconsistency. Then their paths diverged.</p><p><strong>Qwen3-Coder-Next</strong> chose detect-and-halt with fuzzy normalization: strip separators, lowercase, compare. If normalized headers don’t reconcile, exit with a clear error.</p><pre>Inconsistent column headers detected in ../input/c.csv<br>Expected headers: [email firstname lastname]<br>Found headers: [name email_address]<br>exit status 1</pre><p>Recovery 2. Verification pass. The simplest viable strategy, correctly implemented.</p><p><strong>Qwen3-Coder-30B</strong> read all three files and, before writing any Go code, created scripts/csv_normalizer.py. The script correctly documented the full mapping problem:</p><pre># Mapping for c.csv: completely different schema<br># name -&gt; first_name<br># email_address -&gt; email<br># (no last_name field)</pre><p>The Python script had the right answer. Then 30B wrote the Go implementation:</p><pre>func processRecord(record []string) []string {<br>    processed := make([]string, len(unifiedHeaders))<br>    for i, value := range record {<br>        if i &lt; len(processed) {<br>            processed[i] = value<br>        }<br>    }<br>    return processed<br>}</pre><p>Pure positional mapping. c.csv’s name field (“Grace Gutierrez”) lands in column 0 (first_name). Column 1 (last_name) is empty. The correct mapping from the Python script was never implemented in Go.</p><p>Recovery 1. The analysis was right. The implementation contradicted it.</p><p><strong>Devstral Small 2</strong> chose the most ambitious strategy: a hardcoded lookup table mapping every variant column name to a canonical form:</p><pre>columnMappings := map[string]string{<br>    &quot;first_name&quot;:    &quot;first_name&quot;,<br>    &quot;firstname&quot;:     &quot;first_name&quot;,<br>    &quot;name&quot;:          &quot;first_name&quot;,<br>    &quot;last_name&quot;:     &quot;last_name&quot;,<br>    &quot;lastname&quot;:      &quot;last_name&quot;,<br>    &quot;email&quot;:         &quot;email&quot;,<br>    &quot;email_address&quot;: &quot;email&quot;,<br>}</pre><p>The architecture was correct. The unit tests exercised the inconsistent-header error path — the only model in the harness to do so. Then, in the merge loop:</p><pre>reader.ReadAll() // Skip header</pre><p>ReadAll() reads <em>all</em> remaining records, not just the header row. The subsequent reader.Read() loop found nothing. Output: a correct header, zero data rows.</p><p>Recovery 1. One API call from correct. reader.Read() skips one record; reader.ReadAll() consumes everything.</p><p>Three models. Three strategies. Three different failure modes — all invisible in simple pass/fail scoring. 30B’s failure is an analysis-implementation gap: it understood the problem and didn’t translate the understanding into code. Devstral’s failure is an API misuse under architectural correctness: the design was right and one function call was wrong. Next’s instinct was the simplest approach that actually worked.</p><h3>The Prompt Sensitivity Answer</h3><p>Across nine refined runs, Decomposition Quality improved by a combined +10 points across all three models. Execution Fidelity improved by +2. Recovery improved by +4.</p><p>Next ΔDNext ΔENext ΔR30B ΔD30B ΔE30B ΔRDev ΔDDev ΔEDev ΔRG1–3<strong>+2</strong>0 — +10 — +10 — G2–3+1+1 — <strong>+2</strong>0<strong>–0</strong>0 — G3–3+10<strong>+2</strong>+10+1+1+1+1<strong>Σ+4+1+2+40+1+2+1+1</strong></p><p>Decomp is the most responsive dimension because it has the most room — a universal floor of 0 across all 27 original-prompt sessions, directly addressable with an explicit instruction. Execution Fidelity was already near ceiling for Next and 30B; targeted constraints (like the explicit self-contained build requirement that closed Next’s missing go.mod gap on G2-3) address specific failures, but general prompting pressure doesn’t lift an already-high Exec score.</p><p>Recovery improvement tops out at model-level ceilings that prompting alone can’t close. The same read-before-write instruction produced Recovery 2 from Next and Recovery 1 from both 30B and Devstral on G3–3. That gap is not a prompt engineering problem.</p><p>The structural vs. reflective instruction distinction maps cleanly onto the models:</p><p>Structural instructionReflective instruction<strong>Next</strong>Decomp 1Decomp 2<strong>30B</strong>Decomp 1Decomp 2<strong>Devstral</strong>Decomp 1Decomp 0–1</p><p>Next and 30B both reach Decomp 2 when explicitly asked to reason out loud. Devstral reaches Decomp 1 when told to do something specific first, and doesn’t improve on G2 tasks regardless of what the reflective prompt says. In the GasTown workflow, this means prompts for Devstral should embed structural constraints rather than asking for design narration.</p><h3>Action Items</h3><p><strong>GasTown candidacy.</strong> This was a qualifying trial, not a final selection. Qwen3-Coder-Next and Qwen3-Coder-30B-A3B both advance. Their aggregate scores are identical; their profiles are complementary. Next has the stronger Recovery ceiling and responds well to reflective planning prompts — when asked, it plans at high quality. 30B is operationally cleaner, more consistent across task types, and produced the strongest G2 planning in the dataset under refined prompts. The inherited-context experiment will tell me more about which profile matters most in practice.</p><p>Devstral does not advance for GasTown work at this stage. Its resistance to reflective prompting and recurring implementation instability make it the wrong fit for a workflow that depends on reliable process quality. At ~14GB it remains interesting for other use cases, and I’d revisit it on a future harness generation.</p><p><strong>Next experiment: inherited context.</strong> Every run in this harness started from a clean slate. Real agentic coding work doesn’t — it hands a model a codebase with existing patterns, naming conventions, and abstractions it needs to respect. Whether a model reads and integrates that context before adding to it is arguably the most important behavior for the work I’m doing, and this harness gave no signal on it. That’s the next thing to build.</p><p><strong>New models to run.</strong> Qwen2.5-Coder 32B is already in my fleet — a different generation of the same family, a natural comparison point for whether the Qwen3 generation gains justify the size. DeepSeek-Coder-V3 brings a completely different training lineage and strong SWE-Bench numbers; it’s the contrast case the harness was designed to accommodate. A future Devstral generation is worth a run if Mistral continues the pace of iteration between their 2505 and 2512 releases.</p><p><strong>The open questions this leaves.</strong> Single-shot performance and inherited-context performance may rank models differently. Multi-turn compliance — does the model respect explicit constraints across a sequence of subtasks — is unmeasured. The G2 ambiguity design may need sharper fixtures: all three models chose correctly and silently on every underspecified task, which is good for output quality and uninformative for process quality.</p><h3>The Full Task Corpus</h3><p>All nine original prompts and the three refined versions, presented here so the reader can evaluate the tasks directly.</p><h3>Group 1 — Clean Path</h3><p><strong>G1–1: Word Frequency Counter</strong></p><blockquote><em>Build a Go CLI tool that accepts a plain text file path and an integer N as command line arguments, and outputs the top N most frequent words in the file. Words should be treated case-insensitively. Output should be sorted by frequency descending, with ties broken alphabetically. Include at least 3 unit tests using the standard testing package.</em></blockquote><p><strong>G1–2: Directory Inventory</strong></p><blockquote><em>Build a Go CLI tool that walks a directory tree and outputs an inventory report: total file count, total size in bytes, and a breakdown of file count and total size grouped by file extension. Accept the root directory path as a command line argument. Extensions should be normalized to lowercase. Output the breakdown sorted by file count descending, with ties broken alphabetically by extension. Include at least 3 unit tests using the standard testing package.</em></blockquote><p><strong>G1–3: INI Config Parser</strong> <em>(original)</em></p><blockquote><em>Build a Go library package (not a CLI tool) that parses INI-format configuration files. The library must expose a </em><em>Parse(r io.Reader) (Config, error) function. </em><em>Config must support a </em><em>Get(section, key string) (string, bool) method. The parser should handle: section headers in </em><em>[brackets], </em><em>key=value pairs, comments on lines starting with </em><em>; or </em><em>#, blank lines, and keys that appear before any section header (the global section). Include at least 5 unit tests covering both normal operation and edge cases.</em></blockquote><p><strong>G1–3: INI Config Parser</strong> <em>(refined)</em></p><blockquote><em>Before writing any code, state your implementation plan: list the major subtasks you’ll complete and the key design decisions you’ll make.</em></blockquote><blockquote><em>Then build a Go library package (not a CLI tool) that parses INI-format configuration files. Requirements:</em></blockquote><ul><li>The library must expose a Parse(r io.Reader) (Config, error) function.</li><li>Config must support a Get(section, key string) (string, bool) method.</li><li>The parser must handle: section headers in [brackets], key=value pairs, comments on lines starting with ; or #, blank lines, and keys that appear before any section header. Keys before any section header belong to the global section, accessible via Get(&quot;&quot;, key).</li><li>Place all library files at the module root, not in a subdirectory. Use ini as the module name.</li><li>Include at least 5 unit tests covering both normal operation and edge cases. Use the standard testing package only.</li></ul><h3>Group 2 — Underspecified</h3><p>The deliberate ambiguities in each prompt are noted. Models that surfaced these as explicit assumptions before writing scored higher on Decomposition Quality. None did, on original prompts.</p><p><strong>G2–1: CSV Summarizer</strong></p><blockquote><em>Build a Go CLI tool that reads a CSV file and prints a summary of each continuous column — minimum, maximum, and mean. The tool should accept the file path as a command line argument. Include at least 3 unit tests using the standard testing package.</em></blockquote><p><em>Deliberate ambiguities: “continuous column” has two reasonable interpretations (does it include integer columns? columns that are mostly numeric with some null values?). Spec is silent on malformed rows, non-numeric values, and empty files.</em></p><p><strong>G2–2: Duplicate File Finder</strong></p><blockquote><em>Build a Go CLI tool that finds duplicate files in a directory tree and prints a report. Accept the directory path as a command line argument. Include at least 3 unit tests using the standard testing package.</em></blockquote><p><em>Deliberate ambiguities: three plausible definitions of “duplicate” — identical filename, identical file size, or identical content (hash). Each produces different results. Output format, ordering, and symlink handling not specified.</em></p><p><strong>G2–3: HTTP Request Logger Middleware</strong> <em>(original)</em></p><blockquote><em>Build a Go HTTP middleware function that logs incoming requests to a file. The middleware should accept a log file path and an </em><em>http.Handler to wrap, and return an </em><em>http.Handler. Log each request with at least the HTTP method, URL path, and response time. Include at least 3 unit tests using the standard testing package.</em></blockquote><p><em>Deliberate ambiguities: log format unspecified. Response status code logging requires wrapping </em><em>http.ResponseWriter to intercept </em><em>WriteHeader() — a non-trivial design decision not mentioned in the spec. Error handling on log file open/write not specified.</em></p><p><strong>G2–3: HTTP Request Logger Middleware</strong> <em>(refined)</em></p><blockquote><em>Before writing any code, state your interpretation of each design decision you’ll make: the log format, how you’ll handle an error opening the log file, and how you’ll ensure the response status code is captured.</em></blockquote><blockquote><em>Then build a Go HTTP middleware function that logs incoming requests to a file. Requirements:</em></blockquote><ul><li>The middleware must accept a log file path and an http.Handler to wrap, and return an http.Handler.</li><li>Log each request with: timestamp, HTTP method, URL path, response status code, and response time. Format: one line per request, space-separated, in that order (e.g., 2026-01-01T12:00:00Z GET /api/v1 200 12.3ms).</li><li>Include at least 3 unit tests using the standard testing package.</li><li>The delivered artifact must build and test with go build ./... and go test ./... from the working directory root without any additional setup.</li></ul><h3>Group 3 — Friction</h3><p>Each task includes a designed obstacle. The obstacle is not named in the prompt — models that read the provided scaffolding or input files before writing encountered it and had to decide what to do.</p><p><strong>G3–1: Log Parser</strong></p><blockquote><em>Build a Go CLI tool that parses a provided log file and outputs a summary report: total line count, error count, warning count, and the 5 most frequent error messages. Accept the log file path as a command line argument. A starter project is provided. Include at least 3 unit tests.</em></blockquote><p><em>Designed friction: the provided starter project has a </em><em>go.mod with a module name that conflicts with the internal package import paths already stubbed in the scaffolding (</em><em>example.com/logparser vs. </em><em>example.com/log-parser). The project will not compile until the mismatch is reconciled.</em></p><p><strong>G3–2: Template Renderer</strong></p><blockquote><em>Build a Go CLI tool that renders Go template files using data from a JSON file. Accept a templates directory path and a JSON data file path as command line arguments. For each </em><em>.tmpl file in the directory, render it using the JSON data and write the output to a file with the same name minus the </em><em>.tmpl extension. A starter project is provided. Include at least 3 unit tests.</em></blockquote><p><em>Designed friction: the provided starter project imports </em><em>github.com/fake-vendor/gotemplate v1.2.0 — a package that doesn’t exist. The correct implementation uses the standard library </em><em>text/template. The project fails at </em><em>go build or </em><em>go mod tidy until the phantom import is removed and the stub replaced.</em></p><p><strong>G3–3: CSV Merger</strong> <em>(original)</em></p><blockquote><em>Build a Go CLI tool that merges all CSV files in a provided input directory into a single output CSV file. Accept the input directory path and output file path as command line arguments. Include at least 3 unit tests using the standard testing package.</em></blockquote><p><em>Designed friction: the provided sample CSV files have inconsistent column headers across files — </em><em>first_name,last_name,email / </em><em>firstname,lastname,email / </em><em>name,email_address. A naive merge produces a syntactically valid CSV with silently misaligned columns — code that compiles, runs, and looks correct until examined carefully.</em></p><p><strong>G3–3: CSV Merger</strong> <em>(refined)</em></p><blockquote><em>Sample CSV files are provided in the </em><em>input/ directory. Read and examine all of them before writing any code.</em></blockquote><blockquote><em>Before writing any code, state your plan: describe specifically how you will handle files with inconsistent column headers.</em></blockquote><blockquote><em>Then build a Go CLI tool that merges all CSV files in the </em><em>input/ directory into a single output CSV file. Requirements:</em></blockquote><ul><li>Accept the input directory path as the first positional argument and the output file path as the second positional argument (os.Args[1] and os.Args[2]).</li><li>The input files may have inconsistent column headers. Your tool must either normalize headers and produce a correctly merged output, or detect the inconsistency and exit with a clear error message. Silent column misalignment is not acceptable.</li><li>Include at least 3 unit tests using the standard testing package. At least one test must exercise the inconsistent-header case.</li></ul><h3>Methodology Notes</h3><p><strong>Single scorer.</strong> All sessions were scored by me. Inter-rater reliability is an open question.</p><p><strong>Three models, not four.</strong> Llama 4 Scout (~67GB) was dropped after repeated hardware failures on load — the 128GB system couldn’t handle Scout’s footprint alongside Ollama overhead and KV cache. Hardware constraint, not model failure.</p><p><strong>Strategic refined subset.</strong> Refined prompts ran on three tasks only (G1–3, G2–3, G3–3) — the most technically demanding in each group. The sensitivity signal on each task type is preserved; per-task coverage is not exhaustive.</p><p><strong>The G2 ambiguity nuance.</strong> All three models chose the most defensible interpretation on every underspecified task, silently, every time. The harness penalizes non-narration — correctly, because process quality matters — but the outputs were right. Future iterations should test more adversarial G2 fixtures where a silent wrong choice is actually possible.</p><p><strong>Scope.</strong> This harness answers a specific question: which model demonstrates the best process quality on clean, standalone, single-shot tasks with no inherited context and Claude-authored prompts? It does not answer whether a model handles inherited codebases, multi-turn sessions, or explicit negative constraints. Those are the next experiments.</p><p>The full scoring rubric, all 27 run files, and the three refinement briefs are available on request.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373762fd2335" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A (Very) Basic Calculator in Flutter]]></title>
            <link>https://medium.com/@lehmann314159/a-very-basic-calculator-in-flutter-38c9bc34d624?source=rss-910e6b8fbdeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c9bc34d624</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Michael Lehmann]]></dc:creator>
            <pubDate>Wed, 11 Mar 2020 18:11:20 GMT</pubDate>
            <atom:updated>2020-03-11T18:18:53.698Z</atom:updated>
            <content:encoded><![CDATA[<p>I thought that a basic calculator would be a good starter project for flutter. I was mostly right, though I did encounter some unexpected complexity. So let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*tGEcSJCF2R4FRQ_ixEr9oA.png" /></figure><h3>What Problem Are We Trying To Solve?</h3><ol><li>We want to create a series of buttons that represent digits so that we can store two operands in the calculator.</li><li>We want to create a series of buttons that represent operators so that we can store an operators into the calculator.</li><li>We want to create a button that represents a sign flip so that we can can change the sign of an operand.</li><li>We want to create a button that represents calculation so that we can ask the calculator to apply the stored operator to the two operands.</li><li>We want a display widget that represents either one of the operands or the calculated result so that we can see the result of the calculation.</li></ol><h3>About Decimals and Places…</h3><p>It’s more of an implementation detail than an acceptance criteria, but we need to be able to handle the decimal sign. Additionally, we should think about how we’re storing the operands. Initially I favored using a float, but dealing with (operator = operator*10 + new digit) is annoying even before you go right of the decimal point. So I opted to use a String for storage. The only real wrinkle there is handling that decimal point. to wit, we go from an integer-style display to a floating point one once the user hits the “.” button, and we have to handle “.” being the first button that they press when storing an operand.</p><h3>A Bit About State</h3><p>It’s tempting to just go straight into coding. And sometimes that’s what I do. But I think there’s a lot of value in thinking about what our states are before we start. Dart has some pretty solid enum support, so why not use it?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02a3d3afd12ceb7263e6eadba7e0dc85/href">https://medium.com/media/02a3d3afd12ceb7263e6eadba7e0dc85/href</a></iframe><h3>MyApp</h3><p>Reading this article isn’t a good way to learn Flutter (but the flutter <a href="https://flutter.dev/docs">website</a> is amazing). However, I do want to leave a few breadcrumbs here and there. I usually follow the conventions laid out in <a href="https://books.google.com/books/about/Beginning_Flutter.html?id=vkOvDwAAQBAJ">Beginning Flutter</a>, but since this is a one-off I decided to stick it in one file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f36a119dc2a7a02c0ddb11e27e6355c4/href">https://medium.com/media/f36a119dc2a7a02c0ddb11e27e6355c4/href</a></iframe><h3>Scaffolding</h3><p>For layout, we’ll use a column container. The top row will be (eventually) a Text box. Most of the other rows will be actual row containers of widgets. Because a lot of the buttons are either digits or operators, I engaged in a bit of factory work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1750407561bba1896292a5306c78fb/href">https://medium.com/media/9e1750407561bba1896292a5306c78fb/href</a></iframe><p>The rest of the implementation is fairly straight-forward. You can find the whole file here:</p><p><a href="https://gist.github.com/lehmann314159/fe384774d3b34e50cc80684bc468d4b0">https://gist.github.com/lehmann314159/fe384774d3b34e50cc80684bc468d4b0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c9bc34d624" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>