<?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 [chaincoder.] on Medium]]></title>
        <description><![CDATA[Stories by [chaincoder.] on Medium]]></description>
        <link>https://medium.com/@chainc0der?source=rss-7f8489b3bc79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UYNWRGchAE_n6NXzEwf8tg.jpeg</url>
            <title>Stories by [chaincoder.] on Medium</title>
            <link>https://medium.com/@chainc0der?source=rss-7f8489b3bc79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:05:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chainc0der/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[Turn Your Raspberry Pi Into a Personal Git Server]]></title>
            <link>https://medium.com/@chainc0der/turn-your-raspberry-pi-into-a-personal-git-server-f62487038d2c?source=rss-7f8489b3bc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62487038d2c</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[[chaincoder.]]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 22:34:29 GMT</pubDate>
            <atom:updated>2026-08-26T22:34:29.249Z</atom:updated>
            <content:encoded><![CDATA[<h4>Your code does not need to live in somebody else’s cloud.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gBGGnB32SDvg_bWA" /><figcaption>Photo by <a href="https://unsplash.com/@praveentcom?utm_source=medium&amp;utm_medium=referral">Praveen Thirumurugan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>GitHub is great. GitLab is great. Codeberg is great. They are all extremely convenient places to store repositories, collaborate with people, run CI pipelines, collect little green contribution squares, and occasionally discover that you committed a .env file containing credentials six months ago.</p><p>But Git itself never required any of that.</p><p>Git is fundamentally a distributed version control system. A repository can live on GitHub, a VPS, an old ThinkPad under your bed, a NAS, or a Raspberry Pi humming quietly beside your router like a very small and unusually disciplined sysadmin.</p><p>That last option is what we are building.</p><p>By the end of this tutorial, your Raspberry Pi will accept Git pushes over SSH from computers on your network. You will be able to create private repositories, clone them onto other machines, push changes back to the Pi, and use the thing as your own tiny source control appliance.</p><p>No monthly fee. No SaaS dashboard. No Kubernetes cluster summoned from the abyss.</p><p>Just Git, SSH, Linux, and a computer roughly the size of a deck of cards.</p><h3>What We Are Building</h3><p>The architecture is almost suspiciously simple:</p><pre>YOUR LAPTOP<br>    |<br>    | git push over SSH<br>    v<br>RASPBERRY PI<br>    |<br>    +-- /srv/git/project-one.git<br>    +-- /srv/git/project-two.git<br>    +-- /srv/git/website.git</pre><p>Your working files stay on your computer.</p><p>The Pi stores <strong>bare Git repositories</strong>, which are repositories designed specifically to act as remotes.</p><p>Instead of this:</p><pre>project/<br>├── README.md<br>├── src/<br>├── .git/<br>└── ...</pre><p>the server stores something resembling:</p><pre>project.git/<br>├── HEAD<br>├── branches<br>├── config<br>├── objects<br>├── refs<br>└── hooks</pre><p>You generally do not edit files directly inside these repositories.</p><p>You push commits into them.</p><p>Think of the Raspberry Pi as your personal miniature GitHub, except there is no Explore page full of JavaScript frameworks named after household objects.</p><h3>What You Need</h3><p>Almost any modern Raspberry Pi will work.</p><p>A Pi 3, Pi 4, Pi 5, Zero 2 W, or similar board is more than capable of handling personal Git hosting.</p><p>You will need:</p><ul><li><a href="https://amzn.to/4cYdKqb">A Raspberry Pi</a></li><li>Raspberry Pi OS or another Linux distribution</li><li>Network access</li><li>SSH access</li><li>A storage device</li><li>Git installed on your client computer</li></ul><p>For casual use, a microSD card is perfectly adequate.</p><p>For heavier use, particularly repositories containing lots of binary data, I would seriously consider attaching an SSD.</p><p>Git itself is lightweight. Storage corruption is less entertaining.</p><h3>Step 1: Update the Raspberry Pi</h3><p>SSH into the Pi:</p><pre>ssh yourusername@raspberrypi.local</pre><p>If raspberrypi.local does not resolve, use the Pi&#39;s IP address:</p><pre>ssh yourusername@192.168.1.50</pre><p>Then update the system:</p><pre>sudo apt update<br>sudo apt upgrade -y</pre><p>Install Git:</p><pre>sudo apt install git -y</pre><p>Verify it:</p><pre>git --version</pre><p>You should get something similar to:</p><pre>git version 2.x.x</pre><p>Congratulations. Your Raspberry Pi now possesses approximately one percent of GitHub’s functionality and significantly less venture capital.</p><h3>Step 2: Create a Dedicated Git User</h3><p>You could host repositories under your normal Linux account.</p><p>You could also store all your passwords in passwords-final-FINAL-v3.txt.</p><p>We can do better.</p><p>Create a dedicated user:</p><pre>sudo adduser git</pre><p>Linux will ask you for a password and some optional information.</p><p>The extra profile information can be skipped.</p><p>Now we have a user specifically responsible for Git operations:</p><pre>git</pre><p>This gives us a nice clean separation between normal administrative access and repository access.</p><p>Switch to the user temporarily:</p><pre>sudo su - git</pre><p>Check where you are:</p><pre>pwd</pre><p>You should see:</p><pre>/home/git</pre><p>Exit back to your normal account:</p><pre>exit</pre><h3>Step 3: Create a Repository Directory</h3><p>I prefer keeping server repositories somewhere obvious, such as:</p><pre>/srv/git/</pre><p>Create it:</p><pre>sudo mkdir -p /srv/git</pre><p>Give ownership to the Git user:</p><pre>sudo chown git:git /srv/git</pre><p>Check permissions:</p><pre>ls -ld /srv/git</pre><p>You should see the git user and group listed as the owner.</p><p>Something resembling:</p><pre>drwxr-xr-x 2 git git 4096 Aug 26 18:00 /srv/git</pre><p>Now the filesystem has a dedicated home for your remote repositories.</p><h3>Step 4: Create Your First Bare Repository</h3><p>A normal Git repository contains your project files plus Git metadata.</p><p>A bare repository contains only the repository database.</p><p>That makes it ideal for a server.</p><p>Create one:</p><pre>sudo -u git git init --bare /srv/git/helloworld.git</pre><p>Git should respond with something similar to:</p><pre>Initialized empty Git repository in /srv/git/helloworld.git/</pre><p>Look inside:</p><pre>ls /srv/git/helloworld.git</pre><p>You should see:</p><pre>HEAD<br>branches<br>config<br>description<br>hooks<br>info<br>objects<br>refs</pre><p>Notice what you do not see:</p><pre>index.html<br>main.py<br>src/<br>README.md</pre><p>That is intentional.</p><p>The server is not your working directory.</p><p>It is the canonical Git remote.</p><h3>Step 5: Test the Repository</h3><p>Go back to your laptop.</p><p>Create a test project:</p><pre>mkdir helloworld<br>cd helloworld</pre><p>Initialize Git:</p><pre>git init</pre><p>Create something profound:</p><pre>echo &quot;# Hello from my suspiciously tiny Git server&quot; &gt; README.md</pre><p>Add it:</p><pre>git add README.md</pre><p>Commit it:</p><pre>git commit -m &quot;initial commit&quot;</pre><p>If Git complains that your identity is unknown, configure it:</p><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;you@example.com&quot;</pre><p>Then run the commit again.</p><p>Now add your Raspberry Pi as the remote:</p><pre>git remote add origin git@raspberrypi.local:/srv/git/helloworld.git</pre><p>Or use the IP address:</p><pre>git remote add origin git@192.168.1.50:/srv/git/helloworld.git</pre><p>Rename the current branch to main:</p><pre>git branch -M main</pre><p>Push:</p><pre>git push -u origin main</pre><p>If everything works, Git will send your repository to the Raspberry Pi.</p><p>You have now built your own Git hosting infrastructure.</p><p>No account creation form.</p><p>No cookie banner.</p><p>No pricing page mysteriously hiding the actual price.</p><h3>Step 6: Clone It Somewhere Else</h3><p>A Git server is not terribly impressive if it only accepts pushes from the machine that created the repository.</p><p>Move somewhere else:</p><pre>cd ~</pre><p>Clone it:</p><pre>git clone git@raspberrypi.local:/srv/git/helloworld.git</pre><p>Enter the repository:</p><pre>cd helloworld</pre><p>Look around:</p><pre>ls</pre><p>Your README should be there.</p><pre>cat README.md</pre><p>You have now confirmed the full loop:</p><pre>local repository<br>      |<br>      | push<br>      v<br>Raspberry Pi<br>      |<br>      | clone<br>      v<br>new working copy</pre><p>That is a legitimate Git server.</p><p>It just happens to weigh a few ounces.</p><h3>Step 7: Stop Typing Passwords With SSH Keys</h3><p>Typing a password every time you push code gets old remarkably quickly.</p><p>SSH keys fix that.</p><p>On your laptop, check whether you already have one:</p><pre>ls ~/.ssh</pre><p>You may see files like:</p><pre>id_ed25519<br>id_ed25519.pub</pre><p>If not, create one:</p><pre>ssh-keygen -t ed25519</pre><p>Press Enter to accept the default location.</p><p>You can use a passphrase if you want additional security.</p><p>Now copy the key to the Git user:</p><pre>ssh-copy-id git@raspberrypi.local</pre><p>Or:</p><pre>ssh-copy-id git@192.168.1.50</pre><p>Test it:</p><pre>ssh git@raspberrypi.local</pre><p>You should be able to authenticate using your SSH key.</p><p>Now Git operations should work without repeatedly asking for the account password:</p><pre>git push</pre><p>Much nicer.</p><h3>Step 8: Make the Git Account Less Like a Normal User</h3><p>There is another useful security improvement.</p><p>The git user does not really need an interactive shell.</p><p>Its job is essentially:</p><pre>receive Git commands<br>do Git things<br>go back to sleep</pre><p>Git includes a special shell called:</p><pre>git-shell</pre><p>Find it:</p><pre>which git-shell</pre><p>Usually:</p><pre>/usr/bin/git-shell</pre><p>Make sure it appears in /etc/shells:</p><pre>grep git-shell /etc/shells</pre><p>If nothing appears:</p><pre>echo &quot;/usr/bin/git-shell&quot; | sudo tee -a /etc/shells</pre><p>Now change the Git user’s shell:</p><pre>sudo chsh git -s /usr/bin/git-shell</pre><p>Try logging in normally:</p><pre>ssh git@raspberrypi.local</pre><p>You may now see something like:</p><pre>fatal: Interactive git shell is not enabled.</pre><p>Good.</p><p>Git operations should still work:</p><pre>git pull<br>git push<br>git clone git@raspberrypi.local:/srv/git/helloworld.git</pre><p>The account can serve Git repositories without functioning as a convenient general-purpose remote shell.</p><p>That is exactly what we want.</p><h3>Step 9: Make Creating Repositories Less Annoying</h3><p>Right now, every new project requires something like:</p><pre>sudo -u git git init --bare /srv/git/project.git</pre><p>That is already simple, but we can make it even cleaner.</p><p>Create a script on the Pi:</p><pre>sudo nano /usr/local/bin/newrepo</pre><p>Add:</p><pre>#!/bin/bash</pre><pre>set -e</pre><pre>if [ -z &quot;$1&quot; ]; then<br>    echo &quot;usage: newrepo &lt;repository-name&gt;&quot;<br>    exit 1<br>fi</pre><pre>REPO_NAME=&quot;$1&quot;<br>REPO_PATH=&quot;/srv/git/${REPO_NAME}.git&quot;</pre><pre>if [ -e &quot;$REPO_PATH&quot; ]; then<br>    echo &quot;repository already exists:&quot;<br>    echo &quot;$REPO_PATH&quot;<br>    exit 1<br>fi</pre><pre>sudo -u git git init --bare &quot;$REPO_PATH&quot;</pre><pre>echo<br>echo &quot;repository created:&quot;<br>echo &quot;$REPO_PATH&quot;<br>echo<br>echo &quot;remote example:&quot;<br>echo &quot;git remote add origin git@raspberrypi.local:$REPO_PATH&quot;</pre><p>Save it.</p><p>Make it executable:</p><pre>sudo chmod +x /usr/local/bin/newrepo</pre><p>Now creating a repository becomes:</p><pre>newrepo strange-little-project</pre><p>Result:</p><pre>/srv/git/strange-little-project.git</pre><p>Then from your computer:</p><pre>git remote add origin git@raspberrypi.local:/srv/git/strange-little-project.git<br>git push -u origin main</pre><p>You have accidentally invented an extremely tiny developer platform.</p><p>Try not to raise $40 million.</p><h3>Step 10: Give the Raspberry Pi a Predictable Address</h3><p>There is one subtle problem with self-hosting anything on a home network.</p><p>IP addresses can change.</p><p>Today your Pi might be:</p><pre>192.168.1.50</pre><p>Tomorrow DHCP decides:</p><pre>192.168.1.127</pre><p>Your Git remote then points into the void.</p><p>There are a few ways around this.</p><h3>Option A: Use mDNS</h3><p>Raspberry Pi OS commonly advertises itself as:</p><pre>raspberrypi.local</pre><p>So your remote can simply be:</p><pre>git@raspberrypi.local:/srv/git/project.git</pre><p>This is convenient for local networks.</p><h3>Option B: Configure a DHCP Reservation</h3><p>The cleaner long-term solution is usually creating a DHCP reservation in your router.</p><p>Tell the router:</p><pre>Whenever this Raspberry Pi connects,<br>always give it 192.168.1.50.</pre><p>The exact interface varies by router.</p><p>Look for settings named:</p><pre>DHCP Reservation<br>Static Lease<br>Address Reservation<br>Reserved IP</pre><p>Then your remote remains stable:</p><pre>git@192.168.1.50:/srv/git/project.git</pre><h3>Option C: Add a Friendly SSH Alias</h3><p>You can also make your laptop remember the server.</p><p>Edit:</p><pre>nano ~/.ssh/config</pre><p>Add:</p><pre>Host gitpi<br>    HostName raspberrypi.local<br>    User git<br>    IdentityFile ~/.ssh/id_ed25519</pre><p>Now instead of:</p><pre>git clone git@raspberrypi.local:/srv/git/project.git</pre><p>you can use:</p><pre>git clone gitpi:/srv/git/project.git</pre><p>And your remote can look like:</p><pre>git remote add origin gitpi:/srv/git/project.git</pre><p>Much cleaner.</p><h3>Step 11: Push an Existing Project</h3><p>Suppose you already have a local project:</p><pre>~/code/chaincoder-site/</pre><p>First create the server repository:</p><pre>newrepo chaincoder-site</pre><p>Then on your laptop:</p><pre>cd ~/code/chaincoder-site</pre><p>Check the current remotes:</p><pre>git remote -v</pre><p>If there is no remote:</p><pre>git remote add origin gitpi:/srv/git/chaincoder-site.git</pre><p>Then:</p><pre>git push -u origin main</pre><p>If the project already uses GitHub as origin, do not necessarily remove it.</p><p>You can add the Raspberry Pi as another remote:</p><pre>git remote add pi gitpi:/srv/git/chaincoder-site.git</pre><p>Now:</p><pre>git remote -v</pre><p>might show:</p><pre>origin  git@github.com:username/chaincoder-site.git<br>pi      gitpi:/srv/git/chaincoder-site.git</pre><p>Push to GitHub:</p><pre>git push origin main</pre><p>Push to your Pi:</p><pre>git push pi main</pre><p>This is one of my favorite configurations.</p><p>GitHub remains the public or off-site remote.</p><p>The Raspberry Pi becomes your local mirror.</p><p>Two copies. Two locations. Much less anxiety.</p><h3>Step 12: Automatically Push to Multiple Remotes</h3><p>Git can even push to multiple destinations.</p><p>You could configure:</p><pre>git remote set-url --add --push origin git@github.com:username/project.git</pre><p>Then add your Pi:</p><pre>git remote set-url --add --push origin gitpi:/srv/git/project.git</pre><p>Check it:</p><pre>git remote -v</pre><p>You may see:</p><pre>origin  git@github.com:username/project.git (fetch)<br>origin  git@github.com:username/project.git (push)<br>origin  gitpi:/srv/git/project.git (push)</pre><p>Now:</p><pre>git push origin main</pre><p>can push the same branch to both destinations.</p><p>Your code goes into the cloud and into the tiny plastic computer sitting beside the router.</p><p>Redundancy is beautiful when it works.</p><h3>Step 13: Back Up the Git Server</h3><p>This part matters.</p><p>Hosting your repositories yourself does not magically make them backed up.</p><p>It merely means you are now the person responsible when the storage device dies.</p><p>Welcome to infrastructure.</p><p>The important directory is:</p><pre>/srv/git</pre><p>You can copy it to an external drive.</p><p>For example:</p><pre>sudo rsync -a --delete /srv/git/ /mnt/backup/git/</pre><p>That gives you a second copy.</p><p>You could automate this using cron.</p><p>Edit root’s crontab:</p><pre>sudo crontab -e</pre><p>Add:</p><pre>0 3 * * * rsync -a --delete /srv/git/ /mnt/backup/git/</pre><p>Every night at 3:00 AM, your repositories get mirrored.</p><p>You can verify the backup:</p><pre>ls /mnt/backup/git</pre><p>A better backup strategy would also occasionally copy that backup somewhere outside your house.</p><p>Remember the unpleasant but useful rule:</p><blockquote><em>Synchronization is not necessarily backup, and one physical device is definitely not backup.</em></blockquote><p>Your Pi can absolutely be part of a good backup system.</p><p>It should not be the entire backup system.</p><h3>Step 14: Check Repository Integrity</h3><p>Git includes tools for verifying object integrity.</p><p>On the Pi:</p><pre>sudo -u git git -C /srv/git/helloworld.git fsck --full</pre><p>For a healthy repository, you should not see serious corruption errors.</p><p>You can also inspect repository size:</p><pre>du -sh /srv/git/*.git</pre><p>Example:</p><pre>1.2M    /srv/git/helloworld.git<br>84M     /srv/git/website.git<br>230M    /srv/git/firmware-lab.git</pre><p>That makes it easy to see which project quietly swallowed your storage.</p><p>It is always the project containing assets/.</p><p>Always.</p><h3>Step 15: Repository Maintenance</h3><p>Git repositories occasionally benefit from garbage collection.</p><p>Run:</p><pre>sudo -u git git -C /srv/git/helloworld.git gc</pre><p>For many personal repositories, Git will manage itself perfectly well.</p><p>You do not need to sit there manually optimizing object databases every Thursday evening like some haunted database monk.</p><p>Still, it is useful to know the command exists.</p><p>You can inspect object statistics:</p><pre>sudo -u git git -C /srv/git/helloworld.git count-objects -vH</pre><p>Example output:</p><pre>count: 12<br>size: 48.00 KiB<br>in-pack: 182<br>packs: 1<br>size-pack: 31.20 KiB<br>prune-packable: 0<br>garbage: 0<br>size-garbage: 0 bytes</pre><p>This tells you how Git is storing objects internally.</p><h3>Step 16: Use Git Hooks</h3><p>Now things get more interesting.</p><p>Bare repositories contain a directory called:</p><pre>hooks/</pre><p>Look inside:</p><pre>ls /srv/git/helloworld.git/hooks</pre><p>You will find examples like:</p><pre>post-receive.sample<br>pre-receive.sample<br>update.sample</pre><p>Hooks allow the server to automatically run scripts when Git events occur.</p><p>For example:</p><pre>push repository<br>      |<br>      v<br>post-receive hook<br>      |<br>      +-- deploy website<br>      +-- rebuild documentation<br>      +-- send notification<br>      +-- restart service<br>      +-- trigger test script</pre><p>Suddenly our tiny Git server becomes a tiny automation server.</p><p>Suppose you host a static website from:</p><pre>/var/www/site</pre><p>You could create:</p><pre>sudo nano /srv/git/site.git/hooks/post-receive</pre><p>with:</p><pre>#!/bin/bash</pre><pre>set -e</pre><pre>GIT_WORK_TREE=/var/www/site \<br>git --git-dir=/srv/git/site.git checkout -f main</pre><p>Make it executable:</p><pre>sudo chmod +x /srv/git/site.git/hooks/post-receive</pre><p>Make sure permissions are configured correctly for the deployment directory.</p><p>Now a Git push can deploy your website.</p><pre>edit site<br>   |<br>git commit<br>   |<br>git push<br>   |<br>Raspberry Pi receives commit<br>   |<br>hook executes<br>   |<br>website updates</pre><p>That is basically a microscopic CI/CD system.</p><p>No YAML file containing 173 lines of indentation archaeology required.</p><h3>Step 17: Accessing the Server Outside Your House</h3><p>Everything we have built so far works beautifully on your local network.</p><p>Remote internet access requires more thought.</p><p>You could expose SSH directly through your router.</p><p>I generally would not make that the first option.</p><p>A much nicer approach is using a private overlay network such as Tailscale or WireGuard.</p><p>With Tailscale, for example, your laptop and Raspberry Pi can communicate through an encrypted private network even when they are on different physical networks.</p><p>Conceptually:</p><pre>LAPTOP AT COFFEE SHOP<br>        |<br>        | encrypted tunnel<br>        v<br>TAILSCALE NETWORK<br>        |<br>        v<br>RASPBERRY PI AT HOME</pre><p>Your Git remote can continue working as though the machines were sitting beside each other.</p><p>This also means you can host other internal tools without spraying ports across the public internet like confetti.</p><p>If you eventually want remote access, adding a VPN layer is worth investigating.</p><h3>Step 18: Add More Users</h3><p>Maybe this stops being a purely personal server.</p><p>Maybe you want collaborators.</p><p>Each person can generate their own SSH key.</p><p>Their public key can be added to:</p><pre>/home/git/.ssh/authorized_keys</pre><p>Example:</p><pre>sudo mkdir -p /home/git/.ssh<br>sudo nano /home/git/.ssh/authorized_keys</pre><p>Permissions matter:</p><pre>sudo chown -R git:git /home/git/.ssh<br>sudo chmod 700 /home/git/.ssh<br>sudo chmod 600 /home/git/.ssh/authorized_keys</pre><p>Each line in authorized_keys corresponds to another public key.</p><p>This is enough for small trusted groups.</p><p>For larger groups with complex permissions, issues, pull requests, web interfaces, organizations, and per-repository access control, plain Git over SSH eventually becomes less convenient.</p><p>That leads to the next evolution.</p><h3>Step 19: What If You Want a Web Interface?</h3><p>At this point you may be thinking:</p><blockquote><em>This is nice, but I want buttons.</em></blockquote><p>Understandable.</p><p>Plain Git over SSH intentionally gives you almost nothing besides Git.</p><p>If you want something resembling GitHub, install a lightweight Git forge.</p><p>One popular choice is <strong>Gitea</strong>.</p><p>Gitea adds:</p><ul><li>Browser-based repository viewing</li><li>User accounts</li><li>Issues</li><li>Pull requests</li><li>Organizations</li><li>SSH keys</li><li>Webhooks</li><li>Releases</li><li>Markdown rendering</li><li>Repository search</li><li>Permissions</li><li>API access</li></ul><p>The architecture becomes:</p><pre>+----------------+<br>Browser ----&gt;|     Gitea      |<br>             +-------+--------+<br>                     |<br>                     v<br>                Git repos<br>                     ^<br>                     |<br>Laptop ---- SSH -----+</pre><p>A Raspberry Pi 4 or Pi 5 can make an excellent small Gitea server.</p><p>For this tutorial, though, I deliberately started with raw Git.</p><p>It is useful to understand that Git hosting itself is almost absurdly simple.</p><p>The glossy web interface is the extra machinery.</p><p>The repository is the important part.</p><h3>Step 20: Make the Pi Feel Like an Appliance</h3><p>Once your setup works, you can make the machine almost invisible.</p><p>Give it a recognizable hostname:</p><pre>sudo hostnamectl set-hostname gitbox</pre><p>Reboot:</p><pre>sudo reboot</pre><p>Now you might access it as:</p><pre>gitbox.local</pre><p>Update your SSH config:</p><pre>Host gitbox<br>    HostName gitbox.local<br>    User git<br>    IdentityFile ~/.ssh/id_ed25519</pre><p>Repositories become:</p><pre>git clone gitbox:/srv/git/project.git</pre><p>That is deliciously clean.</p><p>You can even physically label the Pi.</p><pre>GITBOX<br>DO NOT UNPLUG<br>CONTAINS THE CONSEQUENCES OF MY DECISIONS</pre><p>Optional, but spiritually correct.</p><h3>My Preferred Setup</h3><p>For a personal Raspberry Pi Git server, I would use something roughly like this:</p><pre>Raspberry Pi 4 or 5<br>       |<br>       +-- Ethernet<br>       |<br>       +-- USB SSD<br>       |<br>       +-- Raspberry Pi OS Lite<br>       |<br>       +-- OpenSSH<br>       |<br>       +-- Git<br>       |<br>       +-- Dedicated &quot;git&quot; user<br>       |<br>       +-- /srv/git/*.git<br>       |<br>       +-- SSH key authentication<br>       |<br>       +-- git-shell<br>       |<br>       +-- nightly rsync backup<br>       |<br>       +-- Tailscale for remote access</pre><p>That setup has very few moving parts.</p><p>Few moving parts means fewer strange things awakening at 2:17 AM demanding Docker logs.</p><p>And because the core system is just SSH plus Git, migration is trivial.</p><p>Want to move repositories to another server later?</p><p>Copy:</p><pre>/srv/git</pre><p>Done.</p><p>Your repositories are not trapped inside some proprietary database.</p><p>They are Git repositories.</p><h3>Useful Commands Cheat Sheet</h3><p>Create a repository:</p><pre>sudo -u git git init --bare /srv/git/project.git</pre><p>Add your Pi as a remote:</p><pre>git remote add origin gitpi:/srv/git/project.git</pre><p>Push:</p><pre>git push -u origin main</pre><p>Clone:</p><pre>git clone gitpi:/srv/git/project.git</pre><p>View remotes:</p><pre>git remote -v</pre><p>Change a remote URL:</p><pre>git remote set-url origin gitpi:/srv/git/project.git</pre><p>Check repositories on the server:</p><pre>ls -lah /srv/git</pre><p>Check storage:</p><pre>du -sh /srv/git/*</pre><p>Verify repository integrity:</p><pre>git -C /srv/git/project.git fsck --full</pre><p>Run garbage collection:</p><pre>git -C /srv/git/project.git gc</pre><p>Back everything up:</p><pre>rsync -a /srv/git/ /mnt/backup/git/</pre><h3>Why Bother?</h3><p>It is fair to ask why anyone would build this when GitHub already exists.</p><p>For me, the interesting answer is not really privacy or cost.</p><p>It is ownership.</p><p>There is something satisfying about realizing how little infrastructure is actually necessary.</p><p>A machine accepts SSH.</p><p>A directory contains Git objects.</p><p>Your laptop pushes commits.</p><p>That is it.</p><p>Modern software platforms often make simple systems look impossibly complicated because we usually encounter the platform before we encounter the primitive underneath it.</p><p>Running Git yourself reverses that.</p><p>You discover that underneath GitHub, GitLab, Bitbucket, CI dashboards, contribution graphs, repository analytics, AI coding assistants, pull-request robots, and the entire modern software-development circus is a beautifully small idea:</p><pre>send these objects to another Git repository</pre><p>A Raspberry Pi is powerful enough to handle that job without breaking a sweat.</p><p>And once you have one little Linux machine permanently attached to your network, the dangerous thought inevitably appears:</p><p><strong>What else could this thing host?</strong></p><p>A package mirror?</p><p>A private wiki?</p><p>A monitoring dashboard?</p><p>A DNS server?</p><p>A build machine?</p><p>An RSS aggregator?</p><p>A VPN gateway?</p><p>A local AI API?</p><p>A deployment server?</p><p>A home automation controller?</p><p>This is how homelabs happen.</p><p>One minute you are storing three repositories on a Raspberry Pi.</p><p>Six months later there is a rack in the closet and you are telling somebody why your network absolutely needs four VLANs.</p><p>Consider yourself warned.</p><h3>Final Thoughts</h3><p>Turning a Raspberry Pi into a personal Git server is one of those projects that hits a sweet spot.</p><p>It is genuinely useful, simple enough to build in an evening, and deep enough to teach you something about how the tools you use every day actually work.</p><p>You end up learning a little Linux administration, SSH authentication, Unix permissions, Git internals, networking, backups, and server architecture without needing some enormous artificial lab environment.</p><p>More importantly, you finish with infrastructure you can actually keep using.</p><p>Create the Pi.</p><p>Create /srv/git.</p><p>Create a bare repository.</p><p>Push code.</p><p>And suddenly that tiny board blinking quietly in the corner of your room is not another abandoned electronics project.</p><p>It is infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62487038d2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Self-Correcting Coding Loop With Python]]></title>
            <link>https://medium.com/@chainc0der/building-a-self-correcting-coding-loop-with-python-a2d413aea775?source=rss-7f8489b3bc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d413aea775</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[[chaincoder.]]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 16:50:22 GMT</pubDate>
            <atom:updated>2026-08-22T16:50:22.363Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generate code, execute it inside a sandbox, capture errors, feed those errors back, rerun tests, and stop under explicit conditions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pw2xbf9wSftLTuW9" /><figcaption>Photo by <a href="https://unsplash.com/@writecodenow?utm_source=medium&amp;utm_medium=referral">Boitumelo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is a point where AI-assisted programming stops feeling like autocomplete with delusions of grandeur and starts becoming something more structurally interesting. That point is not reached when the model gets bigger, or when the prompt becomes three pages long, or when somebody gives the interface a glowing orb and calls it an autonomous engineer. It happens when the model is forced to interact with reality.</p><p>A normal coding assistant is often used in a single pass. You describe a function, it writes the function, and you inspect the result. Sometimes it is correct. Sometimes it contains a bug that would have been obvious if anybody, human or machine, had bothered to execute the thing. The uncomfortable truth is that language models are extraordinarily good at producing code that <em>looks</em> finished. Syntax, naming, comments, structure, even explanations can all radiate competence while a single badly placed assumption quietly waits underneath like a loose stair.</p><p>A self-correcting coding loop changes the relationship completely. Instead of asking the model to produce code and trusting whatever falls out, we surround it with machinery that can execute the generated program, capture actual failures, turn those failures into new context, ask for a repair, and repeat the process until something concrete happens. Either the code satisfies the tests, or the loop reaches an explicit stopping condition and admits defeat.</p><p>That second part matters more than it sounds. A good coding agent should know how to fail.</p><p>The architecture we are going to build is deliberately small. Python will orchestrate the loop. A model will generate candidate code. Pytest will decide whether that candidate actually works. subprocess will execute the tests and collect the resulting stdout, stderr, and exit code. Failed attempts will be fed back into the model as evidence rather than vague criticism. The loop will keep state, detect stagnation, and stop if it runs out of permitted attempts.</p><p>The model provider itself barely matters. You could connect this pattern to OpenAI, Anthropic, Gemini, OpenRouter, Ollama, llama.cpp, a local coding model, or some questionable cluster of refurbished workstation GPUs humming under a desk. What matters is the feedback architecture wrapped around it.</p><p>The primitive shape looks like this:</p><pre>TASK<br>  |<br>  v<br>GENERATE CODE<br>  |<br>  v<br>WRITE CANDIDATE<br>  |<br>  v<br>RUN TESTS<br>  |<br>  +------ PASS ------&gt; VERIFY ------&gt; DONE<br>  |<br> FAIL<br>  |<br>  v<br>CAPTURE ERROR OUTPUT<br>  |<br>  v<br>BUILD REPAIR CONTEXT<br>  |<br>  v<br>GENERATE REVISION<br>  |<br>  v<br>RUN AGAIN</pre><p>That loop may look almost disappointingly simple, but simple mechanisms can become surprisingly capable when the feedback is real. A compiler is not intelligent, but it is brutally useful because it refuses to be impressed by your intentions. Tests behave the same way. They do not care that a generated function appears elegant. They only care whether the expected behavior occurs.</p><p>That is exactly the kind of cold external judgment an AI coding system needs.</p><h3>Start with a task that can actually be verified</h3><p>The first rule of building a correction loop is that the machine needs some definition of correctness that does not come from the model itself. If the model writes the code and then also decides whether the code is good, you have basically created a student who writes their own exam, grades it, and then proudly reports a 100.</p><p>For this example, we will ask the system to implement a slugify function.</p><p>The interface is simple:</p><pre>def slugify(text: str) -&gt; str:<br>    ...</pre><p>We want behavior such as:</p><pre>&quot;Hello World&quot;        -&gt; &quot;hello-world&quot;<br>&quot;  Weird   Spaces &quot; -&gt; &quot;weird-spaces&quot;<br>&quot;Café Time&quot;          -&gt; &quot;cafe-time&quot;<br>&quot;Hello!!!&quot;           -&gt; &quot;hello&quot;<br>&quot;&quot;                   -&gt; &quot;&quot;</pre><p>Instead of merely describing those cases to the model, we encode them as tests. Create a workspace like this:</p><pre>workspace/<br>├── candidate.py<br>└── test_candidate.py</pre><p>The generated implementation will live in candidate.py. Our test contract lives separately in test_candidate.py.</p><pre>from candidate import slugify<br></pre><pre>def test_basic():<br>    assert slugify(&quot;Hello World&quot;) == &quot;hello-world&quot;<br></pre><pre>def test_multiple_spaces():<br>    assert slugify(&quot;  Weird   Spaces &quot;) == &quot;weird-spaces&quot;<br></pre><pre>def test_punctuation():<br>    assert slugify(&quot;Hello!!!&quot;) == &quot;hello&quot;<br></pre><pre>def test_unicode():<br>    assert slugify(&quot;Café Time&quot;) == &quot;cafe-time&quot;<br></pre><pre>def test_empty():<br>    assert slugify(&quot;&quot;) == &quot;&quot;</pre><p>The separation is important. The model is allowed to modify the implementation, but not the evaluator. If you give an autonomous system permission to edit both the program and the tests, it may eventually discover a brilliant and technically flawless strategy:</p><pre>def test_everything():<br>    assert True</pre><p>At that point every bug has been eliminated by abolishing the concept of failure.</p><p>Very efficient. Also completely useless.</p><p>This is one of the recurring lessons in agent design. Never vaguely tell a system to “make everything pass” when it controls the mechanism that decides what passing means. Capabilities need boundaries, especially when the system is optimizing toward a measurable objective.</p><h3>Execute the candidate and capture what actually happened</h3><p>Python’s subprocess module gives us a straightforward bridge between our orchestration code and the test environment.</p><p>Start with a function that launches pytest:</p><pre>import subprocess<br></pre><pre>def run_tests(workspace: str) -&gt; dict:<br>    process = subprocess.run(<br>        [&quot;python&quot;, &quot;-m&quot;, &quot;pytest&quot;, &quot;-q&quot;],<br>        cwd=workspace,<br>        capture_output=True,<br>        text=True,<br>        timeout=20,<br>    )</pre><pre>    return {<br>        &quot;returncode&quot;: process.returncode,<br>        &quot;stdout&quot;: process.stdout,<br>        &quot;stderr&quot;: process.stderr,<br>        &quot;passed&quot;: process.returncode == 0,<br>    }</pre><p>There is more happening here than the size of the function suggests.</p><p>cwd=workspace ensures that pytest executes inside the candidate project rather than wherever the orchestrator happens to be running. capture_output=True tells Python to collect both standard output and standard error instead of dumping everything directly into the parent terminal. text=True converts those streams into normal Python strings, which is especially convenient because we eventually want to insert them into a repair prompt.</p><p>The timeout is equally important:</p><pre>timeout=20</pre><p>Generated code can hang. It can deadlock. It can enter an infinite loop. It can launch some spectacularly misguided recursive process that turns twenty lines of innocent Python into a small tribute to entropy.</p><p>Without a timeout, your “autonomous coding loop” can become an autonomous doing-nothing-forever loop.</p><p>Now the result of the test run is structured enough to reason about:</p><pre>result = run_tests(&quot;./workspace&quot;)</pre><pre>print(result[&quot;returncode&quot;])<br>print(result[&quot;stdout&quot;])<br>print(result[&quot;stderr&quot;])</pre><p>If pytest exits with status code 0, the candidate passed the current test suite. Anything else means we have new evidence to feed back into the system.</p><p>That evidence is dramatically more useful than telling the model, “This didn’t work.”</p><p>Imagine the first candidate looks like this:</p><pre>def slugify(text: str) -&gt; str:<br>    return text.lower().replace(&quot; &quot;, &quot;-&quot;)</pre><p>At a glance, this implementation seems plausible. It lowercases the string and replaces spaces with hyphens. A human skimming a long generated file might even let it slide.</p><p>The tests will not.</p><p>Pytest could return failures indicating that punctuation remains, accented characters are still present, and repeated spaces generate repeated hyphens. Suddenly the repair model is not guessing what went wrong. It has concrete observations from an external environment.</p><p>That distinction is the beginning of the entire self-correction mechanism.</p><h3>A subprocess is not a security sandbox</h3><p>Before going further, there is a distinction worth making because tutorials about coding agents often become irresponsibly casual around the word <em>sandbox</em>.</p><p>Running generated code through subprocess is not the same thing as securely isolating arbitrary code.</p><p>A child process running under your user account may still be able to read files your account can read, inspect environment variables, access network services, create additional processes, consume excessive memory, or find credentials you forgot existed. If you are experimenting locally with code generated from tightly controlled prompts, a subprocess may be enough to prototype the orchestration logic. It is not a serious containment strategy for hostile, untrusted, or public-facing workloads.</p><p>The execution backend should eventually become replaceable.</p><p>For a stronger environment, you might run every candidate inside:</p><pre>Docker<br>Podman<br>bubblewrap<br>nsjail<br>gVisor<br>Firecracker<br>systemd-nspawn<br>a disposable VM</pre><p>A serious sandbox should ideally provide a read-only or disposable filesystem, no inherited API credentials, restricted or disabled networking, a non-root account, process limits, memory limits, CPU limits, and a hard wall-clock timeout. The environment should be treated as expendable. Create it, run the candidate, extract the results you care about, then destroy it.</p><p>This is one reason we are keeping the higher-level loop separate from the execution function. Today run_tests() might call subprocess.run(). Tomorrow it can call Docker. Next month it can dispatch jobs to isolated Firecracker microVMs. The correction logic does not need to know.</p><p>That is the right boundary.</p><h3>Turn raw failure output into repair context</h3><p>Suppose the generated implementation fails three tests. The next model call should not be another copy of the original prompt. If you keep regenerating from the same request, you are not really building a correction loop. You are buying lottery tickets.</p><p>We want the actual test output.</p><p>A small helper can combine the relevant execution evidence:</p><pre>def build_error_report(result: dict) -&gt; str:<br>    return f&quot;&quot;&quot;<br>TEST EXIT CODE:<br>{result[&quot;returncode&quot;]}</pre><pre>STDOUT:<br>{result[&quot;stdout&quot;]}</pre><pre>STDERR:<br>{result[&quot;stderr&quot;]}<br>&quot;&quot;&quot;.strip()</pre><p>Now the repair phase can see exactly what happened.</p><p>That matters because runtime errors tend to contain highly localized information. An assertion such as:</p><pre>assert &#39;café-time&#39; == &#39;cafe-time&#39;</pre><p>tells the model far more than:</p><pre>unicode handling is broken</pre><p>Likewise, a Python traceback may reveal the exact line, exception type, stack path, and input that triggered the failure. A compiler may report a missing type. A linter may identify an invalid import. A browser test might report that a button cannot be found.</p><p>Modern coding agents become much more powerful when they consume the exhaust produced by real tools.</p><p>Errors stop being terminal states.</p><p>They become observations.</p><h3>Build a repair prompt that contains evidence, not vibes</h3><p>We can now construct a prompt specifically for repair.</p><pre>def build_repair_prompt(<br>    task: str,<br>    current_code: str,<br>    error_report: str,<br>) -&gt; str:<br>    return f&quot;&quot;&quot;<br>You are repairing a Python implementation.</pre><pre>ORIGINAL TASK:</pre><pre>{task}</pre><pre>CURRENT IMPLEMENTATION:</pre><pre>```python<br>{current_code}</pre><p>TEST RESULTS:</p><pre>{error_report}</pre><p>Return a corrected implementation.</p><p>Requirements:</p><ul><li>Preserve the requested public interface.</li><li>Fix the underlying problem instead of modifying tests.</li><li>Preserve behavior that is already working.</li><li>Do not remove functionality merely to make one failing test pass.</li><li>Return only the complete contents of candidate.py.</li><li>Do not include Markdown fences.</li></ul><pre>This prompt is doing several useful things at once. It reminds the model of the original goal, shows it the code that currently exists, gives it the objective failure data, and establishes what it is allowed to change.</pre><pre>Notice that we are not asking for an essay explaining the error. We want a complete replacement candidate. That makes the next stage easy to automate.</pre><pre>There is also a subtle architectural principle hiding here: preserve the entire state needed for correction. A repair model that sees only the traceback may misunderstand the intent. A repair model that sees only the source may not understand the failure. A repair model that sees only the original request may simply regenerate another version of the same bug.</pre><pre>The combination matters.</pre><pre>---</pre><pre>## Keep the model provider abstract</pre><pre>A useful agent should not be welded to one API call.</pre><pre>We can define the smallest possible interface:</pre><pre>```python<br>from typing import Protocol<br></pre><pre>class CodeModel(Protocol):<br>    def generate(self, prompt: str) -&gt; str:<br>        ...</pre><p>Anything implementing generate() can now become the backend.</p><p>A provider wrapper might look conceptually like:</p><pre>class MyModel:<br>    def generate(self, prompt: str) -&gt; str:<br>        response = call_some_model_api(prompt)<br>        return response</pre><p>You can swap in a local model later without touching the loop itself.</p><p>For development, I strongly recommend also creating a fake implementation:</p><pre>class FakeModel:<br>    def __init__(self, responses: list[str]):<br>        self.responses = responses<br>        self.index = 0</pre><pre>    def generate(self, prompt: str) -&gt; str:<br>        if self.index &gt;= len(self.responses):<br>            raise RuntimeError(&quot;Fake model ran out of responses&quot;)</pre><pre>        response = self.responses[self.index]<br>        self.index += 1</pre><pre>        return response</pre><p>This lets you test the orchestration machinery without making real model calls. You can prepare one intentionally bad response followed by a corrected response and verify that the loop behaves properly.</p><p>This is one of those small decisions that pays off quickly. Autonomous systems need deterministic tests just as badly as the programs they generate. If every test of your agent requires a live API request, debugging the agent itself becomes slow, expensive, and annoyingly nondeterministic.</p><p>Eventually you find yourself asking one unreliable system to diagnose another unreliable system, which is roughly where software engineering starts turning into spiritualism.</p><h3>Write generated candidates into the workspace</h3><p>The model response needs to become an actual file before pytest can touch it.</p><pre>from pathlib import Path<br></pre><pre>def write_candidate(workspace: str, code: str) -&gt; None:<br>    path = Path(workspace) / &quot;candidate.py&quot;<br>    path.write_text(code, encoding=&quot;utf-8&quot;)</pre><p>Models also have a habit of returning Markdown fences even after being explicitly instructed not to. This is not unusual. Natural language instructions are soft constraints.</p><p>We can clean common formatting automatically:</p><pre>def clean_model_code(response: str) -&gt; str:<br>    response = response.strip()</pre><pre>    if response.startswith(&quot;```python&quot;):<br>        response = response[len(&quot;```python&quot;):]</pre><pre>    elif response.startswith(&quot;```&quot;):<br>        response = response[3:]</pre><pre>    if response.endswith(&quot;```&quot;):<br>        response = response[:-3]</pre><pre>    return response.strip()</pre><p>For a production system, structured model outputs or tool calls are cleaner than shaving Markdown off strings. For a small Python agent, this gets us moving.</p><p>The important thing is that generated output crosses a boundary. Model text becomes candidate source code, candidate source code enters an execution environment, and that environment produces evidence.</p><p>The loop is starting to breathe.</p><h3>Define explicit stopping conditions before you let anything loop</h3><p>This is probably the single most important operational detail in the entire tutorial.</p><p>Never build an autonomous system around:</p><pre>while not passed:<br>    ...</pre><p>unless you want to discover just how efficiently a coding model can turn API credits into warm air.</p><p>Every loop needs an upper bound, and ideally it should have several independent ways to terminate.</p><p>For our first version, we will stop if any of these conditions becomes true:</p><ol><li>All tests pass.</li><li>The maximum number of attempts is reached.</li><li>The model returns empty code.</li><li>The model returns exactly the same candidate again.</li><li>Execution exceeds the timeout.</li><li>The execution infrastructure itself fails.</li></ol><p>Represent the outcome as structured data:</p><pre>from dataclasses import dataclass<br></pre><pre>@dataclass<br>class LoopResult:<br>    success: bool<br>    reason: str<br>    attempts: int<br>    final_code: str<br>    last_stdout: str<br>    last_stderr: str</pre><p>Now the caller does not need to scrape logs to understand what happened. It receives an explicit result describing whether the run succeeded, why it stopped, how many attempts occurred, and what the final candidate looked like.</p><p>That becomes especially useful later when multiple coding runs are being scheduled automatically.</p><h3>Build the actual self-correcting loop</h3><p>Now we can connect the pieces.</p><pre>def self_correcting_loop(<br>    model: CodeModel,<br>    workspace: str,<br>    task: str,<br>    initial_prompt: str,<br>    max_attempts: int = 6,<br>) -&gt; LoopResult:</pre><pre>    previous_code = None<br>    current_prompt = initial_prompt</pre><pre>    last_stdout = &quot;&quot;<br>    last_stderr = &quot;&quot;</pre><pre>    for attempt in range(1, max_attempts + 1):</pre><pre>        print(f&quot;[agent] attempt {attempt}/{max_attempts}&quot;)</pre><pre>        raw_response = model.generate(current_prompt)<br>        candidate = clean_model_code(raw_response)</pre><pre>        if not candidate:<br>            return LoopResult(<br>                success=False,<br>                reason=&quot;model_returned_empty_code&quot;,<br>                attempts=attempt,<br>                final_code=&quot;&quot;,<br>                last_stdout=last_stdout,<br>                last_stderr=last_stderr,<br>            )</pre><pre>        if candidate == previous_code:<br>            return LoopResult(<br>                success=False,<br>                reason=&quot;model_repeated_identical_candidate&quot;,<br>                attempts=attempt,<br>                final_code=candidate,<br>                last_stdout=last_stdout,<br>                last_stderr=last_stderr,<br>            )</pre><pre>        write_candidate(workspace, candidate)</pre><pre>        try:<br>            result = run_tests(workspace)</pre><pre>        except subprocess.TimeoutExpired:<br>            return LoopResult(<br>                success=False,<br>                reason=&quot;execution_timeout&quot;,<br>                attempts=attempt,<br>                final_code=candidate,<br>                last_stdout=last_stdout,<br>                last_stderr=last_stderr,<br>            )</pre><pre>        last_stdout = result[&quot;stdout&quot;]<br>        last_stderr = result[&quot;stderr&quot;]</pre><pre>        if result[&quot;passed&quot;]:<br>            return LoopResult(<br>                success=True,<br>                reason=&quot;tests_passed&quot;,<br>                attempts=attempt,<br>                final_code=candidate,<br>                last_stdout=last_stdout,<br>                last_stderr=last_stderr,<br>            )</pre><pre>        error_report = build_error_report(result)</pre><pre>        current_prompt = build_repair_prompt(<br>            task=task,<br>            current_code=candidate,<br>            error_report=error_report,<br>        )</pre><pre>        previous_code = candidate</pre><pre>    return LoopResult(<br>        success=False,<br>        reason=&quot;maximum_attempts_reached&quot;,<br>        attempts=max_attempts,<br>        final_code=previous_code or &quot;&quot;,<br>        last_stdout=last_stdout,<br>        last_stderr=last_stderr,<br>    )</pre><p>This is the core mechanism.</p><p>A candidate is generated. The candidate is written to disk. Tests execute. If the process succeeds, we return. If the process fails, we turn the failure into new context and ask the model to repair the implementation. The next revision is then tested under the exact same external contract.</p><p>The model is never trusted simply because it says the job is finished.</p><p>That small difference gives the system teeth.</p><h3>Generate the first candidate</h3><p>The loop still needs a starting prompt.</p><p>Define the task clearly:</p><pre>TASK = &quot;&quot;&quot;<br>Implement a function named slugify(text: str) -&gt; str.</pre><pre>Requirements:</pre><pre>- Convert text to lowercase.<br>- Convert runs of whitespace to one hyphen.<br>- Remove punctuation.<br>- Normalize accented Latin characters to their ASCII equivalents.<br>- Remove leading and trailing hyphens.<br>- Preserve the exact function name and signature.<br>&quot;&quot;&quot;</pre><p>Then create an initial generation prompt:</p><pre>INITIAL_PROMPT = f&quot;&quot;&quot;<br>Write candidate.py for the following task:</pre><pre>{TASK}</pre><pre>The implementation will be evaluated using automated tests.</pre><pre>Return only valid Python source code.<br>Do not include Markdown fences.<br>&quot;&quot;&quot;</pre><p>Your model adapter can then be passed into the loop:</p><pre>model = YourModel(...)</pre><p>Run it:</p><pre>result = self_correcting_loop(<br>    model=model,<br>    workspace=&quot;./workspace&quot;,<br>    task=TASK,<br>    initial_prompt=INITIAL_PROMPT,<br>    max_attempts=6,<br>)</pre><pre>print(result)</pre><p>A healthy run might progress like this:</p><pre>[agent] attempt 1/6<br>3 failed, 2 passed</pre><pre>[agent] attempt 2/6<br>1 failed, 4 passed</pre><pre>[agent] attempt 3/6<br>5 passed</pre><p>What you are watching is not magical self-awareness. It is iterative search guided by external feedback.</p><p>That is more useful anyway.</p><p>The first implementation occupied one point in the space of possible programs. Pytest rejected it and returned information about why. The model generated another nearby candidate. That candidate survived more constraints. Eventually one satisfied the evaluator.</p><p>You have converted code generation into a closed-loop process.</p><h3>Archive every attempt</h3><p>Once your loop becomes remotely interesting, you will want history.</p><p>Do not overwrite every failed candidate and throw it away.</p><p>Store them:</p><pre>def archive_candidate(<br>    workspace: str,<br>    code: str,<br>    attempt: int,<br>) -&gt; None:</pre><pre>    history = Path(workspace) / &quot;attempts&quot;<br>    history.mkdir(exist_ok=True)</pre><pre>    filename = history / f&quot;attempt_{attempt:02d}.py&quot;<br>    filename.write_text(code, encoding=&quot;utf-8&quot;)</pre><p>Call this immediately after receiving each candidate.</p><p>Your directory could become:</p><pre>workspace/<br>├── candidate.py<br>├── test_candidate.py<br>└── attempts/<br>    ├── attempt_01.py<br>    ├── attempt_02.py<br>    ├── attempt_03.py<br>    └── attempt_04.py</pre><p>This creates a useful forensic trail. You can inspect how the model moved through the problem, identify regressions, measure whether later attempts actually improved anything, and debug bizarre behavior without relying on terminal scrollback.</p><p>I like to think of this as agent archaeology. When attempt seven somehow replaces a perfectly reasonable parser with 400 lines of regex and existential dread, you can go back and see exactly where civilization collapsed.</p><p>History is cheap.</p><p>Keep it.</p><h3>Add failure memory so the model stops walking in circles</h3><p>A correction loop without memory can still oscillate.</p><p>Imagine this pattern:</p><pre>Attempt 1:<br>Uses str.replace().<br>Fails Unicode.</pre><pre>Attempt 2:<br>Uses regex.<br>Fails whitespace.</pre><pre>Attempt 3:<br>Returns to str.replace().<br>Fails Unicode.</pre><pre>Attempt 4:<br>Uses regex again.<br>Fails whitespace.</pre><p>The system is moving, but not learning in any useful sense.</p><p>Keep a short failure history:</p><pre>failure_history = []</pre><p>After each failed run:</p><pre>failure_history.append({<br>    &quot;attempt&quot;: attempt,<br>    &quot;code&quot;: candidate,<br>    &quot;error&quot;: error_report,<br>})</pre><p>You can then summarize those previous failures into the next prompt.</p><p>For example:</p><pre>PREVIOUS FAILED APPROACHES:</pre><pre>Attempt 1:<br>Used simple str.replace.<br>Failed punctuation and Unicode normalization tests.</pre><pre>Attempt 2:<br>Handled punctuation but produced repeated hyphens for multiple spaces.</pre><pre>Do not repeat these approaches unless the new implementation specifically addresses the observed failure.</pre><p>This changes the search behavior. Instead of treating every retry as a fresh universe, the model gets a crude memory of territory already explored.</p><p>You do not necessarily want to paste six complete Python files and six enormous pytest traces into every prompt. Context can become noisy. Summaries often work better. Preserve the details locally, but feed the model the failures that matter.</p><p>This is where the system begins edging away from “retry loop” and toward something resembling deliberate iterative debugging.</p><p>Not human debugging, obviously. Let us not get drunk on terminology.</p><p>But the structure starts becoming recognizable.</p><h3>Detect cycles, not just identical strings</h3><p>Checking:</p><pre>if candidate == previous_code:</pre><p>catches one obvious failure mode.</p><p>It does not catch:</p><pre>candidate_a<br>candidate_b<br>candidate_a<br>candidate_b</pre><p>A simple hash set works better.</p><pre>import hashlib<br></pre><pre>def code_hash(code: str) -&gt; str:<br>    return hashlib.sha256(<br>        code.encode(&quot;utf-8&quot;)<br>    ).hexdigest()</pre><p>Inside the loop:</p><pre>seen_hashes = set()</pre><p>Then:</p><pre>digest = code_hash(candidate)</pre><pre>if digest in seen_hashes:<br>    return LoopResult(<br>        success=False,<br>        reason=&quot;candidate_cycle_detected&quot;,<br>        attempts=attempt,<br>        final_code=candidate,<br>        last_stdout=last_stdout,<br>        last_stderr=last_stderr,<br>    )</pre><pre>seen_hashes.add(digest)</pre><p>Now any exact previously generated candidate terminates the loop.</p><p>A more advanced system could normalize the Python AST before hashing it. That would let you detect candidates that are semantically almost identical even if the model changed variable names, formatting, or comments.</p><p>At that point you are no longer merely asking whether the text repeated.</p><p>You are asking whether the strategy repeated.</p><p>That is a much more interesting signal.</p><h3>Do not use tests as your only evaluator</h3><p>Passing tests is useful, but tests only measure what you remembered to test.</p><p>A stronger coding loop can combine several independent evaluators.</p><p>For Python, you might run:</p><pre>pytest<br>ruff<br>mypy<br>bandit<br>coverage<br>custom benchmarks</pre><p>Create a reusable command runner:</p><pre>def run_command(<br>    command: list[str],<br>    workspace: str,<br>    timeout: int = 20,<br>) -&gt; dict:</pre><pre>    process = subprocess.run(<br>        command,<br>        cwd=workspace,<br>        capture_output=True,<br>        text=True,<br>        timeout=timeout,<br>    )</pre><pre>    return {<br>        &quot;command&quot;: command,<br>        &quot;returncode&quot;: process.returncode,<br>        &quot;stdout&quot;: process.stdout,<br>        &quot;stderr&quot;: process.stderr,<br>        &quot;passed&quot;: process.returncode == 0,<br>    }</pre><p>Define your checks:</p><pre>CHECKS = [<br>    [&quot;python&quot;, &quot;-m&quot;, &quot;pytest&quot;, &quot;-q&quot;],<br>    [&quot;ruff&quot;, &quot;check&quot;, &quot;.&quot;],<br>    [&quot;mypy&quot;, &quot;candidate.py&quot;],<br>]</pre><p>Then run them:</p><pre>def run_checks(workspace: str) -&gt; list[dict]:<br>    results = []</pre><pre>    for command in CHECKS:<br>        result = run_command(command, workspace)<br>        results.append(result)</pre><pre>    return results</pre><p>Now correctness becomes multi-dimensional.</p><p>The implementation must not merely satisfy examples. It may also need to type-check cleanly, avoid lint violations, pass security analysis, and remain within a performance threshold.</p><p>This is where deterministic tooling starts doing the work that people mistakenly expect a model to do internally.</p><p>Instead of asking:</p><blockquote><em>Is this implementation secure?</em></blockquote><p>run a scanner.</p><p>Instead of asking:</p><blockquote><em>Did you preserve the public API?</em></blockquote><p>inspect it.</p><p>Instead of asking:</p><blockquote><em>Is the function fast?</em></blockquote><p>benchmark it.</p><p>Models are useful generators and interpreters. They are terrible gods.</p><p>Whenever a property can be measured externally, measure it externally.</p><h3>Separate diagnosis from repair</h3><p>One of the best upgrades you can make is inserting a diagnostic stage between failure and rewriting.</p><p>Our first version does this:</p><pre>test failure -&gt; generate revised code</pre><p>A more deliberate version does this:</p><pre>test failure<br>    |<br>    v<br>diagnose root cause<br>    |<br>    v<br>produce repair plan<br>    |<br>    v<br>generate revised code</pre><p>The diagnostic prompt might look like:</p><pre>Analyze the failing implementation before modifying it.</pre><pre>Return:</pre><pre>ROOT CAUSE:<br>A concise explanation of why the observed tests fail.</pre><pre>REQUIRED CHANGE:<br>Describe what behavior must change.</pre><pre>REGRESSION RISKS:<br>Describe which currently passing behaviors could accidentally break.</pre><pre>Do not write replacement code yet.</pre><p>Then pass the diagnosis into a second model call responsible for implementation.</p><p>Why bother?</p><p>Because debugging and code generation are different tasks. If you ask for an immediate rewrite, a model may react to the visible symptom and mutate code blindly. Forcing it to articulate a root cause creates a checkpoint where the system can inspect its theory before committing another candidate.</p><p>You can even validate the diagnosis itself.</p><p>Maybe one model diagnoses and another reviews the diagnosis. Maybe a cheap model writes the candidate while a stronger one gets invoked only after repeated failures. Maybe a specialized static analyzer provides evidence before either model responds.</p><p>Once you start thinking in stages, “AI coding agent” stops meaning one enormous prompt and starts meaning an actual software pipeline.</p><p>That is healthier.</p><h3>Escalate instead of retrying forever</h3><p>If the same model has failed three times, a seventh near-identical attempt may not be the optimal use of money.</p><p>Model escalation can be remarkably effective.</p><p>For example:</p><pre>if attempt &lt;= 3:<br>    active_model = cheap_model<br>else:<br>    active_model = strong_model</pre><p>Or use role specialization:</p><pre>Attempt 1:<br>fast model generates implementation</pre><pre>Attempt 2:<br>fast model repairs obvious test failures</pre><pre>Attempt 3:<br>fast model tries again</pre><pre>Attempt 4:<br>strong model performs root-cause analysis</pre><pre>Attempt 5:<br>coding model implements the diagnosis</pre><pre>Attempt 6:<br>independent verifier reviews final candidate</pre><p>This gives you something closer to an escalation tree than an infinite retry loop.</p><p>You can also escalate based on failure type. A syntax error probably does not need your most expensive model. A subtle concurrency bug after five passing iterations might.</p><p>Agent architecture becomes much more efficient when you stop treating every problem state as equivalent.</p><h3>Put budgets into the stopping logic</h3><p>Attempts are only one resource.</p><p>A real system may also need to limit:</p><pre>wall-clock time<br>model tokens<br>API cost<br>CPU time<br>memory consumption<br>number of sandbox executions<br>number of generated files<br>number of changed lines</pre><p>You could eventually define something like:</p><pre>STOP SUCCESSFULLY IF:</pre><pre>- all unit tests pass<br>- type checking passes<br>- linting passes<br>- security scan passes<br>- coverage &gt;= 90%</pre><pre>STOP UNSUCCESSFULLY IF:</pre><pre>- attempts &gt;= 8<br>- total runtime &gt;= 300 seconds<br>- model budget &gt;= $2.00<br>- candidate cycle detected<br>- identical failure appears three times<br>- sandbox violation detected</pre><pre>REQUEST HUMAN REVIEW IF:</pre><pre>- requirements appear contradictory<br>- repair requires changing a public interface<br>- dependencies cannot be resolved safely<br>- tests appear inconsistent with the task</pre><p>This may sound overly formal for a small Python script, but explicit conditions are what make autonomous systems manageable.</p><p>“Keep trying until it works” sounds exciting right up until the process is still running three hours later because an integration test depends on a service that no longer exists.</p><p>Good autonomy includes the ability to stop and say, “This state requires something outside my permitted actions.”</p><p>That is not weakness.</p><p>That is control.</p><h3>The same pattern works far beyond one Python function</h3><p>Once you have this mechanism, slugify() is almost insultingly small.</p><p>The same structure can drive frontend work:</p><pre>generate component<br>run npm test<br>run TypeScript compiler<br>launch headless browser<br>capture browser console<br>run Playwright tests<br>capture screenshot<br>repair implementation<br>rerun</pre><p>It can drive systems programming:</p><pre>generate Rust<br>cargo check<br>cargo test<br>cargo clippy<br>run benchmark<br>repair</pre><p>It can drive data work:</p><pre>generate transformation<br>run against fixture dataset<br>validate schema<br>compare expected rows<br>inspect failures<br>repair</pre><p>It can even become useful in authorized security research environments where code must be tested against known fixtures or intentionally vulnerable lab targets:</p><pre>generate parser<br>run fuzz corpus<br>capture crash<br>inspect exception<br>repair parser<br>rerun corpus</pre><p>The details change, but the rhythm barely does:</p><pre>PROPOSE<br>EXECUTE<br>OBSERVE<br>DIAGNOSE<br>CORRECT<br>VERIFY<br>STOP</pre><p>That pattern is much more important than whatever model happens to be fashionable this month.</p><h3>The model should generate possibilities. Reality should judge them.</h3><p>There is a strange habit in AI tooling where we ask the same probabilistic system to create something and then certify its own work.</p><p>The model writes the function.</p><p>Then somebody asks:</p><blockquote><em>Are you confident this is correct?</em></blockquote><p>And the model replies with six paragraphs explaining that yes, the implementation correctly handles edge cases, follows best practices, remains robust under malformed input, and probably deserves a small plaque.</p><p>Then you run the program and it throws KeyError on the second input.</p><p>Confidence is not verification.</p><p>What makes self-correcting coding loops useful is not that the model suddenly becomes smarter after seeing an error. It is that the system stops relying exclusively on the model’s internal judgment.</p><p>The language model proposes.</p><p>The environment responds.</p><p>The model interprets the response.</p><p>The evaluator decides whether the new proposal survives.</p><p>You are building a conversation between probabilistic generation and deterministic constraint.</p><p>That is a much more powerful architecture than endlessly polishing prompts in search of a mythical one-shot answer.</p><p>Eventually, the most capable coding agents may contain dozens of tools, multiple specialized models, long-term memory, repository search, dependency analysis, browser automation, test generation, deployment checks, and elaborate planning systems. Those systems will look enormously complicated from the outside.</p><p>Underneath all of that machinery, though, there will still be a loop.</p><p>Try something.</p><p>Run it.</p><p>Observe what happened.</p><p>Change what needs changing.</p><p>Stop when the evidence says you are done.</p><p>That is the interesting part.</p><p>Not the glowing interface. Not the anthropomorphic status messages. Not the model announcing that it is “thinking deeply about your codebase.”</p><p>Give the system a real task. Give it a disposable place to make mistakes. Give it tools that can disagree with it. Give it memory of what already failed. Give it a budget. Give it explicit authority boundaries. Most importantly, give it a definition of done that exists outside the model’s own opinion.</p><p>Then let it argue with reality until either the program works or the machine has the good sense to stop.</p><h3>Keep Building</h3><p>A self-correcting coding loop is where AI development starts getting interesting. Once your model can generate code, execute tools, observe failure, preserve state, and try again under explicit constraints, you are already moving from “chatbot that writes code” toward an actual software agent.</p><p>If you want to take that architecture further, I put together the <strong>Claude Code Field Manual</strong>, covering agent workflows, tool use, MCP, subagents, debugging loops, recovery strategies, and the infrastructure around making coding agents genuinely useful rather than merely impressive in demos.</p><p><strong>→ Claude Code Field Manual:</strong></p><p><a href="https://numbpilled.gumroad.com/l/claudefield">Claude Code Field Manual</a></p><p>Or, if you want to experiment with the basic architecture without another API bill, start with <strong>AGENTS WITHOUT THE CLOUD</strong>, my free field guide to running a local model inside a controlled tool loop with bounded execution and persistent local files.</p><p><strong>→ AGENTS WITHOUT THE CLOUD:</strong></p><p><a href="https://numbpilled.gumroad.com/l/cloudless-agents">AGENTS WITHOUT THE CLOUD - free agent route seed</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*SbujQ3ej0Zstt_owz1T6aw.gif" /><figcaption>Keep pushing!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d413aea775" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Coding With Git Worktrees: Let Multiple Agents Attack the Same Problem]]></title>
            <link>https://medium.com/@chainc0der/ai-coding-with-git-worktrees-let-multiple-agents-attack-the-same-problem-05c8117b74f9?source=rss-7f8489b3bc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/05c8117b74f9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[[chaincoder.]]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 16:50:00 GMT</pubDate>
            <atom:updated>2026-08-22T16:50:00.874Z</atom:updated>
            <content:encoded><![CDATA[<h4>One agent refactors, one writes tests, one hunts bugs, one reviews the others, all without stomping over the same working tree.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ngG0blrM1QDpqFlV" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AI coding gets weird the moment you stop treating the model like autocomplete.</p><p>One agent is manageable. You point Claude Code, Codex, Aider, OpenClaw, or whatever flavor of synthetic intern you currently trust at a repository and tell it to fix something. It reads files. It changes files. Maybe it runs tests. Maybe it creates three unrelated utility classes because you vaguely said “clean this up.” You inspect the wreckage, keep the good parts, revert the strange parts, and continue.</p><p>Then you have the dangerous thought.</p><p>Why use one?</p><p>You have enough compute to run four coding agents simultaneously. One could refactor the implementation. Another could write adversarial tests. A third could hunt for bugs. A fourth could review every change like an exhausted senior engineer who has recently developed strong opinions about null handling.</p><p>This sounds fantastic until all four agents are operating inside the same Git working directory.</p><p>Then your elegant multi-agent engineering department becomes four raccoons fighting over one keyboard.</p><p>Agent A renames a module while Agent B is importing the old filename. Agent C resets a file because its diff looks unexpected. Agent D sees modifications it did not create and helpfully “cleans them up.” One agent runs git checkout -- on something another agent spent twelve minutes generating. A formatter touches thirty files. Tests start failing for reasons that only existed for six seconds. Nobody knows which changes belong to whom.</p><p>The problem is not AI.</p><p>The problem is filesystem architecture.</p><p>Git already has a beautifully boring solution: <strong>worktrees</strong>.</p><p>Git worktrees let multiple independent working directories share the same underlying repository. Each worktree can sit on its own branch, contain its own modified files, run its own processes, and host its own coding agent.</p><p>Same Git history.</p><p>Different directories.</p><p>No file stomping.</p><p>Suddenly multi-agent coding stops looking like four bots elbowing each other in a phone booth and starts looking like actual parallel engineering.</p><p>That is what we are going to build.</p><h3>The Single Working Tree Is the Bottleneck</h3><p>A normal Git repository looks roughly like this:</p><pre>my-project/<br>├── .git/<br>├── src/<br>├── tests/<br>├── package.json<br>└── README.md</pre><p>You might open four terminals and start four agents:</p><pre>cd my-project<br>claude</pre><pre>cd my-project<br>codex</pre><pre>cd my-project<br>aider</pre><pre>cd my-project<br>some-other-agent</pre><p>Technically, congratulations. You are doing “multi-agent development.”</p><p>Practically, all four processes are editing the same physical files.</p><p>That means there is no isolation boundary.</p><p>Suppose your task is:</p><blockquote><em>Improve the authentication module, add stronger tests, identify existing security bugs, and review the final implementation.</em></blockquote><p>Agent 1 starts refactoring:</p><pre>src/auth.py</pre><p>Agent 2 starts adding tests against the current behavior.</p><p>Agent 3 notices a suspicious branch and modifies src/auth.py while Agent 1 is halfway through rewriting it.</p><p>Agent 4 runs:</p><pre>git diff</pre><p>It sees everybody’s changes mixed together and has absolutely no reliable way to know which agent owns which modification.</p><p>The filesystem has become shared mutable state.</p><p>Anyone who has spent enough time debugging concurrent software should already be developing a small nervous twitch.</p><p>The clean solution is not increasingly elaborate agent prompts telling everyone to “please avoid touching each other’s files.”</p><p>The clean solution is isolation.</p><h3>Enter git worktree</h3><p>A Git worktree is another checkout of the same repository.</p><p>You can create one with:</p><pre>git worktree add ../project-tests -b agent/tests</pre><p>Now you have something like:</p><pre>projects/<br>├── my-project/<br>└── project-tests/</pre><p>Both directories belong to the same Git repository, but project-tests is checked out on a different branch.</p><p>Your original repository might be on:</p><pre>main</pre><p>while the new worktree uses:</p><pre>agent/tests</pre><p>Each directory has its own files.</p><p>Agent A can mutilate src/auth.py in one worktree while Agent B edits an entirely separate physical copy of src/auth.py in another.</p><p>Git keeps the repository metadata coordinated underneath.</p><p>This is the important mental model:</p><pre>SHARED GIT HISTORY<br>                           │<br>          ┌────────────────┼────────────────┐<br>          │                │                │<br>       WORKTREE A       WORKTREE B       WORKTREE C<br>       refactor         tests            bughunt<br>          │                │                │<br>      branch A         branch B         branch C</pre><p>The agents share history, not their immediate filesystem state.</p><p>That distinction changes everything.</p><h3>Build the Multi-Agent Workspace</h3><p>Imagine the repository is called:</p><pre>neon-api</pre><p>Start normally:</p><pre>git clone https://github.com/example/neon-api.git<br>cd neon-api</pre><p>Make sure the baseline is clean:</p><pre>git status</pre><p>You want:</p><pre>nothing to commit, working tree clean</pre><p>Now create four worktrees.</p><h3>Agent 1: Refactoring</h3><pre>git worktree add ../neon-api-refactor -b agent/refactor</pre><h3>Agent 2: Tests</h3><pre>git worktree add ../neon-api-tests -b agent/tests</pre><h3>Agent 3: Bug Hunting</h3><pre>git worktree add ../neon-api-bughunt -b agent/bughunt</pre><h3>Agent 4: Review</h3><pre>git worktree add ../neon-api-review -b agent/review</pre><p>Your filesystem now looks like:</p><pre>workspace/<br>├── neon-api/<br>├── neon-api-refactor/<br>├── neon-api-tests/<br>├── neon-api-bughunt/<br>└── neon-api-review/</pre><p>Check the setup:</p><pre>git worktree list</pre><p>You should see output resembling:</p><pre>/home/user/workspace/neon-api           abc1234 [main]<br>/home/user/workspace/neon-api-refactor  abc1234 [agent/refactor]<br>/home/user/workspace/neon-api-tests     abc1234 [agent/tests]<br>/home/user/workspace/neon-api-bughunt   abc1234 [agent/bughunt]<br>/home/user/workspace/neon-api-review    abc1234 [agent/review]</pre><p>Four branches.</p><p>Four directories.</p><p>Four agents.</p><p>One repository.</p><p>Much less screaming.</p><h3>Give Every Agent a Job, Not a Vibe</h3><p>The biggest mistake people make with coding agents is giving them blurry responsibilities.</p><p>Something like:</p><blockquote><em>Improve the project and look for problems.</em></blockquote><p>That is not a role. That is how you accidentally get a 700-line rewrite of your configuration loader.</p><p>Parallel agents work best when their responsibilities deliberately conflict in useful ways.</p><p>Your refactoring agent should optimize implementation quality.</p><p>Your testing agent should distrust the implementation.</p><p>Your bug-hunting agent should assume something is broken.</p><p>Your reviewer should assume the other three are dangerously overconfident.</p><p>That tension is productive.</p><p>For example:</p><h3>Refactor Agent</h3><pre>You are responsible only for improving the authentication implementation.</pre><pre>Goals:</pre><pre>- simplify duplicated logic<br>- improve error handling<br>- preserve external behavior<br>- reduce unnecessary state<br>- improve typing where useful<br>- run the existing test suite</pre><pre>Do not rewrite unrelated modules.</pre><pre>Commit your changes when complete.</pre><p>Launch it inside:</p><pre>cd ../neon-api-refactor<br>claude</pre><p>or:</p><pre>codex</pre><p>or whatever agent runner you use.</p><p>The particular AI is less important than the filesystem separation.</p><h3>Test Agent</h3><p>Inside another terminal:</p><pre>cd ../neon-api-tests</pre><p>Prompt:</p><pre>Your responsibility is to create aggressive tests for the authentication system.</pre><pre>Do not modify production code unless absolutely necessary.</pre><pre>Look for:</pre><pre>- boundary conditions<br>- malformed inputs<br>- authentication bypasses<br>- expired sessions<br>- duplicate requests<br>- race conditions<br>- missing values<br>- invalid encodings</pre><pre>Add tests that expose failures.</pre><pre>Commit your work.</pre><p>This agent is not supposed to make the implementation look good.</p><p>It is supposed to make the implementation uncomfortable.</p><p>Excellent.</p><h3>Bug Hunting Agent</h3><pre>cd ../neon-api-bughunt</pre><p>Prompt:</p><pre>Audit the authentication system for bugs.</pre><pre>Focus on finding concrete failures rather than refactoring.</pre><pre>For each bug:</pre><pre>1. explain the failure<br>2. reproduce it where possible<br>3. create a minimal test<br>4. implement a narrowly scoped fix<br>5. run relevant tests</pre><pre>Commit each logical fix separately when practical.</pre><p>Now you have an agent actively searching for cases nobody thought about.</p><h3>Review Agent</h3><p>The review agent should initially avoid writing code.</p><pre>cd ../neon-api-review</pre><p>Its first task can simply be:</p><pre>Study the authentication subsystem and current tests.</pre><pre>Do not modify anything yet.</pre><pre>Build a review checklist covering:</pre><pre>- correctness<br>- security<br>- API compatibility<br>- error handling<br>- test coverage<br>- concurrency<br>- maintainability<br>- unnecessary complexity</pre><pre>Wait for candidate branches to review.</pre><p>This agent becomes your synthetic code-review goblin.</p><p>Every team deserves one.</p><h3>Why Branches Alone Are Not Enough</h3><p>You might ask why we need worktrees at all.</p><p>Why not just create four branches and switch between them?</p><p>Because a branch is a Git concept.</p><p>A worktree is a filesystem concept.</p><p>You can create:</p><pre>git branch agent/refactor<br>git branch agent/tests<br>git branch agent/bughunt</pre><p>but you still only have one checked-out set of files.</p><p>You would need to constantly do this:</p><pre>git switch agent/refactor</pre><p>then:</p><pre>git switch agent/tests</pre><p>then:</p><pre>git switch agent/bughunt</pre><p>That works for one human doing tasks sequentially.</p><p>It does not work well when four processes need four simultaneously valid versions of the repository.</p><p>Worktrees turn branches into actual parallel workspaces.</p><p>That is the magic.</p><h3>The Agents Commit Their Work Independently</h3><p>Suppose the refactor agent finishes first.</p><p>Inside:</p><pre>neon-api-refactor/</pre><p>it creates a commit:</p><pre>git add .<br>git commit -m &quot;refactor authentication validation flow&quot;</pre><p>The branch now contains:</p><pre>agent/refactor</pre><p>Your main worktree remains untouched.</p><p>You can inspect the commit from the main repository:</p><pre>cd ../neon-api</pre><pre>git log agent/refactor --oneline</pre><p>Maybe you see:</p><pre>7fa41c2 refactor authentication validation flow</pre><p>Meanwhile the testing agent finishes:</p><pre>19c8ad1 add adversarial authentication tests</pre><p>The bug hunter finds two issues:</p><pre>8bc001a fix expired session acceptance<br>15e870c reject malformed bearer tokens</pre><p>Nothing has been merged yet.</p><p>That is important.</p><p>You now have candidate solutions, not one giant unreviewable AI-generated soup commit.</p><h3>Let the Tests Attack the Refactor</h3><p>Here is where this workflow becomes much more interesting than merely running several coding agents.</p><p>The outputs can attack each other.</p><p>Your testing branch contains new tests.</p><p>Your refactor branch contains a new implementation.</p><p>You want to know whether the implementation survives those tests.</p><p>Switch into the refactor worktree:</p><pre>cd ../neon-api-refactor</pre><p>Then cherry-pick the testing commit:</p><pre>git cherry-pick 19c8ad1</pre><p>Run the suite:</p><pre>pytest</pre><p>or:</p><pre>npm test</pre><p>or:</p><pre>cargo test</pre><p>or whatever ritual summons your project’s suffering.</p><p>Now the refactored implementation is being judged by tests written independently from the refactor.</p><p>That independence matters.</p><p>If the same agent writes both the code and the tests, it can unintentionally create tests that validate its own assumptions.</p><p>Humans do this too. We call it development.</p><p>An independent testing agent is more likely to ask questions the implementation agent never considered.</p><p>This is one of the strongest arguments for multi-agent coding.</p><p>You are not merely parallelizing labor.</p><p>You are parallelizing perspectives.</p><h3>Cross-Pollination Without Chaos</h3><p>Suppose the bug hunter discovered that malformed UTF-8 input causes an exception.</p><p>Its branch contains:</p><pre>15e870c reject malformed bearer tokens</pre><p>You can bring that commit into the refactor branch:</p><pre>git cherry-pick 15e870c</pre><p>Now run everything again:</p><pre>pytest</pre><p>Maybe the cherry-pick conflicts.</p><p>Good.</p><p>A merge conflict is not inherently bad. It means Git found two competing modifications to the same region and refused to hallucinate your intent.</p><p>Frankly, Git is already demonstrating better judgment than some AI coding agents.</p><p>Inspect:</p><pre>git status</pre><p>Resolve the conflict manually or ask the refactor agent:</p><pre>A cherry-picked bug fix conflicts with your refactor.</pre><pre>Resolve the conflict while preserving:</pre><pre>1. the refactored architecture<br>2. the malformed-token rejection behavior<br>3. compatibility with the test suite</pre><pre>Explain the resolution before committing it.</pre><p>This is vastly better than letting two agents modify one file simultaneously and discovering twenty minutes later that one silently overwrote the other.</p><h3>Turn the Reviewer Into an Adversarial Meta-Agent</h3><p>Once you have a candidate integrated branch, let the review agent examine it.</p><p>First update the review worktree.</p><pre>cd ../neon-api-review</pre><p>You can merge or cherry-pick the candidate changes.</p><p>For example:</p><pre>git merge agent/refactor</pre><p>Then tell the reviewer:</p><pre>Review the changes introduced by agent/refactor.</pre><pre>Do not assume the implementation is correct.</pre><pre>Inspect:</pre><pre>- the full diff<br>- new tests<br>- error paths<br>- changed behavior<br>- security implications<br>- duplicated code<br>- suspicious abstractions<br>- dead logic<br>- test gaps</pre><pre>Run the test suite.</pre><pre>Produce findings ranked as:</pre><pre>CRITICAL<br>HIGH<br>MEDIUM<br>LOW</pre><pre>For each finding, cite the relevant file and explain how to reproduce or verify it.</pre><p>Now the reviewer is not just another code generator.</p><p>It becomes a quality-control layer.</p><p>This is a subtle but important shift in how to use AI for programming.</p><p>The naive workflow is:</p><pre>PROMPT → CODE</pre><p>The stronger workflow is:</p><pre>PROMPT<br>   ↓<br>IMPLEMENTATION<br>   ↓<br>ADVERSARIAL TESTING<br>   ↓<br>BUG HUNTING<br>   ↓<br>REVIEW<br>   ↓<br>REPAIR<br>   ↓<br>TEST AGAIN</pre><p>And because each stage can happen inside its own worktree, the steps can overlap.</p><p>While the refactor agent is coding, the testing agent is generating attacks.</p><p>While those are happening, the bug hunter is reading the original implementation.</p><p>The reviewer can study architecture before any candidate code even arrives.</p><p>You have transformed one linear coding session into a small pipeline.</p><h3>Use a Branch Naming Convention Before Things Become Cursed</h3><p>Parallel agents generate branches quickly.</p><p>Do not call them:</p><pre>test<br>test2<br>test-new<br>claude-stuff<br>working<br>working-final<br>final2<br>final-final</pre><p>Civilizations have collapsed for less.</p><p>Use structured names:</p><pre>agent/refactor-auth<br>agent/test-auth<br>agent/bughunt-auth<br>agent/review-auth</pre><p>For more automation:</p><pre>agent/01-refactor-auth<br>agent/02-tests-auth<br>agent/03-bughunt-auth<br>agent/04-review-auth</pre><p>For multiple runs:</p><pre>agent/auth/refactor-v1<br>agent/auth/refactor-v2<br>agent/auth/tests-adversarial<br>agent/auth/security-review</pre><p>The exact convention matters less than having one.</p><p>You want to glance at:</p><pre>git branch</pre><p>and understand what the little silicon department is doing.</p><h3>Automate Worktree Creation</h3><p>Once you start using this pattern regularly, typing the setup commands gets boring.</p><p>Boring things belong in scripts.</p><p>Create:</p><pre>spawn-agents.sh</pre><p>with:</p><pre>#!/usr/bin/env bash</pre><pre>set -euo pipefail</pre><pre>PROJECT_ROOT=&quot;$(pwd)&quot;<br>PROJECT_NAME=&quot;$(basename &quot;$PROJECT_ROOT&quot;)&quot;<br>PARENT_DIR=&quot;$(dirname &quot;$PROJECT_ROOT&quot;)&quot;</pre><pre>TASK=&quot;${1:-task}&quot;</pre><pre>declare -A AGENTS=(<br>    [&quot;refactor&quot;]=&quot;agent/${TASK}-refactor&quot;<br>    [&quot;tests&quot;]=&quot;agent/${TASK}-tests&quot;<br>    [&quot;bughunt&quot;]=&quot;agent/${TASK}-bughunt&quot;<br>    [&quot;review&quot;]=&quot;agent/${TASK}-review&quot;<br>)</pre><pre>for ROLE in &quot;${!AGENTS[@]}&quot;; do<br>    BRANCH=&quot;${AGENTS[$ROLE]}&quot;<br>    WORKTREE=&quot;${PARENT_DIR}/${PROJECT_NAME}-${TASK}-${ROLE}&quot;</pre><pre>    echo &quot;Creating $ROLE worktree&quot;<br>    echo &quot;Branch:   $BRANCH&quot;<br>    echo &quot;Location: $WORKTREE&quot;</pre><pre>    git worktree add &quot;$WORKTREE&quot; -b &quot;$BRANCH&quot;<br>done</pre><pre>echo<br>echo &quot;Created worktrees:&quot;<br>git worktree list</pre><p>Make it executable:</p><pre>chmod +x spawn-agents.sh</pre><p>Run:</p><pre>./spawn-agents.sh auth</pre><p>You get:</p><pre>neon-api-auth-refactor/<br>neon-api-auth-tests/<br>neon-api-auth-bughunt/<br>neon-api-auth-review/</pre><p>with matching branches.</p><p>You could extend this script dramatically.</p><p>Generate agent instruction files:</p><pre>AGENT.md</pre><p>Copy environment templates.</p><p>Create role-specific prompts.</p><p>Launch terminal tabs.</p><p>Start tmux panes.</p><p>Run Claude Code in one directory and Codex in another.</p><p>Initialize log files.</p><p>Register PIDs.</p><p>Collect commit hashes.</p><p>At that point your Git repository starts resembling a small compiler farm operated by mildly caffeinated ghosts.</p><p>Which, to be fair, is a pretty good description of modern software development.</p><h3>Add a Shared Task Specification</h3><p>Filesystem isolation does not mean the agents should have zero shared context.</p><p>In fact, you want exactly the opposite.</p><p>They should share the same problem definition while working independently on the solution.</p><p>Create something like:</p><pre>TASK.md</pre><p>before spawning the worktrees.</p><p>Example:</p><pre># Authentication Hardening Task</pre><pre>## Goal</pre><pre>Improve reliability and security of token authentication.</pre><pre>## Constraints</pre><pre>- preserve public API compatibility<br>- do not change database schema<br>- Python 3.12+<br>- all existing tests must pass</pre><pre>## Known concerns</pre><pre>- session expiration logic<br>- malformed Authorization headers<br>- token decoding errors<br>- repeated validation logic</pre><pre>## Completion requirements</pre><pre>- tests passing<br>- no new lint failures<br>- changes reviewed<br>- behavior documented</pre><p>Commit it:</p><pre>git add TASK.md<br>git commit -m &quot;define authentication hardening task&quot;</pre><p>Then create your worktrees.</p><p>Every agent begins from the same written specification.</p><p>Now their disagreement is about implementation, not about what problem they were supposedly solving.</p><p>This tiny bit of discipline saves an absurd amount of nonsense.</p><h3>Do Not Let Every Agent Install Random Dependencies</h3><p>There is another subtle source of chaos.</p><p>Dependencies.</p><p>Agent A decides a 14-line helper function deserves a new package.</p><p>Agent B introduces another testing framework.</p><p>Agent C finds an obscure parsing library last updated during the Obama administration.</p><p>Agent D reviews the result and starts deleting all three.</p><p>You can avoid dependency inflation with explicit rules:</p><pre>Do not add production dependencies unless required.</pre><pre>If you believe a new dependency is necessary:</pre><pre>1. explain why existing dependencies cannot solve the problem<br>2. document maintenance and security implications<br>3. isolate the dependency change in its own commit</pre><p>This makes cross-agent review much easier.</p><p>You want agents producing inspectable decisions, not just functioning output.</p><h3>Commit Granularity Becomes Extremely Important</h3><p>AI agents love giant commits if you let them.</p><p>Do not.</p><p>Ask for logical commits.</p><p>Bad:</p><pre>4d782c1 improve auth</pre><p>which changes:</p><pre>27 files<br>1,934 insertions<br>1,102 deletions</pre><p>Wonderful. A synthetic coworker has delivered an archaeological site.</p><p>Better:</p><pre>ec120af centralize bearer token parsing<br>88d019a reject malformed authorization headers<br>221cc41 add expired-session regression tests<br>7b90133 remove duplicated session validation</pre><p>Now you can cherry-pick individual ideas:</p><pre>git cherry-pick 221cc41</pre><p>reject others:</p><pre>git reset --hard HEAD~1</pre><p>or compare approaches:</p><pre>git show ec120af</pre><p>Small commits turn agent output into modular evidence.</p><p>This is one of the strongest habits you can enforce.</p><h3>Compare Competing Agents Instead of Trusting the First One</h3><p>You are not limited to one refactor agent.</p><p>Create two:</p><pre>git worktree add ../neon-api-refactor-a -b agent/refactor-a<br>git worktree add ../neon-api-refactor-b -b agent/refactor-b</pre><p>Give both the same problem.</p><p>Perhaps Agent A prefers minimal modification.</p><p>Agent B redesigns the internal architecture.</p><p>Then compare:</p><pre>git diff main..agent/refactor-a</pre><p>against:</p><pre>git diff main..agent/refactor-b</pre><p>Run the same adversarial tests against both branches.</p><p>Now instead of asking:</p><blockquote><em>Did the AI produce good code?</em></blockquote><p>you are asking:</p><blockquote><em>Which independent solution performs better under the same evaluation?</em></blockquote><p>That is a much stronger engineering question.</p><p>You can even send both diffs to the review agent and ask:</p><pre>Compare agent/refactor-a and agent/refactor-b.</pre><pre>Evaluate them according to:</pre><pre>- correctness<br>- simplicity<br>- regression risk<br>- test performance<br>- security<br>- maintainability</pre><pre>Recommend one approach or propose a minimal synthesis of both.</pre><p>The AI is no longer merely generating code.</p><p>It is participating in a small evolutionary process.</p><p>Multiple candidates appear.</p><p>Tests apply selection pressure.</p><p>Review filters weak designs.</p><p>The surviving changes move toward main.</p><p>Darwin, but with more YAML.</p><h3>The Integration Branch Is Your Airlock</h3><p>Do not necessarily merge agent branches directly into main.</p><p>Create an integration branch:</p><pre>git switch -c integration/auth-hardening</pre><p>or give it its own worktree:</p><pre>git worktree add ../neon-api-integration -b integration/auth-hardening</pre><p>This becomes your assembly zone.</p><p>Cherry-pick the pieces you want:</p><pre>git cherry-pick ec120af<br>git cherry-pick 221cc41<br>git cherry-pick 88d019a</pre><p>Run the complete suite:</p><pre>pytest</pre><p>Run static analysis:</p><pre>ruff check .</pre><p>Type checking:</p><pre>mypy src</pre><p>Security tools if relevant:</p><pre>bandit -r src</pre><p>Then hand the integration result to the review agent.</p><p>Your final architecture becomes:</p><pre>main<br>                     │<br>              task baseline<br>                     │<br>     ┌───────────────┼────────────────┐<br>     │               │                │<br> refactor           tests           bughunt<br>     │               │                │<br>     └───────────┬───┴───────────────┘<br>                 │<br>            integration<br>                 │<br>               review<br>                 │<br>             final fixes<br>                 │<br>                main</pre><p>This is dramatically safer than allowing a swarm of agents to directly mutate your primary branch.</p><p>The integration worktree is an airlock.</p><p>Nothing enters production without passing through it.</p><h3>Clean Up When the Swarm Is Done</h3><p>Worktrees are cheap, but abandoned worktrees accumulate like cables behind a desk.</p><p>List them:</p><pre>git worktree list</pre><p>Remove one:</p><pre>git worktree remove ../neon-api-tests</pre><p>Remove another:</p><pre>git worktree remove ../neon-api-bughunt</pre><p>After branches are safely merged, delete them:</p><pre>git branch -d agent/tests<br>git branch -d agent/bughunt</pre><p>Prune stale metadata:</p><pre>git worktree prune</pre><p>A completed session might end with:</p><pre>git worktree remove ../neon-api-refactor<br>git worktree remove ../neon-api-tests<br>git worktree remove ../neon-api-bughunt<br>git worktree remove ../neon-api-review</pre><pre>git worktree prune</pre><p>Your filesystem returns to normal.</p><p>The robot engineering firm dissolves quietly before anyone asks about payroll.</p><h3>Where This Gets Really Interesting</h3><p>Git worktrees solve a very specific problem: multiple coding agents need isolated mutable environments while sharing repository history.</p><p>But once you have that primitive, you can build much stranger systems around it.</p><p>A scheduler could create one worktree per hypothesis.</p><pre>agent/fix-parser-state<br>agent/fix-buffer-boundary<br>agent/fix-stream-reset</pre><p>Each agent attempts a different diagnosis.</p><p>Tests score them.</p><p>A controller records:</p><pre>branch<br>commit<br>tests passed<br>tests failed<br>runtime<br>files changed<br>review score</pre><p>Then another model ranks the candidates.</p><p>You could create agents dedicated to different optimization targets:</p><pre>agent/minimal-patch<br>agent/performance<br>agent/readability<br>agent/security<br>agent/backward-compatibility</pre><p>Same bug.</p><p>Different priorities.</p><p>You can also deliberately separate creation from criticism:</p><pre>Builder Agent<br>    ↓<br>Test Agent<br>    ↓<br>Security Agent<br>    ↓<br>Reviewer Agent<br>    ↓<br>Repair Agent</pre><p>Each gets its own worktree when modification is necessary.</p><p>This begins to resemble CI, except some stages can reason about failures and generate new candidate patches.</p><p>The interesting future of AI coding probably does not look like one gigantic agent with unlimited filesystem access being told:</p><blockquote><em>Make the app good</em></blockquote><p>That is merely automation with delusions of management.</p><p>A more reliable pattern is a collection of narrowly scoped agents operating inside controlled environments, producing commits that can be tested, compared, rejected, merged, and audited.</p><p>Git turns out to be weirdly perfect infrastructure for this.</p><p>It already understands branches.</p><p>It already understands history.</p><p>It already understands diffs.</p><p>It already understands merging.</p><p>It already gives us immutable-ish snapshots through commits.</p><p>And worktrees provide the missing piece: multiple simultaneous physical environments.</p><p>We do not need to invent some cosmic blockchain-of-agent-thoughts orchestration protocol.</p><p>Sometimes the killer multi-agent infrastructure is a Git command that has been sitting there quietly while everyone else was busy building dashboards.</p><h3>The Practical Pattern</h3><p>The entire strategy can be reduced to a simple operating model:</p><pre>ONE PROBLEM<br>    ↓<br>ONE SHARED SPEC<br>    ↓<br>MULTIPLE WORKTREES<br>    ↓<br>MULTIPLE SPECIALIZED AGENTS<br>    ↓<br>SMALL COMMITS<br>    ↓<br>CROSS-TESTING<br>    ↓<br>INTEGRATION BRANCH<br>    ↓<br>ADVERSARIAL REVIEW<br>    ↓<br>MAIN</pre><p>The important part is not simply running more models.</p><p>More models can create more garbage faster.</p><p>The advantage comes from giving those models structural independence and making their outputs collide through Git rather than through uncontrolled filesystem edits.</p><p>One agent builds.</p><p>One attacks.</p><p>One searches for edge cases.</p><p>One reviews.</p><p>Maybe two implementations compete.</p><p>Maybe a fifth agent measures performance.</p><p>Maybe a sixth is instructed to reject every unnecessary abstraction because someone has to stop the first five from inventing AbstractAuthenticationStrategyFactoryProvider.</p><p>You decide how elaborate the swarm becomes.</p><p>Git worktrees give each participant a room of its own.</p><p>That one architectural choice turns parallel AI coding from a demo trick into something you can actually reason about.</p><p>And that is the larger lesson here.</p><p>The next leap in AI-assisted programming is not necessarily a smarter autocomplete box.</p><p>It is orchestration.</p><p>Isolation.</p><p>Independent hypotheses.</p><p>Adversarial testing.</p><p>Explicit stopping conditions.</p><p>Reproducible environments.</p><p>Auditable commits.</p><p>The model is only one component.</p><p>The workflow around the model decides whether you have built an engineering system or merely hired four extremely fast interns and seated them at the same desk.</p><p>Use worktrees.</p><p>Give each agent its own branch.</p><p>Make them disagree productively.</p><p>Then let Git sort out the paperwork.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05c8117b74f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CH341A Firmware Dumping Guide for Beginners]]></title>
            <link>https://medium.com/@chainc0der/ch341a-firmware-dumping-guide-for-beginners-acf58894189f?source=rss-7f8489b3bc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/acf58894189f</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[hardware-hacking]]></category>
            <dc:creator><![CDATA[[chaincoder.]]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 16:51:02 GMT</pubDate>
            <atom:updated>2026-08-20T16:51:02.638Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>How to read SPI flash safely with a cheap USB programmer, verify your dump, and understand what the board is actually doing</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jXRVxD8jMK74898A" /><figcaption>Photo by <a href="https://unsplash.com/@brechtcorbeel?utm_source=medium&amp;utm_medium=referral">Brecht Corbeel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The first time you clip a CH341A onto an eight-pin flash chip, there is usually a moment where the whole setup looks too cheap to be doing anything important. A plastic USB programmer, a slightly crooked SOIC8 clip, a ribbon cable that feels like it came out of a bargain-bin electronics kit, and somewhere underneath all of that a router, laptop motherboard, DVR, access point, embedded controller, or nameless board from eBay that still boots perfectly well. Then flashrom identifies the chip, you run a read command, and a few seconds later the contents of that device are sitting on your computer as a binary file.</p><p>That transition is what makes firmware dumping interesting. You stop treating firmware as something that comes from a manufacturer’s support page and start treating it as something physically stored on the board, addressable byte by byte, with electrical requirements and failure modes that have nothing to do with whatever friendly web interface the device normally presents. The CH341A is useful because it makes that boundary unusually easy to cross, but the programmer itself is only the bridge. The real subject is the flash chip.</p><p>For a beginner, this is also one of the better places to start learning hardware-level firmware work because the concepts are compact enough to understand without reducing them to magic. You have a serial memory chip, usually SPI flash. You have power, ground, clock, chip select, data in, data out, and a couple of control pins. The programmer generates the electrical conversation, the flash chip answers, and your computer records the result. When it fails, which it often does the first few times, the failure usually tells you something useful about how the board is actually wired.</p><h3>What the CH341A is really doing</h3><p>The CH341A is a low-cost USB interface chip that appears in countless inexpensive programmers sold as BIOS programmers, EEPROM programmers, SPI programmers, or simply “CH341A USB programmers.” Many kits include the programmer board itself, an SOIC8 test clip, an eight-wire ribbon cable, and one or more small adapter boards for connecting different packages.</p><p>The reason these programmers became so common is not that the CH341A is particularly glamorous hardware. It is because an enormous number of devices use small serial flash chips to store the code and configuration they need to boot.</p><p>If you open a router, motherboard, network appliance, DVR, thin client, printer, industrial controller, or embedded Linux device, there is a good chance you will eventually find a small eight-pin chip carrying markings from Winbond, Macronix, GigaDevice, ISSI, Micron, EON, or another flash manufacturer.</p><p>A marking might look like:</p><pre>W25Q64FV<br>W25Q128JV<br>MX25L6406E<br>GD25Q32</pre><p>Those markings matter more than the color of the programmer or whatever description the seller put on the listing. Before you connect anything, identify the chip and look up its datasheet. That tells you the operating voltage, capacity, pinout, command set, and enough electrical information to prevent several very avoidable mistakes.</p><p>A W25Q64, for example, is generally a 64-megabit flash device. Because eight bits make one byte, 64 megabits works out to 8 megabytes. If you read that chip successfully, an 8 MB dump is therefore exactly what you should expect.</p><p>That simple calculation becomes one of your first sanity checks. If the package says you have an 8 MB device but your resulting file is 1 MB, 16 MB, or some bizarre size you cannot explain, do not immediately start analyzing it. First ask whether you actually read what you think you read.</p><h3>Voltage comes before software</h3><p>This is the part that deserves more attention than it usually gets in beginner tutorials.</p><p>An eight-pin flash chip is not automatically a 3.3-volt device just because it looks like every other eight-pin flash chip you have seen online. Many common SPI flash parts do operate around 3.3 volts, but 1.8-volt parts are also common, especially in newer hardware, and connecting the wrong voltage is not something you should treat as an experiment.</p><p>Read the chip marking first, then verify the voltage in the datasheet.</p><p>If the flash device requires 1.8 volts, use a proper 1.8-volt adapter designed for the programmer. Do not attach a standard CH341A setup and hope the chip tolerates it long enough to get a dump.</p><p>The various inexpensive CH341A programmer boards also deserve some skepticism of their own. There are multiple revisions in circulation, particularly the familiar black and green boards, and not all of them behave identically. Some older or cheaper designs have generated plenty of discussion because the voltage presented by the board and the voltage seen on its signal lines are not always as reassuring as the silk-screen labels suggest.</p><p>This is one of those situations where a multimeter stops being optional hobbyist decoration and becomes part of the process. If you are unsure what your programmer is actually supplying, measure it before connecting the target. A thirty-second voltage check is much easier to recover from than an electrically damaged flash chip.</p><h3>Finding pin 1 without guessing</h3><p>SOIC8 flash devices use a numbered pin arrangement, and orientation matters because rotating the clip by 180 degrees places power, ground, and signal lines where they absolutely do not belong.</p><p>The package usually identifies pin 1 with a small dot, notch, recessed circle, bevel, or other molded marking. The datasheet will show the official orientation.</p><p>A typical SPI flash layout resembles this:</p><pre>_________<br>    /CS  1 |•        | 8  VCC<br>   MISO  2 |         | 7  /HOLD or /RESET<br>    /WP  3 |         | 6  CLK<br>    GND  4 |_________| 5  MOSI</pre><p>Depending on the specific chip, the pin names may vary slightly. What matters is understanding the roles.</p><p>VCC powers the chip. GND provides the electrical reference. CLK carries the serial clock generated by the programmer. CS, or chip select, tells the flash device when it is being addressed. MOSI carries commands and data from the programmer toward the flash chip, while MISO carries data back.</p><p>The remaining pins are commonly write-protect and hold or reset functions.</p><p>Many SOIC8 clip cables use a red conductor to indicate pin 1, but the color of a ribbon cable is not documentation. Trace the adapter, inspect the markings, and make sure the programmer socket orientation matches the clip orientation before applying power.</p><p>This is especially important with cheap kits because adapters are not always labeled as clearly as they should be, and occasionally the most dangerous assumption is simply that the seller wired everything in the way you expected.</p><p>Before I connect USB power, I want five things settled:</p><ul><li>the exact flash chip and its required operating voltage</li><li>the location of pin 1 on both the chip and the clip assembly</li><li>the target device disconnected from its normal external power source</li><li>the SOIC8 clip seated cleanly across all eight pins</li><li>enough storage and patience to make multiple dumps instead of trusting the first one</li></ul><p>That last point is one of the habits worth learning immediately. A successful command does not necessarily mean a trustworthy dump.</p><h3>Why the target board usually stays unpowered</h3><p>In-circuit dumping sounds simpler than it really is because the phrase suggests you are merely connecting to one flash chip while leaving it soldered in place. Electrically, however, the flash chip is still part of the rest of the board.</p><p>Its power rail may be connected to the processor, regulators, pull-up resistors, other memory devices, logic gates, or peripheral chips. Its SPI lines may run directly into a CPU or microcontroller. When the CH341A supplies voltage to the flash chip, some of that voltage can travel through the surrounding circuit in ways you did not intend.</p><p>This is why a target that appears “off” can still behave strangely while you are programming it.</p><p>You might see an LED faintly illuminate. A processor may partially wake. A regulator may be back-fed from its output side. The CPU may begin influencing one or more SPI lines. The programmer may suddenly have to drive a bus that another device on the board is also trying to control.</p><p>At that point, the problem is no longer just software.</p><p>For a normal beginner read, keep the device disconnected from its original power supply unless you have specifically examined the circuit and know how the flash is powered. Avoid casually powering the board from its regular supply while simultaneously supplying power from the CH341A.</p><p>Two power sources feeding the same rail without understanding the board topology can create exactly the kind of problem that does not announce itself until something stops working.</p><h3>Installing flashrom</h3><p>On Linux, flashrom is one of the most useful tools for this job because it supports the CH341A SPI programmer directly and gives you enough visibility into what it detects to catch obvious mistakes early.</p><p>On Arch Linux and related systems:</p><pre>sudo pacman -S flashrom</pre><p>On Debian or Ubuntu:</p><pre>sudo apt install flashrom</pre><p>After connecting the CH341A to USB, confirm that the operating system sees it:</p><pre>lsusb</pre><p>You should find an entry corresponding to the CH341 device.</p><p>At this stage I still would not jump directly into reading. First, ask flashrom to probe the programmer and identify the attached flash chip:</p><pre>sudo flashrom -p ch341a_spi</pre><p>A healthy probe may produce output resembling:</p><pre>Found Winbond flash chip &quot;W25Q64.V&quot; (8192 kB, SPI) on ch341a_spi.</pre><p>Read that line carefully rather than treating it as ceremonial terminal output.</p><p>Does the manufacturer make sense?</p><p>Does the detected family resemble the marking printed on the package?</p><p>Does the capacity match what you calculated from the datasheet?</p><p>If the chip physically says W25Q128 and flashrom confidently tells you it found a tiny unrelated device, you have learned something useful: the setup is not ready for a dump.</p><p>Maybe the clip is not seated properly. Maybe one leg is not contacting. Maybe the target circuitry is interfering with the bus. Maybe the chip is not supported cleanly. Whatever the cause, fix the disagreement before moving forward.</p><h3>Taking the first dump</h3><p>Once the chip identification makes sense, reading the flash is wonderfully uneventful:</p><pre>sudo flashrom -p ch341a_spi -r dump-01.bin</pre><p>The -r option tells flashrom to read the contents into a file.</p><p>When it completes, check the size:</p><pre>ls -lh dump-01.bin</pre><p>If you are reading a W25Q64, an output around 8 MB is expected. A W25Q128 should give you roughly 16 MB.</p><p>This is where a lot of guides move directly into Binwalk, strings, filesystem extraction, and all the exciting stuff.</p><p>I would not.</p><p>Read it again.</p><pre>sudo flashrom -p ch341a_spi -r dump-02.bin</pre><p>Then hash both files:</p><pre>sha256sum dump-01.bin dump-02.bin</pre><p>If both files produce exactly the same SHA-256 digest, you now have much stronger evidence that the read was stable.</p><p>You can also compare the files directly:</p><pre>cmp dump-01.bin dump-02.bin</pre><p>If cmp produces no output, the two files are identical byte for byte.</p><p>This little verification step is one of the most valuable habits in firmware work because bad SOIC8 connections are often subtle. The programmer may successfully return a file even when one contact is marginal, the bus is noisy, or another chip is disturbing communication.</p><p>If two independent reads produce different hashes, do not average them, choose the one that looks better, or begin analyzing whichever one contains more recognizable strings. Something is still wrong with the physical read.</p><p>Fix that first.</p><h3>When flashrom detects nothing</h3><p>A failed probe is usually less mysterious than it initially looks.</p><p>The first suspect should be the clip.</p><p>Cheap SOIC8 clips have a particular talent for appearing perfectly seated while one spring contact is floating just above the chip leg. Nearby resistors or capacitors can prevent one side of the clip from descending completely. Conformal coating can interfere. Oxidation can interfere. Residue around the legs can interfere. Some packages simply expose so little metal that the clip has almost nothing to grab.</p><p>Keep the programmer disconnected from USB while repositioning the clip, then inspect it from the side rather than only from above. You want the jaws aligned with the actual metal legs, not resting comfortably on the plastic package.</p><p>Then reconnect and probe again:</p><pre>sudo flashrom -p ch341a_spi</pre><p>This process can become strangely physical. You move the clip less than a millimeter, reconnect, and suddenly the chip appears correctly. Move it again and it disappears.</p><p>That is not necessarily flaky software.</p><p>That is what marginal electrical contact looks like.</p><p>If repositioning does not help, verify continuity through the cable and adapter with a multimeter. Cheap ribbon cables and clip assemblies can fail internally, especially after repeated bending around the clip.</p><h3>When the dump is full of FF</h3><p>Suppose the chip is detected and the read completes successfully. Before trusting the resulting file, inspect a small region:</p><pre>xxd -l 256 dump-01.bin</pre><p>You may see data similar to:</p><pre>00000000: 2705 1956 552d 426f 6f74 0000 0000 0000<br>00000010: 0010 0000 3412 a84f 2000 0000 0400 0000</pre><p>Or perhaps you see:</p><pre>00000000: ffff ffff ffff ffff ffff ffff ffff ffff<br>00000010: ffff ffff ffff ffff ffff ffff ffff ffff<br>00000020: ffff ffff ffff ffff ffff ffff ffff ffff</pre><p>Do not panic merely because you encounter FF. Erased NOR flash commonly reads as FF, so large blank sections can be completely legitimate.</p><p>What becomes suspicious is an entire firmware image consisting almost exclusively of FF, or similarly an image that is nothing but 00.</p><p>A functioning embedded device normally contains enough structure to produce variation. There may be executable code, filesystem blocks, compression streams, text strings, bootloader structures, checksums, configuration data, partition tables, calibration values, or vendor-specific headers.</p><p>The exact appearance varies wildly, but an entirely featureless multi-megabyte image deserves investigation.</p><p>At that point, return to the physical layer. Check the clip, confirm the detected chip again, and compare several reads.</p><h3>Preserve the originals before exploring them</h3><p>Once I have at least two matching dumps, I separate preservation from analysis.</p><p>For example:</p><pre>mkdir analysis</pre><pre>cp dump-01.bin analysis/firmware.bin</pre><pre>chmod a-w dump-01.bin dump-02.bin</pre><p>You can also create a hash manifest:</p><pre>sha256sum dump-01.bin dump-02.bin &gt; SHA256SUMS.txt</pre><p>For anything important, I prefer filenames that contain enough information to make sense months later:</p><pre>router-w25q128-original-2026-08-20-a.bin<br>router-w25q128-original-2026-08-20-b.bin</pre><p>Firmware projects accumulate files quickly. dump.bin, dump2.bin, fixed.bin, newfixed.bin, and final-final-good.bin are funny until you are trying to remember which one came directly from the untouched chip.</p><p>Keep the raw captures boring and immutable.</p><p>Do experiments on copies.</p><h3>Looking inside the image</h3><p>Now the hardware part begins to fall away and the firmware itself takes over.</p><p>Start with something simple:</p><pre>file analysis/firmware.bin</pre><p>Do not be disappointed if Linux responds with:</p><pre>data</pre><p>A raw flash image is not necessarily a self-describing file format. It may contain several different regions placed at fixed offsets rather than one neat container that file understands.</p><p>Strings are often more revealing:</p><pre>strings -a analysis/firmware.bin | less</pre><p>Depending on the device, you might encounter names such as:</p><pre>U-Boot<br>BusyBox<br>Linux version<br>squashfs<br>factory<br>board_id<br>upgrade<br>recovery<br>httpd</pre><p>You may find web interface paths, boot messages, debug text, manufacturer names, partition labels, internal product codenames, or default configuration values.</p><p>Sometimes you find almost nothing readable at all.</p><p>That does not automatically mean the dump is bad. Large portions of firmware may be compressed, encrypted, encoded, or stored in structures that do not contain much plain ASCII text.</p><p>The absence of obvious strings is information too.</p><h3>Let Binwalk give the binary some geography</h3><p>Binwalk is useful because a flash dump that initially looks like one undifferentiated block often contains several recognizable components.</p><p>Run:</p><pre>binwalk analysis/firmware.bin</pre><p>A result might resemble:</p><pre>DECIMAL       HEXADECIMAL     DESCRIPTION<br>-------------------------------------------------------<br>65536         0x10000         U-Boot<br>262144        0x40000         Linux kernel<br>1835008       0x1C0000        Squashfs filesystem</pre><p>Those exact offsets are only examples, but the important change is conceptual.</p><p>The binary now has geography.</p><p>Perhaps the bootloader lives near the beginning. A kernel appears farther in. A SquashFS filesystem occupies the largest region. Configuration or calibration information may be stored near the end of the chip.</p><p>You have stopped looking at eight million anonymous bytes and started looking at a storage layout.</p><p>Binwalk signatures should still be treated as leads rather than unquestionable facts. Signature scanners can produce false positives, particularly inside compressed or high-entropy data. If Binwalk claims it has found something interesting, verify that finding with another tool or inspect the surrounding bytes before building an entire theory around it.</p><p>The same discipline that mattered at the hardware layer applies here too.</p><p>Verification first.</p><p>Interpretation second.</p><h3>Why in-circuit reads sometimes become unstable</h3><p>This is the part of the problem that becomes much more interesting once you understand what the programmer is physically doing.</p><p>Imagine the flash chip is soldered beside a processor and connected directly to that processor over SPI. Under normal operation, the CPU controls chip select, generates the clock, sends commands over MOSI, and receives data over MISO.</p><p>Now you unplug the device and connect the CH341A.</p><p>The processor has not vanished from the circuit.</p><p>Its pins are still physically connected to those same traces.</p><p>If the programmer powers the flash rail, current may also travel into other parts of the board. Depending on the design, the processor can become partially powered through the supply network or even through protection structures connected to its I/O pins.</p><p>That can create a beautifully confusing failure mode where the CH341A appears to work, but the SPI bus is being loaded or disturbed by circuitry you never intended to power.</p><p>Typical symptoms include a chip that is detected only occasionally, inconsistent identification, successful reads with different hashes, reads that stop partway through, or MISO data that seems implausibly repetitive.</p><p>Running the command again twenty times will not solve an electrical contention problem.</p><p>This is where a logic analyzer starts becoming much more than another gadget on the desk.</p><p>If you monitor chip select, clock, MOSI, and MISO while flashrom performs a read, you can inspect the conversation directly. You can see whether clock pulses are clean, whether chip select is behaving correctly, whether commands leave the programmer, and whether sensible data is returning.</p><p>You are no longer asking, “Why does flashrom hate this board?”</p><p>You are asking what the bus itself is doing.</p><p>That shift matters.</p><h3>When the SOIC clip is no longer enough</h3><p>Some boards simply do not cooperate with in-circuit reading.</p><p>The surrounding circuitry may load the bus too heavily. The processor may interfere. Another device may share the SPI lines. The flash package may be inaccessible. The board may use resistors or buffers that complicate the connection. The clip may physically refuse to stay attached.</p><p>At that point, you have moved beyond the easiest form of CH341A dumping.</p><p>Depending on the board, an experienced technician might isolate particular signal lines, hold the processor in reset, remove a resistor, lift a chip-select pin, or desolder the flash device entirely and read it outside the circuit.</p><p>Those techniques can produce extremely reliable reads because they remove the target board from the electrical conversation, but they also increase the chance of physical damage. Lifting pads, tearing traces, overheating packages, and losing tiny passive components around the chip are all very real ways to turn a firmware project into a repair project.</p><p>For a beginner, the important lesson is simply recognizing the boundary.</p><p>If several carefully performed in-circuit reads continue producing inconsistent data, stop assuming the next software command will fix it. The board may be telling you that the problem is electrical.</p><h3>Do not turn a dumping exercise into a writing exercise</h3><p>flashrom can do much more than read.</p><p>It can erase flash.</p><p>It can write flash.</p><p>Those capabilities are useful, but they belong later.</p><p>Reading a chip is comparatively forgiving because a failed read usually leaves the original contents untouched. Writing is different. An incorrect image, interrupted operation, wrong chip selection, electrical glitch, or mistaken assumption about which regions should be preserved can leave the device unable to boot.</p><p>Some flash images also contain device-specific information that you should not casually replace, including calibration data, MAC addresses, serial information, factory configuration, cryptographic material, or board-specific settings.</p><p>If the goal today is firmware dumping, let the goal remain firmware dumping.</p><p>Get two or three matching reads.</p><p>Hash them.</p><p>Preserve them.</p><p>Analyze copies.</p><p>There is no prize for discovering the write flag five minutes after discovering the read flag.</p><h3>What you actually extracted</h3><p>A raw flash image is often much more interesting than a firmware update downloaded from the manufacturer’s website because the two files answer different questions.</p><p>The vendor update package answers, “What did the manufacturer intend to distribute as an update?”</p><p>The physical flash chip answers, “What is actually stored on this particular device?”</p><p>That distinction can expose material that never appears in a public update package. A bootloader may live in a protected region that normal updates never touch. Factory calibration data may occupy a tiny partition near the end of flash. A recovery image may be stored alongside the main operating system. Configuration defaults or manufacturing information may have been written once at the factory and carried forward across every software update afterward.</p><p>You may also find something completely mundane, which is often more revealing than the dramatic discoveries people imagine when they hear the phrase “firmware extraction.”</p><p>An old product codename buried in a boot string.</p><p>A filesystem that clearly belongs to an earlier hardware revision.</p><p>A recovery partition twice the size you expected.</p><p>A debug interface referenced by software even though the final enclosure never exposed the connector.</p><p>A second kernel.</p><p>A half-empty flash chip.</p><p>These details are where the abstraction starts breaking apart.</p><p>The device is no longer a sealed appliance with a model number printed on the bottom. It becomes a collection of design decisions made by engineers who had limited flash space, manufacturing requirements, recovery procedures, compatibility problems, deadlines, and probably at least one bug they were very tired of looking at.</p><p>The CH341A is only what gets you through the door.</p><p>After that, the board starts explaining itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acf58894189f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In-Circuit Firmware Dumping vs Desoldering the Chip]]></title>
            <link>https://medium.com/@chainc0der/in-circuit-firmware-dumping-vs-desoldering-the-chip-e75f3bbbe486?source=rss-7f8489b3bc79------2</link>
            <guid isPermaLink="false">https://medium.com/p/e75f3bbbe486</guid>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[hardware-hacking]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[[chaincoder.]]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 16:18:19 GMT</pubDate>
            <atom:updated>2026-08-20T16:18:19.010Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Bus contention, backfeeding, bad reads, and the point where hot air becomes the conservative option.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KPHqqsqZnStZi8fu" /><figcaption>Photo by <a href="https://unsplash.com/@anoofc?utm_source=medium&amp;utm_medium=referral">ANOOF C</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The SOIC clip was seated perfectly.</p><p>At least it looked perfect.</p><p>Eight little contacts gripping the flash package, programmer detected, 3.3 volts where 3.3 volts belonged, ground continuity clean. The first read completed without complaint. Eight megabytes landed on disk.</p><p>I read it again.</p><p>Different hash.</p><p>Read it a third time.</p><p>Different again.</p><p>That is the moment in-circuit firmware dumping stops feeling like the elegant option.</p><p>Nothing is visibly wrong. The chip is still attached to the board. No lifted pads. No hot air. No flux smoke hanging over the bench. The device has not been disassembled any further than necessary.</p><p>And yet the board is quietly participating in the read.</p><p>That is the part people underestimate.</p><p>A firmware chip soldered to a PCB is not just a memory chip. It is a memory chip embedded in an electrical argument.</p><h3>The Attractive Option</h3><p>In-circuit dumping sounds almost too clean.</p><p>Find the SPI flash.</p><p>Identify pin 1.</p><p>Attach a clip.</p><p>Connect a programmer.</p><p>Read.</p><p>Done.</p><p>When it works, it is fantastic.</p><p>I would rather take a clean in-circuit dump than remove a chip almost every time. The package stays where the manufacturer put it. Pads stay intact. Orientation stays obvious. You avoid repeated thermal stress, accidental bridges, damaged solder mask, missing 0402 components, and the particular humiliation of watching an eight-pin flash chip launch itself into another dimension when the tweezers slip.</p><p>There is also something satisfying about extracting an entire firmware image while barely disturbing the machine.</p><p>It feels surgical.</p><p>The problem is that a clip touching a chip does not mean the programmer owns the chip.</p><p>The rest of the board is still there.</p><p>The CPU is still connected.</p><p>Pull-ups are still connected.</p><p>Regulators are still connected.</p><p>Other peripherals may share the bus.</p><p>Protection circuitry may exist between your programmer and the package.</p><p>Power can travel in directions the board designer never expected because you are injecting voltage through a programming header or directly into the memory rail.</p><p>The chip may be sitting still, but electrically the rest of the device has not disappeared.</p><h3>Bus Ownership Is the Real Problem</h3><p>Most unreliable in-circuit reads are not mysterious.</p><p>Two things are trying to control the same lines.</p><p>SPI flash commonly gives you clock, chip select, MOSI and MISO, plus power, ground, and sometimes HOLD or write-protect behavior depending on the package and design.</p><p>Your programmer assumes it is talking directly to the flash.</p><p>The motherboard may disagree.</p><p>A processor attached to those same lines can load them even while the device appears powered off. Protection diodes inside ICs can create strange backfeeding paths. A regulator can clamp a rail. A pull-up can be stronger than expected. Another peripheral can refuse to remain electrically invisible.</p><p>You see this as garbage.</p><p>Sometimes obvious garbage.</p><p>Sometimes worse.</p><p>Plausible garbage.</p><p>A read can complete successfully and still be wrong.</p><p>That is why a single completed dump means very little to me.</p><p>The useful signal is repeatability.</p><p>I want multiple reads.</p><p>I want matching hashes.</p><p>I want recognizable structure where recognizable structure should exist.</p><p>Firmware signatures. Padding. Partition boundaries. Filesystem fragments. Bootloader strings. Repeating erased regions that actually repeat.</p><p>If three independent reads disagree, I do not start reverse engineering the firmware.</p><p>I start reverse engineering the electrical situation.</p><h3>The Board Is Not Actually Off</h3><p>This catches people constantly.</p><p>You disconnect the battery or unplug the device and assume the system is inert.</p><p>Then you apply 3.3 volts from an external programmer.</p><p>An LED flickers.</p><p>Something gets warm.</p><p>A regulator wakes halfway up.</p><p>Congratulations. You have accidentally invented a new power state.</p><p>Current enters the flash VCC rail, travels through connected circuitry, and starts partially energizing things elsewhere on the board.</p><p>Not enough to boot normally.</p><p>Enough to become annoying.</p><p>This half-powered condition can be uglier than simply powering the target properly because logic levels stop being predictable. A controller may wake just far enough to interfere with the memory bus. Rails that normally rise together now come up in the wrong order.</p><p>I have learned to treat unexpected LED activity during an external flash read as information.</p><p>The board is telling you that your supposedly isolated memory rail is not isolated.</p><p>Listen to it.</p><p>Before pushing harder, the three things I care about are:</p><ul><li>verify the flash voltage before attaching the programmer</li><li>check whether programmer power is feeding the rest of the board</li><li>perform repeated reads and compare hashes before trusting anything</li></ul><p>That is the entire list.</p><p>Everything else depends on what the board does next.</p><h3>Sometimes Reset Solves Everything</h3><p>There is a middle ground between clipping onto the chip and removing it.</p><p>Stop the processor.</p><p>A board whose main controller is held in reset is often dramatically easier to read because the device responsible for fighting your programmer has been forced out of the conversation.</p><p>Sometimes the reset line is exposed.</p><p>Sometimes there is a test pad.</p><p>Sometimes you discover it only by following traces or checking the controller documentation.</p><p>Other boards make this harder.</p><p>A processor may still electrically load pins while held in reset. A secondary controller may share the bus. Some boards contain series resistors specifically intended to isolate sections of the SPI path, which can help or complicate the situation depending on where you attach.</p><p>This is where a cheap logic analyzer earns its space on the bench.</p><p>Do not guess whether the bus is quiet.</p><p>Watch it.</p><p>If clock or chip-select activity appears when you expected silence, the board is doing something.</p><p>That tiny burst of activity can explain an hour of inconsistent dumps.</p><h3>The Clip Is Also Lying to You</h3><p>Not every failure comes from the target.</p><p>SOIC clips are remarkably good at looking connected while making mediocre contact.</p><p>You attach one.</p><p>The jaws feel secure.</p><p>Seven pins touch correctly.</p><p>One does not.</p><p>Or one pin makes contact until the cable moves two millimeters.</p><p>Or oxidation on the package leg creates just enough resistance to make high-speed reads unstable.</p><p>Or the ribbon cable is routed directly across a noisy switching regulator because apparently today you enjoy suffering.</p><p>The first response is usually to lower the programming speed.</p><p>That often helps.</p><p>Not because slower is philosophically better, but because the electrical margins become less brutal.</p><p>Long clip leads are ugly signal paths.</p><p>They have capacitance.</p><p>They have inductance.</p><p>They pick up noise.</p><p>The programmer is not communicating with a flash chip in a clean socket anymore. It is driving a real PCB through a little plastic claw and a bundle of wires hanging in the air.</p><p>At some point you are doing signal integrity whether you wanted to or not.</p><h3>Then There Is Desoldering</h3><p>Removing the flash changes the entire problem.</p><p>Suddenly there is no motherboard.</p><p>No processor.</p><p>No regulator.</p><p>No mystery pull-up network.</p><p>No shared SPI device.</p><p>No backfeeding through another IC.</p><p>Just the chip.</p><p>Power.</p><p>Ground.</p><p>Signals.</p><p>Silence.</p><p>A stubborn device that produces inconsistent dumps in-circuit can become completely boring once the memory is on an adapter.</p><p>Boring is good.</p><p>You read it three times.</p><p>Hashes match.</p><p>You inspect the binary.</p><p>Everything lines up.</p><p>And you realize you spent two hours fighting a motherboard that was never going to cooperate.</p><p>This is the strongest argument for desoldering.</p><p>Electrical certainty.</p><p>You have physically removed almost every unknown variable.</p><h3>But You Pay for That Certainty</h3><p>The payment is mechanical.</p><p>Heat.</p><p>Pads.</p><p>Solder.</p><p>Orientation.</p><p>Nearby components.</p><p>The chip itself.</p><p>An eight-pin SPI flash package looks forgiving until someone approaches it like plumbing.</p><p>Too much heat for too long can damage the package or the PCB.</p><p>Too much upward force can lift a pad.</p><p>Moving the chip before every joint has actually released can turn a simple firmware extraction into trace repair.</p><p>Tiny passive components around the package can move in the airflow.</p><p>Flux spreads.</p><p>Solder balls appear where nobody invited them.</p><p>Then there is reinstallation.</p><p>You can have a perfect dump and still kill the device putting the chip back.</p><p>That makes desoldering fundamentally different from in-circuit work. The electrical side becomes simpler while the physical consequences become larger.</p><p>It is not inherently the advanced method.</p><p>It is just a different collection of failure modes.</p><h3>The Point Where I Stop Fighting In-Circuit</h3><p>I usually begin non-destructively.</p><p>There is no trophy for removing a chip that would have read cleanly through a clip.</p><p>First I identify the memory part properly.</p><p>Not “it looks like SPI flash.”</p><p>The actual part.</p><p>Voltage matters immediately. A 1.8 volt device connected to a 3.3 volt programmer is not a troubleshooting experiment I want to perform.</p><p>Then I look at the board around it.</p><p>Where does VCC go?</p><p>Where do the data lines go?</p><p>Are there visible series resistors?</p><p>Does the processor have an accessible reset?</p><p>Are there test pads that expose the same signals more cleanly than a clip?</p><p>I attach with the target unpowered and watch the current behavior when programmer power is applied.</p><p>If the board starts waking up, that changes the plan.</p><p>If the chip reads, I read it repeatedly.</p><p>Matching data buys confidence.</p><p>Mismatched data buys investigation.</p><p>Sometimes slowing the bus fixes it.</p><p>Sometimes holding the processor in reset fixes it.</p><p>Sometimes powering the target normally while leaving the programmer’s VCC disconnected produces a cleaner electrical environment, depending on the programmer and board architecture.</p><p>Sometimes none of it works.</p><p>That is the threshold.</p><p>Once I have spent more time trying to electrically negotiate with the board than it would take to remove and reinstall the package safely, desoldering becomes the conservative option.</p><p>That sounds backward until you have done enough of these.</p><p>The supposedly invasive method can become the controlled method.</p><h3>There Is Another Difference Nobody Talks About</h3><p>In-circuit dumping preserves context.</p><p>Desoldering destroys it temporarily.</p><p>That can matter.</p><p>While the chip remains on the board, you can observe what the device does with it.</p><p>You can watch activity during boot.</p><p>You can capture SPI transactions.</p><p>You can see which regions are touched first.</p><p>You can correlate a reset event with flash reads.</p><p>You can discover whether the processor is reading one contiguous image or jumping between regions.</p><p>That information disappears once the chip is sitting alone in a socket.</p><p>You get cleaner access to the bytes but lose visibility into how the system interacts with them.</p><p>So sometimes I deliberately stay in-circuit even when removal would make dumping easier.</p><p>The firmware image is only half the evidence.</p><p>The access pattern can tell you where the bootloader lives, where configuration is stored, whether multiple images exist, or whether the supposedly mysterious flash chip is barely used at all.</p><p>A logic analyzer attached during a normal boot can be more revealing than another binary dump.</p><p>Different question.</p><p>Different tool.</p><h3>Desoldering Is Not Automatically the Final Answer Either</h3><p>Some boards punish removal.</p><p>Multilayer PCBs absorb heat unpredictably.</p><p>Large ground planes pull energy away from the work area.</p><p>Underfilled packages turn what looks removable into something very different.</p><p>BGA storage introduces an entirely different mechanical problem.</p><p>Coatings complicate everything.</p><p>A tiny flash package surrounded by plastic connectors can leave almost no safe hot-air angle.</p><p>Sometimes a clean test pad is safer than touching the package.</p><p>Sometimes a pogo-pin fixture is better than either choice.</p><p>Sometimes the smartest firmware extraction technique is discovering that the manufacturer left a perfectly usable programming interface elsewhere on the board.</p><p>The chip is physically visible, so attention gravitates toward it.</p><p>That does not mean it is the best access point.</p><h3>Dumping Without Bricking Is Mostly About Restraint</h3><p>The dramatic failures get attention.</p><p>Reversed voltage.</p><p>Destroyed flash.</p><p>Lifted pads.</p><p>Dead processors.</p><p>But most devices are lost through smaller decisions stacked together.</p><p>A programmer supplies power when the target already has power.</p><p>A clip is attached one pin off.</p><p>A binary is written back before anyone verifies the original image.</p><p>A supposedly blank region gets “cleaned up.”</p><p>A configuration block gets overwritten because someone assumes every firmware image is interchangeable between two revisions of the same product.</p><p>Reading should be boring.</p><p>Writing is where the temperature in the room changes.</p><p>I treat the first verified firmware dump as an artifact.</p><p>Untouched.</p><p>Hash recorded.</p><p>Copied somewhere away from the programmer.</p><p>The file you extracted before changing anything is not just firmware.</p><p>It is your way back.</p><p>That principle matters more than whether the chip was read through a clip, pogo pins, an ISP header, or after removal.</p><h3>What I Actually Prefer</h3><p>In-circuit first.</p><p>Not because it is cleaner in theory.</p><p>Because leaving hardware physically unchanged gives you more options.</p><p>If the board cooperates, excellent. You get the image without introducing thermal or mechanical risk.</p><p>If it does not cooperate, the failure itself tells you something about the architecture.</p><p>Unexpected current draw tells you about rail topology.</p><p>Bus activity tells you another controller is alive.</p><p>Hash mismatches tell you the electrical environment is unstable.</p><p>A chip that reads perfectly once removed tells you the flash was probably never the problem.</p><p>Desoldering becomes useful precisely because it removes context.</p><p>The motherboard stops having opinions.</p><p>That is sometimes exactly what you need.</p><p>The deeper workflow for preserving original images, validating reads, working through voltage and bus-contention problems, and avoiding the stupid little mistakes that turn firmware extraction into board repair is what I built <a href="https://numbpilled.gumroad.com/l/xkgrh"><strong>SHADOW CATALOG: FIRMWARE DUMPING WITHOUT BRICKING</strong></a> around.</p><p>Because after enough boards, the distinction stops being “easy method versus hard method.”</p><p>It becomes something stranger.</p><p>In-circuit dumping asks the existing system to tolerate your presence.</p><p>Desoldering removes the system from the conversation.</p><p>And occasionally the cleanest firmware dump begins only after you stop trying to make the board cooperate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e75f3bbbe486" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>