Some Bits: Nelson's log

12 posts in September 2026

Fixing invisible endnotes

Claude just surprised me by offering to rewrite a whole epub so the references worked better.

I’m reading an academic biography as an epub on my Kobo reader. Great book and I’m really curious about the sourcing. Unfortunately the book is published in “invisible endnote” form. The text itself has no footnotes at all. There’s 200 pages of endnotes, they reference the main text with small quotes like “(p. 77) a field full of dropsical chickens”. This kind of formatting works OK in a paper book, but it’s a real shame in an ebook.

So I was asking Claude if this is how the original book was published (it is). And then it volunteered on its own “I could fix this”. It never would have occurred to me to ask! 5 minutes later I had a better formatted epub.

Claude’s first pass worked OK but didn’t look great on my Kobo. I worked a bit more to get it to fix some epub formatting problems and to locate some hard-to-correlate quotes back to the original text. The second copy looks great.

I’m flabbergasted. The algorithm it uses is simple enough, as are the technical edits. But it never would have occurred to me to try, nor would I have spent the hours it would take to make it word. Claude/Opus did it with barely a thought.

I think this endnote tool is useful enough it could be turned into a Calibre plugin. I probably won’t bother, it’s a lot of product management and testing. I’m also kind of liking this world of ephemeral software where it’s so easy now to build working code we don’t even bother sharing or keeping it.

I’ve pasted the code Claude generated below just to archive it. I haven’t even looked at it at all. I’m not reviewing most AI generated code anymore.

#!/usr/bin/env python3
"""Add working, visible endnote references to an EPUB with "phrase-keyed" notes.

Many trade non-fiction ebooks have endnotes that look like this:

    10  “I own, but not quite”: Marianne Thornton to ..., KCC.

The page number links back to the start of a page in the text, but nothing in
the text links forward to the note.  This script:

  * finds every note in the Notes section and the cue phrase it glosses,
  * locates that phrase in the body text (starting at the page the note cites),
  * inserts a bold superscript note number after the phrase (and its closing
    quote/punctuation) that links to the note,
  * numbers the notes chapter by chapter and makes the number in front of each
    note a link back to the exact spot in the text,
  * applies a few conservative stylesheet fixes for Kobo's renderer (centered
    text that was pushed off-center by indents, hard-coded font families, a
    stretched cover image, <br> elements styled as blocks).

Everything else in the book is left as-is.  Only the files that change are
re-serialized.

Usage:
    python3 link_endnotes.py book.epub [-o out.epub] [--report notes.txt]

Requires lxml.
"""

import argparse
import bisect
import posixpath
import re
import sys
import zipfile
from collections import defaultdict
from urllib.parse import unquote

from lxml import etree

XHTML_NS = "http://www.w3.org/1999/xhtml"
OPF_NS = "http://www.idpf.org/2007/opf"
CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container"
SVG_NS = "http://www.w3.org/2000/svg"

def X(tag):
    return f"{{{XHTML_NS}}}{tag}"

BLOCK_TAGS = {X(t) for t in (
    "p", "div", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6",
    "li", "td", "th", "table", "tr", "ul", "ol", "dl", "dd", "dt", "body")}
HEADING_TAGS = {X(t) for t in ("h1", "h2", "h3", "h4", "h5", "h6")}
MAJOR_HEADING_TAGS = {X("h1"), X("h2")}
VOID_TAGS = {X(t) for t in (
    "area", "base", "br", "col", "embed", "hr", "img", "input", "link",
    "meta", "param", "source", "track", "wbr")}

# Characters that the note marker is moved past so it lands after punctuation,
# as in print (Chicago style: after everything except dashes).
TRAILING_PUNCT = set(".,;:!?)]’”'\"")

# Classes and ids this script adds.  Short names keep the markup light.
MARKER_CLASS = "nref"       # <sup class="nref"><a ...>12</a></sup> in the text
NOTE_NUM_CLASS = "nnum"     # <a class="nnum">12.</a> at the start of a note
REF_ID = "nref{}"
NOTE_ID = "note{}"

EXTRA_CSS = f"""
/* ---- Added by link_endnotes.py ---- */
/* Note numbers in the text: bold superscript, no underline, so they read
   clearly on e-ink.  line-height: 0 keeps them from spreading lines apart. */
sup.{MARKER_CLASS} {{
    font-size: 0.7em;
    font-style: normal;
    font-weight: bold;
    line-height: 0;
    vertical-align: super;
    text-indent: 0;
}}
sup.{MARKER_CLASS} a {{
    color: inherit;
    text-decoration: none;
}}
/* Note number at the start of each note, linking back to the text. */
a.{NOTE_NUM_CLASS} {{
    color: inherit;
    font-weight: bold;
    font-style: normal;
    text-decoration: none;
}}
img {{
    max-width: 100%;
}}
"""

# --------------------------------------------------------------------------
# EPUB container helpers

class Book:
    def __init__(self, path):
        with zipfile.ZipFile(path) as z:
            self.names = z.namelist()
            self.data = {n: z.read(n) for n in self.names}
        container = etree.fromstring(self.data["META-INF/container.xml"])
        self.opf_path = container.find(f".//{{{CONTAINER_NS}}}rootfile").get("full-path")
        self.opf_dir = posixpath.dirname(self.opf_path)
        self.opf = etree.fromstring(self.data[self.opf_path])

        manifest = {}
        for item in self.opf.iter(f"{{{OPF_NS}}}item"):
            manifest[item.get("id")] = (self.resolve(self.opf_dir, item.get("href")),
                                        item.get("media-type"))
        self.manifest = manifest
        self.spine = [manifest[ref.get("idref")][0]
                      for ref in self.opf.iter(f"{{{OPF_NS}}}itemref")]
        self.stylesheets = [p for p, mt in manifest.values() if mt == "text/css"]
        self._trees = {}
        self.dirty = set()

    @staticmethod
    def resolve(base_dir, href):
        return posixpath.normpath(posixpath.join(base_dir, unquote(href)))

    def tree(self, path):
        if path not in self._trees:
            parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)
            self._trees[path] = etree.fromstring(self.data[path], parser).getroottree()
        return self._trees[path]

    def href(self, from_path, to_path, fragment=None):
        rel = posixpath.relpath(to_path, posixpath.dirname(from_path) or ".")
        return f"{rel}#{fragment}" if fragment else rel

    def split_href(self, from_path, href):
        path, _, frag = href.partition("#")
        if not path:
            return from_path, frag
        return self.resolve(posixpath.dirname(from_path), path), frag

    def write(self, out_path):
        for path in self.dirty:
            if path in self._trees:
                tree = self._trees[path]
                # Keep <a id="x"></a> from becoming <a id="x"/>, which an
                # HTML parser (these files are named .html) reads as an
                # unclosed link swallowing the rest of the paragraph.
                for el in tree.iter():
                    if isinstance(el.tag, str) and el.tag.startswith(f"{{{XHTML_NS}}}") \
                            and el.tag not in VOID_TAGS and el.text is None and len(el) == 0:
                        el.text = ""
                self.data[path] = etree.tostring(
                    tree, xml_declaration=True, encoding="utf-8",
                    doctype=tree.docinfo.doctype or None)
        with zipfile.ZipFile(out_path, "w") as z:
            # mimetype must be first and stored uncompressed.
            z.writestr(zipfile.ZipInfo("mimetype"), self.data["mimetype"],
                       compress_type=zipfile.ZIP_STORED)
            for name in self.names:
                if name == "mimetype" or name.endswith("/"):
                    continue
                z.writestr(name, self.data[name], compress_type=zipfile.ZIP_DEFLATED)

# --------------------------------------------------------------------------
# Text normalization and a flat, searchable view of a document's body text

_CHAR_MAP = {
    "‘": "'", "’": "'", "ʼ": "'", "′": "'", "`": "'",
    "“": '"', "”": '"', "„": '"', "″": '"',
    "–": "-", "—": "-", "‒": "-", "‐": "-", "‑": "-",
    "…": "...",
}
_DROP = {"­", "​", "‌", "‍", ""}

def normalize(s, keep_map=False):
    """Lowercase, unify quotes/dashes, collapse whitespace.

    With keep_map, also return a list mapping each output index to the index
    of the input character it came from.
    """
    out, idx = [], []
    for i, ch in enumerate(s):
        if ch in _DROP:
            continue
        if ch.isspace():
            if out and out[-1] == " ":
                continue
            rep = " "
        else:
            rep = _CHAR_MAP.get(ch, ch).lower()
        for r in rep:
            out.append(r)
            idx.append(i)
    return ("".join(out), idx) if keep_map else "".join(out)

class TextStream:
    """The body text of one document as a single string, with enough
    bookkeeping to map string offsets back to text/tail slots in the tree."""

    def __init__(self, root):
        self.segments = []      # (start, element, "text" | "tail")
        self.id_offsets = {}    # id attribute -> raw offset
        self.block_starts = []  # raw offsets where block elements begin/end
        parts = []
        pos = 0

        def add(el, kind, s):
            nonlocal pos
            self.segments.append((pos, el, kind))
            parts.append(s)
            pos += len(s)

        def walk(el):
            is_elem = isinstance(el.tag, str)
            if is_elem:
                if el.get("id"):
                    self.id_offsets[el.get("id")] = pos
                if el.tag in BLOCK_TAGS:
                    self.block_starts.append(pos)
                if el.text:
                    add(el, "text", el.text)
                for child in el:
                    walk(child)
                    if child.tail:
                        add(child, "tail", child.tail)
                if el.tag in BLOCK_TAGS:
                    self.block_starts.append(pos)

        body = root.find(X("body"))
        walk(body)
        self.raw = "".join(parts)
        self.norm, self.norm_map = normalize(self.raw, keep_map=True)
        self._seg_starts = [s[0] for s in self.segments]

    def raw_offset(self, norm_index):
        return self.norm_map[norm_index] if norm_index < len(self.norm_map) else len(self.raw)

    def norm_offset(self, raw_index):
        # First normalized index whose source is at or after raw_index.
        lo, hi = 0, len(self.norm_map)
        while lo < hi:
            mid = (lo + hi) // 2
            if self.norm_map[mid] < raw_index:
                lo = mid + 1
            else:
                hi = mid
        return lo

    def block_end_after(self, raw_index):
        for b in self.block_starts:
            if b > raw_index:
                return b
        return len(self.raw)

    def segment_before(self, raw_index):
        """The segment containing the character just before raw_index."""
        i = bisect.bisect_right(self._seg_starts, raw_index - 1) - 1
        return self.segments[i]

# --------------------------------------------------------------------------
# Finding the notes

class Note:
    def __init__(self, para, notes_path, link, target_path, target_frag, cue, section):
        self.para = para
        self.notes_path = notes_path
        self.link = link                # the page-number <a>
        self.target_path = target_path  # body document the note refers to
        self.target_frag = target_frag  # page anchor in that document
        self.cue = cue                  # the glossed phrase, as printed
        self.section = section          # index of the notes subsection
        self.number = None              # number within its section
        self.gid = None                 # book-wide unique id number
        self.match = None               # (raw_start, raw_end) in target stream
        self.how = None                 # how the match was found
        self.insert_at = None           # raw offset of the marker

def text_of(el):
    return "".join(el.itertext())

def find_notes(book):
    """Walk the spine from the 'Notes' heading to the next major heading and
    collect every paragraph that starts with a link into the body text."""
    notes = []
    in_notes = False
    section, section_title = -1, ""
    spine_set = set(book.spine)
    for path in book.spine:
        root = book.tree(path).getroot()
        body = root.find(X("body"))
        for el in body.iter():
            if not isinstance(el.tag, str):
                continue
            if el.tag in MAJOR_HEADING_TAGS:
                title = normalize(text_of(el)).strip()
                if title == "notes":
                    in_notes = True
                    continue
                if in_notes and title:
                    return notes
            if not in_notes:
                continue
            if el.tag in HEADING_TAGS:
                section += 1
                section_title = " ".join(text_of(el).split())
                continue
            if el.tag != X("p"):
                continue
            link = next((a for a in el.iter(X("a")) if a.get("href")), None)
            if link is None:
                continue
            link_text = text_of(link).strip()
            full = text_of(el)
            if not link_text or not full.lstrip().startswith(link_text):
                continue
            target_path, frag = book.split_href(path, link.get("href"))
            if target_path not in spine_set or target_path == path:
                continue
            after = full.lstrip()[len(link_text):]
            cue = after.split(":", 1)[0].strip() if ":" in after[:300] else ""
            note = Note(el, path, link, target_path, frag, cue, max(section, 0))
            note.section_title = section_title
            notes.append(note)
    return notes

# --------------------------------------------------------------------------
# Matching cue phrases in the text

_ELLIPSIS = re.compile(r"\s*(?:\.\s*){3,}\s*")
_BRACKETED = re.compile(r"\[[^\]]*\]")

def cue_patterns(cue):
    """(regex, strict) pairs for a cue, from strictest to loosest.  Each
    matches in the normalized text.  Non-strict patterns are only tried near
    the cited page."""
    core = normalize(cue).strip(" \"'.,;")
    if not core:
        return []

    def rx(s, loose_brackets=False):
        chunks = _ELLIPSIS.split(s)
        out = []
        for chunk in chunks:
            chunk = chunk.strip()
            if not chunk:
                continue
            if loose_brackets:
                # "[S]he" in the note may be "She" or "[S]he" in the text.
                pieces = _BRACKETED.split(chunk)
                brackets = _BRACKETED.findall(chunk)
                p = re.escape(pieces[0])
                for b, piece in zip(brackets, pieces[1:]):
                    inner = re.escape(b[1:-1])
                    p += rf"(?:\[?{inner}\]?)?" + re.escape(piece)
                out.append(p)
            else:
                out.append(re.escape(chunk))
        # Elided text between the pieces of a quotation.
        return re.compile(r".{0,600}?".join(out), re.S) if out else None

    pats = [(rx(core), True), (rx(core, loose_brackets=True), True)]

    # Looser: the same words, ignoring punctuation ("‘nice,’ and" vs.
    # "‘nice’ and", "re-emphasise" vs. "reemphasise").
    words = re.findall(r"\w+", _ELLIPSIS.split(core)[0])
    if len(words) >= 2:
        pats.append((re.compile(r"\W*".join(words)), False))
    # Words inserted by the text: "Oh Florence,” he wrote, “what a mean".
    if len(words) >= 3:
        pats.append((re.compile(r"\W+(?:\w+\W+){0,3}?".join(words)), False))
    # The first or last few words, e.g. for a typo in the note ("Ihave").
    if len(words) >= 4:
        pats.append((re.compile(r"\W*".join(words[:3])), False))
        pats.append((re.compile(r"\W*".join(words[-3:])), False))
    # A quotation within the cue: the “oddities and the crudities”.
    for quoted in re.findall(r'"([^"]+)"?', core):
        qwords = re.findall(r"\w+", quoted)
        if len(qwords) >= 2 and len(qwords) < len(words):
            pats.append((re.compile(r"\W*".join(qwords)), False))
    return [(p, strict) for p, strict in pats if p is not None]

def match_notes(book, notes, streams):
    """Find each note's cue in its target document, near its page anchor and
    in note order."""
    last_start = {}  # target path -> norm offset of previous match
    for note in notes:
        stream = streams[note.target_path]
        anchor_raw = stream.id_offsets.get(note.target_frag)
        anchor = stream.norm_offset(anchor_raw) if anchor_raw is not None else 0
        prev = last_start.get(note.target_path, 0)
        # Notes appear in text order, and a cue starts on (or just before)
        # the page the note cites.
        windows = [
            ("page", max(anchor - 400, prev), anchor + 12000),
            ("near", max(anchor - 4000, 0), anchor + 30000),
            ("file", 0, len(stream.norm)),
        ]
        for pi, (pat, strict) in enumerate(cue_patterns(note.cue)):
            for wname, lo, hi in windows if strict else windows[:1]:
                m = pat.search(stream.norm, lo, hi)
                if m:
                    note.match = (stream.raw_offset(m.start()),
                                  stream.raw_offset(m.end() - 1) + 1)
                    note.how = wname if pi == 0 else f"{wname}/loose{pi}"
                    if wname == "page":
                        last_start[note.target_path] = m.start()
                    break
            if note.match:
                break

def choose_insert_points(notes, streams):
    """Decide where each marker goes: after the cue, extended to the end of
    the quotation it starts (if any), then past trailing punctuation.  Never
    past the start of the next cue in the same document or out of the
    paragraph."""
    by_doc = defaultdict(list)
    for n in notes:
        if n.match:
            by_doc[n.target_path].append(n)
    for path, doc_notes in by_doc.items():
        stream = streams[path]
        raw = stream.raw
        starts = sorted(n.match[0] for n in doc_notes)
        for n in doc_notes:
            start, end = n.match
            limit = stream.block_end_after(start)
            later = [s for s in starts if s > start]
            if later:
                limit = min(limit, later[0])
            pos = end
            # If the cue ends inside a quotation, move to the end of it.
            para_start = max((b for b in stream.block_starts if b <= start), default=0)
            through = raw[para_start:end]
            if through.count("“") > through.count("”"):
                close = raw.find("”", pos, limit)
                reopen = raw.find("“", pos, limit)
                if close != -1 and (reopen == -1 or reopen > close) and close - pos < 400:
                    pos = close + 1
            elif normalize(n.cue).lstrip().startswith('"'):
                # A quoted cue with no quotation marks in the text is usually
                # from a block quote: go to the end of the sentence.
                m = re.compile(r"[.?!](?=[\s”’]|$)").search(raw, pos, limit)
                if m and m.end() - pos < 300:
                    pos = m.end()
            while pos < limit and raw[pos] in TRAILING_PUNCT:
                pos += 1
            n.insert_at = pos

# --------------------------------------------------------------------------
# Rewriting the documents

def make_marker(notes, stream_path, book):
    sup = etree.Element(X("sup"))
    sup.set("class", MARKER_CLASS)
    for i, n in enumerate(notes):
        a = etree.SubElement(sup, X("a"))
        a.set("id", REF_ID.format(n.gid))
        a.set("href", book.href(stream_path, n.notes_path, NOTE_ID.format(n.gid)))
        a.text = str(n.number)
        if i < len(notes) - 1:
            a.tail = ","
    return sup

def insert_markers(book, notes, streams):
    by_doc = defaultdict(lambda: defaultdict(list))
    for n in notes:
        if n.insert_at is not None:
            by_doc[n.target_path][n.insert_at].append(n)
    for path, points in by_doc.items():
        stream = streams[path]
        # Back to front, so earlier offsets stay valid.
        for pos in sorted(points, reverse=True):
            group = sorted(points[pos], key=lambda n: n.gid)
            marker = make_marker(group, path, book)
            seg_start, el, kind = stream.segment_before(pos)
            host = el if kind == "text" else el.getparent()
            link = next((a for a in host.iterancestors(X("a")) if a.get("href")),
                        host if host.tag == X("a") and host.get("href") else None)
            if link is not None:
                # Don't nest links: put the marker right after the link.
                marker.tail = link.tail
                link.tail = None
                link.addnext(marker)
                continue
            k = pos - seg_start
            if kind == "text":
                marker.tail = el.text[k:]
                el.text = el.text[:k]
                el.insert(0, marker)
            else:
                marker.tail = el.tail[k:]
                el.tail = el.tail[:k]
                el.addnext(marker)
        book.dirty.add(path)

def rewrite_notes(book, notes):
    for n in notes:
        num = etree.Element(X("a"))
        num.set("class", NOTE_NUM_CLASS)
        num.text = f"{n.number}."
        num.tail = " "
        n.link.addprevious(num)
        if n.para.get("id"):
            num.set("id", NOTE_ID.format(n.gid))
        else:
            n.para.set("id", NOTE_ID.format(n.gid))
        if n.insert_at is not None:
            # The number and the page number both return to the exact spot
            # in the text, not the top of the page.
            back = book.href(n.notes_path, n.target_path, REF_ID.format(n.gid))
            num.set("href", back)
            n.link.set("href", back)
        # "(p. 12)" so the page isn't mistaken for the note number.
        page = text_of(n.link).strip()
        if page.isdigit() and len(n.link) == 0:
            n.link.text = f"(p. {page})"
        book.dirty.add(n.notes_path)

def fix_stylesheets(book):
    """Kobo-oriented CSS fixes that don't change the book's design."""
    for path in book.stylesheets:
        css = book.data[path].decode("utf-8")

        def fix_rule(m):
            selector, body = m.group(1), m.group(2)
            decls = [d.strip() for d in body.split(";") if d.strip()]
            props = {d.split(":", 1)[0].strip().lower(): d for d in decls}
            out = []
            for d in decls:
                prop = d.split(":", 1)[0].strip().lower()
                # A hard-coded font the device doesn't have; let the reader's
                # font setting apply instead.
                if prop == "font-family":
                    continue
                # An indent on centered text pushes it off-center.
                if prop == "text-indent" and "text-align" in props and \
                        "center" in props["text-align"]:
                    continue
                out.append(d)
            if "text-align" in props and "center" in props["text-align"]:
                out.append("text-indent: 0")
            if not out:
                return f"{selector} {{\n    }}"
            return f"{selector} {{\n    " + ";\n    ".join(out) + "\n    }"

        css = re.sub(r"([^{}]+?)\s*\{([^{}]*)\}", fix_rule, css)

        # Headings such as chapter titles are wrapped in a block (originally
        # a <blockquote>, see fix_markup) with a left margin, which shifts
        # centered titles right.
        centered = re.findall(r"(\.[\w-]+)\s*\{[^}]*text-align:\s*center", css)
        if centered:
            css += "\n" + ",\n".join(f"{c} > span" for c in centered) + \
                   " {\n    margin-left: 0;\n    margin-right: 0\n    }\n"
        css += EXTRA_CSS
        book.data[path] = css.encode("utf-8")

def fix_markup(book):
    """Small markup fixes across all content documents."""
    for path in book.spine:
        root = book.tree(path).getroot()
        changed = False
        # <br class="..."> where the class says display: block renders as an
        # extra blank line (or nothing) depending on the reader.
        for br in root.iter(X("br")):
            if br.get("class"):
                del br.attrib["class"]
                changed = True
        # <h3><blockquote>...</blockquote></h3> isn't valid XHTML and strict
        # renderers may mishandle it.  A <span> with the same class (the
        # class already says display: block) renders the same and is valid.
        for heading in [e for e in root.iter() if e.tag in HEADING_TAGS]:
            for bq in heading.iter(X("blockquote")):
                bq.tag = X("span")
                changed = True
        # Cover pages stretched to the screen with preserveAspectRatio="none".
        for svg in root.iter(f"{{{SVG_NS}}}svg"):
            if svg.get("preserveAspectRatio") == "none":
                svg.set("preserveAspectRatio", "xMidYMid meet")
                changed = True
        if changed:
            book.dirty.add(path)

# --------------------------------------------------------------------------

def context(stream, pos, width=60):
    s = stream.raw[max(0, pos - width):pos] + "⟦*⟧" + stream.raw[pos:pos + 25]
    return " ".join(s.split())

def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("epub")
    ap.add_argument("-o", "--output", help="output path (default: '<name> - linked notes.epub')")
    ap.add_argument("--report", help="write a line per note showing where its marker went")
    args = ap.parse_args()

    out = args.output or re.sub(r"\.epub$", "", args.epub, flags=re.I) + " - linked notes.epub"
    book = Book(args.epub)

    notes = find_notes(book)
    if not notes:
        sys.exit("No notes found (looked for a 'Notes' heading followed by "
                 "paragraphs starting with page links).")
    # Number notes within each notes subsection (i.e. per chapter).
    counters = defaultdict(int)
    for gid, n in enumerate(notes, 1):
        counters[n.section] += 1
        n.number = counters[n.section]
        n.gid = gid

    streams = {p: TextStream(book.tree(p).getroot()) for p in {n.target_path for n in notes}}
    match_notes(book, notes, streams)
    choose_insert_points(notes, streams)

    if args.report:
        with open(args.report, "w", encoding="utf-8") as f:
            for n in notes:
                where = (context(streams[n.target_path], n.insert_at)
                         if n.insert_at is not None else "NOT FOUND")
                f.write(f"[{n.section_title} / {n.number}] ({n.how or '-'}) {n.cue}\n"
                        f"    {where}\n")

    insert_markers(book, notes, streams)
    rewrite_notes(book, notes)
    fix_markup(book)
    fix_stylesheets(book)
    book.write(out)

    found = sum(1 for n in notes if n.insert_at is not None)
    loose = sum(1 for n in notes if n.how and n.how != "page")
    print(f"{len(notes)} notes, {found} linked into the text "
          f"({loose} needed a looser match - worth a glance in the report).")
    for n in notes:
        if n.insert_at is None:
            print(f"  not found: {n.section_title}, note {n.number}: {n.cue!r}")
    print(f"Wrote {out}")

if __name__ == "__main__":
    main()

Claude automemory, Nix, and .git

I’m running into a complicated snarl of things in my server management. Long story short: both Claude and Nix make assumptions based on your current working directory and where the nearest .git folder are. You may want to manage that carefully.

Claude Code has a couple of features that are defined “per project”. The one I care about is automemory, where Claude records little things about your projects. The directory Claude attaches these memories to seems to be the top level directory that has something named .git in it. That means if you have git repos in nested directories, the memories are attached to the largest scope.

Nix also has features where it scans all the files in a directory with a .git in it, assuming they belong to the NixOS build you’re doing. This caused me various problems that I can’t really explain.

My fix for all of these is for a sever project like “caddy”, I have a directory with a .git repo in it called src/ai/servers/sfpve/caddy/repo. I launch Claude from inside src/ai/servers/sfpve/caddy, where there is no .git. The memories then attach up to the src/ai/servers/ parent directory where I want them. Claude Code itself is launching Nix and somehow this helps it manage Nix’s magic with .git.

It’s more complicated than that in reality and I don’t actually understand what I’ve done or whether it’s a good idea. But Claude using the location of a .git to decide where automemory goes was helpful for me to learn.

BBR, Proxmox containers, and Starlink

I tried to sync a bunch of big data last night and only got 5MBytes/s despite 30MBytes/s being expected. The fix turned out to be enabling BBR congestion control on the Proxmox host and container I was syncing from.

In detail... I first learned about BBR congestion control three years ago. It’s an alternative TCP congestion control algorithm you enable on a server. It greatly improves performance for Starlink clients connecting to that server. Enabling BBR instantly boosted rsync performance from 5MB/s to 30MB/s for me: that is expected. It’s so extreme because of the high packet loss of Starlink. It’s probably the same for clients on cellular links.

To enable BBR in a container, the easiest way is just to enable BBR in the Proxmox host and then restart the container. On Proxmox:

# Load and enable BBR right now without reboot
modprobe tcp_bbr
sysctl -w net.ipv4.tcp_congestion_control=bbr

# Enable BBR on reboot
echo tcp_bbr >| /etc/modules-load.d/bbr.conf
echo 'net.ipv4.tcp_congestion_control = bbr' >| /etc/sysctl.d/90-bbr.conf

It is not necessary to explicitly enable BBR in containers. They will pick up the Proxmox host’s congestion control algorithm on restart. However any existing containers won’t switch immediately. You can run this in the container to switch without restarting:

sysctl -w net.ipv4.tcp_congestion_control=bbr

It is probably necessary to enable BBR in any VMs you have. I haven’t tested this but it must be this way since the VM has its own kernel and TCP/IP stack.

It is possible to have containers have different algorithms than the Proxmox server or each other. I didn’t test this but Claude Code was telling me I needed to load the modules in the Proxmox server and then set net.ipv4.tcp_allowed_congestion_control= reno cubic bbr. After than containers can choose their own algorithm.

(Claude Code was a big help in diagnosing and fixing this problem. I understand all the commands above and tested them myself.)

I continue to wonder why BBR isn’t the default on Linux. Apparently it can cause contention problems if every server isn’t using BBR. Also so much server traffic these days is QUIC and it has its own congestion control. The TCP setting doesn’t matter to a lot of servers.

rsync --append trap

I learned something from Claude Code today. rsync --append isn’t very safe. The common pattern of rsync --partial --append is suggested as a way to copy files and allow resume. That’s not a good idea to put in recurring sync jobs you run regularly over a long period of time.

The problem is --append won’t retransfer a file in many circumstances if the contents changed. And it only writes new data. It is append only and rsync’s man page warns it is “only applicable to update files that are known to be growing larger, that is, where any existing content on the receiving side is also known to be the same as the content on the sender”. If the file changes on the sending side, it can cause all sorts of corruption on the receiver.

I was using rsync --append to sync video between two machines once a week. But the source occasionally updated files in-place when I got better copies of the video. The destination wouldn’t replace the file when the source changed and so my destination slowly got out of sync.

Before 2008 and rsync 3.0, rsync did more checking with --append. So old advice may not have been wrong at the time.

In modern rsync there’s a --append-verify that will help but won’t catch the case where the updated file is smaller than the original. --append will still skip it in that case.

Claude Code advises me to not use --append at all, it’s the --partial that does the work of allowing resumes (for network copies). There’s also a --partial-dir which keeps partial downloads in an out-of-sight directory until they’re done.

If you’ve been running --append on a mirror, do an rsync -c to verify checksums and find damaged files.

Claude Code, Nix, ssh, and Linux

Claude Code figured out it could use my Desktop ssh agent and did some surprising things on remote systems. Thankfully it only did good things but it was alarming. In short: the problem was I’d set allowAllUnixSockets: true to make Nix work. That enabled ssh access and Claude was smart enough to discover it. Details and a fix below.

ssh agents

ssh agents work by having a daemon listening on a Unix socket. Mine is in /run/user/1000/ssh-agent.socket and $SSH_AUTH_SOCK points to it. Claude is ambitious enough to find and use this agent to access other machines if it helps get a job done. The default sandbox denies access to Unix sockets though, so it’s usually prevented. But...

Nix

Nix’s default install has some elaborate daemon setup to do Nix operations like building new artifacts. The client tools talk to it via a Unix domain socket /nix/var/nix/daemon-socket/socket. That wasn’t working for Claude Code because the default sandbox disallows access to all Unix sockets. (Many are sensitive!) So the devil suggested I augment the sandbox with the policy allowAllUnixSockets: true. And then Nix worked! Only now Claude had access to all sockets. Including ssh-agent.

The fix on MacOS

I can’t test this, but the very sensible fix on MacOS is instead of giving access all Unix sockets, just set "allowUnixSockets": ["/nix/var/nix/daemon-socket/socket"].

Unfortunately this doesn’t work on Linux right now (Sep 2026), some limitation of the sandboxing system. The directive is a no-op on Linux so no access is allowed (and no warning). Your only easy option is to enable all sockets.

The fix on Linux

I’m not certain, but the best I can do on Linux is enable access to all sockets, then disable one by one “dangerous” sockets that Claude might try to use. Claude suggested this configuration based on what it found on my system today:

  "sandbox": {
    "credentials": {
      "envVars": [
        { "name": "SSH_AUTH_SOCK", "mode": "deny" },
        { "name": "SSH_AGENT_PID", "mode": "deny" }
      ],
      "files": [
        { "path": "~/.ssh", "mode": "deny" },
        { "path": "~/.aws/credentials", "mode": "deny" },
        { "path": "/run/user/1000/ssh-agent.socket", "mode": "deny" },
        { "path": "/run/user/1000/gnupg", "mode": "deny" },
        { "path": "/run/user/1000/op-daemon.sock", "mode": "deny" },
        { "path": "/run/user/1000/1Password-BrowserSupport.sock", "mode": "deny" },
        { "path": "/run/user/1000/kwallet5.socket", "mode": "deny" },
        { "path": "/run/user/1000/bus", "mode": "deny" }
      ]
    }
  }

Of course blacklisting some sockets is terrible security, no doubt next week (or next ssh session) some new socket I haven’t blacklisted will be created. Docker is a good example: its sockets are very powerful and I haven’t thought to block it here. (Might not want to, having Claude drive Docker is useful!)

Basically the Linux sandbox isn’t strong enough to protect against a real adversary. But Claude isn’t an adversary. It’s an enthusiastic and very curious puppy. I think it provides helpful protection to put puppy gates across the doors you don’t want it to go through.

The problem is Claude is also the devil. A very persistent one. If you ask it to try hard to get something done it will. It’d be much better to have a more solid sandbox stopping it. Hopefully they fix this limitation about only allowing certain Unix sockets soon. There’s various bug reports about it but I haven’t researched them.

I wonder if there’s some other way to let Nix do its thing without a Unix domain socket, or with some proxy script that Claude is allowed to use.

Vault: my new file storage

After some 35 years of ad hoc carrying files around from place to place, I finally have all my important digital files in one well built storage system I’m calling “Vault”. More or less like a lot of people do with a NAS, but a little different.

Hardware

Vault is a Linux container running on Proxmox in SF. It stores files to three ZFS pools managed by Proxmox. One small volume for important small files on NVMe storage (two devices, mirrored). One large volume of large media files on spinning rust (again, a mirror). And one large volume of backups on spinning rust (single disk). There’s also offsite backups of everything but the video files to Backblaze B2.

Software

So far that’s pretty basic. The slightly unusual thing is what software runs on vault. Note this whole thing is LAN and Tailnet only, not on a public network. The setup was all built via AI but the big choices are mine.

  • Proxmox and ZFS for the hardware management. Tailscale for network access.
  • NixOS in a privileged LXC container for the vault operating system. Nix is my new thing for using AI to build servers. The declarative system seems a good match for coding agents.
  • No NFS or SMB. That’s the weirdest choice I made. I’ve never liked synchronous network filesystems, they are lies. It would be easy to add one of these but I don’t need it.
  • Syncthing. The most important volume I store is all my source code, about 15GB of my career over 35 years. I sync this to several different computers. I’ve been using Syncthing for years and it is a reliable workhorse. This is what I use instead of a network filesystem, particularly when working in Grass Valley.
  • sftp/sshfs. For needing to access a remote file outside of src. Purely for ad hoc use, this is very easy in the Linux Dolphin file manager. I could set up a FUSE mount too.
  • bind mounts and virtiofs. This is what allows a container on the SF Proxmox host to access the files in the Vault’s ZFS pools. Vault itself is working through bind mounts to the volumes. virtiofs is a relatively new option for the same thing for VMs. (I used to use NFS for that.)
  • Restic for backups. Both to a local disk and also offsite to B2.
  • File Browser for web access to files. Not sure I really need this, and the project just got shut down, but it’s there.
  • plocate for finding files. This is really not adequate: I have to ssh in and all it does is grep filenames. But it’s something. One big project I’m considering is some fancy full text indexing of all the contents and their metadata. That’s an endless project, I wonder if there’s something good off the shelf I can use.
  • ntfy.sh for notifications. What a great little service! I just use the public free tier, it’s enough for my needs and very easy to use

AI development

I bought the hard drives for this project in 2024. I even got halfway through building a Debian VM to manage everything, poorly, and then abandoned it because I couldn’t see a path forward to trusting this thing with my files.

I built the whole thing with Claude Code and Opus/High in 5 days.

Claude was active about 23 hours of that time. Me, maybe 10 hours? It used $205 in credits but all fit in the $20/mo subscription.

The process mostly went well. I had it come up with a design, then a work plan, then we stepped through tasks. I gave Claude more power than I have in previous projects and that was a good choice. But then I also had a lot of verification steps, including full backup tests outside Claude’s control. (I’m still trusting Claude somewhat: on my own I’m testing backup integrity and completeness but only spot checking identical files. Claude says it checked every single file.)

We made one major mistake. Part of the consolidation involved changing the UID for my files. I still have a VM that uses the old UID and so now it can’t write some files it used to be able to. (Unfortunately Proxmox’ UI for virtiofs doesn’t support any way to map UIDs.) It’s not a big deal, and I plan to shut that VM down entirely. Claude mostly was working to anticipate and avoid problems like this, as was I, but we both missed this one.

Overall the AI did a much better job than I would have. It got it done with no drama and with better testing and monitoring and backups than I’d ever manage on my own. I’m a total AI convert for this kind of project now.

Giving Claude Code the keys

I’m setting up a new server at home with Claude and NixOS. It’s a NAS-like thing for all my precious files, I’ll talk more about it later. Wanted to note here how I’m working with Claude.

In three devops projects I’ve gone from “talk to Claude and run all the commands myself” to “trust Claude to build a server VM but do all the config work by hand” to “trust Claude with access to Proxmox to create and maintain a server VM”. This Proxmox server is all my important stuff! It’s scary. But it’s also very nice letting an AI do the work.

I’m not insane, I do have backups of everything precious. A truly malicious Claude could probably destroy those backups too. But I’m trusting the agent isn’t adversarial. My goal is to just make it so an honest mistake isn’t catastrophic.

Protections

The first protection was giving Claude clear limits on what I wanted it to do. Don’t delete any data. Only work to make a single container with ID 300. Only use certain resources. Claude seems to be trying to obey those limits in good faith.

One simple protection: Claude mounted my precious data read-only to copy it into the new system. That was its idea and it’s a good one, I feel much safer that way.

I gave Claude an unrestricted ssh login with sudo access. One nice thing it did was make a very precise sudoers file. So for instance pct create 300 is allowed to create a container with id 300, but it doesn’t have general access to pct to manipulate all the containers. I’m not confident the sudo restrictions are complete. And I’m sure a malicious Claude could escalate privileges with the access it has. But it seems to help prevent accidents.

Claude has no trouble sshing to my box. I’m a little confused about this: the default sandbox restricts networking to localhost only plus one HTTP proxy. But Claude just happily writes a script to proxy ssh through HTTP (using the CONNECT command). I don’t know if this is Claude working as intended or if its entire mode of accessing my computer is an exploit.

One thing that did not work great is trying to get Claude to interactively ask me for any commands it runs as root. The new defaults in Claude let it run anything the heuristic checker approves. That’s a lot of things! Including ssh server sudo * (although there may be some restrictions on *. I want to review each command, so I overrode that by explicitly listing commands that I should be asked for. But that matching is very literal. And Claude keeps coming up with new ways to invoke ssh. So now I have something like this in the permissions file:

    "ask": [
      "Bash(ssh -F /home/nelson/.local/state/claude/ssh_config claude@sfpve:*)",
      "Bash(ssh -F /home/nelson/.local/state/claude/ssh_config sfpve:*)",
      "Bash(ssh -F ~/.local/state/claude/ssh_config claude@sfpve:*)",
      "Bash(ssh -F ~/.local/state/claude/ssh_config sfpve:*)",
      "Bash(ssh claude@sfpve:*)",
      "Bash(ssh sfpve:*)",
    ]

There’s nothing stopping Claude from coming up with yet another way to ssh into the box, bypassing these checks. Maybe this is fixable with a smarter glob, not sure.

Update Sep 21

After watching what Claude does some more I got nervous and decided to not give it this much access to Proxmox. I’m fine with it managing individual containers but Proxmox is too much.

For initial setup of a new container I’m having the agent write a shell script I run as root on Proxmox. I look at it closely. It’s basically just a single pct create in the simple case.

For managing a container that has tailscale, Claude has no more access at all to Proxmox. If the container doesn’t even have tailscale I’m giving Claude ssh access to sfpve but solely to run ssh -J to forward into the container via the local IP address. Something like this in the authorized_keys: restrict,port-forwarding,permitopen=”192.168.0.108:22″,command=”/bin/false”

Alarming behavior

Claude did two things that made me nervous.

  • Claude deleted some data despite being told to never delete data. It used rclone to remove something from Google Drive. We’d just established I had other copies of the data and wanted to delete it, so it was reasonable enough to delete the data, and really it only moved it to Trash anyway. But still, it violated a direct limit.
  • A new project went grubbing through other Claude project history, found the ssh key it had, and happily used that to give itself access to answer some questions about the Proxmox setup for something else. It was doing what I asked of it, and I did tell it to try to work autonomously and not bother me. But it got a little frisky letting itself in the door with its cousin’s keys.

Another major problem in my environment.. I use an SSH agent and SSH_AUTH_SOCK is available to Claude. I’m not sure it can normally access that. But Claude convinced me to give it "allowAllUnixSockets": true in its sandbox so it could do Nix things. That enables access to the SSH agent socket, too.

I’m currently testing giving it permission just to talk to Nix and no other sockets via "allowUnixSockets": ["/nix/var/nix/daemon-socket/socket"] but hit a snag. more tomorrow.

No, Opus is really good at reasoning

I’m genuinely flummoxed by how good Opus is at some sysadmin tasks. Today I asked it:

I need some way to manage all the web page content that’s stored on the server. right now the authoritative copy is on the server and the restic backup is the only stopgap. and if I want to change something I live-edit it on the server, or at best live-edit it on a copy and then sync it over. that seems too ad hoc, I should have a content here on my dev machine and some process to sync it. ... help me figure out what to do.

I did not propose a solution. Claude/Opus reasoned very well to get to a solution for me. It’s thinking is clearer than my own!

The AI inventoried all my files. Then it came up with three sensible groups.

  1. Truly hand-edited files that change sometimes
  2. Files that only exist on the server but are archival and never really change
  3. Files that actually exist elsewhere and already are being synced to the server.

It came up with those groups itself. It was using some knowledge from previous discussions (particularly about the synced-from-elsewhere group 3) and I think inferring the archival idea of group 2 from the sizes and ages of files.

It then proposed treating each of the three categories separately. And building a special publish tool for group 1, so I can have them in git on my dev machine and then sync them over. No new publish tool needed for group 3, I already have tools doing that. And no publish tool needed for group 2 at all. Backups are sufficient.

One wrinkle: the AI proposed a fairly minimal solution for solving the problem of me hand-editing the same file in group 1 in both places. (The naive solution has one edit clobbering the other, it suggested adding a --dry-run flag). I asked it to do something more automatic and it came up with a reasonable thing involving touching a sentinel file after each sync and then using find to see if anything had changed. This isn’t super fancy, but it sure is sensible.

This AI is solving design problems as well as I could with very little direction. And I know it will go off and implement it very competently for me. It’s not just saving me time, it’s doing a good job of it.

An AI server project

For nearly 20 years I’ve hand-maintained an Ubuntu Linux server for somebits.com. Every few years I had to recreate it from scratch, a tedious process involving a couple of days of forensics, editing config files, watching logs... so boring. And often stressful because I was doing it only after the old server had died.

No more. I now have a brand new server running NixOS. Here’s the thing. I don’t really know Nix. I played with it once for about an hour and thought “this is cool but too much to learn”.

Thanks to Claude Code and Opus I don’t have to learn it. The AI knows it already. And I think NixOS is a good match for an AI. The whole thing is declarative, you configure the server with some basic text files. AIs are good at writing text and testing the results!

The result worked spectacularly: way better than I expected. I thought I’d tinker with this for a week and learn how poorly AIs are at this complex a task. Instead it got it done for me in about a day and I was ready to switch over. I’m confident Claude did a better job than I would have myself, and much much faster.

The project took 270M tokens, 6M of which were actual work (the rest is cache). Claude values that at about $200 although I did it all in my $20/mo plan.

How I worked with Claude

In the past I haven’t trusted Claude to do complex things with live sites but this time I was setting up a brand new server so was willing to go full YOLO. The more work it did, the better.

I first wrote a page-long README explaining what I wanted to Claude and asking it to come up with a design document. I described the server, pointed it to my old notes, copied off some config files for it to look at, and told Claude I wanted it to do as much work itself as possible. I also suggested Nix. We talked back and forth for awhile and it drafted a 15 page design document. Too much to read! But I skimmed it and suggested some changes. Honestly it was Claude itself that was going to be reading this thing frequently. This whole design process took an hour or two back and forth.

Then I started a new Claude session and asked it to create a work plan. It came up with about 12 pages of specific tasks, each labelled as to whether Claude could do it or I could. (In general I only gave it access to the new server so I had to manually do things to DNS entries, the old server, etc.) One key thing it started doing here was asking for more data from the server, writing scripts for me to run to collect things it wanted to inspect. It made good choices. Again this took a couple of hours.

Then I fired off Claude sessions over a day or so to do the actual work. The work plan was helpful here: each Claude session new what to do or what to tell me to do for it. And I had some idea what it was going to do. Mostly it stuck to the plan and resisted the urge to add things to it: we did create a future work document for new ideas that came up. This process took maybe 4 hours? Some of the time was spent waiting for long network test jobs to finish.

The actual building of the Nix config files went remarkably quickly. The real work was all the testing, particularly in the final phases. Claude was way more thorough than I would have been which was reassuring. OTOH I don’t really know how complete those tests are. They seemed pretty good to me.

I started new Claude sessions every hour or two, after major work. The context window gets full. And anecdotally AIs get dumber as the context gets longer. Automatic compaction is supposed to help with that but I don’t trust it. I’d prefer Claude to dump its thinking into permanent documents that it rereads in a new session, that way I can read them too. The design and work plan docs were the big ones.

Claude Code also keeps a memory. Most of it is technical notes but it’s also developing a theory of my own personality.

  • He wants to be able to verify things himself
  • He values finding what was missed over being reassured
  • He gives blanket “work alone” permission for a stretch and expects a plain report at the end

I still need to have one more session with Claude to tell it to summarize the work it did and document things. It created a lot of scripts, some of which I will want to use. Again these docs are partly for me, partly information for future AI agents.

Thoughts on using AI for devops

This is the first project where I really trusted Claude Code to do things, as an agent, to make server changes and lots of network requests. It worked fine. Great, actually!

This is also the first project where I think Claude did a better job of the work than I would have. First, I don’t know Nix, and while I could have learned it on the fly it would have taken a lot of time and I wouldn’t have been good at it. Also Claude was just much more organized and thoughtful about server setup tasks and how to verify they worked correctly. And it thought of a lot of things I wouldn’t have, like the subtleties of the new server having an IPv6 address.

The magic thing here is how self-directed Claude/Opus was. It came up with its own idea about how to figure out what was on the server. Then came up with its own tests, like a complete set of 150,000 URLs (from Apache logs) to verify and then a 6000 URL sample to run for development work and a 22 URL sample for a smoke test. It wanted to actually test all 150,000 for a final ch eck and I told it that was too much so it whittled it down to 17,000 URLs that would test all the important paths through the server configs.

I’m trying to think what didn’t go well and not coming up with a lot. Opus is awfully wordy though, it’s a bit exhausting to talk to. Maybe I’ll find out something big went wrong in the next few days.

I do need to double back and learn to read the nix configuration files, or at least understand them. Maybe I’ll find something awful in them but on first look they are reasonable.

If I were a working sysadmin I’d be real nervous about my job now. I guess most of them already are. There’s still room for a human in the loop, at least for now. I felt like I had to manage Claude’s work, I gave it a lot of guidance in how to do certain things, and I was riding it pretty hard to verify its work. But the job I did was more like someone managing devops folks with 5+ years experience than being that devops person. This suits me fine, but it is alarming for my industry.

Kobo eReader customizing

I just got a Kobo Clara BW ereader. This seems to be the recommended “not an Amazon Kindle” ebook device. Relatively inexpensive, decent hardware, and a fairly open platform. Some notes as I tinker with it.

Loading books

I guess Kobo has its own store or something? I got this device to read books from all over, not so much to buy books from their catalog.

Adding a new book you already have is as simple as dragging the .epub file to it via USB. It can go anywhere in the filesystem, I made a new Books directory for things. Kobos support some other formats too but epub is the best choice.

Standard Ebooks is an excellent source for free, well edited books that are out of copyright. Note they have a special kepub format that supposedly works better on Kobos. A regular epub will work too.

Kobo also has Libby / Overdrive integration so you can get library books easily. You have to log in through the ereader’s settings program, which gives you a qrcode to scan on your phone. I haven’t seen this actually work yet because I don’t have any books on loan.

I think there’s a built-in web browser you can use to download ebooks directly on the device from our friend Anna or wherever.

If you install KOReader (see below) you can also browse OPDS catalogs which makes it very easy to download books on the fly direct to the device. Standard Ebooks publishes an OPDS server. You can also install Calibre-Web for yourself to give yourself access to a private book collection via OPDS.

Customizing the book reader

I found the reader’s default visual settings surprisingly bad. Some of that may be the formatting of the epubs themselves. But there’s various options you can tweak in the book reader to improve things.

The main thing I did was download the Charis font and install it via USB to the fonts directory. (4 files: Regular, Bold, Italic, BoldItalic.) This is a lovely serif font designed for book reading. It’s attractive without having too much personality.

Beyond that I tweaked the margins to use the full screen. (The device is tiny! Why reserve half an inch of blank screen on either side?!) Then font size to get it to about 8 words a line, tightened up the line spacing. And turned off the footer, epub page numbers, and book progress bar.

Customizing the software

Kobo is a pretty hackable Linux system. My main goal was to get KOReader installed, that’s a popular open source document reader with all the bells and whistles. I followed this guide to get going which has you installing the one click package which gives you a choice of KOReader and/or Plato for reading, also KFMon and NickelMenu for customizing the system. It was very easy to install and worked right out the box.

Having done all that I think I’m happy with the stock Kobo reader. KOReader is your classic open source UX disaster, a zillion settings. Very powerful and I may yet get into it if I need to do something complex. I do like the option to have Readest integration. Plato was a much nicer reading experience but then it doesn’t do as much, not sure why I’d choose it. For basic reading I think Kobo’s got me covered.

The device is open enough you can install a lot of Linux stuff like an ssh server (for rsync), various image displays, a Z-Machine emulator for text adventure games, or a full Linux userspace. Not sure why I’d want to do all that on a device about as powerful as a 2010 cell phone but it’s neat that it’s a general purpose device.

Postcards AI hacking

Just finished a big AI coding project, my travel postcards. I’m very happy with how it turned out. (I’m talking about AI code but this post is written entirely by me.)

I’d originally created a simple thread unroller for my Mastodon posts using an old version of Claude Code and then later Jules + Gemini Flash 3.5. It worked well on a relatively simple task, the Mastodon threads I create are very tidy.

But I’ve been tweeting about trips since 2009 and not always so organized. So I set Claude + Opus 5 to work on a recovery task, to collect all the old travel threads. It did very well, way better than I would have done on my own. I never would have done all this work myself.

(An aside: AI coding is very divisive. One argument is “it doesn’t work very well”. I think that’s just wrong. AI coding can work very well indeed. This experience with Opus 5 was really good, it’s a major improvement over the older models. And this task is well suited to AI. I don’t really care much about the code quality. And it’s easy to inspect the final output and determine if it’s working.)

Interesting work we did

The basic recovery project was pretty simple: take some old Storify posts and my Twitter archive export and tell the AI to write a program to find and organize all the trip tweets.

I gave it a pretty open-ended brief for this and didn’t suggest how to do it. It tried out various heuristics and tested them against one known-good output I already had hand edited. It finally settled on a combination of the text using travel words and city names plus looking at timestamps on tweets for when I was apparently in a different time zone. I really appreciated its proactive autonomy, both for coming up with heuristics and for validating them.

Recovering photos was a harder problem. Twitter’s export archive doesn’t contain full resolution images. And for older tweets there isn’t an image at all, sometimes all you have is a dead twitpic URL.

I would have given up, just accepted the low-res photos and lost images. The AI was much more persistent and found hundreds of photos for me. Some of the strategies it came up with:

  • Finding Flickr photos in my Flickr data export by realizing that the URLs in the tweets were base-58 encoded versions of the IDs in the export.
  • Finding Twitpic and Yfrog images on the Wayback Machine. (Sorry Brewster, y’all throttled me a lot.)
  • Matching low-res photos from the recovery process with higher res originals in my Google Photos export using image-similarity heuristics that it chose and validated itself.
  • Matching cropped photos from the recovery process into uncropped originals on Google Photos by guessing what crop I applied and matching similar images. This was slow but it worked and helped recover a bunch of photos from India.
  • Where no image from Twitter was available, finding photos in Google Photos based solely on timestamps.
  • The only thing it didn’t try was matching my tweet text (“picture of my ice cream!”) to a semantic analysis of the images (identifying pictures of ice cream). I know the AIs are capable of doing vision but I didn’t ask it to and it didn’t volunteer.

A key part of working with AI is knowing when you can just trust its output, when you can have it effectively validate its own output, and when you need to step in and validate it yourself. I spent a lot of time skimming over the output pages it was generating making sure they were plausible. And in several places I had it write tools to let me do editorial work myself, like picking photos when they were ambiguous.

Some AI things that worked

Early on Claude was giving me markdown files to hand-edit to make some editorial decisions. That’s tedious, so I asked the agent to write a basic Web GUI tool that was a custom editor for the task. That was so easy and productive I ended up having it build several tools. times. I would never ever write a throwaway task-specific GUI tool for my own project, it would take hours or days. But Claude got it done in 10 minutes.

I was surprised with how well Opus 5 did with open ended tasks. (I started out on XHigh effort, then dropped to High). I quickly learned to just describe the result I wanted rather than try to lead it by the nose on how to achieve that result. Sometimes it surprised me with what it came up with! And it saved me a lot of work. Opus is very capable, this kind of high level thing wouldn’t work nearly as well with a dumber AI. (You know, the ones that are just six months old...)

Having big data exports from Google, Twitter, and Flickr was a huge help. Those data dumps are hard to work with, they’re often just a big pile of JSON files and images and no organization. It’s 53GB of stuff for Google Photos! But the AI is very good at that kind of thing. I just pointed it at the .zip and said “figure this out” and it did.

Some AI things that didn’t work

The code the AI wrote seems to mostly work but I didn’t read any of it. I’m sure there are horrors there. But I don’t care for this project: as long as the AI can understand it’s own code it’s fine.

The code did run fine. But sometimes it was awfully slow. For instance for the image matching was taking minutes for each post. I aborted it and said “make this faster”. And so it did, mostly by rewriting the code to use numpy. I wish it had taken the initiative to make it faster itself. I wonder if Claude Code could be given agent instructions about when it was worth spending extra time to optimize something instead of relying on me to notice.

I don’t really know if the code is right. It wrote some 600 unit tests but they could be useless for all I know. I was validating the output by eye. If I were more serious about this as a real product I’d write my own high level system integration tests to really validate the output. Or at the very least have the AI write those tests and check very closely they are correct.

Claude is very verbose. It’s really quite annoying when talking to the AI agent and I bet the code is chatty too. This seems to be a problem with all LLM systems. Nothing it’s saying is particularly redundant or wrong, but there is an awful lot of it. Almost like it was talking to another LLM...

The workflow Claude came up with for the recovery process was very complex. I ran tool A and it’d generate a partial config file which tool B could use to get more data for the config file. Then run tools C and D to process, then go back and run tool A again with that extra data, etc etc. I never could quite figure out how to run it all correctly. This is mostly my fault, it reflects the iterative way we designed the whole thing. The good news is Claude itself knew how to run its own tools and was good at diagnosing and fixing failures, so I gave up trying to understand how to run it myself and just had Claude run it for me. That’s OK for a one-off hack like the recovery process. The Mastodon unroller I plan to keep using is much more tightly designed.

Some reflection

Claude tells me we spent about 20 hours working on this over 5 days. I typed 177 prompts to the agent. It processed just about 1 billion tokens in 4200 API calls. It says that’s nominally $685 worth of API usage although I did it all in the bounds of my $20/mo subscription.

Tokei says it’s 14,450 lines of Python code plus another 8600 lines of test code. That feels like an awful lot, I’d have guessed ⅕ that size if I wrote this carefully by hand.

I dunno how I feel about all this. Impressed, mostly. A little sad, I’ve always enjoyed crafting good code and I feel like that skill is suddenly much less useful. But honestly I haven’t been doing much of that in years now. I had a lot of fun getting an AI to build this for me.

I don’t love the emotional experience of working with Claude Code. It’s just fast enough that you mostly want to be paying attention, but still slow enough you get bored and do something in parallel. Most prompts I was typing were 2-15 minutes of work? I liked the Jules asynchronous model better, but then you have to trust it to work autonomously for longer tasks.

I still wouldn’t use an AI for something where the code quality really matters. Or rather I’d use it much more carefully. But for a data processing one-off job? It sure did a good job here.

Cleaning up my hosted services

I’ve got a shiny new dashboard and consistent access to all my home services! It’s very nice.

Since adopting Proxmox a couple of years ago I’ve grown to hosting a bunch of my own services. I didn’t really think about how I accessed them: I just threw them all on Tailscale and accessed them ad hoc. Each with their own URL on a random port, password, failing SSL, etc.

In this new setup I have a gateway that proxies requests to backend services. I have a single wildcard domain for them all. So linkding.private.example.com gets me to linkding instead of linkding.some-nonce.ts.net:9090. And SSL works. For some services, the gateway running at private.example.com could even handle authentication so I don’t have to use Linkding’s own password system. And in theory this system is safe to run on the public Internet, but in the last minute I chickened out.

Gateway: Reverse proxy

¾ of the value of my setup is running Caddy as a reverse proxy for *.private.example.com. I wish I’d done this a long time ago! Now all my requests go to one proxy web server with a wildcard domain. It’s much nicer than setting up tailscale on each service container. And Caddy makes SSL easy so I no longer have to click through a bunch of SSL errors.

Setting this up is pretty easy, mostly it’s just a bunch of config blocks like

        @linkding host linkding.private.example.com
        handle @linkding {
                reverse_proxy 192.168.0.34:9090
        }

A few of the services get persnickety about the hostname on the request matching their idea of their hostname, so you have to tell them to accept the proxy name as theirs.

Gateway: Authelia

The complicating factor on the gateway is I have Caddy set up to only proxy requests if I’m authenticated via Authelia. That works by setting up something like this in Caddy and including it in each service definition:

(authelia) {
        forward_auth 127.0.0.1:9091 {
                uri /api/authz/forward-auth
                copy_headers Remote-User Remote-Groups Remote-Name Remote-Email
        }
}

There’s a bunch of extra work to configure Authelia. For simple things a basic policy: two_factor rule is sufficient, Authelia will demand I log in before forwarding requests. For Linkding I had to add a special bypass rule for /api/ so that the Chrome extension worked.

I’m not sure Authelia was worth the trouble. Originally I did all this because I wanted to make this gateway host be on the public Internet, and so of course authentication is important. I think the config I have is secure to do that. But it’s complicated and I don’t really trust it, so at the last minute I put the gateway on my Tailnet instead of the public Internet. That’s fine for me.

The neat thing about this gateway approach is it works for multiple users. If I had many people accessing my backend services, possibly not from the tailnet, I’d commit to building trust.

The other nice thing Authelia can do is single sign-on. I log in to Authelia as Nelson, then it tells the backend services I’m Nelson and they trust that. Sometimes this works with a simple HTTP header, sometimes you need something more complex like OIDC.

I did set up proxied authentication for the linkding service. It was remarkably complicated, the key config is telling linkding LD_AUTH_PROXY_USERNAME_HEADER=HTTP_REMOTE_USER.

Every backend service has a different setup. And of course this means fully trusting Authelia’s authentication, it’s a little scary. I may do more of this in the future but for now I still have a bunch of passwords.

Homepage

The other part of this project was setting up Homepage, a simple website which serves as a lightweight dashboard + bookmarks for services. I like how it works, everything’s configured in one simple file and it’s pretty stateless. I’ll see how useful this is as a UI, I’m hoping it replaces my unwieldy list of bookmarks.

Sysadmin in the age of Claude

I never would have tried a project this complex without AI help. I used to love tinkering with this kind of stuff. But as I’ve gotten older and more retired I’ve gotten crankier about learning new things.

But using Claude is a marvel. I mostly did this with Opus/High and it was mostly right. I wanted to learn it as I went and I didn’t quite trust Claude, so I ran all the commands myself. Next time I might trust an agent to do the work for me.

Overall this project took about 6 hours over 3 days.