<?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 Jsanca on Medium]]></title>
        <description><![CDATA[Stories by Jsanca on Medium]]></description>
        <link>https://medium.com/@jsanca?source=rss-125179124bf4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qQxICbzNv-rfP-Cb</url>
            <title>Stories by Jsanca on Medium</title>
            <link>https://medium.com/@jsanca?source=rss-125179124bf4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:55:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jsanca/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[Your Coding Agent Doesn’t Need a Better Prompt]]></title>
            <link>https://medium.com/@jsanca/your-coding-agent-doesnt-need-a-better-prompt-ddfa012877c8?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddfa012877c8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 04:53:53 GMT</pubDate>
            <atom:updated>2026-08-25T04:53:53.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u27S1oqwHeQreWX4mIBCBQ.jpeg" /><figcaption>Tools, boundaries, context engineering, and a project that remembers.</figcaption></figure><h3>It Needs Better Working Conditions</h3><blockquote><em>Tools, boundaries, targeted research, evidence, and a project that remembers what it learns.</em></blockquote><p>We started noticing a strange pattern while working with coding agents.</p><p>We would ask an agent to implement something using a framework it did not seem to know particularly well. It would begin reasonably enough: inspect the project, look for the relevant API, search for documentation.</p><p>Then things would deteriorate.</p><p>It would search the web. Run curl. Download a JAR. Inspect it. Search Maven. Try another version. Decompile a class. Grep for an interface. Follow another dependency. Run curl again.</p><p>The agent wasn’t stuck in the traditional sense.</p><p>It was doing work.</p><p>The problem was that, from an engineer’s perspective, much of that work was terribly inefficient.</p><p>In some of our runs, we estimated that close to 70% of the agent’s effort was being spent <strong>discovering the environment rather than solving the engineering problem we had actually delegated</strong>.</p><p>This is not a benchmark for coding agents. It is an observation from our own experiments.</p><p>But it led us to a simple question:</p><blockquote><strong><em>If this were an engineer joining my team, would I make them discover all of this from scratch?</em></strong></blockquote><p>Of course not.</p><p>And that question has gradually changed the way we work with coding agents.</p><h3>The curl loop</h3><p>Imagine asking an engineer to implement a feature using an unfamiliar framework.</p><p>You could give them nothing but a terminal and say:</p><blockquote><em>Figure it out…</em></blockquote><p>Eventually, a sufficiently competent engineer probably will.</p><p>But that’s rarely how we work.</p><p>We tell them which framework we’re using. Dependencies are already in the build. The repository compiles. We point them toward existing implementations. They have an IDE with symbol navigation. We explain architectural constraints and previous decisions.</p><p>Yet we were frequently asking coding agents to work under significantly worse conditions.</p><p>Then we were surprised when they wasted enormous amounts of time discovering things we already knew.</p><p>A typical agent loop might look something like this:</p><pre>search for artifact<br>      ↓<br>try dependency<br>      ↓<br>Maven failure<br>      ↓<br>search web<br>      ↓<br>curl documentation<br>      ↓<br>download JAR<br>      ↓<br>inspect classes<br>      ↓<br>try another version<br>      ↓<br>search again</pre><p>Initially, this looked like a model problem.</p><p>Increasingly, we think it is often an <strong>environment problem disguised as a reasoning problem</strong>.</p><h3>Iteration 1: Fix the environment</h3><p>Our first response was straightforward:</p><p>Stop making the agent rediscover the build.</p><p>If we already know the dependency, put it in the POM.</p><p>If we know the compatible version, resolve it.</p><p>If the application needs a particular runtime configuration, prepare it.</p><p>Make the environment reproducible.</p><p>This eliminated entire classes of discovery loops.</p><p>The model didn’t become smarter.</p><p>Its <strong>working conditions became better</strong>.</p><p>That distinction matters.</p><p>A coding agent is not just:</p><pre>LLM + prompt</pre><p>What actually performs the work is closer to:</p><pre>Model<br>  + instructions<br>  + repository<br>  + build<br>  + tools<br>  + runtime<br>  + available evidence<br>  + project knowledge<br>  + feedback loops</pre><p>The model is obviously important.</p><p>But the model is not the entire system.</p><h3>Iteration 2: Give the agent the navigation tools engineers already use</h3><p>The next realization was almost embarrassing.</p><p>As developers, we take tools like these for granted:</p><ul><li>symbol navigation</li><li>implementations</li><li>references</li><li>dependency sources</li><li>Maven models</li><li>tests</li><li>usages</li><li>indexed repositories</li></ul><p>Meanwhile, we sometimes gave an agent little more than:</p><pre>shell + filesystem + internet</pre><p>Then complained that it navigated code inefficiently.</p><p>Connecting the development environment more effectively changed the economics of investigation.</p><p>A question that previously required several searches could become:</p><pre>interface<br>   ↓<br>implementation<br>   ↓<br>usage<br>   ↓<br>test</pre><p>The lesson was not that every coding agent needs IntelliJ specifically.</p><p>The lesson was broader:</p><blockquote><strong><em>Developer tooling is also context infrastructure.</em></strong></blockquote><p>An IDE doesn’t make an engineer more intelligent. It reduces the cost of reaching relevant evidence.</p><p>The same is true for an agent.</p><h3>Iteration 3: Sometimes the best context is a human pointing at the right file</h3><p>We then started keeping source repositories for frameworks we were actively studying close to the projects using them.</p><p>Not hundreds of repositories.</p><p>The important ones.</p><p>During one experiment, we wanted to understand how LangChain4j performs local embeddings using an ONNX model.</p><p>We already had the LangChain4j source checked out next to our project.</p><p>Instead of asking the agent to reconstruct the entire mechanism through internet searches, we investigated it ourselves with AI assistance and followed a relatively short path through the code:</p><pre>AllMiniLmL6V2EmbeddingModel<br>        ↓<br>AbstractInProcessEmbeddingModel<br>        ↓<br>OnnxBertBiEncoder</pre><p>That exposed the pieces that actually mattered:</p><pre>Hugging Face tokenizer<br>        ↓<br>ONNX Runtime<br>        ↓<br>token representations<br>        ↓<br>pooling<br>        ↓<br>normalization<br>        ↓<br>embedding</pre><p>Now the agent could start there.</p><p>We had not done its engineering task for it.</p><p>We had simply done what engineers do for each other all the time:</p><blockquote><em>Start here. This is the part of the framework that appears relevant.</em></blockquote><p>That led us to one of our more important working hypotheses:</p><blockquote><strong><em>Context engineering is not primarily about giving an agent more context. It is about reducing the distance between the agent and the evidence that matters.</em></strong></blockquote><p>More context is not necessarily better context.</p><p>And that realization led to our next experiment.</p><h3>Iteration 4: Why are we deciding what the agent needs to learn?</h3><p>We were planning a new version of an experimental Java application using several vector storage approaches.</p><p>The candidates included technologies such as Qdrant, Pinecone, Integrallis Vectors, LanceDB, LangChain4j’s in-memory implementation, and local ONNX embeddings.</p><p>Our first instinct was familiar:</p><p>Download repositories. Collect documentation. Prepare examples. Feed everything to the agent.</p><p>Then we asked a much simpler question:</p><blockquote><strong><em>Why don’t we ask the agent what it already knows?</em></strong></blockquote><p>So before asking it to implement anything, we gave our coding agent — Claude Code — a reconnaissance task.</p><p>For each technology, we asked:</p><ul><li>What do you already know?</li><li>How confident are you: HIGH, MEDIUM, or LOW?</li><li>What role do you think this technology plays?</li><li>What are you uncertain about?</li><li>Is your current knowledge sufficient to make a reliable implementation decision?</li><li>Would having the source repository locally available materially improve your understanding?</li><li>If so, what specifically would you inspect?</li></ul><p>And, importantly:</p><blockquote><strong><em>Would downloading this repository be useful, or would it mostly add noise?</em></strong></blockquote><p>The result was much better than dumping eight repositories into the context.</p><p>For some technologies, Claude effectively said:</p><blockquote><em>I know this sufficiently. Official API documentation should be enough. Source inspection would probably add little value.</em></blockquote><p>For others, it identified specific gaps.</p><p>The agent was no longer just consuming context.</p><p>It was helping us <strong>plan context acquisition</strong>.</p><h3>A small experiment with Integrallis Vectors</h3><p>One result was particularly revealing.</p><p>During reconnaissance, Claude had low confidence about Integrallis Vectors.</p><p>Its initial working model was that VectorCollection might primarily be related to the project&#39;s VCR/testing infrastructure.</p><p>But something important happened before it made an engineering decision:</p><p><strong>the agent recognized that its confidence was low.</strong></p><p>It asked for evidence.</p><p>We already had the upstream repository checked out locally:</p><pre>../vectors/</pre><p>So we authorized Claude to inspect it.</p><p>Its conclusion after source inspection was essentially:</p><blockquote><em>My initial assessment was significantly wrong.</em></blockquote><p>VectorCollection was not merely a testing abstraction.</p><p>Source inspection revealed a full embedded vector engine implemented in Java, with multiple indexing strategies, persistence, metadata filtering, quantization, and SIMD distance computation through the JDK Vector API.</p><p>It also discovered that the VCR modules were a separate concern: record/replay infrastructure for AI calls that happened to live in the same ecosystem.</p><p>The interesting result wasn’t that Integrallis Vectors turned out to be useful.</p><p>It was the transition:</p><pre>Initial working model<br>        ↓<br>low confidence recognized<br>        ↓<br>specific evidence requested<br>        ↓<br>source inspected<br>        ↓<br>previous hypothesis falsified<br>        ↓<br>new working model<br>        ↓<br>better engineering recommendation</pre><p>Claude had learned something!</p><h3>Yes, the agent learned…</h3><p>There is an important terminology distinction here.</p><p>We are not claiming that the model updated its weights.</p><p>No training occurred. Its underlying parametric knowledge remained unchanged.</p><p>We mean something much more ordinary — and much more useful during an engineering session.</p><p>The agent:</p><ol><li>held an incomplete or incorrect working model;</li><li>recognized uncertainty;</li><li>acquired new evidence;</li><li>reconciled that evidence with its previous understanding;</li><li>changed its working model;</li><li>subsequently reasoned from the corrected model.</li></ol><p>For practical engineering purposes, that is learning.</p><p>Unfortunately, there is a problem.</p><blockquote><strong>The agent will eventually forget it.</strong></blockquote><p>End the session, replace the agent, or exhaust the context window — and much of that acquired understanding disappears.</p><p>We can spend thousands of tokens, source inspection, compute, and human attention teaching an agent something today…</p><p>…and pay for the same discovery again tomorrow.</p><p>That seems wasteful.</p><h3><strong><em>An agent’s learning should outlive the agent.</em></strong></h3><p>This became our next working principle.</p><p>Agent learning creates organizational value when the acquired knowledge can survive the agent that acquired it.</p><p>So we started separating two kinds of retained information in our projects.</p><p>The first is <strong>engineering history</strong>:</p><pre>docs/engineering/</pre><p>It answers questions such as:</p><ul><li>What did we investigate?</li><li>What evidence did we inspect?</li><li>What failed?</li><li>Which assumptions changed?</li><li>Why did we make this decision?</li></ul><p>The second is <strong>project knowledge</strong>:</p><pre>docs/knowledge/</pre><p>It answers a different question:</p><blockquote><strong><em>What does the project know now?</em></strong></blockquote><p>After the vector investigation, for example, Claude produced retained knowledge about:</p><pre>docs/knowledge/vector-backends/<br>    onnx-embedding-pipeline.md<br>    integrallis-vectors.md<br>    candidate-assessment.md</pre><p>The goal was not to copy upstream documentation.</p><p>It was to <strong>compress what had been learned</strong>.</p><p>A future agent should not need the entire investigation history just to understand our ONNX embedding pipeline.</p><p>It might instead read something equivalent to:</p><pre>Local embedding baseline:<br>- all-MiniLM-L6-v2<br>- 384 dimensions<br>- ONNX Runtime<br>- DJL HuggingFaceTokenizer<br>- mean pooling<br>- L2 normalization</pre><pre>Long inputs:<br>- partitioned before inference<br>- embeddings combined using token-count weighting</pre><pre>LangChain4j:<br>- useful as a verified reference implementation<br>- not required by the runtime design</pre><pre>Upstream source:<br>- available locally for deeper verification</pre><p>Perhaps tens of thousands of tokens of discovery become a few thousand tokens of reusable project knowledge.</p><p>The next agent starts there.</p><p>Only when it encounters a new uncertainty does it return to the source.</p><p>The loop becomes:</p><pre>retained knowledge<br>       ↓<br>task understanding<br>       ↓<br>remaining uncertainty<br>       ↓<br>targeted evidence<br>       ↓<br>new learning<br>       ↓<br>updated retained knowledge<br>       ↓<br>next agent</pre><p>Knowledge begins to compound.</p><h3>Research is part of delegation</h3><p>This also changed how we think about giving agents tasks.</p><p>Suppose I delegate work to an engineer involving an unfamiliar framework.</p><p>A good delegation does not consist solely of:</p><blockquote><em>Implement feature X.</em></blockquote><p>Depending on the problem, I may provide:</p><ul><li>architectural boundaries;</li><li>known dependencies;</li><li>relevant source repositories;</li><li>existing project knowledge;</li><li>constraints;</li><li>examples;</li><li>expected behavior;</li><li>verification criteria.</li></ul><p>And before doing all that, I can ask:</p><blockquote><em>What do you already know about this area?</em></blockquote><blockquote><em>Where are you uncertain?</em></blockquote><blockquote><em>What would you investigate before implementing it?</em></blockquote><p>That reconnaissance step has become surprisingly valuable.</p><p>Instead of blindly performing research for the model, we can perform <strong>AI-assisted research targeted by the model’s declared uncertainty</strong>.</p><p>Sometimes that means web search.</p><p>Sometimes deep research.</p><p>Sometimes official documentation.</p><p>Sometimes checking out upstream source.</p><p>Sometimes opening the code ourselves, finding the relevant implementation and saying:</p><blockquote><em>Start here.</em></blockquote><p>This collaboration is substantially different from either extreme:</p><pre>&quot;Agent, do everything.&quot;</pre><p>or:</p><pre>&quot;Human specifies every line.&quot;</pre><p>It looks much more like engineering work.</p><h3>The agent is not a genie in a lamp</h3><p>Large language models are astonishingly capable.</p><p>That capability can create an unfortunate mental model:</p><blockquote><em>Give the model the correct incantation and intelligence comes out.</em></blockquote><p>We don’t think that is a particularly useful model for serious software engineering.</p><p>Coding agents have knowledge gaps.</p><p>They have stale knowledge.</p><p>They misunderstand libraries.</p><p>They make incorrect assumptions.</p><p>They can spend enormous amounts of effort navigating irrelevant evidence.</p><p>So do human engineers.</p><p>The useful question is not:</p><blockquote><em>How do we make the agent magically know everything?</em></blockquote><p>It is:</p><blockquote><strong><em>How do we build a working environment in which the agent can recognize what it doesn’t know, acquire evidence efficiently, perform the work, and leave its discoveries behind?</em></strong></blockquote><p>That environment includes much more than prompts.</p><pre>Coding Agent<br>                          │<br>          ┌───────────────┼───────────────┐<br>          │               │               │<br>       Harness         Knowledge        Research<br>          │               │               │<br>        tools          project facts     source<br>        build          decisions         docs<br>        IDE            constraints       experiments<br>        runtime        prior learning    external evidence<br>          │               │               │<br>          └───────────────┼───────────────┘<br>                          ↓<br>                    Clear boundaries<br>                          ↓<br>                   Precise delegation<br>                          ↓<br>                    Implementation<br>                          ↓<br>                     Verification<br>                          ↓<br>                  Retained knowledge<br>                          │<br>                          └──────→ next agent</pre><p>The prompt still matters.</p><p>It is simply no longer the whole story.</p><h3>From prompting to engineering working conditions</h3><p>We have started thinking about this less as prompt engineering and more as <strong>engineering the working conditions of an artificial engineer</strong>.</p><p>Our current working hypotheses are:</p><p><strong>1. Many apparent reasoning failures are actually environment failures.</strong><br> Before blaming the model for a long discovery loop, inspect whether the environment is forcing it to rediscover information that should already be available.</p><p><strong>2. More context is not necessarily better context.</strong><br> The objective should be to minimize the distance to relevant evidence, not maximize the number of tokens supplied.</p><p><strong>3. Ask the agent what it doesn’t know before deciding what context to provide.</strong><br> Confidence and uncertainty reconnaissance can make research dramatically more targeted.</p><p><strong>4. Local source code is a powerful form of context.</strong><br> A checked-out, indexed repository can be substantially more useful than repeated web searches.</p><p><strong>5. Humans can participate in context acquisition.</strong><br> Finding the correct class, documentation section, example, or repository is not cheating. It is collaboration.</p><p><strong>6. Agents can learn during engineering sessions without updating their weights.</strong><br> They can acquire evidence, falsify assumptions, and construct better working models.</p><p><strong>7. That learning should be retained.</strong><br> Otherwise every new agent pays the same discovery cost.</p><p><strong>8. Knowledge and engineering history are different artifacts.</strong><br> One records how we arrived somewhere. The other tells the next agent what the project now knows.</p><p>These are not independent ideas.</p><p>Together they describe a feedback loop:</p><pre>better environment<br>      ↓<br>cheaper investigation<br>      ↓<br>better evidence<br>      ↓<br>better decisions<br>      ↓<br>retained learning<br>      ↓<br>better starting environment<br>      ↓<br>next agent</pre><p>The environment itself improves as engineering work happens.</p><h3>Where OSK came from</h3><p>These observations have influenced an experiment we call <a href="https://github.com/jsanca/os-knowledge"><strong>Operative System Knowledge (OSK)</strong></a>.</p><p>OSK is not the premise of these ideas.</p><p>It is one response to them.</p><p>We wanted projects to provide coding agents with more than source code.</p><p>We wanted them to contain durable information about:</p><ul><li>how engineering work should be performed;</li><li>architectural boundaries;</li><li>specialized skills;</li><li>previous investigations;</li><li>verification practices;</li><li>project knowledge;</li><li>decisions and their history.</li></ul><p>Most importantly, we wanted the repository to become better prepared for the <strong>next</strong> agent as a consequence of the work performed by the current one.</p><p>That remains an experiment.</p><p>But the direction increasingly feels right.</p><h3>A different way to program with agents</h3><p>Our interaction with coding agents has gradually changed.</p><p>Instead of:</p><pre>Human request<br>      ↓<br>Agent generates code</pre><p>we increasingly work through something closer to:</p><pre>Human hypothesis<br>      ↓<br>discussion<br>      ↓<br>agent reconnaissance<br>      ↓<br>identify uncertainty<br>      ↓<br>targeted research<br>      ↓<br>retained evidence<br>      ↓<br>human + agent design<br>      ↓<br>implementation<br>      ↓<br>real-world friction<br>      ↓<br>verification<br>      ↓<br>revised architecture<br>      ↓<br>new retained knowledge</pre><p>It is slower than asking for a giant one-shot implementation.</p><p>At least at first.</p><p>But it feels considerably more like engineering.</p><p>And, paradoxically, it can be faster overall because less time is spent recovering from incorrect assumptions, rediscovering dependencies, or repeating research another agent already performed.</p><h3>These are hypotheses, not laws</h3><p>We are still experimenting.</p><p>These observations come from repeated engineering sessions, not controlled scientific studies. Different models, repositories, tools, and tasks may produce different results.</p><p>The approximately 70% discovery overhead we observed in some sessions is exactly that: an observation from our own runs, not a general benchmark for coding agents.</p><p>Likewise, our reconnaissance workflow is not proof that agents can always accurately assess their own uncertainty. That itself deserves more experimentation.</p><p>But the evidence has become strong enough to change how we work.</p><p>We increasingly believe that the next large improvement in coding-agent productivity will not come exclusively from models that know more.</p><p>It will also come from environments in which models can:</p><p><strong>recognize uncertainty, acquire the right evidence cheaply, test their assumptions, work inside clear boundaries, and leave what they learned behind for whoever comes next.</strong></p><p>Perhaps the coding agent doesn’t need another clever prompt.</p><p>Perhaps it needs what good engineers have always needed:</p><blockquote><strong><em>Better working conditions.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddfa012877c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Prompts: What We Learned by Giving Two AI Agents the Same Skill]]></title>
            <link>https://medium.com/@jsanca/beyond-prompts-what-we-learned-by-giving-two-ai-agents-the-same-skill-6042ac51c73d?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6042ac51c73d</guid>
            <category><![CDATA[agent-harness]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[openai-codex]]></category>
            <category><![CDATA[knowledge-management]]></category>
            <category><![CDATA[skills]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 23:33:45 GMT</pubDate>
            <atom:updated>2026-08-18T23:33:45.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaRcxqhRBnBMMBhUuJE5eg.png" /><figcaption>Beyond prompts</figcaption></figure><p>For the last several months, I have been experimenting with a question that sounds simple but becomes increasingly complicated the more you work with coding agents:</p><p><strong>How do you make an AI agent consistently useful inside a real engineering project?</strong></p><p>At first, prompts seem like the obvious answer.</p><p>Give the model good instructions. Provide enough context. Describe the task carefully. Ask it to follow the architecture.</p><p>This works surprisingly well.</p><p>Until it doesn’t.</p><p>As our experiments with coding agents became more complex, a pattern started to emerge: the quality of the model mattered, but so did something else — the environment in which the model was operating.</p><p>A capable model with poor operational context could perform worse than a smaller model operating inside a well-defined set of constraints.</p><p>That observation eventually became one of the ideas behind a project we call <strong>OSK — Operative System Knowledge</strong>.</p><p>OSK is still an evolving experiment rather than a finished framework. Its goal is to explore how engineering knowledge can be packaged so that different AI agents can participate in software projects without requiring every instruction to be reconstructed inside every prompt.</p><p>Along the way, one small experiment involving SVG diagrams, Claude and Codex gave us a surprisingly useful window into the problem.</p><p>And it changed how we think about skills, roles and agent harnesses.</p><h3>From prompts to operational context</h3><p>Most coding-agent workflows begin with instructions.</p><p>A repository may contain something like:</p><pre>Use hexagonal architecture.<br>Write tests.<br>Follow these naming conventions.<br>Use Java 25.<br>Do not put domain logic in controllers.</pre><p>This is already much better than starting from nothing.</p><p>But instructions alone become difficult to manage as projects grow.</p><p>Some knowledge describes the <strong>project</strong>.</p><p>Some describes <strong>how engineering work should be performed</strong>.</p><p>Some describes a particular <strong>capability</strong>.</p><p>And some describes the <strong>responsibilities of the agent currently doing the work</strong>.</p><p>We started separating these concepts.</p><p>In OSK, we currently think about three important pieces:</p><p><strong>Knowledge</strong> describes the system.</p><p>Architecture, domain concepts, decisions, constraints, actors, flows and the history of the project belong here.</p><p><strong>Skills</strong> describe how to perform a capability.</p><p>How to review code. How to document an API. How to create a diagram. How to perform a particular kind of analysis.</p><p><strong>Roles</strong> describe which combination of capabilities should participate in a particular kind of work.</p><p>A developer, reviewer, architect or knowledge curator may share several skills while having different responsibilities.</p><p>Conceptually:</p><pre>Knowledge → What system am I working on?</pre><pre>Skill → How do I perform this capability?</pre><pre>Role → What am I responsible for?</pre><p>This separation seems obvious once written down.</p><p>Getting there was not.</p><p>It emerged from watching agents work.</p><h3>The diagram experiment</h3><p>One of the skills we integrated into our experiments was a diagram-design capability (<a href="https://github.com/cathrynlavery/diagram-design">https://github.com/cathrynlavery/diagram-design</a>).</p><p>The task was straightforward: create an SVG architecture diagram following a defined visual and structural contract.</p><p>The skill described things such as layout expectations, visual conventions, validation rules and how the resulting artifact should be constructed.</p><p>We then gave essentially the same capability and task to two different coding agents.</p><p>One was running with Codex.</p><p>The other with Claude.</p><p>The interesting question was not:</p><blockquote><em>Which model makes prettier diagrams?</em></blockquote><p>We wanted to observe something more fundamental:</p><blockquote><em>What happens when different agents receive the same operational capability?</em></blockquote><p>The results were revealing.</p><p>Codex approached the task almost mechanically.</p><p>It interpreted the instructions, generated the diagram, wrote the SVG and successfully passed the static validation.</p><p>The execution was compact and direct.</p><p>Claude took a very different path.</p><p>It began reasoning through the geometry, coordinates, layout decisions and checklist items in considerably more detail. The reasoning itself was reasonable, but the execution strategy became increasingly expensive.</p><p>Eventually, the attempt stalled.</p><p>The interesting part came afterward.</p><p>When the execution strategy was adjusted — reducing unnecessary narration, performing calculations more silently and moving more directly toward artifact generation — Claude was also able to produce the expected result.</p><p>Same task.</p><p>Same capability.</p><p>Different agents.</p><p>Different execution behavior.</p><p>Comparable final artifact.</p><p>That distinction became important.</p><h3>The skill was not the agent</h3><p>It would have been easy to summarize the experiment as:</p><blockquote><em>Codex was better than Claude at this task.</em></blockquote><p>But that would have been the least interesting conclusion.</p><p>Claude was capable of producing the artifact.</p><p>The failure occurred in <strong>how the agent chose to execute the capability</strong>.</p><p>That suggested a more useful model:</p><pre>Agent<br>  ×<br>Skill<br>  ×<br>Execution Strategy<br>  ×<br>Context<br>  =<br>Observed Behavior</pre><p>The model matters.</p><p>But the model is only one variable in the system.</p><p>This is increasingly how I think about AI engineering.</p><p>We often evaluate agents as if the model itself were the complete system.</p><p>It isn’t.</p><p>A coding agent is operating inside a harness.</p><p>That harness provides tools, context, instructions, permissions, validation mechanisms, memory and execution constraints.</p><p>Change the harness and you can substantially change the behavior of the same underlying model.</p><h3>Skills as operational contracts</h3><p>This led us to reconsider what a skill actually is.</p><p>A skill is not merely a sophisticated prompt.</p><p>At least, it shouldn’t be.</p><p>A useful skill behaves more like an <strong>operational contract</strong>.</p><p>It can describe:</p><ul><li>what the capability is supposed to accomplish;</li><li>what inputs it expects;</li><li>which constraints must be respected;</li><li>what decisions remain open to the agent;</li><li>what artifacts should be produced;</li><li>how those artifacts can be validated;</li><li>and where deterministic tooling should replace probabilistic reasoning.</li></ul><p>That last point is particularly important!</p><p>Not everything should be delegated to the model.</p><p>Suppose an agent creates an SVG diagram.</p><p>The model may be excellent at deciding:</p><ul><li>which architectural concepts belong in the diagram;</li><li>how components should be grouped;</li><li>which relationships are important;</li><li>what level of abstraction communicates the architecture effectively.</li></ul><p>But checking whether the resulting XML is valid?</p><p>A deterministic program can do that perfectly well.</p><p>Checking whether required elements exist?</p><p>Again, deterministic.</p><p>Extracting metadata?</p><p>Deterministic…</p><p>The agent should spend its reasoning budget where reasoning creates value.</p><p>This suggests a useful design principle:</p><blockquote><strong><em>Use probabilistic systems for decisions and deterministic systems for guarantees whenever possible.</em></strong></blockquote><p>Skills become the boundary where those two worlds can meet.</p><h3>Roles are compositions, not personalities</h3><p>Another consequence of these experiments has been a change in how we think about agent roles.</p><p>It is tempting to create agents like:</p><pre>You are an expert software architect...</pre><p>and then place a large collection of instructions behind that persona.</p><p>But this quickly produces duplicated knowledge.</p><p>The architect needs diagramming.</p><p>The developer may also need diagramming.</p><p>The reviewer may need documentation analysis.</p><p>The developer also needs documentation capabilities.</p><p>Instead, we are experimenting with roles as compositions of reusable skills.</p><p>Conceptually:</p><pre>Architect<br> ├── architecture-analysis<br> ├── diagram-design<br> ├── adr<br> └── review</pre><pre>Developer<br> ├── implementation<br> ├── testing<br> ├── code-documentation<br> └── diagram-design</pre><pre>Reviewer<br> ├── code-review<br> ├── architecture-analysis<br> └── testing-analysis</pre><p>The role defines responsibility.</p><p>The skills provide capabilities.</p><p>The project knowledge provides grounding.</p><p>This is a much more composable model than building increasingly enormous system prompts for specialized agents.</p><h3>Knowledge is another capability boundary</h3><p>There is another dimension that becomes increasingly important as agents work on projects for longer periods of time.</p><p><strong><em>Knowledge.</em></strong></p><p>A coding agent may understand Java perfectly and still make a terrible architectural decision because it doesn’t know <strong>why the project looks the way it does</strong>.</p><p>Source code only contains part of that story.</p><p>The rest may live in:</p><ul><li>architectural decisions (ADR);</li><li>domain definitions;</li><li>previous experiments;</li><li>failed approaches;</li><li>engineering reports;</li><li>roadmaps;</li><li>operational constraints;</li><li>and assumptions that are obvious to the team but invisible to the model.</li></ul><p>We therefore started treating project knowledge as something that should be explicitly structured rather than repeatedly reconstructed through prompts.</p><p>In our current OSK experiments, we distinguish between knowledge about <strong>what the project is</strong> and engineering history about <strong>how the project got there</strong>.</p><p>That distinction matters.</p><p>An architecture diagram describes the present.</p><p>An ADR explains why a decision was made.</p><p>An engineering log explains what happened while implementing it.</p><p>A failure record explains what was attempted and why it didn’t work.</p><p>Together they provide something much closer to institutional memory.</p><p>And that memory can become part of the agent’s operational environment.</p><h3>The harness is becoming part of the architecture</h3><p>This is perhaps the larger lesson.</p><p>When we started experimenting with coding agents, we mostly thought about models.</p><p>Then we thought about prompts.</p><p>Then context.</p><p>Then skills.</p><p>Then roles.</p><p>Then validation.</p><p>Eventually it becomes difficult to avoid the conclusion that <strong>the harness itself is an engineering artifact</strong>.</p><p>A mature agent environment may eventually look something like:</p><pre>                 ┌─────────────┐<br>                 │    ROLE     │<br>                 │responsibility│<br>                 └──────┬──────┘<br>                        │<br>               selects / combines<br>                        │<br>                 ┌──────▼──────┐<br>                 │   SKILLS    │<br>                 │ capabilities│<br>                 └──────┬──────┘<br>                        │<br>                    operates on<br>                        │<br>                 ┌──────▼──────┐<br>                 │  KNOWLEDGE  │<br>                 │project truth│<br>                 └──────┬──────┘<br>                        │<br>                    mediated by<br>                        │<br>                 ┌──────▼──────┐<br>                 │   HARNESS   │<br>                 │tools/context│<br>                 │validation   │<br>                 └──────┬──────┘<br>                        │<br>                 ┌──────▼──────┐<br>                 │    MODEL    │<br>                 └─────────────┘</pre><p>The model remains extremely important.</p><p>But it is no longer the entire architecture.</p><h3>Portability may matter more than identical behavior</h3><p>The Claude/Codex experiment also changed what we consider success.</p><p>We should probably not expect two different models to execute a task identically.</p><p>In fact, forcing them to do so may remove some of the advantages of using different models in the first place.</p><p>What we want is something closer to <strong>behavioral interoperability</strong>.</p><p>Given the same operational contract:</p><pre>different model<br>+ same skill<br>+ same constraints<br>+ same validation<br>────────────────────────<br>functionally acceptable artifact</pre><p>The internal path may differ.</p><p>One model might reason more.</p><p>Another might act more aggressively.</p><p>Another might use tools differently.</p><p>That variability is acceptable as long as the boundaries remain controlled.</p><p>This resembles something software engineering has dealt with for decades.</p><p>Two implementations of an interface do not need identical internals.</p><p>They need to respect the contract.</p><p>Perhaps skills can eventually play a similar role for agents!</p><h3>What this means for future agent systems</h3><p>We are still early in this work, and one experiment with two agents and an SVG generator obviously proves very little by itself.</p><p>But it provides a useful direction.</p><p>Instead of asking only:</p><blockquote><em>Which model should we use?</em></blockquote><p>we can start asking:</p><blockquote><em>What operational environment does this model need to succeed?</em></blockquote><p>That leads to a very different engineering discipline.</p><p>We can test skills across models.</p><p>We can identify which instructions are portable and which are model-specific.</p><p>We can measure where agents diverge.</p><p>We can move mechanical operations into deterministic helpers.</p><p>We can define roles as capability compositions.</p><p>We can maintain project knowledge independently from the agent consuming it.</p><p>And eventually we can design harnesses capable of adapting execution strategies to different models without changing the underlying engineering contract.</p><p>This is where OSK is currently heading.</p><p>Not toward eliminating variability.</p><p>Toward <strong>containing it</strong>.</p><h3>From model-centric to system-centric AI engineering</h3><p>Large language models are extraordinarily capable.</p><p>But increasingly, I suspect the most interesting engineering problems are moving one layer above them.</p><p>The question is no longer simply how intelligent the model is.</p><p>It is how effectively we can build systems around models that make their intelligence <strong>repeatable, contextual, observable and useful</strong>.</p><p>Our tiny SVG experiment was certainly not designed to answer that question.</p><p>It simply exposed it.</p><p>Two agents received the same capability.</p><p>They behaved differently.</p><p>One succeeded immediately.</p><p>One initially failed because of its execution strategy.</p><p>Both were ultimately capable of producing the required artifact.</p><p>The stable element was not the model.</p><p>It was the contract surrounding the work.</p><p>And perhaps that is one of the directions agent engineering will increasingly take:</p><p><strong>Models provide intelligence.<br>Skills provide operational contracts.<br>Roles compose responsibilities.<br>Knowledge provides continuity.<br>Harnesses provide control.</strong></p><p>The interesting engineering begins when we stop treating those pieces as one thing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6042ac51c73d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From RMI to gRPC: Twenty Years of Reinventing the Same Problem]]></title>
            <link>https://medium.com/@jsanca/from-rmi-to-grpc-twenty-years-of-reinventing-the-same-problem-57fe95c1a23a?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/57fe95c1a23a</guid>
            <category><![CDATA[mir]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[grpc-java]]></category>
            <category><![CDATA[apache-thrift]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 17:07:34 GMT</pubDate>
            <atom:updated>2026-07-30T17:07:34.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPBkVZ2pKDpr96Bes4XuNQ.png" /><figcaption>RMI</figcaption></figure><h3>A short dose of nostalgia</h3><p>In the late ’90s and early 2000s, if you wanted two Java services to talk to each other remotely, you had <strong>RMI</strong>: a local <em>stub</em> hiding the network, a <em>skeleton</em> on the server side, and a Registry where you’d <em>look up</em> the remote object like flipping through a phone book. If the other side wasn’t Java, <strong>SOAP</strong> stepped in — a WSDL as the contract, an XML envelope as the wire format, and the promise (partially fulfilled) of real cross-platform interoperability.</p><p>Both models shared something we tend to undervalue today: they cleanly separated the <strong>contract</strong> (the remote interface, the WSDL) from the <strong>implementation</strong> (the object resolving it) and from the <strong>transport</strong> (JRMP, HTTP+SOAP). That discipline, twenty years later, is still exactly the backbone of Apache Thrift and gRPC. The surface technology changed; the core idea — <em>define the contract before the code</em> — never really left.</p><h3><strong>Apache Thrift: binary RPC with every layer exposed</strong></h3><p>Thrift was born at Facebook and now lives under Apache. Its defining trait compared to gRPC is that <strong>it hides nothing</strong>: you explicitly choose the serialization protocol, the transport, and the server’s concurrency model. It’s more ceremony, but also more control — the same trade-off we already knew from RMI/EJB: <em>more power, more responsibility</em>.</p><h3>The contract</h3><pre>namespace java com.example.calculator<br><br>exception InvalidOperationException {<br>  1: string message<br>}<br><br>struct OperationResult {<br>  1: double value<br>  2: string operation<br>}<br><br>service Calculator {<br>  OperationResult add(1: double a, 2: double b),<br>  OperationResult divide(1: double a, 2: double b) throws (1: InvalidOperationException ex)<br>}</pre><p>Notice the throws clause in the method definition: the business exception is part of the compiled contract, not a status code bolted on afterward. The compiler (thrift --gen java calculator.thrift) generates, among other things, an Iface interface (the <em>port</em>, in hexagonal architecture terms), a Client (your <em>stub</em>), and a Processor (your <em>skeleton</em>).</p><p><strong>Plain Java</strong></p><pre>public class CalculatorHandler implements Calculator.Iface {<br><br>    @Override<br>    public OperationResult add(double a, double b) {<br>        return new OperationResult(a + b, &quot;add&quot;);<br>    }<br><br>    @Override<br>    public OperationResult divide(double a, double b) throws InvalidOperationException {<br>        if (b == 0) {<br>            throw new InvalidOperationException(&quot;division by zero&quot;);<br>        }<br>        return new OperationResult(a / b, &quot;divide&quot;);<br>    }<br>}</pre><pre>public class CalculatorServer {<br><br>    public static void main(String[] args) throws Exception {<br>        CalculatorHandler handler = new CalculatorHandler();<br>        TProcessor processor = new Calculator.Processor&lt;&gt;(handler);<br><br>        TServerTransport serverTransport = new TServerSocket(9090);<br>        ExecutorService virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();<br><br>        TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport)<br>                .processor(processor)<br>                .protocolFactory(new TBinaryProtocol.Factory())<br>                .executorService(virtualExecutor);<br><br>        new TThreadPoolServer(serverArgs).serve();<br>    }<br>}</pre><pre>public class CalculatorClient {<br><br>    public static void main(String[] args) throws Exception {<br>        TTransport transport = new TSocket(&quot;localhost&quot;, 9090);<br>        transport.open();<br><br>        TProtocol protocol = new TBinaryProtocol(transport);<br>        Calculator.Client client = new Calculator.Client(protocol);<br><br>        OperationResult sum = client.add(4.0, 5.0);<br><br>        try {<br>            client.divide(10.0, 0.0);<br>        } catch (InvalidOperationException e) {<br>            System.out.println(&quot;Business error: &quot; + e.getMessage());<br>        }<br><br>        transport.close();<br>    }<br>}</pre><p>Everything here — port, transport, protocol, server model — is an explicit decision. None of this exists as a decision in gRPC, which fixes it upfront.</p><h4>Spring Boot</h4><p>Unlike gRPC, <strong>there’s no polished official starter</strong> for Thrift in Spring. The common approach is to expose the server as a @Bean managed by SmartLifecycle, so it starts and stops in an orderly fashion alongside the rest of the ApplicationContext.</p><pre>@Service<br>public class CalculatorServiceImpl implements Calculator.Iface {<br><br>    // this is where real DI shows up: repositories, other services, etc.<br><br>    @Override<br>    public OperationResult add(double a, double b) {<br>        return new OperationResult(a + b, &quot;add&quot;);<br>    }<br><br>    @Override<br>    public OperationResult divide(double a, double b) throws InvalidOperationException {<br>        if (b == 0) {<br>            throw new InvalidOperationException(&quot;division by zero&quot;);<br>        }<br>        return new OperationResult(a / b, &quot;divide&quot;);<br>    }<br>}</pre><pre>@Configuration<br>public class ThriftServerConfig {<br><br>    @Value(&quot;${thrift.server.port:9090}&quot;)<br>    private int port;<br><br>    @Bean<br>    public SmartLifecycle thriftServerLifecycle(CalculatorServiceImpl handler) {<br>        return new SmartLifecycle() {<br><br>            private TThreadPoolServer server;<br>            private volatile boolean running = false;<br><br>            @Override<br>            public void start() {<br>                try {<br>                    var processor = new Calculator.Processor&lt;&gt;(handler);<br>                    var serverTransport = new TServerSocket(port);<br>                    var virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();<br><br>                    var args = new TThreadPoolServer.Args(serverTransport)<br>                            .processor(processor)<br>                            .protocolFactory(new TBinaryProtocol.Factory())<br>                            .executorService(virtualExecutor);<br><br>                    server = new TThreadPoolServer(args);<br>                    running = true;<br>                    new Thread(server::serve, &quot;thrift-server&quot;).start();<br>                } catch (Exception e) {<br>                    throw new IllegalStateException(&quot;Could not start Thrift server&quot;, e);<br>                }<br>            }<br><br>            @Override<br>            public void stop() {<br>                if (server != null) server.stop();<br>                running = false;<br>            }<br><br>            @Override<br>            public boolean isRunning() {<br>                return running;<br>            }<br>        };<br>    }<br>}</pre><p>What Spring adds here is DI, coordinated lifecycle management, and externalized configuration. What it does <strong>not</strong> add — unlike gRPC — is auto-configuration, health checks, or interceptors out of the box. That extra ceremony isn’t an implementation flaw: it’s the price of a model that keeps layers separate that gRPC chose to fix in place.</p><h3>gRPC: the same problem, with fewer knobs</h3><p>gRPC comes from Google and makes decisions that Thrift leaves open: transport is always HTTP/2 (multiplexed, single-handshake keep-alive, native bidirectional streaming), and Protocol Buffers is the one and only serialization format. Less flexibility, but a far more mature ecosystem and much less manual configuration surface.</p><p><strong>The contract</strong></p><pre>syntax = &quot;proto3&quot;;<br><br>package calculator;<br><br>option java_package = &quot;com.example.calculator&quot;;<br>option java_multiple_files = true;<br><br>message AddRequest {<br>  double a = 1;<br>  double b = 2;<br>}<br><br>message DivideRequest {<br>  double a = 1;<br>  double b = 2;<br>}<br><br>message OperationResult {<br>  double value = 1;<br>  string operation = 2;<br>}<br><br>service Calculator {<br>  rpc Add(AddRequest) returns (OperationResult);<br>  rpc Divide(DivideRequest) returns (OperationResult);<br>}</pre><p>First notable difference from Thrift: <strong>there are no business exceptions in the contract</strong>. gRPC models errors through Status and standard codes (INVALID_ARGUMENT, NOT_FOUND, etc.) rather than a typed throws — business-error handling ends up, in practice, wrapped either in the response payload or in extra metadata on the Status, depending on the team&#39;s convention.</p><p><strong>Plain Java</strong></p><pre>public class CalculatorServiceImpl extends CalculatorGrpc.CalculatorImplBase {<br><br>    @Override<br>    public void add(AddRequest request, StreamObserver&lt;OperationResult&gt; responseObserver) {<br>        double result = request.getA() + request.getB();<br>        responseObserver.onNext(<br>                OperationResult.newBuilder().setValue(result).setOperation(&quot;add&quot;).build());<br>        responseObserver.onCompleted();<br>    }<br><br>    @Override<br>    public void divide(DivideRequest request, StreamObserver&lt;OperationResult&gt; responseObserver) {<br>        if (request.getB() == 0) {<br>            responseObserver.onError(<br>                    Status.INVALID_ARGUMENT<br>                            .withDescription(&quot;division by zero&quot;)<br>                            .asRuntimeException());<br>            return;<br>        }<br>        double result = request.getA() / request.getB();<br>        responseObserver.onNext(<br>                OperationResult.newBuilder().setValue(result).setOperation(&quot;divide&quot;).build());<br>        responseObserver.onCompleted();<br>    }<br>}</pre><pre>public class CalculatorServer {<br><br>    public static void main(String[] args) throws Exception {<br>        Server server = ServerBuilder.forPort(9090)<br>                .addService(new CalculatorServiceImpl())<br>                .build();<br><br>        server.start();<br>        server.awaitTermination();<br>    }<br>}</pre><p>Notice: you didn’t choose a transport, didn’t choose a serialization protocol, didn’t choose a server concurrency model. ServerBuilder decides all of that for you — exactly the abstraction you&#39;d hand-roll in Thrift.</p><pre>public class CalculatorClient {<br><br>    public static void main(String[] args) throws Exception {<br>        ManagedChannel channel = ManagedChannelBuilder<br>                .forAddress(&quot;localhost&quot;, 9090)<br>                .usePlaintext()<br>                .build();<br><br>        CalculatorGrpc.CalculatorBlockingStub stub = CalculatorGrpc.newBlockingStub(channel);<br><br>        OperationResult sum = stub.add(<br>                AddRequest.newBuilder().setA(4.0).setB(5.0).build());<br><br>        try {<br>            stub.divide(DivideRequest.newBuilder().setA(10.0).setB(0.0).build());<br>        } catch (StatusRuntimeException e) {<br>            System.out.println(&quot;Error: &quot; + e.getStatus().getDescription());<br>        }<br><br>        channel.shutdown();<br>    }<br>}</pre><p><strong>Spring Boot</strong></p><p>Here’s where the contrast with Thrift is sharpest: a mature starter ecosystem exists (grpc-spring-boot-starter, community-maintained rather than official from Google, but widely adopted) that does real auto-configuration.</p><pre>@GrpcService<br>public class CalculatorServiceImpl extends CalculatorGrpc.CalculatorImplBase {<br><br>    // regular DI, same as with Thrift + Spring<br><br>    @Override<br>    public void add(AddRequest request, StreamObserver&lt;OperationResult&gt; responseObserver) {<br>        double result = request.getA() + request.getB();<br>        responseObserver.onNext(<br>                OperationResult.newBuilder().setValue(result).setOperation(&quot;add&quot;).build());<br>        responseObserver.onCompleted();<br>    }<br><br>    @Override<br>    public void divide(DivideRequest request, StreamObserver&lt;OperationResult&gt; responseObserver) {<br>        if (request.getB() == 0) {<br>            responseObserver.onError(<br>                    Status.INVALID_ARGUMENT.withDescription(&quot;division by zero&quot;).asRuntimeException());<br>            return;<br>        }<br>        double result = request.getA() / request.getB();<br>        responseObserver.onNext(<br>                OperationResult.newBuilder().setValue(result).setOperation(&quot;divide&quot;).build());<br>        responseObserver.onCompleted();<br>    }<br>}</pre><pre>grpc:<br>  server:<br>    port: 9090</pre><p>With the @GrpcService annotation and the application.yml, the starter takes care of starting the server, registering the service, and coordinating the lifecycle with Spring — no manual configuration @Bean required. No SmartLifecycle to hand-write, no ExecutorService to decide: it&#39;s all fixed inside the starter.</p><h3>Same idea, three technologies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGK1d8URm4QYQBdmfrGt8A.png" /></figure><p>The trend across the table, left to right, is clear: each generation fixes more decisions upfront in exchange for less operational ceremony. RMI and Thrift leave almost everything open; gRPC closes most of the knobs and trades that for tooling and modern adoption.</p><h3>When the code is the contract: Facebook Swift</h3><p>There’s a third path worth mentioning, because it answers a real design tension: <strong>should the contract live in a separate IDL, or can it be derived straight from the code?</strong></p><p><strong>Facebook Swift</strong> (com.facebook.swift) solves this for the Thrift ecosystem by defining the service as an annotated Java interface — no .thrift file at all — and generating the same wire protocol at runtime via reflection:</p><pre>@ThriftService<br>public interface Calculator {<br>    @ThriftMethod<br>    OperationResult add(double a, double b);<br>}</pre><p>This eliminates any possibility of <em>drift</em> between contract and implementation: if the method is on the interface, it’s on the contract, because they’re literally the same thing. There’s no time window in which code and IDL can fall out of sync.</p><p>The reason neither Thrift nor gRPC adopts this as the default is equally clear: the stated goal of both frameworks is to be <strong>polyglot</strong> — the same contract has to generate consistent stubs in Go, Python, C++, and so on. If the contract originates from Java annotations, there’s no longer a single, language-neutral source of truth; at best you’d end up generating the .proto/.thrift file from Java as an intermediate step for the other languages, which complicates more than it solves.</p><p>That said, the operational reality of most internal RPC systems is single-language. Genuine polyglot needs tend to live at the edge — public APIs, third-party integrations — not in the core of a private network. In that context, the real risk isn’t “how do I integrate with Go tomorrow?” but “I added a method to the handler and forgot to touch the .thrift file&quot; — the classic manual-sync failure between two artifacts that are supposed to say the same thing.</p><p>So the right question isn’t <em>explicit IDL or annotations</em>, but <em>is this system genuinely polyglot, or only theoretically so someday?</em> If the answer is the former, contract-first with a separate IDL remains the right call — it lets teams negotiate the contract before a single line of implementation exists, with a clean, auditable diff on every change. If the answer is the latter — the 99% of cases living on a private, single-language network — the consistency guarantee something like Swift provides is probably worth more than a theoretical flexibility that will never actually get exercised.</p><p>As with almost everything in software architecture: there’s no universally correct answer, only well-understood trade-offs applied to the real context of the system you’re building. And honestly, that’s what makes this profession fun</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57fe95c1a23a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Helianthus Uses Both Dockerfiles and Paketo Buildpacks]]></title>
            <link>https://medium.com/@jsanca/why-helianthus-uses-both-dockerfiles-and-paketo-buildpacks-2183ef8f8487?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2183ef8f8487</guid>
            <category><![CDATA[docket]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[paketo]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 04:03:12 GMT</pubDate>
            <atom:updated>2026-06-23T04:03:12.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-o79Flv9B740_khweQHeg.png" /><figcaption>Paketo/Docker</figcaption></figure><p>When we started modernizing <a href="https://github.com/jsanca/helianthus">Helianthus</a>, Docker was already part of the development workflow.</p><p>The application runs on Kotlin, Spring Boot, PostgreSQL, Keycloak, and a React frontend. We already had a working Dockerfile, a Docker Compose environment, and a fully functional development stack.</p><p>At first glance, there was no problem to solve.</p><p>So why did we add Paketo Buildpacks?</p><p>The answer is simple:</p><p><strong>Because Dockerfiles and Buildpacks solve different problems.</strong></p><h3><strong>The Traditional Approach</strong></h3><p>Like many Java teams, our original deployment path relied on a Dockerfile.</p><p>A typical Spring Boot deployment looks something like this:</p><pre>FROM maven:3.9-eclipse-temurin-25 AS build<br><br>COPY . .<br>RUN mvn package<br><br>FROM eclipse-temurin:25-jre<br><br>COPY target/app.jar app.jar<br><br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/app.jar&quot;]</pre><p>There is nothing wrong with this approach.</p><p>In fact, Dockerfiles remain one of the most flexible deployment mechanisms available today.</p><p>You have complete control over:</p><ul><li>Base images</li><li>Operating system packages</li><li>Runtime configuration</li><li>Entrypoints</li><li>Image layout</li></ul><p>For many applications, that level of control is exactly what you need.</p><h3><strong>The Hidden Cost of Dockerfiles</strong></h3><p>The problem is not correctness.</p><p>The problem is maintenance.</p><p>Every Dockerfile becomes infrastructure code.</p><p>Someone eventually becomes responsible for:</p><ul><li>JDK upgrades</li><li>JRE upgrades</li><li>Container JVM tuning</li><li>CA certificates</li><li>Security patches</li><li>Image hardening</li><li>Runtime best practices</li></ul><p>None of those concerns are related to <a href="https://github.com/jsanca/helianthus">Helianthus</a> itself.</p><p>The actual value of Helianthus comes from:</p><ul><li>Declarative operations</li><li>Streaming pipelines</li><li>ResultFrame transformations</li><li>Security</li><li>Catalog-driven APIs</li><li>Entity CRUD generation</li></ul><p>Not from maintaining Docker infrastructure.</p><h3><strong>Enter Paketo Buildpacks</strong></h3><p>Paketo takes a different approach.</p><p>Instead of describing how to build an image, you describe the application and let Buildpacks generate the container image.</p><p>For Spring Boot applications, the experience is surprisingly simple:</p><pre>mvn spring-boot:build-image</pre><p>That’s it.</p><p>The Buildpacks inspect the application and produce a runnable OCI image.</p><p>Behind the scenes, Paketo handles:</p><ul><li>JVM installation</li><li>Memory tuning</li><li>CA certificates</li><li>Container runtime configuration</li><li>Secure defaults</li><li>Build metadata</li></ul><p>Without requiring a Dockerfile.</p><h3><strong>What We Changed in Helianthus</strong></h3><p>One important decision we made was:</p><p><strong>We did not replace Docker.</strong></p><p>We added a second delivery path.</p><p>Helianthus now supports both approaches.</p><h3>Path 1: Dockerfile</h3><pre>Source<br>↓<br>Dockerfile<br>↓<br>Container Image</pre><h3>Path 2: Paketo</h3><pre>Source<br>↓<br>Buildpacks<br>↓<br>Container Image</pre><p>The application code is exactly the same.</p><p>Only the packaging mechanism changes.</p><h3><strong>The Docker Compose Override Trick</strong></h3><p>One of the nicest discoveries during the migration was that Docker Compose made experimentation extremely easy.</p><p>Our original stack used a Dockerfile:</p><pre>services:<br>  server:<br>    build:<br>      context: ./server<br>      dockerfile: Dockerfile</pre><p>To switch to Paketo we created an override file:</p><pre>services:<br>  server:<br>    image: helianthus-server:paketo<br>    build: null</pre><p>Then we started the application using both files:</p><pre>docker compose \<br>  -f docker-compose.starter.yml \<br>  -f docker-compose.starter.paketo.yml \<br>  up</pre><p>No application code changed.</p><p>No runtime code changed.</p><p>Only the image source changed.</p><p>This allowed us to compare both approaches side-by-side.</p><h3><strong>The First Issue We Encountered</strong></h3><p>Of course, nothing is ever completely free.</p><p>The first time we launched the Paketo image we hit this error:</p><p>Cannot load this JVM TI agent twice</p><p>After some investigation we discovered that both:</p><p><em>JAVA_OPTS</em></p><p>and</p><p><em>JAVA_TOOL_OPTIONS</em></p><p>contained the same JDWP configuration.</p><p>Paketo automatically merges JVM options, which resulted in the debug agent being loaded twice.</p><p>The fix was straightforward:</p><p>Use a single source of JVM debug configuration instead of duplicating it.</p><p>This wasn’t a Paketo problem.</p><p>It was a reminder that understanding the runtime still matters, even when Buildpacks automate most of the work.</p><h3><strong>When We Prefer Dockerfiles</strong></h3><p>Dockerfiles remain our preferred option when we need infrastructure control.</p><p>Examples include:</p><ul><li>Installing operating system packages</li><li>Adding native binaries</li><li>Custom startup behavior</li><li>Enterprise deployment requirements</li><li>Complex runtime environments</li></ul><p>In these situations, Dockerfiles are hard to beat.</p><h3><strong>When We Prefer Paketo</strong></h3><p>Paketo shines when the application is relatively standard.</p><p>Examples include:</p><ul><li>Spring Boot APIs</li><li>Internal services</li><li>Microservices</li><li>Proofs of concept</li><li>Developer environments</li><li>Rapid delivery pipelines</li></ul><p>In these cases, the Dockerfile often becomes maintenance overhead without providing meaningful value.</p><h3><strong>The Real Lesson</strong></h3><p>After adding Paketo support to <a href="https://github.com/jsanca/helianthus">Helianthus</a>, the most important lesson was not that Buildpacks are better than Dockerfiles.</p><p>The lesson was that they solve different problems.</p><p>Dockerfiles optimize for control.</p><p>Buildpacks optimize for delivery.</p><p>By supporting both approaches, Helianthus can choose the right tool for each deployment scenario.</p><p>Sometimes we need infrastructure control.</p><p>Sometimes we just need a secure, production-ready image as quickly as possible.</p><p>The good news is that modern Java ecosystems allow us to have both.</p><p><a href="https://github.com/jsanca/helianthus">https://github.com/jsanca/helianthus</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2183ef8f8487" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic Patterns in Java: A Practical Guide to Building Smarter, Cheaper AI Pipelines]]></title>
            <link>https://medium.com/@jsanca/agentic-patterns-in-java-a-practical-guide-to-building-smarter-cheaper-ai-pipelines-c6a4d5f92865?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6a4d5f92865</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 03:02:16 GMT</pubDate>
            <atom:updated>2026-06-23T03:02:16.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jI5R1TXKu7AltZ-sjckuzw.png" /><figcaption>Agentic Pipelines</figcaption></figure><blockquote>More tools, more intelligence — right? Not quite. Here’s what actually works.</blockquote><h3>The Problem With “Just Add More Tools”</h3><p>Both Anthropic and Vercel learned the same lesson the hard way, independently.</p><p>Vercel built an internal text-to-SQL agent called d0. They started with 17 specialized tools — one to create tables, one to insert rows, one to run queries, one to validate schemas. The intuition was sound: a specialized tool per operation should outperform a generic one. It didn’t. When they stripped it down to essentially one tool (bash execution, letting Claude navigate files with grep/cat/ls the way a human analyst would), the success rate jumped from 80% to 100%, with fewer steps, fewer tokens, and faster responses.</p><p>Anthropic’s guidance on writing tools for agents arrives at the same place from the engineering side: every tool definition — name, description, JSON schema — lives permanently in the agent’s context window whether it gets called or not. One of the most common failure modes they document is <strong>overloaded toolsets that create ambiguous decision points</strong>. Their rule of thumb: if an experienced engineer can’t immediately say which tool fits a given situation, the agent won’t be able to either.</p><p>The insight that unifies all the patterns in this article is this:</p><blockquote><strong><em>Gate expensive or non-deterministic operations behind a cheap decision point. The agent should invoke the expensive thing only when it actually needs it — never by default.</em></strong></blockquote><p>This applies to RAG, to LLM routing, to agent loops, and to tool design itself. Let’s build it in Java.</p><h3>1. Agentic RAG — Context on Demand, Not by Default</h3><h4>The problem with naive RAG</h4><p>Traditional RAG pre-injects retrieved context into every prompt, whether the question needs it or not. An user asking “what are your business hours?” gets the same retrieval pass as one asking for a nuanced product comparison. You pay the latency and token cost every time, and you pollute the context window with noise that can actively hurt the model’s focus.</p><h4>The fix: RAG as a tool</h4><p>Expose retrieval as a @Tool method inside a langchain4j AiServices interface. The model reads the tool description and decides per-turn whether retrieval is necessary. No retrieval call → no tokens spent → no context noise.</p><pre>public interface ProductAssistant {<br>    String chat(String userMessage);<br>}<br><br>public class ProductTools {<br><br>    private final EmbeddingStore&lt;TextSegment&gt; store;<br>    private final EmbeddingModel embeddingModel;<br><br>    public ProductTools(EmbeddingStore&lt;TextSegment&gt; store, <br>                        EmbeddingModel embeddingModel) {<br>        this.store = store;<br>        this.embeddingModel = embeddingModel;<br>    }<br><br>    @Tool(&quot;&quot;&quot;<br>        Search the product catalog for relevant information.<br>        Use this ONLY when the user asks about specific products, <br>        features, pricing, availability, or technical specifications.<br>        Do NOT use for greetings, order status, or general policy questions.<br>        &quot;&quot;&quot;)<br>    public String searchProductCatalog(<br>        @P(&quot;A specific, focused search query derived from the user&#39;s question&quot;) <br>        String query<br>    ) {<br>        Embedding queryEmbedding = embeddingModel.embed(query).content();<br>        <br>        EmbeddingSearchRequest request = EmbeddingSearchRequest.builder()<br>            .queryEmbedding(queryEmbedding)<br>            .maxResults(3)<br>            .minScore(0.75)  // only return high-confidence matches<br>            .build();<br><br>        List&lt;EmbeddingMatch&lt;TextSegment&gt;&gt; matches = <br>            store.search(request).matches();<br><br>        if (matches.isEmpty()) {<br>            return &quot;No relevant products found for: &quot; + query;<br>        }<br><br>        return matches.stream()<br>            .map(m -&gt; m.embedded().text())<br>            .collect(Collectors.joining(&quot;\n---\n&quot;));<br>    }<br>}</pre><pre>// Wiring it together<br>ProductAssistant assistant = AiServices.builder(ProductAssistant.class)<br>    .chatModel(anthropicModel)<br>    .tools(new ProductTools(embeddingStore, embeddingModel))<br>    .build();<br><br>// The model decides whether to call searchProductCatalog or not<br>String response = assistant.chat(&quot;What leather conditioners do you carry?&quot;);</pre><p><strong>The key is the tool description.</strong> It tells the model exactly when to invoke it and — equally important — when <em>not</em> to. This is the same principle Anthropic uses internally: a well-written tool description is the difference between an agent that calls tools purposefully and one that calls them reflexively.</p><h3>2. Tool Overlap Analysis — Catching Ambiguity Before It Reaches the Agent</h3><p>If two tools have descriptions that are semantically similar, the agent will struggle to choose between them — and that hesitation costs tokens, produces inconsistent behavior, and in the worst case causes a loop.</p><p>The fix is to check for overlap before deploying. Embed every tool description and compute pairwise cosine similarity. Flag any pair above a threshold. This is cheap, deterministic, and can run in CI as a validation step.</p><pre>public class ToolOverlapAnalyzer {<br><br>    private final EmbeddingModel embeddingModel;<br>    private static final double OVERLAP_THRESHOLD = 0.85;<br><br>    public ToolOverlapAnalyzer(EmbeddingModel embeddingModel) {<br>        this.embeddingModel = embeddingModel;<br>    }<br><br>    public record ToolDefinition(String name, String description) {}<br>    <br>    public record OverlapWarning(<br>        String toolA, <br>        String toolB, <br>        double similarity,<br>        String suggestion<br>    ) {}<br><br>    public List&lt;OverlapWarning&gt; analyze(List&lt;ToolDefinition&gt; tools) {<br>        // Embed all descriptions in one batch<br>        List&lt;String&gt; descriptions = tools.stream()<br>            .map(ToolDefinition::description)<br>            .toList();<br><br>        List&lt;Embedding&gt; embeddings = embeddingModel<br>            .embedAll(descriptions)<br>            .content();<br><br>        List&lt;OverlapWarning&gt; warnings = new ArrayList&lt;&gt;();<br><br>        // Pairwise similarity check — O(n²) but n is small for a toolset<br>        for (int i = 0; i &lt; tools.size(); i++) {<br>            for (int j = i + 1; j &lt; tools.size(); j++) {<br>                double similarity = cosineSimilarity(<br>                    embeddings.get(i), <br>                    embeddings.get(j)<br>                );<br><br>                if (similarity &gt;= OVERLAP_THRESHOLD) {<br>                    warnings.add(new OverlapWarning(<br>                        tools.get(i).name(),<br>                        tools.get(j).name(),<br>                        similarity,<br>                        &quot;These tools may confuse the agent. Consider merging them &quot; +<br>                        &quot;or making their scope boundaries explicit in the description.&quot;<br>                    ));<br>                }<br>            }<br>        }<br><br>        return warnings;<br>    }<br><br>    private double cosineSimilarity(Embedding a, Embedding b) {<br>        float[] va = a.vector();<br>        float[] vb = b.vector();<br>        double dot = 0, normA = 0, normB = 0;<br>        for (int i = 0; i &lt; va.length; i++) {<br>            dot   += va[i] * vb[i];<br>            normA += va[i] * va[i];<br>            normB += vb[i] * vb[i];<br>        }<br>        return dot / (Math.sqrt(normA) * Math.sqrt(normB));<br>    }<br>}</pre><p>If searchProducts and findProductByName score 0.91 similarity, the test fails and you fix the descriptions (or merge the tools) before the agent ever sees them.</p><h3>3. SLM as Router — The Cheap Gate Before the Expensive Call</h3><p>Not every message needs your most capable model. A greeting, a simple FAQ lookup, a yes/no confirmation — sending these to a frontier LLM is waste. A small, fast model can classify intent and route to the right handler. The LLM only runs when it genuinely needs to.</p><pre>public class IntentRouter {<br><br>    // Fast, cheap classifier — e.g. a quantized Llama 3.2 1B via Ollama<br>    private final ChatModel slmClassifier;<br>    <br>    private static final String CLASSIFICATION_PROMPT = &quot;&quot;&quot;<br>        Classify the user message into exactly one category.<br>        Respond with only the category name, nothing else.<br>        <br>        Categories:<br>        - GREETING       : hello, hi, good morning, how are you<br>        - FAQ_POLICY     : return policy, shipping, business hours, payment methods<br>        - PRODUCT_SEARCH : questions about specific products, features, pricing<br>        - ORDER_STATUS   : order tracking, delivery status, shipment updates<br>        - HUMAN_HANDOFF  : complaints, complex issues, requests for a human agent<br>        - GENERAL        : anything that doesn&#39;t fit the above<br>        <br>        User message: &quot;%s&quot;<br>        &quot;&quot;&quot;;<br><br>    public enum Intent {<br>        GREETING, FAQ_POLICY, PRODUCT_SEARCH, <br>        ORDER_STATUS, HUMAN_HANDOFF, GENERAL<br>    }<br><br>    public Intent classify(String userMessage) {<br>        // Pre-filter: pure regex for the most obvious cases<br>        // Zero model calls, zero latency<br>        if (isGreeting(userMessage)) return Intent.GREETING;<br><br>        String response = slmClassifier<br>            .chat(CLASSIFICATION_PROMPT.formatted(userMessage))<br>            .aiMessage()<br>            .text()<br>            .trim()<br>            .toUpperCase();<br><br>        try {<br>            return Intent.valueOf(response);<br>        } catch (IllegalArgumentException e) {<br>            return Intent.GENERAL;  // safe fallback<br>        }<br>    }<br><br>    private boolean isGreeting(String message) {<br>        String lower = message.toLowerCase().strip();<br>        return lower.matches(&quot;(hi|hello|hey|good morning|good afternoon|hola|pura vida)[!?.,]?&quot;);<br>    }<br>}</pre><pre>public class ConversationOrchestrator {<br><br>    private final IntentRouter router;<br>    private final Map&lt;Intent, ConversationHandler&gt; handlers;<br><br>    public String handle(String userMessage) {<br>        Intent intent = router.classify(userMessage);<br><br>        return switch (intent) {<br>            case GREETING     -&gt; &quot;Hello! How can I help you today?&quot;;         // zero LLM calls<br>            case FAQ_POLICY   -&gt; handlers.get(Intent.FAQ_POLICY)             // static lookup<br>                                         .handle(userMessage);<br>            case PRODUCT_SEARCH -&gt; handlers.get(Intent.PRODUCT_SEARCH)       // LLM + Agentic RAG<br>                                           .handle(userMessage);<br>            case ORDER_STATUS -&gt; handlers.get(Intent.ORDER_STATUS)           // API call only<br>                                         .handle(userMessage);<br>            case HUMAN_HANDOFF -&gt; escalateToHuman(userMessage);<br>            default           -&gt; handlers.get(Intent.GENERAL)<br>                                         .handle(userMessage);<br>        };<br>    }<br>}</pre><p>The regex pre-filter deserves a note: for the most obvious cases (greetings, simple confirmations), you don’t even need the SLM. Deterministic code is always cheaper than statistical inference. The SLM covers the grey zone where regex doesn’t reach; the LLM only runs when the SLM says the task genuinely needs it.</p><h3>4. Loop Guard — Stopping Agents That Won’t Stop Themselves</h3><p>Agent loops are a real failure mode. The most common cause isn’t a bug in the loop logic — it’s ambiguous tool return values. When a tool says “there may be more results available,” the agent has no clear signal that the task is done, so it calls the tool again. And again.</p><p>The fix has two layers: <strong>terminal states in tool contracts</strong>, and a <strong>deterministic circuit breaker</strong> that doesn’t depend on the model’s judgment at all.</p><h4>Layer 1: Terminal states in tool contracts</h4><pre>// Don&#39;t do this — &quot;may be more&quot; is an invitation to loop<br>public String searchOrders(String customerId) {<br>    List&lt;Order&gt; orders = orderService.find(customerId);<br>    if (orders.isEmpty()) return &quot;No orders found. There may be more in the archive.&quot;;<br>    return formatOrders(orders);  // ambiguous: is this everything?<br>}<br><br>// Do this — unambiguous terminal states<br>public String searchOrders(String customerId) {<br>    List&lt;Order&gt; orders = orderService.find(customerId);<br>    <br>    if (orders.isEmpty()) {<br>        return &quot;STATUS:NOT_FOUND | No orders exist for customer &quot; + customerId + <br>               &quot;. This is the complete result — do not search again.&quot;;<br>    }<br>    <br>    return &quot;STATUS:COMPLETE | Found &quot; + orders.size() + &quot; order(s) — this is all of them:\n&quot; <br>           + formatOrders(orders);<br>}</pre><h4>Layer 2: The deterministic circuit breaker</h4><pre>public class AgentLoopGuard {<br><br>    private final ChatModel agent;<br>    private final int maxSteps;<br>    private final Duration timeout;<br>    private final int repetitionWindow;  // detect repeated tool calls<br><br>    public AgentLoopGuard(ChatModel agent, int maxSteps, <br>                          Duration timeout, int repetitionWindow) {<br>        this.agent = agent;<br>        this.maxSteps = maxSteps;<br>        this.timeout = timeout;<br>        this.repetitionWindow = repetitionWindow;<br>    }<br><br>    public record GuardedResult(String response, TerminationReason reason, int stepsUsed) {}<br>    <br>    public enum TerminationReason {<br>        COMPLETED,          // agent said it was done<br>        MAX_STEPS_REACHED,  // hit the step cap<br>        TIMEOUT,            // hit the wall clock limit<br>        REPETITION_DETECTED // same tool+args repeated N times<br>    }<br><br>    public GuardedResult execute(String task, List&lt;ToolSpecification&gt; tools) {<br>        List&lt;ChatMessage&gt; history = new ArrayList&lt;&gt;();<br>        history.add(UserMessage.from(task));<br><br>        Deque&lt;String&gt; recentToolCalls = new ArrayDeque&lt;&gt;();<br>        Instant deadline = Instant.now().plus(timeout);<br>        int steps = 0;<br><br>        while (steps &lt; maxSteps) {<br><br>            // Hard time limit — independent of model behavior<br>            if (Instant.now().isAfter(deadline)) {<br>                return new GuardedResult(<br>                    &quot;Task interrupted: time limit reached after &quot; + steps + &quot; steps.&quot;,<br>                    TerminationReason.TIMEOUT,<br>                    steps<br>                );<br>            }<br><br>            ChatResponse response = agent.chat(history);<br>            steps++;<br><br>            AiMessage aiMessage = response.aiMessage();<br>            history.add(aiMessage);<br><br>            // Agent finished voluntarily<br>            if (!aiMessage.hasToolExecutionRequests()) {<br>                return new GuardedResult(<br>                    aiMessage.text(), <br>                    TerminationReason.COMPLETED, <br>                    steps<br>                );<br>            }<br><br>            // Check for repetitive tool calls<br>            String callSignature = buildCallSignature(aiMessage.toolExecutionRequests());<br>            recentToolCalls.addLast(callSignature);<br>            if (recentToolCalls.size() &gt; repetitionWindow) recentToolCalls.pollFirst();<br><br>            if (recentToolCalls.size() == repetitionWindow &amp;&amp;<br>                recentToolCalls.stream().distinct().count() == 1) {<br>                return new GuardedResult(<br>                    &quot;Task halted: repeated identical tool call detected — likely stuck.&quot;,<br>                    TerminationReason.REPETITION_DETECTED,<br>                    steps<br>                );<br>            }<br><br>            // Execute tools and add results to history<br>            // (tool execution logic omitted for brevity)<br>        }<br><br>        return new GuardedResult(<br>            &quot;Task incomplete: reached the &quot; + maxSteps + &quot;-step limit.&quot;,<br>            TerminationReason.MAX_STEPS_REACHED,<br>            steps<br>        );<br>    }<br><br>    private String buildCallSignature(List&lt;ToolExecutionRequest&gt; requests) {<br>        return requests.stream()<br>            .map(r -&gt; r.name() + &quot;:&quot; + r.arguments())<br>            .sorted()<br>            .collect(Collectors.joining(&quot;|&quot;));<br>    }<br>}</pre><p>The circuit breaker doesn’t trust the agent to stop itself — it doesn’t have to. The step cap and timeout are enforced externally, deterministically, regardless of what the model decides. This is the same philosophy as your SLM router: the cheap, deterministic layer protects the expensive, non-deterministic one.</p><h3>5. Observability — Mining Intent From What the Agent Doesn’t Know</h3><p>Every conversation that falls through to your catch-all handler is a signal. Left unanalyzed, it’s wasted data. Analyzed periodically, it tells you exactly which new deterministic nodes to add to your graph — which intents are common enough to “graduate” from LLM inference to a fixed handler.</p><pre>@Component<br>public class ConversationObserver {<br><br>    private final Langfuse langfuse;  // or any OTel-compatible backend<br>    private final ConversationLogRepository logRepository;<br><br>    // Instrument every conversation turn<br>    public String handleAndObserve(String sessionId, String userMessage, Intent intent) {<br>        Span span = langfuse.span()<br>            .name(&quot;conversation.turn&quot;)<br>            .input(userMessage)<br>            .metadata(Map.of(<br>                &quot;intent&quot;,     intent.name(),<br>                &quot;sessionId&quot;,  sessionId,<br>                &quot;isCatchAll&quot;, intent == Intent.GENERAL<br>            ))<br>            .start();<br><br>        try {<br>            String response = orchestrator.handle(userMessage);<br>            span.output(response).end();<br>            <br>            // Log catch-all turns separately for mining<br>            if (intent == Intent.GENERAL) {<br>                logRepository.saveCatchAll(new CatchAllLog(<br>                    sessionId, userMessage, Instant.now()<br>                ));<br>            }<br>            <br>            return response;<br>        } catch (Exception e) {<br>            span.error(e).end();<br>            throw e;<br>        }<br>    }<br>}</pre><pre>// Run this weekly — offline, not on the hot path<br>@Scheduled(cron = &quot;0 0 9 * * MON&quot;)<br>public void discoverEmergingIntents() {<br>    List&lt;String&gt; recentCatchAll = logRepository<br>        .findCatchAllSince(Instant.now().minus(Duration.ofDays(7)))<br>        .stream()<br>        .map(CatchAllLog::userMessage)<br>        .toList();<br><br>    if (recentCatchAll.size() &lt; 20) return;  // not enough data yet<br><br>    // Ask the LLM to cluster — offline, not in the user flow<br>    String clusteringPrompt = &quot;&quot;&quot;<br>        Analyze these unhandled user messages from our support chatbot.<br>        Group them by intent and identify the top 5 patterns by frequency.<br>        For each pattern, suggest a handler name and example trigger phrases.<br>        <br>        Messages:<br>        %s<br>        &quot;&quot;&quot;.formatted(String.join(&quot;\n- &quot;, recentCatchAll));<br><br>    String analysis = analyticsModel.chat(clusteringPrompt)<br>        .aiMessage().text();<br><br>    // Send to Slack/email for the team to review<br>    notificationService.sendWeeklyInsights(analysis);<br>}</pre><p>The output of this weekly job is your roadmap for new deterministic handlers. When a cluster appears consistently (say, “questions about wholesale pricing” every week), you build a WHOLESALE_INQUIRY handler and add it to the router. Over time, the percentage of traffic hitting the catch-all trends down — which is a concrete KPI for the health of the system.</p><h3>6. Speculative Drafting at the Agent Level</h3><p>Speculative Decoding as described in the literature operates inside the inference server — it needs access to token logprobs that most Java clients don’t expose. But the <em>pattern</em> is valid and implementable at the agent level: a fast, cheap model drafts a response; a capable model verifies it in parallel and only intervenes when the draft isn’t good enough.</p><pre>public class SpeculativeDraftingAgent {<br><br>    private final ChatModel draftModel;    // Fast, cheap: e.g. Haiku, Gemini Flash<br>    private final ChatModel verifierModel; // Capable: e.g. Claude Sonnet, GPT-4o<br>    private final double acceptanceThreshold; // 0.0-1.0<br><br>    public String generate(String prompt, String taskContext) {<br>        // Draft and verify run concurrently<br>        CompletableFuture&lt;String&gt; draftFuture = CompletableFuture<br>            .supplyAsync(() -&gt; draftModel.chat(prompt).aiMessage().text());<br><br>        CompletableFuture&lt;VerificationResult&gt; verifyFuture = draftFuture<br>            .thenApplyAsync(draft -&gt; verify(prompt, draft, taskContext));<br><br>        VerificationResult result = verifyFuture.join();<br><br>        return switch (result.verdict()) {<br>            case ACCEPT  -&gt; result.draft();         // use the cheap draft<br>            case CORRECT -&gt; result.correction();    // use the verifier&#39;s fix<br>            case REJECT  -&gt; regenerate(prompt);     // full verifier generation<br>        };<br>    }<br><br>    private VerificationResult verify(String prompt, String draft, String context) {<br>        String verifyPrompt = &quot;&quot;&quot;<br>            Original request: %s<br>            Context/constraints: %s<br>            Proposed response: %s<br>            <br>            Evaluate the proposed response:<br>            - ACCEPT if it correctly and completely addresses the request<br>            - CORRECT if it&#39;s mostly right but needs a small fix (provide the fix)<br>            - REJECT if it&#39;s fundamentally wrong or incomplete<br>            <br>            Respond as JSON: {&quot;verdict&quot;: &quot;ACCEPT|CORRECT|REJECT&quot;, &quot;correction&quot;: &quot;...if CORRECT&quot;}<br>            &quot;&quot;&quot;.formatted(prompt, context, draft);<br><br>        String verifyResponse = verifierModel.chat(verifyPrompt).aiMessage().text();<br>        return parseVerificationResult(draft, verifyResponse);<br>    }<br><br>    private String regenerate(String prompt) {<br>        return verifierModel.chat(prompt).aiMessage().text();<br>    }<br>}</pre><p>The key insight: the verifier runs a single forward pass over the draft (the same operation as processing a prompt), which is cheaper than generating a full response from scratch. When the draft is accepted — which should be the common case for well-scoped tasks — you’ve paid draft model cost instead of verifier model cost. The pattern is economically sound only if your acceptance rate is high; if the verifier rejects most drafts, your SLM isn’t suitable for the task and you’re paying twice for nothing.</p><h3>7. Graph vs. Chain — When to Add the Complexity</h3><p>A linear chain is the right default. It’s simpler to build, simpler to debug, and simpler to observe. Reach for a graph only when the problem <em>is</em> a graph — when there is genuine conditional branching, cycles, or parallel paths that linear composition can’t express cleanly.</p><h4>Chain</h4><ul><li>Fixed sequence of steps, no branching</li><li>Simple RAG + answer</li></ul><p><strong>Graph with conditional edges</strong></p><ul><li>Route to different handlers by intent</li></ul><p><strong>Graph with a cycle back</strong></p><ul><li>Retry a step on failure</li></ul><p><strong>Graph with parallel nodes</strong></p><ul><li>Two independent tasks that can run in parallel</li></ul><p><strong>Graph (interrupt + resume)</strong></p><ul><li>Human approval gate in the middle</li></ul><pre>// Linear: simple, readable, debuggable<br>public String handleProductQuery(String query) {<br>    String retrieved = ragTool.search(query);<br>    String enriched  = contextEnricher.addBusinessRules(retrieved);<br>    return llm.chat(buildPrompt(query, enriched));<br>}<br><br>// Graph (LangGraph4j): when you genuinely need branching<br>StateGraph&lt;ConversationState&gt; graph = new StateGraph&lt;&gt;(ConversationState.class)<br>    .addNode(&quot;classify&quot;,        this::classifyIntent)<br>    .addNode(&quot;search_products&quot;, this::handleProductSearch)<br>    .addNode(&quot;check_order&quot;,     this::handleOrderStatus)<br>    .addNode(&quot;faq_lookup&quot;,      this::handleFAQ)<br>    .addNode(&quot;human_handoff&quot;,   this::escalateToHuman)<br>    .addEdge(START, &quot;classify&quot;)<br>    .addConditionalEdges(&quot;classify&quot;, this::routeByIntent, Map.of(<br>        &quot;PRODUCT_SEARCH&quot;, &quot;search_products&quot;,<br>        &quot;ORDER_STATUS&quot;,   &quot;check_order&quot;,<br>        &quot;FAQ_POLICY&quot;,     &quot;faq_lookup&quot;,<br>        &quot;HUMAN_HANDOFF&quot;,  &quot;human_handoff&quot;<br>    ))<br>    .addEdge(&quot;search_products&quot;, END)<br>    .addEdge(&quot;check_order&quot;,     END)<br>    .addEdge(&quot;faq_lookup&quot;,      END)<br>    .addEdge(&quot;human_handoff&quot;,   END)<br>    .compile();</pre><p>The overhead of a graph is real — more state to manage, more edges to reason about, harder to trace end-to-end. That overhead is worth it when the branching logic would otherwise be a nest of if/else blocks embedded inside a linear step. If your &quot;chain&quot; already has three nested conditionals in one step, that&#39;s the signal that it wants to be a graph.</p><h3>Putting It Together — The Unified Architecture</h3><p>Every pattern in this article is the same idea applied at a different layer:</p><pre>User message<br>     │<br>     ▼<br>┌────────────────────────────────┐<br>│  Regex pre-filter              │  ← deterministic, zero cost<br>│  (greetings, trivial cases)    │<br>└────────────┬───────────────────┘<br>             │ grey zone<br>             ▼<br>┌────────────────────────────────┐<br>│  SLM Router                   │  ← cheap, fast classification<br>│  (intent → handler)           │<br>└────────────┬───────────────────┘<br>             │ complex intent<br>             ▼<br>┌────────────────────────────────┐<br>│  Agent (LLM + Tools)          │  ← expensive, capable<br>│  • Agentic RAG (@Tool)        │<br>│  • Non-overlapping toolset    │<br>│  • Loop guard (step cap)      │<br>└────────────┬───────────────────┘<br>             │ all turns<br>             ▼<br>┌────────────────────────────────┐<br>│  Observability (Langfuse/OTel)│  ← catch-all mining → new handlers<br>└────────────────────────────────┘</pre><p>The system gets smarter over time not because the LLM improves, but because you continuously graduate common patterns from the probabilistic layer to the deterministic one. The LLM’s job shrinks to only what genuinely requires inference. Everything else runs cheaper, faster, and more predictably.</p><h3>Key Takeaways</h3><ul><li><strong>Fewer, well-defined tools beat many overlapping ones.</strong> Check for semantic overlap before deployment.</li><li><strong>RAG belongs behind a tool</strong>, not pre-injected into every prompt. Let the model decide when it needs context.</li><li><strong>Classification is cheap; generation is expensive.</strong> Put a fast decision point before the capable model.</li><li><strong>Terminal states in tool contracts prevent loops</strong> better than any retry logic.</li><li><strong>Observe your catch-all.</strong> It’s your roadmap for the next deterministic handler.</li><li><strong>Linear chain first. Graph only when the problem is genuinely a graph.</strong></li></ul><blockquote>The best AI system is not the one with the most sophisticated components — it is the one where each component runs only when it earns its cost.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6a4d5f92865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Workflow to Streaming Pipeline: Modernizing a Legacy Query Engine in Kotlin]]></title>
            <link>https://medium.com/@jsanca/from-workflow-to-streaming-pipeline-modernizing-a-legacy-query-engine-in-kotlin-c0011f993099?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0011f993099</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[data-streaming]]></category>
            <category><![CDATA[helianthus]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 05:20:44 GMT</pubDate>
            <atom:updated>2026-06-19T05:20:44.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JskqLuXNauHwsFuSgWRCTw.png" /><figcaption>from workflow to streaming</figcaption></figure><p>A few days ago I started a side project called Helianthus.</p><p>The original codebase was a small query framework written around the Java 1.4 era. It exposed database operations through a servlet-based workflow and produced results in multiple formats. The project wasn’t particularly large, but it represented a situation many engineers eventually face: legacy code, servlet-centric architecture, early materialization of data, and tight coupling between execution and rendering.</p><p>My original goal was simple: learn Kotlin by modernizing an existing codebase. What I didn’t expect was that the most interesting outcome would not be the Kotlin migration itself, but a redesign of the execution model — specifically, how data flows through the system and who is responsible for cleaning up after it.</p><h3>The Original Workflow</h3><p>The legacy implementation followed a straightforward model:</p><pre>Request → Workflow → Query Execution → Formatter → Servlet Response</pre><p>Each workflow step had direct access to the servlet request and response. A formatter would eventually serialize the result and write directly to the HTTP response. Conceptually simple, but it introduced several structural problems: difficult to test, coupled to the Servlet API, execution and rendering mixed together, and all rows materialized before any processing could occur. That last point became particularly important. The system loaded entire query results into memory before a single transformation could run.</p><h3>The First Refactor: From Workflow to Pipeline</h3><p>While modernizing the code, I realized that what I really wanted was not a workflow — I wanted a pipeline. Instead of execute → format, I wanted:</p><pre>Resolve → Bind → Query → Project → Filter → Limit → Materialize</pre><p>Each stage performs a single responsibility and remains independent from HTTP concerns. The controller handles HTTP. The pipeline handles data. This separation immediately improved testability and composability.</p><p>The interface that defines each stage is deliberately minimal:</p><pre>interface PipelineComponent {<br>    fun process(context: PipelineContext): PipelineContext<br>}</pre><p>One method. One responsibility. The pipeline is a list of these components executed in sequence, each receiving and returning a shared context. Assembly happens in a factory:</p><pre>fun createPipeline(request: OperationRequest): Pipeline {<br>    val steps = listOf&lt;PipelineComponent&gt;(<br>        ResolveStep(catalog),<br>        BindStep(),<br>        QueryStep(genericDataAccess),<br>        ProjectStep(),<br>        FilterStep(),<br>        LimitStep(),<br>        ToResultFrameStep()<br>    )<br>    return Pipeline(steps)<br>}</pre><p>The ordering here is not arbitrary. Project runs before Filter so that filtering only evaluates columns that will actually appear in the result. Bind runs before Query so that parameters are validated and coerced before any SQL reaches the database. Each position in the sequence encodes a design decision.</p><h3>The Streaming Problem</h3><p>At first, the pipeline still materialized all rows after QueryStep. That worked, but it raised an obvious question: what happens when a query returns 500,000 rows and the client only needs the first 100?</p><p>The pipeline needed to become lazy. Instead of materializing results at the query boundary, each stage needed to receive a stream and return a transformed stream — no rows collected until the very end.</p><h3>Introducing CloseableRowStream</h3><p>The key abstraction is CloseableRowStream:</p><pre>interface CloseableRowStream : AutoCloseable {<br>    val schema: ResultSchema<br>    val rows: Sequence&lt;Map&lt;String, Any?&gt;&gt;<br><br>    fun withSchema(newSchema: ResultSchema): CloseableRowStream<br>    fun transformRows(<br>        transform: (Sequence&lt;Map&lt;String, Any?&gt;&gt;) -&gt; Sequence&lt;Map&lt;String, Any?&gt;&gt;<br>    ): CloseableRowStream<br>}</pre><p>rows is a Sequence — Kotlin&#39;s lazy evaluation primitive. Nothing is fetched from the database until something iterates the sequence. Pipeline stages like ProjectStep and FilterStep compose transformations over the sequence without triggering any evaluation. The chain of transformations builds up, and the rows flow only when ToResultFrameStep finally consumes them.</p><p>withSchema and transformRows are not convenience methods — they are the mechanism by which stages like ProjectStep transform the stream without breaking the resource ownership chain. When a projection reduces the column set, it does not modify the stream in place; it returns a new DefaultRowStream that wraps the same underlying sequence and delegates close() to the original stream. The JDBC resources remain owned by JdbcRowStream throughout.</p><h3>The Resource Lifecycle: Where the Real Complexity Lives</h3><p>Introducing streaming was not the hard part. Managing resource ownership correctly was.</p><p>A JDBC ResultSet cannot remain open indefinitely. It holds a cursor on the database server, a PreparedStatement that must be closed, and a Connection that must be returned to the pool. When rows become lazy, the question of who closes these resources — and when — becomes architectural.</p><p>The answer lives in JdbcRowStream:</p><pre>class JdbcRowStream(<br>    override val schema: ResultSchema,<br>    private val resultSet: ResultSet,<br>    private val statement: PreparedStatement,<br>    private val connection: Connection<br>) : CloseableRowStream {<br><br>    override val rows: Sequence&lt;Map&lt;String, Any?&gt;&gt; = sequence {<br>        try {<br>            while (resultSet.next()) {<br>                val row = linkedMapOf&lt;String, Any?&gt;()<br>                for (col in schema.columns) {<br>                    val value = resultSet.getObject(col.name)<br>                    row[col.name] = if (resultSet.wasNull()) null else value<br>                }<br>                yield(row)<br>            }<br>        } finally {<br>            close()<br>        }<br>    }<br><br>    @Volatile<br>    private var closed = false<br><br>    override fun close() {<br>        if (!closed) {<br>            closed = true<br>            closeQuiet(resultSet)<br>            closeQuiet(statement)<br>            closeQuiet(connection)<br>        }<br>    }<br>}</pre><p>There are two independent paths through which resources get closed, and both need to work correctly.</p><p>The first path is natural exhaustion: when ToResultFrameStep iterates the sequence to its end, the finally block inside the sequence { } coroutine fires and calls close(). This handles the happy path.</p><p>The second path is early termination or exception: ToResultFrameStep wraps the stream in a use { } block, which calls close() when the block exits, regardless of whether the sequence was fully consumed or an exception was thrown mid-stream.</p><pre>override fun process(context: PipelineContext): PipelineContext {<br>    val stream = context.rowStream<br>        ?: throw IllegalStateException(&quot;No row stream to materialize&quot;)<br><br>    try {<br>        stream.use { s -&gt;<br>            val frame = RowStream.toResultFrame(s)<br>            context.resultFrame = frame<br>        }<br>    } finally {<br>        context.rowStream = null<br>    }<br><br>    return context<br>}</pre><p>Both paths can fire in the same execution — the sequence exhausts naturally and use also calls close() on exit. The @Volatile closed guard in JdbcRowStream ensures that only the first call to close() does any work. @Volatile is necessary here because in a more concurrent context, two threads could conceivably race to close the stream; without it, the closed flag is not guaranteed to be visible across threads.</p><p>Setting context.rowStream = null after materialization is intentional. It makes it impossible for any downstream code to accidentally interact with a stream that has already been closed and whose resources have been returned to the pool.</p><h3>Ownership Transfer at the Query Boundary</h3><p>There is a subtler lifecycle moment that happens earlier, inside JdbcGenericDataAccess, when the stream is first created:</p><pre>val stream = JdbcRowStream(schema, resultSet, statement, connection)<br><br>resultSet = null<br>statement = null<br>connection = null<br><br>return stream</pre><p>Those three null assignments are not cleanup — they are a deliberate transfer of ownership. Once JdbcRowStream is constructed, it owns the resources. The local variables are nulled out so that the catch block&#39;s closeQuiet calls do not double-close them if something goes wrong after this point. If JdbcRowStream&#39;s constructor had thrown, the resources would still be owned by the local scope and the catch block would close them correctly. The null assignments mark exactly where ownership transfers from the method to the stream.</p><p>This is the kind of decision that is invisible when it works and catastrophic when it is wrong.</p><h3>The Column Resolution Bug</h3><p>After implementing projections and filters, I discovered a subtle failure. Projection worked for some operations and silently failed for others. The same issue appeared later in filtering.</p><p>The root cause was embarrassingly simple. The YAML configuration referenced productCode, but JDBC returned the column name as productcode — all lowercase. A case-sensitive lookup found nothing and silently dropped the column.</p><p>At first it looked like two unrelated bugs. In reality, both were symptoms of the same missing abstraction: column resolution was not defined as a contract. Each pipeline stage resolved column names independently, with no shared strategy.</p><p>The fix was not to add .lowercase() calls in two places. The fix was to make column resolution part of the schema itself — normalizing names at the point where the schema is built from ResultSetMetaData, so that every stage downstream operates against the same normalized identifiers. withSchema on CloseableRowStream is what makes this propagation possible: when schema normalization applies, it flows to every stage via the same delegation chain that propagates close().</p><p>The lesson is that many bugs are not logic errors. They are evidence of an abstraction that should exist but does not.</p><h3>The Materialization Boundary</h3><p>The pipeline is lazy from QueryStep through LimitStep. Everything in that range is a composition of transformations over a Sequence — no rows are held in memory, no database reads beyond the fetch buffer occur, and no rendering concerns intrude.</p><p>Materialization happens exactly once, at ToResultFrameStep:</p><pre>fun toResultFrame(stream: CloseableRowStream): ResultFrame {<br>    val rows = stream.rows.toList()<br>    return ResultFrame(stream.schema, rows, ResultMetadata(rows.size))<br>}</pre><p>toList() is the single point where the lazy sequence becomes an eager collection. Before this line, the pipeline is a description of what to do. After it, the result exists in memory and can be serialized to JSON, XML, CSV, or HTML by whichever converter the client requested.</p><p>Having a named, explicit materialization boundary matters for several reasons. It makes memory allocation visible and predictable. It keeps all I/O contained to a single step. And it makes testing earlier stages trivial — any step from Project through Limit can be tested by passing a synthetic CloseableRowStream with known rows, with no database involvement.</p><h3>Beyond the Pipeline</h3><p>The pipeline became the execution core of a broader declarative backend platform. Operations are declared in YAML:</p><pre>operations:<br>  products:<br>    queryRef: products.base<br>    configurations:<br>      default:<br>        pipeline:<br>          - limit: 100<br>      compact:<br>        pipeline:<br>          - project: [productCode, productName, productLine]<br>          - limit: 50<br>      expensive:<br>        pipeline:<br>          - filter:<br>              buyPrice:<br>                gt: 50<br>          - project: [productCode, productName, buyPrice]</pre><p>A single request to GET /api/op/products/expensive.json resolves the operation, binds parameters, streams rows from JDBC, applies the filter and projection as lazy transformations, materializes the result, and serializes it to JSON — without a single custom controller or service class. The pipeline handles it.</p><p>A React admin UI consumes the catalog and dynamically generates forms and execution screens. But that is a story for another article.</p><h3>Final Thoughts</h3><p>The original objective was to migrate a small Java application to Kotlin. The most interesting result was architectural rather than syntactic.</p><p>By moving from a servlet-centric workflow to a lazy streaming pipeline, several things changed at once: execution became composable, transformations became testable in isolation, memory usage became bounded and predictable, rendering became independent of data access, and resource ownership became explicit and verifiable.</p><p>Kotlin’s Sequence and coroutine-based sequence { } builder made the lazy evaluation natural to express. But the language feature was not the point. The point was identifying that the original model had baked in a constraint — eager materialization — that was not inherent to the problem, only to the implementation.</p><p>Sometimes the most valuable part of a modernization is not what you add. It is the constraint you discover you were never required to keep.</p><p>About the project: <a href="https://github.com/jsanca/helianthus">https://github.com/jsanca/helianthus</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0011f993099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Lazy.of() to LazyConstant.of(): Java is Finally Doing This Natively (Sort Of)]]></title>
            <link>https://medium.com/@jsanca/from-lazy-of-to-lazyconstant-of-java-is-finally-doing-this-natively-sort-of-08d9f0c37a2b?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/08d9f0c37a2b</guid>
            <category><![CDATA[lazyconstant]]></category>
            <category><![CDATA[jdk-26]]></category>
            <category><![CDATA[vavr]]></category>
            <category><![CDATA[stablevalue]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 02:04:29 GMT</pubDate>
            <atom:updated>2026-06-16T02:04:29.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4m9bQicUZJwnWJon0nStCQ.png" /><figcaption>From Vavr to LazyConstant</figcaption></figure><p>If you’ve been writing Java long enough, you’ve reached for Vavr’s Lazy at some point. It was clean, it was thread-safe, and it made you feel like you were writing a grown-up language. Now the JDK is building something similar natively — and the journey to get there is worth understanding before you decide what to do with it.</p><p>Let’s talk about the problem first.</p><h3><strong>The Pain: final Wants Everything Now</strong></h3><p>Java’s <em>final</em> keyword is a promise to the JVM: “<em>this value will never change”</em>. In return, the JVM rewards you with constant folding and other optimizations. It’s a good deal — but it comes with a strict condition: you must initialize the value eagerly, right at the point of declaration or in the constructor.</p><p>That constraint causes real problems. Here are three you’ve probably lived through.</p><h4><strong>1. The Classic Singleton</strong></h4><p>The textbook singleton looks innocent enough:</p><pre>public class DatabasePool {<br>    private static DatabasePool instance;<br><br>    public static DatabasePool getInstance() {<br>        if (instance == null) {<br>            instance = new DatabasePool(); // ❌ Not thread-safe<br>        }<br>        return instance;<br>    }<br>}</pre><p>Not thread-safe. Two threads can both see null and create two instances. So you add synchronized:</p><pre>public static synchronized DatabasePool getInstance() {<br>    if (instance == null) {<br>        instance = new DatabasePool();<br>    }<br>    return instance;<br>}</pre><p>Now it’s thread-safe, but you’ve added a lock to every single read — even after the instance exists. So you reach for double-checked locking:</p><pre>public class DatabasePool {<br>    private static volatile DatabasePool instance; // volatile is required<br><br>    public static DatabasePool getInstance() {<br>        if (instance == null) {<br>            synchronized (DatabasePool.class) {<br>                if (instance == null) {<br>                    instance = new DatabasePool();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>}</pre><p>This works, but look at what you had to write. Two null checks, a synchronized block, and volatile — which you need because without it, the JVM’s memory model can let other threads see a partially constructed object. And because the field isn’t final, the JVM can’t apply constant folding. You solved thread safety but gave up the optimization.</p><h4><strong>2. The Heavy Service in a Spring-like Context</strong></h4><p>Imagine an application that initializes a group of services at startup:</p><pre>public class Application {<br>    // All of these are created at class-load time, whether needed or not<br>    private static final OrderService orders = new OrderService();<br>    private static final PaymentService payments = new PaymentService();<br>    private static final ReportingService reports = new ReportingService(); // takes 3 seconds to init<br>    private static final NotificationService notifications = new NotificationService();<br>}</pre><p><em>ReportingService</em> connects to a legacy system and takes three seconds to initialize. Your integration tests that never touch reporting now pay that cost on every run. You can’t make it lazy without dropping <em>final</em> — and dropping <em>final</em> means losing the JVM’s trust.</p><h4><strong>3. Lazy Initialization in a Record or Immutable Class</strong></h4><p>Records are immutable by design. But sometimes you want a derived value computed only on demand:</p><pre>public record UserProfile(String firstName, String lastName, List&lt;String&gt; roles) {<br><br>    // You want this lazy, but records don&#39;t allow non-final instance fields<br>    // This is computed every time — no way to cache it cleanly<br>    public String displayName() {<br>        return firstName + &quot; &quot; + lastName; // fine, cheap<br>    }<br><br>    public String permissionSummary() {<br>        // Imagine this is expensive — parsing, formatting, external lookup<br>        return roles.stream()<br>            .map(RoleRegistry::describe)<br>            .collect(Collectors.joining(&quot;, &quot;));<br>    }<br>}</pre><p>You can’t add a mutable cache field to a record. You could move it out to a wrapper class, but now you’ve broken the clean model. There’s no good answer in vanilla Java.</p><h3><strong>How Vavr Solved It</strong></h3><p>Vavr looked at this mess and offered something elegant:</p><pre>import io.vavr.Lazy;<br><br>public class DatabasePool {<br>    private static final Lazy&lt;DatabasePool&gt; instance = Lazy.of(DatabasePool::new);<br><br>    public static DatabasePool getInstance() {<br>        return instance.get();<br>    }<br>}</pre><p>That’s it. Thread-safe, initialized exactly once, and the field is <em>final</em> so the reference to the <em>Lazy</em> wrapper is stable. The same pattern works for services:</p><pre>public class Application {<br>    private static final Lazy&lt;OrderService&gt; orders = Lazy.of(OrderService::new);<br>    private static final Lazy&lt;PaymentService&gt; payments = Lazy.of(PaymentService::new);<br>    private static final Lazy&lt;ReportingService&gt; reports = Lazy.of(ReportingService::new);<br>    private static final Lazy&lt;NotificationService&gt; notifications = Lazy.of(NotificationService::new);<br><br>    public static ReportingService reports() {<br>        return reports.get(); // only pays the cost if you actually call this<br>    }<br>}</pre><p>Vavr deserves real credit here. It proved that Java developers wanted to <em>declare intent</em> rather than write low-level concurrency scaffolding. The pattern was so clean that it spread everywhere — not just for singletons, but for any expensive computation you wanted to defer.</p><p>The limitation? It’s a library. The JVM doesn’t know what Lazy&lt;T&gt; means. It can’t treat the <em>contents</em> of a Lazy as a constant, only the Lazy reference itself. The inner value sits one indirection away from the optimizer.</p><h3><strong>The JDK’s Answer: A Journey in Two Names</strong></h3><h4>Act 1: StableValue in JDK 25</h4><p>JDK 25 introduced StableValue under JEP 502, and the goal was exactly what Vavr had been doing — but with the JVM in on the secret.</p><p>The key insight: the JDK already had an internal annotation called <em>@Stable</em> used to tell the JIT “trust this value, it won’t change.” Things like <em>String.value</em> and internal VM structures used it. <em>StableValue</em> was a way to expose that power to user code.</p><p>The JDK 25 API was lower-level and gave you manual control:</p><pre>import java.lang.StableValue;<br><br>public class Application {<br>    private static final StableValue&lt;ReportingService&gt; reports = StableValue.of();<br><br>    public static ReportingService reports() {<br>        return reports.orElseSet(ReportingService::new);<br>    }<br>}</pre><p><em>orElseSet</em> would initialize if not yet set, or return the existing value — thread-safe, at-most-once. You also had <em>setOrThrow</em> and <em>trySet</em> for cases where you wanted more control over who initializes the value and when.</p><p>It also shipped with stable collections:</p><pre>// A list where each element is initialized lazily and independently<br>List&lt;Worker&gt; workers = StableValue.list(10, i -&gt; new Worker(&quot;worker-&quot; + i));</pre><p>The community tried it, liked the concept, and gave feedback: <em>the API is too low-level, too close to the JVM internals, and the name doesn’t communicate what it’s actually for.</em></p><h4>Act 2: LazyConstant in JDK 26</h4><p>JDK 26 took that feedback seriously. The JEP itself explains the rename directly: StableValue was appropriate for a low-level API close to the underlying JVM mechanism — but LazyConstant better captures the actual use case: <em>a single constant value that is initialized lazily.</em></p><p>The changes weren’t just cosmetic:</p><ul><li><em>orElseSet, setOrThrow, trySet </em>— all removed. The low-level manual control is gone.</li><li>The API is now purely factory-based: you provide the computing function upfront.</li><li>null is no longer allowed as a computed value (simplifies runtime checks and aligns with unmodifiable collections).</li><li><em>StableValue.list() and StableValue.map()</em> moved to <em>List.ofLazy()</em> <em>and Map.ofLazy()</em> for better discoverability.</li></ul><p>The result:</p><pre>import java.lang.LazyConstant;<br><br>public class Application {<br>    private static final LazyConstant&lt;ReportingService&gt; reports =<br>        LazyConstant.of(ReportingService::new);<br><br>    public static ReportingService reports() {<br>        return reports.get();<br>    }<br>}</pre><p>And lazy collections:</p><pre>// Each worker is initialized only when that index is first accessed<br>final List&lt;Worker&gt; workers = List.ofLazy(10, i -&gt; new Worker(&quot;worker-&quot; + i));</pre><h3><strong>Side by Side: Vavr vs LazyConstant</strong></h3><pre>// Vavr<br>private static final Lazy&lt;ReportingService&gt; reports = Lazy.of(ReportingService::new);<br>ReportingService svc = reports.get();<br><br>// LazyConstant (JDK 26, preview)<br>private static final LazyConstant&lt;ReportingService&gt; reports = LazyConstant.of(ReportingService::new);<br>ReportingService svc = reports.get();</pre><p>The surface API is nearly identical — intentionally so. But the differences matter:</p><p><strong>What’s the same:</strong></p><ul><li>Factory method takes a Supplier</li><li>Thread-safe, at-most-once initialization</li><li>.get() to retrieve the value</li><li>Declare the wrapper as final</li></ul><p><strong>What’s different:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPtO-YdUp_D4OS2ff8WPqw.png" /><figcaption>Vavr vrs JDK</figcaption></figure><p>The optimization difference is the real story. When you declare:</p><pre>private static final LazyConstant&lt;ReportingService&gt; reports = LazyConstant.of(ReportingService::new);</pre><p>The JVM can — after the first initialization — treat reports.get() as if it were reading a static final field directly. The JIT can constant-fold it, inline it, eliminate redundant reads. Vavr can’t offer this because the JVM has no idea what’s inside that <em>Lazy&lt;T&gt; wrapper.</em></p><h3><strong>The Honest Disclaimer</strong></h3><p>LazyConstant is in its <strong>third preview</strong> in JDK 26. To use it today:</p><p><em>javac — enable-preview — release 26 Main.java</em></p><p><em>java — enable-preview Main</em></p><p>Preview features can change. StableValue shipped in JDK 25, got renamed and simplified in JDK 26 — the API you write today might need updates when this graduates to a permanent feature. That’s the contract with preview APIs.</p><p>Should you use it in production today? Probably not, unless you’re comfortable tracking JEP changes. Keep using Vavr. It’s stable, it works, and it will keep working.</p><p>Should you learn it and experiment? Absolutely. The direction is clear, and when LazyConstant graduates — it’s not a question of if, the concept is too well-established to disappear — you’ll want to be ready.</p><h3><strong>Why This Moment Matters</strong></h3><p>There’s something bigger happening here than a single API.</p><p>For years, the Java ecosystem survived by working <em>around</em> the JDK. Vavr gave us functional constructs. Lombok gave us less boilerplate. Spring gave us dependency injection and lazy initialization at the framework level. The community was essentially building the language that the JDK wasn’t providing.</p><p>What’s exciting about the modern JDK — with Project Valhalla slowly arriving, with records and sealed classes already here, with pattern matching maturing — is that the platform is finally moving in the same direction the community already went. LazyConstant is the JDK saying: <em>you were right, this should have been built-in, and now it will be — but done properly, at the JVM level, not just in library code.</em></p><p>Valhalla will deepen this further. When value types arrive, the overhead gap between a library wrapper and a native JVM construct will grow even larger. The JVM will be able to flatten and optimize things that today require heap allocation and pointer indirection.</p><p>LazyConstant is a preview. But it’s a preview of a JDK that’s becoming the language its community always wanted it to be. That’s worth paying attention to.</p><p><em>LazyConstant is a preview feature in JDK 26 (JEP 526, third preview as of this writing). All code examples require — enable-preview to compile and run. The API may change before it graduates to a permanent feature.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08d9f0c37a2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Silicon and Marble: An Architect’s Guide to Attention in the Age of AI Agents]]></title>
            <link>https://medium.com/@jsanca/silicon-and-marble-an-architects-guide-to-attention-in-the-age-of-ai-agents-555eeff9c616?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/555eeff9c616</guid>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[the-age-of-ai]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 22:05:38 GMT</pubDate>
            <atom:updated>2026-06-10T22:05:38.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-uinPpMT8p6cS1KGUuD_A.png" /><figcaption>silicon and marble</figcaption></figure><h3>I. The City Before the Code</h3><p>Imagine a Roman settlement at the moment of its founding.</p><p>Before a single stone is placed, someone draws the map. The forum will anchor the center. The main road will cut straight through the settlement, wide enough for commerce and armies. The aqueduct will follow the contour of the land. Gates will mark the thresholds. Walls will define what is inside and what is not.</p><p>This act — deliberate, structured, intentional — is the founding gesture of every city worth building.</p><p>Now imagine a software system at the moment of its design.</p><p>Before a single class is written, someone draws a different kind of map. A domain model will anchor the business logic. A dependency graph will determine what knows about what. An API surface will expose what the outside world can touch. Bounded contexts will separate what should evolve independently. Some modules will carry critical weight. Others will serve peripheral roles.</p><p>The materials are different — silicon instead of stone, edges instead of mortar — but the gesture is identical.</p><p>A system is a graph. Classes, services, functions, repositories, queues, handlers, and policies become nodes. Calls, dependencies, data flows, event streams, and ownership relationships become edges. To design software is to decide, deliberately and with intention, which nodes matter most and how they connect to each other.</p><p>Architecture is the act of drawing that first map.</p><p>And like every Roman city planner who has ever set chisel to stone, the architect faces the same fundamental question: where does the marble go?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8m0i233x8UP2f1sEg9lg3Q.png" /><figcaption>Bytes and Marble</figcaption></figure><h3>II. The Hypothesis of the Trazado</h3><p>Every architectural decision made before production is, at its core, a hypothesis.</p><p>It may be a well-informed hypothesis — built on years of experience, domain knowledge, pattern recognition, and hard-won intuition. But it is still a conjecture about a future that has not yet arrived.</p><p>We predict that a certain flow will carry most of the traffic. We anticipate that a certain module will absorb most of the change. We assume a given abstraction will hold its shape under real usage. We expect a particular integration point to remain stable. We believe a cache is not necessary yet. We trust that a helper function will stay simple.</p><p>These are architectural bets. Some of them will be correct. Others will not survive first contact with real users.</p><p>This has always been true. But in the current era, it carries a new weight.</p><p>AI coding agents have dramatically accelerated the pace of construction. A feature that once demanded days of careful implementation can now emerge in hours. The scaffolding goes up fast. The roads are laid quickly. And that speed — genuinely useful, genuinely valuable — also means that a flawed hypothesis can propagate further and faster than ever before.</p><p>When an architect directs an agent to build a component, the agent does not question the placement. It does not challenge the hierarchy. It does not ask whether this module deserves more attention than that one. It executes the instruction with skill and efficiency.</p><p>Which means the quality of the outcome depends, more than ever, on the quality of the architectural <strong><em>intent</em></strong> behind the instruction.</p><p>This is not an argument against agents. It is an argument for clarity. The Roman city planner who delegates construction to skilled workers does not abdicate judgment — they sharpen it. The delegate executes; the planner decides where the marble goes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAUl2BN6_wH0x_N3QwCFuw.png" /><figcaption>Il trazado: the quality of the architectural <em>intent</em> behind the instruction</figcaption></figure><h3><strong>III. What the Evidence Reveals</strong></h3><blockquote>The city is built… Users arrive… Traffic flows…</blockquote><p>And the map, almost immediately, begins to tell you where it was wrong.</p><p>A module you considered peripheral starts appearing in critical traces. A service you designed for occasional use becomes the hottest path in the dependency graph. An endpoint you thought would rarely be touched accumulates the highest failure rate. An abstraction you deemed elegant begins accruing workarounds that reveal its mismatch with the domain it was meant to model.</p><p>Simultaneously, a beautifully engineered plaza sits nearly empty. A heavily reinforced bridge carries almost no load. An abstraction layer that cost weeks of careful thought turns out to protect a boundary nobody crosses.</p><blockquote>This is not failure. This is information.</blockquote><p>And <strong>observability/telemetry</strong> is the instrument that converts production behavior into architectural intelligence.</p><p>Logs, traces, metrics, error rates, latency distributions, call graphs, saturation signals — these are not merely operational concerns. They are empirical feedback on the hypotheses you made before the first user arrived. They tell you which streets became avenues. They reveal which peripheral neighborhood grew into an economic center. They show you where the drainage is failing and where the walls are absorbing more pressure than the original design intended.</p><p>Without this feedback, architecture is defended by opinion. With it, architecture is refined by evidence.</p><p>The mature architectural cycle is not:</p><blockquote><em>design → implement → done</em></blockquote><p>It is closer to:</p><blockquote><em>hypothesize → build → observe → learn → reinforce → re-hypothesize</em></blockquote><p>The first design is the opening move. Observability is what keeps the game honest.</p><p>In the age of agents, this feedback loop becomes more important, not less. If an agent can build faster than humans can observe, the risk is not that the code will be poorly written — it is that well-written code will accumulate in the wrong places. Clean stone laid on a misaligned foundation does not make the structure sound.</p><p>The architect who embraces observability as a core design discipline — not an operational afterthought — is the one who can direct that velocity toward the right structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0Iqhfzsab05kqWZ3-Zb_A.png" /><figcaption>Observance &amp; reinforce</figcaption></figure><h3><strong>IV. Attention as a Finite Resource</strong></h3><p>Here is the part that software discussions rarely confront directly.</p><blockquote>Attention is scarce.</blockquote><p>Not just human attention in the abstract sense — but specifically the focused architectural attention required to evaluate, challenge, shape, and reinforce the critical structures of a system. That attention is finite. It cannot be spread uniformly across an entire codebase without losing its value.</p><p>This creates a discipline that is uncomfortable for engineers who are drawn to perfection: the discipline of deliberate neglect.</p><p>Not every module deserves the same scrutiny. Not every service requires the same depth of architectural review. Not every corner of the codebase needs to be challenged, refined, and elevated to the same standard.</p><p>Some structures carry the weight of the city. They are the bridges, the gates, the aqueducts. They process authorization, handle payments, manage publishing pipelines, enforce security boundaries, orchestrate critical workflows. These are the nodes where failures propagate widely, where changes ripple unpredictably, where the cost of a flawed design compounds over time. <strong><em>These deserve marble</em></strong>. They deserve your full attention, your architectural instinct, your careful review of what the agent produced.</p><p>Other structures serve local, bounded, low-risk purposes. A migration script that runs once. An administrative utility used by a handful of people. A simple mapper that translates between two representations nobody else depends on. These can be decent without being exceptional. If the agent produced clean, readable, functional code in these areas, that is enough. The risk of a flawed design is contained. The cost of error is low.</p><p>The cognitive bias you are allowing yourself in the second case is not negligence — it is proportionality. You are applying trust where the blast radius is small and redirecting vigilance toward structures where it matters most.</p><p>But this proportionality only works if it is grounded in evidence, not just intuition.</p><p>This is precisely where observability closes the loop. What you initially categorize as a low-stakes component may, through production data, reveal itself to be far more central than you anticipated. A simple helper that found its way into every critical path. A secondary module that quietly became the system’s most frequently traversed node. An “internal” service that external teams began depending on without announcement.</p><p>When observability surfaces these surprises, the appropriate response is not embarrassment — it is reallocation. Redirect your attention. Elevate the design. Reinforce the structure.</p><p>The city does not fail because an alley was built without marble. It fails when an alley becomes a main road and nobody notices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkl9bAZGlgI8JJ_e9nScfQ.png" /><figcaption>prioritize the architect attention</figcaption></figure><h3><strong>V. The Architect’s Remaining Role</strong></h3><p>There is a version of the AI-assisted development future that is seductive and slightly wrong.</p><p>In this version, agents handle the code, quality is enforced by rules and linting, patterns propagate automatically, and the architect gradually becomes a reviewer of outputs rather than a shaper of systems.</p><p>That version misunderstands what architecture actually is.</p><p>Rules can enforce style. Linters can catch surface violations. Agents can apply patterns with impressive consistency. But none of these mechanisms understand the graph. None of them know which nodes are load-bearing. None of them can sense when a boundary is absorbing the wrong kind of pressure, or when a dependency is creating a fragile coupling that will matter in six months.</p><p>The difference between a well-directed agent and an undirected one is not the quality of the code it produces. It is whether that code is placed with intention in the right location within the graph.</p><p>A weak instruction sounds like: <em>“Refactor this module and clean it up.”</em></p><p>A strong instruction sounds like: <em>“This authorization resolver sits in the critical path of every content publishing operation. It currently logs internal state that should not be exposed in denial responses. The scope evaluation logic needs stronger test coverage. Preserve all existing behavior, improve semantic clarity in the denial path, and ensure the output is safe to render externally.”</em></p><p>The second instruction is only possible because someone understood the graph. Someone knew the traffic pattern. Someone read the observability data and understood what this node actually does under production conditions.</p><p>That is the architect’s irreducible contribution: not writing the code, but knowing the city well enough to direct where the effort goes.</p><p>In the age of agents, that judgment does not become less valuable. It becomes the constraint that everything else depends on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOpilTI5-disecbQpJUrdw.png" /><figcaption>Architect system vision</figcaption></figure><h3><strong>Final Thought</strong></h3><p>The goal was never to make every line of code beautiful.</p><p>The goal is to build systems that can live — that can be observed when something unexpected surfaces, repaired without cascading damage, extended without losing their shape, and understood by the people who will inherit them.</p><p>Clean code shapes the stone. Architecture shapes the city. Observability tells you whether the city you imagined is the one people actually inhabit.</p><p>And in the age of AI agents — where the speed of construction has outpaced the speed of reflection — knowing where to place the marble may be the most consequential architectural skill of all.</p><blockquote><em>Attention is finite. Silicon is not. Spend the former where it cannot be replaced…</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=555eeff9c616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Information Retrieval to Product Extraction: Reusing myIR to Understand an E-commerce Site]]></title>
            <link>https://medium.com/@jsanca/from-information-retrieval-to-product-extraction-reusing-myir-to-understand-an-e-commerce-site-79922c6c9d10?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/79922c6c9d10</guid>
            <category><![CDATA[product-extraction]]></category>
            <category><![CDATA[myir]]></category>
            <category><![CDATA[schema-org]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[json-ld]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 22:05:29 GMT</pubDate>
            <atom:updated>2026-06-09T22:24:00.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCa274RE0lDjtdOM2wtDvg.png" /><figcaption>From MyIR to Product Extraction</figcaption></figure><p><a href="https://github.com/jsanca/myIR">myIR</a> started as a learning project.</p><p>The original goal was not to build a scraper, an e-commerce migration tool, or a product import pipeline. The goal was simpler and more classical: revisit Information Retrieval from the ground up.</p><p>That meant working again with ideas such as tokenization, normalization, inverted indexes, term frequency, TF-IDF, BM25, document vectors, cosine similarity, ranking, and eventually crawling.</p><p>The crawler was not the product. It was infrastructure.</p><p>In an Information Retrieval system, the crawler exists because the system needs a way to build a corpus. It fetches pages, represents them as documents, extracts links, follows seeds, and gives the rest of the system something to index and search.</p><p>But then a practical problem appeared.</p><p>I needed to analyze a real WooCommerce site, discover its products, extract product details, normalize prices, collect images, and prepare the data for a later migration process.</p><p>At first glance, this looked like a separate scraping problem.</p><p>But myIR already had something valuable: it knew how to fetch pages, represent web documents, classify URLs, work with sitemaps, and expose web content to higher-level processing.</p><p>So instead of writing a product scraper from scratch, I built a product extraction layer on top of myIR.</p><h3><strong>The Shift: From Documents to Domain Entities</strong></h3><p>In the original myIR model, a web page is mostly a document.</p><p>A document can be tokenized, normalized, indexed, ranked, and retrieved. It belongs to a corpus. It has text, metadata, and a URI.</p><p>But product extraction asks a different question.</p><p>Information Retrieval asks:</p><blockquote>Given a query, which documents are relevant?</blockquote><p>Product extraction asks:</p><blockquote>Given a messy web page, what real-world entities can be inferred from it?</blockquote><p>That is a different kind of problem.</p><p>A product page is not just text. It may contain a product name, SKU, brand, regular price, sale price, images, availability, short description, OpenGraph metadata, JSON-LD structured data, and HTML fragments generated by WooCommerce.</p><pre>public record ProductCard(<br>        URI url,<br>        String name,<br>        Optional&lt;ProductPrice&gt; regularPrice,<br>        Optional&lt;ProductPrice&gt; salePrice,<br>        Optional&lt;ProductImage&gt; thumbnail<br>) {</pre><p>A category page is different again. It may contain product cards, category cards, navigation links, pagination, filters, and marketing sections.</p><p>The first architectural lesson was that product extraction does not belong to the core of myIR.</p><p>It can reuse myIR, but it should not become myIR.</p><h3><strong>What myIR Already Provided</strong></h3><p>The reason this worked was that myIR already had several useful building blocks.</p><p>It had fetching.</p><p>The project already knew how to download pages and represent them as web page objects. This meant the extraction layer did not need to start by solving HTTP, response handling, or page representation.</p><p>It had crawling.</p><p>myIR already had the concept of starting from one or more seeds, discovering links, and controlling traversal. Even when the product extractor later leaned more on sitemaps, the crawling mindset was already there.</p><p>It had URL handling.</p><p>A crawler quickly teaches you that URLs are not trivial. The same page can appear with fragments, query parameters, tracking parameters, trailing slashes, or slight variations. That experience became useful when the extractor needed to distinguish between URL canonicalization for crawling and URL identity for products.</p><p>It had page classification.</p><p>Before extracting products, it helps to know what kind of page you are looking at. Is this a product page? A category page? A homepage? An article? Something unknown?</p><p>That classification layer gave the extractor a better starting point.</p><p>It had metadata extraction.</p><p>Titles, descriptions, canonical URLs, and OpenGraph metadata were already familiar concepts in the web ingestion layer. Product extraction simply pushed the idea further into more domain-specific structures.</p><p>The important point is this:</p><blockquote>myIR did not know anything about products, but it already knew how to bring web pages into a shape where product extraction could begin.</blockquote><p>That distinction matters.</p><h3><strong>What Did Not Belong to myIR Core</strong></h3><p>Once the product extraction work started, a new set of concerns appeared.</p><p>These concerns were not really Information Retrieval concerns:</p><ul><li>JSON-LD Product extraction</li><li>Schema.org metadata</li><li>OpenGraph product data</li><li>WooCommerce-specific HTML selectors</li><li>product detail pages</li><li>product cards</li><li>category cards</li><li>navigation cards</li><li>price parsing</li><li>Costa Rican colón formatting</li><li>HTML entity decoding</li><li>product URL identity</li><li>extraction warnings</li><li>quality summaries</li></ul><p>These are application-level extraction concerns.</p><p>They are important, but they are not the same as indexing, ranking, tokenization, or retrieval.</p><p>This created an architectural boundary.</p><p>The product extractor could live in the same repository for now, but it needed to live in a clearly isolated corner.</p><p>Not because it was bad code. Not because it was unimportant. But because it represented a different layer of the system.</p><p>The core of myIR should not know about WooCommerce. It should not know about product prices. It should not know what a SKU is. It should not know that a Costa Rican price may look like ₡63,590.</p><p>Those details belong to the extraction layer.</p><h3><strong>The Architecture That Emerged</strong></h3><p>The product extraction layer evolved through small, testable steps.</p><p>The first problem was price normalization.</p><p>Real prices are not always clean. A naive parser can easily turn a product code and a price into a single incorrect number. For this site, Costa Rican colón formatting mattered. Prices such as ₡63,590, ₡145,490, or ₡5,995 needed to be parsed correctly, without accidentally mixing SKUs or product codes into the result.</p><p>Then came HTML entity decoding.</p><pre>public final class ProductPriceParser {<br><br>    private static final Logger LOGGER = LoggerFactory.getLogger(ProductPriceParser.class);<br>    private static final Pattern COLON_NUMBER = Pattern.compile(&quot;₡\\s*([\\d.,]+)&quot;);<br>    private static final Pattern PRICE_PATTERN = Pattern.compile(&quot;\\d[\\d,]*[\\d,]?(?:\\.[\\d]+)?&quot;);<br>    private static final Pattern SKU_LIKE = Pattern.compile(&quot;[A-Za-z].*\\d|\\d.*[A-Za-z]&quot;);<br><br>    public ProductPriceParser() {<br>    }<br><br>    public Optional&lt;ProductPrice&gt; parse(final Element priceElement) {<br>        Objects.requireNonNull(priceElement, &quot;priceElement must not be null&quot;);<br>        final String text = priceElement.text().trim();<br>        if (text.isBlank()) {<br>            return Optional.empty();<br>        }<br><br>        String currencySymbol = null;<br>        final Element symbolEl = priceElement.selectFirst(&quot;.woocommerce-Price-currencySymbol&quot;);<br>        if (symbolEl != null) {<br>            currencySymbol = symbolEl.text().trim();<br>        }<br><br>        return parseText(text, currencySymbol);<br>    }</pre><p>Real HTML often contains encoded or double-encoded text. Product names, descriptions, and labels can contain values such as S&amp;amp;amp;J or encoded angle brackets. The extractor needed controlled decoding so the resulting product data was readable without introducing unpredictable transformations.</p><p>The next logical hurdle was product identity.</p><p>Crawler canonicalization and product identity are related, but they are not the same thing.</p><p>Crawler canonicalization asks:</p><blockquote>Have I already visited this URL?</blockquote><p>Product identity asks:</p><blockquote>Do these URLs represent the same product?</blockquote><p>For product extraction, URLs such as these should point to the same product identity:</p><pre>/producto/sole-wallet/<br>/producto/sole-wallet<br>/producto/sole-wallet?foo=bar<br>/producto/sole-wallet#categories</pre><p>That led to a CanonicalProductKey, focused specifically on product identity rather than global crawler behavior.</p><p>This quickly exposed the need for card classification.</p><p>Category pages contain many things that look like cards. Some are products. Some are categories. Some are navigation links.</p><p>Without classification, labels such as “Categorías”, “Volver”, “Ver todos”, “Bolsos”, or “Accesorios” can leak into the product results.</p><p>The extractor needed to classify extracted cards as:</p><ul><li>PRODUCT</li><li>CATEGORY</li><li>NAVIGATION</li><li>UNKNOWN</li></ul><pre>public final class CardClassifier {<br><br>   <br> public static ExtractedCardType classify(final URI url, final String label, final String rawHref) {<br>        Objects.requireNonNull(url, &quot;url must not be null&quot;);<br><br>        if (rawHref != null &amp;&amp; rawHref.startsWith(&quot;#&quot;)) {<br>            return ExtractedCardType.NAVIGATION;<br>        }<br><br>        if (isNavigationLabel(label)) {<br>            return ExtractedCardType.NAVIGATION;<br>        }<br><br>        final String path = url.getRawPath();<br>        if (path != null) {<br>            final String lower = path.toLowerCase();<br><br>            if (lower.contains(&quot;/producto/&quot;) || lower.contains(&quot;/product/&quot;)) {<br>                return ExtractedCardType.PRODUCT;<br>            }<br><br>            if (lower.contains(&quot;/category-producto/&quot;)<br>                    || lower.contains(&quot;/product-category/&quot;)<br>                    || lower.contains(&quot;/categoria-producto/&quot;)<br>                    || lower.contains(&quot;/product_cat/&quot;)) {<br>                return ExtractedCardType.CATEGORY;<br>            }<br>        }<br><br>        return ExtractedCardType.UNKNOWN;<br>    }</pre><p>Only real product cards should become product cards.</p><p>Then came explicit extraction result models.</p><p>A product detail is not the same as a product card.</p><p>A product detail page may have SKU, brand, description, availability, and multiple images. A product card may have only a name, URL, price, and thumbnail. A category is something else entirely.</p><p>So the model needed to separate:</p><ul><li>ProductDetailExtract</li><li>ProductCardExtract</li><li>CategoryExtract</li><li>PageExtractionResult</li></ul><p>This was an important modeling step.</p><p>It prevented the system from forcing every discovered thing into the same shape.</p><p>Finally, the extractor needed warnings and summaries.</p><p>A good extractor should not only return objects. It should explain the quality of what it found.</p><p>That led to warnings such as:</p><ul><li>MISSING_SKU</li><li>MISSING_IMAGE</li><li>MISSING_DESCRIPTION</li><li>PRICE_LOOKS_SUSPICIOUS</li><li>CARD_CLASSIFIED_AS_NAVIGATION</li><li>UNKNOWN_CARD_TYPE</li></ul><pre>public final class ExtractionWarnings {<br><br>    private static final BigDecimal SUSPICIOUS_PRICE_THRESHOLD = new BigDecimal(&quot;999999&quot;);<br><br>    private ExtractionWarnings() {<br>        throw new UnsupportedOperationException(&quot;Utility class should not be instantiated&quot;);<br>    }<br><br>    public static List&lt;ExtractionWarning&gt; forProductDetail(final ProductDetailExtract extract) {<br>        final List&lt;ExtractionWarning&gt; warnings = new ArrayList&lt;&gt;();<br><br>        if (extract.sku().isEmpty()) {<br>            warnings.add(ExtractionWarning.MISSING_SKU);<br>        }<br>        if (extract.images().isEmpty()) {<br>            warnings.add(ExtractionWarning.MISSING_IMAGE);<br>        }<br>        if (extract.shortDescription().isEmpty()) {<br>            warnings.add(ExtractionWarning.MISSING_DESCRIPTION);<br>        }<br>        if (hasSuspiciousPrice(extract.regularPrice(), extract.salePrice())) {<br>            warnings.add(ExtractionWarning.PRICE_LOOKS_SUSPICIOUS);<br>        }<br><br>        return List.copyOf(warnings);<br>    }</pre><p>And summary metrics such as:</p><ul><li>Pages processed</li><li>Product detail pages</li><li>Category pages</li><li>Product cards found</li><li>Unique product URLs</li><li>Products with detail</li><li>Products only from cards</li><li>Price warnings</li><li>Missing image warnings</li><li>Missing SKU warnings</li><li>Missing description warnings</li></ul><p>This changed the process from “it seems to work” into something measurable.</p><h3><strong>Trade-off 1: Reusing myIR vs Building a Separate Scraper</strong></h3><p>Reusing myIR saved time.</p><p>The project already had web ingestion primitives. It already had a crawler mindset. It already had page representations and classification concepts.</p><p>That made it easier to focus on product semantics instead of starting from HTTP and HTML fetching again.</p><p>But there was a cost.</p><p>The product extraction code introduced concerns that were not part of the original IR study. If left unchecked, this could contaminate the architecture.</p><p>A project that starts as an Information Retrieval engine can slowly become a collection of unrelated utilities unless its boundaries are protected.</p><p>The compromise was practical:</p><blockquote>Keep the product extractor in the repository for now, but isolate it as an application layer built on top of myIR.</blockquote><p>If it grows, it can become a separate module or even a plugin in another repository later.</p><p>But not yet.</p><p>Premature modularization can be as harmful as no modularization at all.</p><h3><strong>Trade-off 2: Heuristics vs Perfect Models</strong></h3><p>Product extraction from real websites is heuristic by nature.</p><p>The extractor can use JSON-LD, Schema.org, OpenGraph, WooCommerce selectors, image tags, prices, and links. But none of these sources are perfect.</p><p>JSON-LD may be missing.</p><p>OpenGraph may be incomplete.</p><p>HTML selectors may change.</p><p>Prices may be formatted in unexpected ways.</p><p>Cards may represent products, categories, or navigation.</p><p>There is no perfect model at the beginning.</p><p>So the extractor grew through layered heuristics:</p><ol><li>Prefer structured data when available.</li><li>Fall back to OpenGraph metadata.</li><li>Fall back to HTML selectors.</li><li>Decode text carefully.</li><li>Normalize product identity.</li><li>Classify cards before accepting them.</li><li>Report warnings instead of pretending everything is clean.</li></ol><p>The lesson was not to avoid heuristics.</p><p>The lesson was to make heuristics visible, isolated, and measurable.</p><h3><strong>Trade-off 3: Filtering Unknown Cards</strong></h3><p>One of the most important decisions was how to treat unknown cards.</p><p>If the extractor accepts every unknown card, the result may contain noise: categories, navigation links, marketing blocks, or random page elements.</p><p>If it rejects every unknown card, it may lose real products from sites that do not follow expected URL patterns.</p><p>For the first version, the extractor behaved conservatively.</p><p>Product cards were accepted when they looked like products. Category and navigation cards were filtered out. Unknown cards were not treated as products by default.</p><p>That made sense for the immediate goal: clean up the product discovery report and avoid obvious false positives.</p><p>But it remains a trade-off.</p><p>A future version may keep ignored cards in a separate diagnostic model, allowing the system to report how many category, navigation, or unknown cards were skipped.</p><p>That would make the extractor even more measurable without polluting the product list.</p><h3><strong>Trade-off 4: Internal Models First</strong></h3><p>Another deliberate choice was to keep the new extraction models internal.</p><p>Records such as <strong><em>ProductDetailExtract, ProductCardExtract, CategoryExtract, and PageExtractionResult</em></strong> are useful, but they do not need to become a public API immediately.</p><pre>public record ProductDetailExtract(<br>        CanonicalProductKey canonicalKey,<br>        URI url,<br>        String name,<br>        Optional&lt;String&gt; sku,<br>        Optional&lt;String&gt; brand,<br>        Optional&lt;ProductPrice&gt; regularPrice,<br>        Optional&lt;ProductPrice&gt; salePrice,<br>        Optional&lt;String&gt; availability,<br>        Optional&lt;String&gt; shortDescription,<br>        List&lt;ProductImage&gt; images,<br>        List&lt;ExtractionWarning&gt; warnings<br>) {<br><br>public record ProductCardExtract(<br>        CanonicalProductKey canonicalKey,<br>        URI url,<br>        String name,<br>        Optional&lt;ProductPrice&gt; regularPrice,<br>        Optional&lt;ProductPrice&gt; salePrice,<br>        Optional&lt;ProductImage&gt; thumbnail,<br>        ExtractedCardType cardType,<br>        List&lt;ExtractionWarning&gt; warnings<br>) {</pre><p>Keeping them internal allowed the model to evolve quickly.</p><p>That matters because extraction models are discovered through contact with real HTML. They should not be frozen too early.</p><p>The trade-off is that, as the application layer grows, some utilities may eventually need to become public or move into a dedicated module.</p><p>That is acceptable.</p><p>Architecture is not only about drawing perfect boundaries from the start. It is also about knowing when a boundary has become important enough to formalize.</p><h3><strong>The Most Important Boundary</strong></h3><p>The most important architectural boundary was this:</p><blockquote>myIR is the retrieval engine. Product extraction is an application built on top of it.</blockquote><p>That simple sentence helps decide where code belongs.</p><p>Tokenization belongs to core.</p><p>Ranking belongs to core.</p><p>Inverted indexes belong to core.</p><p>Document vectors belong to core.</p><p>Fetching and crawling belong to web ingestion.</p><p>WooCommerce selectors do not belong to core.</p><p>Price parsing does not belong to core.</p><p>Product cards do not belong to core.</p><p>Extraction warnings do not belong to core.</p><p>They may live in the same repository for now, but they should not live in the same conceptual layer.</p><h3><strong>Lessons Learned</strong></h3><p>The first lesson is that crawling infrastructure is reusable beyond search.</p><p>A crawler built for Information Retrieval can become the foundation for other web understanding tasks, as long as the layers remain separated.</p><p>The second lesson is that product extraction is not Information Retrieval, but it benefits from IR infrastructure.</p><p>The third lesson is that real HTML forces you to separate ideal domain models from extraction models.</p><p>A clean domain product and an extracted product candidate are not the same thing.</p><p>The fourth lesson is that product detail pages and product cards should not be modeled as the same thing.</p><p>They have different levels of completeness, different confidence levels, and different failure modes.</p><p>The fifth lesson is that URL identity is contextual.</p><p>Crawler canonicalization and product identity look similar, but they answer different questions.</p><p>The sixth lesson is that an extractor needs quality metrics.</p><p>Without warnings and summaries, extraction is hard to evaluate. With metrics, the system can be improved deliberately.</p><p>The seventh lesson is that application-specific logic should be isolated from the core engine.</p><p>A project can grow by reuse, but reuse should not erase boundaries.</p><h3><strong>Closing Thoughts</strong></h3><p>This product extractor was not the original purpose of myIR.</p><p>And that is precisely what made the exercise interesting.</p><p>A learning project about Information Retrieval became useful for a practical e-commerce extraction problem because it had the right lower-level primitives: fetching, crawling, page representation, URL handling, and classification.</p><p>But the experience also reinforced an architectural rule:</p><blockquote>Reuse infrastructure, but protect the core model.</blockquote><p>The product extraction layer can continue to evolve. It may eventually become a separate module, a plugin, or even a different repository.</p><p>For now, it lives as a clearly isolated application layer on top of myIR.</p><p>That is enough.</p><p>The goal was not to turn myIR into a scraping framework.</p><p>The goal was to reuse what myIR already did well, learn where the boundaries were, and build a practical extractor without losing the identity of the original project.</p><p><a href="https://github.com/jsanca/myIR">https://github.com/jsanca/myIR</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79922c6c9d10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Reusable dotCMS Site Blueprint: Lessons from a Real AI Catalog MVP]]></title>
            <link>https://medium.com/@jsanca/building-a-reusable-dotcms-site-blueprint-lessons-from-a-real-ai-catalog-mvp-fa94ed9bfba7?source=rss-125179124bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa94ed9bfba7</guid>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[dotcms]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[template]]></category>
            <category><![CDATA[themes]]></category>
            <dc:creator><![CDATA[Jsanca]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 21:02:54 GMT</pubDate>
            <atom:updated>2026-06-09T21:09:28.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_-Vsx5KBAajCqiIvABFpw.png" /><figcaption>dotCMS MVP</figcaption></figure><p>When building sites in dotCMS, the documentation can help you understand the map, but the code, the logs, and the Page Editor are usually the real source of truth.</p><p>This blueprint documents the practical lessons learned while building a reusable catalog-driven site in dotCMS. The goal was not only to create a nice landing page, but to understand how to build a repeatable foundation for future business sites: content types, assets, templates, containers, starters, URL-mapped detail pages, and eventually an AI-powered product assistant.</p><p>The result is a small but real MVP:</p><ul><li>A reusable dotCMS starter.</li><li>A product catalog loaded as structured content.</li><li>A landing page with editable promotional banners.</li><li>A product listing.</li><li>A basic product detail page using URL-mapped content.</li><li>A path toward an AI chat assistant connected to the catalog.</li></ul><p>This is not a full ecommerce platform yet. There is no checkout, no cart, no advanced inventory, and no variant selection. That is intentional. The first goal was to prove a reusable content architecture.</p><h3><strong>1. The Business Idea</strong></h3><p>The original business idea was simple:</p><p>Take an existing business catalog, extract and normalize its product data, import it into dotCMS, and generate a reusable website foundation that can be customized for different clients with limited effort.</p><p>The commercial version of this idea is:</p><blockquote>A smart catalog website with editable content, product detail pages, promotional banners, and an AI assistant that helps customers find products.</blockquote><p>For many small and medium businesses, this is more immediately valuable than building a complete ecommerce system from scratch.</p><p>A realistic first version includes:</p><ul><li>Landing page.</li><li>Product listing.</li><li>Product detail pages.</li><li>Contact or WhatsApp CTA.</li><li>Optional AI chat connected to the catalog.</li></ul><p>A later version may include:</p><ul><li>Shopify or Stripe for checkout.</li><li>WhatsApp Business integration.</li><li>CRM integration.</li><li>Inventory synchronization.</li><li>Analytics.</li><li>Personalized recommendations.</li></ul><p>The important architectural rule is:</p><blockquote>Dream big, build small, sell early, and expand only when someone pays for the next layer.</blockquote><h3><strong>2. The Architecture in Layers</strong></h3><p>The site was built using a layered pipeline inspired by the medallion architecture pattern.</p><p>Conceptually, the flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Keq2I_F12E4judT05Wrw5A.png" /><figcaption>existing catalog/site &gt; extraction &gt; Bronze &gt; Silver &gt; CT, contentlets, assets &gt; PL &amp; PDP &gt; AI tools</figcaption></figure><p>The important idea is that the dotCMS site is not created manually from scratch every time. Instead, the content model, assets, contentlets, templates, and pages can be generated or pushed as part of a repeatable process.</p><p>This changes the project from “we built one website” into “we are learning how to manufacture websites.”</p><h3><strong>3. dotCMS Starters: The First Big Lesson</strong></h3><p>One of the first major lessons was around custom starters.</p><p>dotCMS can load a starter ZIP when the database is empty. The relevant internal property is:</p><p><em>STARTER_DATA_LOAD</em></p><p>However, when running dotCMS through Docker environment variables, the property must be passed with the dotCMS environment variable convention:</p><p><em>DOT_STARTER_DATA_LOAD</em></p><p>So this is wrong:</p><p><em>STARTER_DATA_LOAD: “/data/shared/assets/site_starter.zip”</em></p><p>And this is correct:</p><p><em>DOT_STARTER_DATA_LOAD: “/data/shared/assets/site_starter.zip”</em></p><p>The logs are the best way to verify this.</p><p>When the starter is not being picked up, dotCMS falls back to the default starter.</p><p>When the custom starter is being picked up correctly, the logs clearly show that the configured starter path is being used.</p><p>Another key lesson:</p><p>The starter only runs when the database is empty.</p><p>If there are already inodes in the database, dotCMS will not reinitialize from the starter.</p><p>For local testing, the clean reset flow is:</p><pre>docker compose down -v<br>docker compose up -d<br>docker compose logs -f dotcms</pre><p>This is destructive because it removes local volumes, but it is the correct way to test a fresh starter boot.</p><h3><strong>4. File-Based dotCMS Sites</strong></h3><p>The project used dotCMS file-based assets for templates, containers, themes, and pages.</p><p>A typical structure looks like this:</p><pre>files/live/en-us/{site}/application/<br>containers/<br>templates/<br>themes/</pre><p>The important folders are:</p><pre>application/containers/<br>application/templates/<br>application/themes/</pre><p>A theme may include:</p><pre>themes/{theme}/template.vtl<br>themes/{theme}/css/styles.css<br>themes/{theme}/js/main.js</pre><p>A template may include:</p><pre>templates/{template}/properties.vtl<br>templates/{template}/layout.json<br>templates/{template}/body.vtl</pre><p>A container may include different files depending on the type of container.</p><p>This is where one of the most important lessons appeared.</p><h3><strong>5. The container_code.vtl Trap</strong></h3><p>At first, it is tempting to think that every file-based container needs a <em>container_code.vtl</em>.</p><p>That is not true.</p><p>The practical rule learned from the Page Editor was:</p><p><strong><em>Static container:</em></strong></p><pre>max_contentlets = 0<br>uses container_code.vtl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*2bZxTofOzNZedAZF0uY_GQ.png" /><figcaption>Static container structure</figcaption></figure><p><strong><em>Dynamic content container:</em></strong></p><p><em>max_contentlets &gt; 0</em></p><p>does not use <em>container_code.vtl</em></p><p>uses <em>container.vtl</em></p><p>uses <em>{contentTypeVariable}.vtl</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*aA_I7ThwnOHIuJceOyzVxw.png" /><figcaption>Dynamic container structure</figcaption></figure><p>This matters a lot.</p><p>If a container is meant to accept content through the dotCMS content palette, then container_code.vtl can interfere with the Page Editor experience.</p><p>For a dynamic content-driven container, dotCMS expects a renderer file named after the content type variable.</p><p>For example, for this content type:</p><p><strong>Hero Banner</strong></p><p>variable: <em>heroBanner</em></p><p>The renderer should be:</p><p><strong><em>heroBanner.vtl</em></strong></p><p>For a product content type:</p><p><strong>Leather Product</strong></p><p>variable: <em>leatherProduct</em></p><p>The renderer should be:</p><p><strong><em>leatherProduct.vtl</em></strong></p><p>This became one of the core rules of the blueprint:</p><blockquote>In dotCMS, rendering something visually is not the same as making it editable through the CMS.</blockquote><blockquote>A frontend implementation can look correct and still be wrong if the editor cannot manage the content through dotCMS.</blockquote><h3><strong>6. Editable Hero Slider</strong></h3><p>The landing page needed a hero banner area, but not a static one.</p><p>The requirement was:</p><p>Editors should be able to add promotional banners through the content palette.</p><p>That means the hero section had to be a dynamic container that accepts multiple Hero Banner contentlets.</p><p>The content type contained fields like:</p><pre>title<br>image<br>buttonText<br>buttonLink<br>contentHost</pre><p>The correct structure was:</p><pre>containers/syj-hero-slider/<br>container.vtl<br>heroBanner.vtl</pre><p>The container allows up to a limited number of contentlets, for example five banners.</p><p>Each selected Hero Banner contentlet renders as one slide through <em>heroBanner.vtl</em>.</p><p>The slider behavior itself is frontend logic:</p><ul><li>CSS hides inactive slides.</li><li>JavaScript activates the first slide.</li><li>JavaScript rotates between slides.</li><li>Dots or navigation can be added with vanilla JS.</li></ul><h4>The big lesson:</h4><blockquote>The container should be content-driven. The slider behavior should be frontend behavior. Do not hardcode promotional banners into the template.</blockquote><h3><strong>7. Theme and Template Rendering</strong></h3><p>Another important discovery was related to how dotCMS applies themes.</p><p>A template that is not using the correct layout structure may render as plain HTML without the expected theme.</p><p>The practical lesson was:</p><blockquote>If the template is drawn and has a layout.json, dotCMS applies the theme rendering path.</blockquote><p>The theme template then becomes responsible for rendering the layout.</p><p>A typical theme uses paths like:</p><pre>#dotParse(&quot;${dotTheme.path}html_head.vtl&quot;)</pre><p>One small but important detail is avoiding accidental double slashes in paths.</p><p>This is better:</p><pre>#dotParse(&quot;${dotTheme.path}footer.vtl&quot;)</pre><p>Instead of:</p><pre>#dotParse(&quot;${dotTheme.path}/footer.vtl&quot;)</pre><p>because the theme path may already include the trailing slash.</p><h3><strong>8. Product Listing</strong></h3><p>Once the content type and products existed, the landing page could render a basic product listing.</p><p>The product cards were intentionally simple:</p><ul><li>Product image.</li><li>Title.</li><li>Brand or category.</li><li>Price.</li><li>Link to the product detail page.</li></ul><p>The important thing was not to build a full ecommerce catalog yet.</p><p>The product listing had one job:</p><p>Prove that real imported content could be rendered as a usable catalog page.</p><p>This is enough for an MVP.</p><h3><strong>9. URL-Mapped Product Detail Page</strong></h3><p>The next step was the product detail page.</p><p>The right dotCMS pattern for this is URL-mapped content.</p><p>The target URL pattern was:</p><pre>/producto/{slug}</pre><p>The content type configuration included:</p><pre>&quot;urlMapPattern&quot;: &quot;/producto/{slug}&quot;,<br>&quot;detailPage&quot;: &quot;/producto-detail&quot;</pre><p>The detail page uses a template and a container, but the renderer should follow the same content-type-variable convention.</p><p>For the Leather Product content type, the correct renderer is:</p><p><em>leatherProduct.vtl</em></p><p>So the PDP container structure should be:</p><pre>containers/syj-pdp/<br>container.vtl<br>leatherProduct.vtl</pre><p>Not:</p><pre>containers/syj-pdp/<br>container_code.vtl</pre><p>The reason is that URL-mapped content is still content rendering. dotCMS resolves the contentlet from the URL map and then renders it using the content type renderer.</p><p>The product detail page can use:</p><p><em>$URLMapContent</em></p><p>as the resolved contentlet.</p><p>A basic PDP can render:</p><ul><li>Main image.</li><li>Title.</li><li>Brand.</li><li>Family and subfamily.</li><li>Price.</li><li>Short description.</li><li>CTA to contact.</li><li>Back link to the listing.</li></ul><p>The MVP PDP does not need:</p><ul><li>Variants.</li><li>Cart.</li><li>Checkout.</li><li>Related products.</li><li>Inventory selection.</li></ul><p>Those belong to a later commercial phase.</p><h3><strong>10. JSON Fields and Data Hygiene</strong></h3><p>While rendering the PDP, dotCMS produced warnings related to JSON fields:</p><p>No content to map due to end-of-input</p><p>The fields involved were JSON fields such as:</p><p><em>variantsJson</em></p><p><em>inventoryJson</em></p><p>The cause was not the PDP renderer. The cause was data hygiene.</p><p>Empty strings are not valid JSON.</p><p>For JSON fields, the import process should never write:</p><p><em>“”</em></p><p>It should write valid JSON defaults instead:</p><p><em>{}</em></p><p>or, when the field semantically represents a list:</p><p><em>[]</em></p><p>For fields that dotCMS expects to map as objects, {} is usually the safer default.</p><p>This became another blueprint rule:</p><blockquote>Generated contentlets should never store empty strings in JSON fields. Always write valid JSON.</blockquote><h3><strong>11. The MVP Boundary</strong></h3><p>One of the most important parts of this project was deciding what not to build.</p><p>The MVP includes:</p><ul><li>Landing page</li><li>Editable hero slider</li><li>Product listing</li><li>Basic PDP</li><li>Contact CTA</li><li>Path toward AI chat</li></ul><p>The MVP does not include:</p><ul><li>Cart</li><li>Checkout</li><li>Payments</li><li>Product variants</li><li>Inventory synchronization</li><li>ERP</li><li>CRM</li><li>Advanced analytics</li><li>Personalization</li><li>Full ecommerce workflow</li></ul><p>This boundary matters because it prevents the project from becoming too large before there is commercial validation.</p><p>The business can still sell a strong first version:</p><blockquote>A catalog website with an AI-powered product assistant and editable content.</blockquote><p>That is already valuable.</p><h3><strong>12. The AI Chat Layer</strong></h3><p>The next layer is the chat assistant.</p><p>The first commercial version does not need to be Amazon Rufus.</p><p>It only needs to answer catalog-related questions:</p><pre>&quot;I&#39;m looking for men&#39;s shoes.&quot;<br><br>&quot;Do you have wallets?&quot;<br><br>&quot;I&#39;d like something as a gift.&quot;<br><br>&quot;Which product do you recommend?&quot;</pre><p>The chat should use tools over the product catalog and return:</p><ul><li>Product name.</li><li>Short explanation.</li><li>Price.</li><li>Link to PDP.</li><li>Optional image.</li></ul><p>The first chat tool can be simple:</p><p><em>searchProducts(query, family, subfamily, limit)</em></p><p>A second tool can retrieve detail:</p><p><em>getProductBySlug(slug)</em></p><p>This keeps the assistant grounded in real catalog data.</p><p>The commercial story becomes:</p><blockquote>Your website is not only a catalog. It has a virtual assistant that helps customers find products.</blockquote><h3>13. Lessons Learned</h3><p>The most important lessons from this build were not abstract. They came from debugging real dotCMS behavior.</p><h4>The code is the source of truth</h4><p>Documentation helps, but the actual implementation, existing demo sites, logs, and Page Editor behavior reveal the real rules.</p><h4>Logs are not noise</h4><p>The logs showed when the starter was not being loaded, when dotCMS was falling back to default behavior, and when JSON fields had invalid data.</p><h4>The Page Editor is part of the architecture</h4><p>A page that renders publicly is not enough. It must also work correctly in the dotCMS editor.</p><h4>Static and dynamic containers are different worlds</h4><p>Using container_code.vtl in the wrong place can break the editable content model.</p><h4>Content type variable names matter</h4><p>For content-driven rendering, dotCMS expects renderer files named after the content type variable, such as:</p><pre>heroBanner.vtl<br>leatherProduct.vtl</pre><h4>URL mapping should not be reinvented</h4><p>For product detail pages, URL-mapped content is the right dotCMS pattern.</p><h4>Generated data must be clean</h4><p>Importers should generate valid defaults, especially for JSON fields.</p><h4>Keep the MVP small</h4><p>A small, working, reusable system is better than an unfinished ecommerce monster.</p><h3><strong>14. Final Blueprint</strong></h3><p>The reusable dotCMS site blueprint now looks like this:</p><p>1. Extract existing catalog</p><p>2. Normalize products into a clean model</p><p>3. Generate/import dotCMS content types</p><p>4. Upload assets</p><p>5. Create contentlets</p><p>6. Build reusable starter</p><p>7. Create theme</p><p>8. Create landing template</p><p>9. Add editable hero slider</p><p>10. Add product listing</p><p>11. Configure URL-mapped PDP</p><p>12. Render PDP with {contentTypeVariable}.vtl</p><p>13. Add chat tools over the catalog</p><p>14. Customize branding per client</p><p>This is the foundation for a repeatable service:</p><blockquote>Build smart catalog websites in dotCMS with editable content, reusable templates, product detail pages, and an AI assistant layer.</blockquote><p>The technical work was not just about getting one site to render.</p><p>It was about discovering the real dotCMS development model:</p><ul><li>files</li><li>templates</li><li>themes</li><li>containers</li><li>content type renderers</li><li>URL maps</li><li>starters</li><li>logs</li><li>Page Editor behavior</li></ul><p>Once those pieces are understood, the system becomes repeatable.</p><p>And that is where the business opportunity begins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa94ed9bfba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>