Friday, December 4, 2026

How to Install Node-RED on Raspberry Pi OS (2026: What Changed Since NOOBS and Raspbian, and the State of DHT11)

This post shows how to install Node-RED on a Raspberry Pi so you can build its behaviour from a browser. My 2019 post assumed NOOBS and Raspbian, and neither is used any more. Here is how to install Node-RED on current Raspberry Pi OS, plus what you should know before using a DHT11 temperature and humidity sensor.

Illustration of a workbench with a Raspberry Pi and a laptop

What you'll learn

  • What has changed since the 2019 procedure (NOOBS, Raspbian, the default user, how Node-RED is installed)
  • How to install Node-RED on current Raspberry Pi OS and start it automatically
  • The current state of using a DHT11 / DHT22 with Node-RED

What changed since 2019

Item 2019 post Now
Installing the OS Install Raspbian from NOOBS NOOBS is no longer supported, and its repository became read-only in February 2023. Write the card with Raspberry Pi Imager
OS name Raspbian Renamed Raspberry Pi OS in May 2020
Login user Default user pi (password raspberry) The default pi user was removed in April 2022. Create a user in Imager or on first boot
Wi-Fi and SSH Put wpa_supplicant.conf and ssh in boot Set them in Imager (separate post)
Installing Node-RED Script from node-red/raspbian-deb-package Script from node-red/linux-installers

The 2019 post is still available: "Setting Up Raspbian + Node-RED on Raspberry Pi with NOOBS, and Reading DHT11 Temperature Sensor".

What you need

Steps

The steps below come from the official Raspberry Pi and Node-RED documentation.

1. Write Raspberry Pi OS and connect over SSH

Write Raspberry Pi OS with Raspberry Pi Imager. If you set a username and password, Wi-Fi and SSH while writing the card, you can carry on without a monitor. I covered the steps in "How to Set Up a Raspberry Pi Headless with Wi-Fi and SSH (2026, Raspberry Pi Imager 2.0)". There is no default pi user any more, so log in with the user you created here.

2. Install Node-RED

If you plan to install extra nodes, install the build packages first.

sudo apt install build-essential git curl

Install Node-RED with the official script.

bash <(curl -sL https://github.com/node-red/linux-installers/releases/latest/download/install-update-nodered-deb)

According to the official documentation, the script:

  • Removes the existing version of Node-RED if present
  • Checks that Node.js is at least v20 if it is installed, and otherwise installs the Node.js v22 LTS release
  • Installs the latest Node-RED and lets you choose whether to install the Raspberry Pi-specific nodes
  • Sets Node-RED up to run as a service

Add --help to the end of the command to see the options the script accepts. The official documentation also notes that there are no 32-bit builds from Node.js v24 onwards. If you use an older model or a 32-bit OS, check the official documentation.

3. Start it and enable autostart

The script installs commands to start and stop the service.

node-red-start
node-red-stop
node-red-log

To start Node-RED automatically at boot, run:

sudo systemctl enable nodered.service

4. Open the editor

Open this URL in a browser on your computer to get the Node-RED editor.

http://<hostname>:1880

If the hostname doesn't work, run hostname -I on the Raspberry Pi to get its IP address. The official documentation explains how to secure the editor in "Securing Node-RED". If you open it up to other devices, secure it following that page.

The current state of DHT11 / DHT22 with Node-RED

In the 2019 post I read the DHT11 with a Node-RED node. Here is where things stand now. I have not been able to confirm a procedure that works on a current setup.

  • The commonly used node, node-red-contrib-dht-sensor, was last updated more than eight years ago (1.0.4) according to the Node-RED library. It needs the BCM2835 library installed separately and requires running your flow with superuser access. Raspberry Pi 5 support isn't mentioned.
  • For reading the sensor from Python there is Adafruit's library (adafruit-circuitpython-dht), but its README lists as a known issue that it "may or may not work in Linux 64-bit platforms". It also says reads can fail and should be retried after at least 2 seconds. And from Raspberry Pi OS Bookworm onwards, you need a virtual environment (venv) to install libraries with pip.
  • In "Modern Replacements for DHT11 and DHT22 Sensors", Adafruit says the DHT11/22 are no longer good choices and suggests I2C sensors such as the AHT20 instead.

If you're starting to measure temperature and humidity now, an I2C sensor is the safer choice, even if you already have a DHT11. If you keep using a DHT11, first check that the node or library supports your Raspberry Pi model and OS (including whether it's 64-bit).

Note: this post summarises the official Raspberry Pi and Node-RED documentation and Adafruit's material as of December 2026. I haven't run through every step end to end on my own hardware. Steps may change with software updates.

Summary

NOOBS and Raspbian are things of the past; today you write Raspberry Pi OS with Raspberry Pi Imager. There is no default pi user either, so create one when writing the card. Install Node-RED with the official node-red/linux-installers script, enable autostart with sudo systemctl enable nodered.service, and open the editor at http://<hostname>:1880. The node that used to be the standard way to read a DHT11 in Node-RED hasn't been updated in years, so check whether it works on your setup before relying on it.

If this post helped, share it on X (Twitter) — it means a lot.

App by the author of this blog

I made an iOS reading management app called My Bookstore. Simple bookshelf management — give it a try.

View on App Store →

Related posts

References

This post is part of an experiment in automated updates using Claude Code.

Friday, November 27, 2026

How to Set Up a Raspberry Pi Headless with Wi-Fi and SSH (2026, Raspberry Pi Imager 2.0)

This post shows how to boot a Raspberry Pi with no monitor or keyboard attached, with Wi-Fi and SSH ready to use. The method I wrote up in 2018 (dropping a wpa_supplicant.conf into the boot partition) no longer works on current Raspberry Pi OS. Here is the current official procedure, updated for Raspberry Pi Imager 2.0.

Title image: setting up Wi-Fi and SSH on a Raspberry Pi without a monitor

What you'll learn

  • What has changed since the 2018 procedure
  • How to set Wi-Fi, a user and SSH in Raspberry Pi Imager when writing the card
  • How to connect over SSH after first boot, and how to find the IP address if that fails
  • How to enable SSH without Imager

What changed since 2018

Item 2018 procedure Now
Writing the OS Write the image with dd Write it with Raspberry Pi Imager
Wi-Fi settings Put wpa_supplicant.conf in the boot partition Enter them in Imager's settings. Putting wpa_supplicant.conf in the boot partition doesn't work on Raspberry Pi OS Bookworm and later
Enabling SSH Put an empty ssh file in the boot partition Enable it in Imager's settings (the ssh file method is still in the official documentation)

The 2018 procedure is still available in "Headless WiFi Setup for Raspberry Pi Zero W (No Keyboard or Monitor)".

What you need

Steps

The steps below come from the official Raspberry Pi documentation and the official Imager 2.0 announcement. Screen names follow the official documentation.

1. Choose the device, OS and storage

Start Imager and work through the screens in order.

  • Device: your Raspberry Pi model
  • OS: for headless use, the official documentation recommends Raspberry Pi OS Lite
  • Storage: the microSD card to write to (leave Exclude system drives selected)

2. Set Wi-Fi, user and SSH under Customisation

Under Customisation you set the hostname, localisation, username and password, Wi-Fi and remote access, selecting Next after each one. For headless use, you must configure Wi-Fi (or wired Ethernet) and either SSH or Raspberry Pi Connect.

  • Wi-Fi: the SSID and password of your network
  • Remote Access: turn on Enable SSH. You can log in with password authentication (the password of the user you created in Imager) or public-key authentication
  • Raspberry Pi Connect: since Imager 2.0 you can link the device to your Raspberry Pi Connect account while writing the card. Use this if you want to connect remotely with Raspberry Pi Connect instead of SSH

3. Write the card and boot

Select Write, put the microSD card into the Raspberry Pi and power it on. The settings you entered in Imager are applied on first boot.

4. Connect over SSH

From a terminal on your computer, connect using the username and hostname you chose in Imager.

ssh <username>@<hostname>.local

If the .local name can't be found (for example on a network without mDNS), connect by IP address instead.

ssh <username>@<ip address>

Without a monitor you can't check the IP address on the Raspberry Pi itself, so the official documentation suggests these methods:

  • Look at the list of connected devices in your router's admin page
  • Scan your network with nmap from your computer
  • Use a network scanner app on your phone (such as Fing)

If you don't want to type a password every time, create a key pair on your computer and copy it to the Raspberry Pi.

ssh-keygen
ssh-copy-id <username>@<ip address>

Changing settings after writing the card

The Debian Trixie-based Raspberry Pi OS released on 24 November 2025 includes cloud-init, which applies the first-boot settings. When you write the card with Imager 2.0, three files are created in the boot partition: user-data, network-config and meta-data. According to the official blog, you can edit user-data or network-config after writing to change the user or network settings. Wi-Fi is configured in network-config like this (replace the values with your own):

network:
  version: 2
  wifis:
    renderer: NetworkManager
    wlan0:
      dhcp4: true
      regulatory-domain: "US"
      access-points:
        "SSID":
          password: "your-wifi-password"
      optional: true

Enabling SSH without Imager

The official documentation also covers the case where you write the image without Imager's settings. Create these two files in the boot partition (bootfs):

  • An empty file named ssh
  • userconf.txt, containing a single line: username:encrypted-password

To get the encrypted password, run the following command on your computer and enter your password twice. The LibreSSL that ships with macOS doesn't support -6, so you'll need to install OpenSSL separately.

openssl passwd -6

Note: this post summarises the procedures in the official Raspberry Pi documentation and blog as of November 2026. I haven't run through every step end to end on my own hardware. Screen names and steps may change with Imager or OS updates.

Summary

On current Raspberry Pi OS you can't configure Wi-Fi by putting wpa_supplicant.conf in the boot partition. Instead, enter Wi-Fi, user and SSH settings under Customisation in Raspberry Pi Imager before writing the card, then connect with ssh <username>@<hostname>.local after it boots. To change settings after writing, edit network-config or user-data in the boot partition. Without Imager, create the ssh and userconf.txt files yourself.

If this post helped, share it on X (Twitter) — it means a lot.

App by the author of this blog

I made an iOS reading management app called My Bookstore. Simple bookshelf management — give it a try.

View on App Store →

Related posts

References

This post is part of an experiment in automated updates using Claude Code.

Tuesday, November 3, 2026

Physical AI: A Robot Development Diary — My New Book on Turning a Ten-Year-Old Romo into an AI Companion

A small Romo robot from the back of a shelf, and a first-generation iPhone SE dug out of a pile of old gadgets. My new Kindle book, Physical AI: A Robot Development Diary, follows the nine days it took to connect them to generative AI and turn them into a companion that stops when you call its name, answers when you ask, and then moves.

Cover of Physical AI: A Robot Development Diary — Nine Days Unearthing and Nurturing a Ten-Year-Old Relic, showing a smiling Romo with an old iPhone on a cluttered workbench

What this post covers

  • What Physical AI: A Robot Development Diary — Nine Days Unearthing and Nurturing a Ten-Year-Old Relic is about
  • The system design that splits the work between a server PC, an iPhone, and the robot's base
  • The public repository for the app and server developed in the book, and the original Romo app and SDK

What the book is about

The subject is Romo, an educational toy robot that made a striking debut on Kickstarter in 2012, raising far more than its funding goal. It was a groundbreaking product: you dock an iPhone into a small tracked base, and the iPhone becomes its face as it drives around. Today its maker, Romotive, has evolved into Zipline, a company that delivers medical supplies by drone. Its consumer product business, including Romo, has wound down, and repairs and spare parts are no longer provided.

Using the design philosophy of Romo — a product that has vanished from the market — as a guide, the book tells the story of rebuilding it as a physical AI robot powered by generative AI, written to be as readable as possible and understandable even without technical knowledge.

In development, the hardware was left alone and the intelligence was put outside the robot. Words spoken to the robot go to a PC acting as a server. The PC works with AI to assemble a behavior scenario and sends it back. The robot then carries it out with its own camera, microphone, and tracks.

Server PC
Works with AI to assemble behavior scenarios
▼ Behavior scenarios  ▲ User speech
iPhone
Sees, hears, and executes scenarios
▼ Motion commands  ▲ Status
Base
Drives the tracks and tilts the head

The technical topics the book covers include dividing roles in a system with physical control, designing a message format for behaviors, troubleshooting on real hardware, and human–AI collaboration.

The narrator sets the architectural direction, and an AI development partner helps turn it into working software. Tracks that stop after a single twitch. A robot responding to its own voice. The challenge of recognizing its name. Each problem calls for physical observation, displays and logs that reveal internal state, and another conversation with the AI development partner. Reading the original app and SDK also uncovers the ingenuity of earlier developers.

Just as the robot with its new generative-AI brain was about to start running, I was made to see something I had overlooked all along. What was it? Told in the first person, the book follows the nine days of trial and error in order, through conversations between the narrator and the AI development partner and the reactions of the family.

Contents

  • Prologue: Calling Its Name
  • Before We Begin: The Back of the Shelf
  • Day 1: A Machine Still Asleep
  • Day 2: That's Not Design
  • Day 3: I'm Not Building a Remote-Controlled Toy / That'll Never Work
  • Day 4: Alive for an Instant / The Drifting Head
  • Day 5: A Dark World
  • Day 6: A Relic Goes for a Walk
  • Day 7: A Seven-Year-Old Voice
  • Day 8: Always the Same Answer
  • Day 9: Its Own Voice – Forward, Whole Body
  • Epilogue: What It's Worth
  • Repositories and Acknowledgements

Who it is for

You don't need a technical background to enjoy it as a development story. At the same time, it is written so that engineers who want to take everyday app and web development experience into robotics or IoT, or combine their own devices with AI, can draw practical insight from it. Through the concrete example of Romo, it offers a way of observing and designing that you can bring to your own projects.

The unboxing, ten years ago

I bought this Romo more than ten years ago as a gift for my son when he started elementary school, and wrote about the day it arrived on this blog:

The book opens with pulling that same base out from the back of a shelf.

Public repository and acknowledgements

These gave us the means to read and understand the robot's structure and behavior throughout this project. I pay my respects to the engineering spirit of the people who developed and maintained the original Romo, and offer them my heartfelt thanks.

Get the book

Related posts

Tuesday, August 11, 2026

Claude Code Asks for /login After Restarting: Cause and Fix [2026 Edition]

After restarting Claude Code, multiple sessions repeatedly displayed Please run /login or 401 OAuth access token has been revoked and then stopped responding to instructions. Running /login restored one session, but the issue returned in each newly started Claude Code process, making long-running sessions unusable.

Colored-pencil illustration of an authentication token being corrupted and lost on its way from a shell to Claude Code

What you can do with this article

  • Troubleshoot Claude Code when it requests /login at startup
  • Know what to check next when fixing the configuration file does not resolve the issue
  • Safely check the value an open shell passes to a child process and the environment variables supplied when a process started

Environment

  • Authentication used OAuth, and multiple Claude Code processes referenced the same saved OAuth credentials
  • CLAUDE_CODE_OAUTH_TOKEN was exported with a fixed value in ~/.bashrc, which interactive, non-login Bash shells read
  • The shell that had loaded the environment variable remained open and was repeatedly used to start Claude Code

Condition that reproduced the issue

The condition that reproduced the 401 authentication error was starting a new Claude Code process from a shell that still held an old token.

Running /login in another terminal does not update the environment variable held by the affected shell. Processes that are already running also retain the environment variables they received at startup.

Investigating the cause

Identifying the cause took about a month. During that time, I checked the following four points in sequence.

What I checked Action Result and conclusion
Whether /login in another session affected existing sessions Compared behavior before and after running /login in another session No connection was observed
Whether concurrently running processes caused a refresh-token update conflict Started processes one at a time instead of concurrently The 401 authentication error continued, so concurrent startup was not the cause
Whether updates to shared saved OAuth credentials applied to a new process Ran /login in one Claude Code process, then started another Claude Code process The new process encountered a 401 authentication error, leaving open the possibility that it was using a different authentication path from the saved OAuth credentials
Whether a process with a 401 authentication error could be restored individually Ran /login in that process That process recovered, but the issue returned in a newly started Claude Code process from the same shell

Cause: an old token in an environment variable took priority over saved OAuth credentials

Checking the environment variables showed that the launching shell still held an old token.

~/.bashrc
Read when an interactive, non-login Bash shell starts
▼
Loaded when the shell starts
Shell left open
Keeps the old value after the configuration file is fixed
▼
Inherited by a child process
Claude Code
Attempts authentication with the old token

The interactive, non-login Bash shell used in this case reads ~/.bashrc when it starts. Removing the export later does not change the environment of a shell that is already open. Every Claude Code process started from that shell received the old token as a child process.

The cause was that the old CLAUDE_CODE_OAUTH_TOKEN took priority over the saved OAuth credentials created by /login. The official Claude Code documentation also explains that this environment variable takes priority over saved OAuth credentials. If the launching shell retains an old value, that value is used.

As a result, every newly started Claude Code process from the same shell inherited the old token and encountered a 401 authentication error.

Resolution: update the shell configuration file, current shell, and Claude Code

Fixing the shell configuration file alone does not remove the value retained by an already open shell or Claude Code process. Clear it at each of the following three levels in order.

Target Action What this action alone does not change
1. Shell configuration file In this environment, remove or comment out the export in ~/.bashrc It does not affect the current shell or running processes
2. Current shell Run unset CLAUDE_CODE_OAUTH_TOKEN. If you recreate the shell, start it from an environment that does not hold the old value It does not affect running processes
3. Running Claude Code process Restart the target process from a shell where the old value has been removed None

Commands used for verification

# 現在の shell に残っているか
$ env | cut -d= -f1 | grep -c '^CLAUDE_CODE_OAUTH_TOKEN$'
0

# 起動済みプロセスに起動時に渡された環境変数
$ tr '\0' '\n' < /proc/<pid>/environ | grep -c '^CLAUDE_CODE_OAUTH_TOKEN='
0

Both commands count matches only. Printing the matching line directly would display the token as variable-name=value.

/proc/<pid>/environ generally shows the initial environment passed to a process when it started. It does not reflect environment-variable changes made by the process after startup, so I use it here only to check whether Claude Code started after inheriting the old token.

Result

After removing the export from the shell configuration file and starting Claude Code from a shell without the old value, authentication succeeded without running /login in each process.

Additional steps when using tmux

The key point with tmux is that it maintains both global and session environments and merges them when creating a new window before passing the result to the process. If the same variable exists in both, the session-environment value is used.

The environment-variable inheritance path is:

tmuxのグローバル環境・セッション環境 → tmux内のshell → Claude Code

Removing an environment variable retained by tmux

In this case, the old token remained in the global environment. Because tmux also has a session environment, check both before removing it.

# tmuxサーバに残っているか(値は表示しない)
$ tmux show-environment -g | cut -d= -f1 | grep -c '^CLAUDE_CODE_OAUTH_TOKEN$'

# 対象セッションにも残っているか(値は表示しない)
$ tmux show-environment -t <session-name> | cut -d= -f1 | grep -c '^CLAUDE_CODE_OAUTH_TOKEN$'

# tmuxサーバから削除する
$ tmux setenv -gu CLAUDE_CODE_OAUTH_TOKEN

# 対象セッションから削除する
$ tmux setenv -u -t <session-name> CLAUDE_CODE_OAUTH_TOKEN

Removing the variable from the tmux environments does not remove the old token from shells and Claude Code processes already running in existing windows or panes. Handle them in this order:

  1. Remove the variable from the tmux global environment and the target session environment
  2. Run unset CLAUDE_CODE_OAUTH_TOKEN in the existing shell inside tmux, or recreate the window or pane
  3. Restart Claude Code from that shell

If you can end every session, tmux kill-server can terminate the tmux server, existing shells, and Claude Code processes together. In this environment, I restarted 14 sessions other than the one still in use, and all 14 authenticated without an individual /login. I restarted the remaining session later and confirmed that it had no old environment variable.

Monitoring a tmux session externally

In this environment, I monitored whether the Claude Code process existed from outside the tmux session. Because the process itself did not exit after the 401 authentication error, checking only for the process could not detect that it had stopped responding.

This article records measurements from a WSL2 environment as of August 2026. Shell and client behavior may vary by version and startup method. If you notice anything, please leave a comment.

Summary

  • The 401 authentication error occurred because the old CLAUDE_CODE_OAUTH_TOKEN retained by the shell took priority over the OAuth credentials saved by /login
  • Resolving it required removing the setting from ~/.bashrc, clearing the environment variable from the current shell, and then restarting Claude Code from that shell
  • When using tmux, also remove the variable from its global and session environments and handle the old token retained by existing shells

If this article helped, I’d be happy if you shared it on X (Twitter).

App by the author of this blog

I made an iOS reading management app called My Bookstore. Simple bookshelf management — give it a try.

View on App Store →

Related articles

References

Wednesday, July 15, 2026

Free on Kindle, July 17–19: Building Your Own Crypto Trading System

For three days — July 17–19, 2026 (PDT) — my book Building Your Own Crypto Trading System is free on Kindle. If you've ever wanted to see how a personal crypto auto-trading system is actually designed, backtested, and run 24/7 — in real Python code — this is a good moment to grab it.

Cover of the book 'Building Your Own Crypto Trading System — Design, Backtesting, and 24/7 Operation in Python' by Isao Takeyasu Get it free on Kindle (July 17–19, 2026 PDT) →

What the book is

Building Your Own Crypto Trading System — Design, Backtesting, and 24/7 Operation in Python walks through a personal BTC/ETH auto-trading system I've built and run for years: the strategy, a backtester that replays the past with the exact same code as production, parameter optimization that avoids overfitting, dynamic capital allocation, and the operational side — absorbing differences between exchange APIs and running it across multiple machines around the clock.

What sets it apart is that it's a transparent record of design and failure, not a success story. Dead ends get top billing: a 1,800-line market-regime detector scrapped for overfitting, an optimizer that misjudged a 98% drawdown as a good score, and more. And the trading "brain" is no flashy AI prediction — it's plain indicators (Bollinger Bands and a linear-regression trend) organized into prioritized rules. The stance is "don't let AI predict the market; use it to build the system."

There's a twist to how the book was made, too: the text, illustrations, and cover were written by AI (Claude Code), with me setting the direction and making the final calls. I wrote up that process separately — I Used Claude Code to Write and Publish a Whole Book on My Crypto Auto-Trading System.

The free campaign

  • Free: July 17–19, 2026 (PDT), three days
  • Normally: $9.99 (also in Kindle Unlimited)
  • Where: Amazon Kindle

If you find it useful, an honest review would mean a lot — it's a brand-new release with no reviews yet.

Note: neither this article nor the book recommends buying or selling any specific crypto asset, and neither is intended as investment advice or solicitation. Any figures shown are results of backtesting / optimization on past data, and do not guarantee future profit or realized returns. Crypto trading carries price-volatility risk. Make your own decisions at your own responsibility.

Friday, June 19, 2026

I Used Claude Code to Write and Publish a Whole Book on My Crypto Auto-Trading System

I've spent the better part of eight years — since 2017 — gradually building my own crypto auto-trading system. Now I've published a book on Zenn that explains how it's designed, validated, and operated. Targeting BTC/ETH, it's an implementation how-to that walks through the trading logic, parameter optimization, and capital allocation, all the way to building the operational system, with real code and measured numbers.

And here's the twist: the book itself — the text, the illustrations, the cover — was written by AI. I'll introduce what's inside first, then talk about how it was made.

Cover of the book 'Building a Personal Crypto Auto-Trading System — From Design to Operation [Complete Edition]'
The book's cover. The background art was generated by an image AI; the title text was placed by a human.

What you'll learn

  • What the book — Building a Personal Crypto Auto-Trading System — From Design to Operation [Complete Edition] — actually covers
  • The behind-the-scenes of an AI writing, illustrating, covering, and QA-ing a whole book through to publication
  • How AI is used to the hilt in both building the system and writing the book, while the human keeps the direction and the final call

What kind of book is it: a transparent record of design and "failure"

The book is Building a Personal Crypto Auto-Trading System — From Design to Operation [Complete Edition] (Zenn, ¥1,200). The introduction and Chapter 1 (the system's track record and its "brain") are free.

  • Introduction — how to read this book, and who it's for (free)
  • Part I — Algorithms
  • Ch. 1 — The system's track record and its "brain" (free)
  • Ch. 2 — Building a backtester: replaying the past with the exact same code as production
  • Ch. 3 — Parameter optimization ①: the search
  • Ch. 4 — Parameter optimization ②: objective functions and avoiding overfitting
  • Ch. 5 — Dynamic capital allocation: how much to put into BTC vs. ETH
  • Part II — Systems
  • Ch. 6 — Absorbing differences between exchange APIs (Coincheck / GMO / bitFlyer)
  • Ch. 7 — Splitting work across three machines: availability, compute, interactivity
  • Ch. 8 — Three-layer config and multi-user operation
  • Closing — looking back over the whole

From the strategy algorithms (Part I) to the operational system (Part II), it backtests roughly three years of trades at high speed on Python and a GPU-equipped PC, so you can follow the design — and the failures — in code and measured numbers.

The theme isn't "the success story" but a transparent record of design and failure. A 1,800-line market-regime detector scrapped wholesale because of overfitting. An optimizer that misjudged a "98% drawdown" as a good score. These dead ends get top billing in each chapter. The trading "brain," too, is no flashy AI prediction: it's just Bollinger Bands and a linear-regression trend, organized into prioritized rules.

This "don't rely on flashy prediction" stance wasn't a belief I started with — it's a conclusion reverse-engineered from failure. The starting point was 2017. My first attempt was machine learning with TensorFlow on price history, and it didn't work at all. After failing hard at "trying to call the future," I settled on plain indicators. The book's stance — "don't let AI predict the market, but use it to the hilt for design and implementation" — comes from this eight-year experience.

Behind the scenes: built by a team of AIs with different roles

Several AIs with different roles went into making this book.

  • (1) Technical source (the system's developer) and technical reviewer: provides the facts the text needs and checks technical correctness. Facts not in the source material aren't invented — they're verified against the real code and real data.
  • (2) Advisor and prose reviewer: a sounding board for "going public" decisions like platform choice and editorial direction, and a reviewer of the writing before release. The pricing and title exchanges below were debates with this one.
  • (3) Illustrator: the chapter illustrations. This one is actually the "high-school AI" from a separate blog, ai.andhandworks.com, moonlighting as the artist.
  • (4) Writer: writes the body of each chapter.

For the cover, (3) generated the background, and a human placed the title text (because AI-made covers tend to look generic). Before release, a gate runs every chapter through automated checks for banned words and leaked sensitive info (account names, hostnames, IPs, keys).

Writing, drawing, researching, checking, consulting — each handled by a different AI, with the human judging the output. That's the division of labor.

An example AI-generated chapter illustration depicting the system's 'brain'
One of the AI-generated chapter illustrations — depicting the system's "brain" (a combination of plain indicators).

The human's role: set the direction, use AI as the "maker"

The human's role has shifted from doing the work by hand to deciding the direction and letting AI make things. It's the same for the system and for the book. Here's what the human decided in producing the book:

  • Goals and publication structure: the book's structure (parts and chapters), and what's free.
  • Final call on price, title, and search keywords.
  • Creative direction: e.g. specifying the cover motifs (blueprints, a timer, a pile of coins, servers and microcontrollers).
  • Final fact-checking and the publish action: a human flips the publish toggle.

And this relationship is not one-way. The AI proposed things the human rejected, and the human's ideas got reworked by the AI. Two examples.

Example 1 — Pricing: the AI put the brakes on "¥2,980"

When we discussed price, the AI first offered "worth ¥3,500 by content, but ¥3,000 given no track record yet." I countered with "what about ¥2,980 or ¥3,200?" The AI pushed back — "odd-number prices look like an infoproduct and hurt the brand; the psychological effect is weak for a tech book; and Zenn only allows ¥100 increments" — and recommended a round number. In the end, I was the one who said "even ¥3,000 is too much" and brought it down to ¥1,200.

Example 2 — Title and keywords: the human rejected the AI's ideas

For title keywords, the AI suggested "Python / BTC / ETH." I pushed back: "the BTC/ETH abbreviations won't land with beginners," and "the essence of this book isn't the personal angle" — and the AI revised them. Conversely, my own "build from scratch" idea I withdrew myself, feeling it was too derivative, and settled on "personal build." On keywords too, the AI pushed "backtest"; I replied "the search volume is too small," and we ended at "machine learning." It's an accumulation of exchanges like this.

Incidentally, once the direction is set, the AI does the actual work — so part of the back-and-forth for this book happened while I was climbing Mt. Tsukuba, from my phone. Tweaking the chapter outline while taking in the view from the summit: that's about the distance you can work from.

A stone monument inscribed 'Mt. Tsukuba' at the summit The view over the Kanto plain from the summit of Mt. Tsukuba
Some of the editing happened at the summit of Mt. Tsukuba. Setting direction takes nothing but a phone.

The content and the making share the same philosophy

The book's argument is "don't rely on flashy prediction; build steadily through design, validation, and iteration." The process of making the book was the same. Don't let AI call the market — but use AI as a maker, to the hilt, for both the system's implementation and the book's writing. Not to guess the future, but as a developer and writer working at your side. The content and the making are built on the same philosophy — and that, I think, is what sets it apart from the usual "written by AI" books.

Take a look

The book is here → Building a Personal Crypto Auto-Trading System — From Design to Operation [Complete Edition] (Zenn). The introduction and Chapter 1 are free.

Note: neither this article nor the book recommends buying or selling any specific crypto asset, and neither is intended as investment advice or solicitation. Any figures shown are results of backtesting / optimization on past data, and do not guarantee future profit or realized returns. Crypto trading carries price-volatility risk. Make your own decisions at your own responsibility.

Related posts

Saturday, June 13, 2026

Modernizing a 9-Year-Old iOS App Without a Rewrite: Realm Device Crashes, OAuth Migration, StoreKit 2 [2026]

App icon for Oyakodon for Mastodon (a parent and child mammoth) See Oyakodon for Mastodon on the App Store

This is a write-up of how I had Claude Code modernize a personal iOS app I had left untouched for years. I didn't write a single line of code — in fact, I never touched the Mac, or even the PC that Claude Code runs on. I just gave instructions from my phone, and Claude Code did everything headlessly on the Mac over SSH: the code changes, the investigation, the builds, the TestFlight delivery, and even the App Store submission. Here I document what was broken and how it got fixed in a roughly 9-year-old Mastodon viewer (about 7.5 of those years completely abandoned), first released back in 2017.

What you'll learn

  • How to have Claude Code modernize an old, abandoned iOS app without writing any code yourself
  • The division of labor (what I asked for vs. what Claude Code asked me to do)
  • The technical updates that resulted (replacing deprecated APIs, OAuth migration, fixing a Realm device-only crash, and more)

Division of labor: what I asked for, and what Claude Code asked of me

In one sentence, what I first asked Claude Code was: "Take Oyakodon, abandoned for 7.5 years, and fix it without a rewrite so it's ready to ship to the App Store again." We hashed out the actual implementation details through back-and-forth, but the one who opened the editor and wrote the code was Claude Code, not me.

What Claude Code did (headlessly, on the Mac):

  • The Swift code changes themselves (all of the Before / After below are Claude Code's edits)
  • Symbolicating crash logs (.ips) with atos to pinpoint the failing locations
  • Hitting the Mastodon API with curl to isolate behavior
  • Running xcodebuild archive → altool on the Mac over SSH and uploading to TestFlight
  • Bumping the build number (CFBundleVersion) and submitting for review on App Store Connect (via the API). The App Store basics (the app record, contracts, baseline info) were already set up from the old-app days, so I never had to log in to App Store Connect anew — Claude Code took it all the way through submission

What I did (only the parts a human can't avoid):

  • Deciding the policy — "modernize without a rewrite" — and sending instructions from my phone
  • Touching the TestFlight builds on my own iPhone and reporting anomalies with screenshots. The "crashes right on launch" and "the bottom edge is misaligned" issues below were both found through this hands-on device check. Notably, even hard-to-describe issues like WebView geometry misalignment only took me sending a single screenshot — it was Claude Code that read the image and isolated the cause

In other words, I never once touched the Mac, nor the PC that Claude Code runs on. I never looked at the code, and I never logged in to App Store Connect. The only thing I physically did was tap through the TestFlight builds that arrived on my iPhone and report what looked wrong. Claude Code's role was "investigation, code changes, builds, delivery, submission"; mine was "deciding direction" and being "the eyes and hands that touch the real device and report what's off."

Background: what had "rotted"

The subject is Oyakodon, a personal iOS app. It's a viewer for juggling multiple Mastodon instances side by side, first released in April 2017 — so the app itself is about 9 years old, and I had completely abandoned it for roughly 7.5 years since its last update in October 2018. The modernized build is now live on the App Store (Oyakodon for Mastodon). When I opened it again after all that time, it wouldn't even build — and the cause wasn't just one thing.

  • iOS SDK side: deprecated APIs had piled up — UILocalNotification, setMinimumBackgroundFetchInterval, UIImageJPEGRepresentation — and private APIs like value(forKey: "statusBar") simply no longer compiled
  • Mastodon side: the web UI's URL routes changed (e.g. /web/timelines/home → /home), the API was bumped (v1 → v2), and ID types changed
  • Dependencies: schema changes in Realm (a mobile database), Firebase API revisions, and the review-prompt library Appirater going unmaintained
  • A vanished external service: the API that returned the instance list (instances.mastodon.xyz) was shut down
  • Auth flow: password grant (sending username and password directly) was removed, effectively forcing a migration to the Authorization Code flow

In short, it was corroding from five directions at once: SDK, server, libraries, external services, and auth. Fix one and the next would collapse — the textbook state of an abandoned project.

Approach: modernize in place, without a rewrite

The first thing I decided was "no full rewrite." Oyakodon's differentiator is multi-posting to N instances simultaneously, plus cross-instance boosts (reposts). That core was still working fine in the existing Swift code. Throwing away something that works and rewriting from scratch costs more — the cost of reproducing "it works" is the expensive part.

So I chose in-place modernization: keep the app's skeleton, and peel off only the surface corrosion (deprecated APIs, the dead auth flow, old types) one layer at a time. The work was split into Phases 0–8, with each phase bounded by "the build goes green (succeeds)."

Phase-by-phase summary (all done by Claude Code)

PhaseWorkScale
0iOS 17 build green / CocoaPods → SPM migrationDeleted 917 files under Pods/, auto-converted the pbxproj
1Fix WebView timeline, keep login persisted, externalize settingsSplit the URL route table / CSS / JS into external files
2Remove the dead instance picker, switch to direct domain entryHandling the shutdown of instances.mastodon.xyz
3Change Status / Notification / Attachment IDs from Int → StringImplemented comparison helpers, 16 unit tests
4Move OAuth to the Authorization Code flowAdded a dedicated OAuth WebView screen, registered a URL scheme
5Support /api/v2/media + /api/v2/search, delete dead old-Twitter integration codeImplemented polling for media-processing completion
6Move to BGTaskScheduler + UserNotificationsDropped old background fetch, removed all iOS 10 guards
7Migrate the Share Extension's type systemMobileCoreServices → UniformTypeIdentifiers, deleted 139 lines
8Migrate IAP (in-app purchases) to StoreKit 2Shrank from 250 lines to 79

The final scale was 949 files changed, 2,717 lines added, 225,731 lines deleted. The deletion count is extreme because Phase 0 dropped CocoaPods (a dependency manager) and replaced the large library binaries that had been committed to the repo with SPM (Swift Package Manager, Apple's first-party dependency manager).

What changed technically: Before / After

From here, let's look at some of the more characteristic changes Claude Code made, as Before / After.

1. The code was breaking login on every launch

The pre-abandonment code cleared the cache on every launch — and in doing so swept away the areas that hold login state (localStorage and IndexedDB) too. A well-intentioned "let's keep the cache clean" was, as a result, logging the user out on every launch.

// BEFORE: wipes the cache AND login data on every launch
func removeCache() {
    URLCache.shared.removeAllCachedResponses()
    WKWebsiteDataStore.default().removeData(
        ofTypes: [
            WKWebsiteDataTypeDiskCache,
            WKWebsiteDataTypeOfflineWebApplicationCache,
            WKWebsiteDataTypeSessionStorage,
            WKWebsiteDataTypeLocalStorage,       // <- holds login state
            WKWebsiteDataTypeIndexedDBDatabases  // <- same
        ], modifiedSince: Date(timeIntervalSince1970: 0), completionHandler: {})
    // also deletes everything under Library/Caches...
}
// AFTER: clear only URLCache; don't touch WKWebsiteDataStore
func removeCache() {
    URLCache.shared.removeAllCachedResponses()
}

The fix was simply "don't touch it." The WKWebView (iOS's web rendering component) session is held by WKWebsiteDataStore, so as long as you don't wipe that, the login persists.

2. Mastodon IDs should be String, not Int

The old code held Status (post) IDs as Int, parsing them via NSString. Mastodon IDs keep growing in digit count over time, so treating them as Int risks overflow. Keeping them as plain strings was the right answer.

// BEFORE: parse via NSString (huge IDs risk overflow)
public class Status { public var id: Int! }

if let statusId = (item["id"] as? NSString)?.integerValue {
    status.id = statusId
}
let body = ["since_id": "\(sinceId)"]  // converted to a string every time
// AFTER: pull it straight out of JSON as a String
public class Status { public var id: String! }

if let statusId = item["id"] as? String {
    status.id = statusId
}
if !sinceId.isEmpty { body["since_id"] = sinceId }  // don't send if empty

Stringifying the ID makes ordering a string comparison, so I implemented a comparison helper with the rule "more digits = newer; same digit count = lexicographic," backed by 16 unit tests.

3. OAuth: from password grant to the Authorization Code flow

Because Mastodon removed password grant (exchanging username and password directly for a token), I had to migrate to the Authorization Code flow, which receives an authorization code via the browser.

// BEFORE: password grant (removed)
static func fetchAccessToken(addr: String, clientId: String, clientSecret: String,
                            username: String, password: String, ...) {
    let body = [
        "grant_type": "password",  // <- the removed flow
        "username":   username,
        "password":   password,
        ...
    ]
}
// AFTER: Authorization Code flow (send only the code obtained in the WebView)
static func fetchAccessToken(addr: String, clientId: String, clientSecret: String,
                            code: String, ...) {
    let body = [
        "grant_type":   "authorization_code",
        "redirect_uri": "oyakodon://oauth",
        "code":         code,
        ...
    ]
}

A design choice: instead of Apple's recommended ASWebAuthenticationSession (an OS-provided, auth-dedicated browser), I complete OAuth inside the app's existing WKWebView. The reason is UX. ASWebAuthenticationSession uses a browser session independent of the WKWebView used for the timeline, which would force a double login — "once for the timeline, once more for OAuth." By catching the navigation to oyakodon://oauth?code=... in the existing WebView's navigation delegate (the hook that watches page transitions), you stay in the same session and log in just once.

4. From StoreKit 1 to StoreKit 2 (250 lines → 79)

The IAP (in-app purchase) code was a StoreKit 1 implementation that hand-managed state with the Observer pattern plus delegates. Replacing it with StoreKit 2's async/await base made the state flags and error counters disappear entirely — 250 lines became 79.

// BEFORE: Observer pattern, singleton, delegates (~250 lines)
class PurchaseManager: NSObject, SKPaymentTransactionObserver {
    var delegate: PurchaseManagerDelegate?
    func startWithProduct(_ product: SKProduct) {
        if SKPaymentQueue.canMakePayments() == false { ... }
        // flag management, error counters...
        SKPaymentQueue.default().add(payment)  // result is left to the Observer
    }
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions: ...) {
        // switch over .purchased / .failed / .restored
    }
}
// AFTER: async/await, @MainActor (~79 lines)
@MainActor final class IAPManager {
    static let shared = IAPManager()

    func purchase(productID: String) async throws -> Bool {
        let products = try await Product.products(for: [productID])
        guard let product = products.first else { return false }
        let result = try await product.purchase()
        switch result {
        case .success(let v):                 return await handleVerification(v)
        case .userCancelled, .pending:        return false
        @unknown default:                     return false
        }
    }

    func restore() async throws {
        try await AppStore.sync()
    }
}

I also moved background notifications from the old performFetchWithCompletionHandler to BGTaskScheduler (the iOS 13+ background-task API), and the Share Extension from MobileCoreServices's C constants to UniformTypeIdentifiers' UTType. These are all "replace an old API with a new one one-to-one" jobs, and raising the minimum OS to iOS 17 let me delete every if #available(iOS 10.0, *) branch.

Three bugs that only surfaced on a real device via TestFlight

This is the part I most want to get across. Even with the build passing and everything working perfectly in the simulator, three bugs that crashed or misaligned appeared the moment I put a TestFlight build on a real device (iPhone). The flow was: I touched the device and reported the anomaly, and Claude Code symbolicated the .ips crash log with atos to pinpoint the cause. Every one of these would have first surfaced on a user's device after release if I'd only watched the simulator.

(1) Realm crashes immediately on device launch (missing embed)

RealmSwift added via SPM is type: .dynamic — that is, always a dynamic framework (loaded at runtime). But when Phase 0 auto-converted the pbxproj (Xcode's project settings file), it only set up the framework "link" and never added the "embed" (the Embed Frameworks phase).

As a result, it works in the simulator (which embeds it via another path) but crashes on a real device right after launch with dyld: Library not loaded: @rpath/RealmSwift.framework.

A quick way to tell: a healthy IPA (the iOS app package) bundles RealmSwift.framework and comes out to about 12MB. If it's only 2.5MB, the embed is missing. Just checking the IPA size before uploading tells you instantly.

(2) The trap of ignoring Realm's Configuration

The second one is also Realm. I had set schemaVersion and migrationBlock (the schema-migration handler) on Realm.Configuration.defaultConfiguration, yet it still crashed on launch.

The cause was opening the DB with Realm(fileURL:). That initializer ignores defaultConfiguration. So the existing DB's schema version (2) and the new default (0), which never picked up my settings, were mismatched.

// NG: schemaVersion / migrationBlock on defaultConfiguration are ignored
let realm = try Realm(fileURL: dbURL)

// OK: pass the Configuration explicitly
var config = Realm.Configuration.defaultConfiguration
config.fileURL = dbURL
let realm = try Realm(configuration: config)

(3) WebView bottom-edge misalignment (took three fixes to truly resolve)

The third is a misalignment where, at the bottom of the screen, the WebView slightly overlaps the toolbar or leaves a gap. I fixed this three times in total — in 2.7.2 build 2, 2.7.3 build 1, and 2.7.3 build 2 (shipping to TestFlight and checking on the device each time). The first two were symptomatic treatments; the root cause was "three parties fighting over the geometry (position and size)."

It's hard to convey in words exactly "how many points it overlaps," but all I did was screenshot the device screen and send it. Claude Code read the amount and direction of the misalignment from the image and narrowed down the cause. This was a moment where a problem that would have taken many round-trips with text alone moved forward with a single image. Here are the actual before / after device screenshots I sent.

Before: device screenshot where the WebView overlaps the toolbar at the bottom, hiding content Before: the bottom edge overlaps the toolbar After: device screenshot where pinning the WebView's four edges with Auto Layout resolves the bottom misalignment After: pinning all four edges resolves it
The before / after I shot on the device and sent to Claude Code. It read the amount of misalignment from these images.
  • Storyboard Auto Layout: views with translatesAutoresizingMaskIntoConstraints = false snap back to their constraint values on every layout pass
  • Manual frame math: the menu-bar show/hide logic used the deprecated statusBarFrame and ignored the 34pt bottom safe area (the home-indicator region)
  • Resize handling: it snapshotted the container height at that instant, so it couldn't follow changes after the toolbar's open/close animation finished

These three kept overwriting the frame values every time, so wherever you fixed it, another piece of logic would roll it back. The real fix was "drop the manual frame math and resize handling, and pin the WebView's four edges to the container with Auto Layout." Pin it once, and the layout follows automatically from then on.

// AFTER: pin all four edges with Auto Layout -> follows automatically afterward
let webView = self.webViewController.webView
webView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    webView.topAnchor.constraint(equalTo: webContainerView.topAnchor),
    webView.bottomAnchor.constraint(equalTo: webContainerView.bottomAnchor),
    webView.leadingAnchor.constraint(equalTo: webContainerView.leadingAnchor),
    webView.trailingAnchor.constraint(equalTo: webContainerView.trailingAnchor),
])
// removed the manual resizeWebView()

Notes on design decisions

  • Don't rewrite: the differentiators (multi-posting, cross-instance boosts) were working in the existing code, so keeping them and only fixing the surface was the surer bet.
  • CocoaPods → SPM: the immediate trigger was a build-environment constraint, but the bigger side effect was wiping out 50MB+ of binaries that had been committed to the repo.
  • Externalizing config: Mastodon's web UI routes will keep changing. Splitting the URL path table / CSS / JS into JSON and files makes it easier to follow the next change without rebuilding the app itself. It's also aimed at sharing the spec when I eventually write an Android version.
  • App Store review risk: an app that merely displays a site in a WebView can be rejected under guideline 4.2 (minimum functionality). The native layers — multi-posting, OAuth, notifications, purchases — are what form that line of defense.

In the end, 2.7.2 is released, and I got 2.7.3 to a state I could submit for App Store review. The actual work took about a week.

FAQ

Q. Did you write the code yourself?

A. No — not a single line, and I never even looked at the code. I just decided the policy ("modernize without a rewrite") and instructed from my phone; Claude Code did the code changes, investigation, builds, TestFlight delivery, and App Store submission headlessly on the Mac over SSH. I never touched the Mac or the PC Claude Code runs on. The only thing I physically did was tap through the TestFlight builds that arrived on my iPhone and report anomalies. The App Store Connect submission was also done by Claude Code via the API (the App Store basics were already set up from the old-app days, so no new login was needed).

Q. Why does it crash on a real device when it works in the simulator?

A. Because the parts the simulator stands in for — whether dynamic frameworks are embedded, code signing, the device-specific safe area — are exposed on a real device. The Realm crash here was exactly that, so before release you should always deliver to a real device via TestFlight and confirm it launches.

Q. Wouldn't rewriting the old app be faster?

A. If the differentiators still work, I don't recommend a rewrite, because reproducing "it works" is costly. Conversely, if the core itself is outdated or broken, a rewrite can be faster. The deciding factor is "is what's broken the inside, or the surface?"

Q. Is completing OAuth inside a WebView safe?

A. Security-wise, ASWebAuthenticationSession is preferable. Here I prioritized the UX of avoiding a double login and kept it inside WKWebView, but for apps where you don't control the authorization server, consider Apple's recommended approach.

Note: the code in this article is simplified from what actually ran on the Xcode / iOS SDK / libraries at the time of writing (June 2026). If versions change, it may not work as-is. If something doesn't work, let me know in the comments. Environment-specific values like the Bundle ID have been replaced with placeholders.

Wrap-up

Even a roughly 9-year-old iOS app (about 7.5 of those years abandoned) can be fixed without a rewrite if what's broken is the "surface." This time I wrote no code and looked at none, never touched the Mac, and stuck to setting direction and checking on my own iPhone, leaving the code changes, builds, TestFlight delivery, and App Store submission to Claude Code. The hard parts were the Realm issues and the WebView geometry — things that build fine but only break on a real device. Don't trust the simulator too much; delivering to a real device via TestFlight to verify is the shortcut.

If this article helped, I'd be glad if you shared it on X (Twitter).

Related posts

References