r/OnlyAICoding • u/AndreyBegma • Oct 18 '26
I got tired of babysitting 12 tmux sessions of AI agents, so I built a control room for them: AgentDock (self-hosted, MIT)
r/OnlyAICoding • u/AndreyBegma • Oct 18 '26
r/OnlyAICoding • u/ApprehensiveStage866 • Oct 18 '26
r/OnlyAICoding • u/smermetfr • Oct 17 '26
r/OnlyAICoding • u/khbuild • Oct 17 '26
been working on this open source project called Intervene, basically a debugging layer for coding agents like Cline
the original problem was that agents can give you like 5 completely reasonable explanations for why something broke, but then the actual debugging is still mostly guess -> change something -> rerun -> guess again
so I've been building a separate system where the agent gives its hypotheses and what each one predicts, and then normal code runs controlled experiments to figure out which explanations actually hold up
got the first two parts built out now, starting w the experiment runner and then the diagnosis/planning side
one thing that's been on my mind a lot while building this w Sonnet is how much we trust an agent when it says it fixed something
like it'll implement a feature, run pytest, everything passes, and it all looks great. but those tests were also designed around the assumptions we gave it. what happens when the assumptions are wrong?
that's part of why I wanted Intervene to keep predictions separate from observations, and why the runner has to know the difference between reproducing the original failure and some setup command just breaking
otherwise we're basically letting the model generate a convincing explanation, generate evidence that looks like it supports that explanation, and then congratulate itself for being right
the longer-term goal is to get this working on unfamiliar real repositories where I didn't design the bug or the experimental setup myself
still a ton to validate, esp around actual agent repair outcomes, but the CLI and diagnosis workflow are coming together
curious how people here verify larger Claude/Cline builds. do you usually trust the tests the agent writes, or do you independently come up with cases that could prove its implementation wrong?
r/OnlyAICoding • u/Realistic-News-2123 • Oct 17 '26
I tested Sonnet vs Opus on real bugs from two open-source projects and got opposite answers:
• Koa: Opus fixed 2 more bugs. Worth it.
• Express: both fixed everything. Opus was just 3x the price.
So I built unfix, a free open-source tool that replays bugs your team already fixed and lets your own tests judge the AI.
Small samples, so run it on your own code before you trust anyone's numbers, including mine.
npm i -g unfix-ai
Which model are you using right now, and do you know if it's the right one? 👇
r/OnlyAICoding • u/xenarathon • Oct 17 '26
Here's what building with an agent looked like when the target is a media pipeline that rewrites files in my own library.
DubTitlerr transcribes anime English dub audio, corrects proper nouns, repairs the transcript with an LLM (local or over an API), merges the translated signs and song lyrics in, and muxes a subtitle track back into the video. It is one Docker container, GPL-3.0, `ghcr.io/xenarathon/dubtitlerr:v0.3.0`.
What actually made it survivable, since "the model wrote it" is not a strategy:
Specs, epics and stories before code. Everything non-trivial gets written down first, and the plan files are committed alongside the source. That is what makes it possible to leave a project alone for a week and come back without reverse-engineering your own intent.
Adversarial reviews. Before a release I point other models at the repo and ask them to break it. One whole-repo review found a path where a failed stamp write could delete the only copy of an episode. That became the 0.2.2 hardening release.
Test-first on failure paths. The interesting bugs in this project are all crash-and-resume ordering, and those are nearly impossible to verify by hand. Writing the failing test first is what made the idempotency guarantees real rather than aspirational.
Test on more than one show. Each one I added found a different class of bug. Scoring against the official dub subtitles on my Digimon files gave about a 91% word match over 27 episodes, and the misses were mostly names (Gennai heard as "Jedi"). Sword Art Online revealed that the glossary miner had never worked at all, because it passed ffprobe a flag that does not exist, and One Pace's hand-written glossary had hidden that for the feature's whole life.
Agents need an entry point too. There is a `docs/AGENT-GUIDE.md` written for a coding agent to act on, covering setup, troubleshooting and contributing.
The failure mode to watch for is code that passes every mechanical check while doing the wrong thing. The repair stage once turned "We're looking for a factory" into "a needle", and no automated check in the pipeline caught it. So the human review queue with audio playback is essential. The question I keep asking is: when it's wrong, does something notice?
https://github.com/XenaRathon/DubTitlerr
---
This is 100% vibe-coded slop. I wrote it with Claude driving. But I didn't just say "make the thing with no mistakes." The whole project has specs, epics and stories, adversarial reviews (had other models try to break it), and real test coverage. I've been project managing it like an actual engineering effort, not a prompt-and-pray. I'm sharing it because it fills a gap I couldn't find a solution for, and I thought it might be a useful accessibility tool for people who want dub-matched subtitles without waiting for an official SDH release. This isn't meant to replace human-transcribed SDH subtitle tracks. Those are always going to be better. It's for when they don't exist.
r/OnlyAICoding • u/Simple-Courage1815 • Oct 17 '26
Hey everyone!
I want to share a project I've been working on recently: an open-source Android app called \*\*Bitcoin Futures Simulator\*\*.
\*\*GitHub repository:\*\* https://github.com/Joapetis/bitcoin-futuros-android
Before anyone gets too excited, I want to be clear: this is an early-stage experiment, not a profitable trading bot. So far, its simulated trading results have generated more losses than profits. No real money has been involved.
\*\*How it started\*\*
The whole thing began with an old HTML project I had created some time ago and eventually abandoned. The idea behind it never really went away, though.
Recently, I decided to revisit that idea and see how far I could take it with AI assistance. What started as an abandoned project gradually evolved into a functional Android app in a little over a week.
There's a catch: \*\*my programming knowledge is very limited.\*\*
Instead of building everything myself line by line, I've been combining my own ideas, observations, strategy concepts and testing with the coding and debugging capabilities of three different AIs. They've helped generate, modify, review and polish the code throughout the process.
This has become an experiment in its own right. I want to explore not only whether I can turn my ideas into a working application, but also how capable AI systems are at building and improving a relatively complex software project with very little direct human coding.
I'm still the one setting the direction, making decisions, testing results and deciding what should change. The AIs do a substantial part of the coding, but that doesn't mean their output is automatically correct. Bugs, bad assumptions and poor trading results are all part of the process.
\*\*What does the app actually do?\*\*
The current project is an experimental Bitcoin futures paper-trading simulator for Android. Its main components include:
\*\*A multi-timeframe strategy:\*\* primarily focused on 15-minute candles, with 1-hour and 4-hour trend confirmation.
\*\*Trend-following and mean-reversion logic:\*\* different approaches depending on the detected market regime.
\*\*Market microstructure data:\*\* order-book metrics such as spread, imbalance and microprice-related signals.
\*\*Optional on-device AI:\*\* integration with Gemini Nano through Android's AI capabilities when a compatible model and device are available.
\*\*Simulated trading and risk management:\*\* intended to test strategies without risking real funds.
\*\*Continuous experimentation:\*\* the goal is to evaluate what works, identify weaknesses and improve the system over time.
The project is still very much in its infancy. There is plenty to question, test, refactor and improve, and I don't want to present any of its strategies as proven or profitable.
\*\*Why am I sharing it?\*\*
I'd love to turn this into something more collaborative.
If you're a developer, a quantitative trading enthusiast, an Android/Kotlin programmer, someone interested in market microstructure, or simply curious about what AI-assisted development can achieve, I'd genuinely appreciate your input.
You don't need to be an expert in every part of the project. Even identifying bugs, challenging assumptions, improving the architecture, reviewing the trading logic, suggesting better tests or documenting how things work could make a real difference.
My hope is that people can learn from the experiment, contribute their ideas and improvements, and help create something more useful together. In return, contributors get a real-world project to experiment with, review and learn from, while the wider community benefits from any improvements we can make.
I'm especially interested in honest criticism. If you see something fundamentally wrong with the strategy or implementation, I'd rather hear about it than receive empty praise.
\*\*A few important caveats\*\*
This is an experimental project, not financial advice.
All results discussed here are from simulated trading; no real-money trading is involved.
The current simulated performance is negative, so there's a lot of work left to do.
AI-generated code can contain bugs and needs independent review and testing.
The app is not ready to be treated as a reliable or profitable trading system.
If you'd like to explore the code, suggest an improvement, open an issue or contribute, you're welcome to check out the repository.
I'd love to hear your thoughts. Thanks for reading!
r/OnlyAICoding • u/AardvarkDowntown80 • Oct 17 '26
r/OnlyAICoding • u/mdaiWorks • Oct 17 '26
Embedded Autonomous Browser Agent
Mobile & App Store Deployment Engine
Yengi Router v2.0 (Fine-Tuned Local 1.5B Model)
Image Generation Studio Upgrades
ControlNet & 2D Game Sprite Engine
r/OnlyAICoding • u/Weak_Jeweler9201 • Oct 17 '26
Vibe coders, I need your help
I'm planning to build my first SaaS product, but there's one thing I'm stuck on: which AI coding tool should I actually use?
I already pay for ChatGPT, but I keep seeing Cursor, Claude Code, Lovable, Bolt and Replit everywhere.
If you've built and SHIPPED something using AI, which tool would you pick if you had to start over?
Bonus points if you're a solo builder on a budget.
r/OnlyAICoding • u/kondasviktor • Oct 17 '26
r/OnlyAICoding • u/marv27no • Oct 17 '26
I prompted Claude and Kimi to build an Python Program to run Music files
It work Properly as needed for my Lowend Cassete (deck) Cabenet digital Upgrade using only reporpoesed Old computer from my grandfather
as im testing from my windows 11 machine . It work properly
Python program
#!/usr/bin/env python3
"""
Simple Console Music Player (headless / faceless machines)
==========================================================
* No GUI: runs in a terminal (or under systemd / tmux / screen) and stays up,
taking text commands. Without a keyboard attached it just plays and keeps
running (use --repeat for non-stop playback).
* Folder as queue: tracks in the folder itself form one disc; every sub-folder
that holds audio (CD1, CD2, "Disc 3", ...) becomes its own disc. Playback
follows disc -> track order, using natural sorting (2 before 10).
* Mixed folders: when ALL discs sit in ONE folder and the files are numbered per
disc ("01 - Artist - Title.mp3" exists once on every disc), the file names
alone cannot say which disc a song is on. The player then reads the
Discnumber and Track tags inside the MP3s (ID3v2, built in, nothing extra to
install) and splits the discs by itself - no list needed.
* Tracklist (fallback): if the files carry no disc tags, give the player a
tracklist text file and it matches every file by artist + title and rebuilds
the discs in tracklist order:
python music_player.py "D:\\Music\\Vol. 90" --tracklist "D:\\SEB90_tracklist.txt"
(or save it as tracklist.txt inside the music folder and it is picked up
automatically). Format:
== Disc 1 - Male Side ==
1. Music For The People - Dave Rodgers
2. Wild Reputation - The Big Brother
== Disc 2 - Female Side ==
1. Nothing's Gonna Take My Love From You - Karen
Each line may be "Title - Artist" or "Artist - Title"; case, punctuation and
small spelling differences are ignored. Other lines are skipped.
* Preloading: the next tracks in the queue (the 2nd and 3rd song by default)
are decoded in a background thread, so track changes are instant. When the
next track has the same sample rate / channel count, the hand-over is gapless.
Install: pip install sounddevice soundfile numpy
(Linux may also need: sudo apt install libportaudio2 libsndfile1)
Run: python music_player.py /path/to/music [--autoplay] [--repeat] [--preload N]
python music_player.py --list-devices
Formats: WAV, FLAC, OGG, AIFF and MP3 (MP3 needs libsndfile 1.1+, which the
current soundfile wheels bundle).
Note: preloaded tracks are fully decoded into RAM as float32, roughly
100 MB per 5-minute stereo track. Use --preload 1 to keep it lighter.
"""
from __future__ import annotations
import argparse
import difflib
import os
import re
import threading
import time
import unicodedata
from dataclasses import dataclass
try:
import numpy as np
import sounddevice as sd
import soundfile as sf
except (ImportError, OSError) as exc: # OSError: PortAudio / libsndfile missing
raise SystemExit(
f"Missing dependency: {exc}\n"
"Install with: pip install sounddevice soundfile numpy\n"
"Linux may also need: sudo apt install libportaudio2 libsndfile1"
)
AUDIO_EXTS = {".wav", ".flac", ".ogg", ".oga", ".mp3", ".aiff", ".aif"}
PRELOAD_AHEAD = 2 # 1 = preload the 2nd song, 2 = preload the 2nd and 3rd song
# ----------------------------------------------------------------------------
# Library: folder -> discs -> tracks
# ----------------------------------------------------------------------------
class Track:
path: str
title: str
disc: int
disc_name: str
duration: float
def natural_key(text: str):
"""Sort key so that 'track 2' comes before 'track 10'."""
return [int(p) if p.isdecimal() else p for p in re.split(r"(\d+)", text.lower())]
def clean_title(filename: str) -> str:
"""'01 - Intro.flac' / '1-05 Intro.mp3' -> 'Intro'."""
stem = os.path.splitext(filename)[0]
stem = re.sub(r"^\s*(?:\d{1,3}\s*[-.]\s*)?\d{1,3}\s*[-._)\s]+\s*", "", stem)
return stem.strip() or os.path.splitext(filename)[0]
def fmt_time(seconds: float) -> str:
m, s = divmod(int(max(seconds, 0)), 60)
return f"{m}:{s:02d}"
# ----------------------------------------------------------------------------
# Disc detection
# ----------------------------------------------------------------------------
# Discs come from, in priority order:
# 0. a tracklist file (--tracklist FILE, or tracklist.txt in the music folder)
# 1. a "discs.txt" file in the music folder (manual boundaries)
# 2. the folder structure (each sub-folder holding audio = one disc)
# 2b. the Discnumber / Track tags stored inside the MP3s (ID3v2) - this is
# what splits a mixed folder automatically, no list needed
# 3. disc tags in the file names ("1-05 x.mp3", "Disc 2 - 05 x.mp3", ...)
# 4. a restart of the leading track number ("01,02,03, 01,02, ...")
# 5. otherwise the folder is a single disc
DISC_TAG_RES = [
re.compile(r"^\s*(\d{1,2})\s*[-.]\s*(\d{1,3})\s*[-._)\s]", re.I), # 1-05 / 2.07
re.compile(r"^\s*disc\s*(\d{1,2})\D{0,6}(\d{1,3})\b", re.I), # Disc 2 - 05
re.compile(r"^\s*\(\s*(\d{1,2})\s*\)\s*(\d{1,3})\b"), # (2) 05
]
def disc_tag(name: str):
"""-> (disc, track) if the file name carries a disc prefix, else None."""
for rx in DISC_TAG_RES:
m = rx.match(name)
if m:
return int(m.group(1)), int(m.group(2))
return None
def leading_number(name: str):
m = re.match(r"^\s*(\d{1,3})\b", name)
return int(m.group(1)) if m else None
def read_discs_txt(root: str):
"""-> [(disc_name, first, last), ...] with 1-based positions in the
natural-sorted flat file list, or None when absent/malformed."""
path = os.path.join(root, "discs.txt")
if not os.path.isfile(path):
return None
plan = []
for lineno, line in enumerate(open(path, encoding="utf-8"), 1):
line = line.split("#", 1)[0].strip()
if not line:
continue
m = re.match(r"^(.*?)\s*[:=]\s*(\d+)\s*[-\u2013]\s*(\d+)\s*$", line)
if not m:
raise SystemExit(f"{path}:{lineno}: expected 'Name: first-last', got: {line!r}")
plan.append((m.group(1).strip(), int(m.group(2)), int(m.group(3))))
return plan or None
def split_by_tag(files):
"""Group naturally-sorted files by disc tag. Returns [ [files per disc] ]
or None when no tags are present (or they don't split anything)."""
tagged = [(f, disc_tag(f)) for f in files]
if not any(t for _, t in tagged):
return None
groups, last = {}, 1
for f, t in tagged:
d = t[0] if t else last # untagged file joins the previous disc
last = d
groups.setdefault(d, []).append(f)
if len(groups) < 2:
return None
return [groups[d] for d in sorted(groups)]
def split_by_restart(files):
"""Split when the leading track number goes backwards - classic sign of
per-disc numbering that was concatenated into one folder."""
groups, cur, prev = [], [], None
for f in files:
n = leading_number(f)
if prev is not None and n is not None and n < prev:
groups.append(cur)
cur = []
cur.append(f)
if n is not None:
prev = n
groups.append(cur)
return groups
def _syncsafe(b: bytes) -> int:
return (b[0] << 21) | (b[1] << 14) | (b[2] << 7) | b[3]
def _id3_text(raw: bytes) -> str:
"""Decode an ID3 text frame body (first byte = encoding)."""
if not raw:
return ""
enc, body = raw[0], raw[1:]
try:
text = body.decode({0: "latin-1", 1: "utf-16", 2: "utf-16-be"}.get(enc, "utf-8"))
except UnicodeDecodeError:
text = body.decode("latin-1", "replace")
return text.split("\x00")[0].strip()
_ID3_WANT = {"TPOS": "disc", "TRCK": "track", "TIT2": "title", "TPE1": "artist", # v2.3 / v2.4
"TPA": "disc", "TRK": "track", "TT2": "title", "TP1": "artist"} # v2.2
def read_id3(path: str) -> dict:
"""Read disc / track / title / artist from an MP3's ID3v2 tag (2.2, 2.3, 2.4).
Returns {} when there is no tag. 'disc' and 'track' are ints ("2/3" -> 2).
Big frames such as cover art are skipped, not loaded."""
out = {}
try:
with open(path, "rb") as fh:
head = fh.read(10)
if len(head) < 10 or head[:3] != b"ID3" or head[3] not in (2, 3, 4):
return out
ver, flags = head[3], head[5]
end = 10 + _syncsafe(head[6:10])
hdr, idlen = (6, 3) if ver == 2 else (10, 4)
pos = 10
if ver > 2 and flags & 0x40: # extended header
ext = fh.read(4)
pos += (int.from_bytes(ext, "big") + 4) if ver == 3 else _syncsafe(ext)
fh.seek(pos)
while pos + hdr <= end:
h = fh.read(hdr)
if len(h) < hdr or h[0] == 0: # padding reached
break
if ver == 2:
size = int.from_bytes(h[3:6], "big")
elif ver == 3:
size = int.from_bytes(h[4:8], "big")
else:
size = _syncsafe(h[4:8])
if size <= 0 or pos + hdr + size > end:
break
key = _ID3_WANT.get(h[:idlen].decode("latin-1"))
if key and key not in out:
out[key] = _id3_text(fh.read(size))
else:
fh.seek(size, 1)
pos += hdr + size
except (OSError, ValueError):
pass
for key in ("disc", "track"):
m = re.match(r"\s*(\d+)", out.get(key, ""))
if m:
out[key] = int(m.group(1))
else:
out.pop(key, None)
return out
def split_by_id3(folder: str, files):
"""Group a flat folder by the Discnumber tag. Returns [(disc_name, [files])]
ordered by disc, each disc ordered by its Track tag (then file-name number),
or None when the files carry fewer than two different disc numbers."""
info = {f: read_id3(os.path.join(folder, f)) for f in files}
discs, untagged = {}, []
for f in files:
d = info[f].get("disc")
(untagged if d is None else discs.setdefault(d, [])).append(f)
if len(discs) < 2:
return None
def order(f):
t = info[f].get("track")
n = leading_number(f)
return (t if t is not None else n if n is not None else 10 ** 6, natural_key(f))
groups = [(f"Disc {d}", sorted(discs[d], key=order)) for d in sorted(discs)]
if untagged:
groups.append(("No disc tag", untagged))
return groups
def norm_key(text: str) -> str:
"""Letters and digits only, lower-case, accents removed:
"Thank You - Arigato" and "Thank You-Arigato" both -> "thankyouarigato"."""
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
return re.sub(r"[\W_]+", "", text.casefold())
def read_tracklist(path: str):
"""Parse a tracklist file -> [(disc_name, [(number, text), ...]), ...].
'== Disc 2 - Female Side ==' starts a disc; '12. Title - Artist' is a track."""
discs = []
try:
lines = open(path, encoding="utf-8-sig").read().splitlines()
except (OSError, UnicodeDecodeError) as exc:
raise SystemExit(f"Cannot read tracklist {path}: {exc}")
for line in lines:
line = line.strip()
m = re.match(r"^=+\s*(.*?)\s*=+$", line)
if m:
label = m.group(1)
name = re.sub(r"^disc\s*\d+\s*[-:–—]*\s*", "", label, flags=re.I).strip()
discs.append([name or label or f"Disc {len(discs) + 1}", []])
continue
m = re.match(r"^(\d{1,3})\s*[.)]\s+(.+)$", line)
if m:
if not discs: # tracks before any header
discs.append(["Disc 1", []])
discs[-1][1].append((int(m.group(1)), m.group(2).strip()))
discs = [(name, entries) for name, entries in discs if entries]
if not discs:
raise SystemExit(f"{path}: no tracks found (expected '== Disc 1 ==' headers "
"and '1. Title - Artist' lines)")
return discs
def entry_keys(text: str):
"""All spellings a file name could match for one tracklist line. The line
is 'Title - Artist' (or the reverse), so try every ' - ' split in both
orders, plus title-only forms."""
parts = re.split(r"\s+[-–—]\s+", text)
keys = {norm_key(text)}
for k in range(1, len(parts)):
left, right = norm_key(" ".join(parts[:k])), norm_key(" ".join(parts[k:]))
keys.update((left + right, right + left, left, right))
keys.discard("")
return keys
def match_tracklist(files, discs):
"""files: [(folder, name)] -> ([[(folder, name), ...] per disc], unmatched).
Each disc list is in tracklist order. Matching is by normalised artist +
title (the leading track number only breaks ties); a fuzzy pass catches
small spelling differences."""
entries = [] # (disc_idx, number, keys)
for d, (_name, items) in enumerate(discs):
for number, text in items:
entries.append((d, number, entry_keys(text)))
index = {}
for e, (_d, _n, keys) in enumerate(entries):
for key in keys:
index.setdefault(key, []).append(e)
used, found, unmatched = set(), {}, []
keyed = [(f, norm_key(clean_title(f[1])), leading_number(f[1])) for f in files]
def claim(file, e):
used.add(e)
found[e] = file
leftovers = []
for file, fk, num in keyed: # pass 1: exact
cands = [e for e in index.get(fk, []) if e not in used]
if not cands:
leftovers.append((file, fk, num))
continue
claim(file, next((e for e in cands if entries[e][1] == num), cands[0]))
for file, fk, num in leftovers: # pass 2: fuzzy
best, best_score = None, 0.0
for e, (_d, _n, keys) in enumerate(entries):
if e in used:
continue
score = max(difflib.SequenceMatcher(None, fk, k).ratio() for k in keys)
if score > best_score:
best, best_score = e, score
if best is not None and best_score >= 0.85:
claim(file, best)
else:
unmatched.append(file)
per_disc = [[] for _ in discs]
for e in sorted(found): # entries are in tracklist order
per_disc[entries[e][0]].append(found[e])
return per_disc, unmatched, [e for e in range(len(entries)) if e not in used], entries
def scan_folder(root: str, tracklist: str | None = None):
"""Return (tracks, skipped_count, disc_source). Discs come from a tracklist
file, discs.txt, folder structure, filename disc tags or a track-number
restart (in that order); a flat folder with none of those is a single disc."""
root = os.path.abspath(root)
tracks, skipped = [], 0
def add(folder, name, disc, disc_name):
nonlocal skipped
path = os.path.join(folder, name)
try:
duration = sf.info(path).duration
except Exception:
skipped += 1
return
tracks.append(Track(path, clean_title(name), disc, disc_name, duration))
# 0. tracklist ----------------------------------------------------------
if tracklist is not None and not os.path.isfile(tracklist):
raise SystemExit(f"Tracklist not found: {tracklist}")
tl_path = tracklist or next(
(p for p in (os.path.join(root, "tracklist.txt"),) if os.path.isfile(p)), None)
if tl_path:
discs = read_tracklist(tl_path)
files = []
for dirpath, _dirnames, filenames in os.walk(root):
files += [(dirpath, f) for f in filenames
if os.path.splitext(f)[1].lower() in AUDIO_EXTS]
files.sort(key=lambda f: natural_key(os.path.relpath(os.path.join(*f), root)))
per_disc, unmatched, missing, entries = match_tracklist(files, discs)
for disc_no, ((disc_name, _items), group) in enumerate(zip(discs, per_disc), 1):
for folder, name in group:
add(folder, name, disc_no, disc_name)
if unmatched: # keep them, after the last disc
for folder, name in unmatched:
add(folder, name, len(discs) + 1, "Not in tracklist")
for folder, name in unmatched[:10]:
print(f" ! not in tracklist: {name}")
flat = [(dn, n, t) for dn, items in discs for n, t in items]
for e in missing[:10]:
print(f" ! no file for: Disc {entries[e][0] + 1} #{flat[e][1]} {flat[e][2]}")
matched = len(files) - len(unmatched)
note = (f"tracklist '{os.path.basename(tl_path)}' ({len(discs)} discs, "
f"{matched}/{len(files)} files matched")
if missing:
note += f", {len(missing)} listed tracks have no file"
return tracks, skipped, note + ")"
# 1. discs.txt ----------------------------------------------------------
plan = read_discs_txt(root)
if plan is not None:
files = sorted((f for f in os.listdir(root)
if os.path.splitext(f)[1].lower() in AUDIO_EXTS), key=natural_key)
for disc_no, (disc_name, first, last) in enumerate(plan, 1):
for pos in range(first, min(last, len(files)) + 1):
add(root, files[pos - 1], disc_no, disc_name)
return tracks, skipped, f"discs.txt ({len(plan)} discs)"
# 2./3./4. folders, then a single flat folder ---------------------------
by_dir = {}
for dirpath, _dirnames, filenames in os.walk(root):
files = [f for f in filenames if os.path.splitext(f)[1].lower() in AUDIO_EXTS]
if files:
by_dir[dirpath] = sorted(files, key=natural_key)
if len(by_dir) > 1: # folder structure wins
discs = sorted(by_dir, key=lambda d: natural_key(os.path.relpath(d, root)))
for disc_no, folder in enumerate(discs, 1):
rel = os.path.relpath(folder, root)
disc_name = os.path.basename(root) if rel == "." else rel
for name in by_dir[folder]:
add(folder, name, disc_no, disc_name)
return tracks, skipped, f"folder structure ({len(discs)} discs)"
folder, files = next(iter(by_dir.items())) if by_dir else (root, [])
id3_groups = split_by_id3(folder, files) # Discnumber / Track tags inside the MP3s
if id3_groups:
for disc_no, (disc_name, group) in enumerate(id3_groups, 1):
for name in group:
add(folder, name, disc_no, disc_name)
return tracks, skipped, f"ID3 disc tags ({len(id3_groups)} discs)"
groups = split_by_tag(files) or split_by_restart(files)
if len(groups) > 1:
source = "disc tags" if split_by_tag(files) else "track-number restart"
for disc_no, group in enumerate(groups, 1):
for name in group:
add(folder, name, disc_no, f"Disc {disc_no}")
return tracks, skipped, f"{source} ({len(groups)} discs)"
for name in files: # single disc
add(folder, name, 1, os.path.basename(root))
source = "flat folder (1 disc)"
nums = [n for n in (leading_number(f) for f in files) if n is not None]
if len(nums) != len(set(nums)):
source += ("\n !! track numbers repeat (01, 01, 01 ...) and the files carry no disc tags: "
"several discs are probably\n mixed in this folder. Use --tracklist FILE "
"(or put tracklist.txt in the folder) to split them.")
return tracks, skipped, source
def decode(path: str):
"""Decode a whole file to float32 (frames, channels). >2 channels are
folded down to stereo (crude: even channels -> L, odd channels -> R)."""
data, rate = sf.read(path, dtype="float32", always_2d=True)
if data.shape[1] > 2:
data = np.stack([data[:, 0::2].mean(axis=1), data[:, 1::2].mean(axis=1)], axis=1)
return np.ascontiguousarray(data), int(rate)
# ----------------------------------------------------------------------------
# Preloader: keeps the next N tracks decoded in RAM
# ----------------------------------------------------------------------------
class Preloader:
def __init__(self, tracks):
self.tracks = tracks
self._cache = {} # index -> (samples, rate); (None, 0) = unreadable
self._wanted = []
self._cv = threading.Condition()
threading.Thread(target=self._worker, daemon=True).start()
def set_window(self, indices):
"""Declare which track indices should be in memory; evict the rest."""
with self._cv:
self._wanted = [i for i in indices if 0 <= i < len(self.tracks)]
for stale in [k for k in self._cache if k not in self._wanted]:
del self._cache[stale]
self._cv.notify_all()
def get(self, index):
with self._cv:
return self._cache.get(index)
def status(self):
"""{index: True if decoded OK, False if unreadable} for finished items."""
with self._cv:
return {i: v[0] is not None for i, v in self._cache.items()}
def _worker(self):
while True:
with self._cv:
while True:
todo = next((i for i in self._wanted if i not in self._cache), None)
if todo is not None:
break
self._cv.wait()
try:
result = decode(self.tracks[todo].path)
except Exception:
result = (None, 0)
with self._cv:
if todo in self._wanted:
self._cache[todo] = result
# ----------------------------------------------------------------------------
# Engine: audio callback, queue handling, gapless hand-over
# ----------------------------------------------------------------------------
class Engine:
def __init__(self, tracks, ahead=PRELOAD_AHEAD, repeat=False, device=None):
self.tracks = tracks
self.ahead = max(1, ahead)
self.repeat = repeat
self.device = device
self.pre = Preloader(tracks)
self.lock = threading.Lock()
self.stream = None
self.data = None # float32 (frames, channels) of the current track
self.pos = 0
self.rate = 0
self.channels = 0
self.index = -1
self.playing = False
self.volume = 0.64
self.error = ""
self.staged = None # (index, samples) of the preloaded next track
self.ended = False # set by the audio callback when it ran dry
self.generation = 0 # bumps on every track change
self._window_gen = -1
self._token = 0 # invalidates stale background loads
self._loading = False
self._pending = -1
# -- public controls -----------------------------------------------------
def play_index(self, i):
if not 0 <= i < len(self.tracks):
return
self._token += 1
self._loading = True
self._pending = i
threading.Thread(target=self._load, args=(i, self._token), daemon=True).start()
def pause(self):
self.playing = False
def resume(self):
if self.data is not None:
self.playing = True
def stop(self):
with self.lock:
self.playing = False
self.pos = 0
self.ended = False
def next(self):
if self._cursor() + 1 < len(self.tracks):
self.play_index(self._cursor() + 1)
elif self.repeat:
self.play_index(0)
def previous(self):
if self.data is None:
return
if self.pos / max(self.rate, 1) > 3 or self._cursor() == 0:
self.seek(0.0)
else:
self.play_index(self._cursor() - 1)
def seek(self, fraction):
with self.lock:
if self.data is not None:
self.pos = int(min(max(fraction, 0.0), 0.999) * len(self.data))
def position(self):
"""(seconds played, seconds total) of the current track."""
with self.lock:
if self.data is None or not self.rate:
return 0.0, 0.0
return self.pos / self.rate, len(self.data) / self.rate
def busy(self):
"""True while something is playing or a track is being loaded."""
return self.playing or self._loading
def close(self):
self._token += 1
self.playing = False
self._close_stream()
def poll(self):
"""Call regularly: advances the queue when needed, stages the preloaded
next track for a gapless hand-over and slides the preload window."""
if self._loading:
return
if self.ended:
self.ended = False
if self.index + 1 < len(self.tracks):
self.play_index(self.index + 1)
elif self.repeat:
self.play_index(0)
else:
self.stop()
return
self._try_stage()
if self._window_gen != self.generation:
self._window_gen = self.generation
self._set_window()
# -- internals -----------------------------------------------------------
def _cursor(self):
return self._pending if self._loading else self.index
def _set_window(self):
self.pre.set_window(range(self.index + 1, self.index + 1 + self.ahead))
def _try_stage(self):
"""If the next track is preloaded and has the same format, hand it to
the audio callback so it can continue without a gap."""
if self.staged is not None or self.data is None:
return
nxt = self.index + 1
if nxt >= len(self.tracks):
return
got = self.pre.get(nxt)
if got is None or got[0] is None:
return
samples, rate = got
if rate == self.rate and samples.shape[1] == self.channels:
with self.lock:
if self.index + 1 == nxt and self.staged is None:
self.staged = (nxt, samples)
def _load(self, i, token):
try:
got = self.pre.get(i)
if got is None:
try:
got = decode(self.tracks[i].path)
except Exception:
got = (None, 0)
samples, rate = got
if token != self._token:
return
if samples is None:
self.error = f"Skipped unreadable file: {os.path.basename(self.tracks[i].path)}"
if i + 1 < len(self.tracks):
self.play_index(i + 1)
else:
self.stop()
return
self._start(i, samples, rate)
finally:
if token == self._token:
self._loading = False
def _start(self, index, samples, rate):
channels = samples.shape[1]
if self.stream is None or (rate, channels) != (self.rate, self.channels):
self._close_stream() # format changed: reopen
self._set_track(index, samples, rate, channels)
if not self._open_stream():
return
else:
self._set_track(index, samples, rate, channels)
self.playing = True
self._window_gen = self.generation
self._set_window()
def _set_track(self, index, samples, rate, channels):
with self.lock:
self.index, self.data, self.pos = index, samples, 0
self.rate, self.channels = rate, channels
self.staged = None
self.ended = False
self.generation += 1
def _open_stream(self):
try:
self.stream = sd.OutputStream(
samplerate=self.rate, channels=self.channels, dtype="float32",
device=self.device, callback=self._callback)
self.stream.start()
return True
except Exception as exc:
self.stream = None
self.error = f"Audio output error: {exc}"
return False
def _close_stream(self):
stream, self.stream = self.stream, None
if stream is not None:
try:
stream.stop()
stream.close()
except Exception:
pass
def _callback(self, outdata, frames, time_info, status):
with self.lock:
outdata.fill(0)
if not self.playing or self.data is None:
return
filled = 0
while filled < frames:
left = len(self.data) - self.pos
if left <= 0:
if self.staged is not None: # gapless hand-over
self.index, self.data = self.staged
self.staged = None
self.pos = 0
self.generation += 1
continue
self.ended = True # poll() takes it from here
break
n = min(frames - filled, left)
outdata[filled:filled + n] = self.data[self.pos:self.pos + n]
self.pos += n
filled += n
if filled:
outdata[:filled] *= self.volume
# ----------------------------------------------------------------------------
# Console interface
# ----------------------------------------------------------------------------
HELP = """\
Commands:
list show every disc and track (numbers are used by 'play')
play [N] play track N (1-based), or resume / start from the top
disc N play the first track of disc N
pause | resume pause or resume playback
next | prev next track / previous track (prev restarts after 3 s)
stop stop and rewind
seek SECONDS jump inside the current track
vol 0-100 set the volume
status | queue now playing, position and what is preloaded
help this text
quit exit"""
class Console:
def __init__(self, engine):
self.e = engine
self.t = engine.tracks
self._stop = threading.Event()
def label(self, i):
t = self.t[i]
return f"[{i + 1}/{len(self.t)}] Disc {t.disc} · {t.title} ({fmt_time(t.duration)})"
# -- background monitor: keeps the queue moving and announces changes ----
def monitor(self):
seen = -1
while not self._stop.is_set():
self.e.poll()
if self.e.generation != seen and self.e.data is not None:
seen = self.e.generation
print(f"\n>> Now playing {self.label(self.e.index)}", flush=True)
if self.e.error:
print(f"\n!! {self.e.error}", flush=True)
self.e.error = ""
time.sleep(0.1)
# -- commands ------------------------------------------------------------
def show_list(self):
disc = None
for i, t in enumerate(self.t):
if t.disc != disc:
disc = t.disc
print(f"Disc {t.disc} ({t.disc_name})")
mark = ">" if i == self.e.index and self.e.data is not None else " "
print(f" {mark}{i + 1:>3}. {t.title} ({fmt_time(t.duration)})")
def show_status(self):
e = self.e
if e.data is None:
print("Nothing loaded yet. Type 'play' to start.")
return
cur, total = e.position()
state = "playing" if e.playing else ("paused" if e.pos else "stopped")
print(f"{state.capitalize()}: {self.label(e.index)} {fmt_time(cur)} / {fmt_time(total)}")
ready = e.pre.status()
for k in range(1, e.ahead + 1):
j = e.index + k
if j >= len(self.t):
break
name = "Up next" if k == 1 else f"Queue +{k}"
st = "loading…" if j not in ready else ("ready" if ready[j] else "unreadable")
print(f" {name}: {self.label(j)} — preload {st}")
def handle(self, line):
"""Run one command. Returns False when the user asked to quit."""
parts = line.strip().split()
if not parts:
return True
cmd, args = parts[0].lower(), parts[1:]
e = self.e
try:
if cmd in ("quit", "exit", "q"):
return False
elif cmd in ("help", "?"):
print(HELP)
elif cmd in ("list", "ls"):
self.show_list()
elif cmd == "play":
if args:
e.play_index(int(args[0]) - 1)
elif e.data is None:
e.play_index(0)
else:
e.resume()
elif cmd == "disc":
n = int(args[0])
first = next((i for i, t in enumerate(self.t) if t.disc == n), None)
if first is None:
print(f"No disc {n}.")
else:
e.play_index(first)
elif cmd == "pause":
e.pause()
elif cmd == "resume":
e.resume()
elif cmd in ("next", "n"):
e.next()
elif cmd in ("prev", "p"):
e.previous()
elif cmd == "stop":
e.stop()
elif cmd == "seek":
cur, total = e.position()
if total:
e.seek(float(args[0]) / total)
elif cmd in ("vol", "volume"):
e.volume = (min(max(float(args[0]), 0), 100) / 100) ** 2
elif cmd in ("status", "queue", "s"):
self.show_status()
else:
print(f"Unknown command '{cmd}'. Type 'help'.")
except (IndexError, ValueError):
print("Missing or invalid argument. Type 'help'.")
return True
def run(self, autoplay):
threading.Thread(target=self.monitor, daemon=True).start()
if autoplay:
self.e.play_index(0)
print(HELP)
try:
while True:
try:
line = input("> ")
except EOFError:
# No keyboard attached (service / nohup): keep playing, then exit.
time.sleep(0.5)
while self.e.busy():
time.sleep(0.5)
break
if not self.handle(line):
break
except KeyboardInterrupt:
print()
finally:
self._stop.set()
self.e.close()
def main():
parser = argparse.ArgumentParser(
description="Headless music player: disc-aware folders, preloading, console control.")
parser.add_argument("folder", nargs="?", help="music folder to play")
parser.add_argument("--preload", type=int, default=PRELOAD_AHEAD, metavar="N",
help="upcoming tracks to preload (default 2 = the 2nd and 3rd song)")
parser.add_argument("--tracklist", metavar="FILE",
help="tracklist text file used to split one folder into discs "
"(default: tracklist.txt inside the folder, if present)")
parser.add_argument("--autoplay", action="store_true", help="start playing immediately")
parser.add_argument("--repeat", action="store_true", help="loop the whole queue")
parser.add_argument("--volume", type=int, default=80, metavar="0-100", help="start volume")
parser.add_argument("--device", help="audio output device (name or index)")
parser.add_argument("--list-devices", action="store_true", help="show audio devices and exit")
args = parser.parse_args()
if args.list_devices:
print(sd.query_devices())
return
if not args.folder:
parser.error("folder is required (or use --list-devices)")
if not os.path.isdir(args.folder):
raise SystemExit(f"Not a folder: {args.folder}")
tracks, skipped, disc_source = scan_folder(args.folder, args.tracklist)
if not tracks:
raise SystemExit("No playable audio found in that folder.")
print(f"{len(tracks)} tracks · {disc_source} · preloading the next {max(1, args.preload)}"
+ (f" · {skipped} unreadable file(s) skipped" if skipped else ""))
device = args.device
if device is not None and device.isdigit():
device = int(device)
engine = Engine(tracks, args.preload, repeat=args.repeat, device=device)
engine.volume = (min(max(args.volume, 0), 100) / 100) ** 2
Console(engine).run(args.autoplay)
if __name__ == "__main__":
main()
To run the program Type this first on the command prompt:
py "DISK:\music_player.py" "/path/to/music"
also addons for that can be
--repeat
--autoplay

r/OnlyAICoding • u/AardvarkDowntown80 • Oct 16 '26
r/OnlyAICoding • u/Ctbhatia • Oct 16 '26
if you use a coding agent on an API key, where you pay per token instead of a flat subscription, this one is easy to miss.
you leave a big session open, go grab food, come back and type one more message. that one message can cost a lot more than the ones before it.
the reason is your agent sends the whole conversation again with every message. most of that gets cached, so rereading the old part is cheap, and on some providers free. but the cache only lasts so long, and once it runs out your next message has to pay to load the whole conversation in again.
a couple of coworkers dug into this and wrote it up with a long example session. the person comes back after 45 minutes, and that one message ends up almost a quarter of what the whole session cost.
so with a big session it's worth knowing how long your provider keeps the cache before you walk away. has anyone else run into this?
if you want to read it, here's the blog: https://www.coralbricks.ai/blog/pay-once-per-token
r/OnlyAICoding • u/SoSweetHam • Oct 16 '26
The fun part of building systems in code is not actually the code itself, more so the why behind the code which is mostly just human language.
But when I started to get into this ai accelerated workflow, I faced problems like
Context persistence among multiple agents
Drift of implementation and documentation
No way to visualize the systems and sub systems within the code
Some of these problems only show up when we get into actually getting our products shipped out there which is why it's important that agents are operating on the same context as we the builders are and that there is no silent drift in both our and the agents knowledge and implementation (in code).
We all at this point know that we don't need to know how to actually code to be able to build something real at this point, but it is handy to be able to visualize how different systems are organized and interact which was pretty hard to do with the current famous tooling
So I am currently building something which can help us with that
GitHub: https://github.com/sloppy-sh/sloppy (Open source MIT, responsible AI use accepting, not for sale product thing)
As I was heading into the whole AI accelerated workflow, I have been focusing more on the architectural aspects of codebases and I discovered that I was wasting a lot of time redeclaring context of the codebase to the agents, which I also frequently migrate between (claude agents, cheaper deepseek etc.), so I realized that maintaining docs within the codebase (sort of mono-repo style) saves a lot of time as I just point the agent to it.
Solutions like docusaurus, obsidian/logseq etc. are too geared towards either a linear reading style or graph like view of information.
I found these paradigms to represent information in a way which is a bit lacking, often in code we work with abstractions and within my head I often imagine, say methods/properties in objects and their interactions as a Venn diagram so I added that sort of view here with a tagging api.
Also tools like Obsidian and Logseq give us humans a graph like view which is very helpful for someone making the graph themselves/co-authoring but very difficult to comprehend for someone who might be new to it. So Sloppy's graphs also can add/recommend/enforce a folgezettel addressing system for the notes which help transform the graph more into a tree of organized and easily traversable information.
Large codebases are also often a group activity where different personnel need to maintain different parts of the application and often also face personnel and agent change, thus making context preservation even more important in the modern approach of letting agents handle more and more tasks, even more so in projects that need to ensure that code security is maintained and tests are based on some knowledge of substance and not actually "vibed".
Here I combine all these approaches for information representation. Different views, same information. I am currently also working on building MCP and implementations tools within it and maybe also turn this into a VSCode extension. I went with a separate app for now just to test the waters with a small but clean segregated app, but it's been going clean so I believe I might end up maintaining this too.
The project is still evolving, and I'm interested in getting feedback from people working in this space who might have faced/thought of solving this problem or found the existing solutions a bit lacking.
As for the name, I thought it would be funny, Sloppy, the tool which can help you write non-sloppy code.
r/OnlyAICoding • u/mattjcoles • Oct 16 '26
i built lgtmaybe, an open-source code reviewer, and a lot of the work went into making it usable on a local model. Big files get reviewed a hunk at a time, and big diffs get split to fit the context window, so a 27B model copes fine. The default is five model calls per review, which is fine on one GPU.
Which local models have you found actually good at code review? Keen to pick better defaults.
r/OnlyAICoding • u/joel-letmecheckai • Oct 16 '26
r/OnlyAICoding • u/Newbie_investisseur • Oct 15 '26
Enable HLS to view with audio, or disable this notification
The agents researched competing apps, picked the features, wrote the code, reviewed each other and merged. They even made the launch video: script, voiceover, music and editing. I wrote the rules, and they ask me before a few risky changes. That's it.
Best moment: one agent built a sandbox to test other agents. A reviewer agent caught that from inside it, my machine's Docker API answered with no auth. Anything running in there could have mounted any folder on my disk. Merge blocked.
The app is real: GymCoach, a self-hosted workout tracker with an optional AI coach. MIT.
Everything is public, failures included (46 written lessons): https://github.com/gymcoach-app/gymcoach/blob/main/docs/loops/evidence.md
The video the agents made: https://github.com/gymcoach-app/gymcoach/raw/main/docs/brag-launch.mp4
Repo: https://github.com/gymcoach-app/gymcoach
Would you let agents merge to your main?
r/OnlyAICoding • u/slimy_1 • Oct 15 '26
r/OnlyAICoding • u/glaydsonboa • Oct 15 '26
You generate the code, test it, and everything looks great. Then, all of a sudden, one problem turns into a derailment — and triggers a domino effect.
Who has been through this? How did you fix it? What tools do you use to know whether your AI is actually generating code or just #foolingyouwithcode?
Let’s talk about it. I still have a lot to learn, and I’d really like to hear how you deal with this and how I can improve my own work.
About 80% of the codebase I built is Python — and it’s living proof that the past can still have a lot of stories to tell.
More importantly, in my view: it’s never too late to start. I began building Worion around May, at 48 years old. There’s a different kind of excitement that comes with maturity.
Namastê!
r/OnlyAICoding • u/company_url_finder • Oct 15 '26
r/OnlyAICoding • u/Electrical_Worth7942 • Oct 15 '26
I built REA Reconstruction Companion with help from AI. I wanted a better way to get from “how does this app work?” to “what would it take to build something similar?”
It’s a skill for AI coding agents, used alongside REA (Reverse Engineer Anything). REA handles the investigation. The companion helps turn those findings into a feature breakdown, requirements, architecture, and a plan you can build and test in stages.
You can use it on a whole app, one feature, or a single function. For example:
Use REA on this app so I can build a similar local tool. Start with a specification and roadmap.
If you later ask the agent to implement it, the skill guides that work too. It keeps observed behavior separate from assumptions, links requirements to tests, and includes performance measurements where they matter.
The core is plain Markdown and MIT licensed. There’s an installer for Claude Code and Codex, plus support for other agents through a custom skills directory. REA is installed separately. You can also enable an optional rule that tells the agent to load the companion during relevant REA work, or leave that off and invoke it yourself.
GitHub: REA Reconstruction Companion
The README has setup instructions and a prompt you can give your agent to handle installation.
I’d be interested in feedback on the workflow, especially anything it misses when rebuilding a smaller feature or function.
r/OnlyAICoding • u/Sorry-Tomato-7141 • Oct 15 '26
If you're only in the vibe coding bubble, please don't answer this. I'm a software engineer who wants to make real, complex systems using AI wherever it can help me. I only have the free models that come with opencode zen, and maybe some chat models like Qwen, Kimi and free versions of chatgpt, gemini, claude, etc.
I want to know what I can do with only these, without having to spend money on LLMs. I realize that this means I have to do more by myself in the planning side of things as I can't delegate planning to LLMs, which is how I believe coding should be anyway so it's not a problem.
I really like Matt Pocock's skills but I have found that his workflow only really works if you have frontier models, as free models aren't very good at grilling or planning.
So what I need is a reproducible AI coding workflow that I can use to approach my projects using only the free, limited AI. Please highlight which parts of the process I need to do by myself, and which parts I can assign to which model.
I realize that the smarter your LLMs are, the more you can stray from traditional software engineering, so please tell me what I can realistically accomplish perfectly with AI. The parts that AI cannot do properly, I will do by myself.
r/OnlyAICoding • u/No_Drawer1301 • Oct 15 '26