<?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 Eric Abell on Medium]]></title>
        <description><![CDATA[Stories by Eric Abell on Medium]]></description>
        <link>https://medium.com/@eric_abell?source=rss-7097c4cd30df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vvZ7nCpBUx89_kcjh5zKaw.jpeg</url>
            <title>Stories by Eric Abell on Medium</title>
            <link>https://medium.com/@eric_abell?source=rss-7097c4cd30df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:56:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eric_abell/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[My Local Agent Guessed the Task ID 10 Times out of 10]]></title>
            <link>https://medium.com/@eric_abell/my-local-agent-guessed-the-task-id-10-times-out-of-10-65d6de2db294?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d6de2db294</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[pydantic-ai]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 01:22:42 GMT</pubDate>
            <atom:updated>2026-11-09T01:22:42.700Z</atom:updated>
            <content:encoded><![CDATA[<p>I asked my agent to “mark the passport task done.” It answered confidently, said all the right things, and marked the wrong task done.</p><p>It did that in 10 out of 10 runs, across two different agent frameworks. And the final answer looked so reasonable that I never would have noticed if I hadn’t been able to look <em>inside</em> the run.</p><p>This post is about that bug, and more than that, about the tool that let me see it. I built a small tool-using agent on a local model, wired it up to <a href="https://phoenix.arize.com/"><strong>Arize Phoenix</strong></a> for tracing, and then used Phoenix the way you’d use a debugger: observe something odd, form a hypothesis, run an experiment, fix it, and check the fix in the same view. The fix itself turned out to be a lesson I now think applies to every agent I’ll ever build: <strong>design your tools around what the model actually knows.</strong></p><h3>The setup</h3><p>The playground is deliberately small: a task-tracker agent with three tools (add_task, list_tasks, complete_task) running entirely on my laptop.</p><ul><li><strong>Model:</strong> qwen3:8b via <a href="https://ollama.com/">Ollama</a>, on an M4 MacBook with 24 GB.</li><li><strong>Frameworks:</strong> the <em>same</em> agent built twice, once in <strong>Pydantic AI</strong> and once in <strong>LangChain/LangGraph</strong>. Both share one domain model and one set of plain-Python tool functions; each framework is just a thin adapter. That makes it a fair, side-by-side comparison.</li><li><strong>Tracing:</strong> OpenInference instrumentation sending OpenTelemetry spans to a local Phoenix server. Nothing leaves the machine.</li></ul><p>Running it looks like this:</p><pre>uv run local-agent chat -v --trace -f pydantic-ai &quot;Mark the passport task done, then tell me what&#39;s most urgent.&quot;<br>uv run local-agent chat -v --trace -f langgraph   &quot;Mark the passport task done, then tell me what&#39;s most urgent.&quot;</pre><h3>Why I added tracing in the first place</h3><p>Before Phoenix, my only window into the agent was a -v flag that logged tool calls. That&#39;s how I hit the first problems, and debugging them that way was miserable.</p><p><strong>The silent context overflow.</strong> My first live test ran for over six minutes on two short prompts. The tool-call log showed nothing useful. I ended up tailing Ollama’s server log and found this:</p><pre>slot context shift, n_keep = 4, n_left = 4091, n_discard = 2045<br>slot print_timing: id 0 | task 566 | n_gen = 7346, tg = 16.28 t/s</pre><p>Ollama’s default context window is <strong>4,096 tokens</strong>. Instructions plus tool schemas plus qwen3’s “thinking” overflowed it, Ollama silently <em>context-shifted</em> (dropped the start of the conversation, prompt included), and the model kept generating, more than 7,000 tokens, with no idea what it had been asked. The kicker: Ollama’s OpenAI-compatible /v1 endpoint, which Pydantic AI uses, <strong>ignores a per-request </strong><strong>num_ctx</strong>. The fix that works for both frameworks is to bake it into a derived model:</p><pre># ollama/qwen3-agent.Modelfile<br>FROM qwen3:8b<br>PARAMETER num_ctx 16384</pre><pre>ollama create qwen3-agent -f ollama/qwen3-agent.Modelfile</pre><p><strong>The cost of thinking.</strong> With the context fixed, a three-step task still took <strong>3.5 minutes</strong>. Back to the server log: one model turn had generated 2,456 tokens of reasoning. Turning thinking off dropped the same task to <strong>about 4 seconds</strong>. One more Ollama gotcha here: Pydantic AI’s unified thinking=False setting is silently dropped for Ollama models, so you have to send the provider setting yourself:</p><pre>settings = OpenAIChatModelSettings(max_tokens=config.max_tokens)<br>if not config.think:<br>    settings[&quot;openai_reasoning_effort&quot;] = &quot;none&quot;</pre><p>Both of those were findable, but only by grepping a server log and doing arithmetic on token counts. That’s when I decided I wanted to <em>see</em> every model call: what went in, what came out, how long it took, and how many tokens it used.</p><h3>Wiring up Phoenix (and the one gotcha)</h3><p>Phoenix runs locally with one command:</p><pre>uvx --python 3.13 arize-phoenix serve   # UI + OTLP receiver on http://localhost:6006</pre><p>The instrumentation is OpenInference, which Phoenix renders natively. LangGraph gets LangChainInstrumentor. Pydantic AI emits its own OpenTelemetry spans, and an OpenInferenceSpanProcessor translates them. Here&#39;s the core of it:</p><pre>provider = TracerProvider(<br>    resource=Resource({ResourceAttributes.PROJECT_NAME: &quot;local-agent&quot;})<br>)<br>match framework:<br>    case Framework.PYDANTIC_AI:<br>        # Must be added BEFORE the exporter: it rewrites spans in on_end,<br>        # and processors run in the order they were added.<br>        provider.add_span_processor(OpenInferenceSpanProcessor())<br>        Agent.instrument_all(InstrumentationSettings(tracer_provider=provider))<br>    case Framework.LANGGRAPH:<br>        LangChainInstrumentor().instrument(tracer_provider=provider)<br><br>provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(traces_url)))</pre><blockquote><em>⚠️ The gotcha: the convenient </em><em>phoenix.otel.register() helper adds its exporter </em>first<em>, so for Pydantic AI the translation would run after the spans were already sent. Building the </em><em>TracerProvider yourself fixes the ordering, and as a bonus the setup becomes backend-neutral. Any OTLP receiver works.</em></blockquote><p>Also worth knowing: you get Phoenix <strong>Sessions</strong> (multi-turn conversations grouped together) for free. Both instrumentors map each framework’s native conversation id (Pydantic AI’s conversation_id, LangGraph&#39;s thread_id) to the session.</p><h3>Observation: reading the first trace</h3><p>I ran the passport prompt with --trace and opened the Pydantic AI trace in Phoenix. The span tree on the left reads like a timeline of the agent loop:</p><pre>AGENT  invoke_agent agent            9.7s<br>├─ LLM   chat qwen3-agent            7.0s   419 in / 21 out   → calls complete_task<br>├─ TOOL  execute_tool complete_task  1ms<br>├─ LLM   chat qwen3-agent            1.4s   462 in / 20 out   → calls list_tasks<br>├─ TOOL  execute_tool list_tasks     &lt;1ms<br>└─ LLM   chat qwen3-agent            1.3s   526 in / 15 out   → final answer</pre><p>Before clicking on anything, the <em>shape</em> already tells you a lot:</p><ul><li><strong>All the time is in the model.</strong> The tools take a millisecond. The first LLM call took 7 seconds against ~1.4 for the others; that’s a cold start (Ollama unloads idle models after five minutes).</li><li><strong>Prompt tokens grow every round</strong> (419 → 462 → 526), because each call resends the whole conversation so far.</li><li><strong>Output tokens are tiny</strong> (15 to 21). That’s direct evidence that thinking really is off, which the invocation parameters on the span don’t show.</li></ul><p>Then I clicked the first LLM span to see exactly what the model was given. Three input messages:</p><ol><li>system: my instructions, which include <em>&quot;Before completing a task or answering any question about tasks, call list_tasks.&quot;</em></li><li>system: a message <strong>I never wrote</strong>. Pydantic AI injects it: <em>&quot;Mid-conversation system messages arrive inside user turns wrapped in </em><em>&lt;system&gt; tags…&quot;</em> That&#39;s a big part of why Pydantic AI&#39;s first request was 419 prompt tokens against LangGraph&#39;s 375 for the same prompt. You simply can&#39;t see framework-injected prompts like that without tracing.</li><li>user: <em>&quot;Mark the passport task done, then tell me what&#39;s most urgent.&quot;</em></li></ol><p>And the output: <strong>complete_task({&quot;task_id&quot;: 1})</strong>.</p><p>That’s the bug, sitting in plain sight. The model was told to call list_tasks first. It didn&#39;t. It had no task data in its context at all, and it produced an id anyway. In my seed data, the passport task <em>happened</em> to be #1, so the run &quot;worked.&quot; The final answer was correct, which is exactly why I&#39;d never have caught it from the output alone.</p><h3>Hypothesis and experiment: was it luck?</h3><p>A trace is one run. To find out whether the model was reasoning or guessing, I needed an experiment where a guess couldn’t pass. I reordered the seed data so the passport task was <strong>#3</strong>, and ran the same prompt five times per framework:</p><pre>pydantic-ai run 1:<br>    tool call   -&gt; complete_task({&quot;task_id&quot;:1})<br>    tool call   -&gt; list_tasks({&quot;include_done&quot;:true})<br>  -&gt; completed [&#39;Water the plants&#39;]  [WRONG]<br>...<br>langgraph run 5:<br>    tool call   -&gt; complete_task({&#39;task_id&#39;: 1})<br>    tool call   -&gt; list_tasks({&#39;include_done&#39;: True})<br>  -&gt; completed [&#39;Water the plants&#39;]  [WRONG]</pre><p><strong>10 out of 10 wrong, identically, in both frameworks.</strong> Every run marked <em>the plants</em> done. Worse, every run then called list_tasks, which plainly showed #1 Water the plants (done) and #3 Renew passport (open), and none of them noticed. Every answer was confident and clean.</p><p>Then the same experiment with thinking turned on: both frameworks called list_tasks first, found the passport task at #3, and completed the right one. Correct, but at about <strong>75 seconds per run</strong> instead of about 5.</p><h3>Why the model guessed “1”</h3><p>Once you can see the input, the failure stops being mysterious:</p><ul><li><strong>It had nothing to look up from.</strong> The trace shows the full context: instructions, the injected message, the request. No task data anywhere.</li><li><strong>It took the shortest path.</strong> The request says “mark … done”; there’s a tool literally named complete_task. That&#39;s the strongest match, so the model starts writing that call. The schema then demands an integer task_id, and with nothing to go on, the most probable number to write in an id slot is <strong>1</strong>: ids start at 1 in a huge amount of training data. Not luck. A <em>prior</em>. That&#39;s why it was 10/10 identical.</li><li><strong>“Look first” requires a plan.</strong> Doing something <em>other</em> than what you were asked (list before completing) is a two-step plan. Without thinking, an 8B model picks each tool in one shot, and the user’s verb outweighs a rule in the system prompt. Thinking gives it scratch space to reason “I don’t know the id, so call list_tasks,&quot; which is exactly what the --think runs did.</li></ul><p>But the real lesson was about my design, not the model. <strong>complete_task demanded something the model couldn&#39;t know.</strong> The user talks in names; the tool wanted an internal id. And a wrong-but-valid id succeeded silently. The tool only errored on ids that didn&#39;t exist.</p><h3>The fix: let the tool take what the model knows</h3><p>Instead of hoping the model plans a lookup, remove the need for one:</p><pre># before<br>def complete_task(tasks: TaskList, task_id: int) -&gt; str: ...<br><br># after<br>def complete_task(tasks: TaskList, title: str) -&gt; str:<br>    matches = tasks.find_by_title(title)<br>    match matches:<br>        case []:<br>            open_titles = &quot;, &quot;.join(f&#39;&quot;{t.title}&quot;&#39; for t in tasks.by_priority()) or &quot;none&quot;<br>            return f&#39;Error: no task matches &quot;{title}&quot;. Open tasks: {open_titles}.&#39;<br>        case [task] if task.status is TaskStatus.DONE:<br>            return f&quot;Already done: {_render(task)}&quot;<br>        case [task]:<br>            tasks.complete(task.task_id)<br>            return f&quot;Completed {_render(task)}&quot;<br>        case _:<br>            candidates = &quot;\n&quot;.join(_render(t) for t in matches)<br>            return (<br>                f&#39;Error: &quot;{title}&quot; matches several tasks, so nothing was changed:\n&#39;<br>                f&quot;{candidates}\nCall complete_task again with one exact title.&quot;<br>            )</pre><p>find_by_title returns an exact (case-insensitive) title match if there is one, otherwise the tasks sharing the most words with the query. The important property is in the error branches: <strong>ambiguous or unmatched input changes nothing</strong>, so a bad guess can no longer silently complete the wrong task.</p><p>(A unit test caught a flaw in my first version of the matching: “the passport task” also overlapped “Water <strong>the</strong> plants,” creating a false tie. Filler words like “the” and “task” are now ignored.)</p><h3>Verification: same experiment, same view</h3><p>Same reordered data, same prompt, thinking still off:</p><pre>pydantic-ai run 1:<br>    tool call   -&gt; complete_task({&quot;title&quot;:&quot;passport&quot;})<br>    tool call   -&gt; list_tasks({&quot;include_done&quot;:true})<br>  -&gt; completed [&#39;Renew passport&#39;]  [OK]<br>...<br>langgraph run 5:<br>    tool call   -&gt; complete_task({&#39;title&#39;: &#39;passport&#39;})<br>    tool call   -&gt; list_tasks({&#39;include_done&#39;: True})<br>  -&gt; completed [&#39;Renew passport&#39;]  [OK]</pre><p><strong>10 out of 10 correct</strong>, still fast, and with no extra lookup round trip. Rerunning with --trace closes the loop in the same place the bug was found: in both frameworks, the first LLM span&#39;s output is now complete_task({&quot;title&quot;: &quot;passport&quot;}). The model pulls the argument straight from the user&#39;s words, which is the one thing it had all along. The experiment now lives in the repo as a live regression test, with the target deliberately <em>not</em> at #1 so luck can&#39;t pass it.</p><h3>What tool design can’t fix</h3><p>I wanted to check the ambiguity path live, so I added “Renew passport photos” next to “Renew passport” and asked to “mark the passport renewal done.” <strong>Both frameworks completed the photos task.</strong> Wrong again, and Phoenix showed two different ways of being wrong:</p><ul><li><strong>Pydantic AI</strong> called complete_task(&quot;passport&quot;), got the &quot;matches several tasks, nothing was changed&quot; error exactly as designed, and then, with both candidates right there in its input, picked the wrong one. That&#39;s visible in the LLM span right after the error.</li><li><strong>LangGraph</strong> skipped the ambiguity entirely: it called complete_task with the exact title of the task it had <em>just added</em> — the most recent title in its context. An exact title passes any matching check.</li></ul><p>That’s the boundary. <strong>Tool design prevents errors caused by missing information. It doesn’t prevent errors of judgment about information the model has.</strong> For those, the defenses are different: human-in-the-loop confirmation for ambiguous or destructive actions, thinking, or a bigger model. That’s my next experiment, and conveniently both frameworks support pausing for approval (Pydantic AI’s deferred tools, LangGraph’s interrupt), so it&#39;ll make a good comparison.</p><h3>Takeaways</h3><ul><li><strong>Trace before you tune.</strong> Every fix in this post started as an observation in a trace or a log. Phoenix turned “the agent seems flaky” into “the first LLM span had no task data and wrote task_id: 1.&quot;</li><li><strong>Read the input, not just the output.</strong> The correct final answer hid a wrong decision. The input messages showed what the model <em>could</em> have known, including a system prompt I didn’t write.</li><li><strong>Turn a trace into an experiment.</strong> One trace is an anecdote. Reorder the data so a guess can’t pass, run it ten times, and you have a finding.</li><li><strong>Design tools around what the model knows.</strong> If a required argument isn’t in the model’s context, you’re asking it to either plan a lookup or guess, and small models guess. Take the user’s words, refuse ambiguity, and never let a wrong guess succeed silently.</li><li><strong>Small local models punish implicit assumptions.</strong> The 4k context default, thinking on by default, provider settings that get silently dropped: none of these throw an error. They just make the agent quietly worse.</li></ul><p><em>Tested on macOS (M4, 24 GB) with Ollama 0.40, qwen3:8b (Q4_K_M), Pydantic AI 2.66, LangChain 1.4 / LangGraph 1.2, and a local Arize Phoenix server.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d6de2db294" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Leak Was Invisible Until I Lined Up My Water Meter With My Sprinkler Controller]]></title>
            <link>https://medium.com/@eric_abell/the-leak-was-invisible-until-i-lined-up-my-water-meter-with-my-sprinkler-controller-5f1ac27fe8cc?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1ac27fe8cc</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[home-automation]]></category>
            <category><![CDATA[smart-home]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 01:06:58 GMT</pubDate>
            <atom:updated>2026-10-23T01:06:58.757Z</atom:updated>
            <content:encoded><![CDATA[<p>My sprinkler system had a broken pipe underground, and everything I’d normally check told me it was fine. Every head popped up. Every head sprayed. Nothing was soggy, nothing was gushing at the surface, and my water utility’s portal, with its tidy charts and its “Possible Leak” indicator, showed nothing unusual.</p><p>It turns out it had happened twice in one year. I only know because I lined up two data sources that, as far as I can tell, almost nobody puts side by side: <strong>what my smart irrigation controller says each zone did, and what my water meter says the house actually used, hour by hour.</strong></p><p>This post is about that cross-check: how to build it, the surprises in the data along the way, and why it catches a kind of leak that the usual tools are structurally blind to.</p><h3>The two data sources</h3><p>I’m building a small personal telemetry project that pulls my house’s utility usage into one database. Two of the sources are the stars here:</p><ul><li><strong>A Rachio smart sprinkler controller.</strong> Rachio has a documented public REST API with a personal API key. It logs an event every time a zone starts, finishes, gets skipped for weather, and so on.</li><li><strong>My water utility’s customer portal.</strong> It’s hosted on <strong>WaterSmart</strong> (now part of VertexOne), a platform a lot of US utilities use. The meter is a smart (AMI) meter that reports hourly usage once a day. There’s no official API, but the portal’s charts are fed by a JSON endpoint, and one request returns the <em>entire</em> account history at hourly resolution.</li></ul><p>Each source alone tells you something. Rachio knows <em>which zone ran and for how long</em>, but it has no idea how much water came out. The meter knows <em>how much water the house used each hour</em>, but it has no idea why. Put them together and you get the thing neither one has: <strong>an expected amount of water to compare against.</strong></p><h3>Pulling the Rachio history (read-only, on purpose)</h3><p>The Rachio API key is a full-access token: it can start zones, stop them, and change schedules. For an analysis script I wanted it to be <em>physically incapable</em> of doing any of that, so the client refuses anything that isn’t a GET before the request ever leaves the machine:</p><pre>import httpx<br><br>def refuse_non_get(request: httpx.Request) -&gt; None:<br>    if request.method != &quot;GET&quot;:<br>        raise RuntimeError(f&quot;read-only probe refused a {request.method} request&quot;)<br>client = httpx.Client(<br>    base_url=&quot;https://api.rach.io/1/public&quot;,<br>    headers={&quot;Authorization&quot;: f&quot;Bearer {token}&quot;},<br>    event_hooks={&quot;request&quot;: [refuse_non_get]},<br>)</pre><p>From there it’s three endpoints: /person/info gives you your person id, /person/{id} gives you your controller and its zones, and /device/{id}/event?startTime=…&amp;endTime=… gives you events (times in epoch <strong>milliseconds</strong>).</p><p>Two things I learned the hard way:</p><ul><li><strong>One month per request, max.</strong> Ask for 90 days and you get HTTP 400: &quot;Only allowed one month of event retrieval data.&quot; So you walk backward month by month.</li><li><strong>History is a rolling 365 days.</strong> The oldest event I could retrieve was exactly one year old, and everything before that came back empty. <strong>Every day you don’t save it, a day of history disappears for good.</strong> If you have a Rachio and any interest in this, start saving your event history now. A full backfill is only 13 API calls.</li></ul><h3>Surprise #1: the zone info is buried in English</h3><p>I expected zone events to have fields like zoneNumber and duration. They don&#39;t. Here&#39;s the entire shape of an event:</p><pre>id, deviceId, type, subType, category, topic, eventDate, summary, hidden, scheduleId</pre><p>Which zone ran, and for how long, lives <strong>only</strong> in the human-readable summary string:</p><pre>&quot;Front Lawn began watering at 07:30 AM (CDT).&quot;<br>&quot;Front Lawn completed watering at 07:45 AM (CDT) for 15 minutes.&quot;<br>&quot;Soaking Front Lawn for 15 minutes, started at 07:45 AM (CDT).&quot;</pre><p>(Illustrative examples, not my real zones or times.)</p><p>So reconstructing zone runs means parsing English. It’s less awful than it sounds:</p><pre>import re<br><br>PATTERNS = {<br>    &quot;ZONE_STARTED&quot;:   re.compile(r&quot;^(?P&lt;z&gt;.+?) began watering at &quot;),<br>    &quot;ZONE_COMPLETED&quot;: re.compile(r&quot;^(?P&lt;z&gt;.+?) completed watering at .* for (?P&lt;n&gt;\d+) (?P&lt;u&gt;minute|second)s?\.&quot;),<br>    &quot;ZONE_STOPPED&quot;:   re.compile(r&quot;^(?P&lt;z&gt;.+?) stopped watering at .* for (?P&lt;n&gt;\d+) (?P&lt;u&gt;minute|second)s?\.&quot;),<br>}</pre><p>Pair each ZONE_STARTED with the next ZONE_COMPLETED or ZONE_STOPPED for the same zone, and use the events&#39; eventDate (millisecond UTC) for the actual times. A few gotchas:</p><ul><li><strong>Zone names get truncated</strong> to about 20 characters with a trailing .... Match them by prefix against the zone list from /person/{id}, and be aware that two zones with long, similar names would collide.</li><li><strong>ZONE_CYCLING is not the end of a run.</strong> It marks the start of a <em>soak</em> period in cycle-and-soak watering. A cycle-and-soak watering is several separate runs of the same zone.</li><li><strong>Completion events are stamped ~10 seconds late.</strong> The next zone’s “began watering” event shows up just <em>before</em> the previous zone’s “completed” event. It looks like two valves were open at once. They weren’t.</li></ul><p>Sanity check: the durations I computed from timestamps matched the minutes stated in the summaries with a <strong>median difference of 0 seconds</strong>. The parsing holds up.</p><h3>Surprise #2: the water timestamps were lying to me</h3><p>The WaterSmart endpoint returns rows like this (values made up):</p><pre>{&quot;read_datetime&quot;: 1736931600, &quot;gallons&quot;: 214.6, &quot;flags&quot;: [&quot;irrigation_v2&quot;], &quot;leak_gallons&quot;: 0}</pre><p>read_datetime is an epoch timestamp, so naturally I treated it as UTC. Then I joined zone runs to water usage and computed the correlation between &quot;zone-minutes in this hour&quot; and &quot;gallons used in this hour.&quot;</p><p>It came out to <strong>0.006</strong>. Basically zero.</p><p>That’s impossible. Sprinklers use a <em>lot</em> of water, and an hour with three zones running should look nothing like an hour with none. Which meant the two timelines weren’t lined up.</p><p>So I scanned: interpret the water timestamps a few different ways, shift them by -8 to +8 hours, and see which version lines up with the sprinklers:</p><pre>interpretation                         shift_h    corr<br>local wall clock as UTC, label=start         0   0.860<br>true UTC, label=start                       -5   0.827</pre><p><strong>The timestamps are local wall-clock time encoded as if they were UTC</strong>, and each one labels the <em>start</em> of its hour. Read as true UTC, the series is off by the UTC offset, and the offset itself changes at every daylight saving transition, which is why a fixed shift only half-works.</p><p>The fix is small once you know:</p><pre>from datetime import datetime, UTC<br>from zoneinfo import ZoneInfo<br><br>def water_hour_start(read_datetime: int, tz: ZoneInfo) -&gt; datetime:<br>    &quot;&quot;&quot;WaterSmart labels are local wall clock dressed up as UTC.&quot;&quot;&quot;<br>    naive_local = datetime.fromtimestamp(read_datetime, UTC).replace(tzinfo=None)<br>    return naive_local.replace(tzinfo=tz)   # now a real, timezone-aware instant</pre><p>This also explained two “quirks” I’d previously written off as provider bugs. Once a year, two rows share the same timestamp: that’s the repeated 1 AM hour when DST ends. And once a year, an hour is missing: that’s the 2 AM that doesn’t exist when DST starts. <strong>Mystery duplicates and gaps around DST are a strong hint that a “UTC” timestamp isn’t actually UTC.</strong></p><p>The billing data then fell into place too: summing the corrected hourly data over each billing period matched the bill to within 100 gallons every single time, which is the meter’s register resolution.</p><h3>Building the expected amount: gallons per minute, per zone</h3><p>With both timelines aligned, the model is simple. Each hour’s water use should be roughly:</p><pre>gallons(hour) = baseline + Σ over zones ( zone_minutes(hour, zone) × gpm(zone) )</pre><p>where baseline is everything that isn&#39;t irrigation (showers, dishes, laundry) and gpm(zone) is that zone&#39;s flow rate. Fit it with ordinary least squares across a year of hours:</p><pre>import numpy as np<br><br>X = np.array([[minutes[h].get(z, 0.0) for z in zones] + [1.0] for h in hours])<br>y = np.array([gallons[h] for h in hours])<br>coef, *_ = np.linalg.lstsq(X, y, rcond=None)<br>gpm = dict(zip(zones, coef[:-1]))<br>baseline = coef[-1]</pre><p>Over a year of hours, zone-minutes alone explain about <strong>85% of the variation in hourly water use</strong> (R² ≈ 0.85). The fitted rates were physically sensible: a few gallons per minute for spray and rotor zones, much less for drip.</p><p>A bonus finding: Rachio stores its own idea of each zone’s flow, implied by the precipitation rate (inchesPerHour) and the yard area (yardAreaSquareFeet) you enter in the app. For several of my zones, the measured flow was <strong>well above</strong> what those settings implied. My area estimates were too small, which means Rachio&#39;s own water-use estimates for those zones were too low too.</p><h3>The payoff: a ratio that sits at 1.0 until it doesn’t</h3><p>Now the useful part. For each day, take only the hours when zones ran, and compare what the meter recorded with what the model expected:</p><pre>def irrigation_ratio(day_hours, gallons, minutes, gpm, baseline):<br>    actual = expected = 0.0<br>    for h in day_hours:<br>        if sum(minutes[h].values()) &lt; 5:          # only hours with real zone activity<br>            continue<br>        actual += gallons[h]<br>        expected += baseline + sum(gpm[z] * m for z, m in minutes[h].items())<br>    return actual / expected if expected else None</pre><p>On a healthy system, this ratio is boring. Day after day, it sat between <strong>0.9 and 1.05</strong>.</p><p>Then, on a handful of days, it jumped to about <strong>2.2</strong>.</p><p>Here’s an illustrative version of what one of those days looks like hour by hour. The times, zones, and values are made up, but the shape matches what I saw:</p><pre>hour   zones running          actual   expected   excess<br>06:00  A(15) B(15) C(15)        480       220       260<br>07:00  A(15) B(15) C(15)        500       220       280<br>08:00  A(12) B(12) C(10)        370       165       205<br>09:00  (none)                     4         5        -1</pre><p>Three things jump out, and together they’re a signature:</p><ol><li><strong>The excess appears only while valves are open.</strong> The moment the schedule ends, usage drops right back to normal. Overnight usage didn’t change at all.</li><li><strong>The excess is proportional to run time.</strong> Divide it by the zone-minutes in each hour and you get nearly the same number every hour.</li><li><strong>It starts mid-run and then persists.</strong> One hour of a run is normal, the next is not, and every run of that zone after that is high.</li></ol><p>That’s not a person running a hose, and it’s not a running toilet. It’s a zone that suddenly passes several times its normal flow <strong>whenever its valve is open</strong>: a broken lateral line or fitting, leaking underground.</p><h3>Two breaks, both invisible</h3><p>The first one I’d actually already found and fixed. I’d noticed something was off with one front-yard zone, dug it up, and repaired a broken lateral. The data told the same story with more precision than my memory: the zone’s flow jumped partway through a run, stayed roughly <strong>four times</strong> normal on every run after that, and dropped back to normal on the first run after my repair. It even showed the repair itself: a day with no scheduled zone runs but an unusually large amount of “other” water use, from flushing and testing the line.</p><p>The second one I hadn’t found. A back-yard zone had recently started doing the exact same thing: about <strong>17 extra gallons per minute</strong> while its valve was open, on top of its normal ~4. That’s well over double what the schedule needed, going straight into the ground, every time it ran.</p><p>The data couldn’t say which of two back-yard zones it was, because they share a schedule and alternate in matching blocks within each hour. (Lesson: if you want to isolate a zone with hourly data, run it <strong>alone</strong> in its own clock hour.) So I went out and ran each one by hand. Every head popped up. Every head sprayed normally. Nothing was visibly wet.</p><p>And on one of them, I could <strong>hear</strong> it: a gushing sound underground, with not a drop showing at the surface.</p><h3>Why nothing else caught it</h3><p>Here’s what I find genuinely interesting. My utility’s portal has an hourly usage chart and a “Possible Leak” indicator, and neither showed anything. That’s not a failing of the portal so much as a limit of having only one side of the picture: the meter knows <em>how much</em> water was used, the controller knows <em>what should have happened</em>, and a leak like this only shows up where the two disagree. Looked at separately:</p><ul><li><strong>On a usage chart, a leaking day looks like a heavy watering day.</strong> In summer, plenty of perfectly normal days are big. A day with a broken lateral is just another tall bar. <strong>A daily total can’t tell “watered a lot” from “watered normally while a pipe leaked.”</strong> You need to know how much water that day’s schedule <em>should</em> have used, and only the controller knows that.</li><li><strong>Meter leak detection looks for flow that never stops.</strong> I don’t know my utility’s exact algorithm, but the leak_gallons field was zero for every hour in my history. Utility leak alerts typically look for continuous use: a running toilet, a dripping supply line, a meter that never reads zero overnight. A broken lateral leaks <em>only while its valve is open</em>, then usage drops back to zero. It never looks continuous.</li><li><strong>The portal’s irrigation tag flagged irrigation, but missed most of it.</strong> WaterSmart marks some hours as irrigation_v2. Against a year of actual zone runs, nearly every flagged hour was a real run, but it flagged only a fraction of them and accounted for roughly a third of the water those runs actually used. And a lateral leak happens during irrigation anyway, so at best it would be labeled irrigation.</li><li><strong>The heads looked fine.</strong> A break in the lateral, or a cracked fitting below a head, doesn’t stop the heads from popping up and spraying. The water just has an easier path into the ground.</li></ul><p>So the problem was invisible from every angle that’s normally available, and obvious the moment I compared the meter with the controller.</p><h3>One more lesson: flow rates change, so date them</h3><p>While checking every zone, one drip zone came back with a measured flow about <strong>20 times lower</strong> than it used to have. A clog? No: we’d torn out a drip-irrigated garden bed and replaced it with three pots on 1 gallon-per-hour drippers. Three drippers at 1 gph is 0.05 gallons per minute, which is almost exactly what the data showed.</p><p>Same valve, same zone number, a completely different flow rate after a known change. If your analysis stores one flow number per zone forever, that change silently breaks it. <strong>Treat each zone’s flow rate as configuration with a date range</strong>, and re-fit it periodically. A re-fit that drifts away from the configured value is either a change you made or a problem you haven’t found yet.</p><h3>Try it yourself</h3><p>If you have a smart irrigation controller and your utility gives you hourly data, here’s the recipe:</p><ol><li><strong>Save your controller history now.</strong> Rachio keeps a rolling year. Everything older is gone.</li><li><strong>Get your hourly water data</strong> from your utility portal. Check its timestamps: if you see a duplicate hour and a missing hour around DST, the “UTC” timestamps are probably local time.</li><li><strong>Reconstruct zone runs</strong> from the controller’s events, then compute zone-minutes per clock hour.</li><li><strong>Fit gallons per minute for each zone</strong>, plus a baseline, with least squares.</li><li><strong>Compute a daily ratio</strong> of actual to expected gallons during irrigation hours, and alert when it leaves the 0.9–1.1 neighborhood.</li><li><strong>When it fires, run the suspect zones one at a time</strong>, each in its own clock hour, and listen.</li></ol><p>The whole analysis is a few hundred lines of Python and some DuckDB. The cross-check found two broken laterals in a year, and one of them I would otherwise have found only by noticing a soggy yard, or a water bill, much later.</p><p>Neither source knew. The water meter saw the gallons but not the schedule; the controller saw the schedule but not the gallons. The leak lived in the gap between them.</p><p><em>Data from a Rachio Gen 3 controller via its public API and a WaterSmart-hosted utility portal. All schedule times, zone names, and hour-by-hour values in this post are illustrative.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1ac27fe8cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When the Write Tool Disappeared, the Model Reached for the Shell]]></title>
            <link>https://medium.com/@eric_abell/when-the-write-tool-disappeared-the-model-reached-for-the-shell-5606b685e63b?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5606b685e63b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[coding-agents]]></category>
            <category><![CDATA[open-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-safety]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 22:34:50 GMT</pubDate>
            <atom:updated>2026-10-05T22:34:50.529Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted to understand how a coding agent actually works under the hood — not the marketing version, the real one — so I set up <a href="https://opencode.ai/">opencode</a>, an open-source coding agent harness, in a sandbox where I could watch every single thing it sent to a model.</p><p>Then I asked it to do the most boring task I could think of:</p><pre>Write a short Python script that prints &quot;Hello world&quot; and then exits.</pre><p>I expected to learn nothing. Instead, that one prompt turned into an afternoon of discoveries — and one moment that I keep thinking about: when I took away the model’s file-writing tools, it wrote the file anyway, with a shell command. Not because it was being sneaky, but because, as far as it could tell, that was simply the tool it had.</p><p>This post is about that moment, and about how much a trivial prompt can reveal when you can see everything.</p><blockquote><strong><em>A note before we start:</em></strong><em> it should go without saying that if you set out to break a tool, you usually can. That’s not what this is. I wasn’t trying to trick the model or defeat opencode’s safeguards — I used an ordinary prompt, default settings, and a single documented permission option, and simply watched what happened. Everything below is observation of normal behavior, not an exploit.</em></blockquote><h3>The setup: a glass box</h3><p>I wanted two things: the agent should not be able to reach the internet on its own, and I wanted a complete record of every request it made to a model. So, with the help of Claude Code, I built a small lab:</p><pre> ┌────────────────────────┐   plain HTTP   ┌──────────────────────────┐   HTTPS<br> │ opencode (Docker)      │ ─────────────► │ logging proxy (mitmproxy)│ ───────► OpenRouter<br> │ no route to internet   │                │ forwards to one host only│<br> │ sees only /workspace   │                │ saves every request      │<br> └────────────────────────┘                └──────────────────────────┘</pre><ul><li><strong>opencode 2.0.23</strong> runs in a Docker container on a network with no route out. It can’t resolve DNS or reach any IP address. Its only reachable neighbor is the proxy.</li><li><strong>The proxy</strong> is mitmproxy in reverse-proxy mode, pointed at <a href="https://openrouter.ai/">OpenRouter</a>. It injects the API key (so opencode never holds it) and writes every request and response to a JSON file.</li><li><strong>Two models:</strong> Claude Sonnet 5.5 (pinned to one upstream provider so results stay consistent) and GPT-6 Luna, a much cheaper OpenAI model.</li></ul><p>The capture files are the whole point. Each one holds the exact system prompt, the tool definitions, the conversation, the streamed reply, token counts, and cost. Reading them is like reading the agent’s mail.</p><h3>The moment: the write tool disappears</h3><p>This came at the end of a series of small experiments, so let me set the scene.</p><p>I had already noticed that when a hello.py <em>already existed</em> in the workspace, Sonnet would simply overwrite it with its write tool — no reading first, no question. opencode&#39;s default permissions allow file edits inside the project without asking. So I wondered: what if I change the permission rules?</p><p>opencode lets you set rules per action, with three effects: allow, ask, or deny. I ran Sonnet three times on the same prompt, with the same existing file, changing one rule each time:</p><pre>{ &quot;permissions&quot;: [ { &quot;action&quot;: &quot;edit&quot;, &quot;resource&quot;: &quot;*&quot;, &quot;effect&quot;: &quot;deny&quot; } ] }</pre><p>Here’s what happened, straight from the captures:</p><pre>policy            what Sonnet did                                   file overwritten?<br>───────────────   ───────────────────────────────────────────────   ─────────────────<br>default (allow)   write(hello.py)                                   yes<br>edit: ask         write(hello.py) → rejected → printed the script    no<br>edit: deny        shell(&quot;cat &gt; /workspace/hello.py &lt;&lt;&#39;EOF&#39; ...&quot;)    yes</pre><p>With deny, Sonnet wrote the file using a shell heredoc:</p><pre>cat &gt; /workspace/hello.py &lt;&lt;&#39;EOF&#39;<br>import sys<br>print(&quot;Hello world&quot;)<br>sys.exit(0)<br>EOF<br>python3 /workspace/hello.py</pre><p>My first reaction was “wait — it went <em>around</em> the rule?” But the captures tell a more interesting story.</p><h3>What the model actually saw</h3><p>When edit was set to deny, opencode didn&#39;t tell the model &quot;you&#39;re not allowed to edit files.&quot; It quietly <strong>removed the </strong><strong>edit and </strong><strong>write tools from the request entirely</strong> — and removed the paragraph in the system prompt that explains how to use them. Compare the tool lists the model received:</p><pre>default:    edit, glob, grep, question, read, shell, skill, subagent, webfetch, websearch, write, execute<br>edit: deny        glob, grep, question, read, shell, skill, subagent, webfetch, websearch,        execute</pre><p>From Sonnet’s point of view, there was no restriction to respect. There was a task (“write a script”), and a toolbox that happened not to contain a file-writing tool. The shell <em>was</em> in the toolbox, and a shell can write files. So it used it. That’s not evasion; that’s what you’d want a capable assistant to do with the tools in front of it. It even tried to run the script afterward to check its work.</p><h3>The contrast that made it click</h3><p>The ask run is the mirror image. In a non-interactive run there&#39;s no human to approve anything, so opencode auto-rejected the write — but this time it <strong>told the model</strong>, in the tool result:</p><pre>This non-interactive run cannot ask the user for permission, so the request was rejected.<br>Continue without this action.</pre><p>And Sonnet did exactly that. It didn’t look for another route. It printed the script in its reply and said it couldn’t save the file.</p><p>Same model, same prompt, same file. The difference was whether the restriction was <strong>explained</strong> or just <strong>made invisible</strong>. When the model was told “no,” it respected it. When the tool silently vanished, it solved the problem another way.</p><h3>The lesson I took from it</h3><p><strong>Permissions in a harness govern tools, not outcomes.</strong> opencode’s edit permission covers the edit, write, and patch tools. A shell command that writes a file is a shell action, which is allowed by default. The opencode docs actually say this plainly:</p><blockquote><em>shell runs with the host user&#39;s filesystem, process, and network authority. Directory inference from command text is best effort, so prefer a narrow shell allowlist instead of patterns intended to recognize every dangerous command.</em></blockquote><p>I’d read that sentence before the experiment and nodded along. After watching it happen, I <em>understood</em> it. If you want to protect files, you have to think about every path to the outcome — <strong>and the shell is a path to almost everything.</strong></p><h3>Everything else one Hello World revealed</h3><p>The permission experiment was the headline, but honestly, the smaller discoveries along the way taught me just as much. Here’s what a single “print Hello world” prompt exposed.</p><h3>1. One prompt, two requests</h3><p>Every prompt produced two requests to the model, sent about 3 milliseconds apart: the actual agent, and a separate <strong>title generator</strong> that names the conversation. The title request has its own little system prompt (“You are a title generator. You output ONLY a thread title…”) and no tools.</p><p>The surprise: even in a Sonnet session, the title was generated by <strong>Luna</strong> — opencode picks a cheaper model for background chores. And in one-shot opencode run mode, the process sometimes exits before the title finishes, so the session ends up with no title at all.</p><h3>2. The system prompt is a layered document</h3><p>The main system prompt is about 8,800 characters, and it has clear layers: behavior rules, an identity section, a capabilities catalog, and an environment block. The identity section is tiny:</p><pre># Your Model<br>- Name: GPT-6 Luna<br>- Provider ID: openrouter<br>- Model ID: openai/gpt-6-luna</pre><p>That explained something from my very first opencode session, before any of this: I’d asked “what model are you?” and it answered correctly — and then couldn’t tell me whether it was local or in the cloud. Now I know why. It was reading these three lines, and that’s all it knew.</p><h3>3. Different models get different instructions — and different tools</h3><p>This one genuinely surprised me. opencode sends a <strong>different system prompt and a different toolset</strong> depending on the model family:</p><ul><li><strong>Luna (OpenAI)</strong> got a single patch tool for all file changes, plus prompt sections on &quot;Destructive actions,&quot; &quot;Autonomy,&quot; and &quot;Delegation,&quot; including <em>&quot;Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.&quot;</em></li><li><strong>Sonnet (Anthropic)</strong> got separate write and edit tools, plus guidance on code comments — but not those three sections.</li></ul><p>And the behavior lined up. Faced with an existing hello.py, Luna read the directory, read the file, and replied that it already did the job and no change was needed. Sonnet wrote over it. I want to be careful here: that&#39;s a handful of runs on one task, not a study. But it was a vivid demonstration that the harness&#39;s instructions and the model&#39;s behavior are deeply intertwined — you can&#39;t really evaluate one without the other.</p><h3>4. The agent loop, made visible</h3><p>When Luna wrote the file into an empty workspace, it took three requests, and the conversation grew each time:</p><pre>request 1   2 messages   → model calls glob(&quot;*&quot;)         → &quot;No files found&quot;<br>request 2   4 messages   → model calls patch(Add file)   → &quot;Success&quot;<br>request 3   6 messages   → model writes its final answer → finish_reason: stop</pre><p>The model never touches a file. It <em>asks</em> for a tool call; the harness runs it, appends the call and its result, and sends the whole conversation back. The model has no memory between requests — every request carries the full history. I knew this in the abstract. Seeing the messages array grow from 2 to 4 to 6 made it concrete.</p><h3>5. Same words, very different token counts</h3><p>Luna’s request and Sonnet’s request were nearly identical in size (about 22,000 characters each), but Sonnet’s counted as <strong>7,406 tokens</strong> to Luna’s <strong>4,169</strong>. Different models tokenize text differently. When comparing costs, “price per token” is only half the story.</p><h3>6. Caching is engineered, not automatic</h3><p>Sonnet’s request had four cache_control markers placed carefully: after the tool definitions, after the core rules, at the end of the system prompt, and on the latest message. On the second turn, about 7,400 tokens were read from cache instead of being processed fresh, and that turn cost roughly 87% less than the first. The whole Hello World task cost about <strong>$0.0008 with Luna</strong> and about <strong>$0.022 with Sonnet</strong>.</p><h3>7. A one-word clue</h3><p>When Sonnet overwrote the existing file, the tool result said Wrote file successfully. When it created a new one, it said Created file successfully. The harness knew the difference and said so — in one word. Sonnet&#39;s final message still said &quot;I created /workspace/hello.py.&quot; It&#39;s a small thing, but it made me think about how much depends on signals being loud enough to notice.</p><h3>8. Defaults assume you’re using git</h3><p>opencode’s default policy allows everything inside the project and asks only for paths outside it and for reading .env files. The safety net is <strong>snapshots</strong>: opencode records your files before and after each model step so /undo can roll them back. But snapshots require a git repository — and my workspace wasn&#39;t one. In my setup, nothing would have recovered an overwritten file. The snapshot docs are refreshingly honest about this: they call snapshots &quot;a convenience, not a transaction or backup.&quot;</p><p>I looked for an official explanation of why the defaults are this permissive and didn’t find one; a couple of GitHub issues asked the same question. My read is that it’s a deliberate trade-off — fewer interruptions, with git plus snapshots as the recovery path — and a reasonable one, <em>if</em> you know that’s the deal.</p><h3>If you want to try this yourself</h3><ul><li><strong>Watch the wire.</strong> A logging proxy turned opencode from a black box into a glass one. You don’t need my exact setup — but if you want to understand an agent, find a way to see the actual requests.</li><li><strong>Use git before you let an agent touch anything.</strong> It’s the cheapest protection, and it’s what the harness’s own undo feature depends on.</li><li><strong>If you want approval for file changes, cover the shell too.</strong> Something like this is a better starting point than edit alone:</li></ul><pre>{<br>  &quot;permissions&quot;: [<br>    { &quot;action&quot;: &quot;edit&quot;,  &quot;resource&quot;: &quot;*&quot;,     &quot;effect&quot;: &quot;ask&quot; },<br>    { &quot;action&quot;: &quot;shell&quot;, &quot;resource&quot;: &quot;*&quot;,     &quot;effect&quot;: &quot;ask&quot; },<br>    { &quot;action&quot;: &quot;shell&quot;, &quot;resource&quot;: &quot;ls *&quot;,  &quot;effect&quot;: &quot;allow&quot; },<br>    { &quot;action&quot;: &quot;shell&quot;, &quot;resource&quot;: &quot;cat *&quot;, &quot;effect&quot;: &quot;allow&quot; }<br>  ]<br>}</pre><ul><li><strong>Sandbox it.</strong> In my lab, the worst case was losing a file in a scratch folder — not my home directory.</li><li><strong>Hold your conclusions loosely.</strong> Everything here comes from a handful of single runs of one tiny task, on one version of one harness. Models aren’t deterministic, and both opencode and the models will change.</li></ul><h3>Why a Hello World was enough</h3><p>I went in thinking a trivial prompt would be a warm-up before the real experiments. It turned out the trivial prompt <em>was</em> the experiment. Because the task itself was so simple, everything interesting stood out: the scaffolding around the model, the decisions the harness makes on your behalf, the way instructions differ between models, the economics of every turn.</p><p>And the moment that stuck with me wasn’t a failure. It was a capable model doing what capable assistants do — getting the job done with the tools it could see — and a harness whose permission system was doing exactly what it says it does. The gap was in <em>my</em> mental model: I thought I was protecting a file, when I was really just removing a tool.</p><p>That’s the kind of thing you only learn by watching.</p><p><em>Tested with opencode 2.0.23 in Docker, mitmproxy 12.2.3, and OpenRouter, using Claude Sonnet 5.5 (via Amazon Bedrock) and GPT-6 Luna, in October 2026. Results are from a small number of single runs and may not generalize.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5606b685e63b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Model Analyzes, Code Computes]]></title>
            <link>https://medium.com/@eric_abell/the-model-analyzes-code-computes-2887ce7d2147?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/2887ce7d2147</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 15:44:46 GMT</pubDate>
            <atom:updated>2026-10-01T15:44:46.747Z</atom:updated>
            <content:encoded><![CDATA[<p>Ask a language model for the mean of twenty numbers and you’ll usually get something close. Sometimes it’s exactly right. Sometimes it’s off in the second decimal. Occasionally it’s a number that appears nowhere in the arithmetic at all, and it looks <em>exactly</em> as confident as the right one.</p><p>That isn’t a flaw that will get fixed in the next release. A model produces text one token at a time by predicting what comes next. It doesn’t hold the numbers in a register and add them. When it writes “the mean is 51.6”, it’s generating a string that is very likely to follow the question. That’s often the right number, because the model has seen a lot of arithmetic. But the mechanism that makes it fluent is the same one that makes a wrong number look plausible. Nothing in the output marks the difference between a computed figure and a guessed one.</p><p>For prose, that’s fine. For data analysis, it’s the whole ballgame.</p><h3>Where this bit me</h3><p>I’ve been building a personal health-data pipeline: Apple Health exports and a wearable’s API, loaded into a DuckDB database. Most of the engineering went into one idea. <strong>The database should never hand back a misleading answer quietly.</strong> Devices change over thirteen years, coverage has holes, and a clean star schema will happily draw a smooth line across all of it.</p><p>So the read layer is defensive. Every query returns its values <em>joined to coverage metadata</em>: which sources contributed, whether the window crosses a device change, whether there are gaps. A window with no data raises an error instead of returning zero rows that average to nothing.</p><p>Then I started asking questions in chat. <em>“Compare my average HRV in August and September.”</em> <em>“How many hours did I sleep last month?”</em> My AI assistant wrote the query, ran it, and got back trustworthy rows with all their caveats attached. And then the next step happened in the model.</p><p>The rows landed in its context. It read them, did the mean in its head, and wrote “your HRV rose about 3 ms.” The caveat that the September window crossed a device change got paraphrased away. The read layer had done its job perfectly, and the answer still couldn’t be trusted, because <strong>the last consumer of the data was the model itself.</strong></p><h3>The principle</h3><p>The fix came out of a long back-and-forth with the assistant, and it reduced to one rule:</p><blockquote><strong><em>The model analyzes; code computes.</em></strong></blockquote><p>The model decides <em>what</em> to compute, states what it assumed, weighs the caveats, and explains what a result means. Code does every calculation, including the math hidden inside the question. Turning “last month” into dates is arithmetic. So is converting seconds to hours, and so is the difference in “compare”. The model quotes only numbers that code printed.</p><p>In practice, every question gets a small committed script in an analyses/ folder. It runs inside a context manager that records every read and prints a fixed report:</p><pre>&quot;&quot;&quot;Compare average nightly HRV, August vs September.&quot;&quot;&quot;<br>from statistics import fmean<br>from apple_health_explorer.evidence import Evidence<br><br>with Evidence(__file__) as e:<br>    aug = e.period(&quot;August&quot;, &quot;2026-08-01&quot;, &quot;2026-08-31&quot;)<br>    sep = e.period(&quot;September&quot;, &quot;2026-09-01&quot;, &quot;2026-09-30&quot;)<br>    e.assume(&quot;measure&quot;, &quot;mean of in-session RMSSD per night&quot;)<br>    hrv_aug = e.sleep_metric_series(HRV, aug)<br>    hrv_sep = e.sleep_metric_series(HRV, sep)<br>    a = e.result(&quot;August mean&quot;, fmean(n.mean for n in hrv_aug.rows), unit=&quot;ms&quot;, reads=[hrv_aug])<br>    s = e.result(&quot;September mean&quot;, fmean(n.mean for n in hrv_sep.rows), unit=&quot;ms&quot;, reads=[hrv_sep])<br>    e.compare(&quot;September vs August&quot;, s, a)</pre><p>The report it prints looks like this (the numbers here are made up):</p><pre>-- results --<br>September vs August<br>    September mean  48.7 ms<br>    August mean     46.9 ms<br>    difference      1.8 ms   (September mean minus August mean)<br>    percent change  3.8%     (relative to August mean)<br>    ⚠ partial: 27/30 days [2]; spans discontinuity [2]</pre><p>Two details carry most of the weight. compare() exists because the difference is exactly the number a model is most tempted to work out itself. And the ⚠ marker sits <em>on the result line</em>, so a caveat can&#39;t be separated from its number in a paraphrase. Tables also refuse to print more than 40 rows, because otherwise &quot;print the table&quot; becomes a back door for dumping raw rows into the conversation.</p><h3>Naming it</h3><p>We spent longer on the package name than on some of the code, and I think it was worth it. The first candidate was analysis, which was one letter away from the analyses/ folder. The next was answer, but the package deliberately produces only <em>half</em> the answer, because the interpretation is the model&#39;s. We settled on evidence, because the name <em>is</em> the rule: the script produces evidence, the model interprets it, and <strong>interpretation may not introduce evidence.</strong></p><h3>Enforcing it with a hook</h3><p>A rule in a prompt is a request. So we added a Claude Code Stop hook, a script that runs every time the assistant finishes a reply. Once the session has read from the database, it pulls every number out of the reply and requires each one to appear in some tool output from the session. A number with no source blocks the reply and gets named back to the model: <em>&quot;Not in any tool output this session: 3.4. Compute it in code.&quot;</em></p><p>Two design decisions surprised me:</p><ul><li><strong>It corrects; it doesn’t prevent.</strong> A Stop hook fires after the reply is already on screen. It can&#39;t un-show a bad number; it can only force a correction. Prevention comes from making the script path the easy one.</li><li><strong>We didn’t gate ad-hoc queries.</strong> I’m still doing active development, and blocking raw SQL would have killed my velocity. But dev decisions based on hand-computed numbers turn into bugs too. So data access stays unrestricted, and the hook enforces the rule in dev turns as well: put the AVG in the query, not in your head. Sources are counted across the whole session, so a follow-up that quotes an earlier answer still passes.</li></ul><h3>Validating it</h3><p>The package has 92 unit tests. Every positive case has a negative counterpart, because a check that always passes looks identical to one that works. The three motivating questions ran against the real database, and asking for a metric inside a known multi-year gap refused cleanly.</p><p>The best test was running the hook against our own session transcript. Quoted figures passed, and an invented 1.27 was blocked by name. Then I tried <em>&quot;you slept 238.3 hours, about 34 hours a week&quot;</em>, with the 34 computed in my head, and it <strong>passed</strong>. The number 34 appeared in an ingest timestamp, 08:34:12, so the hook treated the minutes as a source. File reads had the same problem: every line-number prefix sourced every integer up to the file&#39;s length. Both are now stripped before sources are collected, and there&#39;s a test for each.</p><p>The hook still has limits, and I’d rather name them:</p><ul><li><strong>Words without digits.</strong> “HRV rose” has nothing to check.</li><li><strong>Coincidence.</strong> A short number probably appears somewhere in any output, so the check is strong for 51.63 and weak for 12.</li><li><strong>Laundering.</strong> A number the model echoes in a shell command becomes tool output. The hook proves a number was <em>printed</em>, not that it was <em>computed</em>. That’s why the scripts are committed: they’re where the computation gets reviewed.</li></ul><h3>The takeaway</h3><p>If you analyze data with an LLM in the loop, the model will be the last thing to touch your numbers before you read them. Make it the part that can’t change them. Let it choose the question, read the caveats, and tell you what the result means. Let code do the arithmetic, every time, and check the reply for any number that didn’t come from code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2887ce7d2147" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[119 Devices, Not 120]]></title>
            <link>https://medium.com/@eric_abell/119-devices-not-120-551e9fd3d9c3?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/551e9fd3d9c3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[apple-health]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 13:59:31 GMT</pubDate>
            <atom:updated>2026-08-13T13:59:31.839Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post I spent a day measuring my Apple Health export instead of writing the parser, and found that most of what I believed about the file was wrong. Device strings contained memory addresses. Every timestamp was rendered in the wrong timezone. I wrote it all down in a design document, felt good about myself, and stopped.</p><p>Then I noticed the sentence at the bottom of my own notes: <em>“Every measurement in this document was derived by ad-hoc streaming scans. Those scripts were throwaway and no longer exist.”</em></p><p>So I had a design document full of numbers, resting on evidence I had deleted. Three architectural decisions — how records get their identity, how time is stored, how competing data sources get merged — were all justified by figures nobody could re-derive.</p><p>This post is about making those numbers reproducible, which took an afternoon, and about the one number that came back off by one, which is the part worth reading.</p><h3>Build the measuring tool before the parser</h3><p>The obvious next step was the parser. I built the profiler instead: a single streaming pass that regenerates every measurement the design rests on — element census, record volumes, source matrix, per-year coverage, the timezone analysis, the device-pointer collisions, sleep gap histograms, workout grouping.</p><p>Two reasons, and only one of them was verification.</p><p>The first: my design decisions were downstream of numbers I couldn’t check. If the census was wrong, the identity scheme was wrong, and I’d find out after writing 2,000 lines against it.</p><p>The second is the one I’d argue for more strongly. <strong>Apple Health exports are full-history dumps, so every future export is a chance for something to change out from under me.</strong> A new device starts writing. A metric appears that didn’t exist. Or — the one that actually scares me — I take my next export in January instead of August, every timestamp in thirteen years re-renders in a different UTC offset, and my content hashes all change at once. A profiler that runs <em>before</em> ingestion and diffs against the last one turns those from silent corruption into a message.</p><p>One expectation I got wrong immediately. I’d predicted Python would be “meaningfully slower” than my original unzip -p | awk reconnaissance, which took about 40 seconds. The real number:</p><pre>2,279,100 records total<br>Parsed in 12.7s</pre><p>iterparse with disciplined element clearing was three times <em>faster</em> than the shell pipeline, mostly because the expensive work is per-record and I cached it aggressively — device strings parse once per distinct string, timezone offsets resolve once per UTC hour instead of once per record. Worth measuring rather than assuming; I&#39;d written the pessimistic estimate into the design doc as fact.</p><h3>Most of it reproduced exactly, which is the boring part</h3><p>Here’s what came back identical to the original scans:</p><ul><li><strong>Element census</strong> — Record 2,279,100 · Workout 2,172 · ActivitySummary 1,428 · Correlation 141. Exact.</li><li><strong>Every record type volume</strong> — exact, across all 29 types.</li><li><strong>Contested metrics</strong> — all 11 of them, with identical per-source counts.</li><li><strong>Sleep segment values</strong> — AsleepCore 2,978 · REM 1,060 · Deep 1,056 · Awake 741 · InBed 203. Exact.</li><li><strong>Workout grouping</strong> — 141 multi-source groups covering 285 workouts. Exact.</li><li><strong>Timezone rendering</strong> — all 2,279,100 records carry -0500, in every year, including deep winter.</li></ul><p>Two independent implementations — a pile of awk from a design session, and a structured Python profiler written a day later — landing on the same numbers is genuinely reassuring. It&#39;s also the least interesting outcome possible, and it&#39;s not what that list is for.</p><p><strong>The list is for the lines that don’t match.</strong> Because where two independent measurements disagree, exactly one thing is certain: something is broken. You just don’t know which side yet.</p><h3>One number was off by one</h3><p>The device-pointer collision was the centerpiece of my last post. Apple renders the device attribute using Objective-C&#39;s default description format, which embeds the <em>heap address</em> of the device object in the exporting process:</p><pre>&lt;&lt;HKDevice: 0x7119d8900&gt;, name:Body Smart, manufacturer:Withings, model:Withings Scale,<br>  hardware:0, firmware:1000, localIdentifier:000000, creation date:2026-01-07 23:58:53 +0000&gt;</pre><p>That address gets recycled as the exporter streams, so it is worse than useless for identity — one address hosts many devices, one device appears under many addresses. Hash the raw string and your record identity depends on someone else’s allocator.</p><p>I had six numbers characterizing this. Five came back exactly right:</p><pre>distinct hex pointers                     52   ✓<br>pointers mapping to &gt;1 identity           48   ✓<br>identities mapping to &gt;1 pointer         116   ✓<br>most identities under one pointer         70   ✓<br>most pointers for one identity            44   ✓<br>distinct device identities               119   ✗  (original scan said 120)</pre><p>One hundred nineteen against one hundred twenty.</p><p>Everything about that says <em>off-by-one error</em>. Five of six exact, the sixth off by a single unit, in a count of an obscure derived quantity. The original scan was a one-liner; my new one strips fields slightly differently. It would have been extremely easy — and completely reasonable-sounding — to write “119, the original said 120, close enough, the collision behavior is confirmed either way” and move on.</p><p>The collision behavior <em>was</em> confirmed either way. That’s what makes it a good trap.</p><h3>What the missing device was hiding</h3><p>A device identity is a set of fields pulled out of that device string. If I&#39;m missing one, either I&#39;m parsing a string wrong, or <strong>I&#39;m not looking at a string I should be looking at.</strong></p><p>The second one turned out to be true, and it was not subtle once I checked. My profiler walked the XML and dispatched on element type:</p><pre>if tag == &quot;Record&quot;:<br>    accumulator.observe_record(element.attrib)<br>elif tag == &quot;Workout&quot;:<br>    accumulator.observe_workout(element.attrib)<br>elif tag == &quot;WorkoutRoute&quot;:<br>    accumulator.observe_workout_route(element.attrib)<br>elif tag == &quot;Correlation&quot;:<br>    accumulator.observe_correlation(element.attrib)</pre><p>Reasonable-looking. It is also a closed list, and the file contains an element that isn’t on it:</p><pre>&lt;Audiogram type=&quot;HKDataTypeIdentifierAudiogram&quot; sourceName=&quot;Settings&quot;<br>           device=&quot;&lt;&lt;HKDevice: 0x7119d98c0&gt;, name:AirPods Pro, model:AirPods Pro, ...&quot;&gt;<br>  &lt;SensitivityPoint frequencyValue=&quot;250&quot; leftEarValue=&quot;0.374992&quot; .../&gt;<br>&lt;/Audiogram&gt;</pre><p>One Audiogram in thirteen years — a hearing test taken through a pair of AirPods. My dispatch didn&#39;t handle it, so its device was never registered.</p><p>That’s the missing 120th device. Mystery solved, one-line fix, except that the AirPods were the <em>less</em> interesting thing it was hiding.</p><p>Look at the sourceName. That Audiogram was written by <strong>Settings</strong> — Apple&#39;s own Settings app — and Settings appears nowhere else in the entire export. It writes no Record elements at all. It was a data source I did not know I had, in a file I had already characterized in detail and written a blog post about.</p><p>The fix is to stop enumerating element types and start reading the attributes that actually matter, wherever they appear:</p><pre>def observe_element(self, tag: str, attrs: dict[str, str] | None = None) -&gt; None:<br>    &quot;&quot;&quot;Count an element and register any source or device it carries.</pre><pre>    Deliberately generic. sourceName and device appear on Record, Workout,<br>    WorkoutRoute, Correlation, Audiogram, ClinicalRecord and VisionPrescription,<br>    and a source that writes only one of the rarer element types would<br>    otherwise be invisible.<br>    &quot;&quot;&quot;<br>    self._elements[tag] += 1<br>    if not attrs:<br>        return<br>    if source := attrs.get(&quot;sourceName&quot;):<br>        self._seen_sources.add(source)<br>    self._observe_device(attrs.get(&quot;device&quot;))</pre><p>With that in place, all six device numbers reconciled at 120, and the profiler reported a source it had never mentioned before.</p><h3>The check that was supposed to fail loudly</h3><p>Here’s the part that actually bothered me.</p><p>My design document has a rule, written in bold, before any of this: <strong>“Unknown sources must fail loudly, never silently. A silently-defaulted new source is exactly how a wrong merge slips in unnoticed.”</strong></p><p>Why does that matter so much? Because sources get <em>ranked</em>. When two devices record the same walk, a merge policy decides which one wins, and an unranked source quietly falling to the bottom is how real data disappears from a total without any error anywhere.</p><p>I had implemented that check. It compared every source name I’d seen against a known roster and warned about anything unrecognized. The logic was correct. It ran on every profile.</p><p>And it could not see Settings, because the thing feeding it names had a closed list of element types.</p><p><strong>The check wasn’t wrong. Its input coverage was.</strong> I had verified the logic — does it warn when given an unknown name? — and never verified the part where names get collected. A guard against silent failure that is itself silently incomplete is arguably worse than no guard, because it produces a clean report you now trust.</p><p>The regression test that pins it doesn’t assert on the warning logic at all. It asserts on reachability, using a synthetic fixture built for exactly this shape:</p><pre>def test_sees_sources_and_devices_on_rare_element_types(mini_archive):<br>    &quot;&quot;&quot;A source writing only an Audiogram must not be invisible.&quot;&quot;&quot;<br>    stats = profile_archive(mini_archive)</pre><pre>    assert &quot;AudioOnlySource&quot; in stats.unknown_sources<br>    assert [&quot;Earbuds&quot;, None, &quot;E1&quot;, None, &quot;7B21&quot;, None, &quot;abc&quot;] in stats.device_identities</pre><h3>The same blind spot, one layer up</h3><p>I fixed the detection, re-ran, got my warning, mapped the source to a role, and looked at the generated report to confirm. The sources table:</p><pre>| Records | sourceName | Role                   | First      | Last       |<br>|--------:|------------|------------------------|------------|------------|<br>| 1517252 | Zepp       | wrist_wearable         | 2026-01-04 | 2026-08-11 |<br>|  646552 | (my phone) | phone                  | 2014-12-19 | 2026-08-11 |<br>...<br>|       1 | Health     | manual_entry           | 2026-05-29 | 2026-05-29 |</pre><p>Ten sources. Settings isn&#39;t there.</p><p>Detection was now correct — it had warned, I’d acted on the warning. But the <em>report</em> iterated over sources that had written Record elements, and Settings has written zero. Same blind spot, different layer: I&#39;d fixed the code that finds sources and left the code that displays them assuming records exist.</p><p>This one has teeth beyond my own project. I’d just finished making the source roster user-configurable so this could work on someone else’s export, and the pitch for it was that the profiler <em>is</em> the onboarding scan — run it on a stranger’s archive and it tells them what sources they have. A first-run report that quietly omits a source is precisely wrong for that. So the table now reads every source seen anywhere, and calls out the ones that write no records:</p><pre>|       0 | Settings   | system_app             | —          | —          |</pre><pre>1 source(s) write no `Record` at all and appear only on other element types: `Settings`.</pre><h3>A postscript on naming things</h3><p>One small thing I nearly got wrong at the very end, which I mention because the mistake was so comfortable.</p><p>Having found Settings, I needed to assign it a role, and I reached for audio_device — it wrote a hearing test, after all. But that’s not quite right: that isn&#39;t the same kind of statement as the others.</p><p>Checking the data made it obvious. Withings = body_composition_scale asserts <em>this source is a scale</em>, which is why it outranks everything on body mass. Settings = audio_device would assert <em>this source is an audio device</em>, which is false. Settings is an OS surface acting as a conduit. The audio device is the AirPods — and that&#39;s already captured in the device attribute, which is a different column entirely.</p><p><strong>The source name says who wrote the data. The device says what measured it.</strong> Collapsing those is true of whatever the conduit happens to be carrying today and silently false the moment it carries something else.</p><p>The role I’d invented also turned out to have zero members — every headphone-audio record in the archive comes from the phone, not from any audio device. So the fix was a role describing what Settings actually is (system_app, alongside the existing manual_entry and aggregator), and deleting the speculative one.</p><h3>What I’d take away from this</h3><ul><li><strong>An off-by-one in a reproduction is a finding, not noise.</strong> Everything about 119-versus-120 said off-by-one error, and it was a missing element type that hid a whole data source. The cost of checking was twenty minutes; the cost of shrugging was a permanently blind guard.</li><li><strong>Two independent measurements are worth more than one careful one.</strong> Where they agree you get real confidence. Where they disagree, something is broken and you don’t yet know which side — which is a much better position than never finding out.</li><li><strong>Verify the coverage of your safety checks, not just their logic.</strong> Mine warned correctly about every name it was given, and was never given the one that mattered. Test that the dangerous input can <em>reach</em> the check.</li><li><strong>Closed lists of types are where silent gaps live.</strong> if tag == &quot;Record&quot; elif ... looked exhaustive because it enumerated everything I&#39;d thought of. Reading the attribute wherever it appears has no such failure mode.</li><li><strong>The same bug reappears at every layer.</strong> Fixed in detection, still present in presentation. When you find a blind-spot bug, immediately go looking for its siblings downstream.</li><li><strong>Make your measurements regenerable, then diff them.</strong> Prose numbers in a design doc decay the moment the world changes. Mine had already drifted from a file that hadn’t changed at all.</li></ul><p>The profiler is committed now, runs in thirteen seconds, and exits non-zero when something structural changes. The parser still isn’t written. But the numbers it’ll be built against are ones I can regenerate on demand — and I now know that includes at least one source I’d never have thought to look for.</p><p><em>Tooling: Python 3.14, </em><em>xml.etree.ElementTree.iterparse streaming straight out of the zip, DuckDB waiting downstream. Fixtures are synthetic; no real health data is committed, published, or in this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=551e9fd3d9c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every Assumption Was Wrong]]></title>
            <link>https://medium.com/@eric_abell/every-assumption-was-wrong-322182029286?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/322182029286</guid>
            <category><![CDATA[quantified-self]]></category>
            <category><![CDATA[apple-health]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 21:54:01 GMT</pubDate>
            <atom:updated>2026-08-12T21:54:01.904Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted a boring thing: my Apple Health data in DuckDB so I could actually query it.</p><p>The Health app will hand you an export.zip on demand. Inside is a complete, from-the-beginning-of-time dump of everything HealthKit has ever recorded for you. Mine is 669 MB of XML holding about 2.3 million records across thirteen years. The plan wrote itself — parse the XML, model a star schema, load it up. And because each export is a <em>full</em> dump, the interesting engineering problem is incremental ingestion: when I export again in six months, only load what&#39;s new.</p><p>Records have no IDs, so the obvious move is to hash each record’s contents and skip hashes you’ve seen before. Simple, well-understood, done a hundred times.</p><p>Every part of that plan survived contact with the actual file except the parts that mattered.</p><p>This is a post about a design session where I measured before I built, and where almost everything I believed going in turned out to be wrong — including one thing I had already confidently written down and had to retract.</p><h3>Rule zero: open the file before you design for it</h3><p>The temptation with a documented format is to design from the documentation. Apple publishes a DTD right in the export’s prologue, it’s thorough, and it tells you nothing about what’s actually in <em>your</em> file.</p><p>So before writing any parser, I did a few streaming passes with unzip -p | awk to build a census — element counts, record types, sources, date ranges. Forty seconds per pass over 669 MB. That census is the only reason the rest of this post exists.</p><p>Two things fell out of it immediately, and both are undocumented, and both silently destroy the hash-based dedupe plan.</p><h3>Landmine #1: the device field contains a memory address</h3><p>Every record can carry a device attribute. Here&#39;s the shape of one:</p><pre>&lt;&lt;HKDevice: 0x600001a2b3c0&gt;, name:Body Smart, manufacturer:Withings, model:Withings Scale,<br>  hardware:0, firmware:1000, localIdentifier:000000, creation date:2020-01-01 00:00:00 +0000&gt;</pre><p><em>(Serial numbers and timestamps in the examples throughout this post are synthetic — the structure is real, the identifiers aren’t.)</em></p><p>That leading 0x600001a2b3c0 is not a device property. It&#39;s Objective-C&#39;s default description format — &lt;&lt;ClassName: allocation-address&gt;, properties…&gt; — and the hex is the heap address where that HKDevice instance happened to live inside the exporting process.</p><p>I flagged this and got an entirely reasonable pushback: Apple’s own docs say HKDevice objects are <strong>immutable</strong>. Properties are set at construction and cannot change. So how could the string vary?</p><p>The docs are correct. They just don’t govern the prefix. Immutability is a promise about the object’s <em>properties</em>, not about where the allocator put it. So I counted, across the whole file:</p><p>distinct hex pointers <strong>52</strong></p><p>distinct device identities (pointer stripped) <strong>120</strong></p><p>pointers mapping to more than one identity 48 of 52 — one address hosts <strong>70</strong> different devices</p><p>identities mapping to more than one pointer 116 of 120 — one device appears under <strong>44</strong> addresses</p><p>Fifty-two addresses cannot identify a hundred and twenty devices. The exporter streams samples out and the allocator recycles slots underneath it, so the same address gets reused for completely different devices, and the same physical device shows up under dozens of addresses.</p><p>And here’s the thing — immutability <em>strengthens</em> the conclusion rather than refuting it. Because the properties genuinely can’t change, seeing one identical property set under 44 different addresses tells you the only varying component is the one that was never a property.</p><p><strong>Consequence:</strong> hash the raw device string and identical records get different keys. Parse it into (name, manufacturer, model, hardware, firmware, localIdentifier) and throw the pointer away.</p><h3>Landmine #2: every timestamp is rendered in the export-time timezone</h3><p>This one is nastier, because it stays invisible until it isn’t.</p><p>I’d assumed each record’s timestamp carried the timezone offset in effect <em>when it was recorded</em> — that’s what you’d expect from a health archive spanning years and travel. So I framed a design decision around it: do we roll data up by device-local time, or by a fixed home timezone?</p><p>That decision doesn’t exist. All 2.3 million records carry the <strong>same</strong> UTC offset — every source, every year, including deep winter when my home timezone is an hour off from that. The offset matches the zone my phone was in on the day I ran the export.</p><p>Apple re-renders the entire archive into whatever zone your phone is in at export time.</p><h3>Proving it with a spring-forward night</h3><p>The clean way to test this is a daylight-saving transition. On a US spring-forward night the local clock jumps 01:59:59 straight to 03:00:00 — the 2 a.m. hour <em>does not exist</em> locally. So I pulled the sleep segments recorded across one of those nights (times below are illustrative, but the structure is exactly what I found):</p><pre>01:51 → 02:06   segment<br>02:07 → 02:14   segment     ← 02:00–02:59 never happened locally<br>02:15 → 02:33   segment<br>02:34 → 03:41   segment</pre><p>Continuous data straight through an hour that didn’t occur. If these were true local wall-clock times there’d be a gap. There isn’t one, so they aren’t.</p><p>The good news: <strong>the instants are correct.</strong> An instant is an instant, and the offset label is honest. What’s wrong is the rendered wall clock for anything recorded during the other half of the year, which reads exactly one hour off.</p><p>That has two consequences of wildly different size. A small one: a fraction of a percent of records render just after midnight when they truly happened just before it, so naive date extraction files them on the wrong day. And a large one: roughly <em>half</em> my records fall in the shifted window, so any hour-of-day analysis — when do I actually fall asleep, when does my activity peak — is an hour wrong for half the archive, seasonally. That’s the worst kind of wrong, because it looks precisely like a real winter/summer behavioral signal.</p><h3>The part that eats the database</h3><p>Here’s why this matters for incremental loading, and it’s the reason I’d call it a landmine rather than a bug.</p><p>If Apple renders timestamps in the export-time zone, then <strong>an export taken in winter produces different timestamp strings than one taken in summer — for identical records.</strong> Different strings, different hashes, and your next export re-ingests all 2.3 million records as new.</p><p>It works perfectly until the season changes. Then it silently doubles your database.</p><h3>The fix: hash canonical values, never raw strings</h3><p>Both landmines have the same root cause and the same remedy. The hash must be computed over <em>parsed, canonicalized</em> values rather than the bytes the XML happened to contain:</p><p>FieldHash inputtimestampsUTC instant (epoch seconds) — invariant regardless of export-time zonedeviceparsed property tuple, pointer discardedvaluecanonical numeric form, so 70 and 70.0 can&#39;t divergetype, unit, sourceas-is; genuinely stable</p><p>There’s a testing lesson hiding in here too. My original plan had an idempotency test: ingest the same export twice, assert zero new rows the second time. That test is worthless — it passes trivially, because re-parsing identical bytes produces identical strings by construction. It cannot detect either landmine.</p><p>The test that actually works: <strong>re-render the export into a different timezone programmatically, ingest both, assert zero new rows.</strong> Same for shuffling the device pointers. Test the transformation you’re afraid of, not the one that’s easy to write.</p><h3>The free ground-truth oracle (and the prediction I got wrong)</h3><p>Next problem. Five different things write step counts into my HealthKit: my iPhone, a Zepp (Amazfit) watch, AllTrails, Garmin Connect, and Withings’ Health Mate. Six write active energy — add Runkeeper to that list. They overlap in time. Summing them double-counts: naively adding my calorie samples inflates the total by 39%.</p><p>So how do you merge them? I had opinions. I wrote them down. Then I noticed something better than opinions.</p><p><strong>Apple ships a de-duplicated answer.</strong> The activity rings are computed from a daily summary that Apple produces with its own dedupe logic, and both the summary <em>and</em> the raw samples that feed it are in the export. That’s a test oracle, free, sitting in the file. I could stop arguing and start scoring.</p><p>Three candidate strategies:</p><ol><li><strong>Naive sum</strong> — add everything.</li><li><strong>Ranked single-source</strong> — per day, pick the highest-priority source that has data.</li><li><strong>Interval merge</strong> — take the union of sample time intervals, credit each elementary segment to its highest-priority <em>covering</em> source at that sample’s rate.</li></ol><p>I predicted ranked single-source would badly undercount, and said so, with a number: about 37% low. My reasoning was that on a day with a hike, AllTrails only covers the hike itself, so taking it alone would throw away the rest of the day that only my phone saw.</p><p>Then I ran it. Here’s the scoring, restricted to the days that actually have competing sources — 28% of days, but 73% of the total:</p><p>strategytotal vs oraclemedian daily errordays within 2%naive sum1.537x50.2%8/402ranked single-source0.995x16.0%27/402<strong>interval merge</strong>1.069x<strong>7.4%152/402</strong></p><p>My prediction was wrong. Ranked single-source lands at 0.995x — nearly perfect in aggregate.</p><p>But it’s right for the wrong reason, and that’s the actually interesting result. Its per-day median error is 16%, and it lands within 2% on only 27 of 402 days. The aggregate accuracy is over-shoots and under-shoots cancelling each other out across hundreds of days. If I’d evaluated only on the total — which is exactly what a quick sanity check would have done — I’d have shipped a model that’s wrong every single day and looks flawless annually.</p><p>Interval merge is more than five times better per-day. It also composes the two layers the problem actually has: <strong>coverage</strong> (which sources have data covering this moment, which falls out of the data for free) and <strong>priority</strong> (among those, who wins, which is policy). A watch left charging makes no claim on that time window, so the phone’s data gets used in full, automatically. No special-casing.</p><h3>The twist: your oracle is a reference, not a target</h3><p>Interval merge still sits 7% above Apple’s number. My instinct was to tune that down. That instinct was wrong.</p><p>Look closer at individual days and Apple’s daily total is sometimes <em>below what a single third-party device measured on its own</em>. Apple isn’t computing a neutral truth — it’s applying its own ecosystem-favoring dedupe, and it discounts non-Apple sources.</p><p>So if my merged number exactly reproduced Apple’s, that would mean I had successfully replicated Apple’s habit of throwing away data from devices I actually own and wear. Being 7% above the oracle isn’t error. It’s the whole point.</p><p><strong>Use the oracle to catch order-of-magnitude mistakes. Never tune toward it.</strong> An oracle that encodes someone else’s policy is a sanity check, not a specification.</p><h3>Where the data made a hard question easy</h3><p>Not every question got harder. Sleep is stored as individual stage segments — there’s no “duration” field anywhere, so a night has to be stitched together from consecutive pieces. The obvious knob is: how big a gap ends a session?</p><p>I expected to agonize. Instead I histogrammed the gaps between consecutive segments:</p><pre>&lt; 1 min      5,526  ████████████████████████████████████████<br>5–15 min         1<br>15–30 min       14<br>30–60 min        2<br>1–2 h            4<br>2–4 h            4<br>4–8 h            1<br>8–16 h         147  █<br>&gt; 16 h          47</pre><p>Sharply bimodal. Gaps are either under a minute or over eight hours, and the entire range in between holds 26 out of 5,746 — under half a percent. Any threshold from one hour to four hours produces the same answer within a rounding error. The parameter I was prepared to argue about turned out not to matter, and ten minutes of measurement bought that certainty.</p><p>The same pass turned up a trap I would absolutely have shipped. Alongside the sleep-stage segments there’s an InBed segment — and it doesn&#39;t sit <em>beside</em> the stages, it <strong>envelops</strong> them. One night showed a single InBed block spanning ten hours while a dozen stage segments tiled inside it. Sum all segments naively and you roughly double every night&#39;s sleep. Time asleep has to come from the stage segments only; time in bed is a separate measurement that happens to overlap all of them.</p><h3>Designing for churn: roles, not identities</h3><p>The iPhone is probably permanent. Everything else — the watch, AllTrails, the gym equipment — will get replaced over the life of this archive. I want “hiking distance over the last decade” to survive swapping hiking apps.</p><p>Most of this turned out to be free, and again, only measurement showed it. HealthKit normalizes the semantic axes: activity types and metric types are Apple-controlled enums, not app-chosen strings. I verified it across my own data:</p><p>activityapps writing itHikingAllTrails, Garmin ConnectEllipticalZepp, SweatDown, FTMSBluetoothWalkingRunkeeper, Zepp, AllTrails, Garmin ConnectRunningRunkeeper, Garmin Connect, Zepp</p><p>Every one of them writes the identical canonical identifier — HKWorkoutActivityTypeHiking and friends. A hiking app I adopt in 2030 will write the same constant.</p><p><strong>So analysis queries filter on activity type and metric type, never on source name.</strong> A WHERE source_name = &#39;…&#39; in analysis code is a design smell.</p><p>Source identity legitimately matters in exactly one place: merge priority. So that got abstracted behind a <strong>role</strong> — phone, wrist_wearable, outdoor_activity_app, gym_equipment, body_composition_scale. Priority ranks roles, not apps. Replacing AllTrails with Gaia GPS becomes one row mapping the new source to outdoor_activity_app; it inherits the ranking, and no query or policy changes.</p><p>Two details that make it hold up:</p><ul><li><strong>Unknown sources fail loudly.</strong> A new source with no role mapping gets the most conservative rank, a warning, and a line in the ingestion report. Silently defaulting a new source is exactly how a wrong merge slips in unnoticed six months later.</li><li><strong>There’s an </strong><strong>aggregator role that ranks below everything.</strong> Some apps re-publish data they ingested from elsewhere rather than measuring anything. That&#39;s derivative, not a measurement, and it should never outrank a real instrument.</li></ul><p>And the whole merge policy lives in <strong>tables, not code</strong> — ranks are rows, so two policies can coexist and be compared on real numbers before either is adopted. Changing my mind is a DELETE and a recompute, not a refactor.</p><h3>The real risk isn’t a parser bug</h3><p>Here’s what I think is actually most dangerous about this project, and it isn’t anything above.</p><p>A clean star schema makes the wrong analysis effortless and gives no warning when you do it:</p><pre>SELECT date, value FROM daily_metrics WHERE metric = &#39;X&#39; ORDER BY date;</pre><p>That returns a smooth thirteen-year line. No nulls, no errors, nothing indicating that the early years are a different instrument, the middle is a different device, and that a chunk of those metrics didn’t exist at all until recently. One recent year holds over 70% of all my records and carries roughly twice the metric breadth of any prior year — that’s simply when the Zepp went on my wrist and started sampling heart rate continuously. Respiratory rate and blood oxygen don’t exist in my archive before it, at all.</p><p>That line looks like a finding about my body. It’s substantially a finding about which gadgets I owned.</p><p>Compare the failure modes. A broken content hash produces millions of duplicate rows — loud, obvious, and recoverable, because the raw layer lets you fix the hash and rebuild without re-parsing. A bad afternoon. This one is silent and permanent: a plausible, confident, wrong conclusion about your own health, with no error message anywhere, of exactly the kind a person acts on.</p><p>A coverage table doesn’t fix it if it’s <em>passive</em> — a lookup only helps someone who already suspected a problem and thought to check. So three things went in as build-now requirements rather than analysis-time polish:</p><ol><li><strong>Analysis reads go through a view, never the bare fact table.</strong> The view returns values joined to their coverage metadata, so the caveat arrives attached to the data instead of requiring a lookup nobody remembers.</li><li><strong>Every returned range carries a </strong><strong>spans_discontinuity flag</strong>, computed per request — true when the window crosses a device change or a coverage gap. Mark it at the point of use, because that&#39;s the last moment the distinction can still be made.</li><li><strong>Empty ranges refuse rather than return nothing.</strong> Asking for sleep data from a year before I tracked sleep must say <em>no coverage</em> — not return zero rows that average to nothing and render as a confident flat line.</li></ol><p>That third one is the one most likely to get quietly dropped during implementation, because returning an empty result is always the path of least resistance and never throws an error. Silence and emptiness are the failure mode being defended against; they can’t also be the response.</p><h3>What I’d take away from this</h3><p>I spent a day measuring and didn’t write a line of the parser. It was easily the highest-leverage day of the project.</p><p>Six things I believed at the start were wrong: that device strings were stable, that timestamps carried recording-time zones, that a “device-local versus home timezone” choice existed, that ranked precedence would undercount, that the sleep threshold needed careful tuning, and that Apple’s daily totals were a target to hit. Every correction came from a forty-second scan of a file I already had sitting on disk.</p><p>The generalizable bits:</p><ul><li><strong>Design from the bytes, not the docs.</strong> The DTD was accurate and told me nothing that mattered.</li><li><strong>Hash canonical values, never raw serialized strings.</strong> Anything that passed through someone else’s formatter can carry allocator noise, locale, or timezone state.</li><li><strong>Test the transformation you’re afraid of.</strong> “Ingest the same file twice” passes by construction and proves nothing.</li><li><strong>Score competing designs when an oracle is available</strong>, and score them <em>per-unit</em>, not in aggregate. Aggregate accuracy hides models that are wrong every single day.</li><li><strong>An oracle encodes someone’s policy.</strong> Use it to catch blunders, never to tune toward.</li><li><strong>The scariest bug is the one that returns a plausible number.</strong> Everything else announces itself.</li></ul><p>The parser still isn’t written. But when it is, it’ll be built against what’s actually in the file — and the assumptions it makes are all written down, measured, and testable.</p><p><em>Tooling: Python with </em><em>iterparse for streaming, DuckDB for storage, and an embarrassing amount of </em><em>unzip -p | awk for reconnaissance. No health data was harmed, or published, in the making of this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=322182029286" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capturing Every Shell Command Claude Code Runs — with Atuin]]></title>
            <link>https://medium.com/@eric_abell/capturing-every-shell-command-claude-code-runs-with-atuin-6c6dd7f594dc?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c6dd7f594dc</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[atuin]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[zsh]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 17:54:35 GMT</pubDate>
            <atom:updated>2026-06-25T17:54:35.831Z</atom:updated>
            <content:encoded><![CDATA[<p>When you pair-program with an AI agent like <strong>Claude Code</strong>, something quietly frustrating happens: the agent runs <em>dozens</em> of shell commands on your behalf — clever jq filters, the exact ffmpeg incantation you&#39;d never remember, a git recovery dance — and then they evaporate. They live for a moment in the agent&#39;s context window and are gone. You can&#39;t Ctrl-R for them. You can&#39;t learn from them. You can&#39;t reuse them tomorrow.</p><p>Meanwhile, you’ve got your <em>own</em> shell history, and you’d really rather not blend the two into one undifferentiated soup.</p><p>This post walks through the setup I landed on: <strong>every command the agent runs gets recorded into </strong><a href="https://atuin.sh/"><strong>Atuin</strong></a><strong>, tagged as an “agent” command, and kept cleanly separate from my own history</strong> — but instantly browsable whenever I want it. The whole thing is about 15 lines of config.</p><h3>The cast of characters</h3><p>Two tools do the heavy lifting:</p><ul><li><strong>Atuin</strong> — replaces your shell’s Ctrl-R with a SQLite-backed, full-text-searchable history database. Once you&#39;ve used it you can&#39;t go back.</li><li><strong>Claude Code hooks</strong> — Claude Code can fire a shell command before/after each tool call. We’ll use that to notify Atuin every time the agent runs a Bash command.</li></ul><p>The magic ingredient is recent: <strong>modern Atuin (I’m on </strong><strong>18.16.1) ships native &quot;AI-agent&quot; hooks and author tagging out of the box.</strong> No forks, no glue scripts. Check your version:</p><pre>atuin --version</pre><p>If you’re on something older, upgrade first (cargo install atuin, your package manager, or the install script).</p><h3>Step 1 — Atuin records your history</h3><p>If you already use Atuin, you’ve done this. Your shell init records every interactive command you type:</p><pre># ~/.zshrc  (bash/fish are analogous)<br>eval &quot;$(atuin init zsh)&quot;</pre><p>These commands get tagged, implicitly, as <strong>user</strong> commands. Hold that thought — the tag is the whole trick.</p><h3>Step 2 — Atuin records the agent’s history</h3><p>Here’s the part most people don’t know exists. Atuin has a subcommand whose entire job is wiring AI agents into your history:</p><pre>atuin hook install claude-code</pre><p>That one command writes the necessary hooks into Claude Code’s settings (~/.claude/settings.json). When you look at what it produced, it&#39;s refreshingly simple — three hooks, all matching the Bash tool, each handing the command off to Atuin:</p><pre>{<br>  &quot;PreToolUse&quot;: [<br>    { &quot;matcher&quot;: &quot;Bash&quot;,<br>      &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;atuin hook claude-code&quot; }] }<br>  ],<br>  &quot;PostToolUse&quot;: [<br>    { &quot;matcher&quot;: &quot;Bash&quot;,<br>      &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;atuin hook claude-code&quot; }] }<br>  ],<br>  &quot;PostToolUseFailure&quot;: [<br>    { &quot;matcher&quot;: &quot;Bash&quot;,<br>      &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;atuin hook claude-code&quot; }] }<br>  ]<br>}</pre><ul><li><strong>PreToolUse</strong> fires <em>before</em> the agent’s command runs.</li><li><strong>PostToolUse</strong> fires <em>after</em> it succeeds.</li><li><strong>PostToolUseFailure</strong> catches the ones that error out — because the command that <em>failed</em> is often exactly the one you want to inspect later.</li></ul><p>Every Bash command Claude Code executes now flows into Atuin, tagged as an <strong>agent</strong> command.</p><blockquote><em>💡 Tip: back up </em><em>~/.claude/settings.json before running the install if you&#39;ve hand-edited it, so you can diff the result. Mine left everything else untouched and just added the </em><em>hooks block.</em></blockquote><h3>Step 3 — The payoff: author-filtered history</h3><p>Now your Atuin database has two kinds of rows in it, and you can slice by author. Atuin’s --author flag understands three forms:</p><ul><li>$all-user — commands <em>you</em> typed (non-agents)</li><li>$all-agent — commands an AI agent ran</li><li>a literal name — if you want to get specific</li></ul><p>So this:</p><pre>atuin search --author &#39;$all-agent&#39; -- &#39;&#39;</pre><p>…returns <em>only</em> the commands the agent ran. And on my machine right now, the split looks like this:</p><pre>agent commands: 2006<br>user  commands: 2421</pre><p>Two thousand agent commands I’d otherwise have lost.</p><h3>Step 4 — Make it a joy to browse (fzf)</h3><p>Raw atuin search output is fine for scripting, but for <em>browsing</em> I want an interactive fuzzy picker. Enter <a href="https://github.com/junegunn/fzf">fzf</a>. I keep three aliases — one per &quot;author&quot; view:</p><pre># ~/.zshrc<br>alias atuin-claude=&quot;atuin search --author &#39;\$all-agent&#39; --print0 -- &#39;&#39; | \<br>  fzf --read0 --no-sort --tac --layout=reverse --prompt=&#39;claude&gt; &#39;&quot;<br>alias atuin-mine=&quot;atuin search --author &#39;\$all-user&#39; --print0 -- &#39;&#39; | \<br>  fzf --read0 --no-sort --tac --layout=reverse --prompt=&#39;mine&gt; &#39;&quot;<br>alias atuin-all=&quot;atuin search --print0 -- &#39;&#39; | \<br>  fzf --read0 --no-sort --tac --layout=reverse --prompt=&#39;all&gt; &#39;&quot;</pre><p>atuin-claude browses what the agent ran, atuin-mine browses what I ran, atuin-all is everything. Each flag is earning its place, so let me unpack them — this is where the behavior gets <em>exactly</em> right:</p><ul><li><strong>--print0 / </strong><strong>--read0</strong> — Atuin emits results NUL-separated and fzf reads them the same way. Without this, a single multi-line command (think a heredoc, or a for loop you pasted) would be shredded into separate, useless entries. NUL-delimiting keeps each command intact.</li><li><strong>--no-sort</strong> — tells fzf <em>not</em> to reorder by fuzzy-match score, so it preserves Atuin&#39;s chronological order until you start typing.</li><li><strong>--tac</strong> — reverses the input. Atuin emits <strong>oldest-first</strong>, and --tac flips it so the <strong>most recent command lands at the top</strong>, right under your cursor. (I learned this the slightly annoying way: without --tac, the picker opens on the <em>oldest</em> entry and you scroll down forever to reach what you just did.)</li><li><strong>--layout=reverse</strong> — puts the prompt at the top with the list flowing downward, which pairs naturally with --tac so newest-at-top reads correctly.</li></ul><blockquote><em>⚠️ One escaping gotcha: inside a </em><strong><em>double-quoted</em></strong><em> alias, write </em><em>\$all-agent (with a backslash) so your shell doesn&#39;t try to expand </em><em>$all-agent as a variable when the alias is defined. Inside single quotes it&#39;d be literal, but the aliases above are double-quoted so fzf&#39;s own single-quoted </em><em>--prompt works.</em></blockquote><h3>The subtle bug you’ll hit (and how to kill it)</h3><p>Here’s a trap worth the price of admission. If you also run the wonderful <strong>zsh-autosuggestions</strong> plugin (the fish-style grey &quot;ghost text&quot; that completes your command as you type), Atuin and the plugin have an interaction you need to know about.</p><p>When Atuin’s shell integration loads and detects zsh-autosuggestions, it <strong>silently hijacks the suggestion source</strong> — it sets:</p><pre>ZSH_AUTOSUGGEST_STRATEGY=(atuin ...)</pre><p>…so your inline ghost text now comes from Atuin’s database. Which, remember, <em>includes every command the agent ran.</em> Suddenly you start typing eza and the ghost text suggests some gnarly compound command your AI ran three days ago. Not what you want inline.</p><p>The fix is one line, placed <strong>after</strong> Atuin’s init (and after the plugin loads), so it wins:</p><pre># ~/.zshrc — keep inline suggestions to MY history only<br>ZSH_AUTOSUGGEST_STRATEGY=(history completion)</pre><p>This points the ghost text back at your native ~/.zsh_history — which, crucially, the Claude Code Bash tool <strong>never writes to</strong> (it goes through the Atuin hook, not your interactive history file). So your inline suggestions stay 100% yours, while the agent&#39;s commands remain one atuin-claude away whenever you actually want them.</p><p>That’s the whole philosophy in a sentence: <strong>agent history is opt-in, not in-your-face.</strong></p><h3>How it feels day to day</h3><p>A few real moments from my week:</p><ul><li>Claude debugged a flaky test with a for-loop that re-ran it 50 times and grepped for a race. I didn&#39;t memorize it. Two days later: atuin-claude, type flaky, hit enter, run it again.</li><li>I wanted to know <em>what the agent actually did</em> to my git history during a messy rebase. atuin-claude, search rebase, and there&#39;s the full forensic trail — including the command that failed, thanks to the PostToolUseFailure hook.</li><li>Quick sanity check on how much the agent is doing: the user-vs-agent counts are a surprisingly fun productivity metric.</li></ul><p>And because everything’s still in one Atuin database, plain Ctrl-R works exactly like it always did — atuin-all is there for the rare moment I want the unified firehose.</p><h3>The complete setup, in one place</h3><pre># 1. Make sure Atuin is recent enough for AI-agent hooks<br>atuin --version          # want a modern build; I&#39;m on 18.16.1<br># 2. Record your own interactive history (in ~/.zshrc)<br>eval &quot;$(atuin init zsh)&quot;<br># 3. Wire Claude Code&#39;s Bash tool into Atuin<br>atuin hook install claude-code<br># 4. Browser aliases (in ~/.zshrc)<br>alias atuin-claude=&quot;atuin search --author &#39;\$all-agent&#39; --print0 -- &#39;&#39; | fzf --read0 --no-sort --tac --layout=reverse --prompt=&#39;claude&gt; &#39;&quot;<br>alias atuin-mine=&quot;atuin search --author &#39;\$all-user&#39; --print0 -- &#39;&#39; | fzf --read0 --no-sort --tac --layout=reverse --prompt=&#39;mine&gt; &#39;&quot;<br>alias atuin-all=&quot;atuin search --print0 -- &#39;&#39; | fzf --read0 --no-sort --tac --layout=reverse --prompt=&#39;all&gt; &#39;&quot;<br># 5. Keep agent commands OUT of inline autosuggestions (after atuin init, in ~/.zshrc)<br>ZSH_AUTOSUGGEST_STRATEGY=(history completion)</pre><p>Reload your shell (exec zsh) and you&#39;re done.</p><h3>Why I like this</h3><p>The best automation is the kind you stop noticing. Your AI pair-programmer becomes a tireless explorer who <em>leaves a trail</em> — every command it tries is captured, searchable, and reusable, without you lifting a finger or muddying your own muscle memory. It turns the agent from a black box that “did some stuff in the terminal” into a transparent collaborator whose work you can inspect, learn from, and build on.</p><p>Give it a try. The first time you fuzzy-search your way back to a command you didn’t even write, you’ll get it.</p><p><em>Setup tested on macOS with zsh, Atuin 18.16.1, Ghostty, and Claude Code. The Atuin and Claude Code pieces are shell-agnostic; adapt the alias/plugin bits to bash or fish as needed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6dd7f594dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Warp AI vs Claude Pro: A Terminal Developer’s Dilemma]]></title>
            <link>https://medium.com/@eric_abell/warp-ai-vs-claude-pro-a-terminal-developers-dilemma-756441afc2ce?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/756441afc2ce</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Fri, 04 Jul 2025 18:11:48 GMT</pubDate>
            <atom:updated>2025-07-04T18:11:48.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I’m sticking with Claude Code instead of paying twice for AI assistance</h3><p>As a developer already subscribed to Claude Pro, I recently found myself wondering whether Warp’s new AI-powered terminal was worth the additional monthly cost. After diving deep into both pricing models and usage patterns, the answer became surprisingly clear — and it’s not what Warp probably hopes to hear.</p><h3>The Setup: Two Different Approaches to AI Billing</h3><p>Claude Pro gives me access to Claude 3.5 Sonnet and Opus for $20/month with a straightforward model: roughly 5x more usage than the free tier, with limits that reset every 5 hours. When I hit my limit, I know exactly when I can continue working.</p><p>Warp Pro costs $15/month and offers 1,000 “AI requests” per month, integrated directly into their terminal interface. Sounds reasonable, right?</p><h3>The Problem: What Exactly Is a “Request”?</h3><p>Here’s where things get murky. Warp defines a request as “each time you submit a prompt,” but the documentation reveals the devil in the details:</p><p>“More complex interactions may use multiple requests based on the number of tool calls, context gathered, and steps required. Prompts that include large context (such as attached blocks or long messages) or file attachments like images may also increase the number of requests used.”</p><p>This means asking “what’s my IP address?” might consume one request, while “analyze this codebase and suggest optimizations” could burn through 5–10+ requests in a single interaction. There’s no way to predict this ahead of time.</p><p>Even worse, Warp has both request limits AND token limits that are calculated separately. You can hit either ceiling, adding another layer of uncertainty to your usage planning.</p><h3>The User Experience Reality</h3><p>I discovered that Warp’s AI features can consume requests in unexpected ways:</p><ul><li>Command suggestions burn through requests as you type (before you even submit)</li><li>• AI autofill in workflows counts as separate requests</li><li>• Large context or file attachments multiply request consumption</li></ul><p>One user reported burning through their entire daily limit “within a minute or two” just from typing a long prompt, as the suggestion feature made multiple AI calls while they were still composing their question.</p><h3>Claude Code: A Better Alternative</h3><p>Meanwhile, Claude Code gives me terminal AI integration without the billing complexity:</p><ul><li>Predictable limits: Clear 5-hour reset cycles I can plan around</li><li>• Usage-based pricing: Limited by conversation volume, not arbitrary request counts</li><li>• No hidden multipliers: Complex tasks don’t mysteriously consume extra “requests”</li><li>• Already paid for: It’s included with my existing Claude Pro subscription</li></ul><h3>The Bottom Line</h3><p>Warp’s terminal integration is genuinely impressive, and their AI features work well when they’re available. But paying an additional $15/month on top of my $20 Claude Pro subscription feels like double-dipping — especially when the usage model is so unpredictable.</p><p>Claude Code gives me the best of both worlds: AI-powered terminal assistance with the transparent, developer-friendly billing model I already understand and trust.</p><p>For developers already invested in the Claude ecosystem, the choice seems clear. Why pay twice for AI that uses the same underlying models, especially when one option offers predictable usage patterns and the other leaves you guessing whether your next complex prompt will consume 1 request or 20?</p><p>Sometimes the most innovative pricing model isn’t the most complex one — it’s the one that gets out of your way and lets you focus on building great software.</p><p>Are you using AI in your terminal workflow? I’d love to hear about your experiences with different tools and pricing models in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=756441afc2ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom User model with email in Django]]></title>
            <link>https://medium.com/@eric_abell/custom-user-model-with-email-in-django-cb3776ad3efb?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb3776ad3efb</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[django-custom-user-model]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 21:00:01 GMT</pubDate>
            <atom:updated>2025-06-03T21:03:52.602Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up a custom user model that uses email instead of a traditional username is one of the most common tasks in a Django project. If you’re reading this, you’ve probably already created a CustomUser class in which you specify:</p><pre>class CustomUser(AbstractBaseUser, PermissionsMixin):<br>    email = models.EmailField(unique=True)<br>    # … any other fields you need …<br><br>    USERNAME_FIELD = &quot;email&quot;<br>    REQUIRED_FIELDS = []<br>    objects = CustomUserManager()</pre><p>And in your CustomUserManager you’ve written something like:</p><pre>class CustomUserManager(BaseUserManager):<br>    def _create_user(self, email, password, **extra_fields):<br>        # Normalize the email (lowercasing the domain part) … <br>        email = self.normalize_email(email)<br>        user = self.model(email=email, **extra_fields)<br>        user.set_password(password)<br>        user.save(using=self._db)<br>        return user<br><br>    def create_user(self, email, password=None, **extra_fields):<br>        extra_fields.setdefault(&quot;is_staff&quot;, False)<br>        extra_fields.setdefault(&quot;is_superuser&quot;, False)<br>        return self._create_user(email, password, **extra_fields)<br><br>    def create_superuser(self, email, password, **extra_fields):<br>        extra_fields.setdefault(&quot;is_staff&quot;, True)<br>        extra_fields.setdefault(&quot;is_superuser&quot;, True)<br>        return self._create_user(email, password, **extra_fields)</pre><p>This all seems straightforward — and it is, up until the point where you realize that a login attempt will fail every time someone types their email with different casing in the domain portion. In other words, if someone signed up as user@Example.com (and you normalized it to user@example.com when creating their account) but then tries to log in as user@Example.com, Django’s default authentication backend will look for a user with a literal email=&#39;user@Example.com&#39;. No match → authentication fails → confusion sets in.</p><p>In this post, I’ll walk through:</p><ol><li>Why you need normalize_email in your manager</li><li>How Django’s default get_by_natural_key() behaves</li><li>Why that leads to “CaseMismatch” logins</li><li>How to override get_by_natural_key() so logins “just work”</li></ol><p>Hopefully this will save you (and anyone who tries to sign in to your app) a ton of headaches.</p><h3>Why Normalize at Creation Time?</h3><p>Django’s BaseUserManager.normalize_email() method lowercases the domain part of whatever email you pass in. For example:</p><pre>&gt;&gt;&gt; from django.contrib.auth.base_user import BaseUserManager<br>&gt;&gt;&gt; BaseUserManager.normalize_email(&quot;User@Example.COM&quot;)<br>&quot;user@example.com&quot;</pre><p>The logic is simple:</p><ul><li>The local part (everything before the @) is left exactly as typed.</li><li>The domain part (everything after @) is lowercased.</li></ul><p>Why does this matter? Because email domains are case‐insensitive by standard — but some (less common) mail servers treat local parts differently. By normalizing at creation time, we:</p><ul><li>Guarantee that everyone’s email is stored in a consistent form (normalize_email ensures user@EXAMPLE.com → user@example.com).</li><li>Prevent subtle duplication issues (someone signs up as user@example.com, someone else as user@Example.com; without normalization, Django would think these are distinct).</li></ul><p>So far, so good: in your _create_user method, you definitely want to call:</p><pre>email = self.normalize_email(email)</pre><p>before you actually call self.model(...) and save. That way, every record in the database has a canonical, normalized email address.</p><h3>How Django’s Default get_by_natural_key() Works</h3><p>When a user attempts to log in, Django’s authentication machinery (by default) does something like:</p><ol><li>Takes the “username” field from the login form. By default this is username, but in a custom user model with USERNAME_FIELD = &quot;email&quot;, it takes the value of email.</li><li>Calls your user model’s manager method get_by_natural_key(username_value).</li><li>If a matching row is found, authenticate() then checks the provided password against that user’s hashed password. If it matches, login succeeds.</li></ol><p>Django’s default implementation of get_by_natural_key() in BaseUserManager is essentially:</p><pre>def get_by_natural_key(self, username):<br>    return self.get(**{self.model.USERNAME_FIELD: username})</pre><p>Notice that it does <strong>not</strong> normalize the input before looking in the database. In other words, if someone enters User@Example.Com at login, Django does:</p><pre>User.objects.get(email=&quot;User@Example.Com&quot;)</pre><p>…even though the record in the database was saved as user@example.com. That lookup returns <strong>no rows</strong>, so authentication immediately fails (regardless of how correct the password is).</p><h3>Why That Leads to Stumbling on Case</h3><p>Let’s step through a concrete scenario:</p><ol><li>Alice signs up with alice@Example.com.</li></ol><ul><li>In CustomUserManager._create_user(), you call normalize_email(&quot;alice@Example.com&quot;) → &quot;alice@example.com&quot;.</li><li>You save the user record as email=&quot;alice@example.com&quot;.</li></ul><p>2. Later, Alice tries to log in and types alice@Example.com (capital “E”).</p><ul><li>Django calls get_by_natural_key(&quot;alice@Example.com&quot;).</li><li>That does User.objects.get(email=&quot;alice@Example.com&quot;).</li><li>No record matches, because the only value in the database is alice@example.com.</li><li>Login fails, even though we <em>know</em> Alice is typing the same email she registered with.</li></ul><p>This is confusing not only for the developer (why won’t Alice’s login work?), but also for the user (“I know I signed up with this exact email — why isn’t it letting me in?”). Since domain names are <em>technically</em> case‐insensitive, you almost never want your login flow to be this strict.</p><h3>Overriding get_by_natural_key() to Normalize on Lookup</h3><p>The fix is straightforward: in your CustomUserManager, override get_by_natural_key() so that it calls normalize_email() on the value coming from the login form. For example:</p><pre>class CustomUserManager(BaseUserManager):<br>    # … _create_user, create_user, etc. as before …<br><br>    def get_by_natural_key(self, username):<br>        &quot;&quot;&quot;<br>        Override this method to normalize the email input<br>        before attempting to find the user in the database.<br>        &quot;&quot;&quot;<br>        email = self.normalize_email(username)<br>        return self.get(**{self.model.USERNAME_FIELD: email})</pre><p>What did we just do?</p><ul><li>We took the raw “username” (which is really an email string) passed in from the login form.</li><li>We lowercased the <em>domain</em> part via self.normalize_email(username).</li><li>We performed self.get(email=normalized_email) instead of self.get(email=username).</li><li>As long as users type the exact same local part (everything before @), they’ll find the right record. Any casing difference in the domain part (e.g. Example.com → example.com) is “normalized away” so Django still finds the correct user.</li></ul><p>Now, even if Alice typed ALICE@EXAMPLE.COM, the lookup becomes:</p><pre>normalized = BaseUserManager.normalize_email(&quot;ALICE@EXAMPLE.COM&quot;)  # -&gt; &quot;ALICE@example.com&quot;<br>User.objects.get(email=&quot;ALICE@example.com&quot;)</pre><p>Caveat: this still requires that the <em>local part</em> (the bit before @) match exactly what’s in the database (Django does not, by default, lowercase or otherwise transform the local part). If you want to make the entire email case‐insensitive, you could .lower() the entire string instead of just the domain:</p><pre># If you really want to ignore local-part case as well:<br>def get_by_natural_key(self, username):<br>    normalized = username.lower()<br>    return self.get(**{self.model.USERNAME_FIELD: normalized})</pre><p>…but be aware that, according to the email specification, local parts can technically be case‐sensitive. In practice almost nobody enforces that, but it’s worth knowing.</p><h3>Putting It All Together</h3><p>Here’s a minimal, fully‐working example of both the model and manager:</p><pre># users/models.py<br><br>from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager<br>from django.contrib.auth.models import PermissionsMixin<br>from django.db import models<br><br><br>class CustomUserManager(BaseUserManager):<br>    def _create_user(self, email, password, **extra_fields):<br>        # Normalize the domain part of the email<br>        email = self.normalize_email(email)<br>        user = self.model(email=email, **extra_fields)<br>        user.set_password(password)<br>        user.save(using=self._db)<br>        return user<br><br>    def create_user(self, email, password=None, **extra_fields):<br>        extra_fields.setdefault(&quot;is_staff&quot;, False)<br>        extra_fields.setdefault(&quot;is_superuser&quot;, False)<br>        return self._create_user(email, password, **extra_fields)<br><br>    def create_superuser(self, email, password, **extra_fields):<br>        extra_fields.setdefault(&quot;is_staff&quot;, True)<br>        extra_fields.setdefault(&quot;is_superuser&quot;, True)<br>        return self._create_user(email, password, **extra_fields)<br><br>    def get_by_natural_key(self, username):<br>        &quot;&quot;&quot;<br>        Normalize email before lookup so that varying case in the domain<br>        doesn’t block authentication.<br>        &quot;&quot;&quot;<br>        email = self.normalize_email(username)<br>        return self.get(**{self.model.USERNAME_FIELD: email})<br><br><br>class CustomUser(AbstractBaseUser, PermissionsMixin):<br>    email = models.EmailField(unique=True)<br>    first_name = models.CharField(max_length=30, blank=True)<br>    last_name = models.CharField(max_length=30, blank=True)<br>    is_staff = models.BooleanField(default=False)<br>    is_active = models.BooleanField(default=True)<br>    date_joined = models.DateTimeField(auto_now_add=True)<br><br>    USERNAME_FIELD = &quot;email&quot;<br>    REQUIRED_FIELDS = []  # EMAIL_ONLY signup–no other “required” fields<br><br>    objects = CustomUserManager()<br><br>    def __str__(self):<br>        return self.email</pre><p>And in your settings.py:</p><pre>AUTH_USER_MODEL = &quot;users.CustomUser&quot;</pre><p>With this in place:</p><ol><li>All new signups automatically store email as lowercased‐domain.</li><li>Any login attempt is looked up through normalize_email() first.</li><li>Users can sign in with any combination of upper/lowercase in the domain portion, and Django will still find them.</li></ol><h3>Wrapping Up</h3><p>Switching to an email‐as‐username model in Django is a great way to simplify your UX (no more “remember a random username” for users) and tighten security (email is almost always unique). But without a small tweak to your manager’s get_by_natural_key(), your login system can be tripped up by simple letter‐case mismatches in the domain. Overriding that one method to normalize the email on lookup generally fixes all of this.</p><h3>Key Takeaways</h3><ul><li>Always call normalize_email() in your manager’s _create_user().</li><li>If you don’t override get_by_natural_key(), Django will try to look up the raw string passed at login—which may not match the normalized value in the database.</li><li>A quick override of get_by_natural_key() to normalize the incoming username (email) ensures that users can sign in regardless of how they capitalize their email domain.</li><li>If you want to be extra safe and remove any local‐part casing issues, you can lowercase the entire string (but be aware of the “official” email‐spec nuance).</li></ul><p>Hopefully, seeing this pattern laid out will help you avoid those “works on my machine” moments where Alice — who registered as Alice@Example.com—can’t log in as alice@EXample.com. Fixing it is as simple as normalizing both at creation <em>and</em> at lookup. Once you’ve added that get_by_natural_key() override, you can breathe easy knowing that email lookups will be seamless, and your users won’t ever have to worry about hitting the wrong capitalization.</p><p>Happy coding — and may your authentication workflows be frictionless!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb3776ad3efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DNS and Docker (part 1)]]></title>
            <link>https://medium.com/@eric_abell/dns-and-docker-d839479109ac?source=rss-7097c4cd30df------2</link>
            <guid isPermaLink="false">https://medium.com/p/d839479109ac</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coredns]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Eric Abell]]></dc:creator>
            <pubDate>Mon, 12 May 2025 19:35:35 GMT</pubDate>
            <atom:updated>2025-05-13T20:24:00.799Z</atom:updated>
            <content:encoded><![CDATA[<p>This may end up being multiple parts, but here’s where I’m at.</p><h3>The Goal</h3><p>I’m building a local CoreDNS server that intercepts all DNS queries for *.vps domains and resolves them by forwarding those requests to Docker&#39;s internal DNS resolver at 127.0.0.11. This setup allows me to create custom service names (like grafana.vps, ntfy.vps, etc.) that automatically map to containers inside my Docker network, without having to hardcode IP addresses or manage external DNS records.</p><p>By acting as a local intermediary, my DNS server can selectively rewrite, cache, and forward requests as needed. For anything ending in .vps, it passes the query to Docker’s built-in resolver — which understands container names and resolves them within the context of Docker’s internal DNS system. This gives me a powerful way to integrate container-based services into my local development environment, with predictable, human-readable names that feel like a private TLD.</p><h3>The Problem</h3><p>When I type grafana.vps into Chrome’s address bar, it doesn’t just perform a single DNS query — instead, it often sends <strong>multiple DNS lookups</strong> in parallel for the same domain, but with different record types. For example, Chrome might query for A, AAAA, HTTPS, and even SVCB records. This behavior is part of Chrome’s effort to support newer DNS features like <strong>Encrypted Client Hello (ECH)</strong> and <strong>HTTP/3</strong>, both of which rely on records like HTTPS and SVCB to determine how to connect to a server securely.</p><p>The problem arises because Docker’s internal DNS (127.0.0.11) — which is designed primarily for basic A and PTR lookups — doesn’t understand or support these newer record types. So when Chrome sends an HTTPS query for grafana.vps, it receives a <strong>SERVFAIL</strong>, or worse, no response at all. This causes Chrome to fall back on search behavior or display an error page, even if an A record for that domain was resolved correctly just milliseconds earlier. The result is a frustrating and inconsistent experience when trying to access containerized services through friendly internal names like grafana.vps.</p><h3>Figuring out what was happening</h3><p>The first thing I did was let tcpdump show me the requests that Chrome was sending.</p><pre>sudo tcpdump -n -vv -i any port 53 and udp</pre><p>Which showed me the DNS record requests. This was how I discovered why Chrome wasn’t loading the page.</p><p>To understand why Chrome was failing to load internal services like grafana.vps, I used the drill command-line tool to manually inspect how DNS resolution was working. First, I ran a simple A record query against Docker’s internal DNS resolver at 127.0.0.11 to confirm that the basic lookup worked:</p><pre>drill @127.0.0.11 -t A grafana.vps</pre><p>This returned the expected IP address of the running container, which confirmed that Docker’s embedded DNS server was correctly resolving the A record for grafana.vps.</p><p>Next, I ran a query for an HTTPS record, which modern browsers like Chrome also request automatically when a URL is entered:</p><pre>drill @127.0.0.11 -t HTTPS grafana.vps</pre><p>This time, the response failed with SERVFAIL, and in some cases, also showed a mismatch in DNS transaction IDs. That revealed the root of the problem: Docker’s internal DNS resolver doesn’t understand or support newer record types like HTTPS (type 65). Chrome was interpreting the failure or absence of an HTTPS response as an overall DNS failure, even though the A record had resolved just fine — which explains why the browser would refuse to load the page or redirect to a search instead.</p><p><strong>First Solution Attempt — change Corefile for CoreDNS Docker image</strong></p><p>My first attempts at modifying the Corefile configuration for CoreDNS failed miserably. I tried to route all *.vps queries through Docker’s internal resolver by adding custom rewrite and forward rules, but the syntax was unforgiving and the results were inconsistent. Some queries didn’t resolve at all, others returned SERVFAIL, and in a few cases, CoreDNS wouldn’t even start due to a subtle config error. Despite poring over plugin documentation and examples, it was clear that CoreDNS&#39;s flexibility came with a steep learning curve — and that making it play nicely with Docker’s internal DNS and modern record types like HTTPS wasn’t going to be as straightforward as I had hoped.</p><p><strong>Second Solution Attempt — write my own DNS server in Python</strong></p><p>To take full control of DNS resolution in my setup, I’ve decided to write my own DNS server in Python using the dnslib library. This gives me the flexibility to intercept, rewrite, cache, and forward queries exactly the way I want — especially for custom domains like *.vps. I’m building it with detailed, structured logging so I can see every incoming query, how it&#39;s being processed, whether it&#39;s handled locally or forwarded upstream, and exactly what response is sent back. This approach not only eliminates the guesswork and limitations I ran into with CoreDNS, but also gives me a clear window into how modern DNS clients like Chrome behave under the hood.</p><p>Stay tuned for my next update…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d839479109ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>