Posts in Tutorial (20 found)
Blog System/5 4 days ago

Entering the Geminispace

On May 1st, 2020, Project Gemini made the rounds for the first time via a Hacker News discussion thread . I remember seeing the announcement back then, barely a month after the Covid 19 worldwide lockdown, and thinking it was a cool gimmick. But that was that. However, I’ve recently been seeing a few links here and there as footers in hand-crafted blogs, and I nerd-snipped myself to export this blog as a Gemini capsule that you can find at . The process has been fun, and I actually quite like the extreme minimalism of the resulting site. So what else would you expect from me? I had to write about it—hence this post. Today we’ll learn a little bit about what Gemini is, how I approached the blog export to its native gemtext format, and I’ll confess a couple of… sins I committed along the way. A terrible name, that is. Looking for information about Gemini these days is extremely hard, thanks to Google polluting the namespace with its own AI offering. Of course that’s not Project Gemini’s fault because Google’s thing came after them, but still, good luck finding stuff about this network. Joking aside, let’s look at Project Gemini’s barebones front page: Project Gemini's front page, displayed in the Lagrange browser. … and break down the introductory and only paragraph: Gemini is a new internet technology supporting an electronic library of interconnected text documents. You can think of Gemini as a way to access a bunch of text-only pages, with links among them, so you can find information and follow links to additional resources. Instead of using or URL prefixes, you use instead. That’s not a new idea, but it’s not old fashioned either. Exactly. Gemini is like the WWW , or “the web” in more colloquial/modern parlance. In fact, Gemini is a parallel community to the web. Obviously, that’s not a new idea because the web dates back to 1989, and we are now 37 years after that. The idea is not unique either because Gopher , a much lesser-known option, exists as well. Surprisingly to me, I realized that Gopher came after the web in 1991 while researching this article. I had always assumed Gopher was first and that the web came to replace it because of Gopher’s rigidness. But that’s not quite what happened. It’s timeless, and deserves tools which treat it as a first class concept, not a vestigial corner case. Humans have shared written documents since around 3400–3100 BCE (roughly 5,100–5,400 years ago) in ancient Mesopotamia and Egypt, and that’s probably (hopefully?) not going away. It’s true, though, that at this point, text sharing is not the primary thing that the web does, as you well know. We have morphed the web from a document distribution tool into an app platform, for better or worse. A little confession: I worked at Google for 12 years, starting right at the time they published Google Wave (2009), which to me marked the start of truly interactive web apps—more so than Gmail (2004) did. In the back of my mind, I knew I was helping turn the web into how we run apps, destroying the traditional desktop paradigm—a feeling I never liked. And… it happened. Obviously, it’d have happened without me, a little pawn in the game, but it bothered me regardless. Gemini isn’t about innovation or disruption, it’s about providing some respite for those who feel the internet has been disrupted enough already. (That comma splice hurts.) As we have established earlier, Gemini’s ideas are not new, so it’s indeed not innovative. And seeing how little people read these days, or even how unable to pay attention to long-form text they are, it’s not going to disrupt anything either. But respite is key: having a separate place where you know you’ll only find some sort of counter-culture sounds entertaining. Fun fact: I wasn’t quite sure what respite meant and originally took it to be similar to spite. That meaning would have worked equally well here, if not better? We’re not out to change the world or destroy other technologies. We are out to build a lightweight online space where documents are just documents, in the interests of every reader’s privacy, attention and bandwidth. Here is the interesting thing. Gemini claims that it has been designed to minimize the chances of becoming bloated, and I’m not exactly sure how you can prevent that. For example: articles can provide links to images, but images are not auto-loaded. OK, says who? The auto-loading part is something the client browser controls, and it’d be trivial to create a Gemini browser, or modify an existing one, to auto-load and render images. That’d go against the spirit of Gemini, but if enough people wanted it, it’d happen. Same story as the browser wars . And that’s the key: “enough people”. As long as Gemini stays under the radar and only like-minded people gravitate towards it, these properties will be maintained. But if for any reason it becomes more mainstream… unwanted changes will happen. Enjoying so far? Please take a moment to show me by subscribing to Blog System/5. It’s free! Gemtext is the native format of documents stored in the Gemini network, with a MIME type of and a extension. Gemtext documents are typically grouped in capsules —which is just another name for “website”. The format itself is like a super-diluted version of Markdown, supporting just these features: Three levels of headings. Paragraphs. Links as standalone lines, not as inline text. Preformatted text blocks, also not as inline text. Unordered lists. Blockquotes. Workable for sure, but weak. In my opinion, Gemini missed the boat of creating a truly semantical web, but for that you need additional primitives to represent more concepts. In any case, you can read through the long FAQ to know that this was discussed and eventually ruled against, so know that a lot of thought was put into its design. Yet another fun fact: just two days ago, I stumbled upon “Good morning and welcome to my idea of a new web” : the proposal of a “browser” that just renders Markdown documents. This feels quite similar to the idea behind Gemini, but using a better (not a great) format with more markup abilities. And I say fun fact because, as I was learning about Gemini, I was imagining developing this exact alternate idea. One curious bit is that Gemtext is also the format for subscription feeds. Sure, you can offer an RSS feed for your capsule, but RSS is a monster spec that feels out of place in a minimalistic network like Gemini’s. So you can abuse Gemtext to create a feed by creating a page that’s primarily links with a de-facto format. Again, it’s simple, and it works. The big benefit of Gemtext’s simplicity is that clients can also be super-simple. You can rest assured that all clients will be able to display the same content, consistently. So far I’ve tried Elpher within Emacs , Lagrange on the desktop , and Buran on my Android phone . All are simple. All display text in the same way. I definitely do not recommend using the Gemtext format to persist your original content, but that doesn’t mean you have to write in Gemtext. Which brings us to Markdown again. All of the content you are reading in this blog is authored and stored as Markdown documents. Like many other people who still maintain a blog in this day and age, I started with a hosted platform (Blogger) and then experimented with Medium. But as soon as Medium became riddled with noise, I ran away. Unfortunately, escaping was difficult: the format that Medium spit out was frigging awful—almost as if it were designed to provide the illusion that you could export content, even if the content was nearly useless after the fact. It was at that point that I committed to converting my golden copies to Markdown even though authoring in Markdown was more inconvenient. And believe me: it is inconvenient, especially when having to insert images. But now I own my content in a format that’ll survive for years to come. Which brings us back to Gemtext. The thought that crossed my mind when I stumbled upon Project Gemini again three weeks ago and that triggered this whole thing was: can I write a script to convert my Markdown docs into a capsule? And with “I” I really mean AI, because this is the kind of experiment I was not going to code myself. And of course I could. After just one simple prompt, I had a converted site that I could browse. Granted: the conversion Python script was literally awful, and the converted format was not great either, but having something I could play with inspired me to try harder. A run of my blog-to-capsule exporter. So I threw everything away and started over, again with AI, to write a conversion tool for my blog (codenamed for now) that takes the existing Hugo layout and spits out a capsule end-to-end in just 300 milliseconds while processing 1000 documents. The tool is obviously written in Rust, and by now supports enough configurable features that I’m increasingly tempted to throw Hugo away for the web version and create my own static site generator too. Because, you know, while Hugo works, it isn’t the greatest in usability and its recurrent incompatible changes are annoying. I’ll resist the urge to do that for now… I think. Let’s dive a tiny bit into . First of all, this second iteration is still entirely vibecoded. Oops, first sin. I have not looked at the code because it’s working for what I need it to do, it’s fast, and it’s not going to be used by anyone else… unless you want it, but then I’d probably rewrite it once more now that I know what the final feature set looks like. Now, for this second iteration, I was so close to running out of my $20 weekly OpenAI quota that I pivoted from my favorite GPT 6.1 Sol model to GPT 6 Luna to see how far I could go. Luna is so cheap that you can do a ton with it, and I actually got to work well enough within just a few iterations. But oh dear. Luna is cheap, but it’s also kind of crap for coding. It stops half-way. It doesn’t think through enough corner cases. It doesn’t produce enough tests. The plans it produces are very vague. You have to be extremely prescriptive when asking it to do things and even that leads to mixed results. Out of curiosity, when my weekly cap was reset, I asked Sol to review what Luna did, and oh boy did it have things to say. From design problems to important missing tests, passing through outright bugs. I let it fix those issues, and I continued building with Sol. Right now, I’m actually pretty happy with the results of . I can configure the mapping of pages to templates in a much more explicit way than in Hugo. I can use MiniJinja for templating. I can specify cross-site links. I can handle inline links, figures, and even tables. I can generate archives/feeds for the site, for each year, for each month. I can process blog posts, and also standalone pages. All in all, the results are very satisfactory given the close-to-zero effort I put into it. With the site exported to Gemtext, I needed a server. There are a lot of options out there, but the one that piqued my interest was Agate : a minimalistic Gemini server written, of course, in Rust. You run the binary pointing it at the directory containing the generated site and, voila, it works. Agate even takes care of auto-generating SSL certificates because all Gemini traffic is TLS-protected, and the fact that it’s automated is a relief because dealing with certificates is a pain. My new Gemini capsule shown by a Surface Go 2 running Lagrange. Artwork courtesy of Eva Merino. But running Agate once, interactively, and making it serve in the background are different stories. I am running FreeBSD on my server and I could have used the prebuilt package, but then I encountered a crashing bug and wanted to add a feature, so I had to pivot to building from source. And, as you can imagine, Cargo leaves a lot to be desired if you want to install the resulting product to a running system. Now, of course you can copy the built binary to, say, , but there is typically much more than a binary in a distribution: think about documents, examples and, for a server program in particular, startup scripts. Mind you, Agate’s source tree does include a FreeBSD rc.d script, but it was buggy, insufficient, and it also required manual copying. So I created a PR to revamp the installation system based on earlier experience with setting up similar infrastructure in other Rust services I run. I mentioned briefly above that I wanted to add a feature to Agate and that it was the reason I had to build from source. And that feature is… analytics, which are the second sin right there. “Oh no, ah-nah-ly-tics! Privacy enemy number one! How dare you add analytics to something in the Gemini network!?!” But wait a second. What are analytics? You do realize that Agate prints and saves a log of incoming connections (with IPs redacted by default), right? That’s par for the course for any Internet server out there, because in order to serve requests… well, the server actually needs to know what those requests are and where to send the responses to. So you can always analyze the log to gain some insights on traffic. And that’s pretty much what I did. I just wired this exact same information to my own analytics service for visualization. The only thing I see are the pages that are being downloaded, when they are downloaded, and the originating country (computed from the requester’s IP after truncating the last octet to mask it). Essentially… good old page counters from the 1990s. Live page views graph showing both https:// and gemini:// visits at once. The way I implemented this is generic though: I extended Agate to add optional support for an SSI-style URL inclusion primitive and then added such a call to the capsule-wide footer template given to my Gemtext generator. As a high-level primitive, it can serve other purposes, like sourcing comments for each page by making the footer download a pre-rendered chunk. I haven’t implemented that yet in my comments service, but it should be pretty easy. Sounds interesting? I might try to contribute this SSI feature upstream to Agate, but I predict that this collides with the goal of a lightweight server and that it’ll be rejected. But I’ll try anyway. I want to get the FreeBSD-related bug fixes and related improvements merged first, because those are helpful to everyone, I hope. That’s about it! If you are in the U.S. you are about to have 4 days off, so spend that time falling into the Gemini rathole. And if you are elsewhere, do the same! It’s entertaining. From now on, remember that you can also read this blog via gemini://capsule.jmmv.dev/ if you want a super-fast, distraction-free experience. To get started, visit the Gemini software page for a long list of clients to choose from and install. (Content also available at: ) Project Gemini's front page, displayed in the Lagrange browser. … and break down the introductory and only paragraph: Gemini is a new internet technology supporting an electronic library of interconnected text documents. You can think of Gemini as a way to access a bunch of text-only pages, with links among them, so you can find information and follow links to additional resources. Instead of using or URL prefixes, you use instead. That’s not a new idea, but it’s not old fashioned either. Exactly. Gemini is like the WWW , or “the web” in more colloquial/modern parlance. In fact, Gemini is a parallel community to the web. Obviously, that’s not a new idea because the web dates back to 1989, and we are now 37 years after that. The idea is not unique either because Gopher , a much lesser-known option, exists as well. Surprisingly to me, I realized that Gopher came after the web in 1991 while researching this article. I had always assumed Gopher was first and that the web came to replace it because of Gopher’s rigidness. But that’s not quite what happened. It’s timeless, and deserves tools which treat it as a first class concept, not a vestigial corner case. Humans have shared written documents since around 3400–3100 BCE (roughly 5,100–5,400 years ago) in ancient Mesopotamia and Egypt, and that’s probably (hopefully?) not going away. It’s true, though, that at this point, text sharing is not the primary thing that the web does, as you well know. We have morphed the web from a document distribution tool into an app platform, for better or worse. A little confession: I worked at Google for 12 years, starting right at the time they published Google Wave (2009), which to me marked the start of truly interactive web apps—more so than Gmail (2004) did. In the back of my mind, I knew I was helping turn the web into how we run apps, destroying the traditional desktop paradigm—a feeling I never liked. And… it happened. Obviously, it’d have happened without me, a little pawn in the game, but it bothered me regardless. Gemini isn’t about innovation or disruption, it’s about providing some respite for those who feel the internet has been disrupted enough already. (That comma splice hurts.) As we have established earlier, Gemini’s ideas are not new, so it’s indeed not innovative. And seeing how little people read these days, or even how unable to pay attention to long-form text they are, it’s not going to disrupt anything either. But respite is key: having a separate place where you know you’ll only find some sort of counter-culture sounds entertaining. Fun fact: I wasn’t quite sure what respite meant and originally took it to be similar to spite. That meaning would have worked equally well here, if not better? We’re not out to change the world or destroy other technologies. We are out to build a lightweight online space where documents are just documents, in the interests of every reader’s privacy, attention and bandwidth. Here is the interesting thing. Gemini claims that it has been designed to minimize the chances of becoming bloated, and I’m not exactly sure how you can prevent that. For example: articles can provide links to images, but images are not auto-loaded. OK, says who? The auto-loading part is something the client browser controls, and it’d be trivial to create a Gemini browser, or modify an existing one, to auto-load and render images. That’d go against the spirit of Gemini, but if enough people wanted it, it’d happen. Same story as the browser wars . And that’s the key: “enough people”. As long as Gemini stays under the radar and only like-minded people gravitate towards it, these properties will be maintained. But if for any reason it becomes more mainstream… unwanted changes will happen. Enjoying so far? Please take a moment to show me by subscribing to Blog System/5. It’s free! Gemtext Gemtext is the native format of documents stored in the Gemini network, with a MIME type of and a extension. Gemtext documents are typically grouped in capsules —which is just another name for “website”. The format itself is like a super-diluted version of Markdown, supporting just these features: Three levels of headings. Paragraphs. Links as standalone lines, not as inline text. Preformatted text blocks, also not as inline text. Unordered lists. Blockquotes.

0 views

How I automated my bookkeeping with AI and replaced the work I outsourced to an admin assistant

Hey, what's up? It's Takuya here. I'm an indie developer based in Japan, and I make a living by developing and selling an app called Inkdrop on my own. Over the past 2–3 months, I've been automating my bookkeeping little by little. It turned out that AI can handle almost all of the work I used to outsource to an admin assistant, so I'd like to share how I set it up. I run my business as a sole proprietor in Japan, and this is about automating my bookkeeping there. So a lot of it is specific to Japan, like the accounting service I use. But I think some parts can be useful wherever you are, so I'm sharing it in English, too. I don't run a company. I work as a sole proprietor, and I used to do all the bookkeeping by myself. But managing expenses and recording transactions had become a real burden. I didn't want to spend my time on it, so I tried various tricks, but I still couldn't keep up. So I hired an admin assistant for about ¥10,000 a month. I asked them to handle this flow: I have no employees and no physical store, so there aren't that many documents to process. And since it's simple work, the volume was easy for an assistant to handle. I had documented everything I'd been doing on my own as a manual, so that anyone could do it by following it, and then handed it over. Once the initial handover was done, the rest was easy. They actually had spare hours left over, which was a huge help. But those spare hours bugged me a bit, and I thought this kind of simple work could be done by AI. It saves money, too. So I gave it a try. I mainly use Claude Code, so please read this with that in mind. I also saved each step as a skill so I can call it easily. First, receipts. They come in through 3 routes: Let me walk you through each. Most email receipts come as PDF attachments. At first, I thought the Gmail MCP would do the job, but it turned out it can't download attachments. So I switched to the Apple Mail MCP , which can save attachments to any path. Some emails are receipts themselves, like Apple's "Your receipt from Apple." For those, I wrote a script that reads the email source and prints it to PDF with headless Chrome. Both go straight into a designated folder. I scan paper receipts with my iPhone and save them to a folder. When I let Claude Code read the scanned images, Claude's vision picks up the date, the company name and the amount, even in Japanese. Then it renames each file in my format: So far, it hasn't misread a single one, and I'm amazed at how accurate it is. This alone took a lot off my plate. This one can't be fully automated, because I have to log in to each site to download receipts. I used to share account credentials with my assistant through 1Password . In the same way, I let the AI log in by passing the credentials safely through the 1Password CLI . But I don't let AI control my everyday Chrome. It holds a lot of personal information and login sessions, and if any of them leaked through a prompt injection or something, that would be a disaster. Instead, I use a tool called agweb . It's a browser built for agents, in other words, a browser app made for automation. You can drive it with TypeScript scripts. I use it to log in, navigate the pages and download the receipts. Right now, it supports Amazon and Adobe, as well as sites for utility bills, mobile and internet plans, and various subscriptions. As I expected, there was a problem: it can't log in to sites protected against bots. That can't be helped, so I do just those parts by hand every time, like solving a CAPTCHA or clicking a button. Filling in the forms is automated. I asked Claude to get around the bot protection, but it refused (of course lol). So I fixed some of the scripts myself and tuned them, for example by adding waits (Yodobashi.com is one of them). Also, 1Password asks me to authenticate every time a password is read, which is annoying. So I use op-cache , a wrapper tool I made. It caches the credentials for a while, so I don't get asked for Touch ID again and again while a script runs. The key is not to let AI operate the browser every time. Let it do the job a few times as a trial, then turn that into a script. From then on, it just runs the script. This saves tokens, too. And since the AI checks the results, it can tell whether the run worked, and when a run fails because a site changed, it fixes the script on its own. I use Money Forward Cloud Tax Return (マネーフォワード クラウド確定申告) to keep my books. Receipts from overseas services are usually in USD, not yen, so they don't tell me how much I actually paid. In that case, I check the actual amount charged to my credit card on Money Forward and put it in the file name. This is easy once you connect the Money Forward Cloud Accounting MCP server . If the charge hasn't shown up on the statement yet, I leave the amount as and handle it next time. Next, journal entries and attaching receipts as supporting documents. I record the entries through the Money Forward MCP as well. It's pretty well made, and you can set things like the tax category properly. I automate the choice of account titles in 2 ways: The CSV keeps a history of which account titles I used for past entries. If an item matches, the AI follows that rule. If a new item shows up, it asks me. Once I decide, a row is added to the CSV, so it won't ask me again next time. Still, I was nervous at first, so I had it show a preview of everything and pointed out anything wrong one by one. For attaching the receipts, I use the Money Forward Cloud Box API . It's only available on request, though, so I won't go into details here. All the app's revenue is paid out to my bank account through Stripe . I aggregate the balance transactions through the Stripe MCP server and record accounts receivable and sales in bulk. The breakdown includes the taxes and fees. Then, to make sure the balance adds up, I check it against the accounts receivable subsidiary ledger for any gaps. So, apart from the logins for downloading receipts from websites, I'd say it's mostly automated now. The more journal entries pile up, the more accurately the AI can pick account titles, so the accuracy should keep getting better. That's it! I hope it's helpful for automating your own bookkeeping :) Download receipts from various websites Read the receipts I scanned and rename the files following a naming format Upload them and record the transactions Scanned paper receipts Auto-journal rules on Money Forward A CSV file managed with git

0 views
Uros Popovic 1 weeks ago

Building a static website with Bazel

Build a complete static website with a single Bazel command using Pageforge: templates, Markdown posts, listings, tags, static files, a local dev server, and a zip ready for Cloudflare Pages.

0 views

Notes on the discrete Fourier transform (DFT)

In the previous post on this topic , we’ve seen how the Discrete-Time Fourier Series (DTFS) and transform (DTFT) are used to analyze infinite-duration periodic and non-periodic discrete signals. Now, it’s time to turn to realistic digital signal processing where signals are not only discrete, but also finite in …

0 views
Unsung 1 weeks ago

“I’ve spent years on it. Years. On a box.”

Designer Pablo Stanley created a really fun interactive exploration of what it takes to create a seemingly simple “composer” (industry’s jargon for a more sophisticated input field or things like it): = 2x) and (width >= 700px)" srcset="https://unsung.aresluna.org/_media/ive-spent-years-on-it-years-on-a-box/1.2096w.avif" type="image/avif"> = 3x) or (width >= 700px)" srcset="https://unsung.aresluna.org/_media/ive-spent-years-on-it-years-on-a-box/1.1600w.avif" type="image/avif"> It’s a bit outside of Unsung’s purview since a lot of it is very “sung.” The case study focuses on visual presentation, and doesn’t cover systems design or consistency with other things; I even worried at times it could perpetuate an image of a UX designer being a “lone genius,” overindexing on visuals and tactile experiences over more important things, of which there is a ton in the AI neck of the industry woods. At the same time, there are also mentions of flow, and a general drive toward reducing complexity that feel worthwhile. Plus, the theme of details that seem minuscule on the surface, but will all ladder up to a lot of friction in repeated use, is something we cover a lot . Also, I am burying the lede: it’s a really enjoyable and well-crafted experience – don’t miss the sound and music! – and this unique way of talking about interface details could be inspiring in and of itself. You can also watch the entire thing as a video with Stanley narrating, but I personally liked the interactive version more:

0 views
The Coder Cafe 2 weeks ago

Building Barista—Part 2: Formal Verification and TLA+

☕ Welcome to The Coder Cafe! Part 1 of Building Barista covered the architecture. Today, we explore formal verification through a real bug my tests missed. You’ll learn what model checking is, how to read a bit of TLA+, and why it catches the bugs we never think about. I spent a lot of time on formal verification at Google; this time, I pointed it at my own system. Get cozy, grab a coffee, and let’s begin! One Email a Day A quick summary of Barista : it’s a system I built that fetches hundreds of sources, gets a unique prompt per user, and sends that user one email per day with the best sources for them. Making sure Barista sends a single email per user per day is something important to me. If Alice receives the same email twice on a random day, that’s a terrible user experience. As discussed in Part 1 , Barista is a set of independent stages coordinating through Postgres. The last one, , runs every 5 minutes, looks for the users whose send time has passed, and emails each of them the posts picked by the stage. The nominal scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ✅ Barista writes back in Postgres that the email to Alice was sent that day. Now the worst-case scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ❌ Before writing back in Postgres that the email was sent, Barista crashes. The stage starts again and notices an email has to be sent to Alice. Barista calls the email provider again and receives an ACK. ← Duplicate email ✅ Barista writes back in Postgres that the email to Alice was sent that day. How do you prevent that? I picked my email provider for it: Plunk. Why Plunk? Because it accepts an idempotency key. When calling Plunk, I pass a key like : the user and the day. If Plunk receives the same key again, it doesn’t send anything; it replies with a 409. My code reads that 409 as “these posts were already sent” and marks them as sent. No duplicate. It was a conscious decision. Plunk is 10x more expensive per email than AWS SES, which has no idempotency key. I was happy to pay for it. So here was the state: A business decision: no duplicates, even if it costs more. A sound design, with an email provider deduplicating for me. Unit tests, integration tests, end-to-end tests. All green. Great mental model of the code. Pure intellectual control . Now, what if I told you my code had a bug? One that none of my tests caught. I only managed to find it with something called formal verification. Let’s see how. Formal Verification Before becoming an SRE, I worked in Air Traffic Management (I talked about it in Reliability Explained ). It’s a so-called safety-critical domain. You can easily imagine why. In a safety-critical system, green tests aren’t enough. That’s the blind spot of intellectual control: tests only check the scenarios we thought about. And the bugs that hurt are, by definition, the ones we didn’t think about. In domains like this, green tests aren’t the end of the conversation. Some teams go further and prove that certain bugs can’t happen. Airbus, for example, used a static analyzer called Astrée to prove that the flight control software of the A340 and A380 is free of a whole class of runtime errors. So instead of picking scenarios one by one, what if we could check all of them? That’s the idea behind formal verification: describe the system precisely, write down the properties it must respect, and let a tool check that no possible execution breaks them. Note the word: verification . It answers “did we build the thing right?”, meaning does the design respect our properties. Not to be confused with validation : “did we build the right thing?”, meaning are these the properties we actually need. A tool can do the first. The second stays on us. There are several ways to verify a system, from mathematical proofs to running real code on generated inputs. The one I used is model checking . A model checker sees a system as states (a value for every variable) and actions (a step from one state to the next). It starts from the initial state, tries every possible action, then every possible action from each new state, and so on, until it has visited every reachable state. A test follows one path. A model checker walks all of them. That’s why it finds bugs nobody writes a test for. AWS described it in 2015, in a paper on how they use formal methods: one of their DynamoDB bugs had survived design reviews, code reviews, and testing. The shortest sequence of events to trigger it was 35 steps long. At each state, the model checker checks our properties. They come in two flavors: Safety : Something bad never happens (e.g., Alice never receives the same email twice) Liveness : Something good eventually happens (e.g., Alice eventually receives her daily email) When a property breaks, we get a counterexample : the exact sequence of steps that led there. The model checker I used is TLC. It reads models written in TLA+, a language created by Leslie Lamport to describe a system as states and actions. In other words: we describe the system in TLA+, and TLC explores every state it can reach. A TLA+ spec doesn’t look like code. There are no instructions executed one after the other. Instead, each action is a formula that says two things: when the step is allowed (a condition on the current state), and what the state looks like after it (the values in the next state). TLC then tries every allowed action, in every possible order. A few symbols are enough to follow the examples below: means “is defined as” is the value of in the next state and mean “for all” and “there exists” Let’s see it on a simple example. Imagine a cafe with one croissant left and two baristas. When a customer asks for a croissant, a barista does two things: first, they check the display case to see if there’s one left; then, they sell it. The property we want is a safety one (something bad never happens): the cafe never sells a croissant it doesn’t have. In other words, the stock never goes below zero. To model this cafe, we need two variables: : how many croissants are left. It starts at 1. : where each barista is. Each one starts , moves to after checking, and ends . Now, the two actions. The first one is checking the display case: The first two lines are conditions: can only happen if barista is idle and there’s a croissant left. The last two lines describe the next state: is now selling ( means “every other barista stays where they are”), and the stock stays the same. The second action is selling: And the property, written as an invariant that must hold in every state: That’s the whole model. TLC starts from the initial state (one croissant, two idle baristas) and tries every action, in every possible order. In most orders, everything is fine. For example, barista 1 checks and sells, then barista 2 can’t check anymore because the stock is zero. But TLC finds one order that breaks the invariant: Both baristas looked at the display case before either one sold. Both saw a croissant. Both sold it. That’s how to read a counterexample: find the step where it broke (5), then walk back to the decision that made it inevitable (3). The fix is to make checking and selling a single action, so nobody can slip in between. Re-run TLC, and it explores every state without finding a violation. In a cafe, we can merge two steps. Across a network call and a database write, we can’t, and that’s exactly why idempotency keys exist. Now, let’s do the same with Barista. Back to Barista. Years after leaving Air Traffic Management, I wondered: what if I applied the same rigor here? So I wrote a TLA+ spec of the stage. The model was tiny: one user, two posts, a clock with eight slots per day, and two days. The key idea is that it tracks two things separately: what was really delivered to the user, and what Barista believes was delivered. If Barista works, both always agree. The full spec also has a few actions I’m leaving out here: the clock ticks, Rank picks new posts, and moves the next send time forward. Here are the variables (simplified): : the clock. : when user ’s next email is due. : the posts picked for ’s next email. : the idempotency keys Plunk has already seen. : the list of emails really delivered. The truth. : the posts Barista has marked as sent to . What Barista believes. And a simplified version of the action at the time: A few new pieces: defines a local name (here, the key). is a pair, our . adds to a set, and adds to the end of a list. And is a record: an email to containing these posts. Read it line by line. can only run once the send time has passed. If Plunk already knows the key, it replies with a 409 and nothing is delivered. Otherwise, the email goes out. Either way, Plunk remembers the key, and Barista marks the posts as sent. That last line is the one to watch. The real action can also end badly: Plunk delivers the email, then Barista crashes before recording anything. TLC tries that outcome too. Now the property, in the same spirit as the cafe’s : In plain English: Barista’s belief must match the truth. If a post is marked as sent, an email really contained it. I ran TLC. Guess what? Despite all the tests, despite the idempotency key I was paying 10x for, it failed on the first run . Every configuration failed, even the simplest one: no crash, no settings change. Here’s one of the counterexamples, in real times. Alice gets her email at 22:00 UTC: An outage on May 20 eats Alice’s May 21 email. The catch-up send at 01:00 UTC uses key , so the regular send at 22:00 gets a 409, and its posts are marked as sent without being delivered. Alice never gets her May 21 email. Its posts are marked as sent, so Barista will never offer them again. No error, no alert. And it happens 21 hours after everything recovered. The fun part is that I never modeled an outage. Nothing in the spec says Barista can be down. But nothing forces to run on time either: in TLA+, the clock is just another action, and TLC is free to let it tick while waits. An outage, a slow deploy, a job stuck behind another one: for the model, it’s all the same. TLC tried every possible delay and found the one crossing midnight. So what went wrong? Plunk did exactly what it promised. A 409 doesn’t mean “these posts were sent.” It means “something was already sent under this key.” My key was the day of the attempt, not the day the email was for. As long as a send ran on the day it was due, it didn’t matter. The moment one slipped past midnight, it did. Should Barista skip the catch-up, then? No. Alice should still get her May 20 email. The catch-up was right; my reading of the 409 was wrong. Ironically, I was obsessed with sending too many emails, and the very thing I was paying 10x for made me send too few, silently. Would my tests have caught it? Honestly, no. I tested a crash after the ACK, and the idempotency key handled it. I would never have written a test where runs late, past midnight UTC, followed by a regular send the next evening. And that was exactly my fear in the first place. The fix? One key per email instead of one per day. I re-ran TLC. Green. In December 2025, Martin Kleppmann, the author of Designing Data-Intensive Applications , published a post with a bold prediction: AI will make formal verification go mainstream . His argument is mostly about cost. Formal verification has always been expensive. Proving that seL4, an OS kernel of about 8,700 lines of C, was correct took around 20 person-years. For most systems, a bug was cheaper than the proof that would have prevented it. But coding agents are getting good at writing proofs. And a wrong proof isn’t dangerous: the checker rejects it, and the agent tries again. One of the issues with TLA+ has always been making sure the spec is accurate. A TLA+ spec is a model, and a model is only as good as its abstraction. TLC checks the spec, not the code. The hard part is making sure the spec describes what the code actually does. But with the rise of coding agents, especially over the last few months, I feel like this gap is shrinking. An agent can read the code and draft the spec, keep both in sync when the code changes, and turn a counterexample into a failing test against the real code. At Google, I spent a lot of time exploring formal verification, especially on convoluted logic: loops with several paths, retries, error codes. On many occasions, I found bugs despite significant test coverage. Back then, though, writing and maintaining a spec was a real investment, so it was reserved for the parts that truly justified it. That’s what’s changing. When a spec costs an afternoon instead of weeks, the question is no longer “is this part critical enough to deserve a spec?” It becomes “why not?” Does it mean software will be bug-free? No. As Kleppmann also points out, the hard part moves to the specification itself: are we checking the properties we actually care about? That’s the validation question from earlier. But think about what it took to find Barista’s bug: a property of a few lines, and a tool patient enough to try every delay, every order, every midnight. Now extend that. Maybe that’s what software engineering becomes: less time on how the code achieves something, more time on what must hold no matter what. Alice never receives the same email twice. Alice eventually receives her daily email. We write those down; agents write the code and the spec; tools check that the properties hold. Kleppmann compares it to compilers: we don’t read the machine code they produce, and maybe one day, we won’t read the code agents produce either. Will we get there? I don’t know. But it might be worth exploring in your own system: write down its invariants, and see whether a model can show you where they break. If you want to see what this pipeline picks for you, give Barista a try. Describe what you like to read, and your first email lands in your inbox in seconds. It’s free (one post a day), and every new account gets 7 days of the paid plan to try more. Resources Sources How Amazon Web Services Uses Formal Methods, Newcombe et al., CACM, 2015 Systems Correctness Practices at AWS, Brooker and Desai, ACM Queue, 2024 The Astrée Static Analyzer Prediction: AI will make formal verification go mainstream How we continuously validate formal specifications in production - Datadog One Email a Day A quick summary of Barista : it’s a system I built that fetches hundreds of sources, gets a unique prompt per user, and sends that user one email per day with the best sources for them. Making sure Barista sends a single email per user per day is something important to me. If Alice receives the same email twice on a random day, that’s a terrible user experience. As discussed in Part 1 , Barista is a set of independent stages coordinating through Postgres. The last one, , runs every 5 minutes, looks for the users whose send time has passed, and emails each of them the posts picked by the stage. The nominal scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ✅ Barista writes back in Postgres that the email to Alice was sent that day. The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ❌ Before writing back in Postgres that the email was sent, Barista crashes. The stage starts again and notices an email has to be sent to Alice. Barista calls the email provider again and receives an ACK. ← Duplicate email ✅ Barista writes back in Postgres that the email to Alice was sent that day. A business decision: no duplicates, even if it costs more. A sound design, with an email provider deduplicating for me. Unit tests, integration tests, end-to-end tests. All green. Safety : Something bad never happens (e.g., Alice never receives the same email twice) Liveness : Something good eventually happens (e.g., Alice eventually receives her daily email) means “is defined as” is the value of in the next state and mean “for all” and “there exists” : how many croissants are left. It starts at 1. : where each barista is. Each one starts , moves to after checking, and ends . : the clock. : when user ’s next email is due. : the posts picked for ’s next email. : the idempotency keys Plunk has already seen. : the list of emails really delivered. The truth. : the posts Barista has marked as sent to . What Barista believes. An outage on May 20 eats Alice’s May 21 email. The catch-up send at 01:00 UTC uses key , so the regular send at 22:00 gets a 409, and its posts are marked as sent without being delivered. Alice never gets her May 21 email. Its posts are marked as sent, so Barista will never offer them again. No error, no alert. And it happens 21 hours after everything recovered. The fun part is that I never modeled an outage. Nothing in the spec says Barista can be down. But nothing forces to run on time either: in TLA+, the clock is just another action, and TLC is free to let it tick while waits. An outage, a slow deploy, a job stuck behind another one: for the model, it’s all the same. TLC tried every possible delay and found the one crossing midnight. So what went wrong? Plunk did exactly what it promised. A 409 doesn’t mean “these posts were sent.” It means “something was already sent under this key.” My key was the day of the attempt, not the day the email was for. As long as a send ran on the day it was due, it didn’t matter. The moment one slipped past midnight, it did. Should Barista skip the catch-up, then? No. Alice should still get her May 20 email. The catch-up was right; my reading of the 409 was wrong. Ironically, I was obsessed with sending too many emails, and the very thing I was paying 10x for made me send too few, silently. Would my tests have caught it? Honestly, no. I tested a crash after the ACK, and the idempotency key handled it. I would never have written a test where runs late, past midnight UTC, followed by a regular send the next evening. And that was exactly my fear in the first place. The fix? One key per email instead of one per day. I re-ran TLC. Green. The Future of Software Engineering? In December 2025, Martin Kleppmann, the author of Designing Data-Intensive Applications , published a post with a bold prediction: AI will make formal verification go mainstream . His argument is mostly about cost. Formal verification has always been expensive. Proving that seL4, an OS kernel of about 8,700 lines of C, was correct took around 20 person-years. For most systems, a bug was cheaper than the proof that would have prevented it. But coding agents are getting good at writing proofs. And a wrong proof isn’t dangerous: the checker rejects it, and the agent tries again. One of the issues with TLA+ has always been making sure the spec is accurate. A TLA+ spec is a model, and a model is only as good as its abstraction. TLC checks the spec, not the code. The hard part is making sure the spec describes what the code actually does. But with the rise of coding agents, especially over the last few months, I feel like this gap is shrinking. An agent can read the code and draft the spec, keep both in sync when the code changes, and turn a counterexample into a failing test against the real code. At Google, I spent a lot of time exploring formal verification, especially on convoluted logic: loops with several paths, retries, error codes. On many occasions, I found bugs despite significant test coverage. Back then, though, writing and maintaining a spec was a real investment, so it was reserved for the parts that truly justified it. That’s what’s changing. When a spec costs an afternoon instead of weeks, the question is no longer “is this part critical enough to deserve a spec?” It becomes “why not?” Does it mean software will be bug-free? No. As Kleppmann also points out, the hard part moves to the specification itself: are we checking the properties we actually care about? That’s the validation question from earlier. But think about what it took to find Barista’s bug: a property of a few lines, and a tool patient enough to try every delay, every order, every midnight. Now extend that. Maybe that’s what software engineering becomes: less time on how the code achieves something, more time on what must hold no matter what. Alice never receives the same email twice. Alice eventually receives her daily email. We write those down; agents write the code and the spec; tools check that the properties hold. Kleppmann compares it to compilers: we don’t read the machine code they produce, and maybe one day, we won’t read the code agents produce either. Will we get there? I don’t know. But it might be worth exploring in your own system: write down its invariants, and see whether a model can show you where they break. If you want to see what this pipeline picks for you, give Barista a try. Describe what you like to read, and your first email lands in your inbox in seconds. It’s free (one post a day), and every new account gets 7 days of the paid plan to try more. Resources Sources How Amazon Web Services Uses Formal Methods, Newcombe et al., CACM, 2015 Systems Correctness Practices at AWS, Brooker and Desai, ACM Queue, 2024 The Astrée Static Analyzer Prediction: AI will make formal verification go mainstream How we continuously validate formal specifications in production - Datadog

0 views

Monads in Lean

This post demonstrates how to use monads in the Lean programming language (Lean 4, to be specific). If you're not familiar with Lean, this part of the language is very similar to other functional programming languages, like Haskell or OCaml. Suppose we want to write a simple numerical expression evaluator that supports numbers with addition and division: What happens when we encounter a division by zero? We'll want our evaluator to report this as a failure, which will be represented explicitly using the the Option type: With this in hand, the eval function can be written as follows: safeDiv returns an Option ; to propagate that possible failure to its caller, eval also returns an Option , and - moreover - has to perform lots of tedious checking for the possibility of a none value. Is there a better way? Note a common code pattern repeated here: We can extract it into a helper function: And rewrite our eval using this helper: This is already much better; we can make it even cleaner using operator overloading: Congratulations - we've pretty much invented monads! In simplified form, the Monad type class in Lean is defined as: In our code, pure is equivalent to some , and bind is equivalent to withSome ; in fact, the Monad instance for Option is something like: An operator akin to >>? for monads is already defined in Lean; it's called >>= , and picks up the bind method of the Monad type class. So we can rewrite our evaluator using the standard Monad instance, without defining withSome or the >>? operator [1] : We can go even further with the do notation, which is syntactic sugar around >>= that lets us rewrite the evaluator as: This notation should be familiar if you've seen Lean code dealing with I/O; we'll revisit I/O later in the post. Functional programming languages place a lot of emphasis on pure functions that are free of side effects. There's no question that such functions are easier to reason about, debug, and even optimize (by memoization). That said, the real world is messy and sometimes side effects are inescapable; monads help encapsulate side effects in functional programs. The core idea is: side effects are encapsulated inside a Monad , which wraps the value returned from a computation. The bind method (or the equivalent >>= operator) lets us take a wrapped value and push it into the next computation in the sequence. This may look familiar from continuation-passing style (CPS). Continuations themselves can also be modeled with a monad [2] . The definition of bind is: Here's a mental model to think about it: Chaining multiple bind s together is essentially a sequence of computations while keeping track of the side effects. A monad decouples what computations do from how they are sequenced . The programmer describes the sequence of computations and their dependencies, while the monad's bind implementation handles the bookkeeping necessary to combine their side effects. Our evaluator case study shows one example of side effects: early return from a computation with a none value. Let's see another idiomatic way of doing that, with the Except type that contains either a successful result or an error value (very similar to the Result type in Rust). We'll begin by writing an exception-returning version of safeDiv : Instead of writing a whole new eval variant for Except , we'll create a generic one that works with any Monad [3] : Now evalM can be used with safeDivExc to implement an evaluator where division returns Except ; used with safeDiv , it would be equivalent to the Option -specific evalDo we've written before. Let's look at a more advanced example: an evaluator that also logs the computation it executes in a linear log of strings. The challenge here is that we still have to combine that with Option to support the divide-by-zero case, so we'll start by creating a new structure to carry the state of the computation: This will be the result of one eval call; it produces an optional value, along with a list of strings (the log). Here's the Monad implementation for this type: The main idea is combining the stored log with the log of the next computation by appending them (thus accumulating a linear log). Here's our evaluator: Note how the code of evalLogged doesn't have to deal with the mechanics of logging too much (other than adding new log entries). All of that is hidden within the monad instance. LoggedOption is an example of the writer monad , which is a write-only version of the state monad . One of the most important use cases of monads in functional programming languages is modeling mutable state through a computation. A stateful computation is modeled as a function that takes an initial state and returns a tuple containing the result value and a new, updated state. In Lean notation: To demonstrate this in action, let's enhance our evaluator to support variable assignments and lookups. Our state is going to be an association list of name, value pairs: And we'll augment our expression enum with additional operations: This is going to be our state monad: Note the correspondence of the run function to the State signature above: This is its Monad class implementation: And finally, the evaluator: Operations that don't deal with variables directly (like .num and .add ) just do their work as before. .div only has to deal with the actual monad type to ensure that none is propagated in case of division by zero. Note also that this evaluator supports stores as expressions, since they separately return a value and the updated state; therefore, computations like this one will work: Producing the result some (16, [("x", 12)]) . In a language with mutable state, modeling side effects is easy - just assign some state (like a struct field or class member). In a functional language like Lean, however, we have to carry this state across the computations explicitly; monads help us do this with elegance - by hiding most of the mechanics of actually carrying the state around, the majority of the code remains free of bookkeeping. Perhaps the most well known example of a monad in functional programming languages like Lean and Haskell is IO . To anyone who's written a "real" program that interacts with the outer world, IO is very familiar. Here's a customized "Hello" program that's typically taught in the first 15 minutes of learning a new programming language: Note the do notation here, suggesting monads. As mentioned before, do is syntactic sugar for the monad's bind method, or the >>= operator; we can rewrite this code more explicitly as: In essence, IO is a state monad, where the state carried around represents the "outside world". IO operations like println act on that world, and its state is carried over using bind , like other state monads. Here's a version of our expression evaluator that logs directly to standard out, instead of collecting the log as a list of strings: The only unusual construct here is OptionT , which is a monad transformer that helps us compose Option (for propagating failure from safe division) with the IO Monad [4] . The IO monad also supports throw for Python-like exception behavior, but in this example we use Option explicitly; exceptions are a matter of programming preference, and using them inside library functions like eval doesn't feel right to me. Just like in Haskell, monads in Lean should obey certain laws . Those are: Left identity : wrapping a value in pure and immediately passing it to f with bind should be equivalent to just calling f on the value: Right identity : extracting a value from a computation and immediately wrapping it with pure again should not change the computation: Associativity : the grouping of operations doesn't matter, as long as their order remains the same: Let's see how Option obeys these laws. For left identity, pure v is some v and the bind implementation matches some x to next x , which is equivalent to f v . For right identity, m >>= pure just rewraps a some value in pure , leaving none alone - this is equivalent to keeping things as they are. For associativity, if m is none then both sides are none . If m is some v , the left side is f v >>= g , and the right side reduces to the same, so again they are equivalent. While Lean doesn't enforce that a Monad instance obeys these laws, it has a separate type class called LawfulMonad which does require Lean proofs; this is useful for Lean's main use case - proving theorems about programs, expressed through its powerful type system. But this is a topic for another day. Examine the value of an Option If it's none , return none without proceeding Otherwise if it's some result , continue the computation with result Take a value wrapped with potential side effects Take a computation that takes this value and may produce additional side effects Combine the results into a final wrapped value It takes the current state, which for our use cases is an association list carrying values for all defined variables. It returns an optional result which is a pair of some value (in our case, the result of the computation) and an updated state.

0 views

Claude Code token cost explorer

I am experimenting with involving subagents more in my LLM coding agent workflow. I discovered that subagents make it more difficult to diagnose token usage in Claude Code, because the regular command only breaks down context usage for the main conversation, not for the subagents. I tried some existing tools like and , but they weren’t able to give me the sort of breakdown into specifics I needed to optimise my usage. Thus, I shamelessly had Claude Code whip up a tool that gives me a better view of its token usage. This is vibecoded in the true sense of the word – I have barely looked at the code – but I’m okay with that becuase it is not critical infrastructure and it does what I need it to. If you want to know how to get more out of your Claude Code sessions without paying more for it, here’s how you can find out. First, open the context cost explorer in your browser. Everything happens locally on your machine, so none of your transcript data leaves your computer. If you’re the paranoid kind, you can verify by opening the network tab in your browser and reading in a non-sensitive session and seeing that nothing funny happens. Then follow the steps below, or use your own analytical ability. (Continue reading the full article on the web.)

0 views
James Stanley 3 weeks ago

How to make a CNC plasma cutter with high-frequency start

The issue with high-frequency start ("HF start") on plasma cutters is that igniting the pilot arc creates an enormous amount of electromagnetic interference which causes problems for nearby electronics, in particular tending to disconnect the USB connection to your CNC motion controller. You can solve this by talking to the motion controller over WiFi. This is my machine in its temporary location on the workbench: If you still need to acquire a plasma cutter then I obviously recommend trying to get one with "blowback start" instead of "HF start" so that you don't have to worry about it. In acquiring a machine with HF start I made an error. But I got it to work anyway, so if you already have an HF start machine and you want to use it for CNC, you might be able to do the same thing. I kind of wanted a CNC plasma cutter because I have recently spent lots of time and end mills making planar parts like this for my cyclecar at excruciatingly low feed rates and depths of cut: So I started placing some bids on eBay and accidentally won a Parkside PPS 30 B2 for £80: The seller stated that he bought it from Lidl on a whim but then realised it needed a compressor and he didn't have one. If I had done my research I would not have bid on a machine without blowback start, but here we are. So when it arrived I set it up on the garage floor and tried to run my 6040 CNC router while lighting the plasma arc. As you might predict, I couldn't get it to work. Most of the time lighting the arc would disconnect UGS from Grbl. But serendipitously I was running a test program that had a small number of very long and very slow movements, which meant I had several minutes of motion left in Grbl's buffer, and I noticed that even though UGS got disconnected from Grbl and was totally broken... Grbl was still moving the machine! It was still following my gcode perfectly. So the issue isn't that the HF start actually prevents Grbl from working, it's just that it disconnects the USB serial connection . Solution: use FluidNC on an ESP32 board and talk to it over WiFi. FluidNC is Grbl-compatible but suitable for more modern microcontrollers. Charlie suggested talking to the controller over fibre optic, which would probably work even better than WiFi but is more faff to set up. Annoyingly, ESP32 outputs are 3.3v instead of 5v. I made up a breakout board for an Arduino Nano ESP32 on a piece of stripboard with a 74HCT245 abused as a level-shifter on the outputs and this was sufficient to provide 5v output from 3.3v input, unsure how legit this is. You can see my custom breakout board in here: I initially experimented with some small stepper motors with A4988 drivers, left over from when I dismantled my i3 clone 3d printer , and I think these would have been fine. But I also had some spare Leadshine easy servos from the unfinished CNC mini mill project I bought years ago. I didn't think the Leadshine servos would work because I thought the interference would confuse the encoder input, but I tested them and they seemed fine. And they're more powerful and better so I used them. But for a plasma cutter I really don't think fancy servos are necessary, the cutting load is basically zero, it's just a glorified pen plotter. The Leadshine documentation says they need at least 18v, but I only had a 12v power supply lying around so I tried it and it seems fine. I did subsequently connect the alarm output from the servo to an input on FluidNC and it kept falsely triggering every time the arc started (sigh) so I am running the servos without the alarm input. That's no worse a position than I would have been in using open-loop stepper motors anyway. My motion platform is made out of box section steel and 3d printed parts: With GT2 belts left over from the same 3d printer, and printed pulleys. The bigger of the two orange parts was a 36-hour print and used 700g of material, that's my biggest ever 3d print. All printed in ABS-GF on Bambu Studio "strength" setting. The "linear rails" consist of 608 bearings riding directly on the steel box section. I didn't make any of them adjustable but I should have done because it has slightly more play in it than I would prefer. Again this would be nowhere near adequate for a router but for a plasma cutter I think it should be fine. (The aluminium foil wrapped around the torch lead was a shielding experiment from before I was using FluidNC, it didn't help, I just haven't taken it off yet). I need to get a larger water tray. To fire the arc on the plasma cutter, it has a 2-pin GX16 connector which you normally connect to the torch trigger. I connected it to a relay operated by FluidNC so that I can turn it on/off with M3/M5. (But note you need to give FluidNC a non-zero "spindle speed" else M3 won't do anything, so get used to "M3 S1"). So at this point I have a working CNC motion system, with an HF start plasma cutter that I can fire from CNC control. Time to cut something out? Unfortunately I have no plasma cutting experience and (story of my life) it's harder than it looks. I messed around with the air pressure, current setting, and feed rate, and I just couldn't get a clean cut in 4mm steel. That's disappointing because the machine documentation says it can cut through up to 12mm steel. But I tried a piece of 3mm steel and my first test cuts worked a lot better, so I tried to cut out a heart shape. (I got ChatGPT to write the gcode for this). It blew the fuse in the extension lead 3/4 of the way through because I foolishly had the compressor and plasma cutter plugged into the same one. D'oh! I moved the compressor to a different extension lead and then it worked first time, albeit with a lot of slag on the underside of the cut: I cleaned this off with the angle grinder and you can see that along one axis my machine is cutting nice straight sides but on the other axis it is quite badly bevelled: I am going to replace the consumables in the torch when they arrive, and failing that I am going to make the torch clamp angle adjustable, and I expect I will be able to get rid of the bevel, but I don't know if the combination of the excessive bevel and the poor cutting performance are evidence that my machine is actually faulty. This may be the real reason it was sold on eBay after hardly any use. I have subsequently had my 16 amp breaker trip a few times while cutting so I may want to either find a way to run the compressor on a different circuit or else upgrade the circuit I have. These are the switches and lights on my control cabinet: Though the "alarm" light is now surplus as the servo drives can no longer trigger it. The "torch" light comes on when FluidNC is asking for the relay to turn on, but the relay doesn't actually turn on unless the switch is set to "enable". This is so I can ensure that even when I'm fumbling the gcode the torch can't light unexpectedly. And btw I obviously don't have an emergency stop button on this machine, but I can still toggle the torch off, or switch the power off, and there's no world in which I'm running a plasma cutter unattended, so I'm not very worried about it. I also don't have limit switches. I don't really understand why people bother putting limit switches on DIY machines (unless they have an automatic tool changer or whatever). What's the benefit to having a global coordinate system? You need to set up work coordinates for every job anyway. I don't have limit switches on any of my machines, but on this one in particular I expect limit switches would falsely trigger whenever the HF arc starts. So what have we learnt about making CNC plasma cutters? you can use a HF start machine if you talk to the motion controller over WiFi you don't want any inputs to the microcontroller, including limit switches, emergency stop, alarm inputs, USB serial if you make linear rails out of box section and ball bearings then make some of them adjustable so that you can take out the play GT2 belts are adequate 3d-printed structure is adequate getting correct cutting parameters is not any easier than it is with milling unfortunately, so still lots to learn Leadshine easy servos appear to work with 12v supply even though the documentation says they need at least 18v I made a custom gcode sender to talk to FluidNC because I wanted it to work differently to any existing ones and coding agents make software cheap, but I'm pretty sure UGS can talk over WiFi so it is not necessary to make your own sender. If you make a CNC plasma cutter using information from this post then please email me and show me, I'd love to hear from you. you can use a HF start machine if you talk to the motion controller over WiFi you don't want any inputs to the microcontroller, including limit switches, emergency stop, alarm inputs, USB serial if you make linear rails out of box section and ball bearings then make some of them adjustable so that you can take out the play GT2 belts are adequate 3d-printed structure is adequate getting correct cutting parameters is not any easier than it is with milling unfortunately, so still lots to learn Leadshine easy servos appear to work with 12v supply even though the documentation says they need at least 18v

0 views
neilzone 3 weeks ago

Automating renewal of Let's Encrypt certificates with Home Assistant OS

I had an alert from my monitoring tool that the Let’s Encrypt TLS certificate for my Home Assistant OS installation had expired. The answer lay in the documentation for the Let’s Encrypt app : Certificates are not renewed automatically by the plugin. The app has to be started again to renew certificates. If the app is started again, it checks if the certificates are due for renewal. This is usually the case 30 days before the certificates’ due date. If the certificates are not due for renewal, the app terminates without changes. If the certificates are due for renewal, new certificates will be created. There are multiple ways how the app can be started to check/renew the certificates. One way to automate the certificate renewal is to configure a Home Assistant automation to restart this app every night via the Supervisor app restart action. My automation looks like this: I can see in the log for the Let’s Encrypt app, and the log for the automation, that it ran as expected so, fingers crossed, no more TLS certificate issues…

0 views
Nelson Figueroa 3 weeks ago

How to Serve Your Hugo Site on a Local Network

Sometimes it’s useful to check how a Hugo site looks on a real mobile device before deploying. That requires serving the site on a local network so other devices on that network can access it. Here’s the command to serve a Hugo site on a local network: Then open on your phone. The site should load and work as expected. The option is necessary because Hugo binds itself to by default, which means no other devices except the one serving the site would be able to reach said site. The option is needed so that links generated in the Hugo site all point to the local IP address the site is being served from. Otherwise, the links will be generated with . Note that if you’re on public wifi this command may not work due to client isolation! If you need to get your local IP address, here are a few methods depending on your operating system. On macOS, try running: If it returns nothing, try instead. On Linux, try this command. The first address is usually the one you need: On Windows, try this command. Look for “IPv4 Address”: I felt the need to write this post because I tried this command that worked for loading the home page on my phone, but everything else was broken. I couldn’t tell if I was doing something wrong or if there was something wrong with Hugo. With this command, the home page loaded on my mobile device on the same local network, but clicking on any links to other pages of the site resulted in a connection error. That’s because the links are all generated with , which means the device tries to connect to itself and the Hugo server is running on a separate device. Using is necessary to get past this.

0 views
Takuya Matsuyama 3 weeks ago

Effective Neovim setup for agentic coding towards 2027

Hey, what's up? It's Takuya here. In this article, I'm going to share my new Neovim setup, which I built from scratch with an AI agent. Watch the video tutorial on YouTube: My Dotfiles is here: In the previous setup I shared in 2023 , I used LazyVim to avoid maintaining plugins, and it's been working great. Thanks to the LazyVim community, I could easily keep my plugins up to date and tweak the settings. But the more I customized it, the more unstable it got. Fixing errors after every LazyVim update was kind of annoying. Meanwhile, recent Neovim releases have added a lot of built-in features that used to need plugins: So I decided to build a fresh setup on top of them. The agentic coding paradigm shift has arrived, and I've adapted to an agentic workflow . These days, I mainly use Neovim to review code , rather than to write it by hand. To be honest, I don't know how long I'll keep using it, since workflows are changing so fast. But I thought it would be interesting to share my current setup. Tweaking a Neovim config is super easy now, because you just tell your agent what you want. So instead of writing Lua, I wrote a spec of my config in English on Inkdrop , and fed it to my agent step by step via the MCP server . The spec describes what I want and why , not how . The agent figures out the Lua. I gave the agent these rules: I mapped to . Below is the whole spec, step by step. Feel free to copy it and feed it to your own agent, and tweak it to your taste. I started by telling the agent where the spec lives: Neovim 0.12's experimental ui2 handles messages. It's turned on at the end of . tiny-cmdline.nvim shows the command line as a floating box, centered left to right, 20% from the top. It's set up in . A custom tabline in , with no plugin. lualine , one global bar, theme . snacks.nvim provides the notifier, indent guides, statuscolumn, and word highlighting. Later steps turn on more of it, like the picker and the lazygit integration. The snacks.nvim picker. oil.nvim replaces netrw and shows hidden files. nvim-treesitter , main branch. Mason + mason-tool-installer install on start, and never auto-update: nvim-lspconfig supplies defaults. For example, typing in a TSX file: Per-server settings live in . Neovim 0.12 merges these automatically, so there's no setup boilerplate. blink.cmp , version , preset: Enter accepts. conform.nvim formats on save with a 1000 ms timeout, falling back to the LSP. Since I mostly review code written by my agent now, this is the part of the setup I use the most. gitsigns.nvim with defaults. mini.diff from my fork ( , branch ). codediff.nvim for side-by-side diffs and history. I use it when my agent makes a lot of changes in the codebase. opens lazygit in a float through snacks.nvim , with the theme synced and the active border in the WarningMsg color. Pressing on a file closes lazygit and opens the file in the window it was launched from, through and . Lazygit's own config lives in , outside the Neovim config. snacks.nvim loads it together with the synced theme. It holds: copilot.lua with auto-trigger on, enabled in Markdown and help too. The keys work in insert mode: These are small helpers for passing context from Neovim to an agent. To try the setup in a real agentic workflow, I built a keymap cheat sheet website with Vite+ and my agent. To show how I use this setup day to day, I built a tiny app with it: a one-page cheat sheet of every keymap in this config. I followed Inkdrop's note-driven agentic coding workflow. Each task gets one note, which works as a shared place for me and the agent. I write the requirements, and the agent fills in the rest of the plan. I created a Waku app in : I created a new note and applied the built-in Implementation plan note template with . My requirements were just two lines, plus a link to the spec note: I copied the note link and passed it to Claude Code: Claude Code reads and updates the note through the Inkdrop MCP server, using the skill. Before writing the plan, it read both the spec note and my actual Lua config. Then it asked me about the decisions only I could make: It recorded my answers in Decisions Needed and broke the work into three phases: Reviewing a plan is much cheaper than reviewing code, so this is where I spend my attention. I told Claude Code to work on it, and it implemented all three phases in 1 minute 18 seconds . It checked off each phase in the note's Status section as it went. The cheat sheet has 7 sections and 59 keys, with dark mode. This is where the Git part of my setup comes in: After the review, I switched the project to pnpm and committed it. Finally, I pasted a screenshot of the working page into Claude Code. It filled out the note's Outcome and Follow-up sections. Now the note records what was built and why, including the follow-up to fix the typo in my spec. The finished note: Create a keymap cheatsheet for Neovim setup Writing code is very cheap now, so writing the config as a spec in a natural language felt natural. It's English and Japanese for me. The spec is readable, it keeps the why next to each setting, and I can rebuild or tweak the setup any time by just telling my agent what I want. The full spec is above, so feel free to copy it and make it your own. I hope it's helpful for your Neovim setup. Thanks for reading/watching! : a built-in plugin manager and : LSP setup with almost no boilerplate ui2: a new message UI : reloads Neovim and restores the session Write a step of the spec. Ask the agent to implement only that step. Reload Neovim with and check the behavior myself. Review the diff and commit. Read the spec and implement only the step I name. Add nothing beyond it. Check your work lightly: Neovim starts without errors: New keymaps exist: Don't build test projects or drive the UI. I check the behavior myself after the restart. Neovim restarts in the same terminal and restores the windows, tabs, and buffers. Save first with . Unsaved buffers block the restart. Or use to discard them. After a step that adds a plugin, shows an install prompt. Confirm it. Run the agent in a separate terminal split, not in a inside Neovim, since the restart kills it. Neovim 0.12 or newer. The config relies on built-ins that landed in 0.12: , , and the ui2 message UI. A Nerd Font. I use PlemolJP Console NF. Icons appear in the tabline, statusline, completion menu, and file explorer, so a plain font shows boxes. The config folder is a git repository. : the config root folder : enables for faster startup, then requires these files directly, in order: , assigned to the global : my config lives here : shared helpers : returns a table of helper modules, empty for now. Later steps add modules like , exposed as . : plain Neovim settings, one file per name above : installs every plugin in one call, then requires each group file Each plugin group gets its own file next to it (e.g. ), which configures its plugins with . : every keymap that uses a plugin, required last so all plugins are set up first. Group files hold no keymaps. Lua files are indented with tabs, formatted by stylua with its defaults. Leader and local leader are Space . Mouse is off . Keyboard-only. Clipboard is , so yank and paste go through the system clipboard. Indent is 2 spaces : , , and are all 2 and are on counts as part of a word, so is one word. Fits CSS classes and kebab-case names. Hybrid line numbers: + on , so the cursor line shows its real number. on . No wrap, 10 , 8 . always on . Text doesn't jump when git or diagnostic marks appear. 0 and one global statusline ( 3 ). Maximizes vertical space. Rounded borders on every float ( ). Popup menu: at most 10 rows, slightly see-through ( 10 , 10 ). Matching brackets flash briefly ( on , 2 ). on , so the terminal tab shows the file name. Diagonal fill in empty diff areas. + on : case-insensitive until a capital letter is typed. adds , so searches subfolders. completion: is skips , , , , , and off . Persistent undo ( on ) lives in . Undo survives closing the file. Swap files only get in the way. Snappier timing: 300 , 500 , 0 . Faster CursorHold events, and key sequences resolve without lag. Edit , , reopen it, then New splits open below and to the right . Folds come from Treesitter , with 99 . Everything starts unfolded, and folds can still be closed by syntax. , then / inside a function Short messages: corner popup up to 30% of the screen tall, gone after 5 seconds . Long output (errors, , , shell commands, progress): a scrollable pager up to half the screen. Search count, search pattern, completion, completion list, and confirm prompts stay in the command line. Output of a command I type goes to the command line too, whatever its kind. It expands over the bottom of the screen until the next key. moves it into the pager. With 0, the command line needs somewhere to appear, and near the top is where the eyes already are. Yanked text flashes briefly. Only the active window shows the cursorline. closes every hidden buffer, except unsaved ones. solarized-osaka , style, transparent background. The terminal's blur shows through, and the palette matches the Ghostty theme. mini.icons , also mocking nvim-web-devicons . One icon source for every plugin. Shown only when there are 2 or more tabs. Each tab shows the active window's file name with its icon, padded with 3 spaces, between slanted separators. Both edges slant outward going down, so each tab is a trapezoid, wider at the bottom: Colors from the solarized-osaka palette: Active tab: bold base4 text on yellow Inactive tab: base0 on base02 The icon takes the tab's text color. The separators take the tab's color on a transparent background, and so does the empty area after the last tab. Names longer than 20 characters are cut to 17 plus . Unsaved tabs show before the icon. Terminals show and empty buffers , with no icon. The project root is found by searching upward for , , , , , , or . Refreshes on cursor move and macro start/stop. The recording indicator replaces the hidden command line. The result would look like: incline.nvim shows a filename tag with an icon in the top-right corner of each window, plus when unsaved. With a single global statusline, each split still needs to say which file it holds. The tag hides when the cursor reaches its line. Words : the word under the cursor is highlighted everywhere. / jump between occurrences. It needs a language server, so it works after step 5.1. Smooth scroll is off . Scrolling should feel instant. The directory is a buffer, so renaming, moving, and deleting files is plain text editing followed by . Columns: icon, permissions, size, modified time. Renaming a file asks the LSP to update imports and saves those edits automatically. In the tabline (2.3), an oil tab shows its directory ( ) with no icon. Paths longer than 20 characters are cut from the left to plus the last 17 . Ensures 38 parsers: astro, bash, c, cmake, cpp, css, diff, fish, gitignore, go, graphql, html, http, java, javascript, jsdoc, json, lua, luadoc, luap, markdown, markdown_inline, php, printf, python, query, regex, rust, scss, sql, svelte, toml, tsx, typescript, vim, vimdoc, xml, yaml A FileType autocmd starts highlighting and Treesitter indent whenever a parser exists. runs on the event. Parsers stay in sync with the plugin version. todo-comments.nvim highlights , , and the like, with defaults. nvim-highlight-colors paints hex, rgb, hsl, ANSI, and CSS variable colors as backgrounds. Tailwind is off. Neovim's LSP document colors are turned off, so colors aren't painted twice. Servers: lua-language-server, vtsls, eslint-lsp, oxlint, tailwindcss-language-server, css-lsp, rust-analyzer, copilot-language-server Formatters: prettier, prettierd, oxfmt, stylua, shfmt Servers are turned on with : eslint, oxlint, lua_ls, cssls, vtsls, tailwindcss, rust_analyzer. Every server gets file-rename support ( / ). Underlined, not updated while typing, sorted by severity. Inline text: , with the source only when there are several. Gutter icons come from the shared icon set. The error is underlined, with inline and an icon in the gutter. The line also has a "never read" hint, but the gutter shows the error icon, since they are sorted by severity. oxlint flags the unused too, so each message shows its source ( , ). vtsls : Uses the workspace TypeScript and updates imports on file move. Server-side fuzzy matching and function-call completion. Inlay hints are short: no variable types, 30 characters max. lua_ls : knows the Neovim runtime, shows param-type hints, silences a few noisy checks. cssls : ignores empty rules. oxlint : starts with . Every language server from 5.1 also gets blink.cmp 's completion capabilities. Auto-brackets after functions. Docs pop up after 200 ms . Menu items are colorized by Treesitter, with kind icons from the shared icon set. Ghost text is off . Copilot already shows inline suggestions, and two ghost texts would clash. In the command line, the menu opens by itself for commands only, with nothing preselected. mini.pairs with defaults, in insert and command mode. oxfmt runs only when the project has an oxfmt config, like or a Vite+ . Projects using prettier keep their own formatter. turns format-on-save off or back on for the current buffer, with a notification. The command lives in . The fork groups changes into whole hunks, the way shows them. Explorer: tree view, 50 columns wide, opens files as the cursor moves, shows +/- line stats. Compact mode: only changes plus 8 context lines, with folds synced across panes. remembers the current window. quits lazygit, focuses that window with , then opens the file, so the cursor ends up in the file. Not a new tab and not a nested Neovim. Outside Neovim, it just runs . The edit command is written in fish syntax. Diffs render with . Mouse events are off and auto-fetch is off. in the files panel commits with commitizen ( ). gitlinker.nvim : copies a GitHub URL for the current line, or the selected range. Notes and docs benefit from suggestions as much as code does. Requires once. On macOS, the terminal needs Option as Alt. Both show the copied text in a notification. Pasting the path into an agent's prompt points it at the exact line. The template starts with Requirements and Related notes sections for me to write. The rest is a skeleton for the agent: requirements restatement, current state, decisions, phases, risks, status, and outcome. Instructions for the agent live in and blocks. Inkdrop strips them from the created note, and the agent reads them from the source template. It listed where every keymap is defined, with references. It found mismatches between the spec and the config. e.g. the spec had a typo, instead of , for finding files. It decided to trust the config over the spec. Keymap data Page and table component Remove starter leftovers : lazygit, to skim the whole diff : codediff, to walk through each changed file side by side : the mini.diff overlay, to see the changes inside a file

0 views
Maggie Appleton 3 weeks ago

Fortune Telling and Speculative Design

Practical tools for design engineers to explore possible futures through speculative design

0 views
Kev Quirk 4 weeks ago

How I Customised Pure Blog for This Site

A few people have reached out to me to ask how I did X, or Y with my site, so I thought I'd talk about the customisations I've made to this site, and how they work. Firstly, this site runs on Pure Blog , a CMS that I've been building over the last year or so. As it's matured, I've added features that allow more advanced users to do clever things without having to fiddle with the core platform. This means that people generally shouldn't have to fork the project and should continue to get all the new goodness as I release it. This site is no different. I haven't done anything clever that Pure Blog can't do out of the box - everything is documented so by reading the docs and using a bit of creativity, you can do quite a lot with this plucky little CMS. I'll link out to the appropriate docs as we go through this post. Ok, so what customisations have I made? This is going to be a fairly long post, so I'll list them here with links to each header so you can jump around and read the parts that interest you. If you want to see specific code examples for any of these customisations, feel free to contact me . I have three custom post types on this site - notes , links , and books . Notes are used as short-form social media type posts, links are links to other blog posts that I've enjoyed, and books are short reviews of the books I read. Each has their own layout and in the case of notes, they have a different view on the homepage too. To do this I've created a custom partial, but we will come to that later. I could just use the default post type for all these posts, but I prefer to have a customised UI at the back-end for each. Here's what books and links look like in my editor: Notes are a little different as I use a custom page for them that only I can access. This looks more like a social media post window than a blog post window: Read the custom post layout docs ➡ I like to think of hooks as little tripwires that are set to go off when certain conditions are met. For example, something happens when an image is uploaded, or a new post is published. They're extremely useful and I have a number of them on this site: Read the hooks docs ➡ Beyond custom post types, Pure Blog lets you drop PHP files into . These can either override default pieces of the site (like navigation or post footers), or serve as entirely bespoke standalone pages, like my quick-publish notes screen, or the terminal 404 page . Here's a full list of the templates and partials used on this site: Read the layout partials docs ➡ I've replaced the default feed with one that allows for filtering on post type. So one feed file, 5 feeds - one for each post type, and a fifth for everything. My custom feed template allows you to visit for everything, or (e.g. ) for the posts of that particular type. This custom feed file lives in and I then used redirects to redirect the default URL to . All the feed URLs are available here . I use a self-hosted instance of Sendy to send out email "newsletters" whenever I publish a new post. These emails always contain the entire post, so people can read my content from their inbox if they wish. Because I write notes much more frequently than long-form posts, I let readers choose what they receive: everything, long-form content only, or notes only. To make that work without sending people through clunky third-party forms, I wrote a custom server-side handler ( ). When someone submits the form on the subscribe page , the handler: This not only helps segregate the emails people receive, but it has also had a dramatic effect on spammy sign ups. Which, if you've ever run a newsletter, you will know is a common problem. Pure Blog allows you to add your own PHP helper functions for all kinds of things. On my site, I only have 1 function defined: which transforms fractional score strings in my book posts (e.g. ) into accessible star glyph strings (e.g. ). I just think that looks far nicer in a post than . But how is this star rating accessible? Well, it's rendered on the front-end like this so screen readers can parse it: Read the custom functions docs ➡ I don't do anything magical with the design on this site. I use the Victor Mono font , and around 850 lines of CSS, which I've added to the custom CSS field within settings. Combined with the custom , and files above, it gives me everything I need to customise the site from the default look to what you see now. I have a custom theme palette that I've defined too, also in settings. The colours used can be found at the bottom of my colophon . Read the design customisation docs ➡ One of the most powerful things about using a static site generator is the ability to use data files. With data files you can have a structure data file, like YAML, that contains repeated data, which can then be looped through on the front-end to render content. I really wanted Pure Blog to be able to support data files, so I added support very early on. Personally, I use two data files on this site: Data files are fantastic as they reduce the amount of repetitive code you have to write. Instead of typing , after , after manually, you write your once, then loop through it with a data file and Pure Blog does the rest. Read the data files docs ➡ The final thing I customise is my file. There's a number of things I do to the standard Pure Blog file to either redirect URLs, or protect various locations: This ended up being an even longer post than I anticipated, but hopefully it shows just how much you can bend Pure Blog to your will, by design . None of this requires hacks to the core code, or maintaining your own fork. Everything you see here is achieved using Pure Blog as designed: settings, custom CSS, hooks, custom layouts, and partials. Because all these files live inside , , and , I can upgrade Pure Blog the moment a new release drops without worrying about overwriting my site's bespoke features. That was always my goal with Pure Blog - a super simple, distraction-free blogging platform out of the box, with enough flexibility under the hood for tinkerers (like me!) to build whatever they want. If you're running Pure Blog and have built your own customisations, or if this post inspired you to try something new with your setup, hit the reply button below, or find me on Mastodon. I'd love to see what you've done with it. Thanks for reading this post via RSS. RSS is ace, and so are you. ❤️ You can reply to this post by email , or leave a comment . Post layouts Hooks and automations Templates and partials RSS feed enhancements Newsletter subscriptions Functions and helpers Design and typography Data driven pages .htaccess rules Final thoughts Email Obfuscation ( ) : Scans rendered content and encodes the site email address into hexadecimal HTML entities to protect against scrapers. This has been pretty effective at reducing spam - I wrote more about this feature in this post . Post Sanitisation & Metadata Preservation ( ) : Automatically generates date/time titles for new notes. Normalises layout values by stripping quotes (turning layout: "notes" into layout: notes), ensuring posts written in external editors like Obsidian don't break layout checks. Preserves in post frontmatter when saving via the admin interface so the Mastodon card at the bottom of every post continues to work. Image Optimisation ( ) : Automatically resizes images exceeding 2560px width whilst maintaining aspect ratio, also converts them to lossless WebP, and cleans up original unoptimised files. Mastodon Cross-Posting & Syndication ( ) : Automatically crossposts all published post types to Fosstodon via the Mastodon API. Notes posts are cross-posted with full body text and media attachments (uploaded to Mastodon's media endpoint). Articles, links, and books are crossposted with their description and permalink URL. Captures the returned Mastodon status URL and automatically persists into the post's frontmatter which is then used for the Mastodon card at the bottom of every post. Custom Font for Open Graph Images ( ) : Makes dynamic Open Graph image generation to use my custom font. (partial) : This replaces the default and adds post-type filter buttons, preserving query parameters across pagination. It also displays notes in full, while other post types show only the title and excerpt. (partial) : A customised version of the default file from Pure Blog. On top of the default tag list and post pagination, this version adds the obfuscated "Reply by email" button, a client-side Mastodon conversation card displaying live stats (favourites, boosts, replies) as well as a link to the post on Fosstodon, Pure Comments integration, and a subscription call-to-action. (template) : Dedicated discovery hub combining Pure Blog's full-text search with an alphabetical, weighted tag cloud showing post frequencies. (template) : An interactive metro map that lists all of the pages on this site. There's also an option to see the pages as a list. (template) : My quick-publish admin screen for composing and publishing short-form note posts. (template) : Dashboard for tracking the 100 Days to Offload challenge streaks in batches of 100 posts. (partial) : This replaces the default template in Pure Blog. It adds a custom layout, as well as 404 handoff ( ) to render the custom template without modifying core Pure Blog files. (template) : A fun interactive terminal-styled 404 page with custom commands that include goats! (template) : Endpoint that resolves and redirects visitors to a randomly chosen published post . Checks a simple verification question ("What is Kev's surname?") to keep bots at bay. Silently discards submissions that trigger a honeypot field, or exceed IP rate limits. Subscribes the user to the correct Sendy list(s) via Sendy's API in a single click. which is then used to render my blogroll page . which is used for my projects . Admin Access Restriction : I restricts access to specific allowed IP addresses. Legacy URL & Feed Redirects : 301 redirects mapping historical and URLs to clean root and routes that Pure Blog uses. Redirects for legacy feed and social endpoints ( , , , , , etc.) to or to make sure the feed URLs from various versions of this site don't break. Route Rewrites : clean URL routing for all my RSS feeds so they have simple to share URLs.

0 views
Abhinav Sarkar 1 months ago

An LC-3 Disassembler in Haskell

LC-3 assembly is an educational programming language. It is simple enough that complex programs can be written directly in it without needing a compiler, and thus it is often used in teaching assembly. An LC-3 textual assembly program is compiled to a binary object file by an assembler, and then executed by a virtual machine . Writing a virtual machine for LC-3 is a fun little exercise. However, in this post, we implement a disassembler for compiled LC-3 binaries back to textual assembly programs. This post was originally published on abhinavsarkar.net . LC-3 has a simple instruction set with only 18 instructions. It works with eight 16-bit registers (numbered from 0 to 7), and 16-bit addressable memory. LC-3 instructions are also 16-bit, with first four bits used for opcodes, and the rest for instruction arguments. There are instructions for doing arithmetic and bitwise logical operations, conditional branching, executing subroutines, loading from and storing to memory, handling interrupts and doing system calls. Some of them take source, destination, and base registers as arguments ( , , and respectively in the diagram above). Some other take integer immediate values, program counter, and address offsets ( , , and respectively in the diagram above). The instruction take a code for the syscall to execute. Notice that we count the bits from right to left, zero-indexed. When written in the textual assembly format, we use mnemonics for the opcodes and syscalls. The eight registers are written as to . The instructions can be labeled and referred from other instructions using them. Let’s start by looking at a simple LC-3 assembly file: As seen above, the assembly file can also contain assembler directives such as , , , , and . Quoting the docs: We assemble the program with the assembler, and then execute the resultant binary with the VM 1 : It works as expected! As much fun as it would be to write an assembler and a VM, in this post, we don’t assemble or run LC-3 programs, we disassemble them. We don’t care what the instructions do, only how they are encoded. Unlike an object file generated from X86 or Arm assembly, an LC-3 object file does not contain section tables separating code from data, symbol tables indicating function and variable names, relocation information, or debug symbols 2 . It contains only raw binary instructions and data that are freely intermixed in a single address space. This is made necessary by the fact that LC-3 has only 16-bit addressable memory. So data blocks and read-write memory addressed from code has to be within \(2^{16}\) bits or 8192 bytes of the code addressing it. Consider these bytes: A disassembler looking only at binary code has no context. A 16-bit word that decodes perfectly as a legal instruction may actually be a character, a part of a packed string, a number/byte literal, or a memory address. We need context to decode correctly, so the disassembler works in multiple passes: Let’s go over the disassembler part-by-part. First, the imports: We use the vector library for instruction lists, and the monad for manipulating them mutably. We also use bytestring for doing binary IO. Here are the data types we use: The type enumerates the eight LC-3 registers. The type represents the condition codes used for conditional jumping, which are negative, zero and positive. The type enumerates the eight standard LC-3 trap codes used for doing IO and halting the programs: The type is the heart of the disassembler. It doesn’t represent only the real LC-3 instructions, but also adds more constructors that are useful for disassembling: This representation lets us handle ambiguous data. Also note that we capture the raw bytes in some instructions like and . Finally, represents entire 16-bit binary code, and is the type for representing an LC-3 object file with an origin address and the binary code. Since we work a lot with bits here, we define some patterns to make it easier and less error-prone: Each LC-3 instruction has a 4-bit opcode, and many have 3-bit register or flag fields. So, we define two new types: (3-bit) and (4-bit), with pattern synonyms for exhaustive pattern matching. By defining patterns through , we map directly to the ISA specification. For example, visually shows the bit pattern for the opcode. GHC’s pragma enforces exhaustiveness, so no fallback cases are needed. The smart constructor functions and take the least significant 3 or 4 bits of the passed 16-bit parameter respectively, and return respective typed bits. First, we decode the registers and trap routines: We see the bit patterns in action here. The trap routines codes are as defined in the ISA. Next, the function extracts the opcode nibble (the most significant four bits), and decodes the arguments by calling , which dispatches on the opcodes: Now, we go over decoding of each instruction one-by-one. has two variations: one that takes two source registers, and another that takes one source register and one immediate value. First, we extract and decode the destination and first source register. Then depending on the sixth bit, we either decode the second source register or the value. The value is sign extended by calling the helper function . When decoding the second register, if we find that the forth and fifth bits are not , that means this is not a valid instruction. In that case, we return the raw bytes wrapped in the constructor, because the malformed instructions are far more likely to be data that happens to have an opcode prefix. Capturing them as lets us treat them as data in the later steps. This same pattern is used in decoding other instructions as well: extract and decode registers, flags, and values, and check fixed bits for validity. If valid, return the decoded instruction, or else the raw bytes. The instruction has exactly same format as the instruction, except for the different opcode. To decode the instruction, we decode the registers and check for the fixed bits. Decoding the instruction requires us to decode the condition flags, which is a straightforward mapping from their bit patterns. In case no flags are set, the instruction is likely to be an ASCII character instead with the high byte set to , so we add a special check for that. Note that we capture the raw byte in the output instruction, to be used later. The and instructions have same opcode, but differ in the bits 7–9, which are set to for . Note that the function also checks for the fixed bits, failing which it returns a instruction. The and instructions have the same opcode, differing in the 12th bit. Decoding the , and instructions is a straightforward matter of decoding their registers and offsets. Notice that the and instructions also capture the raw bytes. Decoding the , and instructions is similar to the , and instructions. Again, straightforward decoding of register and offset: The instruction is a constant byte pattern. Decoding the instruction requires us to decode the trap routines. We don’t care about the rest of the bytes if the opcode is for the instruction. That’s it for decoding the bytes to instructions. But that was the easy part. Up next, we get into the heuristic operations. , the function below, is our main entry point to disassembling the binary code. It runs in the monad so that we can work with a mutable vector of instructions. First we allocate the mutable vector, and then we do a basic disassembly of the binary code into it by calling . After that, we go over the disassembled instructions in , and use heuristics to guess better ones. Finally, we clean up by combining the character data and inserting the labels, and return the final immutable vector of instructions. is where our first heuristic is applied. We go over the binary code vector element-by-element, decoding each raw word using the function we wrote earlier. But we don’t stop there, we do an additional check. If a freshly decoded instruction is one of some instructions, preceded by some particular instructions, we use it to further disassemble some data. We recognize these three patterns: These patterns are very common and almost standard, so we can confidently use them for detecting character and string data. Also, note the checks in the beginning of that prevent already disassembled char/string data from being overwritten. At this point, we have decoded the instructions and char/string data. But there are more possibilities of improving the disassembly quality. In this pass, we revisit the decoded instructions and correct them based on their targets and neighbours: runs till a fixed-point is reached, that is to say, till the instructions stop changing. It does a backward sweep with the function, then a forward sweep, then repeats until no changes occur. We do this because a rewrite can create conditions for another rewrite. Doing this till fixed-point is safe because of the way is written: it only changes code-like instructions to data-like instructions, and never the other way. That makes the whole pass monotonic, causing it to eventually terminate. We do the sweep in both directions to make the changes order-independent. Next up is : The idea behind is that, certain instructions that point to other instructions are likely to be data. Different instructions have different confidence levels for their target addresses, encoded as : below carries out the actual rewrites: The two helper predicates distinguish definite data and speculative data: checks for , , , and the original side of . checks for the speculative data alternative. Note how speculative data can cause neighbouring instructions to become data, but cannot alone cause a branch/call instruction to change, thus limiting speculation from spreading. After the previous pass the instructions become stable. We now process them to do some cleanups. First, we merge consecutive characters into strings: uses to walk the instruction list and combine: If a run is not -terminated, we revert the characters in it to . Finally, we insert the labels before the instructions that other instructions point to: We also change the pointing instructions to use the labels instead of offsets. This concludes the entire disassembly of LC-3 binary code. To finish off, we need functions to print the instructions and to read the binary files. is our top-level function that takes an object file and returns the disassembly as text: simply pretty prints each disassembled instruction and wraps the result with and directives from LC-3 assembler format. Here is the pretty printer: The instructions are rendered in the LC-3 assembly syntax. words become directives. values become with proper escape sequences. instructions are rendered with both interpretations: the speculated data form followed by the original instruction as a comment. This preserves ambiguity for human review. The helper pretty-printers: The registers are printed as – . Numeric values are prefixed with , and the escape sequences ( , , etc.) are properly encoded in strings. The trap routines are looked up by their standard codes and output as their names. After all we’ve been through, this is a piece of cake: Only important thing to note is to combine the byte pairs in the big-endian order. The function reads a binary file from STDIN, parses it, and disassembles it to STDOUT: Error messages are printed and the program exits with status 1 on failure. And, we are done! Let’s test it on the “Hello World!” program : Amazing! We assembled the disassembled program and ran it, and it produced the same output. The assembly is also pretty much the same. To make sure the disassembler works correctly, let’s run it on a the binary code for a larger program: lc3-fizzbuzz.asm that output the solution for the Fizzbuzz problem. It works perfectly. You can also see the word-wise diff between original and disassembled assembly below: Except for the data section at the end, the assembly is pretty much same other than the label names. Perfect! Building a disassembler for a format without metadata is a fun exercise. You have to find the patterns in the data, come up with heuristics, and use them to write your disassembler. You may need to go over the output multiple times to refine it. While the approach here is specific to LC-3, the principles generalize to other code/data separation problems in binary analysis and reverse engineering. The full code for this disassembler is available here . If you have any questions or comments, please leave a comment below. If you liked this post, please share it. Thanks for reading! I patched the VM to not print when halting. ↩︎ Most LC-3 assemblers produce .sym files containing the debug symbols. But we don’t use them for disassembling the binaries in this post. ↩︎ Actually, the ISA defines opcode as reserved for future use. ↩︎ Thanks for reading this post via feed. Feeds are great, and you're great for using them. ♥ This post was originally published on abhinavsarkar.net . Read more of my posts and notes . Introduction to LC-3 Problem in Disassembling LC-3 Decoding Instructions Basic Disassembly Fixed-Point Cleanup Postprocessing Pretty-Printing Reading the Binary Finishing Up First, we decode instructions that are unambiguous. Then, we use the context of the decoded instructions to speculatively decode the rest of the instructions/data. We repeat this till a fix-point is reached. Next, we clean up the data by combining bytes. Finally, we insert labels at the right places. to are the real LC-3 instructions. represents the one reserved opcode that the ISA defines as invalid 3 . is for capturing raw encoded binary data. represents a single character. represents a string, that is a sequence of characters. is a textual label used to annotate instructions that other instructions may jump to. It doesn’t exist in binary data, and is inserted by the disassembler. is a speculated instruction. It holds both the original instruction decoded from the binary data, and the guessed instruction depending on the context. followed by : This pattern loads a character at the relative into the registers and prints it. If we see this pattern, we know that the instruction at current index plus is a character. So we disassemble it immediately as a character in . followed by : This signals that the data at the relative is a null-terminated one-character-per-word string. So we disassemble it character-by-character till we reach the null bit in . followed by : This pattern is for a null-terminated two-characters-per-word string, so we disassemble accordingly in . , used for , : If the target is known to be data or does not exist, this instruction must be wrong, because these instructions are for jumping to code. Rewrite the instruction to . , used for : may or may not point to data. But if the instruction is in a neighbourhood that mostly has data, it is very likely to be data itself. Rewrite such instruction as , capturing both the data and instruction forms. , used for , , : The target doesn’t strongly indicate code or data. However, if is as well, the instruction is likely to be data if present in a data-heavy neighbourhood. In such case, rewrite as , otherwise ignore. a run of s followed by to become a single with the terminator, and a run of two-character entries followed by to become a single combined . I patched the VM to not print when halting. ↩︎ Most LC-3 assemblers produce .sym files containing the debug symbols. But we don’t use them for disassembling the binaries in this post. ↩︎ Actually, the ISA defines opcode as reserved for future use. ↩︎

0 views
Nelson Figueroa 1 months ago

Enums Can Be Enforced at the Database Level in PostgreSQL

PostgreSQL databases support having enumerated type (enum) columns so that the column only accepts one of a predefined set of values. I’ve worked with ORMs like Active Record from Ruby on Rails . Using Active Record, I could work with database columns that only allowed a certain set of values. I always thought that was only possible due to the ORM layer abstracting away these things, but that’s not the case. Enums can be enforced at the database level (at least with PostgreSQL). I’ll demonstrate on a PostgreSQL container with a simple table. I’ll be using Podman. You can also use Docker to follow along, just replace with in the commands. Make sure Podman/Docker is running, then run the following to get a running PostgreSQL container locally: Then exec into the running container: Now we can start setting up the table to try out enums. First, we’ll create the enum type itself. It’s going to be a type just like or are types in a database. I’m thinking of CI/CD pipelines to use as an example, so the enum will be called and it’ll only accept the values , , , and . Run this SQL query in the container: PostgreSQL should return: Now let’s create a simple table that makes use of the enum. The table will be called and it’ll have two columns: of type , and which uses our enum type . Run this in the container: PostgreSQL should return: Now let’s try inserting a row. This SQL query inserts a row where is and is one of the four predefined enum values ( ). PostgreSQL replies: We can check for the newly created row: You should see: Now let’s try inserting a row with an enum value that is not a part of the values we defined. We’ll try inserting for the column. We should get an error. PostgreSQL should say: The value isn’t one of , so PostgreSQL gives us an error. PostgreSQL itself is enforcing enums! No ORMs here. Note that the values in the enum are case sensitive. So inserting instead of will fail: PostgreSQL returns the error: Another caveat is that inserting as the value for is still allowed unless the column is also created with . Let’s say we actually want to be a part of the enum. We can modify the enum like so: PostgreSQL responds with: Now that is a valid value, we can try inserting again and we won’t get an error: PostgreSQL responds with: We should have two rows total now. We can double check: You should see: We successfully added a value to the enum and used it in a new row. One final note: there isn’t a clean way to remove a value from an enum. You can add values, but you would need to rebuild the enum if you want to remove any values. Plan ahead! Now that the demo is over, exit the PostgreSQL prompt by running: Then clean up the container and, optionally, the image: We created an enum type with predefined values, tried inserting both valid and invalid values, and it was all enforced at the database level with no abstractions from an ORM!

0 views
neilzone 1 months ago

Fixing the unavailability of Tasmota devices after HomeAssistant restarts

Earlier this year, I moved from running HomeAssistant in Python venvs to HomeAssistantOS . After an initial challenge with proxying , it has been working fine. I still don’t like using HAOS, but I can live with it. It seems to need updating a lot , and there is no - at least, not that I have found - automated way of doing this. So I am using an automation based on this template to automate updates . This works fine, but I have noticed that my Tasmota devices - of which I have quite a lot - are unavailable after HomeAssistant Core restarts. There are a lot of search results about this, so I am not the only one with this problem. I looked into a couple of the options ( to 0, and to 0), but I already had these set. Reloading the Tasmota integration did not do anything either. What seems to have worked, though, is an automation which tells all the Tasmota devices to restart, once HomeAssistant restarts . Mine looks like this: This seems - a bit more testing needed - to preserve the state of the device, so if it is off when it restarts, it remains off, and vice versa. I imagine that, because the Tasmota devices are restarting, if HomeAssistant tried to send a command to one or more devices during this restart window, the command would fail. Probably not an issue for me, but perhaps something to bear in mind.

0 views
Jeff Geerling 1 months ago

Noctua Fan Swap on a Calnex Rb/GPS Frequency Reference

Since this will be the only source of this process on the Internet 1 , I figured I'd document a quick fan swap I did on a piece of test/reference equipment I'm running in my Atomic Clock Tower . I took my Torx T10 screwdriver and popped off the top cover. The screws required some force to loosen, as they were all secured with Loctite. The inside is simple and serviceable. There's a SpectraTime GRClok-1500 , with an integrated timing-grade GPS module, and a stabilized 10 MHz output 2 .

0 views
neilzone 1 months ago

LibreOffice Writer, changing text styles, and accepting formatting changes

Hello, future Neil. Here are the two things that you often want to do with formatting and LibreOffice Writer, but do not always remember how to do them. You can use the “Find and Replace” function to change all instances of text in one style to another style. Ctrl + H to open “Find and Replace”. Under “Other options”, select “Paragraph Styles”. In “Find”, select the style that you want to replace. In “Replace”, select the style with which you want to replace it. Often, I want to tidy up tracked changes in a document, to remove formatting changes. From the menu bar, select Edit / Track changes / Manage … Select the “Filter” tab, and, under “Actions” select “Formats”. Go back to the “List” tab, and then “Accept All”.

0 views