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= --match= --pattern= [--trigger=] [--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 '' # first page target +// cdp-read --url=groq '' # 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] ''\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); 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/free-agent b/bin/free-agent new file mode 100755 index 0000000..202fffa --- /dev/null +++ b/bin/free-agent @@ -0,0 +1,299 @@ +#!/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 = { 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") { + console.log(`free-agent — hand a brief to a free model + + --brief task brief (required unless --list) + --dir working directory for the worker (default: brief's folder) + --role code | review | infra (default code) + --id run id (default: derived from the brief file name + time) + --model

force one model instead of the pool + --timeout per attempt (default 1800) + --attempts how many pool models to try (default 3) + --dry-run print the chosen model and exit + --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]; + 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; + +// 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; + if (u.minute.length >= m.rpm) continue; + return m; + } + 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; + // 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) { + 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) { + 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 }; + 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; + } + skip.add(model.id); + + const b = loadBudget(); + record(b, model.id); + saveBudget(b); + + 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`); + + 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); + 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); + 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; + } + 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; + + attempts.push({ model: model.id, exit: last.exit, secs: Number(secs), rateLimited, ok, tries: modelAttempts.length }); + + 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 limit|RPD|insufficient balance|no resource package/i.test(lastOut); + 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) { + 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 ${lastCode}, 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/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/bin/freebuff-agent b/bin/freebuff-agent new file mode 100755 index 0000000..ce30574 --- /dev/null +++ b/bin/freebuff-agent @@ -0,0 +1,97 @@ +#!/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. 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 +while [ "$(date +%s)" -lt "$deadline" ]; do + sleep 10 + 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 + if [ "$marker" -eq 1 ] && [ "$busy" -eq 0 ]; then state=done; break; 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 +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 new file mode 100755 index 0000000..e164b8b --- /dev/null +++ b/bin/handoff @@ -0,0 +1,251 @@ +#!/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="" 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 ;; + 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" + + # 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 + + # 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" + + python3 - "$QUEUE/$id.json" "$id" "$dir" "$role" "$bpath" "$backend" <<'PY' +import json, sys, datetime +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 &" +} + +ensure_session() { + tmux has-session -t "$TMUX_SESSION" 2>/dev/null && return 0 + # 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 +} + +running_count() { find "$RUNNING" -maxdepth 1 -name '*.json' | wc -l | tr -d ' '; } + +start_task() { + 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")" + 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 + 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" \ + "$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 ($backend/$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 +} + +# 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 + 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("backend") or d.get("state","-"))' "$st" 2>/dev/null)" + 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 +} + +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/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/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}" 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..7314f9c --- /dev/null +++ b/config/free-agent/pool.json @@ -0,0 +1,95 @@ +{ + "$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", + "roles": [ + "code", + "infra" + ], + "rpm": 10, + "rpd": 200, + "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", + "roles": [ + "code", + "review" + ], + "rpm": 12, + "rpd": 800, + "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", + "roles": [ + "code", + "review", + "infra" + ], + "rpm": 8, + "rpd": 200, + "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", + "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).", + "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", + "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.", + "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", + "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.", + "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", + "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.", + "usage": "developer-api", + "terms": "https://cohere.com/terms-of-use", + "policy": "Trial key for the developer API." + } + ] +} diff --git a/config/free-pi/models.json b/config/free-pi/models.json index 0bb66a2..3010219 100644 --- a/config/free-pi/models.json +++ b/config/free-pi/models.json @@ -130,6 +130,60 @@ } } ] + }, + "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\"'", + "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/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` | diff --git a/config/pi/models.json b/config/pi/models.json index 0f1a678..81d86f9 100644 --- a/config/pi/models.json +++ b/config/pi/models.json @@ -176,6 +176,60 @@ "supportsStrictMode": false, "supportsUsageInStreaming": true } + }, + "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\"'", + "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..a77d447 --- /dev/null +++ b/config/skills/cli/handoff/SKILL.md @@ -0,0 +1,120 @@ +--- +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`. + +## 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 + +``` +# + +Repository: + +1. +2. + +Files: +Do not touch: + +Acceptance: +``` + +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. + +**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 +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 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. + +## 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 +`~/.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. + +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. 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. diff --git a/home/agents.nix b/home/agents.nix index 54030c2..b719592 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" "roku-tv" "zsa-moonlander" ]; - 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}"; @@ -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,48 @@ 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" ]; + }; + + # 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). } 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"; }; }; diff --git a/tests/handoff.sh b/tests/handoff.sh new file mode 100755 index 0000000..02d9856 --- /dev/null +++ b/tests/handoff.sh @@ -0,0 +1,138 @@ +#!/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" +# 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)" +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" <"$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" + +# ---------------------------------------------------------------- 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" + +# 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' 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 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 [warn_pct] [crit_pct] + +- Defaults: `warn_pct=80`, `crit_pct=90`. Both are whole percentages. +- Usage percent comes from `df -P ` (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 % ` below warn, `WARN % ` at or above warn, + `CRIT % ` 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 [warn_pct] [crit_pct] + +- Defaults: `warn_pct=80`, `crit_pct=90`. Both are whole percentages. +- Usage percent comes from `df -P ` (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 % ` below warn, `WARN % ` at or above warn, + `CRIT % ` 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-.md --dir --role --model `. + +**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 ] diff --git a/tools/music-audit/README.md b/tools/music-audit/README.md new file mode 100644 index 0000000..0810700 --- /dev/null +++ b/tools/music-audit/README.md @@ -0,0 +1,68 @@ +# 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. + +## 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. + +## 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`. + +## 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/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) 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()) diff --git a/tools/music-audit/followup.sh b/tools/music-audit/followup.sh new file mode 100755 index 0000000..a058f7f --- /dev/null +++ b/tools/music-audit/followup.sh @@ -0,0 +1,100 @@ +#!/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-[i]dentify" >/dev/null' 2>/dev/null; then + 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) +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/fpcalc b/tools/music-audit/fpcalc new file mode 100755 index 0000000..ba3c0ca --- /dev/null +++ b/tools/music-audit/fpcalc @@ -0,0 +1,77 @@ +#!/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 + + # -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] + # 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() + + 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)) 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/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/mb-pick.py b/tools/music-audit/mb-pick.py new file mode 100755 index 0000000..9f5d413 --- /dev/null +++ b/tools/music-audit/mb-pick.py @@ -0,0 +1,176 @@ +#!/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"^\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 + # 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/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 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/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()) diff --git a/tools/music-audit/resolve-albums.py b/tools/music-audit/resolve-albums.py new file mode 100755 index 0000000..15f416d --- /dev/null +++ b/tools/music-audit/resolve-albums.py @@ -0,0 +1,215 @@ +#!/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(" -") + + +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): + 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 = 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: + 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()) 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()) 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" 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()) diff --git a/tools/windows-vm/README.md b/tools/windows-vm/README.md new file mode 100644 index 0000000..211c111 --- /dev/null +++ b/tools/windows-vm/README.md @@ -0,0 +1,100 @@ +# Throwaway Windows VMs on Proxmox + +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**. + +## The automation hooks + +A provisioned VM has everything needed to run it entirely over the network: + +| Hook | What it gives you | +|---|---| +| `qemu-guest-agent` | `qm guest exec -- cmd /c …`, `qm shutdown`, `qm guest cmd` — no RDP, no console | +| **OpenSSH Server** (port 22) | ordinary `ssh doge@`, 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 +# 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 # only when the test needs real hardware +qm start 150 +qm guest cmd 150 network-get-interfaces # find its address +ssh doge@ # or: qm guest exec 150 -- cmd /c ver +``` + +Template creation: run `sysprep /oobe /generalize /shutdown` inside Windows, then +`qm template `. Sysprep is optional for single-use test VMs — a clone without +it shares the SID, which only matters on a domain. + +## 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`, `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 traps (learned the hard way, 2026-11-28) + +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 = [""] + ``` + 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. + +## 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 +pnmtopng /tmp/f.ppm > /tmp/f.png +md5sum /tmp/f.png # identical over time = static screen +``` + +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 → 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 new file mode 100644 index 0000000..89b8d23 --- /dev/null +++ b/tools/windows-vm/answer/autounattend.xml @@ -0,0 +1,142 @@ + + + + + + + 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 + + + + + OnError + + 0 + true + + 1EFI100 + 2MSR16 + 3Primarytrue + + + + 11FAT32 + + 22 + + 33NTFSC + + + + + + + + + + /IMAGE/INDEX + 1 + + + 03 + + + + + true + doge + homelab + + + + + + + WINTEST + UTC + + + + + 1 + never lock, never sleep + cmd /c powercfg /change standby-timeout-ac 0 & powercfg /change monitor-timeout-ac 0 + + + + + + + + + true + true + true + true + 3 + + + + + doge + doge + Administrators + + doge123! +

true</PlainText> + </Password> + </LocalAccount> + </LocalAccounts> + </UserAccounts> + <AutoLogon> + <Enabled>true</Enabled> + <Username>doge</Username> + <Password><Value>doge123!</Value><PlainText>true</PlainText></Password> + <LogonCount>999</LogonCount> + </AutoLogon> + <FirstLogonCommands> + <SynchronousCommand wcm:action="add"> + <Order>1</Order> + <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> + </settings> +</unattend> 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/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 new file mode 100644 index 0000000..9881910 --- /dev/null +++ b/tools/windows-vm/win11.pkr.hcl @@ -0,0 +1,168 @@ +# 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-noprompt.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" + } + + boot_iso { + type = "ide" + iso_file = var.iso_file + unmount = true + } + additional_iso_files { + device = "ide2" + iso_file = var.virtio_iso + unmount = true + iso_storage_pool = "local" + } + + # 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 = "ide2" + 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. + 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. + # 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>"])}"] + + # 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 = "doge" + winrm_password = "doge123!" + 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 +} + +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", + ] + } +}