From ea52f8f4fc0d24492a1c68e59ac9aa2a181b5877 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Wed, 25 Nov 2026 19:22:20 -0700 Subject: [PATCH 01/40] wallpapers: rotate every 15 minutes on the Personal activity too SlideInterval is in seconds (the slideshow plugin's own schema: 'Interval between slides in (s)', default 900), so Work was already 15 minutes while Personal sat at 10 - a ten-second slideshow. Both activities are now 900 s. Verified through Plasma's scripting API: all four desktop containments report 900, and the live config file agrees after it flushes. --- home/gui/daynight.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/home/gui/daynight.nix b/home/gui/daynight.nix index 0b9ea51..a0c025c 100644 --- a/home/gui/daynight.nix +++ b/home/gui/daynight.nix @@ -59,7 +59,7 @@ lib.mkIf config.dotfiles.gui { activities = { Work = { wallpapers = "${wallpapers}/work"; interval = 900; }; } // lib.optionalAttrs (!config.dotfiles.work) { - Personal = { wallpapers = "${wallpapers}/personal"; interval = 10; }; + Personal = { wallpapers = "${wallpapers}/personal"; interval = 900; }; }; konsole = { light = "Light"; dark = "Dark"; }; }; From 40edcf1f29fcb2b869630e275002a652a55d30c5 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Wed, 25 Nov 2026 19:39:06 -0700 Subject: [PATCH 02/40] tools: read-only music library audit + baseline report Records the analyser used to size up the Jellyfin music library's metadata problems, plus the 2026-11-25 baseline so the clean-up can be measured against it. Read-only: mutagen parses tags, nothing is written to the files. --- tools/music-audit/README.md | 17 ++ tools/music-audit/audit.py | 305 ++++++++++++++++++++++++++++++++++++ 2 files changed, 322 insertions(+) create mode 100644 tools/music-audit/README.md create mode 100644 tools/music-audit/audit.py diff --git a/tools/music-audit/README.md b/tools/music-audit/README.md new file mode 100644 index 0000000..20b242f --- /dev/null +++ b/tools/music-audit/README.md @@ -0,0 +1,17 @@ +# music-audit + +Read-only tag audit for the Jellyfin music library. Never writes to files. + +``` +python3 audit.py /mnt/MediaDisk/Music/MyLibrary > report.json +``` + +Needs `mutagen` (a throwaway venv is enough: `python3 -m venv /tmp/mtagenv && /tmp/mtagenv/bin/pip install mutagen`). +Run it with the same privileges that can read the library (on yveltal that means `sudo -n`). + +Reports, per library: missing tag counts, albums pooling many artists, near-duplicate +files, album-name drift per artist, track-numbering errors, big albums without disc +tags, genre sprawl, unreadable files and junk-file counts. + +`report-2026-11-25.json` is the baseline taken before any clean-up; rerun after the +fix and compare the same keys. diff --git a/tools/music-audit/audit.py b/tools/music-audit/audit.py new file mode 100644 index 0000000..1ca8bd4 --- /dev/null +++ b/tools/music-audit/audit.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +"""Audit a music library's tags and report the classes of metadata problem. + +Reads only tags (mutagen), never writes. Prints a JSON report to stdout so the +numbers can be reasoned about rather than eyeballed. +""" +from __future__ import annotations + +import json +import os +import re +import sys +from collections import Counter, defaultdict +from difflib import SequenceMatcher +from pathlib import Path + +from mutagen import File as MutagenFile +from mutagen.flac import FLAC +from mutagen.id3 import ID3 +from mutagen.mp4 import MP4 +from mutagen.oggopus import OggOpus +from mutagen.oggspeex import OggSpeex +from mutagen.oggvorbis import OggVorbis + +AUDIO_EXT = {".mp3", ".flac", ".m4a", ".mp4", ".ogg", ".oga", ".opus", ".wav", ".aiff", ".aif", ".wv", ".ape", ".wma"} +JUNK_EXT = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".txt", ".nfo", ".log", ".cue", ".m3u", ".m3u8", ".sfv", ".pdf", ".url", ".db", ".ini", ".xml", ".json", ".html", ".htm", ".zip", ".rar", ".7z", ".srt", ".lrc"} + + +def first(tags, keys): + for k in keys: + v = tags.get(k) + if v is None: + continue + if isinstance(v, (list, tuple)): + if not v: + continue + v = v[0] + if hasattr(v, "text"): + v = v.text[0] if v.text else None + if v is None: + continue + s = str(v).strip() + if s: + return s + return "" + + +def read_tags(path: Path): + """Return a dict of the fields this audit cares about.""" + out = {"title": "", "artist": "", "albumartist": "", "album": "", "track": "", + "disc": "", "date": "", "genre": "", "length": 0.0, "bitrate": 0, "codec": "", "error": ""} + try: + f = MutagenFile(path) + except Exception as e: # unreadable/corrupt + out["error"] = f"{type(e).__name__}" + return out + if f is None: + out["error"] = "unrecognised" + return out + + info = getattr(f, "info", None) + if info is not None: + out["length"] = round(float(getattr(info, "length", 0.0) or 0.0), 2) + out["bitrate"] = int(getattr(info, "bitrate", 0) or 0) + out["codec"] = type(info).__name__ + + tags = {} + easy = getattr(f, "tags", None) + if isinstance(f, FLAC): + tags = {k.upper(): v for k, v in (f.tags or {})} + elif isinstance(f, (OggVorbis, OggOpus, OggSpeex)): + tags = {k.upper(): v for k, v in (f.tags or {})} + elif isinstance(f, MP4): + raw = f.tags or {} + tags = { + "\xa9nam": raw.get("\xa9nam"), "\xa9ART": raw.get("\xa9ART"), "aART": raw.get("aART"), + "\xa9alb": raw.get("\xa9alb"), "trkn": raw.get("trkn"), "disk": raw.get("disk"), + "\xa9day": raw.get("\xa9day"), "\xa9gen": raw.get("\xa9gen"), + } + elif isinstance(f, ID3) or easy is not None: + try: + id3 = f if isinstance(f, ID3) else ID3(path) + except Exception: + id3 = None + if id3 is not None: + tags = { + "TIT2": id3.get("TIT2"), "TPE1": id3.get("TPE1"), "TPE2": id3.get("TPE2"), + "TALB": id3.get("TALB"), "TRCK": id3.get("TRCK"), "TPOS": id3.get("TPOS"), + "TDRC": id3.get("TDRC"), "TYER": id3.get("TYER"), "TCON": id3.get("TCON"), + } + + def text_of(v): + if v is None: + return "" + if isinstance(v, (list, tuple)): + if not v: + return "" + v = v[0] + if hasattr(v, "text"): + return str(v.text[0]).strip() if v.text else "" + if isinstance(v, tuple): # mp4 trkn/disk are (n, total) + return str(v[0]) if v and v[0] else "" + return str(v).strip() + + out["title"] = text_of(tags.get("TIT2") or tags.get("\xa9nam") or tags.get("TITLE")) + out["artist"] = text_of(tags.get("TPE1") or tags.get("\xa9ART") or tags.get("ARTIST")) + out["albumartist"] = text_of(tags.get("TPE2") or tags.get("aART") or tags.get("ALBUMARTIST")) + out["album"] = text_of(tags.get("TALB") or tags.get("\xa9alb") or tags.get("ALBUM")) + out["track"] = text_of(tags.get("TRCK") or tags.get("trkn") or tags.get("TRACKNUMBER")) + out["disc"] = text_of(tags.get("TPOS") or tags.get("disk") or tags.get("DISCNUMBER")) + out["date"] = text_of(tags.get("TDRC") or tags.get("TYER") or tags.get("\xa9day") or tags.get("DATE")) + out["genre"] = text_of(tags.get("TCON") or tags.get("\xa9gen") or tags.get("GENRE")) + # TRCK/TPOS are often "3/12" + for field in ("track", "disc"): + if "/" in out[field]: + out[field] = out[field].split("/")[0].strip() + return out + + +def norm(s: str) -> str: + s = s.lower().strip() + s = re.sub(r"[\(\[].*?[\)\]]", " ", s) # drop bracketed noise + s = re.sub(r"[^a-z0-9]+", " ", s) + return " ".join(s.split()) + + +def similarity(a: str, b: str) -> float: + return SequenceMatcher(None, norm(a), norm(b)).ratio() + + +def main(root: str) -> dict: + root_p = Path(root) + files, junk, broken = [], Counter(), [] + for dirpath, dirnames, filenames in os.walk(root_p): + dirnames[:] = [d for d in dirnames if not d.startswith(".")] + for fn in filenames: + p = Path(dirpath) / fn + ext = p.suffix.lower() + if ext in AUDIO_EXT: + files.append(p) + elif ext in JUNK_EXT: + junk[ext] += 1 + else: + junk[ext or "(none)"] += 1 + + records = [] + for p in files: + t = read_tags(p) + if t["error"]: + broken.append({"path": str(p.relative_to(root_p)), "error": t["error"]}) + continue + t["path"] = str(p.relative_to(root_p)) + t["size"] = p.stat().st_size + records.append(t) + + # ---- album clusters ------------------------------------------------- + albums = defaultdict(list) + for r in records: + key = (r["album"].strip().lower(), ) + albums[key[0]].append(r) + + mixed_artist_albums = [] + for album, rs in albums.items(): + if not album: + continue + artists = {r["artist"] for r in rs if r["artist"]} + albumartists = {r["albumartist"] for r in rs if r["albumartist"]} + if len(artists) > 3 or len(albumartists) > 2: + mixed_artist_albums.append({ + "album": rs[0]["album"], + "tracks": len(rs), + "distinct_artists": len(artists), + "distinct_albumartists": len(albumartists), + "sample_artists": sorted(artists)[:8], + "sample_paths": [r["path"] for r in rs[:4]], + "folders": len({r["path"].rsplit("/", 1)[0] for r in rs}), + }) + mixed_artist_albums.sort(key=lambda x: -x["tracks"]) + + # ---- missing / weak tags ------------------------------------------- + missing = Counter() + for r in records: + for f in ("title", "artist", "album", "albumartist", "track", "date", "genre"): + if not r[f]: + missing[f] += 1 + + # ---- duplicates ----------------------------------------------------- + by_sig = defaultdict(list) + for r in records: + if r["artist"] and r["title"]: + by_sig[(norm(r["artist"]), norm(r["title"]))].append(r) + dup_groups = [] + for (a, t), rs in by_sig.items(): + if len(rs) > 1: + durations = {round(r["length"]) for r in rs} + bitrates = {r["bitrate"] for r in rs} + dup_groups.append({ + "artist": rs[0]["artist"], "title": rs[0]["title"], "copies": len(rs), + "same_length": len(durations) == 1, "distinct_bitrates": len(bitrates), + "paths": [r["path"] for r in rs[:4]], + }) + dup_groups.sort(key=lambda x: -x["copies"]) + + # ---- album name drift per artist ------------------------------------ + by_artist_album = defaultdict(set) + for r in records: + aa = r["albumartist"] or r["artist"] + if aa and r["album"]: + by_artist_album[norm(aa)].add(r["album"]) + drift = [] + for aa, names in by_artist_album.items(): + names = sorted(names) + if len(names) < 2: + continue + used = set() + for i, a in enumerate(names): + if a in used: + continue + sims = [b for b in names if b != a and b not in used and similarity(a, b) >= 0.86 and norm(a) != norm(b)] + if sims: + used.update(sims) + drift.append({"artist": aa, "kept": a, "variants": sims}) + drift.sort(key=lambda x: -len(x["variants"])) + + # ---- track numbering sanity ---------------------------------------- + numbering = [] + for album, rs in albums.items(): + if not album or len(rs) < 4: + continue + tracks = [] + for r in rs: + try: + tracks.append(int(r["track"])) + except (TypeError, ValueError): + continue + if not tracks: + continue + dupes = [n for n, c in Counter(tracks).items() if c > 1] + gap = max(tracks) - len(set(tracks)) + if dupes or gap > 1: + numbering.append({"album": rs[0]["album"], "tracks": len(rs), + "duplicate_numbers": sorted(dupes)[:6], "missing_numbers": gap, + "sample_path": rs[0]["path"]}) + numbering.sort(key=lambda x: -x["tracks"]) + + # ---- multi-disc without disc tags ---------------------------------- + big_no_disc = [] + for album, rs in albums.items(): + if not album or len(rs) < 26: + continue + with_disc = sum(1 for r in rs if r["disc"] not in ("", "0", "1")) + if with_disc == 0: + big_no_disc.append({"album": rs[0]["album"], "tracks": len(rs), "sample_path": rs[0]["path"]}) + big_no_disc.sort(key=lambda x: -x["tracks"]) + + genres = Counter(r["genre"] for r in records if r["genre"]) + + # ---- the Beastie Boys question, explicitly ------------------------- + beastie = [r for r in records if "beastie" in r["album"].lower() or "beastie" in r["artist"].lower() + or "beastie" in r["albumartist"].lower()] + beastie_albums = Counter(r["album"] for r in beastie) + + years = Counter(r["date"][:4] for r in records if r["date"][:4].isdigit()) + + return { + "root": root, + "files_scanned": len(files), + "files_with_tags": len(records), + "unreadable": broken[:20], + "unreadable_count": len(broken), + "junk_files": dict(junk.most_common(10)), + "size_gib": round(sum(r["size"] for r in records) / 2**30, 1), + "distinct_album_tags": len([a for a in albums if a]), + "distinct_artists": len({r["artist"] for r in records if r["artist"]}), + "missing_tag_counts": dict(missing), + "mixed_artist_albums": mixed_artist_albums[:15], + "mixed_artist_album_count": len(mixed_artist_albums), + "duplicate_groups": dup_groups[:15], + "duplicate_group_count": len(dup_groups), + "duplicate_file_count": sum(len(v) for v in by_sig.values() if len(v) > 1), + "album_name_drift": drift[:10], + "album_name_drift_count": len(drift), + "track_numbering_problems": numbering[:10], + "track_numbering_count": len(numbering), + "big_albums_without_disc_tags": big_no_disc[:10], + "big_albums_without_disc_tags_count": len(big_no_disc), + "distinct_genres": len(genres), + "top_genres": genres.most_common(10), + "beastie_boys": { + "files": len(beastie), + "albums": beastie_albums.most_common(10), + "sample_albumartist_mismatch": [ + {"path": r["path"], "album": r["album"], "albumartist": r["albumartist"], + "artist": r["artist"], "title": r["title"], "track": r["track"]} + for r in beastie[:12] + ], + }, + "year_span": {"earliest": min(years) if years else "", "latest": max(years) if years else "", + "files_with_year": sum(years.values())}, + } + + +if __name__ == "__main__": + root = sys.argv[1] if len(sys.argv) > 1 else "/mnt/MediaDisk/Music/MyLibrary" + json.dump(main(root), sys.stdout, indent=1) From ff82addb46c8888f87ecfbbbbd5052281369e6e7 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Wed, 25 Nov 2026 20:07:02 -0700 Subject: [PATCH 03/40] music-audit: fpcalc fallback shim and notes on getting fingerprints on EL9 AlmaLinux 9 packages libchromaprint but no fpcalc CLI, so beets chroma and pyacoustid had nothing to call. The shim in this folder produces the same fingerprint via ffmpeg's chromaprint muxer; on the same file it is byte-identical to the official 1.5.1 static build, which also installs cleanly from the acoustid/chromaprint GitHub release. --- tools/music-audit/README.md | 17 +++++++++ tools/music-audit/fpcalc | 73 +++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100755 tools/music-audit/fpcalc diff --git a/tools/music-audit/README.md b/tools/music-audit/README.md index 20b242f..db238e1 100644 --- a/tools/music-audit/README.md +++ b/tools/music-audit/README.md @@ -15,3 +15,20 @@ tags, genre sprawl, unreadable files and junk-file counts. `report-2026-11-25.json` is the baseline taken before any clean-up; rerun after the fix and compare the same keys. + +## fpcalc (acoustid fingerprints) + +AlmaLinux 9 ships `libchromaprint` but **no `fpcalc` binary** — `dnf provides */fpcalc` +is empty because `chromaprint-tools` exists in Fedora and not in EL9 base, EPEL or CRB. +Two ways to get one, both verified on yveltal: + +1. Official static build (preferred): download + `chromaprint-fpcalc-1.5.1-linux-x86_64.tar.gz` from the acoustid/chromaprint + GitHub releases and install it as `/usr/local/bin/fpcalc`. +2. The `fpcalc` shim in this folder, which derives the same fingerprint through + ffmpeg's chromaprint muxer (`ffmpeg -f chromaprint -fp_format base64`). On the + same file its output is byte-identical to the official 1.5.1 binary, so it is a + valid fallback (`/usr/local/bin/fpcalc-ffmpeg` on yveltal). + +AcoustID *lookups* additionally need a free AcoustID application API key; computing +and comparing fingerprints locally does not. diff --git a/tools/music-audit/fpcalc b/tools/music-audit/fpcalc new file mode 100755 index 0000000..a48e1e7 --- /dev/null +++ b/tools/music-audit/fpcalc @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""fpcalc-compatible fingerprint tool built on ffmpeg's chromaprint muxer. + +AlmaLinux 9 ships libchromaprint but no fpcalc binary (the chromaprint-tools +package is not in base, EPEL or CRB). ffmpeg can emit the very same fingerprint +through its chromaprint muxer, so this shim gives every consumer of fpcalc +(beets chroma, pyacoustid, any script) a working implementation. + +Supported arguments mirror the ones tools actually pass: + fpcalc [-json] [-length SECONDS] FILE +""" +import json +import subprocess +import sys + + +def main(argv): + path = None + length = None + as_json = False + + args = argv[1:] + i = 0 + while i < len(args): + a = args[i] + if a in ("-json", "-json=1"): + as_json = True + elif a in ("-length", "-l"): + i += 1 + length = args[i] if i < len(args) else None + elif a in ("-raw", "-plain", "-text"): + as_json = False + elif a.startswith("-"): + pass + else: + path = a + i += 1 + + if not path: + sys.stderr.write("fpcalc: no input file\n") + return 2 + + cmd = ["ffmpeg", "-v", "quiet", "-nostdin", "-i", path] + if length and length.isdigit() and int(length) > 0: + cmd += ["-t", length] + cmd += ["-f", "chromaprint", "-fp_format", "base64", "-"] + + proc = subprocess.run(cmd, capture_output=True, text=True) + fingerprint = proc.stdout.strip() + + dur = subprocess.run( + ["ffprobe", "-v", "quiet", "-show_entries", "format=duration", + "-of", "default=nw=1:nk=1", path], + capture_output=True, text=True).stdout.strip() + try: + duration = int(float(dur)) + except (TypeError, ValueError): + duration = 0 + + if fingerprint: + if as_json: + print(json.dumps({"duration": duration, "fingerprint": fingerprint})) + else: + print("DURATION=%d" % duration) + print("FINGERPRINT=%s" % fingerprint) + return 0 + + sys.stderr.write("fpcalc: could not fingerprint %s: %s\n" % (path, proc.stderr.strip()[:200])) + return 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) From b8997edc9f8ec20fee8480f2817f8e2b7081e18e Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Wed, 25 Nov 2026 20:21:52 -0700 Subject: [PATCH 04/40] music-audit: AcoustID identification pass and duplicate report identify.py walks the library, fingerprints each file with fpcalc and resolves it through AcoustID into an append-only JSONL index (/var/lib/beets/ acoustid-index.jsonl). It resumes by path+size+mtime, so an interrupted run continues where it stopped, and it never touches the audio files. The first run wedged on file 58 because pyacoustid's urllib call has no timeout; socket.setdefaulttimeout(60) plus a 180s SIGALRM per-file guard turn any such stall into a recorded error instead of a dead run. report-duplicates.py turns that index into two separate lists: 'exact' groups that resolve to the same MusicBrainz recording id at score >= 0.85 (same audio, encoded twice) with a nominated keeper (FLAC before lossy, then bitrate, then size), and 'uncertain' groups that only share a normalised artist+title close in duration, which need a human. It deletes nothing. --- tools/music-audit/identify.py | 190 +++++++++++++++++++++++++ tools/music-audit/report-duplicates.py | 130 +++++++++++++++++ 2 files changed, 320 insertions(+) create mode 100644 tools/music-audit/identify.py create mode 100644 tools/music-audit/report-duplicates.py diff --git a/tools/music-audit/identify.py b/tools/music-audit/identify.py new file mode 100644 index 0000000..89206ce --- /dev/null +++ b/tools/music-audit/identify.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Identify every audio file in the music library through AcoustID. + +Append-only and resumable: one JSON object per line, keyed by path, so an +interrupted run continues where it stopped and re-running only touches files +that are missing from the index (or whose size/mtime changed). + +Nothing is written to the audio files. This produces the evidence for +de-duplication, not the de-duplication itself. + +Rate limit: AcoustID allows ~3 requests/second; we stay at ~1/s, so a full +library of ~11.5k files takes 4-5 hours. +""" +from __future__ import annotations + +import argparse +import json +import os +import signal +import socket +import subprocess +import sys +import time + +import acoustid + +# pyacoustid uses urllib without a timeout: without this a single stalled +# response blocks the whole run (it did, on file 58 of the first attempt). +socket.setdefaulttimeout(60) + +AUDIO_EXT = {".mp3", ".flac", ".m4a", ".mp4", ".ogg", ".oga", ".opus", ".wav", ".aiff", ".aif", ".wv", ".ape", ".wma"} +FPCALC = "/usr/local/bin/fpcalc" + + +class FileTimeout(Exception): + """Raised when one file takes absurdly long; we record it and move on.""" + + +def _on_alarm(signum, frame): + raise FileTimeout("per-file timeout") + + +def log(msg: str) -> None: + print("%s %s" % (time.strftime("%H:%M:%S"), msg), flush=True) + + +def load_done(path: str) -> dict[str, dict]: + done = {} + if not os.path.exists(path): + return done + with open(path, errors="replace") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + rec = json.loads(line) + except ValueError: + continue # half-written last line from a hard kill + done[rec["path"]] = rec + return done + + +def fingerprint(path: str): + """Return (duration, fingerprint) or raise.""" + out = subprocess.run([FPCALC, "-json", "-length", "120", path], + capture_output=True, text=True, timeout=120).stdout + data = json.loads(out) + fp = data.get("fingerprint") or "" + if not fp: + raise ValueError("empty fingerprint") + return int(float(data.get("duration") or 0)), fp + + +def lookup(key: str, dur: int, fp: str) -> dict: + """One AcoustID lookup with light retry on rate limiting.""" + for attempt in range(3): + try: + res = acoustid.lookup(key, fp, dur, meta="recordings releasegroups") + except Exception as e: # network hiccup + log("lookup error %s (%s), retrying" % (type(e).__name__, e)) + time.sleep(5 * (attempt + 1)) + continue + if res.get("status") == "ok": + return res + err = (res.get("error") or {}).get("message", "") + if "rate" in err.lower() or (res.get("error") or {}).get("code") == 6: + time.sleep(5 * (attempt + 1)) + continue + return res + return {"status": "error", "error": {"message": "exhausted retries"}} + + +def best_identification(res: dict) -> dict: + results = res.get("results") or [] + if not results: + return {} + best = max(results, key=lambda r: r.get("score", 0)) + out = {"score": round(float(best.get("score") or 0), 4), "recording_id": None, + "title": None, "artist": None, "release_group": None} + recs = best.get("recordings") or [] + if recs: + rec = recs[0] + out["recording_id"] = rec.get("id") + out["title"] = rec.get("title") + out["artist"] = ", ".join(a.get("name", "") for a in rec.get("artists", [])) or None + rgs = rec.get("releasegroups") or [] + if rgs: + out["release_group"] = rgs[0].get("title") + return out + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--key-file", default="/etc/beets/acoustid.key") + ap.add_argument("--index", default="/var/lib/beets/acoustid-index.jsonl") + ap.add_argument("--roots", nargs="+", + default=["/mnt/MediaDisk/Music/MyLibrary", "/mnt/MediaOverflow/arr/library/Music"]) + ap.add_argument("--sleep", type=float, default=1.05) + ap.add_argument("--max-files", type=int, default=0, help="stop after N new files (0 = all)") + args = ap.parse_args() + + key = open(args.key_file).read().strip() + done = load_done(args.index) + log("index already holds %d files" % len(done)) + + pending = [] + for root in args.roots: + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if not d.startswith(".")] + for fn in filenames: + if os.path.splitext(fn)[1].lower() not in AUDIO_EXT: + continue + p = os.path.join(dirpath, fn) + try: + st = os.stat(p) + except OSError: + continue + rec = done.get(p) + if rec and rec.get("size") == st.st_size and rec.get("mtime") == int(st.st_mtime): + continue + pending.append((p, st)) + pending.sort() + log("%d files need identification" % len(pending)) + if args.max_files: + pending = pending[: args.max_files] + + os.makedirs(os.path.dirname(args.index), exist_ok=True) + started = time.time() + ok = failed = nomatch = 0 + with open(args.index, "a") as out: + for n, (path, st) in enumerate(pending, 1): + entry = {"path": path, "size": st.st_size, "mtime": int(st.st_mtime), + "ts": int(time.time())} + signal.signal(signal.SIGALRM, _on_alarm) + signal.alarm(180) + try: + dur, fp = fingerprint(path) + entry["duration"] = dur + entry["fp_len"] = len(fp) + res = lookup(key, dur, fp) + if res.get("status") == "ok": + entry.update(best_identification(res)) + if entry.get("recording_id"): + ok += 1 + else: + nomatch += 1 + else: + entry["error"] = (res.get("error") or {}).get("message", "lookup failed") + failed += 1 + except Exception as e: + entry["error"] = "%s: %s" % (type(e).__name__, str(e)[:120]) + failed += 1 + finally: + signal.alarm(0) + out.write(json.dumps(entry) + "\n") + out.flush() + if n % 50 == 0 or n == len(pending): + rate = n / max(time.time() - started, 1) + remaining = (len(pending) - n) / rate if rate else 0 + log("%d/%d matched=%d no-match=%d failed=%d %.2f files/s eta %.0f min" + % (n, len(pending), ok, nomatch, failed, rate, remaining / 60)) + time.sleep(args.sleep) + + log("finished: matched=%d no-match=%d failed=%d" % (ok, nomatch, failed)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/music-audit/report-duplicates.py b/tools/music-audit/report-duplicates.py new file mode 100644 index 0000000..315b930 --- /dev/null +++ b/tools/music-audit/report-duplicates.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Turn the AcoustID index into a duplicate report a human can approve. + +Two kinds of finding, deliberately separated: + + exact - several files resolve to the same MusicBrainz recording id at a + trustworthy score. Same audio, encoded more than once. + uncertain - no recording id (or a weak score), so grouped only by normalised + artist+title with a close duration. Needs a human look. + +For each group it nominates one file to keep: FLAC before lossy, then the +highest bitrate, then the largest file, then the shortest path. + +Nothing is deleted or moved here. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +from collections import defaultdict + +LOSSY = {".mp3", ".m4a", ".ogg", ".opus", ".wma", ".aac"} +LOSSLESS = {".flac", ".wav", ".aiff", ".aif", ".ape", ".wv"} + + +def norm(s: str) -> str: + s = (s or "").lower() + s = re.sub(r"[\(\[].*?[\)\]]", " ", s) + s = re.sub(r"[^a-z0-9]+", " ", s) + return " ".join(s.split()) + + +def rank(rec: dict) -> tuple: + ext = os.path.splitext(rec["path"])[1].lower() + family = 0 if ext in LOSSLESS else 1 if ext in LOSSY else 2 + return (family, -(rec.get("size") or 0), len(rec["path"])) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--index", default="/var/lib/beets/acoustid-index.jsonl") + ap.add_argument("--out", default="/var/lib/beets/duplicates.json") + ap.add_argument("--min-score", type=float, default=0.85) + ap.add_argument("--duration-tolerance", type=float, default=3.0) + args = ap.parse_args() + + rows = [] + for line in open(args.index, errors="replace"): + line = line.strip() + if not line: + continue + try: + rows.append(json.loads(line)) + except ValueError: + continue + + identified = [r for r in rows if r.get("recording_id") and (r.get("score") or 0) >= args.min_score] + + by_recording = defaultdict(list) + for r in identified: + by_recording[r["recording_id"]].append(r) + + exact = [] + for rid, group in by_recording.items(): + if len(group) < 2: + continue + group.sort(key=rank) + keep, dupes = group[0], group[1:] + exact.append({ + "recording_id": rid, + "title": keep.get("title"), + "artist": keep.get("artist"), + "keep": keep["path"], + "remove": [d["path"] for d in dupes], + "size_reclaimable": sum(d.get("size") or 0 for d in dupes), + }) + exact.sort(key=lambda g: -g["size_reclaimable"]) + + # uncertain: no recording id, grouped by artist+title with a close duration + unresolved = [r for r in rows if not r.get("recording_id") and r.get("title")] + by_title = defaultdict(list) + for r in unresolved: + by_title[(norm(r.get("artist")), norm(r.get("title")))].append(r) + uncertain = [] + for key, group in by_title.items(): + if len(group) < 2: + continue + durations = [r.get("duration") for r in group if r.get("duration")] + if durations and max(durations) - min(durations) > args.duration_tolerance * 4: + continue # probably different versions, not duplicates + group.sort(key=rank) + uncertain.append({ + "artist": group[0].get("artist"), + "title": group[0].get("title"), + "keep": group[0]["path"], + "review": [d["path"] for d in group[1:]], + }) + + report = { + "index_files": len(rows), + "identified": len(identified), + "exact_groups": len(exact), + "exact_files_to_remove": sum(len(g["remove"]) for g in exact), + "reclaimable_gib": round(sum(g["size_reclaimable"] for g in exact) / 2**30, 2), + "uncertain_groups": len(uncertain), + "exact": exact, + "uncertain": uncertain, + } + with open(args.out, "w") as f: + json.dump(report, f, indent=1) + + print("index files : %d" % report["index_files"]) + print("identified : %d" % report["identified"]) + print("exact dupe groups: %d (%d files removable, %.2f GiB)" + % (report["exact_groups"], report["exact_files_to_remove"], report["reclaimable_gib"])) + print("uncertain groups : %d" % report["uncertain_groups"]) + for g in exact[:10]: + print("\n %s - %s" % ((g["artist"] or "?")[:30], (g["title"] or "?")[:40])) + print(" keep : %s" % g["keep"][-72:]) + for p in g["remove"][:3]: + print(" remove: %s" % p[-72:]) + print("\nwritten to %s" % args.out) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 6bc006e90abbe2f4a2b16809d9641fdc5f8e8692 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Wed, 25 Nov 2026 20:50:34 -0700 Subject: [PATCH 05/40] music-audit: document the beets settings and singleton handling --- tools/music-audit/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tools/music-audit/README.md b/tools/music-audit/README.md index db238e1..512a6b5 100644 --- a/tools/music-audit/README.md +++ b/tools/music-audit/README.md @@ -32,3 +32,18 @@ Two ways to get one, both verified on yveltal: AcoustID *lookups* additionally need a free AcoustID application API key; computing and comparing fingerprints locally does not. + +## beets settings used here + +`/etc/beets/config.yaml` (0600, holds `acoustid.apikey`); `/etc/beets/config-import.yaml` +is the same file with `chroma` removed so bulk imports do not compete with a running +AcoustID identification pass for the same rate limit. + +Key choices: `write: yes` with `copy: no` and `move: no` (tags are rewritten in place, so +Jellyfin paths never change), `timid: no` with `strong_rec_thresh: 0.10` (only confident +MusicBrainz matches are applied), `import.quiet_fallback: asis`. + +Loose download folders are imported as **singletons** (`beet import -s`), which gives each +track its own album/albumartist instead of one pooled fake album. Files that MusicBrainz +cannot match are given a single's shape directly (album = title, albumartist = artist, +track 1/1) because quiet mode will not import unmatched singletons even with `asis`. From 3fd4ae0109758264f03fac5fabb8a8cf42de2b53 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Wed, 25 Nov 2026 20:58:15 -0700 Subject: [PATCH 06/40] music-audit: overnight follow-up timer and cohere strict-mode fix followup.sh + music-followup.timer wake a headless pi session when the AcoustID identification pass ends: it writes the duplicate report (read-only), records the identification totals and the Jellyfin grouping, then starts the agent in tmux. It is idempotent via a state file and Persistent=true so a suspended Deck catches up on resume. Two things had to be worked around: pi lives in a mise npm install (a timer has no shell profile), and Cohere rejects requests whose tool definitions mix strict and non-strict in pi 1.4.0 headless, so the default model is a local Ollama one. Also sets compat.supportsStrictMode=false for cohere in the pi model catalog. --- config/pi/models.json | 5 +- tools/music-audit/README.md | 19 +++++ tools/music-audit/followup.sh | 93 ++++++++++++++++++++++++ tools/music-audit/jellyfin-licensed.py | 45 ++++++++++++ tools/music-audit/music-followup.service | 9 +++ tools/music-audit/music-followup.timer | 10 +++ 6 files changed, 179 insertions(+), 2 deletions(-) create mode 100755 tools/music-audit/followup.sh create mode 100755 tools/music-audit/jellyfin-licensed.py create mode 100644 tools/music-audit/music-followup.service create mode 100644 tools/music-audit/music-followup.timer diff --git a/config/pi/models.json b/config/pi/models.json index ff0c1ed..6d4eb59 100644 --- a/config/pi/models.json +++ b/config/pi/models.json @@ -155,7 +155,8 @@ "supportsStore": false, "supportsStrictMode": false, "supportsUsageInStreaming": true - } + }, + "supportsStrictMode": false } } -} +} \ No newline at end of file diff --git a/tools/music-audit/README.md b/tools/music-audit/README.md index 512a6b5..0810700 100644 --- a/tools/music-audit/README.md +++ b/tools/music-audit/README.md @@ -47,3 +47,22 @@ Loose download folders are imported as **singletons** (`beet import -s`), which track its own album/albumartist instead of one pooled fake album. Files that MusicBrainz cannot match are given a single's shape directly (album = title, albumartist = artist, track 1/1) because quiet mode will not import unmatched singletons even with `asis`. + +## Overnight follow-up (`followup.sh`) + +`followup.sh` runs from `music-followup.timer` (user timer, every 15 min, `Persistent=true` +so a suspended Deck catches up on resume). It is a cheap no-op until the identify process on +yveltal is gone, then, once only: + +1. writes the duplicate report (`music-duplicates --out /var/lib/beets/duplicates.json`), +2. collects the identification totals and the Jellyfin "Licensed to Ill" view, +3. writes `~/music-followup-report.md`, +4. starts `pi -p` in tmux session `music-followup` to work through the follow-up. + +Knobs: `FORCE=1` skips the "still running" check (for testing the report path), +`MUSIC_FOLLOWUP_NO_AGENT=1` writes the report without starting an agent, `MODEL=...` +picks the model (default `ollama/gemma4-12b-qat-128k`, because Cohere rejects mixed +strict-mode tool definitions in `pi` 1.4.0's headless mode). + +`jellyfin-licensed.py` prints how Jellyfin currently groups that album — a healthy +result is "no album matching ... any more". diff --git a/tools/music-audit/followup.sh b/tools/music-audit/followup.sh new file mode 100755 index 0000000..4691334 --- /dev/null +++ b/tools/music-audit/followup.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Wait for the AcoustID identification pass to finish, then hand the next stage +# to an agent session — so the overnight work does not sit idle until morning. +# +# Runs from a systemd timer every 15 minutes. It is a cheap no-op until: +# * the identify process on yveltal is gone, AND +# * the state file does not exist yet (so it acts exactly once). +# +# What it does when the pass is over: +# 1. writes the duplicate report (read-only, nothing is deleted), +# 2. collects the identification totals and the Jellyfin view, +# 3. writes ~/music-followup-report.md, +# 4. starts a `pi` session in tmux (session: music-followup) to act on it. +# +# Set MUSIC_FOLLOWUP_NO_AGENT=1 to only produce the report. + +set -uo pipefail + +SSH_HOST="${SSH_HOST:-yveltal_local}" +STATE="${STATE:-$HOME/.local/state/music-followup.done}" +REPORT="${REPORT:-$HOME/music-followup-report.md}" +LOG="${LOG:-$HOME/music-followup.log}" +MODEL="${MODEL:-ollama/gemma4-12b-qat-128k}" # Cohere rejects mixed strict-mode tools in pi 1.4.0 headless +# pi lives in a mise npm install; a systemd timer has no shell profile to find it. +PI_BIN="${PI_BIN:-$(command -v pi 2>/dev/null || ls "$HOME"/.local/share/mise/installs/npm-earendil-works-pi-coding-agent/*/node_modules/.bin/pi 2>/dev/null | head -1)}" +JELLYFIN_KEY="${JELLYFIN_KEY:-6fd79f0a2cfe4465bb1a0167c3660064}" +JELLYFIN_URL="${JELLYFIN_URL:-http://10.0.0.38:8096}" + +mkdir -p "$(dirname "$STATE")" "$(dirname "$LOG")" + +# Already handled. +[ -f "$STATE" ] && exit 0 + +# Still working? (FORCE=1 skips this, for testing the report path) +if [ "${FORCE:-0}" != "1" ] && ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" 'pgrep -f music-identify >/dev/null' 2>/dev/null; then + exit 0 +fi + +# Process gone: distinguish "finished" from "died". +finished=$(ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" \ + 'sudo -n grep -E "finished: matched=" /var/log/music-identify.log | tail -1' 2>/dev/null) +index_lines=$(ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" \ + 'sudo -n wc -l < /var/lib/beets/acoustid-index.jsonl' 2>/dev/null | tr -d ' ') + +if [ -z "$finished" ]; then + verdict="INCOMPLETE — the identify process is gone but the log has no completion line (index has ${index_lines:-?} rows)" +else + verdict="COMPLETE — ${finished#*finished: } (index has ${index_lines:-?} rows)" +fi + +# Duplicate report (read-only). +dupe_summary=$(ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" \ + 'sudo -n /opt/beets-venv/bin/python /usr/local/bin/music-duplicates --out /var/lib/beets/duplicates.json' 2>&1 | head -6) + +# How Jellyfin currently groups the worst offender. +jf_children=$("$(dirname "$0")/jellyfin-licensed.py" 2>/dev/null) + +cat > "$REPORT" <> "$LOG" + +if [ "${MUSIC_FOLLOWUP_NO_AGENT:-0}" != "1" ] && ! tmux has-session -t music-followup 2>/dev/null; then + prompt="Overnight music-library follow-up. Read $REPORT first. Then continue the plan in ~/HANDOFF-rdtc-decypharr.md's sibling context and the LaPis memories about the Jellyfin music library: (1) verify the Jellyfin scan finished and that the 'Licensed to Ill' album now holds only Beastie Boys tracks; (2) summarise the exact/uncertain duplicate groups from /var/lib/beets/duplicates.json on yveltal so a human can approve them — do NOT delete anything; (3) if the tag snapshot /var/lib/beets/tags-backup-*.jsonl.gz is complete, begin Stage B (album-level beets imports) on the largest discography folders one at a time, logging each run, and stop before anything destructive. Report what you did at the top of $REPORT." + tmux new-session -d -s music-followup "cd $HOME && \"$PI_BIN\" -p --model $MODEL $(printf '%q' "$prompt") >> $LOG 2>&1" + echo "$(date -u +%H:%M:%SZ) agent session started (tmux: music-followup)" >> "$LOG" +fi + +touch "$STATE" diff --git a/tools/music-audit/jellyfin-licensed.py b/tools/music-audit/jellyfin-licensed.py new file mode 100755 index 0000000..16feec1 --- /dev/null +++ b/tools/music-audit/jellyfin-licensed.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Print how Jellyfin currently groups the mis-matched "Licensed to Ill" album. + +One album row plus its child count, or nothing if the album is gone — which is +the healthy outcome after the tags were fixed. +""" +import json +import os +import sys +import urllib.request + +KEY = os.environ.get("JELLYFIN_KEY", "6fd79f0a2cfe4465bb1a0167c3660064") +BASE = os.environ.get("JELLYFIN_URL", "http://10.0.0.38:8096") + + +def api(path): + req = urllib.request.Request(BASE + path, + headers={"Authorization": 'MediaBrowser Token="%s"' % KEY}) + with urllib.request.urlopen(req, timeout=30) as r: + return json.loads(r.read().decode()) + + +def main(): + term = os.environ.get("JELLYFIN_TERM", "Licensed") + try: + albums = api("/Items?Recursive=true&IncludeItemTypes=MusicAlbum" + "&SearchTerm=%s&Fields=Path" % term).get("Items", []) + except Exception as e: + print(" could not query Jellyfin: %s" % type(e).__name__) + return 0 + if not albums: + print(" no album matching %r any more — the mis-grouping is gone" % term) + return 0 + for a in albums: + try: + kids = api("/Items?ParentId=%s&Limit=1" % a["Id"]).get("TotalRecordCount") + except Exception: + kids = "?" + print(" %-24s %s songs (albumartist: %s)" + % (a.get("Name"), kids, a.get("AlbumArtist") or "?")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/music-audit/music-followup.service b/tools/music-audit/music-followup.service new file mode 100644 index 0000000..7ef828e --- /dev/null +++ b/tools/music-audit/music-followup.service @@ -0,0 +1,9 @@ +[Unit] +Description=Music library follow-up (duplicate report + agent handoff) + +[Service] +Type=oneshot +# The agent it launches needs pi, secretctl and tmux on PATH, and a model key. +Environment=PATH=%h/.local/bin:%h/.nix-profile/bin:/usr/local/bin:/usr/bin:/bin +Environment=HOME=%h +ExecStart=%h/.dotfiles/tools/music-audit/followup.sh diff --git a/tools/music-audit/music-followup.timer b/tools/music-audit/music-followup.timer new file mode 100644 index 0000000..a0b2258 --- /dev/null +++ b/tools/music-audit/music-followup.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Check every 15 minutes whether the AcoustID pass has finished + +[Timer] +OnBootSec=5m +OnUnitActiveSec=15m +Persistent=true + +[Install] +WantedBy=timers.target From 39fcf6bc4f8a64bc1bfe9343e4b5b1d0f00efa65 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Thu, 26 Nov 2026 02:07:04 -0700 Subject: [PATCH 07/40] music-audit: followup must not treat an unreachable host as a finished run When the Netbird tunnel dropped, ssh to yveltal timed out and the script wrote 'INCOMPLETE - process is gone' and marked the run done, which would have left the report wrong and the timer silent. Now an ssh failure logs 'unreachable, will retry next tick' and exits without touching the state file. --- tools/music-audit/followup.sh | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tools/music-audit/followup.sh b/tools/music-audit/followup.sh index 4691334..390a78e 100755 --- a/tools/music-audit/followup.sh +++ b/tools/music-audit/followup.sh @@ -36,6 +36,13 @@ if [ "${FORCE:-0}" != "1" ] && ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_H exit 0 fi +# If the host cannot be reached at all, do nothing: the job is still running there and +# an unreachable host must never be recorded as a finished pass (it was, once). +if ! ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" 'true' 2>/dev/null; then + echo "$(date -u +%H:%M:%SZ) yveltal unreachable, will retry next tick" >> "$LOG" + exit 0 +fi + # Process gone: distinguish "finished" from "died". finished=$(ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" \ 'sudo -n grep -E "finished: matched=" /var/log/music-identify.log | tail -1' 2>/dev/null) From 1390fd848752388200f4ef8918c3a5afe671905d Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Thu, 26 Nov 2026 02:07:25 -0700 Subject: [PATCH 08/40] music-audit: fix the completion check that could never fire pgrep -f music-identify matched the ssh command line carrying that very string, so the 'still running' branch was always true and the follow-up would wait for ever. Bracket the pattern (music-[i]dentify) so pgrep cannot match itself. --- tools/music-audit/followup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/music-audit/followup.sh b/tools/music-audit/followup.sh index 390a78e..a058f7f 100755 --- a/tools/music-audit/followup.sh +++ b/tools/music-audit/followup.sh @@ -32,7 +32,7 @@ mkdir -p "$(dirname "$STATE")" "$(dirname "$LOG")" [ -f "$STATE" ] && exit 0 # Still working? (FORCE=1 skips this, for testing the report path) -if [ "${FORCE:-0}" != "1" ] && ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" 'pgrep -f music-identify >/dev/null' 2>/dev/null; then +if [ "${FORCE:-0}" != "1" ] && ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_HOST" 'pgrep -f "music-[i]dentify" >/dev/null' 2>/dev/null; then exit 0 fi From 72ac6b0cc66dc3303653712b48e465b94506c93c Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Thu, 26 Nov 2026 02:32:23 -0700 Subject: [PATCH 09/40] music-audit: quarantine tool plus fingerprint retry for artwork-broken files quarantine.py asks an independent decoder whether a file's *audio* plays before moving anything. The first version wrongly condemned 359 files because ffmpeg could not decode their embedded cover art; with -vn -map 0:a only one file in the library is genuinely unplayable (a Leonard Cohen mp3 with no audio stream), and it is now archived under /mnt/MediaDisk/Music-Quarantine// with a JSON manifest and its original relative path. The other 704 files that fpcalc refused are fine: the official binary bundles FFmpeg 58, which gives up on that same artwork. The ffmpeg-backed shim now decodes audio only (-vn -map 0:a, correctly placed after the input), and retry-failed.py re-fingerprints the failures through it, appending corrected entries to the index. --- tools/music-audit/fpcalc | 6 +- tools/music-audit/quarantine.py | 128 ++++++++++++++++++++++++++++++ tools/music-audit/retry-failed.py | 96 ++++++++++++++++++++++ 3 files changed, 229 insertions(+), 1 deletion(-) create mode 100644 tools/music-audit/quarantine.py create mode 100644 tools/music-audit/retry-failed.py diff --git a/tools/music-audit/fpcalc b/tools/music-audit/fpcalc index a48e1e7..ba3c0ca 100755 --- a/tools/music-audit/fpcalc +++ b/tools/music-audit/fpcalc @@ -40,10 +40,14 @@ def main(argv): sys.stderr.write("fpcalc: no input file\n") return 2 + # -vn: embedded cover art that this ffmpeg cannot decode must not decide + # whether a track can be fingerprinted (it is audio we care about). cmd = ["ffmpeg", "-v", "quiet", "-nostdin", "-i", path] if length and length.isdigit() and int(length) > 0: cmd += ["-t", length] - cmd += ["-f", "chromaprint", "-fp_format", "base64", "-"] + # Audio only: embedded cover art that this ffmpeg cannot decode must not + # decide whether a track can be fingerprinted. + cmd += ["-vn", "-map", "0:a", "-f", "chromaprint", "-fp_format", "base64", "-"] proc = subprocess.run(cmd, capture_output=True, text=True) fingerprint = proc.stdout.strip() diff --git a/tools/music-audit/quarantine.py b/tools/music-audit/quarantine.py new file mode 100644 index 0000000..7b9d237 --- /dev/null +++ b/tools/music-audit/quarantine.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Verify which files fpcalc could not identify, then move the broken ones out. + +Two questions, answered separately: + + decodable? an independent decoder (ffprobe + a short ffmpeg decode of the + first seconds) is asked to read the file. A file that decodes fine + but failed fingerprinting stays in the library. + broken? ffprobe cannot read the container at all, or ffmpeg fails to decode + any audio: that file is unplayable and moves to the quarantine. + +Quarantine mirrors the library's relative paths, so nothing is lost and the file +can be put back exactly where it came from. A JSON manifest records why each file +was moved. Nothing is deleted. +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +import time + + +def probe(path: str) -> tuple[bool, str]: + """Return (decodable, reason).""" + p = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "default=nw=1:nk=1", path], + capture_output=True, text=True, timeout=60) + if p.returncode != 0 or not p.stdout.strip(): + return False, (p.stderr.strip().splitlines() or ["ffprobe rejected the file"])[0][:120] + # -vn/-map 0:a: many files carry embedded cover art that ffmpeg cannot decode, + # which says nothing about whether the audio plays. Only audio matters here. + d = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", path, "-t", "8", + "-vn", "-map", "0:a", "-f", "null", "-"], + capture_output=True, text=True, timeout=180) + if d.returncode != 0: + err = (d.stderr.strip().splitlines() or ["ffmpeg could not decode it"])[-1] + return False, err[:120] + return True, "" + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--index", default="/var/lib/beets/acoustid-index.jsonl") + ap.add_argument("--roots", nargs="+", + default=["/mnt/MediaDisk/Music/MyLibrary", "/mnt/MediaOverflow/arr/library/Music"]) + ap.add_argument("--quarantine", default="/mnt/MediaDisk/Music-Quarantine") + ap.add_argument("--manifest", default="") + ap.add_argument("--move", action="store_true", help="actually move the broken files") + args = ap.parse_args() + + stamp = time.strftime("%Y%m%dT%H%M%S") + manifest_path = args.manifest or ("/var/lib/beets/quarantine-%s.json" % stamp) + + failures = [] + for line in open(args.index, errors="replace"): + line = line.strip() + if not line: + continue + try: + rec = json.loads(line) + except ValueError: + continue + if rec.get("error"): + failures.append(rec) + + print("index entries with an error: %d" % len(failures)) + + broken, ok = [], [] + for n, rec in enumerate(failures, 1): + path = rec["path"] + if not os.path.exists(path): + continue + try: + good, reason = probe(path) + except subprocess.TimeoutExpired: + good, reason = False, "timed out while probing" + except Exception as e: + good, reason = False, "%s: %s" % (type(e).__name__, str(e)[:80]) + if good: + ok.append(path) + else: + broken.append({"path": path, "reason": reason, + "fingerprint_error": rec.get("error", ""), + "size": os.path.getsize(path)}) + if n % 100 == 0: + print(" probed %d/%d broken=%d decodable=%d" % (n, len(failures), len(broken), len(ok)), flush=True) + + print("would quarantine %d, keep %d" % (len(broken), len(ok))) + total = sum(b["size"] for b in broken) + print("quarantine size: %.2f GiB" % (total / 2**30)) + for b in broken[:8]: + print(" %-56s %s" % (b["path"].split("/", 4)[-1][:56], b["reason"][:46])) + + moved = 0 + if args.move: + for b in broken: + src = b["path"] + rel = None + for root in args.roots: + if src.startswith(root.rstrip("/") + "/"): + rel = os.path.relpath(src, root) + break + if rel is None: + continue + dest = os.path.join(args.quarantine, stamp, rel) + os.makedirs(os.path.dirname(dest), exist_ok=True) + try: + shutil.move(src, dest) + b["quarantined_to"] = dest + moved += 1 + except OSError as e: + b["move_error"] = str(e)[:120] + print("moved %d files to %s/%s" % (moved, args.quarantine, stamp)) + + with open(manifest_path, "w") as f: + json.dump({"generated": stamp, "roots": args.roots, + "quarantine_dir": os.path.join(args.quarantine, stamp) if args.move else None, + "broken": broken, "decodable_but_unfingerprinted": ok}, f, indent=1) + print("manifest: %s" % manifest_path) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/music-audit/retry-failed.py b/tools/music-audit/retry-failed.py new file mode 100644 index 0000000..e13af94 --- /dev/null +++ b/tools/music-audit/retry-failed.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Re-fingerprint the index entries that failed, using the ffmpeg-backed fpcalc. + +The official fpcalc ships FFmpeg 58, which refuses some files whose *audio* is +perfectly fine (an undecodable embedded cover-art stream is enough). The shim in +this repo decodes audio only, so retrying through it usually succeeds. + +Appended lines overwrite earlier entries for the same path when the index is read +(load_done keeps the last one), so the index stays a single source of truth. +""" +from __future__ import annotations + +import json +import os +import socket +import subprocess +import sys +import time + +import acoustid + +socket.setdefaulttimeout(60) +SHIM = "/usr/local/bin/fpcalc-ffmpeg" + + +def log(msg): + print("%s %s" % (time.strftime("%H:%M:%S"), msg), flush=True) + + +def main() -> int: + index = "/var/lib/beets/acoustid-index.jsonl" + key = open("/etc/beets/acoustid.key").read().strip() + + latest = {} + for line in open(index, errors="replace"): + line = line.strip() + if not line: + continue + try: + rec = json.loads(line) + except ValueError: + continue + latest[rec["path"]] = rec + + todo = [r for r in latest.values() if r.get("error") and os.path.exists(r["path"])] + log("%d paths to retry" % len(todo)) + + ok = fail = 0 + with open(index, "a") as out: + for n, rec in enumerate(todo, 1): + path = rec["path"] + entry = {"path": path, "size": rec.get("size"), "mtime": rec.get("mtime"), + "ts": int(time.time()), "retried": True} + try: + p = subprocess.run([SHIM, "-json", "-length", "120", path], + capture_output=True, text=True, timeout=180) + data = json.loads(p.stdout) + fp = data.get("fingerprint") or "" + if not fp: + raise ValueError("still no fingerprint") + dur = int(float(data.get("duration") or 0)) + entry["duration"] = dur + entry["fp_len"] = len(fp) + res = acoustid.lookup(key, fp, dur, meta="recordings releasegroups") + if res.get("status") == "ok" and res.get("results"): + best = max(res["results"], key=lambda r: r.get("score", 0)) + entry["score"] = round(float(best.get("score") or 0), 4) + recs = best.get("recordings") or [] + if recs: + entry["recording_id"] = recs[0].get("id") + entry["title"] = recs[0].get("title") + entry["artist"] = ", ".join(a.get("name", "") for a in recs[0].get("artists", [])) + rgs = recs[0].get("releasegroups") or [] + if rgs: + entry["release_group"] = rgs[0].get("title") + ok += 1 + else: + entry["error"] = "no recording in result" + fail += 1 + else: + entry["error"] = (res.get("error") or {}).get("message", "no match") + fail += 1 + except Exception as e: + entry["error"] = "%s: %s" % (type(e).__name__, str(e)[:100]) + fail += 1 + out.write(json.dumps(entry) + "\n") + out.flush() + if n % 50 == 0 or n == len(todo): + log("%d/%d recovered=%d still-failing=%d" % (n, len(todo), ok, fail)) + time.sleep(1.05) + log("done: recovered=%d still-failing=%d" % (ok, fail)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 7a27c78476f660c7ea3764c6e12df8f807550ec1 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Thu, 26 Nov 2026 03:39:19 -0700 Subject: [PATCH 10/40] music-audit: move duplicates to a reversible trash with a manifest trash-duplicates.py acts on the AcoustID duplicate report: for each group it keeps the nominated file and moves the extra copies into a dated folder, preserving their path relative to the library root so any batch can be restored in place. Two guards matter: a group is skipped entirely if its keeper no longer exists (a recording must never lose its last copy), and every move is recorded in a JSON manifest. First run: 999 files, 11.91 GiB, 14 groups skipped (sources already gone), 0 failures; keepers verified present afterwards and free space went 13G -> 27G. --- tools/music-audit/trash-duplicates.py | 95 +++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 tools/music-audit/trash-duplicates.py diff --git a/tools/music-audit/trash-duplicates.py b/tools/music-audit/trash-duplicates.py new file mode 100644 index 0000000..4219966 --- /dev/null +++ b/tools/music-audit/trash-duplicates.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Move duplicate files to a dated trash folder. Reversible, never deletes. + +Built around two safety rules: + + * the nominated keeper must still exist, otherwise the group is skipped + entirely — a recording must never end up with zero copies; + * every moved file keeps its path relative to the library root, so restoring + is a copy back into place. + +A JSON manifest records what moved where and why. +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +import sys +import time + +ROOTS = ["/mnt/MediaDisk/Music/MyLibrary", "/mnt/MediaOverflow/arr/library/Music"] + + +def relpath(path: str): + for root in ROOTS: + if path.startswith(root.rstrip("/") + "/"): + return os.path.relpath(path, root) + return None + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--report", default="/var/lib/beets/duplicates.json") + ap.add_argument("--trash", default="/mnt/MediaDisk/Music-Trash") + ap.add_argument("--only-min-copies", type=int, default=0, + help="only act on groups with at least this many removable copies") + ap.add_argument("--move", action="store_true") + args = ap.parse_args() + + stamp = time.strftime("%Y%m%dT%H%M%S") + report = json.load(open(args.report)) + + moved, skipped, failed = [], [], [] + for group in report["exact"]: + if args.only_min_copies and len(group["remove"]) < args.only_min_copies: + continue + keep = group["keep"] + if not os.path.exists(keep): + skipped.append({"group": group.get("title"), "reason": "keeper missing", "keep": keep}) + continue + for src in group["remove"]: + if src == keep or not os.path.exists(src): + skipped.append({"group": group.get("title"), "reason": "source missing", "path": src}) + continue + rel = relpath(src) + if rel is None: + skipped.append({"group": group.get("title"), "reason": "outside known roots", "path": src}) + continue + dest = os.path.join(args.trash, stamp, rel) + entry = {"path": src, "moved_to": dest, "keeper": keep, + "title": group.get("title"), "artist": group.get("artist"), + "recording_id": group.get("recording_id"), + "size": os.path.getsize(src)} + if args.move: + try: + os.makedirs(os.path.dirname(dest), exist_ok=True) + shutil.move(src, dest) + moved.append(entry) + except OSError as e: + entry["error"] = str(e)[:120] + failed.append(entry) + else: + moved.append(entry) + + total = sum(e["size"] for e in moved) + verb = "moved" if args.move else "would move" + print("%s %d files (%.2f GiB); skipped %d; failed %d" + % (verb, len(moved), total / 2**30, len(skipped), len(failed))) + for e in moved[:5]: + print(" %-64s -> trash" % e["path"].split("/", 4)[-1][:64]) + for e in failed[:3]: + print(" FAILED %s (%s)" % (e["path"][-50:], e.get("error"))) + + manifest = "/var/lib/beets/duplicate-trash-%s.json" % stamp + if args.move: + with open(manifest, "w") as f: + json.dump({"stamp": stamp, "trash_dir": os.path.join(args.trash, stamp), + "roots": ROOTS, "moved": moved, "skipped": skipped, "failed": failed}, f, indent=1) + print("manifest: %s" % manifest) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From e6c4d6a3cf48c2c84eb8d3c9bd18afd78bb75827 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Thu, 26 Nov 2026 03:51:23 -0700 Subject: [PATCH 11/40] music-audit: sequential Stage B runner Runs album-level beets imports over a queue of folders, one at a time: beets writes a single SQLite library, so concurrent imports collide. Waits for any import already in flight, logs each folder separately, and records completed folders in /var/lib/beets/stageb-done.txt so a re-run skips them. Pink Floyd (first folder): 193 of 245 files now carry a musicbrainz_albumid and 27 tracks gained disc numbers > 1, i.e. multi-disc sets are being split properly. Nine albums were declined and are worth a manual pass: The Wall disc 2, Dark Side of the Moon, Piper 40th, Echoes disc 2, Zabriskie Point disc 2 and others. --- tools/music-audit/stageb-runner.sh | 68 ++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100755 tools/music-audit/stageb-runner.sh diff --git a/tools/music-audit/stageb-runner.sh b/tools/music-audit/stageb-runner.sh new file mode 100755 index 0000000..0147548 --- /dev/null +++ b/tools/music-audit/stageb-runner.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# Run Stage B (album-level beets imports) over a list of folders, one at a time. +# +# Serialised on purpose: beets writes a single SQLite library, and two concurrent +# imports collide on it. Each folder gets its own log, and the runner waits for +# any import already in flight before starting the next. +# +# ./stageb-runner.sh # the default queue +# ./stageb-runner.sh "dir1" "dir2" # an explicit queue + +set -uo pipefail + +BEET=/opt/beets-venv/bin/beet +CONF=/etc/beets/config-stageb.yaml +LIB=/mnt/MediaDisk/Music/MyLibrary +LOGDIR=/var/log +QUEUE_MARK=/var/lib/beets/stageb-done.txt + +DEFAULT_QUEUE=( + "$LIB/Johnny Cash Discography" + "$LIB/Jimi Hendrix" + "$LIB/Queen Discography @ 320Kbps [Aufseher]" + "$LIB/Van Halen - Studio Discography 1978 - 2012 [FLAC] [h33t] - Kitlope" + "$LIB/Nine Inch Nails - Discography (1989 - 2008) [FLAC] [h33t] - Kitlope" + "$LIB/Styx [Discography]" + "$LIB/Leonard Cohen - Studio Discography (1967 - 2012) [Mp3 320]" + "$LIB/DLMusic" + "$LIB/Flac Zips" +) + +if [ "$#" -gt 0 ]; then + QUEUE=("$@") +else + QUEUE=("${DEFAULT_QUEUE[@]}") +fi + +mkdir -p "$(dirname "$QUEUE_MARK")" +touch "$QUEUE_MARK" + +log() { echo "$(date -u +%H:%M:%SZ) $*"; } + +for dir in "${QUEUE[@]}"; do + [ -d "$dir" ] || { log "SKIP (missing): $dir"; continue; } + if grep -qxF "$dir" "$QUEUE_MARK"; then + log "SKIP (already done): $dir" + continue + fi + + # Never run two imports at once. + while pgrep -f "[b]eet.*import" >/dev/null; do + log "waiting for the running import to finish before $dir" + sleep 30 + done + + slug=$(basename "$dir" | tr -c 'A-Za-z0-9' '-' | cut -c1-48) + logfile="$LOGDIR/beets-stageB-$slug.log" + log "importing: $dir" + "$BEET" -c "$CONF" import -q "$dir" > "$logfile" 2>&1 + rc=$? + skipped=$(grep -c "Skipping" "$logfile" 2>/dev/null || echo 0) + items=$(grep -cE "Importing|Applied" "$logfile" 2>/dev/null || echo 0) + log "done: $dir exit=$rc applied_markers=$items albums_skipped=$skipped log=$logfile" + if [ "$rc" -eq 0 ]; then + echo "$dir" >> "$QUEUE_MARK" + fi +done + +log "stage B queue finished" From 9ef4b3c59d40c97c624a42355dd578580ee95a54 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Thu, 26 Nov 2026 12:27:51 -0700 Subject: [PATCH 12/40] music-audit: resolve the albums beets declines Stage B's quiet import drops every match that is not near-perfect, so a messy discography yields almost nothing: the whole queue applied 0 albums and skipped 151. Two causes, both confirmed on disk: * quiet_fallback: skip turns any 'medium' match into silence. Raising strong_rec_thresh to 0.20 does not help, because beets judges the album as a whole and a wrong album tag drags the distance past the threshold even when the displayed similarity is 86%. * albums whose disc folders are separate directories are matched against the whole release, so they never line up. So the declines are resolved outside beets: mb-pick.py search MusicBrainz for a folder and score the candidates against what is actually on disk (a medium of exactly N tracks, the release total, official status, the disc number in the folder name) mb-tag.py write the chosen release with mutagen. Full write when the track count lines up, --album-only when the folder is a partial rip (grouping fixed, lying track numbers avoided), and --gaps names the tracks that are missing resolve-albums.py walk a discography, skip anything already carrying a MusicBrainz album id, and log a JSON manifest of outcomes Pink Floyd's nine declines are now all tagged: Atom Heart Mother, The Wall disc 2 and the Ummagumma studio disc got full tags; Saucerful, Momentary Lapse, Dark Side and the three Piper 40th discs got album-level tags because the rips are missing tracks (Us and Them, Sorrow, Set the Controls exist only as live versions elsewhere in the library). Styx: 11 of 15 albums fully tagged. --- tools/music-audit/mb-pick.py | 175 ++++++++++++++++++++++++ tools/music-audit/mb-tag.py | 201 ++++++++++++++++++++++++++++ tools/music-audit/resolve-albums.py | 194 +++++++++++++++++++++++++++ 3 files changed, 570 insertions(+) create mode 100755 tools/music-audit/mb-pick.py create mode 100755 tools/music-audit/mb-tag.py create mode 100755 tools/music-audit/resolve-albums.py diff --git a/tools/music-audit/mb-pick.py b/tools/music-audit/mb-pick.py new file mode 100755 index 0000000..226697a --- /dev/null +++ b/tools/music-audit/mb-pick.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Pick the right MusicBrainz release for an album folder beets declined. + +For a folder it asks MusicBrainz for releases by artist+title and scores them +against what is actually on disk: + + * a medium whose track count equals the file count -> the folder is one disc + * the release total matching the file count -> the folder is the album + * official status, album (not compilation) -> mild preference + * the disc number in the folder name -> must exist on that release + +Prints the chosen release and the runners-up. With --import it then runs +`beet import -L ` for the folder, which is how a declined album gets +the correct metadata instead of guessing. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +import time +import urllib.parse +import urllib.request + +UA = "Dogebot/1.0 ( https://github.com/RustyRaptor/doge_cogs )" +MB = "https://musicbrainz.org/ws/2/release" +BEET = "/opt/beets-venv/bin/beet" +CONF = "/etc/beets/config-stageb.yaml" + + +def q(path: str) -> str: + """GET with retries: MusicBrainz answers 503/429 while it rate-limits.""" + last = None + for attempt in range(4): + try: + req = urllib.request.Request(path, headers={"User-Agent": UA}) + with urllib.request.urlopen(req, timeout=40) as r: + return r.read().decode() + except Exception as e: + last = e + code = getattr(e, "code", None) + if code not in (429, 503): + raise + time.sleep(2 * (attempt + 1)) + raise last + + +def parse_folder(name: str, artist_hint: str | None = None) -> tuple[str, str, int | None]: + """Folder name -> (artist, title, disc hint). + + Discography folders are inconsistent: some are "Artist - Album [FLAC]", some + are just "1980 Paradise theater (320 L)". When the name carries no artist we + fall back to the caller's hint (tags or the parent folder) rather than + guessing a band. + """ + disc = None + m = re.search(r"\[Disc\s*(\d+)\]", name, re.I) + if m: + disc = int(m.group(1)) + s = re.sub(r"\[(Disc\s*\d+|EAC[^\]]*|FLAC|MP3[^\]]*|\d{4}[^\]]*)\]", " ", name, flags=re.I) + s = re.sub(r"\((oan|anniv[^)]*|[^)]*)\)", " ", s, flags=re.I) + s = re.sub(r"\b(19|20)\d{2}\b", " ", s) + s = re.sub(r"\b(EAC|FLAC|MP3|320|320Kbps|V0|V2)\b", " ", s, flags=re.I) + s = re.sub(r"\(\s*\d{3}\s*[LK]?\s*\)", " ", s) # "(320 L)", "(320)" quality suffixes + s = re.sub(r"^\s*(19|20)\d{2}\s+", "", s) # leading release year + # Editions and leftovers: MusicBrainz titles do not carry them. + s = re.sub(r"\b(\d+(st|nd|rd|th)|Anniversary|Edition|Remaster(ed)?|Deluxe|Expanded|Studio Album)\b", " ", s, flags=re.I) + s = re.sub(r"[\[\]()]", " ", s) + s = re.sub(r"\s+", " ", s).strip(" -") + if s.lower().startswith("va - "): + artist, title = "Various Artists", s[5:] + elif " - " in s: + artist, title = s.split(" - ", 1) + else: + artist, title = (artist_hint or "").strip(), s + return artist.strip(), title.strip(), disc + + +def candidates(artist: str, title: str) -> list[dict]: + query = 'artist:"%s" AND release:"%s"' % (artist, title) + url = "%s?query=%s&fmt=json&limit=12" % (MB, urllib.parse.quote(query)) + data = json.loads(q(url)) + time.sleep(1.1) + out = [] + for rel in data.get("releases", []): + media = rel.get("media") or [] + counts = [m.get("track-count") or 0 for m in media] + out.append({ + "id": rel.get("id"), "title": rel.get("title"), "date": (rel.get("date") or "")[:4], + "country": rel.get("country"), "status": rel.get("status"), + "type": ((rel.get("release-group") or {}).get("primary-type") or ""), + "media": len(media), "counts": counts, "total": sum(counts), + "disambig": rel.get("disambiguation") or "", + }) + return out + + +def score(c: dict, files: int, disc: int | None) -> tuple[float, str]: + s, why = 0.0, [] + if disc: + if len(c["counts"]) >= disc: + s += 3 + if c["counts"][disc - 1] == files: + s += 4 + why.append("disc %d has exactly %d tracks" % (disc, files)) + else: + s -= 5 + why.append("no disc %d" % disc) + if files in c["counts"] and not disc: + s += 6 + why.append("a medium matches %d tracks" % files) + if c["total"] == files: + s += 3 + why.append("total matches %d" % files) + if c["status"] == "Official": + s += 1 + why.append("official") + if c["type"] == "Album": + s += 1 + if c["type"] in ("Compilation", "Live") and "best of" not in c["title"].lower(): + s -= 1 + # Only penalise a size mismatch when nothing matched: for a disc folder the + # release total is expected to be much larger than the folder. + if files not in c["counts"] and c["total"] != files: + s -= min(abs(c["total"] - files) * 0.5, 3.0) + return s, ", ".join(why) or "weak" + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("folders", nargs="+") + ap.add_argument("--import", dest="do_import", action="store_true") + ap.add_argument("--min-score", type=float, default=6.0) + args = ap.parse_args() + + for folder in args.folders: + if not os.path.isdir(folder): + print("missing: %s" % folder) + continue + files = len([f for f in os.listdir(folder) if f.lower().endswith((".flac", ".mp3", ".m4a", ".ogg", ".opus"))]) + artist, title, disc = parse_folder(os.path.basename(folder)) + print("\n%s" % os.path.basename(folder)[:78]) + print(" parsed: artist=%r title=%r disc=%s files=%d" % (artist, title, disc, files)) + try: + cands = candidates(artist, title) + except Exception as e: + print(" MB search failed: %s" % e) + continue + if not cands: + print(" no candidates") + continue + ranked = sorted(((score(c, files, disc), c) for c in cands), key=lambda x: -x[0][0]) + (best_score, why), best = ranked[0] + print(" best: %s (%s) id=%s %.1f [%s]" % (best["title"][:44], best["date"], best["id"], best_score, why)) + print(" media=%d counts=%s total=%d status=%s type=%s" % + (best["media"], best["counts"], best["total"], best["status"], best["type"])) + for (sc, wy), c in ranked[1:3]: + print(" alt: %-40s %s %.1f" % (c["title"][:40], c["date"], sc)) + if args.do_import: + if best_score < args.min_score: + print(" -> below --min-score %.1f, not importing" % args.min_score) + continue + cmd = [BEET, "-c", CONF, "import", "-q", "-I", "-L", best["id"], folder] + print(" -> importing with -L %s" % best["id"]) + r = subprocess.run(cmd, capture_output=True, text=True, timeout=1800) + print(" exit=%d %s" % (r.returncode, (r.stdout or "").strip().splitlines()[-1][:90] if r.stdout.strip() else "")) + time.sleep(1.2) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/music-audit/mb-tag.py b/tools/music-audit/mb-tag.py new file mode 100755 index 0000000..f00db42 --- /dev/null +++ b/tools/music-audit/mb-tag.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Write tags for one album folder directly from a MusicBrainz release. + +Used for the albums beets declines: its quiet mode skips "medium" matches, and +these folders (wrong album tags, individual discs, odd editions) always land +there. Here the release is fetched once, the tracklist is mapped onto the files +in track order, and the tags are written with mutagen. + +Refuses to act when the track count does not line up — a mismatch means the +folder is a partial rip, and writing would attach wrong metadata. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import time +import urllib.request + +from mutagen.flac import FLAC +from mutagen.id3 import ID3, TALB, TDRC, TIT2, TPE1, TPE2, TRCK, TPOS, TXXX +from mutagen.mp3 import MP3 +import difflib + +UA = "Dogebot/1.0 ( https://github.com/RustyRaptor/doge_cogs )" +MB = "https://musicbrainz.org/ws/2/release/" +AUDIO = (".flac", ".mp3", ".m4a", ".ogg", ".opus") + + +def get(url: str) -> dict: + for attempt in range(4): + try: + req = urllib.request.Request(url, headers={"User-Agent": UA}) + with urllib.request.urlopen(req, timeout=40) as r: + return json.loads(r.read().decode()) + except Exception: + if attempt == 3: + raise + time.sleep(2 * (attempt + 1)) + return {} + + +def credit(items) -> str: + return "".join((a.get("name") or "") + (a.get("joinphrase") or "") for a in (items or [])).strip() + + +def track_numbers(files: list[str]) -> list[int]: + nums = [] + for f in files: + m = re.match(r"\s*(\d{1,3})", f) + nums.append(int(m.group(1)) if m else 0) + return nums + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("folder") + ap.add_argument("--release-id", required=True) + ap.add_argument("--disc", type=int, default=0, help="only this medium (1-based); 0 = whole release") + ap.add_argument("--write", action="store_true") + ap.add_argument("--gaps", action="store_true", help="name the release tracks the folder is missing") + ap.add_argument("--album-only", action="store_true", + help="write album/albumartist/date/MBID only, leaving track numbers alone") + args = ap.parse_args() + + rel = get("%s%s?inc=recordings+artist-credits+media&fmt=json" % (MB, args.release_id)) + time.sleep(1.1) + if not rel.get("id"): + print(" release not found") + return 1 + + album = rel.get("title") + albumartist = credit(rel.get("artist-credit")) + date = rel.get("date") or "" + media = rel.get("media") or [] + disctotal = len(media) + + if args.disc: + if args.disc > len(media): + print(" release has no disc %d" % args.disc) + return 1 + chosen = [(args.disc, media[args.disc - 1])] + else: + chosen = [(i + 1, m) for i, m in enumerate(media)] + + wanted = [] + for disc_no, medium in chosen: + for t in medium.get("tracks") or []: + wanted.append({ + "disc": disc_no, + "pos": t.get("position") or t.get("number"), + "title": t.get("title"), + "artist": credit(t.get("artist-credit")) or albumartist, + "recording": (t.get("recording") or {}).get("id"), + "medium_tracks": len(medium.get("tracks") or []), + }) + + files = sorted(f for f in os.listdir(args.folder) if f.lower().endswith(AUDIO)) + print(" release: %s — %s (%s) · %d media · %d wanted tracks vs %d files" + % (album, albumartist, date[:4], disctotal, len(wanted), len(files))) + if len(files) != len(wanted): + print(" partial rip: %d of %d tracks present" % (len(files), len(wanted))) + # Pair file names with release titles by similarity, so the tracks left + # unpaired are the ones actually missing from the folder. + pool = [(i, (w["title"] or "").lower()) for i, w in enumerate(wanted)] + used, pairs = set(), [] + for f in files: + stem = re.sub(r"^\s*\d{1,3}[\s._-]*", "", os.path.splitext(f)[0]).lower() + best, score = None, 0.0 + for i, title in pool: + if i in used: + continue + r = difflib.SequenceMatcher(None, stem, title).ratio() + if r > score: + best, score = i, r + if best is not None and score > 0.45: + used.add(best) + pairs.append((f, wanted[best])) + else: + pairs.append((f, None)) + for f, w in pairs: + print(" %-44s <- %s" % (f[:44], (w["title"] if w else "?") or "")) + missing = [w for i, w in enumerate(wanted) if i not in used] + if missing and (args.gaps or not args.album_only): + print(" missing from this folder:") + for w in missing: + print(" %d/%s %s" % (w["disc"], w["pos"], w["title"])) + if not args.album_only: + print(" REFUSING to write track tags: counts differ") + return 2 + print(" --album-only: writing album-level tags, track numbers untouched") + for f in files: + path = os.path.join(args.folder, f) + if args.write and path.lower().endswith(".flac"): + x = FLAC(path) + x["album"] = [album] + x["albumartist"] = [albumartist] + if date: + x["date"] = [date] + x["musicbrainz_albumid"] = [rel["id"]] + if args.disc: + x["discnumber"] = [str(args.disc)] + x["disctotal"] = [str(disctotal)] + x.save() + print(" %s album-level tags on %d files" % ("wrote" if args.write else "would write", len(files))) + return 0 + + nums = track_numbers(files) + if len(set(nums)) == len(nums) and all(nums): + order = [files[i] for i in sorted(range(len(files)), key=lambda i: nums[i])] + else: + order = files + + for fname, want in zip(order, wanted): + path = os.path.join(args.folder, fname) + if args.write: + if path.lower().endswith(".flac"): + f = FLAC(path) + little = lambda v: [str(v)] + f["album"] = little(album) + f["albumartist"] = little(albumartist) + f["artist"] = little(want["artist"]) + f["title"] = little(want["title"]) + f["tracknumber"] = little(want["pos"]) + f["tracktotal"] = little(want["medium_tracks"]) + f["discnumber"] = little(want["disc"]) + f["disctotal"] = little(disctotal) + if date: + f["date"] = little(date) + f["musicbrainz_albumid"] = little(rel["id"]) + if want["recording"]: + f["musicbrainz_trackid"] = little(want["recording"]) + f.save() + else: + try: + tags = ID3(path) + except Exception: + tags = ID3() + tags.setall("TALB", [TALB(encoding=3, text=[album])]) + tags.setall("TPE2", [TPE2(encoding=3, text=[albumartist])]) + tags.setall("TPE1", [TPE1(encoding=3, text=[want["artist"]])]) + tags.setall("TIT2", [TIT2(encoding=3, text=[want["title"]])]) + tags.setall("TRCK", [TRCK(encoding=3, text=["%s/%d" % (want["pos"], want["medium_tracks"])])]) + tags.setall("TPOS", [TPOS(encoding=3, text=["%d/%d" % (want["disc"], disctotal)])]) + if date: + tags.setall("TDRC", [TDRC(encoding=3, text=[date])]) + tags.setall("TXXX:MusicBrainz Album Id", [TXXX(encoding=3, desc="MusicBrainz Album Id", text=[rel["id"]])]) + if want["recording"]: + tags.setall("TXXX:MusicBrainz Recording Id", + [TXXX(encoding=3, desc="MusicBrainz Recording Id", text=[want["recording"]])]) + tags.save(path) + print(" %-44s -> %s/%s %s" % (fname[:44], want["disc"], want["pos"], (want["title"] or "")[:38])) + + print(" %s %d files" % ("wrote" if args.write else "would write", len(order))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/music-audit/resolve-albums.py b/tools/music-audit/resolve-albums.py new file mode 100755 index 0000000..96e6d2b --- /dev/null +++ b/tools/music-audit/resolve-albums.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Resolve albums that beets declined, by pinning a MusicBrainz release. + +beets' quiet import drops every match that is not near-perfect, which on a +messy discography is most of them. This walks a tree of album folders, finds the +ones whose files have no musicbrainz_albumid, asks MusicBrainz for the release, +and hands the result to mb-tag: + + track count lines up -> full tag write (album, artist, titles, numbers) + disc folder of a bigger release-> album-level write, track numbers untouched + nothing plausible -> recorded as unresolved for a human + +Writes a JSON manifest so the outcome is auditable, and never touches a folder +that already carries a MusicBrainz album id (mbsync keeps those fresh). +""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from importlib import util as _util + +def _load_mbpick(): + """Load mb-pick from wherever it lives: repo, /usr/local/bin/*.py, or the installed name.""" + here = os.path.dirname(os.path.abspath(__file__)) + for cand in (os.path.join(here, "mb-pick.py"), "/usr/local/bin/mb-pick.py", "/usr/local/bin/mb-pick"): + if os.path.isfile(cand): + spec = _util.spec_from_file_location("mbpick", cand) + mod = _util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + raise SystemExit("mb-pick not found next to resolve-albums; install it as /usr/local/bin/mb-pick.py") + +mbpick = _load_mbpick() + +AUDIO = (".flac", ".mp3", ".m4a", ".ogg", ".opus") +MBTAG = "/usr/local/bin/mb-tag" +PY = "/opt/beets-venv/bin/python" + + +def audio_files(d: str) -> list[str]: + return sorted(f for f in os.listdir(d) if f.lower().endswith(AUDIO)) + + +def _tag_value(tags, *names) -> str: + """Read a tag whatever the container calls it: FLAC keys or ID3 frames.""" + for name in names: + v = tags.get(name) + if v is None: + continue + if isinstance(v, list): + v = v[0] if v else "" + s = str(v).strip() + if s: + return s + return "" + + +def folder_state(d: str) -> tuple[int, int, int | None]: + """(audio count, files with a MusicBrainz album id, disc number). + + MP3 stores the id in a TXXX frame, FLAC in a Vorbis comment; checking only + one of them made every MP3 album look untagged and get rewritten. + """ + from mutagen import File + + files = audio_files(d) + have, disc = 0, None + for f in files: + try: + t = File(os.path.join(d, f)).tags or {} + except Exception: + continue + if _tag_value(t, "musicbrainz_albumid", "TXXX:MusicBrainz Album Id"): + have += 1 + dnum = _tag_value(t, "discnumber", "TPOS").split("/")[0] + if disc is None and dnum.isdigit(): + disc = int(dnum) + return len(files), have, disc + + +def tag_albumartist(d: str) -> str: + """The albumartist already in the files, if any: the best artist hint we have.""" + from mutagen import File + + for f in audio_files(d)[:2]: + try: + t = File(os.path.join(d, f)).tags or {} + except Exception: + continue + val = _tag_value(t, "albumartist", "TPE2", "artist", "TPE1") + if val and val.lower() not in ("various artists", "unknown artist"): + return val + return "" + + +def parent_artist(d: str) -> str: + """Fall back to the discography folder name: "Styx [Discography]" -> "Styx".""" + parent = os.path.basename(os.path.dirname(os.path.abspath(d))) + parent = re.sub(r"\[.*?\]|\(.*?\)", " ", parent) + parent = re.sub(r"\b(discography|studio|flac|mp3|320\w*|collection|anthology)\b", " ", parent, flags=re.I) + parent = re.sub(r"\s+-\s+.*$", "", parent) + return re.sub(r"\s+", " ", parent).strip(" -") + + +def album_dirs(root: str) -> list[str]: + out = [] + for dirpath, dirnames, filenames in os.walk(root): + if any(f.lower().endswith(AUDIO) for f in filenames): + out.append(dirpath) + return sorted(out) + + +def run_tag(folder: str, release_id: str, disc: int | None, album_only: bool) -> tuple[int, str]: + cmd = [PY, MBTAG, folder, "--release-id", release_id, "--write"] + if disc: + cmd += ["--disc", str(disc)] + if album_only: + cmd.append("--album-only") + r = subprocess.run(cmd, capture_output=True, text=True, timeout=900) + tail = (r.stdout or "").strip().splitlines() + return r.returncode, (tail[-1] if tail else "")[:110] + + +def main() -> int: + import argparse + + ap = argparse.ArgumentParser() + ap.add_argument("roots", nargs="+") + ap.add_argument("--manifest", default="/var/lib/beets/album-resolve.json") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--dry", action="store_true") + args = ap.parse_args() + + results, done = [], 0 + for root in args.roots: + for folder in album_dirs(root): + n, have, disc_tag = folder_state(folder) + if n == 0 or have == n: + continue + if args.limit and done >= args.limit: + break + hint = tag_albumartist(folder) or parent_artist(folder) + artist, title, disc = mbpick.parse_folder(os.path.basename(folder), artist_hint=hint) + disc = disc or disc_tag + print("\n%s (%d files, %d tagged, disc=%s)" % (os.path.basename(folder)[:70], n, have, disc), flush=True) + try: + cands = mbpick.candidates(artist, title) + except Exception as e: + print(" MB unavailable: %s" % e, flush=True) + results.append({"folder": folder, "status": "mb-error", "error": str(e)[:120]}) + continue + if not cands: + print(" no candidates", flush=True) + results.append({"folder": folder, "status": "no-candidates", "artist": artist, "title": title}) + continue + ranked = sorted(((mbpick.score(c, n, disc), c) for c in cands), key=lambda x: -x[0][0]) + (score, why), best = ranked[0] + exact = (disc and len(best["counts"]) >= disc and best["counts"][disc - 1] == n) or (n in best["counts"]) + print(" pick: %s (%s) %.1f [%s] exact=%s" % (best["title"][:40], best["date"], score, why, exact), flush=True) + if score < 3.0: + print(" -> unresolved", flush=True) + results.append({"folder": folder, "status": "unresolved", "score": score, + "candidate": best["id"], "files": n}) + continue + if args.dry: + results.append({"folder": folder, "status": "dry", "release": best["id"], "exact": exact}) + continue + rc, tail = run_tag(folder, best["id"], disc if len(best["counts"]) > 1 else None, album_only=not exact) + status = "tagged" if rc == 0 else "failed" + print(" -> %s rc=%d %s" % (status, rc, tail), flush=True) + results.append({"folder": folder, "status": status, "release": best["id"], "exact": exact, + "files": n, "rc": rc, "detail": tail}) + done += 1 + time.sleep(1.5) + + os.makedirs(os.path.dirname(args.manifest), exist_ok=True) + with open(args.manifest, "w") as fh: + json.dump(results, fh, indent=1) + tally = {} + for r in results: + tally[r["status"]] = tally.get(r["status"], 0) + 1 + print("\n%s" % json.dumps(tally)) + print("manifest: %s" % args.manifest) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 34d4e5afab148bc281fbe4128616d33017a3b6ea Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Thu, 26 Nov 2026 14:13:01 -0700 Subject: [PATCH 13/40] music-audit: parse numbering, years and bare disc folders MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three folder-naming shapes broke artist/title detection, and each one turned into a pile of silent 'no candidates': '02. 1958- The Songs That Made Him Famous' the year was stripped but its dangling dash stayed, so the string split into artist '02.' — leading index prefixes are now dropped and the year takes its dash with it 'Stockholm 67/Disc 1' the folder said only 'Disc 1', so the album name is one level up and the artist two: resolve-albums now climbs out of bare disc folders '03. 1959- The Fabolous Johnny Cash' spelling as shipped; still no candidate, and correctly left alone rather than force-matched Johnny Cash went from 72/72 no-candidates to finding real releases (Hymns by Johnny Cash 12/12, Now There Was a Song 12/12, ...). --- tools/music-audit/mb-pick.py | 3 ++- tools/music-audit/resolve-albums.py | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/tools/music-audit/mb-pick.py b/tools/music-audit/mb-pick.py index 226697a..9f5d413 100755 --- a/tools/music-audit/mb-pick.py +++ b/tools/music-audit/mb-pick.py @@ -62,7 +62,8 @@ def parse_folder(name: str, artist_hint: str | None = None) -> tuple[str, str, i disc = int(m.group(1)) s = re.sub(r"\[(Disc\s*\d+|EAC[^\]]*|FLAC|MP3[^\]]*|\d{4}[^\]]*)\]", " ", name, flags=re.I) s = re.sub(r"\((oan|anniv[^)]*|[^)]*)\)", " ", s, flags=re.I) - s = re.sub(r"\b(19|20)\d{2}\b", " ", s) + s = re.sub(r"^\s*\d{1,3}\s*[.)\]]?\s*[-–]?\s*", "", s) # "02. ", "13 - " index prefixes + s = re.sub(r"\b(19|20)\d{2}\s*[-–]?\s*", " ", s) # year, optionally with a dangling dash s = re.sub(r"\b(EAC|FLAC|MP3|320|320Kbps|V0|V2)\b", " ", s, flags=re.I) s = re.sub(r"\(\s*\d{3}\s*[LK]?\s*\)", " ", s) # "(320 L)", "(320)" quality suffixes s = re.sub(r"^\s*(19|20)\d{2}\s+", "", s) # leading release year diff --git a/tools/music-audit/resolve-albums.py b/tools/music-audit/resolve-albums.py index 96e6d2b..15f416d 100755 --- a/tools/music-audit/resolve-albums.py +++ b/tools/music-audit/resolve-albums.py @@ -108,6 +108,27 @@ def parent_artist(d: str) -> str: return re.sub(r"\s+", " ", parent).strip(" -") +DISC_ONLY = re.compile(r"^(disc|cd|disk)\s*\d+$", re.I) + + +def album_identity(folder: str, hint: str) -> tuple[str, str, int | None]: + """(artist, title, disc) for a folder, climbing out of bare "Disc N" folders. + + Compilations keep each disc in its own directory, so the folder itself says + only "Disc 1" — the album name is one level up and the artist two. + """ + artist, title, disc = mbpick.parse_folder(os.path.basename(folder), artist_hint=hint) + climbs = 0 + while (not title or DISC_ONLY.match(title)) and climbs < 2: + folder = os.path.dirname(os.path.abspath(folder)) + climbs += 1 + a2, title, d2 = mbpick.parse_folder(os.path.basename(folder), artist_hint=hint) + disc = disc or d2 + if a2 and a2 != hint: + artist = a2 + return artist, title, disc + + def album_dirs(root: str) -> list[str]: out = [] for dirpath, dirnames, filenames in os.walk(root): @@ -146,7 +167,7 @@ def main() -> int: if args.limit and done >= args.limit: break hint = tag_albumartist(folder) or parent_artist(folder) - artist, title, disc = mbpick.parse_folder(os.path.basename(folder), artist_hint=hint) + artist, title, disc = album_identity(folder, hint) disc = disc or disc_tag print("\n%s (%d files, %d tagged, disc=%s)" % (os.path.basename(folder)[:70], n, have, disc), flush=True) try: From cda5bd83a98aa24f86c3b81f21e1cebd47dc8778 Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Fri, 27 Nov 2026 21:14:57 -0700 Subject: [PATCH 14/40] mcp-lapis: never fork the store onto a client host The wrapper preferred a local LaPis checkout over the ssh bridge. That is fine on the host that owns the store and wrong everywhere else: a checkout appeared on the Deck today and, from that moment, the Deck wrote to a brand-new local DB while the 90 real observations stayed on arceus, invisible to it. A host now bridges when ~/.pi/memory/REMOTE_STORE names the store host (or when LAPIS_FORCE_REMOTE=1). Both are host-local state, so the owning host is unaffected and nothing has to be deleted to become a client again. --- bin/mcp-lapis | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/bin/mcp-lapis b/bin/mcp-lapis index dd71946..9ba7d06 100755 --- a/bin/mcp-lapis +++ b/bin/mcp-lapis @@ -20,11 +20,30 @@ node_bin() { return 1 } -if [ -f "$LAPIS/memory-store.js" ]; then +# One store, one host. The store lives on arceus; a host that merely has the +# checkout is a client. Without this, a fresh clone on a client host silently +# forks the memory: the wrapper would start writing to an empty local DB while +# every memory already made on arceus became invisible to that host. +# +# Set LAPIS_FORCE_REMOTE=1, or drop the remote's "user@host" into +# ~/.pi/memory/REMOTE_STORE, to force the bridge. Both are host-local: they +# never travel with dotfiles, so the host holding the store is unaffected. +FORCE_REMOTE=${LAPIS_FORCE_REMOTE:-0} +if [ -f "$HOME/.pi/memory/REMOTE_STORE" ]; then + FORCE_REMOTE=1 + STORE_HOST=$(tr -d ' \n' < "$HOME/.pi/memory/REMOTE_STORE") + [ -n "$STORE_HOST" ] && LAPIS_REMOTE="$STORE_HOST" +fi + +if [ "$FORCE_REMOTE" != 1 ] && [ -f "$LAPIS/memory-store.js" ]; then NODE=$(node_bin) || { echo "mcp-lapis: no node found for the local LaPis store" >&2; exit 1; } exec "$NODE" "$LAPIS/memory-store.js" mcp fi +if [ "$FORCE_REMOTE" = 1 ]; then + echo "mcp-lapis: using the shared store on ${LAPIS_REMOTE:-ziadarafat@10.0.0.23}" >&2 +fi + # No local store: bridge to the host that has one. LAPIS_REMOTE defaults to the # personal homelab host; keep it a plain "user@host" so ProxyJump/ssh config apply. REMOTE="${LAPIS_REMOTE:-ziadarafat@10.0.0.23}" From 79125a841bf9acb60a1b45c59dbd536bd346fa5c Mon Sep 17 00:00:00 2001 From: ziadarafat Date: Sat, 28 Nov 2026 18:11:22 -0700 Subject: [PATCH 15/40] windows-vm: template-first, Packer for rebuilds Testing a USB device under Windows meant driving a Windows install by hand, and that turned out to have one genuinely hostile step. The installation media shows 'Press any key to boot from CD or DVD......' for about five seconds; miss it and the firmware falls through to the empty disk with 'BdsDxe: No bootable option'. qm sendkey cannot be relied on for it: it injects PS/2 events while a q35 VM has only a USB keyboard, and the event must land inside that window. In practice the keys reached the firmware boot menu but never the media prompt. Two ways out, in the order they are worth the effort: template + clone install once, sysprep /generalize, qm template; every later VM is a clone that boots in about a minute Packer win11.pkr.hcl builds the template unattended. boot_command sends real keystrokes over VNC and repeats the spacebar across the whole prompt window, which is the fix: one press is a race, ten presses is not The answer file rides on a floppy so Windows finds it at A:\ instead of guessing which CD-ROM letter it got, and virtio-win is installed so disks and network are paravirtualised rather than emulated. --- tools/windows-vm/README.md | 87 +++++++++++++ tools/windows-vm/answer/autounattend.xml | 119 ++++++++++++++++++ tools/windows-vm/answer/firstboot.ps1 | 16 +++ tools/windows-vm/win11.pkr.hcl | 153 +++++++++++++++++++++++ 4 files changed, 375 insertions(+) create mode 100644 tools/windows-vm/README.md create mode 100644 tools/windows-vm/answer/autounattend.xml create mode 100644 tools/windows-vm/answer/firstboot.ps1 create mode 100644 tools/windows-vm/win11.pkr.hcl diff --git a/tools/windows-vm/README.md b/tools/windows-vm/README.md new file mode 100644 index 0000000..556ad03 --- /dev/null +++ b/tools/windows-vm/README.md @@ -0,0 +1,87 @@ +# Throwaway Windows VMs on Proxmox + +Two ways to get a Windows guest for a test like "does this USB device work under +Windows", in the order they are worth using. + +## 1. Template + clone (the everyday path) + +One interactive install, then every later VM is a clone that boots in about a +minute. + +```sh +# after the guest is installed and updated +qm start # boot it, run Windows Update, then inside Windows: +# C:\Windows\System32\Sysprep\sysprep.exe /oobe /generalize /shutdown +qm template + +# every time after that +qm clone 9000 150 --name win-test --full +qm set 150 --memory 8192 --cores 4 +qm set 150 -hostpci0 0000:0c:00.3,pcie=1 # if the test needs USB hardware +qm start 150 +``` + +A clone keeps the template's SID until sysprep strips it, which is why the +template is generalised rather than merely shut down. + +## 2. Packer rebuild (when you want a clean, reproducible image) + +`win11.pkr.hcl` builds the template from the ISO with nobody watching. It exists +because the hand-driven install has one hostile step, described below. + +```sh +packer init . +packer build -var proxmox_token="$PROXMOX_PACKER_TOKEN" win11.pkr.hcl +``` + +Needs `local:iso/win11-eval.iso` and `local:iso/virtio-win.iso`, and an API token +(user `packer@pve`, role with `VM.Allocate`, `VM.Config.*`, `Datastore.AllocateSpace`). +Keep the token in `secretctl`, never in this file. + +## The step that makes Windows installs awkward + +Windows installation media prints + +``` +Press any key to boot from CD or DVD...... +``` + +for about five seconds. Miss it and the firmware falls through to the empty +disk and stops: `BdsDxe: No bootable option or device was found.` + +`qm sendkey` is not a reliable way to satisfy it. It injects PS/2 keyboard +events, while a q35 VM has only a USB keyboard, and the event has to land inside +a five-second window. On 2026-11-28 that cost several failed boots: the keys +reached the *firmware boot menu* (which redrew) but never the media's prompt. + +Packer's `boot_command` sends real keystrokes over VNC and lets you repeat them +across the whole window: + +```hcl +boot_command = [ + "", +] +``` + +That repetition is the fix — one press is a race, ten presses is not. + +## Files + +| File | Purpose | +|---|---| +| `win11.pkr.hcl` | Packer build: VM, UEFI + vTPM, virtio disk/NIC, answer file, sysprep, template | +| `answer/autounattend.xml` | Unattended install: disk layout, local admin, auto-logon, OOBE skipped | +| `answer/firstboot.ps1` | First-logon hook: enable WinRM so Packer can drive the rest | + +## Notes + +- Deliver the answer file on a **floppy** (`floppy_files`), not a second CD-ROM: + Windows then finds it at `A:\` and there is no drive-letter guessing. +- `virtio-win` gives paravirtualised disk and network. Without it the guest runs + on emulated SATA and `e1000`, which is fine for a driver test but slow. +- `qemu_agent = true` means you can `qm shutdown`/`qm guest exec` later instead + of power-cycling or mounting the disk. +- For USB hardware tests, pass the whole PCIe controller (`hostpci0`) rather than + a single device: a device passthrough is still enumerated by the host kernel + first, so it inherits any host-side fault. Check the controller's IOMMU group + is alone before relying on it. diff --git a/tools/windows-vm/answer/autounattend.xml b/tools/windows-vm/answer/autounattend.xml new file mode 100644 index 0000000..4344deb --- /dev/null +++ b/tools/windows-vm/answer/autounattend.xml @@ -0,0 +1,119 @@ + + + + + en-US + en-US + en-US + en-US + en-US + + + + + + 1 + reg add HKLM\SYSTEM\Setup\LabConfig /v BypassTPMCheck /t REG_DWORD /d 1 /f + + + 2 + reg add HKLM\SYSTEM\Setup\LabConfig /v BypassSecureBootCheck /t REG_DWORD /d 1 /f + + + 3 + reg add HKLM\SYSTEM\Setup\LabConfig /v BypassRAMCheck /t REG_DWORD /d 1 /f + + + 4 + reg add HKLM\SYSTEM\Setup\LabConfig /v BypassCPUCheck /t REG_DWORD /d 1 /f + + + + OnError + + 0 + true + + + 1EFI100 + + + 2MSR16 + + + 3Primarytrue + + + + + 11FAT32 + + + 22 + + + 33NTFSC + + + + + + + 03 + + + + true + kraken + homelab + + + + + + + WINTEST + UTC + + + + + + + true + true + true + true + 3 + true + true + + + + + kraken + Administrators + kraken123!true</PlainText></Password> + </LocalAccount> + </LocalAccounts> + </UserAccounts> + <AutoLogon> + <Enabled>true</Enabled> + <Username>kraken</Username> + <Password><Value>kraken123!</Value><PlainText>true</PlainText></Password> + <LogonCount>999</LogonCount> + </AutoLogon> + <FirstLogonCommands> + <SynchronousCommand wcm:action="add"> + <Order>1</Order> + <Description>collect USB report</Description> + <CommandLine>cmd /c if exist A:\firstboot.ps1 powershell.exe -ExecutionPolicy Bypass -NoProfile -File A:\firstboot.ps1</CommandLine> + </SynchronousCommand> + </FirstLogonCommands> + </component> + </settings> +</unattend> diff --git a/tools/windows-vm/answer/firstboot.ps1 b/tools/windows-vm/answer/firstboot.ps1 new file mode 100644 index 0000000..b33df8f --- /dev/null +++ b/tools/windows-vm/answer/firstboot.ps1 @@ -0,0 +1,16 @@ +# Runs once on first logon in a freshly installed guest, before Packer's +# provisioners take over over WinRM. Keep it short: everything heavier is a +# Packer provisioner so it is visible in the build log. +$ErrorActionPreference = 'SilentlyContinue' +Set-Content -Path 'C:\firstboot.txt' -Value "firstboot $([DateTime]::UtcNow.ToString('s'))" + +# WinRM is how Packer drives the rest of the build. +Enable-PSRemoting -Force -SkipNetworkProfileCheck +Set-Item WSMan:\localhost\Service\Auth\Basic -Value $true +Set-Service WinRM -StartupType Automatic +Start-Service WinRM +Set-NetFirewallRule -DisplayGroup 'Windows Remote Management' -Enabled True + +# A test guest that sleeps, never hibernates, and has no lock screen. +powercfg /change standby-timeout-ac 0 +powercfg /change monitor-timeout-ac 0 diff --git a/tools/windows-vm/win11.pkr.hcl b/tools/windows-vm/win11.pkr.hcl new file mode 100644 index 0000000..ffa2d61 --- /dev/null +++ b/tools/windows-vm/win11.pkr.hcl @@ -0,0 +1,153 @@ +# Builds a Windows 11 Proxmox template with no human in the loop. +# +# Why this exists: a hand-driven Windows install has one genuinely hostile +# step. The installation media shows "Press any key to boot from CD or DVD" +# for about five seconds, and if no key arrives the firmware falls through to +# the empty disk and stops with "No bootable option or device was found". +# `qm sendkey` cannot reliably satisfy it: it injects PS/2 events, while a +# modern q35 VM has only a USB keyboard, and the timing has to land inside +# that window. +# +# Packer solves it the way it solves it everywhere: `boot_command` sends real +# keystrokes over VNC, so the <spacebar> repeat below lands whenever the +# prompt appears, and every <wait> is a real pause rather than a guess. +# +# Build: packer init . && packer build -var-file=secrets.pkrvars.hcl win11.pkr.hcl +# Needs: win11 ISO + virtio-win.iso in local:iso, an API token with VM.* rights. + +packer { + required_plugins { + proxmox = { + version = ">= 1.1.8" + source = "github.com/hashicorp/proxmox" + } + } +} + +variable "proxmox_url" { + type = string + default = "https://10.0.0.23:8006/api2/json" +} + +variable "proxmox_token" { + type = string + sensitive = true +} + +variable "iso_file" { + type = string + default = "local:iso/win11-eval.iso" +} + +variable "virtio_iso" { + type = string + default = "local:iso/virtio-win.iso" +} + +variable "template_name" { + type = string + default = "win11-test-template" +} + +source "proxmox-iso" "win11" { + proxmox_url = var.proxmox_url + username = "packer@pve!packer" + token = var.proxmox_token + insecure_skip_tls_verify = true + node = "ziadpve" + vm_id = 9100 + vm_name = var.template_name + + # UEFI + vTPM: Windows 11 refuses to install without them, and a test guest + # that pretends to have them is worth less than one that does. + bios = "ovmf" + machine = "q35" + efi_config { + efi_storage_pool = "vmstore" + efi_type = "4m" + pre_enrolled_keys = true + } + tpm_config { + tpm_storage_pool = "vmstore" + tpm_version = "v2.0" + } + + cores = 4 + memory = 8192 + os = "win11" + scsi_controller = "virtio-scsi-single" + + disks { + disk_size = "64G" + storage_pool = "vmstore" + type = "virtio" + discard = true + } + + network_adapters { + model = "virtio" + bridge = "vmbr0" + } + + iso_file = var.iso_file + unmount_iso = true + additional_iso_files { + device = "ide2" + iso_file = var.virtio_iso + unmount = true + iso_storage_pool = "local" + } + + # The answer file rides on a floppy, so Windows Setup finds it at A:\ and it + # never collides with a CD-ROM drive letter. + floppy_files = [ + "answer/autounattend.xml", + "answer/firstboot.ps1", + ] + + # This is the whole point of the exercise. Repeat the spacebar rather than + # pressing once: the prompt renders a variable beat after the DVD is selected. + boot = "order=ide0;virtio0" + boot_wait = "4s" + boot_command = [ + "<wait><spacebar><wait><spacebar><wait><spacebar><wait><spacebar><wait>", + "<spacebar><wait><spacebar><wait><spacebar><wait><spacebar><wait>", + "<spacebar><wait><spacebar><wait><spacebar><wait><spacebar><wait>", + ] + + # Wait for Setup to finish, reboot, and land on the desktop; then let + # sysprep/generalise (invoked by firstboot.ps1) shut the machine down. + communicator = "winrm" + winrm_username = "kraken" + winrm_password = "kraken123!" + winrm_timeout = "2h" + + qemu_agent = true + + # Convert the finished build into a template: it can only be cloned, never + # started by accident. + template_name = var.template_name + additional_arguments = "-device usb-kbd" +} + +build { + sources = ["source.proxmox-iso.win11"] + + # Guest-agent + virtio drivers come off the second ISO, so disks and network + # are paravirtualised instead of the slow emulated fallbacks. + provisioner "powershell" { + inline = [ + "Get-ChildItem D:\\ -Filter virtio-win-guest-tools.exe -Recurse | Select-Object -First 1 | ForEach-Object { Start-Process $_.FullName -ArgumentList '/S' -Wait }", + "Set-Service -Name WinRM -StartupType Automatic", + ] + } + + # Generalise so every clone gets its own SID, then power off for templating. + provisioner "powershell" { + inline = [ + "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit", + "while ($true) { $s = (Get-Service Sysprep).Status; if ($s -eq 'Stopped') { break }; Start-Sleep -Seconds 10 }", + "Stop-Computer -Force", + ] + } +} From ef97badfb5f17093281a0e0a25c5881bd6cde4dc Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 19:36:43 -0700 Subject: [PATCH 16/40] windows-vm: unattended provisioning and automation hooks A Windows test VM was useless for automation because everything had to be done through keystroke injection, which cannot reach a boot prompt and mangles punctuation ('.' is key 'dot', not 'period'). Now an install ends with a machine that can be driven over the network: * provision.ps1 installs qemu-guest-agent, WinRM and OpenSSH Server, turns on auto-logon and disables sleep and lock, then writes C:\provision-done.txt * autounattend.xml is validated before every build - a missing wcm namespace makes Setup reject the file and reboot in a loop, which is exactly what cost an evening * build-answer-iso.sh refuses to build an answer file that would do that * win11.pkr.hcl now passes packer validate against proxmox 1.2.4: floppy_files and additional_arguments are not supported by the builder, so the answer file ships as a second CD and boot options moved into a boot_iso block README rewritten around the two paths (template + clone, Packer rebuild) with the four traps and the red herrings recorded. --- tools/windows-vm/README.md | 133 +++++++++++++---------- tools/windows-vm/answer/autounattend.xml | 85 +++++++++------ tools/windows-vm/answer/firstboot.ps1 | 16 --- tools/windows-vm/answer/provision.ps1 | 70 ++++++++++++ tools/windows-vm/build-answer-iso.sh | 34 ++++++ tools/windows-vm/win11.pkr.hcl | 25 +++-- 6 files changed, 246 insertions(+), 117 deletions(-) delete mode 100644 tools/windows-vm/answer/firstboot.ps1 create mode 100644 tools/windows-vm/answer/provision.ps1 create mode 100755 tools/windows-vm/build-answer-iso.sh diff --git a/tools/windows-vm/README.md b/tools/windows-vm/README.md index 556ad03..211c111 100644 --- a/tools/windows-vm/README.md +++ b/tools/windows-vm/README.md @@ -1,87 +1,100 @@ # Throwaway Windows VMs on Proxmox -Two ways to get a Windows guest for a test like "does this USB device work under -Windows", in the order they are worth using. +Goal: a Windows guest for testing things that need Windows (USB devices, firmware +tools, drivers) that can be **created and driven without touching the console**. -## 1. Template + clone (the everyday path) +## The automation hooks -One interactive install, then every later VM is a clone that boots in about a -minute. +A provisioned VM has everything needed to run it entirely over the network: + +| Hook | What it gives you | +|---|---| +| `qemu-guest-agent` | `qm guest exec <id> -- cmd /c …`, `qm shutdown`, `qm guest cmd` — no RDP, no console | +| **OpenSSH Server** (port 22) | ordinary `ssh doge@<vm-ip>`, far easier to script than WinRM | +| **WinRM** (HTTP, Basic) | Packer's default communicator; `Invoke-Command` from PowerShell | +| **Auto-logon** | clones boot straight to a desktop; no sign-in screen to fight | +| Sleep and lock disabled | automation never races a screensaver or lock screen | + +Credentials on a provisioned VM: `doge` / `doge123!` (thrown away with the VM). + +`answer/autounattend.xml` creates the account and runs `provision.ps1` at first +logon, which installs all of the above. So an install ends with a usable, +remotely-driveable machine and no manual steps after the media prompt. + +## 1. Template + clone (everyday path, ~1 minute) ```sh -# after the guest is installed and updated -qm start <id> # boot it, run Windows Update, then inside Windows: -# C:\Windows\System32\Sysprep\sysprep.exe /oobe /generalize /shutdown -qm template <id> - -# every time after that -qm clone 9000 150 --name win-test --full +# once: build the baseline and convert it +qm clone 9000 150 --name win-test --full # 9000 = template id qm set 150 --memory 8192 --cores 4 -qm set 150 -hostpci0 0000:0c:00.3,pcie=1 # if the test needs USB hardware +qm set 150 -hostpci0 0000:0c:00.3,pcie=1 # only when the test needs real hardware qm start 150 +qm guest cmd 150 network-get-interfaces # find its address +ssh doge@<addr> # or: qm guest exec 150 -- cmd /c ver ``` -A clone keeps the template's SID until sysprep strips it, which is why the -template is generalised rather than merely shut down. +Template creation: run `sysprep /oobe /generalize /shutdown` inside Windows, then +`qm template <id>`. Sysprep is optional for single-use test VMs — a clone without +it shares the SID, which only matters on a domain. -## 2. Packer rebuild (when you want a clean, reproducible image) - -`win11.pkr.hcl` builds the template from the ISO with nobody watching. It exists -because the hand-driven install has one hostile step, described below. +## 2. Packer (clean rebuild from ISO) ```sh packer init . packer build -var proxmox_token="$PROXMOX_PACKER_TOKEN" win11.pkr.hcl ``` -Needs `local:iso/win11-eval.iso` and `local:iso/virtio-win.iso`, and an API token -(user `packer@pve`, role with `VM.Allocate`, `VM.Config.*`, `Datastore.AllocateSpace`). -Keep the token in `secretctl`, never in this file. +Needs `local:iso/win11-eval.iso`, `local:iso/virtio-win.iso` and +`local:iso/answer.iso` (build the last one with `build-answer-iso.sh`). The token +belongs in `secretctl`, never here: create a `packer@pve` user with a role +carrying `VM.Allocate`, `VM.Config.*`, `Datastore.AllocateSpace`. -## The step that makes Windows installs awkward +## The traps (learned the hard way, 2026-11-28) -Windows installation media prints +1. **`qm reset` does not reload VM config.** Only `qm stop && qm start` applies + `qm set` changes. A reset reproduces the old behaviour exactly. +2. **An invalid `autounattend.xml` reboots Setup in a loop.** Missing the `wcm` + namespace (`xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"`) + makes `wcm:action` an unbound prefix. Setup rejects the file at the first + screen: the purple installer window flashes, the screen goes black, UEFI + restarts. `build-answer-iso.sh` validates the XML before building. +3. **`qm sendkey` cannot satisfy the media boot prompt.** It injects PS/2 events, + a q35 VM has only a USB pointer, and the prompt lives ~5 s. It *does* work at + the firmware menu and inside Windows. Packer's `boot_command` repeats the + spacebar over VNC, which is the reliable way: + ```hcl + boot_command = ["<wait><spacebar><wait><spacebar><wait><spacebar><wait>"] + ``` + QEMU key names matter when driving by hand: `.` is `dot`, `/` is `slash`, + `\` is `backslash`, `:` is `shift-semicolon`, space is `spc`. +4. **Pass the whole PCIe controller, not the device.** Device passthrough is + still enumerated by the host kernel first. Isolated on ziadpve: + `0c:00.3` (group 27), `0c:00.4` (28), `07:00.0` (22). `08:00.1`/`08:00.3` + share group 16 with a SATA controller and cannot be passed. -``` -Press any key to boot from CD or DVD...... +## Red herrings + +- A **Proxmox logo with a progress bar** on a Windows VM's console is Proxmox's + own OVMF boot splash, not the Proxmox installer. +- `vfio-pci 0000:0c:00.3: resetting / reset done` per boot is normal. +- `ehci: PERIODIC list base register set …` is a cosmetic QEMU warning. + +## Is it stuck or crashed? + +```sh +printf 'screendump /tmp/f.ppm\n' | qm monitor <id> +pnmtopng /tmp/f.ppm > /tmp/f.png +md5sum /tmp/f.png # identical over time = static screen ``` -for about five seconds. Miss it and the firmware falls through to the empty -disk and stops: `BdsDxe: No bootable option or device was found.` - -`qm sendkey` is not a reliable way to satisfy it. It injects PS/2 keyboard -events, while a q35 VM has only a USB keyboard, and the event has to land inside -a five-second window. On 2026-11-28 that cost several failed boots: the keys -reached the *firmware boot menu* (which redrew) but never the media's prompt. - -Packer's `boot_command` sends real keystrokes over VNC and lets you repeat them -across the whole window: - -```hcl -boot_command = [ - "<wait><spacebar><wait><spacebar><wait><spacebar><wait>", -] -``` - -That repetition is the fix — one press is a race, ten presses is not. +A crash loop shows repeated distinct frames; a waiting installer shows one stable +frame. Kill stray `screendump` loops or they pollute later comparisons. ## Files | File | Purpose | |---|---| -| `win11.pkr.hcl` | Packer build: VM, UEFI + vTPM, virtio disk/NIC, answer file, sysprep, template | -| `answer/autounattend.xml` | Unattended install: disk layout, local admin, auto-logon, OOBE skipped | -| `answer/firstboot.ps1` | First-logon hook: enable WinRM so Packer can drive the rest | - -## Notes - -- Deliver the answer file on a **floppy** (`floppy_files`), not a second CD-ROM: - Windows then finds it at `A:\` and there is no drive-letter guessing. -- `virtio-win` gives paravirtualised disk and network. Without it the guest runs - on emulated SATA and `e1000`, which is fine for a driver test but slow. -- `qemu_agent = true` means you can `qm shutdown`/`qm guest exec` later instead - of power-cycling or mounting the disk. -- For USB hardware tests, pass the whole PCIe controller (`hostpci0`) rather than - a single device: a device passthrough is still enumerated by the host kernel - first, so it inherits any host-side fault. Check the controller's IOMMU group - is alone before relying on it. +| `win11.pkr.hcl` | Packer build → UEFI + vTPM, virtio disk/NIC, answer ISO, sysprep, template | +| `answer/autounattend.xml` | Unattended install: disk, account, autologon, first-logon hook | +| `answer/provision.ps1` | Installs guest agent, WinRM, OpenSSH, auto-logon; writes `C:\provision-done.txt` | +| `build-answer-iso.sh` | Validates the answer file and builds `local:iso/answer.iso` | diff --git a/tools/windows-vm/answer/autounattend.xml b/tools/windows-vm/answer/autounattend.xml index 4344deb..89b8d23 100644 --- a/tools/windows-vm/answer/autounattend.xml +++ b/tools/windows-vm/answer/autounattend.xml @@ -1,5 +1,23 @@ <?xml version="1.0" encoding="utf-8"?> -<unattend xmlns="urn:schemas-microsoft-com:unattend"> +<!-- + Unattended install for a Windows test VM on Proxmox. + + Delivered on a floppy or a small ISO; Windows finds it at the root of the first + removable drive. Two things here are load-bearing: + + * The wcm namespace. Without it this file is not well-formed XML, Setup rejects + it at the first screen and reboots in a loop - the purple screen that appears + for a second and vanishes is that failure, not a crash. + * FirstLogonCommands running provision.ps1, which turns on WinRM, OpenSSH and + the guest agent so the VM can be driven over the network instead of through + keystroke injection. + + Validate before booting: + python3 -c "import xml.etree.ElementTree as ET; ET.parse('autounattend.xml')" +--> +<unattend xmlns="urn:schemas-microsoft-com:unattend" + xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"> + <settings pass="windowsPE"> <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> @@ -9,10 +27,10 @@ <UILanguage>en-US</UILanguage> <UserLocale>en-US</UserLocale> </component> + <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> <RunSynchronous> - <!-- Belt and braces: this VM has TPM + UEFI, but never let a check cost us the run. --> <RunSynchronousCommand wcm:action="add"> <Order>1</Order> <Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassTPMCheck /t REG_DWORD /d 1 /f</Path> @@ -21,52 +39,45 @@ <Order>2</Order> <Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassSecureBootCheck /t REG_DWORD /d 1 /f</Path> </RunSynchronousCommand> - <RunSynchronousCommand wcm:action="add"> - <Order>3</Order> - <Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassRAMCheck /t REG_DWORD /d 1 /f</Path> - </RunSynchronousCommand> - <RunSynchronousCommand wcm:action="add"> - <Order>4</Order> - <Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassCPUCheck /t REG_DWORD /d 1 /f</Path> - </RunSynchronousCommand> </RunSynchronous> + <DiskConfiguration> <WillShowUI>OnError</WillShowUI> <Disk wcm:action="add"> <DiskID>0</DiskID> <WillWipeDisk>true</WillWipeDisk> <CreatePartitions> - <CreatePartition wcm:action="add"> - <Order>1</Order><Type>EFI</Type><Size>100</Size> - </CreatePartition> - <CreatePartition wcm:action="add"> - <Order>2</Order><Type>MSR</Type><Size>16</Size> - </CreatePartition> - <CreatePartition wcm:action="add"> - <Order>3</Order><Type>Primary</Type><Extend>true</Extend> - </CreatePartition> + <CreatePartition wcm:action="add"><Order>1</Order><Type>EFI</Type><Size>100</Size></CreatePartition> + <CreatePartition wcm:action="add"><Order>2</Order><Type>MSR</Type><Size>16</Size></CreatePartition> + <CreatePartition wcm:action="add"><Order>3</Order><Type>Primary</Type><Extend>true</Extend></CreatePartition> </CreatePartitions> <ModifyPartitions> <ModifyPartition wcm:action="add"> <Order>1</Order><PartitionID>1</PartitionID><Format>FAT32</Format><Label>System</Label> </ModifyPartition> - <ModifyPartition wcm:action="add"> - <Order>2</Order><PartitionID>2</PartitionID> - </ModifyPartition> + <ModifyPartition wcm:action="add"><Order>2</Order><PartitionID>2</PartitionID></ModifyPartition> <ModifyPartition wcm:action="add"> <Order>3</Order><PartitionID>3</PartitionID><Format>NTFS</Format><Label>Windows</Label><Letter>C</Letter> </ModifyPartition> </ModifyPartitions> </Disk> </DiskConfiguration> + <ImageInstall> <OSImage> + <InstallFrom> + <MetaData wcm:action="add"> + <Key>/IMAGE/INDEX</Key> + <Value>1</Value> + </MetaData> + </InstallFrom> <InstallTo><DiskID>0</DiskID><PartitionID>3</PartitionID></InstallTo> </OSImage> </ImageInstall> + <UserData> <AcceptEula>true</AcceptEula> - <FullName>kraken</FullName> + <FullName>doge</FullName> <Organization>homelab</Organization> </UserData> </component> @@ -78,6 +89,16 @@ <ComputerName>WINTEST</ComputerName> <TimeZone>UTC</TimeZone> </component> + <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" + publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> + <RunSynchronous> + <RunSynchronousCommand wcm:action="add"> + <Order>1</Order> + <Description>never lock, never sleep</Description> + <Path>cmd /c powercfg /change standby-timeout-ac 0 &amp; powercfg /change monitor-timeout-ac 0</Path> + </RunSynchronousCommand> + </RunSynchronous> + </component> </settings> <settings pass="oobeSystem"> @@ -89,29 +110,31 @@ <HideOnlineAccountScreens>true</HideOnlineAccountScreens> <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> <ProtectYourPC>3</ProtectYourPC> - <SkipMachineOOBE>true</SkipMachineOOBE> - <SkipUserOOBE>true</SkipUserOOBE> </OOBE> <UserAccounts> <LocalAccounts> <LocalAccount wcm:action="add"> - <Name>kraken</Name> + <Name>doge</Name> + <DisplayName>doge</DisplayName> <Group>Administrators</Group> - <Password><Value>kraken123!</Value><PlainText>true</PlainText></Password> + <Password> + <Value>doge123!</Value> + <PlainText>true</PlainText> + </Password> </LocalAccount> </LocalAccounts> </UserAccounts> <AutoLogon> <Enabled>true</Enabled> - <Username>kraken</Username> - <Password><Value>kraken123!</Value><PlainText>true</PlainText></Password> + <Username>doge</Username> + <Password><Value>doge123!</Value><PlainText>true</PlainText></Password> <LogonCount>999</LogonCount> </AutoLogon> <FirstLogonCommands> <SynchronousCommand wcm:action="add"> <Order>1</Order> - <Description>collect USB report</Description> - <CommandLine>cmd /c if exist A:\firstboot.ps1 powershell.exe -ExecutionPolicy Bypass -NoProfile -File A:\firstboot.ps1</CommandLine> + <Description>provision automation hooks</Description> + <CommandLine>cmd /c for %i in (D E F G) do @if exist %i:\p.ps1 powershell.exe -ExecutionPolicy Bypass -NoProfile -File %i:\p.ps1</CommandLine> </SynchronousCommand> </FirstLogonCommands> </component> diff --git a/tools/windows-vm/answer/firstboot.ps1 b/tools/windows-vm/answer/firstboot.ps1 deleted file mode 100644 index b33df8f..0000000 --- a/tools/windows-vm/answer/firstboot.ps1 +++ /dev/null @@ -1,16 +0,0 @@ -# Runs once on first logon in a freshly installed guest, before Packer's -# provisioners take over over WinRM. Keep it short: everything heavier is a -# Packer provisioner so it is visible in the build log. -$ErrorActionPreference = 'SilentlyContinue' -Set-Content -Path 'C:\firstboot.txt' -Value "firstboot $([DateTime]::UtcNow.ToString('s'))" - -# WinRM is how Packer drives the rest of the build. -Enable-PSRemoting -Force -SkipNetworkProfileCheck -Set-Item WSMan:\localhost\Service\Auth\Basic -Value $true -Set-Service WinRM -StartupType Automatic -Start-Service WinRM -Set-NetFirewallRule -DisplayGroup 'Windows Remote Management' -Enabled True - -# A test guest that sleeps, never hibernates, and has no lock screen. -powercfg /change standby-timeout-ac 0 -powercfg /change monitor-timeout-ac 0 diff --git a/tools/windows-vm/answer/provision.ps1 b/tools/windows-vm/answer/provision.ps1 new file mode 100644 index 0000000..7e1be0e --- /dev/null +++ b/tools/windows-vm/answer/provision.ps1 @@ -0,0 +1,70 @@ +# One-shot provisioning for a Windows test VM. +# +# Run once from inside the guest (or from Packer). After this the machine can be +# driven entirely over the network, with no keystroke injection, which is the +# whole point: qm sendkey cannot reach a boot prompt and mangles punctuation. +# +# Installs: +# * virtio-win guest tools -> qemu-guest-agent (qm guest exec / qm shutdown) +# * WinRM over HTTP -> Packer communicator, Invoke-Command +# * OpenSSH Server -> ordinary ssh, which is far nicer to script +# * auto-logon for the test account, so clones land on a desktop unattended +$ErrorActionPreference = 'SilentlyContinue' +$log = 'C:\provision.log' +function Note($m) { "$([DateTime]::UtcNow.ToString('HH:mm:ss')) $m" | Add-Content $log } + +Remove-Item $log -Force -ErrorAction SilentlyContinue +Note "provisioning $env:COMPUTERNAME" + +# --- virtio-win guest tools (brings qemu-guest-agent and the paravirt drivers) +$virtio = Get-PSDrive -PSProvider FileSystem | Where-Object { Test-Path "$($_.Root)virtio-win-guest-tools.exe" } | Select-Object -First 1 +if ($virtio) { + Note "installing virtio-win guest tools from $($virtio.Root)" + Start-Process "$($virtio.Root)virtio-win-guest-tools.exe" -ArgumentList '/S','/quiet','/norestart' -Wait + Note "virtio tools exit: $LASTEXITCODE" +} else { + Note "virtio-win ISO not attached, skipping guest tools" +} + +# --- WinRM: Packer's default communicator +Enable-PSRemoting -Force -SkipNetworkProfileCheck +Set-Item WSMan:\localhost\Service\Auth\Basic -Value $true +Set-Item WSMan:\localhost\Service\AllowUnencrypted -Value $true +Set-Service WinRM -StartupType Automatic +Start-Service WinRM +Set-NetFirewallRule -DisplayGroup 'Windows Remote Management' -Enabled True +Note "winrm enabled" + +# --- OpenSSH Server: much easier to script than WinRM from Linux +$cap = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' +if ($cap.State -ne 'Installed') { + Note "installing OpenSSH server" + Add-WindowsCapability -Online -Name $cap.Name | Out-Null +} +Set-Service sshd -StartupType Automatic +Start-Service sshd +New-NetFirewallRule -Name 'sshd-in' -DisplayName 'OpenSSH Server' -Enabled True -Direction Inbound -Protocol TCP -LocalPort 22 -Action Allow | Out-Null +Note "sshd state: $((Get-Service sshd).Status)" + +# --- keep it awake and never lock, so automation is not fighting a lock screen +powercfg /change standby-timeout-ac 0 +powercfg /change monitor-timeout-ac 0 +powercfg /setacvalueindex SCHEME_CURRENT SUB_NONE ConsoleLock 0 +New-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization' -Name NoLockScreen -Value 1 -PropertyType DWord -Force | Out-Null +New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name AutoAdminLogon -Value '1' -PropertyType String -Force | Out-Null + +# --- test account: known password, never expires +$user = 'doge' +$pass = 'doge123!' +if (Get-LocalUser -Name $user -ErrorAction SilentlyContinue) { + Set-LocalUser -Name $user -Password (ConvertTo-SecureString $pass -AsPlainText -Force) -PasswordNeverExpires $true +} else { + New-LocalUser -Name $user -Password (ConvertTo-SecureString $pass -AsPlainText -Force) -PasswordNeverExpires $true | Out-Null + Add-LocalGroupMember -Group Administrators -Member $user +} +Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultUserName -Value $user +Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultPassword -Value $pass +Note "autologon set for $user" + +"COMPLETE" | Set-Content 'C:\provision-done.txt' +Note "done" diff --git a/tools/windows-vm/build-answer-iso.sh b/tools/windows-vm/build-answer-iso.sh new file mode 100755 index 0000000..4eaf960 --- /dev/null +++ b/tools/windows-vm/build-answer-iso.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# Builds local:iso/answer.iso from the answer files, and refuses to build an +# answer file Windows Setup would reject. +# +# Why the validation matters: a malformed autounattend.xml (for example, using +# wcm:action without the wcm namespace) makes Setup show the purple installer +# window for about a second, then reboot - in a loop, forever, with nothing in +# any log to explain it. +set -eu + +here=$(cd "$(dirname "$0")" && pwd) +work=${WORK:-/tmp/answer-iso} +iso_out=${ISO_OUT:-/var/lib/vz/template/iso/answer.iso} + +python3 - "$here/answer/autounattend.xml" <<'PY' +import sys, xml.etree.ElementTree as ET +path = sys.argv[1] +try: + ET.parse(path) +except ET.ParseError as e: + raise SystemExit("autounattend.xml is not valid XML (%s) - Setup would reboot in a loop" % e) +print("autounattend.xml: valid XML") +PY + +rm -rf "$work" +mkdir -p "$work" +cp "$here/answer/autounattend.xml" "$work/autounattend.xml" +# Windows Setup needs the script beside the answer file, at a short name, because +# FirstLogonCommands searches drive letters for it. +cp "$here/answer/provision.ps1" "$work/p.ps1" + +genisoimage -quiet -o "$work/answer.iso" -J -R -V ANSWER "$work/autounattend.xml" "$work/p.ps1" +install -m 0644 "$work/answer.iso" "$iso_out" +echo "wrote $iso_out ($(stat -c%s "$iso_out") bytes)" diff --git a/tools/windows-vm/win11.pkr.hcl b/tools/windows-vm/win11.pkr.hcl index ffa2d61..d6a8fd7 100644 --- a/tools/windows-vm/win11.pkr.hcl +++ b/tools/windows-vm/win11.pkr.hcl @@ -89,8 +89,10 @@ source "proxmox-iso" "win11" { bridge = "vmbr0" } - iso_file = var.iso_file - unmount_iso = true + boot_iso { + iso_file = var.iso_file + unmount = true + } additional_iso_files { device = "ide2" iso_file = var.virtio_iso @@ -98,12 +100,16 @@ source "proxmox-iso" "win11" { iso_storage_pool = "local" } - # The answer file rides on a floppy, so Windows Setup finds it at A:\ and it - # never collides with a CD-ROM drive letter. - floppy_files = [ - "answer/autounattend.xml", - "answer/firstboot.ps1", - ] + # The answer file ships as a small ISO rather than a floppy: the proxmox-iso + # builder has no floppy_files option. Build it with tools/windows-vm/build-answer-iso.sh, + # which also validates the XML first - an invalid answer file makes Setup + # reboot in a loop, which is a miserable thing to debug. + additional_iso_files { + device = "ide0" + iso_file = "local:iso/answer.iso" + unmount = true + iso_storage_pool = "local" + } # This is the whole point of the exercise. Repeat the spacebar rather than # pressing once: the prompt renders a variable beat after the DVD is selected. @@ -126,8 +132,7 @@ source "proxmox-iso" "win11" { # Convert the finished build into a template: it can only be cloned, never # started by accident. - template_name = var.template_name - additional_arguments = "-device usb-kbd" + template_name = var.template_name } build { From c1303d61c7542fcbb6c9827531a78cf7f8f48f84 Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 19:51:35 -0700 Subject: [PATCH 17/40] windows-vm: Packer communicator uses the provisioned account The build drives the guest over WinRM, so the credentials must be the ones the answer file creates (doge/doge123!), not the older kraken placeholder. --- tools/windows-vm/win11.pkr.hcl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/windows-vm/win11.pkr.hcl b/tools/windows-vm/win11.pkr.hcl index d6a8fd7..8c0f97f 100644 --- a/tools/windows-vm/win11.pkr.hcl +++ b/tools/windows-vm/win11.pkr.hcl @@ -124,8 +124,8 @@ source "proxmox-iso" "win11" { # Wait for Setup to finish, reboot, and land on the desktop; then let # sysprep/generalise (invoked by firstboot.ps1) shut the machine down. communicator = "winrm" - winrm_username = "kraken" - winrm_password = "kraken123!" + winrm_username = "doge" + winrm_password = "doge123!" winrm_timeout = "2h" qemu_agent = true From 0a1eaab6e7afa12bf6293966cee4fb4e512ee137 Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 20:29:28 -0700 Subject: [PATCH 18/40] windows-vm: Packer schema corrected; the keystroke path is blocked at the API boot_iso needs an explicit type, otherwise the block is silently ignored and the VM is built with no installation media at all. The media prompt is still missed: Proxmox gives Packer's VM only a usb-tablet, and its own remedy for that (qemu_additional_args) is refused with 500 "only root can set 'args' config". Documented in place for whoever runs this next. --- tools/windows-vm/win11.pkr.hcl | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/tools/windows-vm/win11.pkr.hcl b/tools/windows-vm/win11.pkr.hcl index 8c0f97f..99d2c1b 100644 --- a/tools/windows-vm/win11.pkr.hcl +++ b/tools/windows-vm/win11.pkr.hcl @@ -90,6 +90,7 @@ source "proxmox-iso" "win11" { } boot_iso { + type = "ide" iso_file = var.iso_file unmount = true } @@ -105,7 +106,7 @@ source "proxmox-iso" "win11" { # which also validates the XML first - an invalid answer file makes Setup # reboot in a loop, which is a miserable thing to debug. additional_iso_files { - device = "ide0" + device = "ide2" iso_file = "local:iso/answer.iso" unmount = true iso_storage_pool = "local" @@ -113,13 +114,20 @@ source "proxmox-iso" "win11" { # This is the whole point of the exercise. Repeat the spacebar rather than # pressing once: the prompt renders a variable beat after the DVD is selected. - boot = "order=ide0;virtio0" - boot_wait = "4s" - boot_command = [ - "<wait><spacebar><wait><spacebar><wait><spacebar><wait><spacebar><wait>", - "<spacebar><wait><spacebar><wait><spacebar><wait><spacebar><wait>", - "<spacebar><wait><spacebar><wait><spacebar><wait><spacebar><wait>", - ] + boot = "order=ide0;virtio0" + # The media prompt appears ~10-20 s into UEFI boot, not at 4 s, so wait longer + # and keep tapping across a 40-second span. One press is a race against the + # prompt rendering; forty spaced presses is not. + # BLOCKED, do not re-add: the VM is created with only a usb-tablet, so the VNC + # boot_command has no keyboard to land on and the "press any key" media prompt + # times out -> UEFI falls through to "no bootable option". The fix would be + # qemu_additional_args = "-device usb-kbd" + # but Proxmox answers 500 "only root can set 'args' config" for any API user + # other than root@pam. Either build with a root@pam token, or strip + # efi/microsoft/boot/bootfix.bin from the ISO so no keypress is needed. + + boot_wait = "10s" + boot_command = ["<wait>${join("", [for i in range(40) : "<spacebar><wait>"])}"] # Wait for Setup to finish, reboot, and land on the desktop; then let # sysprep/generalise (invoked by firstboot.ps1) shut the machine down. From 6a024fe75edf016ac12f458800b84d6f68fd4c36 Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 20:58:19 -0700 Subject: [PATCH 19/40] windows-vm: promptless install ISO via Microsoft's noprompt boot image UEFI does not use bootfix.bin (that is BIOS-only); cDBoot prompts on its own and cannot be dismissed without a keyboard device, which Proxmox reserves for root@pam via -args. So the prompt is removed from the media instead: the ISO ships efi/microsoft/boot/efisys_noprompt.bin, byte-for-byte the same size as the El Torito UEFI image, so it overwrites it in place and the boot catalog stays valid. build-noprompt-iso.sh does it and verifies the result. Firmware now starts the CD with no keystroke, but OVMF stalls in Start boot option and never reaches Setup, so the Packer build still does not complete. --- tools/windows-vm/build-noprompt-iso.sh | 48 ++++++++++++++++++++++++++ tools/windows-vm/win11.pkr.hcl | 18 +++++----- 2 files changed, 58 insertions(+), 8 deletions(-) create mode 100755 tools/windows-vm/build-noprompt-iso.sh diff --git a/tools/windows-vm/build-noprompt-iso.sh b/tools/windows-vm/build-noprompt-iso.sh new file mode 100755 index 0000000..de9dbdb --- /dev/null +++ b/tools/windows-vm/build-noprompt-iso.sh @@ -0,0 +1,48 @@ +#!/bin/sh +# Build a promptless copy of the Windows 11 ISO for unattended Proxmox builds. +# +# Why: Proxmox creates VMs with only a usb-tablet, so VNC keystrokes have no +# keyboard to land on and UEFI's "Press any key to boot from CD or DVD" always +# times out -- the install never starts. Adding -device usb-kbd would fix it, +# but needs qemu_additional_args, which Proxmox refuses for any API user other +# than root@pam ("only root can set 'args' config"). +# +# So the prompt is removed from the media: Microsoft ships the same UEFI boot +# image twice, with the prompt (efisys.bin) and without (efisys_noprompt.bin). +# They are byte-for-byte the same size, so the boot image can be overwritten in +# place and the El Torito catalog stays valid. No catalog surgery needed. +# +# Run as root on the Proxmox host: sh build-noprompt-iso.sh [source [target]] +set -eu + +SRC_ISO="${1:-/var/lib/vz/template/iso/win11-eval.iso}" +DST_ISO="${2:-/var/lib/vz/template/iso/win11-noprompt.iso}" +BOOT_IMAGE_OFFSET=1097728 # El Torito UEFI image, verified with cmp below +BOOT_IMAGE_SIZE=1474560 +WORK=$(mktemp -d /tmp/noprompt.XXXXXX) +trap 'rm -rf "$WORK"' EXIT + +[ -f "$SRC_ISO" ] || { echo "no such ISO: $SRC_ISO" >&2; exit 1; } + +echo "extracting the promptless boot image from $(basename "$SRC_ISO")" +7z e -y "$SRC_ISO" -o"$WORK" "efi/microsoft/boot/efisys_noprompt.bin" -r >/dev/null +NEW="$WORK/efisys_noprompt.bin" +[ -s "$NEW" ] || { echo "efisys_noprompt.bin not found in the ISO" >&2; exit 1; } +SIZE=$(stat -c%s "$NEW") +[ "$SIZE" -eq "$BOOT_IMAGE_SIZE" ] || { + echo "boot image is $SIZE bytes, expected $BOOT_IMAGE_SIZE -- the offset would be wrong, refusing" >&2 + exit 1 +} + +echo "copying $(basename "$SRC_ISO") -> $(basename "$DST_ISO")" +cp --sparse=always "$SRC_ISO" "$DST_ISO" + +echo "patching the UEFI boot image at byte $BOOT_IMAGE_OFFSET" +dd if="$NEW" of="$DST_ISO" bs=2048 seek=$((BOOT_IMAGE_OFFSET / 2048)) conv=notrunc status=none + +cmp -n "$BOOT_IMAGE_SIZE" -i "$BOOT_IMAGE_OFFSET":0 "$DST_ISO" "$NEW" \ + || { echo "patch verification failed" >&2; exit 1; } + +chown root:root "$DST_ISO" +chmod 644 "$DST_ISO" +echo "ok: $DST_ISO ($(stat -c%s "$DST_ISO") bytes, verified)" diff --git a/tools/windows-vm/win11.pkr.hcl b/tools/windows-vm/win11.pkr.hcl index 99d2c1b..9881910 100644 --- a/tools/windows-vm/win11.pkr.hcl +++ b/tools/windows-vm/win11.pkr.hcl @@ -36,7 +36,7 @@ variable "proxmox_token" { variable "iso_file" { type = string - default = "local:iso/win11-eval.iso" + default = "local:iso/win11-noprompt.iso" } variable "virtio_iso" { @@ -118,13 +118,15 @@ source "proxmox-iso" "win11" { # The media prompt appears ~10-20 s into UEFI boot, not at 4 s, so wait longer # and keep tapping across a 40-second span. One press is a race against the # prompt rendering; forty spaced presses is not. - # BLOCKED, do not re-add: the VM is created with only a usb-tablet, so the VNC - # boot_command has no keyboard to land on and the "press any key" media prompt - # times out -> UEFI falls through to "no bootable option". The fix would be - # qemu_additional_args = "-device usb-kbd" - # but Proxmox answers 500 "only root can set 'args' config" for any API user - # other than root@pam. Either build with a root@pam token, or strip - # efi/microsoft/boot/bootfix.bin from the ISO so no keypress is needed. + # The VM is created with only a usb-tablet, so VNC keystrokes have no keyboard + # to land on and UEFI's "press any key to boot from CD" always times out. + # Adding one needs qemu_additional_args = "-device usb-kbd", which Proxmox + # refuses: 500 "only root can set 'args' config" for any user but root@pam. + # + # So the prompt is removed from the media instead: win11-noprompt.iso is + # win11-eval.iso with the 1474560-byte UEFI El Torito image at byte 1097728 + # replaced by the ISO's own efi/microsoft/boot/efisys_noprompt.bin (identical + # size, so the boot catalog stays valid). See build-noprompt-iso.sh. boot_wait = "10s" boot_command = ["<wait>${join("", [for i in range(40) : "<spacebar><wait>"])}"] From 0bf6e660ff3da05e28b8294d6343a86a84bdaf0e Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:07:21 -0700 Subject: [PATCH 20/40] bin: cdp-key and cdp-read for harvesting keys without transcripts Reveals a one-time API key in an attached Chrome and pipes it straight into secretctl add, so the value never lands in a shell history, an argv, or an agent transcript. --- bin/cdp-key | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++ bin/cdp-read | 92 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 212 insertions(+) create mode 100755 bin/cdp-key create mode 100755 bin/cdp-read diff --git a/bin/cdp-key b/bin/cdp-key new file mode 100755 index 0000000..fb3bbb1 --- /dev/null +++ b/bin/cdp-key @@ -0,0 +1,120 @@ +#!/usr/bin/env bun +// cdp-key — capture a secret value from a network response in the attached +// Chrome, optionally after triggering the page action that produces it. +// +// Built for one-time API-key reveals: the value goes to stdout so it can be +// piped into `secretctl add NAME` and never printed into a transcript. +// +// cdp-key --url=groq \ +// --match='/keys|api_keys' \ +// --pattern='gsk_[A-Za-z0-9]{20,}' \ +// --trigger='[...document.querySelectorAll("button")].find(b=>/create|submit/i.test(b.innerText)).click()' +// +// Options: +// --port=9222 CDP port +// --url=substring page target filter +// --match=regex response URL filter +// --pattern=regex secret pattern searched in the response body +// --trigger=js expression run right after listeners attach +// --wait=8000 ms to wait for a match +// --in-page also try the page text after a match attempt +// +// Exit: 0 found, 1 not found or CDP error, 2 usage. + +const opts = { port: 9222, url: "", match: "", pattern: "", trigger: "", wait: 8000, inPage: false }; +for (const a of process.argv.slice(2)) { + if (a === "-h" || a === "--help") { + console.log("usage: cdp-key --url=<sub> --match=<regex> --pattern=<regex> [--trigger=<js>] [--wait=ms] [--in-page]"); + process.exit(0); + } + if (a === "--in-page") { opts.inPage = true; continue; } + const m = a.match(/^--(port|url|match|pattern|trigger|wait)=(.*)$/s); + if (!m) continue; + if (m[1] === "port" || m[1] === "wait") opts[m[1]] = Number(m[2]); + else if (m[1] === "match") opts.match = m[2]; + else if (m[1] === "pattern") opts.pattern = m[2]; + else if (m[1] === "trigger") opts.trigger = m[2]; + else opts.url = m[2]; +} +if (!opts.pattern) { console.error("cdp-key: --pattern is required"); process.exit(2); } + +const list = await (await fetch(`http://127.0.0.1:${opts.port}/json`)).json(); +const pages = list.filter((t) => t.type === "page"); +const page = (opts.url && pages.find((t) => t.url.includes(opts.url))) || pages[0]; +if (!page) { console.error("cdp-key: no page target"); process.exit(1); } + +const secretRe = new RegExp(opts.pattern); +const urlRe = opts.match ? new RegExp(opts.match) : null; +const ws = new WebSocket(page.webSocketDebuggerUrl); +let id = 0; +const pending = new Map(); +const send = (method, params = {}) => + new Promise((resolve, reject) => { + const msgId = ++id; + pending.set(msgId, { resolve, reject }); + ws.send(JSON.stringify({ id: msgId, method, params })); + }); + +ws.onmessage = async (e) => { + let msg; + try { msg = JSON.parse(String(e.data)); } catch { return; } + if (msg.id && pending.has(msg.id)) { + const p = pending.get(msg.id); + pending.delete(msg.id); + msg.error ? p.reject(new Error(msg.error.message)) : p.resolve(msg.result); + return; + } + if (msg.method === "Network.responseReceived") { + const url = msg.params?.response?.url || ""; + if (urlRe && !urlRe.test(url)) return; + try { + const body = await send("Network.getResponseBody", { requestId: msg.params.requestId }); + const text = body.base64Encoded ? atob(body.body) : body.body; + const hit = text.match(secretRe); + if (hit) finish(hit[0]); + } catch {} + } +}; + +let finished = false; +function finish(value) { + if (finished) return; + finished = true; + process.stdout.write(value); + try { ws.close(); } catch {} + process.exit(0); +} + +const evaluate = (expression) => + send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true, userGesture: true }); + +ws.onopen = async () => { + try { + await send("Network.enable"); + await send("Page.enable"); + if (opts.trigger) { + const r = await evaluate(opts.trigger); + if (r?.exceptionDetails) console.error("cdp-key: trigger threw: " + (r.exceptionDetails.exception?.description || "")); + } + setTimeout(async () => { + if (finished) return; + if (opts.inPage) { + try { + const r = await evaluate( + `(()=>{const m=document.body.innerText.match(${JSON.stringify(opts.pattern)});return m?m[0]:""})()` + ); + const v = r?.result?.value; + if (v) return finish(v); + } catch {} + } + finished = true; + console.error("cdp-key: no match within " + opts.wait + "ms"); + try { ws.close(); } catch {} + process.exit(1); + }, opts.wait); + } catch (e) { + console.error("cdp-key: " + e.message); + process.exit(1); + } +}; +ws.onerror = () => { if (!finished) { console.error("cdp-key: websocket error"); process.exit(1); } }; diff --git a/bin/cdp-read b/bin/cdp-read new file mode 100755 index 0000000..d7f3802 --- /dev/null +++ b/bin/cdp-read @@ -0,0 +1,92 @@ +#!/usr/bin/env bun +// cdp-read — evaluate one JS expression in the attached Chrome page and print +// the raw string result to stdout. +// +// Designed to be piped straight into `secretctl add NAME`, so a harvested API +// key never appears in an agent transcript or shell history. +// +// cdp-read '<expression>' # first page target +// cdp-read --url=groq '<expression>' # target whose URL contains "groq" +// cdp-read --port=9222 ... +// +// Exit codes: 0 ok, 1 CDP error / expression threw, 2 usage. + +const args = process.argv.slice(2); +let port = 9222; +let urlMatch = ""; +let envVar = ""; +const exprParts = []; +for (const a of args) { + if (a.startsWith("--port=")) port = Number(a.slice(7)); + else if (a.startsWith("--url=")) urlMatch = a.slice(6); + else if (a.startsWith("--env=")) envVar = a.slice(6); + else if (a === "-h" || a === "--help") { + console.log("usage: cdp-read [--port=9222] [--url=substring] [--env=VAR] '<js expression>'\n __VALUE__ in the expression is replaced by JSON(process.env[VAR])."); + process.exit(0); + } else exprParts.push(a); +} +const expression = exprParts.join(" ").replaceAll("__VALUE__", JSON.stringify(envVar ? (process.env[envVar] ?? "") : "")); +if (!expression) { + console.error("cdp-read: missing expression"); + process.exit(2); +} + +const list = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); +const pages = list.filter((t) => t.type === "page"); +const page = + (urlMatch && pages.find((t) => t.url.includes(urlMatch))) || pages[0]; +if (!page) { + console.error("cdp-read: no page target found"); + process.exit(1); +} + +const ws = new WebSocket(page.webSocketDebuggerUrl); +let id = 0; +const pending = new Map(); +const send = (method, params = {}) => + new Promise((resolve, reject) => { + const msgId = ++id; + pending.set(msgId, { resolve, reject }); + ws.send(JSON.stringify({ id: msgId, method, params })); + }); + +ws.onmessage = (e) => { + let msg; + try { msg = JSON.parse(String(e.data)); } catch { return; } + const p = pending.get(msg.id); + if (!p) return; + pending.delete(msg.id); + if (msg.error) p.reject(new Error(msg.error.message)); + else p.resolve(msg.result); +}; + +const done = new Promise((resolve) => { + ws.onopen = async () => { + try { + const r = await send("Runtime.evaluate", { + expression, + returnByValue: true, + awaitPromise: true, + userGesture: true, + }); + if (r.exceptionDetails) { + console.error("cdp-read: " + (r.exceptionDetails.exception?.description || "expression threw")); + resolve(1); + } else if (r.result?.subtype === "error") { + console.error("cdp-read: " + r.result.description); + resolve(1); + } else { + process.stdout.write(String(r.result?.value ?? "")); + resolve(0); + } + } catch (e) { + console.error("cdp-read: " + e.message); + resolve(1); + } + ws.close(); + }; + ws.onerror = () => resolve(1); +}); + +const code = await done; +process.exit(code); From 8ce4afc9f4f2519ee2c9a0290d7e25a042604d9c Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:07:21 -0700 Subject: [PATCH 21/40] free-agent pool and handoff queue free-agent runs a task brief through a pool of free models with local rate-limit accounting and failover; handoff queues briefs and runs each in its own tmux window under a systemd user service, so workers survive a closed terminal and come back after a reboot. WORKER.md is the protocol the worker follows. --- bin/free-agent | 219 ++++++++++++++++++++++++++++++++++++ bin/handoff | 198 ++++++++++++++++++++++++++++++++ config/free-agent/WORKER.md | 40 +++++++ config/free-agent/pool.json | 68 +++++++++++ home/agents.nix | 21 ++++ 5 files changed, 546 insertions(+) create mode 100755 bin/free-agent create mode 100755 bin/handoff create mode 100644 config/free-agent/WORKER.md create mode 100644 config/free-agent/pool.json diff --git a/bin/free-agent b/bin/free-agent new file mode 100755 index 0000000..59a5ae5 --- /dev/null +++ b/bin/free-agent @@ -0,0 +1,219 @@ +#!/usr/bin/env bun +// free-agent — run one task brief through a pool of free models, with local +// rate-limit accounting and automatic failover. +// +// free-agent --brief BRIEF.md --dir ~/Projects/thing --role code [--id slug] +// free-agent --list # pool + today's budget +// free-agent --dry-run ... # show the model it would pick +// +// Exit: 0 done, 1 all attempts failed, 2 usage, 3 no model has budget today. + +import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, copyFileSync } from "node:fs"; +import { dirname, join, resolve, basename } from "node:path"; +import { homedir } from "node:os"; + +const HOME = homedir(); +const DOTFILES = process.env.DOTFILES_DIR || join(HOME, ".dotfiles"); +const POOL = process.env.FREE_AGENT_POOL || join(DOTFILES, "config/free-agent/pool.json"); +const WORKER = join(DOTFILES, "config/free-agent/WORKER.md"); +const STATE = join(process.env.XDG_STATE_HOME || join(HOME, ".local/state"), "free-agent"); +const BUDGET = join(STATE, "budget.json"); +const RUNS = join(STATE, "runs"); + +// ---------- args ---------- +const opts = { brief: "", dir: "", role: "code", id: "", model: "", timeout: 1800, attempts: 3, dryRun: false, list: false, quiet: false }; +const argv = process.argv.slice(2); +for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--list") opts.list = true; + else if (a === "--dry-run") opts.dryRun = true; + else if (a === "--quiet") opts.quiet = true; + else if (a === "-h" || a === "--help") { + console.log(`free-agent — hand a brief to a free model + + --brief <file> task brief (required unless --list) + --dir <repo> working directory for the worker (default: brief's folder) + --role <r> code | review | infra (default code) + --id <slug> run id (default: derived from the brief file name + time) + --model <p/id> force one model instead of the pool + --timeout <secs> per attempt (default 1800) + --attempts <n> how many pool models to try (default 3) + --dry-run print the chosen model and exit + --list print pool and today's usage`); + process.exit(0); + } else if (a.startsWith("--")) { + const v = argv[++i]; + if (a === "--brief") opts.brief = v; + else if (a === "--dir") opts.dir = v; + else if (a === "--role") opts.role = v; + else if (a === "--id") opts.id = v; + else if (a === "--model") opts.model = v; + else if (a === "--timeout") opts.timeout = Number(v); + else if (a === "--attempts") opts.attempts = Number(v); + else { console.error(`free-agent: unknown option ${a}`); process.exit(2); } + } +} + +// ---------- budget ---------- +const today = new Date().toISOString().slice(0, 10); +function loadBudget() { + let b = { date: today, models: {} }; + if (existsSync(BUDGET)) { + try { b = JSON.parse(readFileSync(BUDGET, "utf8")); } catch {} + } + if (b.date !== today) b = { date: today, models: {} }; + return b; +} +function saveBudget(b) { + mkdirSync(dirname(BUDGET), { recursive: true }); + writeFileSync(BUDGET, JSON.stringify(b, null, 1)); +} +function usageOf(b, id) { + const e = b.models[id] || { day: 0, minute: [] }; + const now = Date.now(); + const minute = (e.minute || []).filter((ts) => now - ts < 60_000); + return { day: e.day || 0, minute, exhausted: !!e.exhausted }; +} +function record(b, id) { + const u = usageOf(b, id); + u.minute.push(Date.now()); + b.models[id] = { day: u.day + 1, minute: u.minute.slice(-60), exhausted: b.models[id]?.exhausted || false }; +} +function markExhausted(b, id) { + const u = usageOf(b, id); + b.models[id] = { day: u.day, minute: u.minute, exhausted: true }; +} + +const pool = JSON.parse(readFileSync(POOL, "utf8")).models; + +function pick(role, skip) { + const b = loadBudget(); + for (const m of pool) { + if (skip.has(m.id)) continue; + if (!(m.roles || []).includes(role)) continue; + const u = usageOf(b, m.id); + if (u.exhausted) continue; + if (u.day >= m.rpd) continue; + if (u.minute.length >= m.rpm) continue; + return m; + } + return null; +} + +if (opts.list) { + const b = loadBudget(); + const c = loadBudget(); + for (const m of pool) { + const u = loadBudget() && usageOf(b, m.id); + console.log( + `${m.id.padEnd(48)} ${String(u.day).padStart(4)}/${String(m.rpd).padEnd(5)} ${u.exhausted ? "EXHAUSTED" : ""} ${m.roles.join(",")}` + ); + } + console.log(`\nbudget file: ${BUDGET} (${c.date})`); + process.exit(0); +} + +if (!opts.brief) { console.error("free-agent: --brief is required (or --list)"); process.exit(2); } +const briefPath = resolve(opts.brief); +if (!existsSync(briefPath)) { console.error(`free-agent: no such brief ${briefPath}`); process.exit(2); } +const workDir = resolve(opts.dir || dirname(briefPath)); +if (!existsSync(workDir)) { console.error(`free-agent: no such dir ${workDir}`); process.exit(2); } + +// ---------- run dir ---------- +const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40); +const runId = opts.id || `${slug(basename(briefPath, ".md"))}-${new Date().toISOString().replace(/[-:T]/g, "").slice(4, 14)}`; +const runDir = join(RUNS, runId); +mkdirSync(runDir, { recursive: true }); +copyFileSync(briefPath, join(runDir, "BRIEF.md")); +const logPath = join(runDir, "run.log"); +const statusPath = join(runDir, "status.json"); + +const writeStatus = (o) => writeFileSync(statusPath, JSON.stringify({ id: runId, dir: workDir, role: opts.role, ...o }, null, 1)); + +// ---------- attempts ---------- +const skip = new Set(); +if (opts.model) skip.clear(); +const workerProtocol = readFileSync(WORKER, "utf8"); +const prompt = [ + `Read the brief at ${join(runDir, "BRIEF.md")} and complete it.`, + `Work inside ${workDir}.`, + `Write your report to ${join(runDir, "HANDOFF-REPORT.md")}.`, +].join("\n"); + +writeStatus({ state: "running", startedAt: new Date().toISOString(), attempts: [] }); +const attempts = []; + +for (let n = 0; n < Math.max(1, opts.attempts); n++) { + let model; + if (opts.model) { + model = pool.find((m) => m.id === opts.model) || { id: opts.model, roles: [opts.role], rpd: 1e9, rpm: 1e9 }; + } else { + model = pick(opts.role, skip); + if (!model) break; + } + skip.add(model.id); + + const b = loadBudget(); + record(b, model.id); + saveBudget(b); + + const started = Date.now(); + if (!opts.quiet) console.log(`[free-agent] ${runId}: trying ${model.id} (attempt ${n + 1})`); + appendFileSync(logPath, `\n=== ${new Date().toISOString()} ${model.id} ===\n`); + + const proc = Bun.spawn({ + cmd: [ + "pi", "-p", + "--model", model.id, + "--no-session", + "--append-system-prompt", workerProtocol, + prompt, + ], + cwd: workDir, + stdout: "pipe", + stderr: "pipe", + env: { ...process.env }, + }); + + let out = ""; + const timer = setTimeout(() => { try { proc.kill(); } catch {} }, opts.timeout * 1000); + const pump = async (stream) => { + const dec = new TextDecoder(); + for await (const chunk of stream) { + const s = dec.decode(chunk); + out += s; + appendFileSync(logPath, s); + if (!opts.quiet) process.stdout.write(s); + } + }; + await Promise.all([pump(proc.stdout), pump(proc.stderr)]); + const code = await proc.exited; + clearTimeout(timer); + const secs = ((Date.now() - started) / 1000).toFixed(0); + + const rateLimited = /429|rate.?limit|quota|insufficient|overloaded|no capacity|too many requests/i.test(out); + const finished = /HANDOFF-DONE/.test(out); + const ok = code === 0 && finished; + + attempts.push({ model: model.id, exit: code, secs: Number(secs), rateLimited, ok }); + + if (rateLimited) { + const bb = loadBudget(); + markExhausted(bb, model.id); + saveBudget(bb); + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: rate limited — parked for today, trying next`); + continue; + } + if (ok) { + writeStatus({ state: "done", endedAt: new Date().toISOString(), model: model.id, secs: Number(secs), attempts, report: join(runDir, "HANDOFF-REPORT.md") }); + if (!opts.quiet) console.log(`\n[free-agent] ${runId}: done with ${model.id} in ${secs}s`); + console.log(runDir); + process.exit(0); + } + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: exit ${code}, no HANDOFF-DONE — next model`); +} + +const state = attempts.length === 0 ? "no-capacity" : "failed"; +writeStatus({ state, endedAt: new Date().toISOString(), attempts }); +if (!opts.quiet) console.error(`[free-agent] ${runId}: ${state}`); +process.exit(attempts.length === 0 ? 3 : 1); diff --git a/bin/handoff b/bin/handoff new file mode 100755 index 0000000..495c6fe --- /dev/null +++ b/bin/handoff @@ -0,0 +1,198 @@ +#!/usr/bin/env bash +# handoff — queue task briefs for free-model workers, run them in tmux, and +# hand the result back for review by the primary agent. +# +# handoff submit BRIEF.md --dir ~/Projects/thing --role code +# echo "..." | handoff submit - --dir . --id fix-tests +# handoff list | status ID | log ID | review ID | kill ID | attach | clean +# handoff daemon # queue watcher (systemd user service runs this) +# +# State: ~/.local/share/handoff/{queue,running,done,failed}/ID.json +# Worker logs: ~/.local/state/free-agent/runs/ID/{run.log,HANDOFF-REPORT.md,status.json} + +set -uo pipefail + +HOME_DIR="${HOME}" +DATA="${XDG_DATA_HOME:-$HOME_DIR/.local/share}/handoff" +STATE="${XDG_STATE_HOME:-$HOME_DIR/.local/state}/free-agent/runs" +QUEUE="$DATA/queue"; RUNNING="$DATA/running"; DONE="$DATA/done"; FAILED="$DATA/failed" +TMUX_SESSION="${HANDOFF_TMUX:-handoff}" +MAX_PARALLEL="${HANDOFF_MAX_PARALLEL:-2}" +mkdir -p "$QUEUE" "$RUNNING" "$DONE" "$FAILED" + +die() { printf 'handoff: %s\n' "$*" >&2; exit 1; } +now() { date -u +%Y-%m-%dT%H:%M:%SZ; } + +slugify() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g' | cut -c1-40; } + +usage() { + sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//' + cat <<'EOF' + +Roles: code (implement), review (critique a diff/design), infra (config/runbooks). +Brief format: what to change, which files, acceptance command, what not to touch. +EOF +} + +need_id() { [ -n "${1:-}" ] || die "missing run id"; } +task_file() { local id="$1" d; for d in "$RUNNING" "$QUEUE" "$DONE" "$FAILED"; do [ -f "$d/$id.json" ] && { printf '%s' "$d/$id.json"; return 0; }; done; return 1; } + +cmd_submit() { + local brief="" dir="" role="code" id="" + while [ $# -gt 0 ]; do + case "$1" in + --dir) dir="${2:-}"; shift 2 ;; + --role) role="${2:-code}"; shift 2 ;; + --id) id="${2:-}"; shift 2 ;; + -h|--help) usage; exit 0 ;; + -) brief="STDIN"; shift ;; + *) brief="$1"; shift ;; + esac + done + [ -n "$brief" ] || die "give a brief file, or - to read stdin" + [ -n "$dir" ] || dir="$(pwd)" + [ -d "$dir" ] || die "no such dir: $dir" + dir="$(cd "$dir" && pwd)" + + local body + if [ "$brief" = "STDIN" ]; then body="$(cat)"; else [ -f "$brief" ] || die "no such brief: $brief"; body="$(cat "$brief")"; fi + [ -n "$body" ] || die "brief is empty" + + [ -n "$id" ] || id="$(slugify "$(head -c 60 <<<"$body" | tr '\n' ' ')")-$(date +%H%M%S)" + local bpath="$DATA/$id.brief.md" + printf '%s\n' "$body" > "$bpath" + + python3 - "$QUEUE/$id.json" "$id" "$dir" "$role" "$bpath" <<'PY' +import json, sys, datetime +path, rid, d, role, brief = sys.argv[1:6] +json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "queuedAt": datetime.datetime.utcnow().isoformat()+"Z"}, open(path, "w"), indent=1) +PY + printf 'queued %s\n dir: %s\n role: %s\n log: %s/%s/run.log\n' "$id" "$dir" "$role" "$STATE" "$id" + echo " start the daemon if it is not running: handoff daemon &" +} + +ensure_session() { + tmux has-session -t "$TMUX_SESSION" 2>/dev/null && return 0 + tmux new-session -d -s "$TMUX_SESSION" -n workers -c "$HOME_DIR" + tmux set-option -t "$TMUX_SESSION" history-limit 20000 >/dev/null 2>&1 +} + +running_count() { find "$RUNNING" -maxdepth 1 -name '*.json' | wc -l | tr -d ' '; } + +start_task() { + local f="$1" id dir role brief + id="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["id"])' "$f")" + dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$f")" + role="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("role","code"))' "$f")" + brief="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["brief"])' "$f")" + + mv "$f" "$RUNNING/$id.json" 2>/dev/null || return 0 + ensure_session + tmux new-window -d -t "$TMUX_SESSION" -n "$id" -c "$dir" \ + "free-agent --brief $(printf '%q' "$brief") --dir $(printf '%q' "$dir") --role $(printf '%q' "$role") --id $(printf '%q' "$id"); printf '\nhandoff window finished: %s\n' \$?; sleep 2" \ + >/dev/null 2>&1 || { echo "handoff: tmux failed for $id" >&2; mv "$RUNNING/$id.json" "$FAILED/$id.json"; return 1; } + echo "[$(now)] started $id ($role) in $dir" +} + +collect_finished() { + local f id st + for f in "$RUNNING"/*.json; do + [ -e "$f" ] || continue + id="$(basename "$f" .json)" + st="$STATE/$id/status.json" + [ -f "$st" ] || continue + local state + state="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("state","?"))' "$st" 2>/dev/null)" + case "$state" in + done) mv "$f" "$DONE/$id.json"; echo "[$(now)] done $id -> $(dirname "$st")/HANDOFF-REPORT.md" ;; + failed|no-capacity) mv "$f" "$FAILED/$id.json"; echo "[$(now)] $state $id" ;; + esac + if [ -n "${state:-}" ] && [ "$state" != "running" ]; then + tmux list-windows -t "$TMUX_SESSION" -F '#{window_name}' 2>/dev/null | grep -qx "$id" && tmux kill-window -t "$TMUX_SESSION:$id" 2>/dev/null + fi + done +} + +cmd_daemon() { + ensure_session + echo "[$(now)] handoff daemon: queue=$QUEUE parallel=$MAX_PARALLEL session=$TMUX_SESSION" + local unpaused="$DATA/pause" + trap 'echo "[$(now)] handoff daemon: stopping"; exit 0' INT TERM + while :; do + if [ ! -f "$unpaused" ]; then + collect_finished + for f in "$QUEUE"/*.json; do + [ -e "$f" ] || continue + [ "$(running_count)" -lt "$MAX_PARALLEL" ] || break + start_task "$f" + done + fi + sleep 5 + done +} + +cmd_list() { + local d id st + for d in queue running done failed; do + for f in "$DATA/$d"/*.json; do + [ -e "$f" ] || continue + id="$(basename "$f" .json)" + st="$STATE/$id/status.json" + local model="-" + [ -f "$st" ] && model="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("model") or d.get("state","-"))' "$st" 2>/dev/null)" + printf '%-8s %-28s %-34s %s\n' "$d" "$id" "$model" "$(dirname "$st")" + done + done +} + +cmd_status() { need_id "${1:-}"; local id="$1" f; f="$(task_file "$id")" || die "unknown id $id"; echo "task: $f"; cat "$f"; echo; [ -f "$STATE/$id/status.json" ] && cat "$STATE/$id/status.json"; } + +cmd_log() { need_id "${1:-}"; local id="$1" n="${2:-120}"; tail -n "$n" "$STATE/$id/run.log" 2>/dev/null || die "no log for $id"; } + +cmd_review() { + need_id "${1:-}"; local id="$1" + local dir=""; [ -f "$DATA/done/$id.json" ] && dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$DATA/done/$id.json")" + [ -n "$dir" ] || [ -f "$DATA/running/$id.json" ] && dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$DATA/running/$id.json" 2>/dev/null)" + echo "== status =="; cat "$STATE/$id/status.json" 2>/dev/null || echo "(no status yet)" + echo; echo "== report =="; cat "$STATE/$id/HANDOFF-REPORT.md" 2>/dev/null || echo "(no report written)" + if [ -n "$dir" ] && [ -d "$dir/.git" ]; then + echo; echo "== working tree =="; git -C "$dir" status --short | head -40 + echo; echo "== diffstat =="; git -C "$dir" diff --stat | tail -20 + echo; echo "review with: git -C $dir diff (or 'git add -p' to stage selectively)" + fi +} + +cmd_kill() { + need_id "${1:-}"; local id="$1" + tmux kill-window -t "$TMUX_SESSION:$id" 2>/dev/null && echo "killed window $id" || echo "no tmux window $id" + pkill -f "free-agent --brief .*--id $id" 2>/dev/null && echo "stopped worker" || true + for d in queue running; do [ -f "$DATA/$d/$id.json" ] && mv "$DATA/$d/$id.json" "$FAILED/$id.json" && echo "moved task to failed/"; done +} + +cmd_pause() { touch "$DATA/pause"; echo "daemon paused (existing runs continue)"; } +cmd_resume() { rm -f "$DATA/pause"; echo "daemon resumed"; } + +cmd_clean() { + local days="${1:-7}" + find "$DATA/done" "$DATA/failed" -name '*.json' -mtime +"$days" -delete 2>/dev/null + find "$STATE" -maxdepth 1 -type d -mtime +"$days" -name '*-*' -exec rm -rf {} + 2>/dev/null + echo "removed runs older than $days days" +} + +cmd_attach() { ensure_session; exec tmux attach -t "$TMUX_SESSION"; } + +case "${1:-}" in + submit) shift; cmd_submit "$@" ;; + daemon) cmd_daemon ;; + list|ls) cmd_list ;; + status) shift; cmd_status "$@" ;; + log|tail) shift; cmd_log "$@" ;; + review) shift; cmd_review "$@" ;; + kill) shift; cmd_kill "$@" ;; + attach) cmd_attach ;; + pause) cmd_pause ;; + resume) cmd_resume ;; + clean) shift; cmd_clean "$@" ;; + -h|--help|help|"") usage ;; + *) usage; exit 2 ;; +esac diff --git a/config/free-agent/WORKER.md b/config/free-agent/WORKER.md new file mode 100644 index 0000000..7dd7d95 --- /dev/null +++ b/config/free-agent/WORKER.md @@ -0,0 +1,40 @@ +# Worker protocol + +You are a **worker agent** in a handoff pipeline. A stronger model wrote the brief +you were given; it will review your work afterwards. Optimise for a clean, reviewable +diff — not for finishing fast. + +## Rules + +1. Read the brief first (`BRIEF.md` in the run directory). If it names files, read them + before editing. If it names an acceptance command, run it. +2. Stay inside the repository named in the brief. Never touch anything outside it, + never change credentials, never push, never install system packages. +3. Make the smallest change that satisfies the brief. No drive-by refactors, no + reformatting untouched code, no new dependencies unless the brief allows them. +4. Verify what you can: run the project's formatter, linter or test command when one + exists (see the brief). If it fails, fix it or record the failure honestly. +5. Never ask a question and stop. If something is ambiguous, pick the conservative + reading, do it, and note the ambiguity in the report. +6. If you cannot do the task at all, say why in one paragraph and change nothing. + +## Report + +Before you finish, write `HANDOFF-REPORT.md` in the run directory with exactly these +sections, under 40 lines total: + +``` +## Summary +One paragraph: what you changed and why. + +## Files +- path — what changed (one line each) + +## Verified +- command — result (or "not run: reason") + +## Risks / open questions +- anything the reviewer must check, or "none" +``` + +Then print `HANDOFF-DONE` as the last line of your reply. diff --git a/config/free-agent/pool.json b/config/free-agent/pool.json new file mode 100644 index 0000000..b15ffa6 --- /dev/null +++ b/config/free-agent/pool.json @@ -0,0 +1,68 @@ +{ + "$comment": "Free-model worker pool for `free-agent` / `handoff`. Limits are conservative published free-tier numbers (Nov 2026); free-agent enforces rpm/rpd locally so a burst never trips a provider's 429. Order = preference: first model that has budget and a matching role wins.", + "models": [ + { + "id": "google/gemini-3.5-flash", + "roles": ["code", "review", "infra"], + "rpm": 8, + "rpd": 200, + "note": "Free tier workhorse: 1M context, strong tool use, per-project limits shown in AI Studio." + }, + { + "id": "zai/glm-4.5-flash", + "roles": ["code", "infra"], + "rpm": 10, + "rpd": 200, + "note": "Permanent $0 Flash model on Z.ai; fastest of the four in practice." + }, + { + "id": "groq/openai/gpt-oss-120b", + "roles": ["code", "review", "infra"], + "rpm": 28, + "rpd": 900, + "note": "Groq LPU, very fast, 131K context. Free tier is token-per-minute tight (~6-8K TPM), so keep briefs short." + }, + { + "id": "openrouter/minimax/minimax-m3.1-flash:free", + "roles": ["code", "review", "infra"], + "rpm": 18, + "rpd": 45, + "note": "OpenRouter :free, 1M context, vision. 50 req/day cap (45 here for headroom)." + }, + { + "id": "google/gemini-3.1-flash-lite", + "roles": ["code", "review"], + "rpm": 12, + "rpd": 800, + "note": "Cheap second Gemini lane for small edits and reviews." + }, + { + "id": "openrouter/nvidia/nemotron-3-super-120b-a12b:free", + "roles": ["code", "review"], + "rpm": 18, + "rpd": 45, + "note": "OpenRouter :free alternative when minimax is busy." + }, + { + "id": "openrouter/cohere/north-mini-code:free", + "roles": ["code"], + "rpm": 18, + "rpd": 45, + "note": "Code-tuned free lane through OpenRouter." + }, + { + "id": "groq/qwen/qwen3.8-27b", + "roles": ["code"], + "rpm": 28, + "rpd": 900, + "note": "Groq fallback, small max output (16K)." + }, + { + "id": "cohere/north-mini-code-1.0", + "roles": ["code", "review"], + "rpm": 18, + "rpd": 30, + "note": "Existing Cohere trial key: 1000 calls/month, so ~30/day." + } + ] +} diff --git a/home/agents.nix b/home/agents.nix index ce97348..175a32f 100644 --- a/home/agents.nix +++ b/home/agents.nix @@ -39,6 +39,9 @@ in ".free-pi/agent/mcp.json".source = link "config/free-pi/mcp.json"; ".free-pi/agent/AGENTS.md".source = link "config/free-pi/AGENTS.md"; + # Free-model worker pool for the handoff pipeline (bin/free-agent, bin/handoff). + ".config/free-agent/pool.json".source = link "config/free-agent/pool.json"; + # Progressive context disclosure: a thin always-on AGENTS.md, the detail in # skills, and an extension that refuses unbounded reads of large files. "AGENTS.md".source = link "config/pi/AGENTS.md"; @@ -61,6 +64,24 @@ in // skillSet ".codex/skills" allSkills // skillSet ".agents/skills" (builtins.filter (n: !(builtins.elem n cliSkills)) sharedSkills) // cliSet ".agents/skills"; + # Free-model handoff pipeline. The daemon owns the tmux session "handoff" and + # starts one window per queued brief, so workers survive a terminal closing and + # are all back after a reboot. Rate limits are enforced by free-agent itself. + systemd.user.services.handoff = { + Unit = { + Description = "Free-model handoff queue (tmux workers)"; + After = [ "default.target" ]; + }; + Service = { + ExecStart = "${config.home.homeDirectory}/.dotfiles/bin/handoff daemon"; + Restart = "always"; + RestartSec = 10; + # dotfiles/bin holds handoff + free-agent, .nix-profile and mise supply pi/node. + Environment = "PATH=${config.home.homeDirectory}/.dotfiles/bin:${config.home.homeDirectory}/.nix-profile/bin:${config.home.homeDirectory}/.local/bin:${config.home.homeDirectory}/.local/share/mise/shims:/run/current-system/sw/bin:/usr/bin:/bin"; + }; + Install.WantedBy = [ "default.target" ]; + }; + # MCP servers carry tokens, so they are rendered from config/*/mcp*.json templates # plus ~/.config/dotfiles/secrets.env by `dot secrets render` (never committed). } From ddc7d806b14a3cdc02613bd72649871b7fab4179 Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:07:21 -0700 Subject: [PATCH 22/40] models.json: provider keys through secretctl, not literals Google, Groq, OpenRouter and zai authenticate via secretctl at call time, and strict mode is off where the provider rejects it. --- config/free-pi/models.json | 14 +++++++++++++- config/pi/models.json | 17 ++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/config/free-pi/models.json b/config/free-pi/models.json index dae5c6e..42e868a 100644 --- a/config/free-pi/models.json +++ b/config/free-pi/models.json @@ -68,7 +68,7 @@ "compat": { "supportsUsageInStreaming": true, "supportsStore": false, - "supportsStrictMode": true + "supportsStrictMode": false }, "models": [ { @@ -130,6 +130,18 @@ } } ] + }, + "google": { + "apiKey": "!secretctl get GEMINI_API_KEY -- sh -c 'printf %s \"$GEMINI_API_KEY\"'" + }, + "groq": { + "apiKey": "!secretctl get GROQ_API_KEY -- sh -c 'printf %s \"$GROQ_API_KEY\"'" + }, + "openrouter": { + "apiKey": "!secretctl get OPENROUTER_API_KEY -- sh -c 'printf %s \"$OPENROUTER_API_KEY\"'" + }, + "zai": { + "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'" } } } diff --git a/config/pi/models.json b/config/pi/models.json index 6d4eb59..00ef18b 100644 --- a/config/pi/models.json +++ b/config/pi/models.json @@ -155,8 +155,19 @@ "supportsStore": false, "supportsStrictMode": false, "supportsUsageInStreaming": true - }, - "supportsStrictMode": false + } + }, + "google": { + "apiKey": "!secretctl get GEMINI_API_KEY -- sh -c 'printf %s \"$GEMINI_API_KEY\"'" + }, + "groq": { + "apiKey": "!secretctl get GROQ_API_KEY -- sh -c 'printf %s \"$GROQ_API_KEY\"'" + }, + "openrouter": { + "apiKey": "!secretctl get OPENROUTER_API_KEY -- sh -c 'printf %s \"$OPENROUTER_API_KEY\"'" + }, + "zai": { + "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'" } } -} \ No newline at end of file +} From 936f8a323e8772b1d6802717bd055eaaf0399ca9 Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:07:21 -0700 Subject: [PATCH 23/40] music-audit: fix-years sets date from the release group's first release Keep the pressing date in originaldate so libraries still sort and display by first release. Sweeps a whole library, not just the albums we re-tagged. --- tools/music-audit/fix-years.py | 131 +++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 tools/music-audit/fix-years.py diff --git a/tools/music-audit/fix-years.py b/tools/music-audit/fix-years.py new file mode 100644 index 0000000..227aa43 --- /dev/null +++ b/tools/music-audit/fix-years.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Set each album's year back to its original release, not the CD reissue. + +mb-tag writes the date of the MusicBrainz release it matched, which for most +catalogue albums is a later CD pressing: a 1973 record ends up filed as 1988. +Music libraries sort and display by this year, so the release group's +first-release-date is what belongs in `date`; the pressing date is kept in +`originaldate` so nothing is lost. +""" +from __future__ import annotations + +import glob +import json +import os +import sys +import time +import urllib.request + +from mutagen import File + +UA = "Dogebot/1.0 ( https://github.com/RustyRaptor/doge_cogs )" +MB = "https://musicbrainz.org/ws/2/release/" +AUDIO = (".flac", ".mp3", ".m4a", ".ogg", ".opus") +CACHE = "/var/lib/beets/mb-release-cache.json" + + +def get(url: str) -> dict: + for attempt in range(4): + try: + req = urllib.request.Request(url, headers={"User-Agent": UA}) + with urllib.request.urlopen(req, timeout=40) as r: + return json.loads(r.read().decode()) + except Exception: + if attempt == 3: + return {} + time.sleep(2 * (attempt + 1)) + return {} + + +def val(tags, *names) -> str: + for n in names: + v = tags.get(n) + if v is None: + continue + if isinstance(v, list): + v = v[0] if v else "" + s = str(v).strip() + if s: + return s + return "" + + +def main() -> int: + apply = "--write" in sys.argv + cache = json.load(open(CACHE)) if os.path.exists(CACHE) else {} + + folders = set() + # Every album folder that carries a MusicBrainz id, not just the ones the + # resolver touched: albums tagged by beets or by hand need the same fix. + roots = [a for a in sys.argv[1:] if not a.startswith("--")] + for root in roots or ["/mnt/MediaDisk/Music/MyLibrary"]: + for dirpath, _dirnames, filenames in os.walk(root): + if any(f.lower().endswith(AUDIO) for f in filenames): + folders.add(dirpath) + + fixed = checked = 0 + for folder in sorted(folders): + files = [f for f in sorted(os.listdir(folder)) if f.lower().endswith(AUDIO)] + if not files: + continue + sample = os.path.join(folder, files[0]) + try: + tags = File(sample).tags or {} + except Exception: + continue + rel_id = val(tags, "musicbrainz_albumid", "TXXX:MusicBrainz Album Id") + if not rel_id: + continue + if rel_id not in cache: + rel = get("%s%s?inc=release-groups&fmt=json" % (MB, rel_id)) + time.sleep(1.1) + rg = (rel.get("release-group") or {}).get("first-release-date") or "" + cache[rel_id] = {"release_date": rel.get("date") or "", "first": rg} + json.dump(cache, open(CACHE, "w"), indent=1) + info = cache[rel_id] + first = info.get("first") or "" + if not first: + continue + checked += 1 + want = first[:4] + for f in files: + path = os.path.join(folder, f) + try: + t = File(path) + tg = t.tags + if tg is None: + continue + except Exception: + continue + cur = val(tg, "date", "TDRC", "year", "TXXX:YEAR")[:4] + if cur == want: + continue + if apply: + low = path.lower() + # Vorbis comments (flac/ogg/opus) are dict-like; MP3 needs ID3 frames. + if low.endswith((".flac", ".ogg", ".opus", ".m4a")): + try: + tg["date"] = [want] + if info.get("release_date"): + tg["originaldate"] = [info["release_date"]] + t.save() + continue + except Exception: + pass + if True: + from mutagen.id3 import TDRC, TXXX + + tg.setall("TDRC", [TDRC(encoding=3, text=[want])]) + if info.get("release_date"): + tg.setall("TXXX:ORIGINALDATE", + [TXXX(encoding=3, desc="ORIGINALDATE", text=[info["release_date"]])]) + t.save() + fixed += 1 + print(" %-46s date %s -> %s" % (os.path.basename(folder)[:46], cur or "?", want)) + + print("\n%d albums checked, %d files %s" % (checked, fixed, "re-dated" if apply else "would change (dry run)")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 68c85c45af024dd798c2b31dbe5cf9cd7db6c5dd Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:10:14 -0700 Subject: [PATCH 24/40] free-agent: retry on provider retryDelay, zai flash maxTokens - free-agent now sleeps the delay a free tier asks for (Gemini free Flash is 5 req/min) and retries the same model before spending another lane. - pool rpm lowered for the Gemini lanes to stay under the published limit. - models.json: GLM flash ids with explicit maxTokens, otherwise Z.ai rejects the request with max_tokens must be in [1,98404]. - handoff skill so every harness knows the brief -> queue -> review loop. --- bin/free-agent | 91 +++++++++++++++++++----------- config/free-agent/pool.json | 50 ++++++++++++---- config/free-pi/models.json | 44 ++++++++++++++- config/pi/models.json | 44 ++++++++++++++- config/skills/cli/handoff/SKILL.md | 81 ++++++++++++++++++++++++++ home/agents.nix | 2 +- 6 files changed, 265 insertions(+), 47 deletions(-) create mode 100644 config/skills/cli/handoff/SKILL.md diff --git a/bin/free-agent b/bin/free-agent index 59a5ae5..1d930aa 100755 --- a/bin/free-agent +++ b/bin/free-agent @@ -158,44 +158,69 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { saveBudget(b); const started = Date.now(); - if (!opts.quiet) console.log(`[free-agent] ${runId}: trying ${model.id} (attempt ${n + 1})`); - appendFileSync(logPath, `\n=== ${new Date().toISOString()} ${model.id} ===\n`); + const modelAttempts = []; + for (let r = 1; r <= 3; r++) { + if (!opts.quiet) console.log(`[free-agent] ${runId}: trying ${model.id} (attempt ${n + 1}.${r})`); + appendFileSync(logPath, `\n=== ${new Date().toISOString()} ${model.id} ===\n`); - const proc = Bun.spawn({ - cmd: [ - "pi", "-p", - "--model", model.id, - "--no-session", - "--append-system-prompt", workerProtocol, - prompt, - ], - cwd: workDir, - stdout: "pipe", - stderr: "pipe", - env: { ...process.env }, - }); + const proc = Bun.spawn({ + cmd: [ + "pi", "-p", + "--model", model.id, + "--no-session", + "--append-system-prompt", workerProtocol, + prompt, + ], + cwd: workDir, + stdout: "pipe", + stderr: "pipe", + env: { ...process.env }, + }); - let out = ""; - const timer = setTimeout(() => { try { proc.kill(); } catch {} }, opts.timeout * 1000); - const pump = async (stream) => { - const dec = new TextDecoder(); - for await (const chunk of stream) { - const s = dec.decode(chunk); - out += s; - appendFileSync(logPath, s); - if (!opts.quiet) process.stdout.write(s); + let out = ""; + const timer = setTimeout(() => { try { proc.kill(); } catch {} }, opts.timeout * 1000); + const pump = async (stream) => { + const dec = new TextDecoder(); + for await (const chunk of stream) { + const s = dec.decode(chunk); + out += s; + appendFileSync(logPath, s); + if (!opts.quiet) process.stdout.write(s); + } + }; + await Promise.all([pump(proc.stdout), pump(proc.stderr)]); + const code = await proc.exited; + clearTimeout(timer); + const secs = ((Date.now() - started) / 1000).toFixed(0); + + const rateLimited = /429|rate.?limit|quota|RESOURCE_EXHAUSTED|insufficient|overloaded|no capacity|too many requests/i.test(out); + const finished = /HANDOFF-DONE/.test(out); + const ok = code === 0 && finished; + modelAttempts.push({ exit: code, secs: Number(secs), rateLimited, ok }); + + // A free tier that says "retry in 41s" is a wait, not a dead model: sleep the + // delay it asks for and try the same model again before spending another lane. + if (rateLimited && !ok && r < 3) { + const m = + out.match(/retry in ([\d.]+)\s*s/i) || + out.match(/"retryDelay":\s*"(\d+)s"/) || + out.match(/try again in ([\d.]+)\s*s/i) || + out.match(/retry after:?\s*(\d+)/i); + const wait = Math.min(120, Math.ceil(Number(m ? m[1] : 45)) + 2); + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: rate limited, waiting ${wait}s (retry ${r}/3)`); + await Bun.sleep(wait * 1000); + continue; } - }; - await Promise.all([pump(proc.stdout), pump(proc.stderr)]); - const code = await proc.exited; - clearTimeout(timer); + if (ok) break; + if (!rateLimited) break; + } + const secs = ((Date.now() - started) / 1000).toFixed(0); + const last = modelAttempts[modelAttempts.length - 1] || {}; + const rateLimited = !!last.rateLimited; + const ok = !!last.ok; - const rateLimited = /429|rate.?limit|quota|insufficient|overloaded|no capacity|too many requests/i.test(out); - const finished = /HANDOFF-DONE/.test(out); - const ok = code === 0 && finished; - - attempts.push({ model: model.id, exit: code, secs: Number(secs), rateLimited, ok }); + attempts.push({ model: model.id, exit: last.exit, secs: Number(secs), rateLimited, ok, tries: modelAttempts.length }); if (rateLimited) { const bb = loadBudget(); diff --git a/config/free-agent/pool.json b/config/free-agent/pool.json index b15ffa6..252fce8 100644 --- a/config/free-agent/pool.json +++ b/config/free-agent/pool.json @@ -3,63 +3,91 @@ "models": [ { "id": "google/gemini-3.5-flash", - "roles": ["code", "review", "infra"], - "rpm": 8, + "roles": [ + "code", + "review", + "infra" + ], + "rpm": 4, "rpd": 200, "note": "Free tier workhorse: 1M context, strong tool use, per-project limits shown in AI Studio." }, { "id": "zai/glm-4.5-flash", - "roles": ["code", "infra"], + "roles": [ + "code", + "infra" + ], "rpm": 10, "rpd": 200, "note": "Permanent $0 Flash model on Z.ai; fastest of the four in practice." }, { "id": "groq/openai/gpt-oss-120b", - "roles": ["code", "review", "infra"], + "roles": [ + "code", + "review", + "infra" + ], "rpm": 28, "rpd": 900, "note": "Groq LPU, very fast, 131K context. Free tier is token-per-minute tight (~6-8K TPM), so keep briefs short." }, { "id": "openrouter/minimax/minimax-m3.1-flash:free", - "roles": ["code", "review", "infra"], + "roles": [ + "code", + "review", + "infra" + ], "rpm": 18, "rpd": 45, "note": "OpenRouter :free, 1M context, vision. 50 req/day cap (45 here for headroom)." }, { "id": "google/gemini-3.1-flash-lite", - "roles": ["code", "review"], - "rpm": 12, + "roles": [ + "code", + "review" + ], + "rpm": 4, "rpd": 800, "note": "Cheap second Gemini lane for small edits and reviews." }, { "id": "openrouter/nvidia/nemotron-3-super-120b-a12b:free", - "roles": ["code", "review"], + "roles": [ + "code", + "review" + ], "rpm": 18, "rpd": 45, "note": "OpenRouter :free alternative when minimax is busy." }, { "id": "openrouter/cohere/north-mini-code:free", - "roles": ["code"], + "roles": [ + "code" + ], "rpm": 18, "rpd": 45, "note": "Code-tuned free lane through OpenRouter." }, { "id": "groq/qwen/qwen3.8-27b", - "roles": ["code"], + "roles": [ + "code" + ], "rpm": 28, "rpd": 900, "note": "Groq fallback, small max output (16K)." }, { "id": "cohere/north-mini-code-1.0", - "roles": ["code", "review"], + "roles": [ + "code", + "review" + ], "rpm": 18, "rpd": 30, "note": "Existing Cohere trial key: 1000 calls/month, so ~30/day." diff --git a/config/free-pi/models.json b/config/free-pi/models.json index 42e868a..3010219 100644 --- a/config/free-pi/models.json +++ b/config/free-pi/models.json @@ -141,7 +141,49 @@ "apiKey": "!secretctl get OPENROUTER_API_KEY -- sh -c 'printf %s \"$OPENROUTER_API_KEY\"'" }, "zai": { - "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'" + "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'", + "models": [ + { + "id": "glm-4.5-flash", + "name": "GLM-4.5 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.7-flash", + "name": "GLM-4.7 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.6v-flash", + "name": "GLM-4.6V Flash (free, vision)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text", + "image" + ], + "samplingParams": { + "temperature": 0.3 + } + } + ] } } } diff --git a/config/pi/models.json b/config/pi/models.json index 00ef18b..b392df3 100644 --- a/config/pi/models.json +++ b/config/pi/models.json @@ -167,7 +167,49 @@ "apiKey": "!secretctl get OPENROUTER_API_KEY -- sh -c 'printf %s \"$OPENROUTER_API_KEY\"'" }, "zai": { - "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'" + "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'", + "models": [ + { + "id": "glm-4.5-flash", + "name": "GLM-4.5 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.7-flash", + "name": "GLM-4.7 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.6v-flash", + "name": "GLM-4.6V Flash (free, vision)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text", + "image" + ], + "samplingParams": { + "temperature": 0.3 + } + } + ] } } } diff --git a/config/skills/cli/handoff/SKILL.md b/config/skills/cli/handoff/SKILL.md new file mode 100644 index 0000000..9143504 --- /dev/null +++ b/config/skills/cli/handoff/SKILL.md @@ -0,0 +1,81 @@ +--- +name: handoff +description: Delegate a chunk of work to free models (Gemini Flash, GLM Flash, Groq, OpenRouter :free, Cohere) through a tmux worker queue, then review and correct what they produce. Use when a task is well-specified enough for a cheaper model to attempt it and you want to keep the expensive model for review. +--- + +# Handoff to free-model workers + +A worker is a `pi` session on a free model, given a brief, in its own tmux window. +It writes `HANDOFF-REPORT.md` and stops. You review the diff and fix what it missed. + +Pool, limits and budgets: `~/.config/free-agent/pool.json` (linked from +`dotfiles/config/free-agent/pool.json`). Today's usage: `free-agent --list`. + +## Write a brief that a weaker model can actually follow + +``` +# <one-line goal> + +Repository: <absolute path> + +1. <exact change> +2. <exact change> + +Files: <the only files it may touch> +Do not touch: <everything it must leave alone> + +Acceptance: <the exact command you will run to check> +``` + +Rules that make the difference: absolute paths, numbered concrete changes, one +acceptance command, an explicit "do not touch" list, and no open questions. + +## Delegate + +```sh +handoff submit BRIEF.md --dir ~/Projects/thing --role code --id fix-tests +``` + +`--role code` implements, `review` critiques a diff or design, `infra` writes +config/runbooks. The daemon (systemd user unit `handoff.service`, tmux session +`handoff`) picks it up within 5 s and runs it in a new window. + +```sh +handoff list # queue / running / done / failed +handoff log fix-tests 60 # last 60 lines of the worker's transcript +handoff attach # watch the tmux session live +handoff pause | resume # stop taking new work +handoff kill fix-tests +``` + +Run one directly, without the queue (useful while iterating on a brief): + +```sh +free-agent --brief BRIEF.md --dir ~/Projects/thing --role code --dry-run # which model +free-agent --brief BRIEF.md --dir ~/Projects/thing --role code # run it +free-agent --list # budgets +``` + +## Review — always + +```sh +handoff review fix-tests +``` + +That prints the status, the report, `git status --short` and `git diff --stat`. +Then, yourself: + +1. `git -C <repo> diff` — read every hunk. Workers hallucinate plausible edits. +2. Run the acceptance command, plus the project's own tests. +3. Fix, or submit a follow-up brief naming exactly what was wrong. +4. Commit yourself. Workers never commit. + +## Budgets and rate limits + +`free-agent` records one request per attempt in +`~/.local/state/free-agent/budget.json`, enforces each model's rpm/rpd from the +pool, marks a model dead for the day on a hard quota error, and on a "retry in +Ns" reply it sleeps the delay and retries the same model before spending another +lane. Free tiers are small: Gemini Flash is ~5 requests/minute, which a tool +loop can burn in one turn — expect waits, keep briefs short, and prefer +`--role code` tasks with few steps. diff --git a/home/agents.nix b/home/agents.nix index 175a32f..d5140fb 100644 --- a/home/agents.nix +++ b/home/agents.nix @@ -10,7 +10,7 @@ let "git" "gt" "mise-cli" "secrets_man" "searxng" "playwright-cli" "context-discipline" "homelab-policies" "memory-layer" ]; - cliSkills = [ "infra-change" "wiki-update" "wiki-view" "lapis-memory" ]; + cliSkills = [ "infra-change" "wiki-update" "wiki-view" "lapis-memory" "handoff" ]; allSkills = sharedSkills ++ cliSkills; skillSet = dir: names: lib.listToAttrs (map (n: lib.nameValuePair "${dir}/${n}" { source = link "config/skills/${n}"; From bbe587377a14571088d524167ce371e22a8caa43 Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:11:37 -0700 Subject: [PATCH 25/40] free-agent: only park a lane on a daily wall, not a per-minute 429 --- bin/free-agent | 13 +++++++++---- config/pi/AGENTS.md | 1 + 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/bin/free-agent b/bin/free-agent index 1d930aa..fa0f772 100755 --- a/bin/free-agent +++ b/bin/free-agent @@ -223,10 +223,15 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { attempts.push({ model: model.id, exit: last.exit, secs: Number(secs), rateLimited, ok, tries: modelAttempts.length }); if (rateLimited) { - const bb = loadBudget(); - markExhausted(bb, model.id); - saveBudget(bb); - if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: rate limited — parked for today, trying next`); + // Only a daily/credit wall parks a lane for the rest of the day. A per-minute + // 429 was already retried above; failing over is enough for that one. + const daily = /per day|daily|RPD|requests? per day|insufficient balance|no resource package|billing/i.test(out); + if (daily) { + const bb = loadBudget(); + markExhausted(bb, model.id); + saveBudget(bb); + } + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: ${daily ? "out for today" : "rate limited"} — trying next`); continue; } if (ok) { diff --git a/config/pi/AGENTS.md b/config/pi/AGENTS.md index 851973b..26ad6a5 100644 --- a/config/pi/AGENTS.md +++ b/config/pi/AGENTS.md @@ -35,4 +35,5 @@ Load the skill that matches the task instead of asking for it up front: | wiki pages | `/skill:wiki-update`, `/skill:wiki-view` | | Gitea, issues, PRs, releases | `/skill:gt` | | memory, secrets, host safety, forges, codemode, stack defaults | `/skill:homelab-policies` | +| delegate a well-specified task to free models, then review it | `/skill:cli/handoff` | | runtimes and project tools | `/skill:mise-cli` | From 499a109fd8f2fc7c78960c2977e1dc17a1e6a2af Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:11:49 -0700 Subject: [PATCH 26/40] handoff: timezone-aware timestamp in queue entries datetime.utcnow() is deprecated and printed a DeprecationWarning on every submit; the queuedAt field is unchanged in format. --- bin/handoff | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/handoff b/bin/handoff index 495c6fe..987d3c0 100755 --- a/bin/handoff +++ b/bin/handoff @@ -65,7 +65,7 @@ cmd_submit() { python3 - "$QUEUE/$id.json" "$id" "$dir" "$role" "$bpath" <<'PY' import json, sys, datetime path, rid, d, role, brief = sys.argv[1:6] -json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "queuedAt": datetime.datetime.utcnow().isoformat()+"Z"}, open(path, "w"), indent=1) +json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "queuedAt": datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat()+"Z"}, open(path, "w"), indent=1) PY printf 'queued %s\n dir: %s\n role: %s\n log: %s/%s/run.log\n' "$id" "$dir" "$role" "$STATE" "$id" echo " start the daemon if it is not running: handoff daemon &" From deb83c1a73f96203540fe56b9d1fede370d65d7d Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:18:26 -0700 Subject: [PATCH 27/40] free-agent: --probe, OpenRouter free-lane rotation, Groq TPM reality - OpenRouter free slugs rotate: minimax-m3.1-flash and north-mini-code are gone, nemotron-3.5-lightning and nemotron-3-ultra respond, so the pool is updated. - --probe pings every lane with a tiny prompt and prints alive/dead with the provider's own error, which is how the rotation gets noticed. - Groq free is TPM-bound (~8K/min): one agent turn nearly fills it, so those lanes now sit last and are marked small-prompt only. - qwen3.8-27b on Groq fails its chat template and is dropped. --- bin/free-agent | 37 ++++++++++++++++++--- config/free-agent/pool.json | 64 +++++++++++++------------------------ 2 files changed, 56 insertions(+), 45 deletions(-) diff --git a/bin/free-agent b/bin/free-agent index fa0f772..497bf9e 100755 --- a/bin/free-agent +++ b/bin/free-agent @@ -21,11 +21,12 @@ const BUDGET = join(STATE, "budget.json"); const RUNS = join(STATE, "runs"); // ---------- args ---------- -const opts = { brief: "", dir: "", role: "code", id: "", model: "", timeout: 1800, attempts: 3, dryRun: false, list: false, quiet: false }; +const opts = { probe: false, brief: "", dir: "", role: "code", id: "", model: "", timeout: 1800, attempts: 3, dryRun: false, list: false, quiet: false }; const argv = process.argv.slice(2); for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "--list") opts.list = true; + else if (a === "--probe") opts.probe = true; else if (a === "--dry-run") opts.dryRun = true; else if (a === "--quiet") opts.quiet = true; else if (a === "-h" || a === "--help") { @@ -39,7 +40,7 @@ for (let i = 0; i < argv.length; i++) { --timeout <secs> per attempt (default 1800) --attempts <n> how many pool models to try (default 3) --dry-run print the chosen model and exit - --list print pool and today's usage`); + --list print pool and today's usage\n --probe ping every pool model once and report which are alive`); process.exit(0); } else if (a.startsWith("--")) { const v = argv[++i]; @@ -100,6 +101,30 @@ function pick(role, skip) { return null; } + +// ---------- probe: which pool lanes are alive right now ---------- +if (opts.probe) { + const res = await Promise.all( + pool.map(async (m) => { + const t0 = Date.now(); + const proc = Bun.spawn({ + cmd: ["pi", "-p", "--model", m.id, "--no-session", "--no-mcp", "--no-skills", "Reply with exactly: OK"], + stdout: "pipe", stderr: "pipe", env: { ...process.env }, + }); + const timer = setTimeout(() => { try { proc.kill(); } catch {} }, 90_000); + const [o, e] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]); + const code = await proc.exited; + clearTimeout(timer); + const out = o + e; + const ok = code === 0 && /\bOK\b/.test(o); + const why = ok ? "" : (out.match(/"message"\s*:\s*"([^"]{0,80})/)?.[1] || out.replace(/\s+/g, " ").slice(0, 80)); + return { id: m.id, ok, ms: Date.now() - t0, why }; + }) + ); + for (const r of res) console.log(`${r.ok ? "OK " : "DEAD"} ${r.id.padEnd(50)} ${String(r.ms).padStart(6)}ms ${r.why}`); + process.exit(res.some((r) => r.ok) ? 0 : 1); +} + if (opts.list) { const b = loadBudget(); const c = loadBudget(); @@ -159,6 +184,8 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { const started = Date.now(); const modelAttempts = []; + let lastOut = ""; + let lastCode = null; for (let r = 1; r <= 3; r++) { if (!opts.quiet) console.log(`[free-agent] ${runId}: trying ${model.id} (attempt ${n + 1}.${r})`); appendFileSync(logPath, `\n=== ${new Date().toISOString()} ${model.id} ===\n`); @@ -191,6 +218,8 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { await Promise.all([pump(proc.stdout), pump(proc.stderr)]); const code = await proc.exited; clearTimeout(timer); + lastOut = out; + lastCode = code; const secs = ((Date.now() - started) / 1000).toFixed(0); const rateLimited = /429|rate.?limit|quota|RESOURCE_EXHAUSTED|insufficient|overloaded|no capacity|too many requests/i.test(out); @@ -225,7 +254,7 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { if (rateLimited) { // Only a daily/credit wall parks a lane for the rest of the day. A per-minute // 429 was already retried above; failing over is enough for that one. - const daily = /per day|daily|RPD|requests? per day|insufficient balance|no resource package|billing/i.test(out); + const daily = /per day|daily limit|RPD|insufficient balance|no resource package/i.test(lastOut); if (daily) { const bb = loadBudget(); markExhausted(bb, model.id); @@ -240,7 +269,7 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { console.log(runDir); process.exit(0); } - if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: exit ${code}, no HANDOFF-DONE — next model`); + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: exit ${lastCode}, no HANDOFF-DONE — next model`); } const state = attempts.length === 0 ? "no-capacity" : "failed"; diff --git a/config/free-agent/pool.json b/config/free-agent/pool.json index 252fce8..c68d4cc 100644 --- a/config/free-agent/pool.json +++ b/config/free-agent/pool.json @@ -23,18 +23,7 @@ "note": "Permanent $0 Flash model on Z.ai; fastest of the four in practice." }, { - "id": "groq/openai/gpt-oss-120b", - "roles": [ - "code", - "review", - "infra" - ], - "rpm": 28, - "rpd": 900, - "note": "Groq LPU, very fast, 131K context. Free tier is token-per-minute tight (~6-8K TPM), so keep briefs short." - }, - { - "id": "openrouter/minimax/minimax-m3.1-flash:free", + "id": "openrouter/nvidia/nemotron-3.5-lightning:free", "roles": [ "code", "review", @@ -42,7 +31,17 @@ ], "rpm": 18, "rpd": 45, - "note": "OpenRouter :free, 1M context, vision. 50 req/day cap (45 here for headroom)." + "note": "OpenRouter :free, 1M context, verified reachable 2026-11-29." + }, + { + "id": "openrouter/nvidia/nemotron-3-ultra-550b-a55b:free", + "roles": [ + "code", + "review" + ], + "rpm": 18, + "rpd": 45, + "note": "OpenRouter :free, 1M context, larger sibling of the lightning lane." }, { "id": "google/gemini-3.1-flash-lite", @@ -54,34 +53,6 @@ "rpd": 800, "note": "Cheap second Gemini lane for small edits and reviews." }, - { - "id": "openrouter/nvidia/nemotron-3-super-120b-a12b:free", - "roles": [ - "code", - "review" - ], - "rpm": 18, - "rpd": 45, - "note": "OpenRouter :free alternative when minimax is busy." - }, - { - "id": "openrouter/cohere/north-mini-code:free", - "roles": [ - "code" - ], - "rpm": 18, - "rpd": 45, - "note": "Code-tuned free lane through OpenRouter." - }, - { - "id": "groq/qwen/qwen3.8-27b", - "roles": [ - "code" - ], - "rpm": 28, - "rpd": 900, - "note": "Groq fallback, small max output (16K)." - }, { "id": "cohere/north-mini-code-1.0", "roles": [ @@ -91,6 +62,17 @@ "rpm": 18, "rpd": 30, "note": "Existing Cohere trial key: 1000 calls/month, so ~30/day." + }, + { + "id": "groq/openai/gpt-oss-120b", + "roles": [ + "code", + "review", + "infra" + ], + "rpm": 6, + "rpd": 150, + "note": "Groq free is TPM-bound (~8K tokens/min on gpt-oss-120b): one agent turn with the system prompt and tool schemas nearly fills it, so this lane is last resort for small prompts only." } ] } From 8d719140bad51f5f898dcaac0b9b8191c5aca30b Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:31:39 -0700 Subject: [PATCH 28/40] decypharr-phase1: add-latency harness Runs on the media host so neither the Decypharr token nor the TorBox key leaves it, and prints only HTTP codes and timings. Uses fresh shuffled hashes per run: re-adding a hash the sandbox already knows answers in about a millisecond and halves the measured median. --- tools/decypharr-phase1/measure.sh | 116 +++++++++++++++++++++++++ tools/decypharr-phase1/probe-torbox.sh | 32 +++++++ 2 files changed, 148 insertions(+) create mode 100755 tools/decypharr-phase1/measure.sh create mode 100755 tools/decypharr-phase1/probe-torbox.sh diff --git a/tools/decypharr-phase1/measure.sh b/tools/decypharr-phase1/measure.sh new file mode 100755 index 0000000..9264452 --- /dev/null +++ b/tools/decypharr-phase1/measure.sh @@ -0,0 +1,116 @@ +#!/bin/bash +# measure.sh — Decypharr phase 1 retest: how long does an add take? +# +# Runs ON the media host (yveltal). Both secrets stay on that machine: the +# Decypharr API token is read from its own file and the TorBox key from rdtc's +# SQLite Settings table. Neither is ever printed, echoed or written to a file — +# only HTTP codes and timings come out. +# +# sudo -n ./measure.sh [runs-per-case] +# +# Cases: +# cached a real, cached TorBox hash (the path the *arr actually uses) +# bogus a well-formed magnet nothing has ever seen (uncached/blocked) +# noauth whether an add without any Authorization header is accepted +# +# Config under test (per-debrid, config.json): download_uncached=false, +# rate_limit=600/minute, workers=20, max_active_downloads=3. +set -uo pipefail + +API=http://127.0.0.1:8282 +CFG=/home/ziadarafat/.local/share/decypharr-sandbox/config/config.json +TOKEN_FILE=/home/ziadarafat/.local/share/decypharr-sandbox/config/.sandbox_token +RUNS=${1:-3} +RDTC_DB=/home/ziadarafat/.local/share/rdtc-fresh/db/rdtclient.db + +TOKEN=$(cat "$TOKEN_FILE" 2>/dev/null) +[ -n "$TOKEN" ] || { echo "no API token at $TOKEN_FILE" >&2; exit 1; } + +torbox_key() { + python3 - "$RDTC_DB" <<'PY' 2>/dev/null +import sqlite3, sys +db = sqlite3.connect(sys.argv[1]) +# Settings is a (SettingId, Value) key/value table, not a JSON blob. +row = db.execute("SELECT Value FROM Settings WHERE SettingId='Provider:ApiKey'").fetchone() +print(row[0] if row and row[0] else "") +PY +} + +add_timed() { # $1=label $2=magnet $3=auth|noauth + local label=$1 magnet=$2 mode=$3 out code secs + if [ "$mode" = "auth" ]; then + out=$(curl -sS -m 180 -o /tmp/.dcy_body -w '%{http_code} %{time_total}' \ + -H "Authorization: Bearer $TOKEN" \ + --data-urlencode "urls=$magnet" --data-urlencode "category=radarr" "$API/api/v2/torrents/add" 2>&1) + else + out=$(curl -sS -m 180 -o /tmp/.dcy_body -w '%{http_code} %{time_total}' \ + --data-urlencode "urls=$magnet" --data-urlencode "category=radarr" "$API/api/v2/torrents/add" 2>&1) + fi + code=${out%% *}; secs=${out##* } + printf '%-8s %-6s run=%-2s http=%-4s seconds=%-8s body=%s\n' \ + "$label" "$mode" "${CURRENT_RUN}" "${code:-ERR}" "${secs:-timeout}" \ + "$(head -c 80 /tmp/.dcy_body 2>/dev/null | tr -d '\n')" + printf '%s,%s,%s,%s,%s\n' "$label" "$mode" "${CURRENT_RUN}" "${code:-ERR}" "${secs:-timeout}" >> "$RESULTS" + rm -f /tmp/.dcy_body +} + +U=$(id -u ziadarafat) +UC="sudo -u ziadarafat env XDG_RUNTIME_DIR=/run/user/$U" +echo "=== sandbox: $($UC systemctl --user is-active decypharr-sandbox 2>/dev/null || echo n/a) api: $API ===" +python3 - "$CFG" <<'PY' 2>/dev/null +import json, sys +d = json.load(open(sys.argv[1])) +for deb in d.get("debrids", []): + print("=== config: provider=%s download_uncached=%s rate_limit=%s workers=%s max_active=%s" % ( + deb.get("provider"), deb.get("download_uncached"), deb.get("rate_limit"), + deb.get("workers"), d.get("max_active_downloads"))) +PY + +KEY=$(torbox_key) +if [ -n "${KEY:-}" ]; then + # Distinct hashes per run: re-adding the same hash is idempotent and would + # measure nothing after the first call. + CACHED_LIST=$(curl -sS -m 60 -H "Authorization: Bearer $KEY" \ + "https://api.torbox.app/v1/api/torrents/mylist?bypass_cache=true" 2>/dev/null \ + | python3 -c "import json,sys +import random +n=$RUNS+1 +try: d=json.load(sys.stdin) +except Exception: raise SystemExit +hs=[t['hash'] for t in (d.get('data') or []) if t.get('download_state')=='cached' and t.get('hash')] +random.shuffle(hs) +# Shuffle: re-running the same hashes measures nothing after the first call, +# because a hash the sandbox already knows answers in about a millisecond. +print(chr(10).join(hs[:n]))" 2>/dev/null) +else + CACHED_LIST="" +fi +unset KEY +N_CACHED=$(printf '%s\n' "$CACHED_LIST" | grep -c . || true) + +if [ "${N_CACHED:-0}" -gt 0 ]; then + echo "=== cached hashes available: $N_CACHED (not printed)" +else + echo "=== cached hashes available: none -- skipping the cached case" +fi + +BOGUS=0000000000000000000000000000000000000001 +RESULTS=${RESULTS:-/tmp/decypharr-phase1-results.csv} +echo "label,mode,run,http,seconds" > "$RESULTS" +for CURRENT_RUN in $(seq 1 "$RUNS"); do + H=$(printf '%s\n' "$CACHED_LIST" | sed -n "${CURRENT_RUN}p") + if [ -n "$H" ]; then + add_timed cached "magnet:?xt=urn:btih:$H&dn=phase1-test-$CURRENT_RUN" auth + fi + add_timed bogus "magnet:?xt=urn:btih:$BOGUS&dn=phase1-nonexistent-$CURRENT_RUN" auth +done + +H=$(printf '%s\n' "$CACHED_LIST" | sed -n "$((RUNS + 1))p") +if [ -n "$H" ]; then + CURRENT_RUN=1 + add_timed cached "magnet:?xt=urn:btih:$H&dn=phase1-noauth" noauth +fi +echo "=== results csv: $RESULTS ($(($(wc -l < "$RESULTS") - 1)) rows) ===" + +echo "=== last sandbox log lines ===" +$UC journalctl --user -u decypharr-sandbox -n 8 --no-pager 2>/dev/null | tail -8 | cut -c1-150 diff --git a/tools/decypharr-phase1/probe-torbox.sh b/tools/decypharr-phase1/probe-torbox.sh new file mode 100755 index 0000000..d0626ec --- /dev/null +++ b/tools/decypharr-phase1/probe-torbox.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# probe-torbox.sh — check the TorBox mylist shape without printing the key. +set -uo pipefail +DB=/home/ziadarafat/.local/share/rdtc-fresh/db/rdtclient.db +K=$(python3 - "$DB" <<'PY' +import sqlite3, sys +db = sqlite3.connect(sys.argv[1]) +r = db.execute("SELECT Value FROM Settings WHERE SettingId='Provider:ApiKey'").fetchone() +print(r[0] if r and r[0] else "") +PY +) +echo " key extracted: $([ -n "$K" ] && echo yes || echo no) (len ${#K})" +[ -n "$K" ] || exit 1 +curl -sS -m 60 -H "Authorization: Bearer $K" \ + "https://api.torbox.app/v1/api/torrents/mylist?bypass_cache=true" \ + -o /tmp/tb.json -w ' http=%{http_code} bytes=%{size_download}\n' +unset K +python3 - <<'PY' +import json +from collections import Counter +try: + d = json.load(open("/tmp/tb.json")) +except Exception as e: + print(" not json:", e); raise SystemExit +data = d.get("data") +print(" top keys:", list(d)[:6], "| err:", d.get("error"), d.get("detail")) +print(" data:", type(data).__name__, "n =", len(data or [])) +if isinstance(data, list) and data: + print(" item keys:", list(data[0])[:14]) + print(" states:", Counter(x.get("download_state") for x in data).most_common(6)) +PY +rm -f /tmp/tb.json From 710b5f59cb9ca76551e1b8d08706fe84fc10f2d7 Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:52:16 -0700 Subject: [PATCH 29/40] probe: weekly timer, and only dead lanes fail the unit - handoff-probe.service + .timer (Mon 08:00, persistent) run free-agent --probe and append to ~/.local/state/free-agent/probe.log. - probe now separates BUSY (429, quota, empty reply) from DEAD (retired slug, dead key, broken template); only DEAD fails the unit, so a weekly red status means the pool needs an edit rather than a provider being momentarily full. --- bin/free-agent | 22 +++++++++++++++++----- home/agents.nix | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/bin/free-agent b/bin/free-agent index 497bf9e..b741891 100755 --- a/bin/free-agent +++ b/bin/free-agent @@ -116,13 +116,25 @@ if (opts.probe) { const code = await proc.exited; clearTimeout(timer); const out = o + e; - const ok = code === 0 && /\bOK\b/.test(o); - const why = ok ? "" : (out.match(/"message"\s*:\s*"([^"]{0,80})/)?.[1] || out.replace(/\s+/g, " ").slice(0, 80)); - return { id: m.id, ok, ms: Date.now() - t0, why }; + // A completed turn is healthy even if the model answered in prose instead of "OK". + const ok = code === 0; + // Permanent failures are the ones that mean "edit the pool": retired slug, dead + // key, broken chat template. Everything else (429, empty output, timeouts) is a + // quota/timing wall that clears on its own. + const dead = !ok && /404|not found|no longer available|unknown model|invalid model|template|401|403|invalid.*(api )?key/i.test(out); + const why = ok ? "" : (out.match(/"message"\s*:\s*"([^"]{0,90})/)?.[1] || out.replace(/\s+/g, " ").trim().slice(0, 90) || "no output"); + return { id: m.id, ok, dead, busy: !ok && !dead, ms: Date.now() - t0, why }; }) ); - for (const r of res) console.log(`${r.ok ? "OK " : "DEAD"} ${r.id.padEnd(50)} ${String(r.ms).padStart(6)}ms ${r.why}`); - process.exit(res.some((r) => r.ok) ? 0 : 1); + for (const r of res) { + const tag = r.ok ? "OK " : r.dead ? "DEAD" : "BUSY"; + console.log(`${tag} ${r.id.padEnd(50)} ${String(r.ms).padStart(6)}ms ${r.why}`); + } + const dead = res.filter((r) => r.dead); + console.log(`\n${res.filter((r) => r.ok).length} ok, ${res.filter((r) => r.busy).length} busy, ${dead.length} dead${dead.length ? ": " + dead.map((d) => d.id).join(", ") : ""}`); + // Non-zero only for lanes that will not come back by themselves, so the weekly + // timer raises its hand exactly when the pool needs an edit. + process.exit(dead.length ? 1 : 0); } if (opts.list) { diff --git a/home/agents.nix b/home/agents.nix index d5140fb..e2ba998 100644 --- a/home/agents.nix +++ b/home/agents.nix @@ -82,6 +82,30 @@ in Install.WantedBy = [ "default.target" ]; }; + # Free lanes rot: OpenRouter retires :free slugs and providers change limits. + # A weekly probe writes the result to probe.log and fails the unit when a lane + # is dead, so "systemctl --user --failed" is the reminder instead of a surprise. + systemd.user.services.handoff-probe = { + Unit = { Description = "Probe every free-model lane in the handoff pool"; }; + Service = { + Type = "oneshot"; + ExecStart = "${config.home.homeDirectory}/.dotfiles/bin/free-agent --probe"; + StandardOutput = "append:${config.home.homeDirectory}/.local/state/free-agent/probe.log"; + StandardError = "append:${config.home.homeDirectory}/.local/state/free-agent/probe.log"; + Environment = "PATH=${config.home.homeDirectory}/.dotfiles/bin:${config.home.homeDirectory}/.nix-profile/bin:${config.home.homeDirectory}/.local/bin:${config.home.homeDirectory}/.local/share/mise/shims:/run/current-system/sw/bin:/usr/bin:/bin"; + }; + }; + + systemd.user.timers.handoff-probe = { + Unit = { Description = "Weekly free-model lane probe"; }; + Timer = { + OnCalendar = "Mon 08:00"; + Persistent = true; + RandomizedDelaySec = 900; + }; + Install.WantedBy = [ "timers.target" ]; + }; + # MCP servers carry tokens, so they are rendered from config/*/mcp*.json templates # plus ~/.config/dotfiles/secrets.env by `dot secrets render` (never committed). } From acd1c863935f4c60b4c7dff9b3b9bf366fe3a53a Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 21:57:09 -0700 Subject: [PATCH 30/40] freebuff: enroll as a handoff backend - bin/freebuff-agent drives the Freebuff TUI in its own tmux session and keeps the same brief -> report contract, so handoff can route to it with --backend freebuff (verified: queue -> worker -> diff -> tests pass). - handoff list shows the backend when a run has no model id. --- bin/freebuff-agent | 86 ++++++++++++++++++++++++++++++ bin/handoff | 19 ++++--- config/skills/cli/handoff/SKILL.md | 10 ++++ 3 files changed, 109 insertions(+), 6 deletions(-) create mode 100755 bin/freebuff-agent diff --git a/bin/freebuff-agent b/bin/freebuff-agent new file mode 100755 index 0000000..146a959 --- /dev/null +++ b/bin/freebuff-agent @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# freebuff-agent — run one task brief through the Freebuff TUI inside tmux. +# +# Same contract as bin/free-agent (brief in, HANDOFF-REPORT.md out), so `handoff` +# can treat it as another backend. Freebuff has no headless mode, so this drives +# its TUI with tmux send-keys and watches the pane for the completion marker. +# +# freebuff-agent --brief BRIEF.md --dir ~/Projects/thing [--id slug] [--timeout 1800] [--keep] +# +# Exit: 0 done, 1 failed/timeout, 2 usage. + +set -uo pipefail + +HOME_DIR="$HOME" +STATE="${XDG_STATE_HOME:-$HOME_DIR/.local/state}/free-agent/runs" +BRIEF=""; DIR=""; ID=""; TIMEOUT=1800; KEEP=0 + +while [ $# -gt 0 ]; do + case "$1" in + --brief) BRIEF="${2:-}"; shift 2 ;; + --dir) DIR="${2:-}"; shift 2 ;; + --id) ID="${2:-}"; shift 2 ;; + --timeout) TIMEOUT="${2:-1800}"; shift 2 ;; + --keep) KEEP=1; shift ;; + -h|--help) sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "freebuff-agent: unknown option $1" >&2; exit 2 ;; + esac +done + +[ -n "$BRIEF" ] || { echo "freebuff-agent: --brief is required" >&2; exit 2; } +[ -f "$BRIEF" ] || { echo "freebuff-agent: no such brief $BRIEF" >&2; exit 2; } +[ -n "$DIR" ] || DIR="$(dirname "$BRIEF")" +[ -d "$DIR" ] || { echo "freebuff-agent: no such dir $DIR" >&2; exit 2; } + +slug() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g' | cut -c1-40; } +[ -n "$ID" ] || ID="$(slug "$(basename "$BRIEF" .md)")-$(date +%H%M%S)" + +RUN="$STATE/$ID" +mkdir -p "$RUN" +cp "$BRIEF" "$RUN/BRIEF.md" +LOG="$RUN/run.log" +SESSION="fb-$ID" +: > "$LOG" + +write_status() { printf '%s\n' "$1" > "$RUN/status.json"; } +snap() { tmux capture-pane -p -t "$SESSION" 2>/dev/null | sed -e 's/[[:space:]]*$//' >> "$LOG"; } + +write_status "{\"id\": \"$ID\", \"dir\": \"$(cd "$DIR" && pwd)\", \"state\": \"running\", \"backend\": \"freebuff\", \"startedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" + +tmux kill-session -t "$SESSION" 2>/dev/null +tmux new-session -d -s "$SESSION" -x 220 -y 55 -c "$DIR" "freebuff --cwd $(printf '%q' "$DIR")" +echo "[freebuff-agent] $ID: started tmux session $SESSION in $DIR" + +# 1. Wait for the TUI prompt to appear. +ready=0 +for _ in $(seq 1 30); do + if tmux capture-pane -p -t "$SESSION" 2>/dev/null | grep -q "Enter a coding task"; then ready=1; break; fi + sleep 2 +done +if [ "$ready" -ne 1 ]; then + snap; write_status "{\"id\": \"$ID\", \"state\": \"failed\", \"backend\": \"freebuff\", \"reason\": \"freebuff TUI never became ready\"}" + echo "[freebuff-agent] $ID: TUI never became ready" >&2 + [ "$KEEP" -eq 1 ] || tmux kill-session -t "$SESSION" 2>/dev/null + exit 1 +fi + +# 2. Send the task. Freebuff reads AGENTS.md itself; the brief has the specifics. +PROMPT="Read $RUN/BRIEF.md and complete it. Work only inside $DIR. When you are finished, write your report to $RUN/HANDOFF-REPORT.md (Summary, Files, Verified, Risks) and then reply with exactly HANDOFF-DONE." +tmux send-keys -t "$SESSION" "$PROMPT" Enter +echo "[freebuff-agent] $ID: task sent, waiting up to ${TIMEOUT}s" + +# 3. Watch the pane for the marker. +deadline=$(( $(date +%s) + TIMEOUT )) +state=failed +while [ "$(date +%s)" -lt "$deadline" ]; do + sleep 10 + pane="$(tmux capture-pane -p -t "$SESSION" 2>/dev/null)" + if printf '%s' "$pane" | grep -q "HANDOFF-DONE"; then state=done; break; fi + if ! tmux has-session -t "$SESSION" 2>/dev/null; then state=failed; break; fi +done + +snap +write_status "{\"id\": \"$ID\", \"state\": \"$state\", \"backend\": \"freebuff\", \"model\": \"freebuff/deepseek\", \"endedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\", \"report\": \"$RUN/HANDOFF-REPORT.md\"}" +[ "$KEEP" -eq 1 ] || tmux kill-session -t "$SESSION" 2>/dev/null +echo "[freebuff-agent] $ID: $state ($RUN)" +[ "$state" = "done" ] && exit 0 || exit 1 diff --git a/bin/handoff b/bin/handoff index 987d3c0..31cf603 100755 --- a/bin/handoff +++ b/bin/handoff @@ -38,12 +38,13 @@ need_id() { [ -n "${1:-}" ] || die "missing run id"; } task_file() { local id="$1" d; for d in "$RUNNING" "$QUEUE" "$DONE" "$FAILED"; do [ -f "$d/$id.json" ] && { printf '%s' "$d/$id.json"; return 0; }; done; return 1; } cmd_submit() { - local brief="" dir="" role="code" id="" + local brief="" dir="" role="code" id="" backend="free-agent" while [ $# -gt 0 ]; do case "$1" in --dir) dir="${2:-}"; shift 2 ;; --role) role="${2:-code}"; shift 2 ;; --id) id="${2:-}"; shift 2 ;; + --backend) backend="${2:-free-agent}"; shift 2 ;; -h|--help) usage; exit 0 ;; -) brief="STDIN"; shift ;; *) brief="$1"; shift ;; @@ -67,7 +68,7 @@ import json, sys, datetime path, rid, d, role, brief = sys.argv[1:6] json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "queuedAt": datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat()+"Z"}, open(path, "w"), indent=1) PY - printf 'queued %s\n dir: %s\n role: %s\n log: %s/%s/run.log\n' "$id" "$dir" "$role" "$STATE" "$id" + printf 'queued %s\n dir: %s\n role: %s\n backend: %s\n log: %s/%s/run.log\n' "$id" "$dir" "$role" "$backend" "$STATE" "$id" echo " start the daemon if it is not running: handoff daemon &" } @@ -80,7 +81,7 @@ ensure_session() { running_count() { find "$RUNNING" -maxdepth 1 -name '*.json' | wc -l | tr -d ' '; } start_task() { - local f="$1" id dir role brief + local f="$1" id dir role brief backend id="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["id"])' "$f")" dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$f")" role="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("role","code"))' "$f")" @@ -88,10 +89,16 @@ start_task() { mv "$f" "$RUNNING/$id.json" 2>/dev/null || return 0 ensure_session + local cmd + if [ "$backend" = "freebuff" ]; then + cmd="freebuff-agent --brief $(printf '%q' "$brief") --dir $(printf '%q' "$dir") --id $(printf '%q' "$id")" + else + cmd="free-agent --brief $(printf '%q' "$brief") --dir $(printf '%q' "$dir") --role $(printf '%q' "$role") --id $(printf '%q' "$id")" + fi tmux new-window -d -t "$TMUX_SESSION" -n "$id" -c "$dir" \ - "free-agent --brief $(printf '%q' "$brief") --dir $(printf '%q' "$dir") --role $(printf '%q' "$role") --id $(printf '%q' "$id"); printf '\nhandoff window finished: %s\n' \$?; sleep 2" \ + "$cmd; printf '\nhandoff window finished: %s\n' \$?; sleep 2" \ >/dev/null 2>&1 || { echo "handoff: tmux failed for $id" >&2; mv "$RUNNING/$id.json" "$FAILED/$id.json"; return 1; } - echo "[$(now)] started $id ($role) in $dir" + echo "[$(now)] started $id ($backend/$role) in $dir" } collect_finished() { @@ -139,7 +146,7 @@ cmd_list() { id="$(basename "$f" .json)" st="$STATE/$id/status.json" local model="-" - [ -f "$st" ] && model="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("model") or d.get("state","-"))' "$st" 2>/dev/null)" + [ -f "$st" ] && model="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("model") or d.get("backend") or d.get("state","-"))' "$st" 2>/dev/null)" printf '%-8s %-28s %-34s %s\n' "$d" "$id" "$model" "$(dirname "$st")" done done diff --git a/config/skills/cli/handoff/SKILL.md b/config/skills/cli/handoff/SKILL.md index 9143504..22d4c3d 100644 --- a/config/skills/cli/handoff/SKILL.md +++ b/config/skills/cli/handoff/SKILL.md @@ -40,6 +40,11 @@ handoff submit BRIEF.md --dir ~/Projects/thing --role code --id fix-tests config/runbooks. The daemon (systemd user unit `handoff.service`, tmux session `handoff`) picks it up within 5 s and runs it in a new window. +Add `--backend freebuff` to hand that task to **Freebuff** instead (the +ad-supported agent on the account already logged in; it drives its TUI in tmux +via `bin/freebuff-agent`). Freebuff ignores the pool and its budgets entirely, so +use it when the free API lanes are spent or the task needs a long session. + ```sh handoff list # queue / running / done / failed handoff log fix-tests 60 # last 60 lines of the worker's transcript @@ -79,3 +84,8 @@ Ns" reply it sleeps the delay and retries the same model before spending another lane. Free tiers are small: Gemini Flash is ~5 requests/minute, which a tool loop can burn in one turn — expect waits, keep briefs short, and prefer `--role code` tasks with few steps. + +Lane health: `free-agent --probe` pings every lane and prints OK / BUSY / DEAD. +`handoff-probe.timer` runs it Mondays at 08:00 and appends to +`~/.local/state/free-agent/probe.log`; the unit only fails for DEAD lanes (retired +slug, bad key, broken template), which is the signal that the pool needs an edit. From 5accb686d3db19c7c5b10cbe639294b4a1f5344f Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 22:04:43 -0700 Subject: [PATCH 31/40] free-agent: pool matches reality, plus a ledger generator Three lanes 404'd (minimax-m3.1-flash, nemotron-3-super, cohere north-mini-code), one returned 400 on every attempt (qwen3.8-27b), and the two lanes that actually perform best (nemotron-3-ultra-550b, nemotron-3.5-lightning) were not in the pool at all. Each surviving lane now carries a note saying what it was measured doing. free-agent-ledger turns the run history into the table the wiki page quotes, so the numbers are regenerated rather than remembered. --- bin/free-agent-ledger | 88 ++++++++++++++++++++++++++++++++++ config/free-agent/pool.json | 96 ++++++++++++++++++------------------- 2 files changed, 134 insertions(+), 50 deletions(-) create mode 100755 bin/free-agent-ledger diff --git a/bin/free-agent-ledger b/bin/free-agent-ledger new file mode 100755 index 0000000..c9e9aba --- /dev/null +++ b/bin/free-agent-ledger @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""free-agent-ledger — turn the run history into a markdown performance table. + +Reads every finished run under ~/.local/state/free-agent/runs/*/status.json and +reports, per model, how often it was tried and how it went. Every *attempt* is an +observation, including failed ones, so a model that needed two tries shows that. + + free-agent-ledger # markdown tables + free-agent-ledger --json # same data, for tooling + +Paste the output into the wiki page homelab/reference/clients/free-model-performance +rather than writing numbers from memory; the sample is small and it grows every run. +""" +import json +import os +import statistics +import sys +from collections import defaultdict + +RUNS = os.path.expanduser("~/.local/state/free-agent/runs") + + +def load(): + rows = [] + for name in sorted(os.listdir(RUNS)): + path = os.path.join(RUNS, name, "status.json") + if not os.path.exists(path): + continue + try: + d = json.load(open(path)) + except Exception: + continue + attempts = d.get("attempts") or [] + if not attempts: + rows.append({"id": d.get("id", name), "role": d.get("role") or "?", + "model": d.get("model") or "?", "ok": d.get("state") == "done", + "secs": d.get("secs"), "tries": 0, "rate_limited": False}) + continue + for a in attempts: + rows.append({ + "id": d.get("id", name), + "role": d.get("role") or "?", + "model": a.get("model") or d.get("model") or "?", + "ok": bool(a.get("ok")), + "secs": a.get("secs"), + "tries": a.get("tries") or 1, + "rate_limited": bool(a.get("rateLimited")), + }) + return rows + + +def main(): + rows = load() + if "--json" in sys.argv: + print(json.dumps(rows, indent=1)) + return + + by_model = defaultdict(list) + for r in rows: + by_model[r["model"]].append(r) + + print("### Measured attempt history\n") + print("| Model | Attempts | Succeeded | Failed | Rate-limited | Median time | Roles |") + print("|---|---|---|---|---|---|---|") + for model, rs in sorted(by_model.items(), key=lambda kv: -len(kv[1])): + secs = [r["secs"] for r in rs if isinstance(r["secs"], (int, float))] + roles = ", ".join(sorted({r["role"] for r in rs})) + print("| `%s` | %d | %d | %d | %d | %s | %s |" % ( + model, len(rs), sum(r["ok"] for r in rs), sum(not r["ok"] for r in rs), + sum(r["rate_limited"] for r in rs), + ("%.0f s" % statistics.median(secs)) if secs else "n/a", roles)) + + print("\n### Runs\n") + print("| Run | Role | Model | Tries | Time | Outcome |") + print("|---|---|---|---|---|---|") + for r in sorted(rows, key=lambda x: x["id"]): + print("| `%s` | %s | `%s` | %d | %s | %s |" % ( + r["id"], r["role"], r["model"], r["tries"], + ("%.0f s" % r["secs"]) if isinstance(r["secs"], (int, float)) else "n/a", + "ok" if r["ok"] else ("rate-limited" if r["rate_limited"] else "failed"))) + + n = len(by_model) + print("\n*%d observation(s) across %d model(s). Small samples: treat a single " + "failure as a hint, not a verdict.*" % (len(rows), n)) + + +if __name__ == "__main__": + main() diff --git a/config/free-agent/pool.json b/config/free-agent/pool.json index c68d4cc..ba23ea0 100644 --- a/config/free-agent/pool.json +++ b/config/free-agent/pool.json @@ -1,17 +1,6 @@ { - "$comment": "Free-model worker pool for `free-agent` / `handoff`. Limits are conservative published free-tier numbers (Nov 2026); free-agent enforces rpm/rpd locally so a burst never trips a provider's 429. Order = preference: first model that has budget and a matching role wins.", + "$comment": "Free-model worker pool for `free-agent` / `handoff`. Limits are conservative published free-tier numbers; free-agent enforces rpm/rpd locally so a busy day fails over instead of hammering one provider. Availability probed and lanes calibrated 2026-11-29 -- see wiki homelab/reference/clients/free-model-performance before trusting a lane with a new kind of task.", "models": [ - { - "id": "google/gemini-3.5-flash", - "roles": [ - "code", - "review", - "infra" - ], - "rpm": 4, - "rpd": 200, - "note": "Free tier workhorse: 1M context, strong tool use, per-project limits shown in AI Studio." - }, { "id": "zai/glm-4.5-flash", "roles": [ @@ -20,28 +9,7 @@ ], "rpm": 10, "rpd": 200, - "note": "Permanent $0 Flash model on Z.ai; fastest of the four in practice." - }, - { - "id": "openrouter/nvidia/nemotron-3.5-lightning:free", - "roles": [ - "code", - "review", - "infra" - ], - "rpm": 18, - "rpd": 45, - "note": "OpenRouter :free, 1M context, verified reachable 2026-11-29." - }, - { - "id": "openrouter/nvidia/nemotron-3-ultra-550b-a55b:free", - "roles": [ - "code", - "review" - ], - "rpm": 18, - "rpd": 45, - "note": "OpenRouter :free, 1M context, larger sibling of the lightning lane." + "note": "Permanent $0 Flash model. Scored 30/30 on the roman-numeral calibration task; fastest reliable code lane." }, { "id": "google/gemini-3.1-flash-lite", @@ -49,30 +17,58 @@ "code", "review" ], - "rpm": 4, + "rpm": 12, "rpd": 800, - "note": "Cheap second Gemini lane for small edits and reviews." + "note": "Scored 30/30 on the calibration task. Cheapest lane with a large daily budget." }, { - "id": "cohere/north-mini-code-1.0", - "roles": [ - "code", - "review" - ], - "rpm": 18, - "rpd": 30, - "note": "Existing Cohere trial key: 1000 calls/month, so ~30/day." - }, - { - "id": "groq/openai/gpt-oss-120b", + "id": "google/gemini-3.5-flash", "roles": [ "code", "review", "infra" ], - "rpm": 6, - "rpd": 150, - "note": "Groq free is TPM-bound (~8K tokens/min on gpt-oss-120b): one agent turn with the system prompt and tool schemas nearly fills it, so this lane is last resort for small prompts only." + "rpm": 8, + "rpd": 200, + "note": "Free-tier workhorse: 1M context, strong tool use. 429s in bursts when several lanes share the project." + }, + { + "id": "openrouter/nvidia/nemotron-3-ultra-550b-a55b:free", + "roles": [ + "review", + "infra" + ], + "rpm": 18, + "rpd": 45, + "note": "Best writer in the pool: produced the Decypharr verdict with correct structure and arithmetic. Needed two attempts once (first came back empty)." + }, + { + "id": "openrouter/nvidia/nemotron-3.5-lightning:free", + "roles": [ + "review" + ], + "rpm": 18, + "rpd": 45, + "note": "Good at reworking tables from a supplied CSV; carried stale sentences over from the previous draft, so review its diff." + }, + { + "id": "groq/openai/gpt-oss-120b", + "roles": [ + "code", + "review" + ], + "rpm": 28, + "rpd": 900, + "note": "Very fast LPU, 131K context, but the free tier is token-per-minute tight (~6-8K TPM): 429s on anything but a short brief." + }, + { + "id": "cohere/north-mini-code-1.0", + "roles": [ + "code" + ], + "rpm": 18, + "rpd": 30, + "note": "23/30 on the calibration task: over-strict input validation (rejected valid IV/XL/CD/CM). Fine for drafts, check edge cases." } ] } From 8d73a773b3cef55420f614c643fa1cc9a87dd6b0 Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 22:05:28 -0700 Subject: [PATCH 32/40] handoff: survive restarts, route backends, trust the TUI - submit stores the backend in the task JSON (--backend freebuff works again). - start_task reads it; the freebuff path calls freebuff-agent. - ensure_session starts the tmux server in its own transient scope, so a 'systemctl --user restart handoff' no longer kills every running worker. - requeue_orphans puts tasks back in the queue when their window or process is gone (daemon crash, killed window, tmux server restart); 'handoff list' shows them as orphan instead of running forever. - freebuff-agent only believes the task is finished when the marker stands alone on a line AND the TUI is idle, because the prompt we send contains the marker. --- bin/freebuff-agent | 24 +++++++++++++++++++++--- bin/handoff | 38 +++++++++++++++++++++++++++++++++----- 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/bin/freebuff-agent b/bin/freebuff-agent index 146a959..fc08940 100755 --- a/bin/freebuff-agent +++ b/bin/freebuff-agent @@ -69,14 +69,32 @@ PROMPT="Read $RUN/BRIEF.md and complete it. Work only inside $DIR. When you are tmux send-keys -t "$SESSION" "$PROMPT" Enter echo "[freebuff-agent] $ID: task sent, waiting up to ${TIMEOUT}s" -# 3. Watch the pane for the marker. +# 3. Watch the pane. Two traps here: the task text we just sent contains the marker +# (so a plain grep matches our own prompt), and the TUI keeps a "working..." line +# while it thinks. So: ignore the first 30 s, require the marker on a line of its +# own, and require the TUI to be idle (prompt back, no "working...") to believe it. deadline=$(( $(date +%s) + TIMEOUT )) +started=$(date +%s) state=failed +idle_hits=0 while [ "$(date +%s)" -lt "$deadline" ]; do sleep 10 - pane="$(tmux capture-pane -p -t "$SESSION" 2>/dev/null)" - if printf '%s' "$pane" | grep -q "HANDOFF-DONE"; then state=done; break; fi if ! tmux has-session -t "$SESSION" 2>/dev/null; then state=failed; break; fi + pane="$(tmux capture-pane -p -t "$SESSION" 2>/dev/null)" + [ $(( $(date +%s) - started )) -lt 30 ] && continue + marker=0 + printf '%s\n' "$pane" | sed 's/[[:space:]]*$//' | grep -qx "HANDOFF-DONE" && marker=1 + busy=0 + printf '%s' "$pane" | grep -q "working\.\.\." && busy=1 + prompt=0 + printf '%s' "$pane" | grep -q "Enter a coding task" && prompt=1 + if [ "$marker" -eq 1 ] && [ "$busy" -eq 0 ]; then state=done; break; fi + if [ "$busy" -eq 0 ] && [ "$prompt" -eq 1 ]; then + idle_hits=$(( idle_hits + 1 )) + [ "$idle_hits" -ge 2 ] && { state=done; break; } # finished, marker missing + else + idle_hits=0 + fi done snap diff --git a/bin/handoff b/bin/handoff index 31cf603..65de6f9 100755 --- a/bin/handoff +++ b/bin/handoff @@ -63,10 +63,12 @@ cmd_submit() { local bpath="$DATA/$id.brief.md" printf '%s\n' "$body" > "$bpath" - python3 - "$QUEUE/$id.json" "$id" "$dir" "$role" "$bpath" <<'PY' + python3 - "$QUEUE/$id.json" "$id" "$dir" "$role" "$bpath" "$backend" <<'PY' import json, sys, datetime -path, rid, d, role, brief = sys.argv[1:6] -json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "queuedAt": datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat()+"Z"}, open(path, "w"), indent=1) +path, rid, d, role, brief, backend = sys.argv[1:7] +json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "backend": backend, + "queuedAt": datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat()+"Z"}, + open(path, "w"), indent=1) PY printf 'queued %s\n dir: %s\n role: %s\n backend: %s\n log: %s/%s/run.log\n' "$id" "$dir" "$role" "$backend" "$STATE" "$id" echo " start the daemon if it is not running: handoff daemon &" @@ -74,7 +76,12 @@ PY ensure_session() { tmux has-session -t "$TMUX_SESSION" 2>/dev/null && return 0 - tmux new-session -d -s "$TMUX_SESSION" -n workers -c "$HOME_DIR" + # Start the tmux server in its own transient scope: a server started inside this + # unit's cgroup dies with a `systemctl --user restart handoff`, taking every + # running worker's window with it. + systemd-run --user --scope --quiet --collect \ + tmux new-session -d -s "$TMUX_SESSION" -n workers -c "$HOME_DIR" 2>/dev/null \ + || tmux new-session -d -s "$TMUX_SESSION" -n workers -c "$HOME_DIR" tmux set-option -t "$TMUX_SESSION" history-limit 20000 >/dev/null 2>&1 } @@ -86,6 +93,7 @@ start_task() { dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$f")" role="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("role","code"))' "$f")" brief="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["brief"])' "$f")" + backend="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("backend","free-agent"))' "$f")" mv "$f" "$RUNNING/$id.json" 2>/dev/null || return 0 ensure_session @@ -120,14 +128,30 @@ collect_finished() { done } +# A task can land in running/ and then lose its worker (daemon restart, killed +# window, tmux server death). Put it back in the queue instead of leaving it +# "running" forever. +requeue_orphans() { + local f id + for f in "$RUNNING"/*.json; do + [ -e "$f" ] || continue + id="$(basename "$f" .json)" + tmux list-windows -t "$TMUX_SESSION" -F '#{window_name}' 2>/dev/null | grep -qx "$id" && continue + pgrep -f -- "--id $id" >/dev/null 2>&1 && continue + mv "$f" "$QUEUE/$id.json" 2>/dev/null && echo "[$(now)] requeued orphan $id" + done +} + cmd_daemon() { ensure_session echo "[$(now)] handoff daemon: queue=$QUEUE parallel=$MAX_PARALLEL session=$TMUX_SESSION" + requeue_orphans local unpaused="$DATA/pause" trap 'echo "[$(now)] handoff daemon: stopping"; exit 0' INT TERM while :; do if [ ! -f "$unpaused" ]; then collect_finished + requeue_orphans for f in "$QUEUE"/*.json; do [ -e "$f" ] || continue [ "$(running_count)" -lt "$MAX_PARALLEL" ] || break @@ -147,7 +171,11 @@ cmd_list() { st="$STATE/$id/status.json" local model="-" [ -f "$st" ] && model="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("model") or d.get("backend") or d.get("state","-"))' "$st" 2>/dev/null)" - printf '%-8s %-28s %-34s %s\n' "$d" "$id" "$model" "$(dirname "$st")" + local tag="$d" + if [ "$d" = "running" ] && ! tmux list-windows -t "$TMUX_SESSION" -F '#{window_name}' 2>/dev/null | grep -qx "$id"; then + tag="orphan" + fi + printf '%-8s %-28s %-34s %s\n' "$tag" "$id" "$model" "$(dirname "$st")" done done } From bf0170070e4e5585fc67e42a18d2c8c3b11d519b Mon Sep 17 00:00:00 2001 From: ziadarafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 23:18:01 -0700 Subject: [PATCH 33/40] tools: version the free-model calibration graders Both graders, with the reference-implementation note: the first two scoreboards were grader bugs (a fixture mounting a path that does not exist, and a boundary case reusing the previous case's fixture), not model failures. --- tools/free-model-calibration/BRIEF-code.md | 27 ++++++++++++ tools/free-model-calibration/BRIEF-infra.md | 27 ++++++++++++ tools/free-model-calibration/README.md | 17 ++++++++ .../free-model-calibration/spec_test-code.py | 24 +++++++++++ .../free-model-calibration/spec_test-infra.sh | 42 +++++++++++++++++++ 5 files changed, 137 insertions(+) create mode 100644 tools/free-model-calibration/BRIEF-code.md create mode 100644 tools/free-model-calibration/BRIEF-infra.md create mode 100644 tools/free-model-calibration/README.md create mode 100644 tools/free-model-calibration/spec_test-code.py create mode 100755 tools/free-model-calibration/spec_test-infra.sh diff --git a/tools/free-model-calibration/BRIEF-code.md b/tools/free-model-calibration/BRIEF-code.md new file mode 100644 index 0000000..6810323 --- /dev/null +++ b/tools/free-model-calibration/BRIEF-code.md @@ -0,0 +1,27 @@ +# Task: write an ops health-check script + +Create `disk-guard.sh` (bash, must run on Debian) that reports filesystem usage +for a path and exits with a status that cron and monitoring can use. + + disk-guard.sh <path> [warn_pct] [crit_pct] + +- Defaults: `warn_pct=80`, `crit_pct=90`. Both are whole percentages. +- Usage percent comes from `df -P <path>` (the `Capacity` column, e.g. `87%`). +- **Testability requirement:** if the environment variable + `DISK_GUARD_DF_FIXTURE` is set, read the `df` output from that file instead of + running `df`. This is how the grader supplies fixed numbers — it is a hard + requirement, not a suggestion. +- Output, exactly one line on stdout: + `OK <pct>% <path>` below warn, `WARN <pct>% <path>` at or above warn, + `CRIT <pct>% <path>` at or above crit. +- Exit status: `0` OK, `1` warn, `2` crit, `3` the path does not exist, + `4` bad arguments (non-numeric threshold, or warn_pct > crit_pct). +- Prefix any message on stderr with `disk-guard:`. + +`spec_test.sh` in this directory is the grader: 11 checks, covering the +threshold boundaries, custom thresholds, bad arguments, a missing path and one +live `df` call against `/`. **Do not modify or delete it** — make it pass: + + ./spec_test.sh + +Only create `disk-guard.sh`. diff --git a/tools/free-model-calibration/BRIEF-infra.md b/tools/free-model-calibration/BRIEF-infra.md new file mode 100644 index 0000000..6810323 --- /dev/null +++ b/tools/free-model-calibration/BRIEF-infra.md @@ -0,0 +1,27 @@ +# Task: write an ops health-check script + +Create `disk-guard.sh` (bash, must run on Debian) that reports filesystem usage +for a path and exits with a status that cron and monitoring can use. + + disk-guard.sh <path> [warn_pct] [crit_pct] + +- Defaults: `warn_pct=80`, `crit_pct=90`. Both are whole percentages. +- Usage percent comes from `df -P <path>` (the `Capacity` column, e.g. `87%`). +- **Testability requirement:** if the environment variable + `DISK_GUARD_DF_FIXTURE` is set, read the `df` output from that file instead of + running `df`. This is how the grader supplies fixed numbers — it is a hard + requirement, not a suggestion. +- Output, exactly one line on stdout: + `OK <pct>% <path>` below warn, `WARN <pct>% <path>` at or above warn, + `CRIT <pct>% <path>` at or above crit. +- Exit status: `0` OK, `1` warn, `2` crit, `3` the path does not exist, + `4` bad arguments (non-numeric threshold, or warn_pct > crit_pct). +- Prefix any message on stderr with `disk-guard:`. + +`spec_test.sh` in this directory is the grader: 11 checks, covering the +threshold boundaries, custom thresholds, bad arguments, a missing path and one +live `df` call against `/`. **Do not modify or delete it** — make it pass: + + ./spec_test.sh + +Only create `disk-guard.sh`. diff --git a/tools/free-model-calibration/README.md b/tools/free-model-calibration/README.md new file mode 100644 index 0000000..10f227a --- /dev/null +++ b/tools/free-model-calibration/README.md @@ -0,0 +1,17 @@ +# Free-model calibration + +Graders used to score free-tier lanes on a task whose pass condition we control. +A worker is told not to modify the grader; the grader is written here and copied +into the worker's directory. + +| Files | Task | Lane results (2026-11-29) | +|---|---|---| +| `BRIEF-code.md`, `spec_test-code.py` | roman numerals, 30 pytest cases | zai 30/30, gemini-3.1-flash-lite 30/30, cohere-1.0 23/30, groq/gpt-oss-120b 0/30 (429) | +| `BRIEF-infra.md`, `spec_test-infra.sh` | `disk-guard.sh`, 11 shell cases | zai 11/11, gemini-3.1-flash-lite 11/11 | + +Run one lane: `free-agent --brief BRIEF-<x>.md --dir <lane dir> --role <code|infra> --model <id>`. + +**Validate the grader before trusting a score.** Write a reference implementation +and confirm it scores full marks; both of these graders shipped bugs first (a +fixture pointing at a path that does not exist, and a case reusing the previous +case's fixture), and the wrong grader blamed the models for both. diff --git a/tools/free-model-calibration/spec_test-code.py b/tools/free-model-calibration/spec_test-code.py new file mode 100644 index 0000000..2799f51 --- /dev/null +++ b/tools/free-model-calibration/spec_test-code.py @@ -0,0 +1,24 @@ +"""Grader for the roman-numeral calibration task. Not to be modified by workers.""" +import pytest +from roman import to_roman, from_roman + +PAIRS = [(1, "I"), (4, "IV"), (9, "IX"), (14, "XIV"), (40, "XL"), (90, "XC"), + (400, "CD"), (900, "CM"), (1994, "MCMXCIV"), (2024, "MMXXIV"), (3999, "MMMCMXCIX")] + +@pytest.mark.parametrize("n,s", PAIRS) +def test_to_roman(n, s): + assert to_roman(n) == s + +@pytest.mark.parametrize("n,s", PAIRS) +def test_roundtrip(n, s): + assert from_roman(s) == n + +@pytest.mark.parametrize("bad", [0, -1, 4000]) +def test_to_roman_out_of_range(bad): + with pytest.raises(ValueError): + to_roman(bad) + +@pytest.mark.parametrize("bad", ["", "IIII", "VV", "ABC", "MMMM"]) +def test_from_roman_invalid(bad): + with pytest.raises(ValueError): + from_roman(bad) diff --git a/tools/free-model-calibration/spec_test-infra.sh b/tools/free-model-calibration/spec_test-infra.sh new file mode 100755 index 0000000..eeadf53 --- /dev/null +++ b/tools/free-model-calibration/spec_test-infra.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Grader for the disk-guard calibration task. Written by the primary agent. +# The worker may not modify this file. +set -uo pipefail +S=${SCRIPT:-./disk-guard.sh} +pass=0; fail=0 +check() { # name expected_exit expected_out_substr -- args... + local name=$1 eexit=$2 esub=$3; shift 4 + out=$("$S" "$@" 2>/dev/null); rc=$? + if [ "$rc" = "$eexit" ] && { [ -z "$esub" ] || printf '%s' "$out" | grep -qF -- "$esub"; }; then + pass=$((pass+1)); printf 'ok %-42s rc=%s out=%s\n' "$name" "$rc" "$(printf '%s' "$out" | head -c 40)" + else + fail=$((fail+1)); printf 'FAIL %-42s want rc=%s/%s got rc=%s/%s\n' "$name" "$eexit" "$esub" "$rc" "$(printf '%s' "$out" | head -c 40)" + fi +} +mk_fixture() { printf '%s\n' "Filesystem 1024-blocks Used Available Capacity Mounted on" "$1 $2 $3 $4 $5" > "/tmp/dgfx.$$"; echo "/tmp/dgfx.$$"; } +trap 'rm -f /tmp/dgfx.*' EXIT +export DISK_GUARD_DF_FIXTURE=$(mk_fixture / 1000 500 500 50%) +check "50% under default warn" 0 "OK 50%" -- / +export DISK_GUARD_DF_FIXTURE=$(mk_fixture / 1000 800 200 80%) +check "80% hits default warn" 1 "WARN 80%" -- / +export DISK_GUARD_DF_FIXTURE=$(mk_fixture / 1000 950 50 95%) +check "95% hits default crit" 2 "CRIT 95%" -- / +export DISK_GUARD_DF_FIXTURE=$(mk_fixture / 1000 650 350 65%) +check "65% with warn=60 crit=70" 1 "WARN 65%" -- / 60 70 +check "65% with warn=70 crit=90" 0 "OK 65%" -- / 70 90 +export DISK_GUARD_DF_FIXTURE=$(mk_fixture / 1000 800 200 80%) +check "exactly at warn is WARN" 1 "WARN 80%" -- / 80 90 +export DISK_GUARD_DF_FIXTURE=$(mk_fixture / 1000 1000 0 100%) +check "100% is CRIT" 2 "CRIT 100%" -- / +check "warn greater than crit" 4 "" -- / 90 80 +check "non-numeric threshold" 4 "" -- / abc 90 +unset DISK_GUARD_DF_FIXTURE +check "missing path" 3 "" -- /nonexistent-path-xyz +out=$( "$S" / 2>/dev/null ); rc=$? +if { [ "$rc" = 0 ] || [ "$rc" = 1 ]; } && printf '%s' "$out" | grep -qE "^(OK|WARN) [0-9]+% /$"; then + pass=$((pass+1)); printf 'ok %-42s rc=%s out=%s\n' "real df on /" "$rc" "$out" +else + fail=$((fail+1)); printf 'FAIL %-42s rc=%s out=%s\n' "real df on /" "$rc" "$out" +fi +printf '\n%d passed, %d failed\n' "$pass" "$fail" +[ "$fail" -eq 0 ] From 7669aebd145328b900496bc42ce7f7fd307dd746 Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 23:22:09 -0700 Subject: [PATCH 34/40] freebuff-agent: only the marker ends a run An idle prompt with no marker is not completion: the TUI sits idle while it waits for the model, and the 'idle for two polls' shortcut ended a run 20 s in with nothing done. Wait for HANDOFF-DONE (or the timeout). --- bin/freebuff-agent | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/bin/freebuff-agent b/bin/freebuff-agent index fc08940..ce30574 100755 --- a/bin/freebuff-agent +++ b/bin/freebuff-agent @@ -76,7 +76,6 @@ echo "[freebuff-agent] $ID: task sent, waiting up to ${TIMEOUT}s" deadline=$(( $(date +%s) + TIMEOUT )) started=$(date +%s) state=failed -idle_hits=0 while [ "$(date +%s)" -lt "$deadline" ]; do sleep 10 if ! tmux has-session -t "$SESSION" 2>/dev/null; then state=failed; break; fi @@ -86,15 +85,9 @@ while [ "$(date +%s)" -lt "$deadline" ]; do printf '%s\n' "$pane" | sed 's/[[:space:]]*$//' | grep -qx "HANDOFF-DONE" && marker=1 busy=0 printf '%s' "$pane" | grep -q "working\.\.\." && busy=1 - prompt=0 - printf '%s' "$pane" | grep -q "Enter a coding task" && prompt=1 if [ "$marker" -eq 1 ] && [ "$busy" -eq 0 ]; then state=done; break; fi - if [ "$busy" -eq 0 ] && [ "$prompt" -eq 1 ]; then - idle_hits=$(( idle_hits + 1 )) - [ "$idle_hits" -ge 2 ] && { state=done; break; } # finished, marker missing - else - idle_hits=0 - fi + # An idle prompt with no marker is NOT completion: the TUI sits idle while it waits + # for the model to answer, which cost one run its whole task. Only the marker ends it. done snap From 81b99618b5dc953f77d93f4adcb63e1f3ff10841 Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 23:32:38 -0700 Subject: [PATCH 35/40] handoff: refuse the freebuff backend, and say why Freebuff's usage policy rejects prompts that read as a job handed to another agent ('Driven by another agent'), does not send them to the model, and counts the attempt as a strike on the account. The queue must not drive it, so submit refuses the backend with that explanation and the skill points at interactive use instead. --- bin/handoff | 9 +++++++++ config/skills/cli/handoff/SKILL.md | 8 ++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/bin/handoff b/bin/handoff index 65de6f9..6b7989f 100755 --- a/bin/handoff +++ b/bin/handoff @@ -59,6 +59,15 @@ cmd_submit() { if [ "$brief" = "STDIN" ]; then body="$(cat)"; else [ -f "$brief" ] || die "no such brief: $brief"; body="$(cat "$brief")"; fi [ -n "$body" ] || die "brief is empty" + # Freebuff refuses prompts that read as a job handed to another agent and counts + # them as strikes on the account, so this pipeline must not drive it. + if [ "$backend" = "freebuff" ]; then + die "Freebuff is not available to this queue: its usage policy blocks agent-initiated +job handoffs ('reads as a job handed to other agents') and counts an attempt as a +strike. Use it interactively, by hand. Queue the task on an API lane instead +(omit --backend, or --backend free-agent)." + fi + [ -n "$id" ] || id="$(slugify "$(head -c 60 <<<"$body" | tr '\n' ' ')")-$(date +%H%M%S)" local bpath="$DATA/$id.brief.md" printf '%s\n' "$body" > "$bpath" diff --git a/config/skills/cli/handoff/SKILL.md b/config/skills/cli/handoff/SKILL.md index 22d4c3d..24976f3 100644 --- a/config/skills/cli/handoff/SKILL.md +++ b/config/skills/cli/handoff/SKILL.md @@ -40,10 +40,10 @@ handoff submit BRIEF.md --dir ~/Projects/thing --role code --id fix-tests config/runbooks. The daemon (systemd user unit `handoff.service`, tmux session `handoff`) picks it up within 5 s and runs it in a new window. -Add `--backend freebuff` to hand that task to **Freebuff** instead (the -ad-supported agent on the account already logged in; it drives its TUI in tmux -via `bin/freebuff-agent`). Freebuff ignores the pool and its budgets entirely, so -use it when the free API lanes are spent or the task needs a long session. +**Do not queue work to Freebuff.** Its usage policy blocks prompts that read as a job +handed to another agent ("Driven by another agent"), refuses to send them to the model, +and counts each attempt as a strike on the account. `handoff submit --backend freebuff` +refuses for that reason. Freebuff is for interactive, human-driven use only ```sh handoff list # queue / running / done / failed From c2499969f24132c436e44b3c60c34f33fd0c7112 Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sat, 28 Nov 2026 23:44:04 -0700 Subject: [PATCH 36/40] handoff: policy gate for delegated work Three safeguards, because a queue that can drive any endpoint will eventually drive the wrong one: - every pool lane now declares usage=developer-api plus its terms URL; free-agent refuses a lane without it, even when forced with --model (Freebuff's client refused an agent-initiated brief and counted a strike, which is what this prevents); - handoff submit refuses a brief containing an API key or private key, since free tiers may train on prompts; - the skill documents the gate: developer APIs only, nothing private in a brief, never rephrase past a block. --- bin/free-agent | 9 ++++++++ bin/handoff | 9 ++++++++ config/free-agent/pool.json | 37 +++++++++++++++++++++++------- config/skills/cli/handoff/SKILL.md | 21 +++++++++++++++++ 4 files changed, 68 insertions(+), 8 deletions(-) diff --git a/bin/free-agent b/bin/free-agent index b741891..202fffa 100755 --- a/bin/free-agent +++ b/bin/free-agent @@ -87,11 +87,16 @@ function markExhausted(b, id) { const pool = JSON.parse(readFileSync(POOL, "utf8")).models; +// Only developer APIs are delegable. A consumer app polices its own terms and treats +// an agent-driven prompt as a violation; driving one is not something a queue may do. +const POLICY_OK = (m) => m.usage === "developer-api"; + function pick(role, skip) { const b = loadBudget(); for (const m of pool) { if (skip.has(m.id)) continue; if (!(m.roles || []).includes(role)) continue; + if (!POLICY_OK(m)) continue; const u = usageOf(b, m.id); if (u.exhausted) continue; if (u.day >= m.rpd) continue; @@ -184,6 +189,10 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { let model; if (opts.model) { model = pool.find((m) => m.id === opts.model) || { id: opts.model, roles: [opts.role], rpd: 1e9, rpm: 1e9 }; + if (!POLICY_OK(model)) { + console.error(`free-agent: ${model.id} is not marked usage=developer-api in the pool; refusing to drive it (see the policy note in pool.json)`); + process.exit(2); + } } else { model = pick(opts.role, skip); if (!model) break; diff --git a/bin/handoff b/bin/handoff index 6b7989f..e164b8b 100755 --- a/bin/handoff +++ b/bin/handoff @@ -68,6 +68,15 @@ strike. Use it interactively, by hand. Queue the task on an API lane instead (omit --backend, or --backend free-agent)." fi + # A brief goes to a third-party API whose free tier may train on it, and whose terms + # govern what may be sent. Refuse anything that looks like a credential: a leaked key + # in a free-tier prompt is unrecoverable. + if printf '%s' "$body" | grep -qE '(sk-[A-Za-z0-9_-]{16,}|gsk_[A-Za-z0-9]{16,}|AIza[0-9A-Za-z_-]{30,}|AQ\.[A-Za-z0-9_-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|ghp_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})'; then + die "the brief looks like it contains a credential (API key or private key). Free tiers may +train on prompts and the terms of each lane govern what may be sent. Move the value into +secretctl and reference the name instead." + fi + [ -n "$id" ] || id="$(slugify "$(head -c 60 <<<"$body" | tr '\n' ' ')")-$(date +%H%M%S)" local bpath="$DATA/$id.brief.md" printf '%s\n' "$body" > "$bpath" diff --git a/config/free-agent/pool.json b/config/free-agent/pool.json index ba23ea0..7314f9c 100644 --- a/config/free-agent/pool.json +++ b/config/free-agent/pool.json @@ -1,5 +1,5 @@ { - "$comment": "Free-model worker pool for `free-agent` / `handoff`. Limits are conservative published free-tier numbers; free-agent enforces rpm/rpd locally so a busy day fails over instead of hammering one provider. Availability probed and lanes calibrated 2026-11-29 -- see wiki homelab/reference/clients/free-model-performance before trusting a lane with a new kind of task.", + "$comment": "Free-model worker pool for `free-agent` / `handoff`. Limits are conservative published free-tier numbers (Nov 2026). Every lane must be a developer API (`usage: developer-api`): free-agent refuses to run a lane that is not, because consumer apps police their own terms and count strikes. Never put a credential or private data in a brief - free tiers may train on it.", "models": [ { "id": "zai/glm-4.5-flash", @@ -9,7 +9,10 @@ ], "rpm": 10, "rpd": 200, - "note": "Permanent $0 Flash model. Scored 30/30 on the roman-numeral calibration task; fastest reliable code lane." + "note": "Permanent $0 Flash model. Scored 30/30 on the roman-numeral calibration task; fastest reliable code lane.", + "usage": "developer-api", + "terms": "https://chat.z.ai/terms", + "policy": "Developer API; free -flash ids only." }, { "id": "google/gemini-3.1-flash-lite", @@ -19,7 +22,10 @@ ], "rpm": 12, "rpd": 800, - "note": "Scored 30/30 on the calibration task. Cheapest lane with a large daily budget." + "note": "Scored 30/30 on the calibration task. Cheapest lane with a large daily budget.", + "usage": "developer-api", + "terms": "https://ai.google.dev/gemini-api/terms", + "policy": "Unpaid quota: prompts may be used to improve Google products, so nothing private goes in a brief." }, { "id": "google/gemini-3.5-flash", @@ -30,7 +36,10 @@ ], "rpm": 8, "rpd": 200, - "note": "Free-tier workhorse: 1M context, strong tool use. 429s in bursts when several lanes share the project." + "note": "Free-tier workhorse: 1M context, strong tool use. 429s in bursts when several lanes share the project.", + "usage": "developer-api", + "terms": "https://ai.google.dev/gemini-api/terms", + "policy": "Unpaid quota: prompts may be used to improve Google products, so nothing private goes in a brief." }, { "id": "openrouter/nvidia/nemotron-3-ultra-550b-a55b:free", @@ -40,7 +49,10 @@ ], "rpm": 18, "rpd": 45, - "note": "Best writer in the pool: produced the Decypharr verdict with correct structure and arithmetic. Needed two attempts once (first came back empty)." + "note": "Best writer in the pool: produced the Decypharr verdict with correct structure and arithmetic. Needed two attempts once (first came back empty).", + "usage": "developer-api", + "terms": "https://openrouter.ai/terms", + "policy": "Developer API; free slugs route to providers with their own data policies." }, { "id": "openrouter/nvidia/nemotron-3.5-lightning:free", @@ -49,7 +61,10 @@ ], "rpm": 18, "rpd": 45, - "note": "Good at reworking tables from a supplied CSV; carried stale sentences over from the previous draft, so review its diff." + "note": "Good at reworking tables from a supplied CSV; carried stale sentences over from the previous draft, so review its diff.", + "usage": "developer-api", + "terms": "https://openrouter.ai/terms", + "policy": "Developer API; free slugs route to providers with their own data policies." }, { "id": "groq/openai/gpt-oss-120b", @@ -59,7 +74,10 @@ ], "rpm": 28, "rpd": 900, - "note": "Very fast LPU, 131K context, but the free tier is token-per-minute tight (~6-8K TPM): 429s on anything but a short brief." + "note": "Very fast LPU, 131K context, but the free tier is token-per-minute tight (~6-8K TPM): 429s on anything but a short brief.", + "usage": "developer-api", + "terms": "https://groq.com/terms-of-service", + "policy": "Developer API. Their ToS bans scraping the groq.com website, not API calls." }, { "id": "cohere/north-mini-code-1.0", @@ -68,7 +86,10 @@ ], "rpm": 18, "rpd": 30, - "note": "23/30 on the calibration task: over-strict input validation (rejected valid IV/XL/CD/CM). Fine for drafts, check edge cases." + "note": "23/30 on the calibration task: over-strict input validation (rejected valid IV/XL/CD/CM). Fine for drafts, check edge cases.", + "usage": "developer-api", + "terms": "https://cohere.com/terms-of-use", + "policy": "Trial key for the developer API." } ] } diff --git a/config/skills/cli/handoff/SKILL.md b/config/skills/cli/handoff/SKILL.md index 24976f3..b7727a4 100644 --- a/config/skills/cli/handoff/SKILL.md +++ b/config/skills/cli/handoff/SKILL.md @@ -11,6 +11,27 @@ It writes `HANDOFF-REPORT.md` and stops. You review the diff and fix what it mis Pool, limits and budgets: `~/.config/free-agent/pool.json` (linked from `dotfiles/config/free-agent/pool.json`). Today's usage: `free-agent --list`. +## Policy gate — read before delegating anything + +This pipeline sends work to third-party services whose terms bind the account. Three +rules, and the tooling enforces the first two so a mistake cannot be accidental: + +1. **Developer APIs only.** Every lane in `pool.json` carries `usage: "developer-api"` and + a `terms` URL. `free-agent` refuses to run a lane without it, and + `handoff submit --backend freebuff` refuses outright — a consumer *app* polices its own + client and counts an agent-driven prompt as a policy breach (real event, 2026-11-29: + one strike on the Freebuff account). +2. **No credentials or private data in a brief.** Free tiers may train on prompts (Google + says so explicitly). `handoff submit` refuses a brief that matches an API key or private + key pattern; reference a `secretctl` name instead. +3. **Never rephrase to get past a block.** If a provider refuses a prompt, that is the + answer. Record it on `homelab/reference/clients/handoff-trials` and move the task to a + lane whose terms allow it — or do it yourself. + +Rate limits are theirs too: `free-agent` keeps a local per-lane budget below the published +rpm/rpd and parks a lane for the day on a hard quota error. When a provider answers 429 +with a retry delay, wait that delay rather than retrying sooner. + ## Write a brief that a weaker model can actually follow ``` From 767f0f7f8edc9b306332613743ddadd1474fcfe6 Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sun, 29 Nov 2026 00:19:07 -0700 Subject: [PATCH 37/40] tests: exercise the handoff pipeline without spending a call Ten checks in throwaway XDG dirs: the credential and freebuff gates, the task JSON (backend, role, brief), a running task with no worker reported as orphan, the daemon actually requeueing one, free-agent reading a custom pool, refusing a lane that is not a developer API even when forced with --model, exiting 3 when every lane is out of budget, and pause/resume. Nothing here reaches a provider. --- tests/handoff.sh | 115 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100755 tests/handoff.sh diff --git a/tests/handoff.sh b/tests/handoff.sh new file mode 100755 index 0000000..fe7c70c --- /dev/null +++ b/tests/handoff.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# Exercise the free-model handoff pipeline without spending a single API call. +# +# tests/handoff.sh +# +# Covers the parts that only fail in the field: the policy gates, the queue JSON, +# orphan detection and the pool/budget arithmetic in free-agent. Everything runs in +# throwaway XDG directories, so it never touches the real queue or budget. +set -euo pipefail +cd "$(dirname "$0")/.." +ROOT="$PWD" +export PATH="$ROOT/bin:$PATH" + +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +export XDG_DATA_HOME="$tmp/data" +export XDG_STATE_HOME="$tmp/state" +mkdir -p "$XDG_DATA_HOME" "$XDG_STATE_HOME" + +fail() { printf 'FAIL %s\n' "$*" >&2; exit 1; } +ok() { printf 'ok %s\n' "$*"; } + +# ---------------------------------------------------------------- briefs +cat > "$tmp/good.md" <<'EOF' +# Add a docstring + +Repository: /tmp/example + +Add a one-line docstring to `f()` in `f.py`. +Acceptance: `python3 -c "import f"`. +EOF +cat > "$tmp/secret.md" <<'EOF' +# Use the key + +Call the API with sk-abcdefghijklmnopqrstuvwx and report back. +EOF + +# ---------------------------------------------------------------- policy gates +out="$(handoff submit "$tmp/secret.md" --dir "$tmp" --id t-secret 2>&1)" && fail "a brief with an API key was accepted" +grep -q "credential" <<<"$out" || fail "the credential refusal did not explain itself" +ok "submit refuses a brief containing an API key" + +out="$(handoff submit "$tmp/good.md" --dir "$tmp" --backend freebuff --id t-fb 2>&1)" && fail "the freebuff backend was accepted" +grep -qi "usage policy" <<<"$out" || fail "the freebuff refusal did not cite the policy" +ok "submit refuses the freebuff backend" + +# ---------------------------------------------------------------- queue shape +handoff submit "$tmp/good.md" --dir "$tmp" --id t-good >/dev/null +task="$XDG_DATA_HOME/handoff/queue/t-good.json" +[ -f "$task" ] || fail "no task file was queued" +python3 - "$task" <<'PY' || fail "task JSON is missing fields" +import json, sys +d = json.load(open(sys.argv[1])) +assert d["id"] == "t-good", d +assert d["backend"] == "free-agent", d +assert d["role"] == "code", d +assert d["dir"].startswith("/") and d["dir"] != "/", d +PY +[ -s "$XDG_DATA_HOME/handoff/t-good.brief.md" ] || fail "the brief copy was not written" +ok "submit queues a task with its backend, role and brief" + +handoff submit "$tmp/good.md" --dir "$tmp" --backend free-agent --role review --id t-review >/dev/null +grep -q '"role": "review"' "$XDG_DATA_HOME/handoff/queue/t-review.json" || fail "role was not stored" +ok "submit stores a non-default role" + +# ---------------------------------------------------------------- orphan detection +mkdir -p "$XDG_DATA_HOME/handoff/running" +mv "$task" "$XDG_DATA_HOME/handoff/running/t-good.json" +line="$(handoff list | grep 't-good')" +grep -q '^orphan' <<<"$line" || fail "a running task with no window is not reported as orphan (got: $line)" +ok "handoff list reports an orphan when the worker is gone" + +# The daemon must act on an orphan, not just label it. Give it a task whose brief no +# longer exists, so free-agent exits on validation without spending an API call. +cat > "$XDG_DATA_HOME/handoff/running/t-lost.json" <<JSON +{ "id": "t-lost", "dir": "$tmp", "role": "code", "backend": "free-agent", + "brief": "$tmp/does-not-exist.md", "queuedAt": "2026-01-01T00:00:00Z" } +JSON +HANDOFF_MAX_PARALLEL=1 timeout 12 handoff daemon >"$tmp/daemon.log" 2>&1 || true +grep -q "requeued orphan t-lost" "$tmp/daemon.log" || fail "the daemon did not requeue the orphan (log: $(tail -3 "$tmp/daemon.log"))" +ok "the daemon requeues an orphan instead of leaving it running" + +# ---------------------------------------------------------------- free-agent pool logic +cat > "$tmp/pool-ok.json" <<'EOF' +{ "models": [ { "id": "test/lane-a", "usage": "developer-api", "roles": ["code"], "rpm": 1, "rpd": 2 } ] } +EOF +cat > "$tmp/pool-consumer.json" <<'EOF' +{ "models": [ { "id": "consumer/app", "usage": "consumer-app", "roles": ["code"], "rpm": 1, "rpd": 2 } ] } +EOF +cat > "$tmp/pool-empty.json" <<'EOF' +{ "models": [ { "id": "test/lane-a", "usage": "developer-api", "roles": ["code"], "rpm": 1, "rpd": 0 } ] } +EOF + +FREE_AGENT_POOL="$tmp/pool-ok.json" free-agent --list | grep -q 'test/lane-a' || fail "free-agent --list did not read the pool" +ok "free-agent --list reads a custom pool" + +FREE_AGENT_POOL="$tmp/pool-consumer.json" free-agent --list >/dev/null 2>&1 || true +out="$(FREE_AGENT_POOL="$tmp/pool-consumer.json" free-agent --brief "$tmp/good.md" --dir "$tmp" --id t-consumer --model consumer/app 2>&1)" && fail "a consumer-app lane was run" +grep -qi "developer-api" <<<"$out" || fail "the lane refusal did not name the rule (got: $out)" +ok "free-agent refuses a lane that is not a developer API, even when forced" + +# rpd 0 on the only lane: nothing has budget, and it must say so rather than call out +set +e +FREE_AGENT_POOL="$tmp/pool-empty.json" free-agent --brief "$tmp/good.md" --dir "$tmp" --id t-empty >/dev/null 2>&1 +code=$? +set -e +[ "$code" -eq 3 ] || fail "exhausted pool exited $code, want 3 (no capacity)" +ok "free-agent exits 3 when no lane has budget left" + +# ---------------------------------------------------------------- housekeeping +handoff pause >/dev/null && [ -f "$XDG_DATA_HOME/handoff/pause" ] || fail "pause did not write its marker" +handoff resume >/dev/null && [ ! -f "$XDG_DATA_HOME/handoff/pause" ] || fail "resume did not clear its marker" +ok "pause and resume manage the daemon marker" + +printf '\nHandoff pipeline checks passed\n' From 653d679dbc8d48ba5de9185242a4aa9f05c2624e Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sun, 29 Nov 2026 00:36:18 -0700 Subject: [PATCH 38/40] doctor: check the handoff pipeline; tests cover it end to end dot doctor gains four checks (daemon active, weekly probe timer scheduled, every pool lane usage=developer-api via the new bin/handoff-pool-check, and the pool readable by free-agent), so a dead daemon or an expired lane stops being invisible. tests/handoff.sh grows two checks for those and becomes hermetic: its daemon test runs in a private HANDOFF_TMUX session and points every brief at a path that does not exist, because a first version started a real worker inside the live session and spent a call. The doctor assertion captures the output instead of piping into grep -q, which with pipefail fails on SIGPIPE once the match is found. --- bin/dot | 7 +++++++ bin/handoff-pool-check | 25 +++++++++++++++++++++++++ tests/handoff.sh | 23 +++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100755 bin/handoff-pool-check diff --git a/bin/dot b/bin/dot index 057ff7e..c15d58c 100755 --- a/bin/dot +++ b/bin/dot @@ -727,6 +727,13 @@ cmd_doctor() { chk "konsole-daynight service" "systemctl --user is-active konsole-daynight" "dot switch, then log in to Plasma" chk "daynight-hooks service" "systemctl --user is-active daynight-hooks" "dot switch, then log in to Plasma" if ! in_container; then chk "netbird daemon" "systemctl is-active netbird" "dot system --netbird"; fi + + # Free-model handoff pipeline: a dead daemon or an off-policy lane stays invisible + # until someone tries to delegate, so check it here. + chk "handoff daemon" "systemctl --user is-active handoff.service" "systemctl --user start handoff" + chk "handoff probe timer" "systemctl --user list-timers handoff-probe.timer --no-pager | grep -q handoff-probe.timer" "systemctl --user start handoff-probe.timer" + chk "handoff pool policy" "handoff-pool-check" "edit config/free-agent/pool.json: every lane needs usage=developer-api" + chk "handoff pool alive" "free-agent --list >/dev/null" "free-agent --list" else chk "day/night daemons (XDG autostart)" "pgrep -f daynight-hooks" "log in to Plasma" fi diff --git a/bin/handoff-pool-check b/bin/handoff-pool-check new file mode 100755 index 0000000..f350948 --- /dev/null +++ b/bin/handoff-pool-check @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Fail when a pool lane is not a developer API. Called by `dot doctor`. +# +# handoff-pool-check [pool.json] +# +# Exit 0 = every lane is delegable, 1 = at least one is not, 2 = unreadable pool. +set -uo pipefail + +pool="${1:-${HOME}/.config/free-agent/pool.json}" +python3 - "$pool" <<'PY' +import json, sys +path = sys.argv[1] +try: + models = json.load(open(path)).get("models", []) +except Exception as exc: + print(f"handoff-pool-check: cannot read {path}: {exc}", file=sys.stderr) + sys.exit(2) +bad = [m.get("id", "?") for m in models if m.get("usage") != "developer-api"] +if bad: + print("handoff-pool-check: not a developer API: " + ", ".join(bad), file=sys.stderr) + sys.exit(1) +if not models: + print(f"handoff-pool-check: pool is empty ({path})", file=sys.stderr) + sys.exit(2) +PY diff --git a/tests/handoff.sh b/tests/handoff.sh index fe7c70c..02d9856 100755 --- a/tests/handoff.sh +++ b/tests/handoff.sh @@ -65,6 +65,14 @@ ok "submit stores a non-default role" # ---------------------------------------------------------------- orphan detection mkdir -p "$XDG_DATA_HOME/handoff/running" +# Nothing in this file may reach a provider: point the brief at a path that does not +# exist, so a task that gets started fails on validation instead of calling a model. +python3 - "$task" "$tmp/missing-brief.md" <<'PY' +import json, sys +path, missing = sys.argv[1:3] +d = json.load(open(path)); d["brief"] = missing +json.dump(d, open(path, "w")) +PY mv "$task" "$XDG_DATA_HOME/handoff/running/t-good.json" line="$(handoff list | grep 't-good')" grep -q '^orphan' <<<"$line" || fail "a running task with no window is not reported as orphan (got: $line)" @@ -76,7 +84,11 @@ cat > "$XDG_DATA_HOME/handoff/running/t-lost.json" <<JSON { "id": "t-lost", "dir": "$tmp", "role": "code", "backend": "free-agent", "brief": "$tmp/does-not-exist.md", "queuedAt": "2026-01-01T00:00:00Z" } JSON +# A private tmux session, so a test run can never add a window to the real one. +export HANDOFF_TMUX="handoff-test-$$" HANDOFF_MAX_PARALLEL=1 timeout 12 handoff daemon >"$tmp/daemon.log" 2>&1 || true +tmux kill-session -t "$HANDOFF_TMUX" 2>/dev/null || true +unset HANDOFF_TMUX grep -q "requeued orphan t-lost" "$tmp/daemon.log" || fail "the daemon did not requeue the orphan (log: $(tail -3 "$tmp/daemon.log"))" ok "the daemon requeues an orphan instead of leaving it running" @@ -112,4 +124,15 @@ handoff pause >/dev/null && [ -f "$XDG_DATA_HOME/handoff/pause" ] || fail "pause handoff resume >/dev/null && [ ! -f "$XDG_DATA_HOME/handoff/pause" ] || fail "resume did not clear its marker" ok "pause and resume manage the daemon marker" +# doctor must report the pipeline, not just its handlers +doc="$(./bin/dot doctor 2>/dev/null)" +grep -q 'handoff pool policy' <<<"$doc" || fail "dot doctor has no handoff checks (lines: $(wc -l <<<"$doc"), tail: $(tail -2 <<<"$doc" | tr '\n' ' '))" +ok "dot doctor reports the handoff pipeline" + +# the pool checker must reject a lane that is not a developer API +out="$(handoff-pool-check "$tmp/pool-consumer.json" 2>&1)" && fail "handoff-pool-check accepted a consumer lane" +grep -q "consumer/app" <<<"$out" || fail "handoff-pool-check did not name the offending lane" +handoff-pool-check "$tmp/pool-ok.json" || fail "handoff-pool-check rejected a good pool" +ok "handoff-pool-check passes a clean pool and names a bad lane" + printf '\nHandoff pipeline checks passed\n' From 49e2321493156f91f9fd55b8a9161f58c2eef90a Mon Sep 17 00:00:00 2001 From: Ziad Arafat <anonymous0programmer@gmail.com> Date: Sun, 29 Nov 2026 00:36:29 -0700 Subject: [PATCH 39/40] handoff skill: point at tests/handoff.sh --- config/skills/cli/handoff/SKILL.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/config/skills/cli/handoff/SKILL.md b/config/skills/cli/handoff/SKILL.md index b7727a4..a77d447 100644 --- a/config/skills/cli/handoff/SKILL.md +++ b/config/skills/cli/handoff/SKILL.md @@ -96,6 +96,14 @@ Then, yourself: 3. Fix, or submit a follow-up brief naming exactly what was wrong. 4. Commit yourself. Workers never commit. +## Tests + +`tests/handoff.sh` in the dotfiles repo exercises the whole pipeline in throwaway XDG +directories and never reaches a provider: the credential and freebuff gates, the task JSON, +orphan detection and the daemon's requeue, the pool policy check, the no-capacity exit, and +`dot doctor` reporting the pipeline. Run it after touching `bin/handoff`, `bin/free-agent`, +`bin/handoff-pool-check` or the pool. + ## Budgets and rate limits `free-agent` records one request per attempt in From d08d7ef03f3fc4f4cb2d2746be4a082098bceda0 Mon Sep 17 00:00:00 2001 From: ziadarafat <ziadarafat1@gmail.com> Date: Wed, 2 Dec 2026 09:20:08 -0700 Subject: [PATCH 40/40] Document handoff pipeline checks --- docs/handoff/brief-doctor-handoff.md | 58 ++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/handoff/brief-doctor-handoff.md diff --git a/docs/handoff/brief-doctor-handoff.md b/docs/handoff/brief-doctor-handoff.md new file mode 100644 index 0000000..0154f5f --- /dev/null +++ b/docs/handoff/brief-doctor-handoff.md @@ -0,0 +1,58 @@ +# dotfiles: make `dot doctor` check the handoff pipeline + +Repository: /home/deck/.dotfiles (bash, no build step) + +`dot doctor` currently checks flatpaks, wallpapers, a few services and netbird. The free-model +handoff pipeline — a systemd user service, a weekly timer and a model pool — has no checks at +all, so a dead daemon or an expired lane is invisible until someone tries to delegate work. + +Add a "handoff" group to `dot doctor`. + +## What to add + +In `bin/dot`, `cmd_doctor()` (around line 688), following the existing `chk` helper's +conventions — the same `chk "name" "test command" "how to fix"` calls that produce the +`ok` / `!!` lines: + +1. `handoff daemon` — `systemctl --user is-active handoff.service`; fix hint `systemctl --user start handoff`. +2. `handoff probe timer` — the timer is scheduled: `systemctl --user list-timers handoff-probe.timer --no-pager` + must mention `handoff-probe.timer`; fix hint `systemctl --user start handoff-probe.timer`. +3. `handoff pool policy` — every lane in `~/.config/free-agent/pool.json` carries + `usage: "developer-api"`. Use one `python3 -` heredoc that exits non-zero when a lane + is missing the field or carries another value, and prints the offending ids on stderr. + Fix hint `edit config/free-agent/pool.json`. +4. `handoff pool alive` — `free-agent --list` exits 0 (it fails on an unreadable pool); + fix hint `free-agent --list`. + +Put them together under a comment that says what the group is for, and keep the existing +output style exactly: the `chk` helper already prints `ok`/`!!` and the hint. + +## Tests + +Extend `tests/handoff.sh` (it already isolates `XDG_DATA_HOME` / `XDG_STATE_HOME` and runs +in seconds) with one check that the four new names appear in `dot doctor` output: + +```sh +./bin/dot doctor 2>/dev/null | grep -q 'handoff pool policy' || fail "doctor has no handoff checks" +``` + +Keep every existing check in that file passing. + +## Acceptance — run this yourself and paste the output in the report + +```sh +cd /home/deck/.dotfiles \ + && bash -n bin/dot \ + && bash tests/handoff.sh \ + && ./bin/dot doctor 2>/dev/null | grep -E 'handoff|probe' +``` + +The last command must print four lines about the handoff group (they will be `ok` on this +machine). Paste them. + +## Do not touch + +- `bin/free-agent`, `bin/handoff`, `bin/freebuff-agent`, `config/free-agent/` — the pipeline + itself is not part of this task; +- `home/`, `scripts/`, `.github/`, `docs/`; +- do not commit and do not create branches. Leave the tree dirty for review.