<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tony Alapatt on Medium]]></title>
        <description><![CDATA[Stories by Tony Alapatt on Medium]]></description>
        <link>https://medium.com/@tonypiusalapatt?source=rss-e2f0bd5541d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_fR7BeJ_8eYW7T558mWelA.png</url>
            <title>Stories by Tony Alapatt on Medium</title>
            <link>https://medium.com/@tonypiusalapatt?source=rss-e2f0bd5541d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:51:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tonypiusalapatt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PocketNVR — Selfhosted AI Security Hub]]></title>
            <link>https://medium.com/@tonypiusalapatt/pocketnvr-selfhosted-ai-security-hub-4e9b582d578b?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e9b582d578b</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[nvr]]></category>
            <category><![CDATA[yolov11]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 15:26:01 GMT</pubDate>
            <atom:updated>2026-10-29T15:26:01.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pb0ZRnBCR3hL2v-Xl1ZwRw.png" /></figure><h3>I turned my old OnePlus 7 into a self-hosted AI security hub — and its GPU lost to its own CPU</h3><p><em>Continuous recording, on-device YOLO detection, push alerts and an installable web UI, running as root Linux daemons on a rooted Android phone. No cloud, no subscription, and no footage ever leaves the house. Code: </em><a href="https://github.com/tonypius/pocket-nvr"><em>github.com/tonypius/pocket-nvr</em></a><em>.</em></p><h3>The number that broke my assumptions</h3><p>Every edge-ML guide tells you the same thing: put the model on the GPU. So when I got YOLO11n running on a spare 2019 OnePlus 7, I benchmarked the GPU path first, fully expecting it to win. Here’s what came back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5f1DPy1M3IyM1XEnzZMlkA.png" /></figure><p>On this phone, for this model, the GPU is nearly four times <em>slower</em> than the CPU sitting next to it.</p><p>This post is the story of the appliance I built around that surprise. I’ll get to why the GPU lost, and to why Vulkan is still exactly one config line away in case your hardware disagrees with mine. But first, what the benchmark is for.</p><p><strong>PocketNVR</strong> turns a spare rooted Android phone into a network video recorder. It records IP cameras 24/7, runs object detection on the phone itself, sends a push notification with a snapshot when a person shows up, and serves an installable web app for live view, events, clips and settings. There’s no cloud, no subscription, and no per-camera licence. Nothing leaves the LAN.</p><p>Let me concede something up front: if you came here for a better NVR than <a href="https://frigate.video/">Frigate</a>, there isn’t one here. <a href="https://frigate.video/">Frigate</a> is the closest open-source analog, it’s far more mature, and I studied it closely. What <em>is</em> worth taking from this post is the pattern underneath: <strong>static arm64 binaries plus a Magisk boot script turn any rooted Android phone into a root Linux appliance.</strong> The NVR is just the first thing I built on it. Everything else here is what it took to make that appliance survive being ignored.</p><h3>Why a rooted phone — and why not an app, or a Pi</h3><p>Start with the hardware, because it’s absurd. A 2019 flagship is an 8-core big.LITTLE SoC with a real GPU, hardware video blocks, Wi-Fi, and a thermal solution already bolted on. It also ships with a built-in UPS: the battery. To match that with a Raspberry Pi you add a power bank, a case, cooling, and an SD card you will eventually regret. And unlike a Pi, most of us already own one, sitting in a drawer.</p><p>The software decision mattered more, and everything downstream depends on it: <strong>PocketNVR is not an Android app.</strong> An app fights the platform at every turn — activity lifecycles, Doze, background-execution limits, Play Store policy. A recorder that has to run unattended for months cannot be negotiating with the OS for permission to stay awake. So I stopped treating the phone as an Android device at all. PocketNVR is a set of plain arm64 Linux daemons running as root, started at boot by Magisk. Android is demoted to two jobs: kernel and driver vendor.</p><blockquote><strong>Magisk in 200 words.</strong> Magisk is the standard way to root modern Android without touching the system partition. It patches the boot image so a small root daemon starts before Android’s framework does. The feature that matters here is modules: a zip with a few shell scripts, one of which, service.sh, runs as root on every boot once the system is up. That single hook is enough to start an entire Linux service stack. KernelSU and APatch, the main alternatives, honour the same hook, so anything that works as a Magisk boot script ports to them with little or no change. The price of admission is an unlocked bootloader, which usually means wiping the phone and possibly voiding its warranty. Use a spare.</blockquote><p>Why not just run <a href="https://frigate.video/">Frigate</a> or <a href="https://zoneminder.com/">ZoneMinder</a> in Termux or a chroot? Both assume a normal Linux userland, which on Android means proot overhead or chroot gymnastics — and a stack that starts <em>after</em> you open an app, not at boot. I wanted daemons that come up on their own before anyone touches the screen.</p><p>Why not use the phone’s own camera? There’s no clean root-level path into Android’s camera HAL, and IP cameras that speak RTSP are the commodity route anyway. That also clears up the most common misconception about this project: the phone is the <em>recorder</em>, not the camera. Your video quality is your cameras’ problem, not the phone’s.</p><p>I’ll own the downsides before you find them. An unlocked bootloader can void your warranty. With root, <em>you</em> are the security boundary. A battery held on a charger 24/7 ages badly (there’s a whole section on that). And none of this is a product — it’s a pattern you can copy, with sharp edges left in.</p><h3>Phase 0: kill the project before it costs you a month</h3><p>Before I wrote a line of architecture, I ran two throwaway smoke tests. Each one answered a question that could have killed the whole idea, and each took about an hour.</p><p><strong>Smoke test A: can a root daemon even exist at boot on this ROM?</strong> (<a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/smoke_test_a.sh">scripts/smoke_test_a.sh</a>) A static Go hello-world, built with CGO_ENABLED=0, pushed over adb and run via su -c. It printed uid:0, wrote to /data/nvr, bound a port, and came back on its own after a reboot when launched from a Magisk script. That one test proves the entire portability story. A static binary doesn’t care that Android ships its own C library; if a Go binary can run as root at boot, so can anything else built the same way.</p><p><strong>Smoke test B: does the ML stack run on this GPU at all?</strong> I cross-built NCNN with the Android NDK, Vulkan enabled, and ran YOLO11n on the Adreno 640 against a real frame with a person in it (<a href="https://github.com/tonypius/pocket-nvr/blob/main/detector/tools/vulkan_smoke.cpp">detector/tools/vulkan_smoke.cpp</a>). It found the person, on the GPU. That mattered more than it sounds: a LineageOS build only has working Vulkan if the vendor blobs came along, and I wanted to know that on day one, not after building a detector around it. (Ironically, this same tool later produced the benchmark that told me not to use the GPU.)</p><p><strong>Lesson 1: burn down the existential risks first, not the fun parts.</strong> “Can root daemons exist at boot?” and “does the ML stack run on this hardware?” were the two questions that could make every later line of code worthless. Two hours retired both.</p><blockquote><strong>Static binaries vs. bionic.</strong> Android uses its own C library, bionic, not glibc — which is why a normal Linux binary usually won’t run on a phone. There are two clean escapes, and PocketNVR uses both. Go with CGO_ENABLED=0 produces a fully static binary with no libc dependency at all. C++ built with the Android NDK links against bionic on purpose, so it runs as a native Android executable. Go for the services, NDK C++ for the detector.</blockquote><h3>The architecture: three daemons, zero Android APIs</h3><p>The whole system is three long-running processes and a shell supervisor, roughly 9,000 lines across Go, C++, JavaScript and shell. Not one of them calls an Android API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pG8CJdD2QeAjGVvzilcZA.png" /></figure><p>The main stream goes straight to disk; only the sub-stream is decoded, and only by the detector.</p><p>Every boundary sits where it does for a reason.</p><p><a href="https://github.com/bluenviron/mediamtx"><strong>MediaMTX</strong></a> handles RTSP ingest, segmented recording and restreaming. It’s vendored as a prebuilt arm64 binary, because the first rule of a hobby NVR is: do not reimplement a media server.</p><p><strong>nvrdet</strong> (C++17 on <a href="https://github.com/Tencent/ncnn">NCNN</a>) is the only latency-sensitive code in the system. It owns the loop that reads camera sub-streams and runs inference, and nothing else.</p><p><strong>nvrd</strong> (Go, CGO_ENABLED=0, pure-Go SQLite) does everything else: the event store, notifications, the REST API, the web UI, clip extraction and retention. My original spec listed these as three separate components and explicitly allowed merging them. I merged them. One process is one supervisor target and one binary to ship.</p><p><strong>nvrctl</strong> is a shell script: start, stop, status, logs, watch. Supervision lives in shell deliberately. It’s the one layer that has to work when everything else is broken, and sh is always there.</p><p>Config has exactly one source of truth. You hand-write config.yaml and secrets.yaml (mode 600); secrets are referenced as ${secret:key} and percent-escaped automatically when they land inside an RTSP URL. MediaMTX’s mediamtx.yml and the detector’s detector.json are <em>generated</em> from that file, at deploy time and again on every single boot. Derived files are never trusted. If the UI changes a camera, the next boot rebuilds everything from the one file that matters. Every daemon hot-reloads on SIGHUP, and an invalid config keeps the last good one running instead of taking the system down.</p><p>On the phone, the whole appliance is one directory:</p><pre>/data/nvr/<br> bin/{nvrd,mediamtx,nvrdet,nvrctl,ffmpeg}<br> config.yaml, secrets.yaml (600) # mediamtx.yml + detector.json are generated<br> events.db recordings/ snapshots/ clips/ logs/ run/</pre><h3>Ingest: the two-stream split is the whole trick</h3><p>One process owns the cameras. MediaMTX pulls RTSP with per-camera credentials, handles reconnects, restreams for live view, and writes fMP4 segments to disk.</p><p>The load-bearing decision is how it treats the two streams most IP cameras serve. Tapo, Dahua/CP Plus and Hikvision all offer a high-resolution main stream and a low-resolution sub-stream, and PocketNVR treats them completely differently. The main stream is <strong>recorded but never decoded</strong>: MediaMTX stream-copies it into segments, so recording costs almost no CPU. The sub-stream is the <strong>only thing ever decoded</strong>, and only by the detector, over localhost RTSP.</p><p><strong>Lesson 2: never decode what you only need to store.</strong> That split decouples everything. Camera load, network bandwidth and CPU cost stop depending on how much analysis you do. You can raise detection fps without touching recording, and recording quality without touching the detector’s budget.</p><p>Camera config exists in exactly one place. A camera entry in config.yaml becomes two MediaMTX paths — /&lt;cam&gt; for the main stream and /&lt;cam&gt;_sub for the sub-stream — rendered by a small Go generator:</p><pre>cameras:<br> - id: front_door<br> name: Front Door<br> enabled: true<br> source_main: rtsp://${secret:front_user}:${secret:front_pass}@192.168.1.10:554/stream1<br> source_sub: rtsp://${secret:front_user}:${secret:front_pass}@192.168.1.10:554/stream2<br> detect:<br> fps: 5<br> threshold: 0.5<br> zones: [] # empty = whole frame</pre><p>Recording as stream-copied segments pays a second dividend later: event clips get cut from these same segments without a single re-encode.</p><h3>The detector: where the ML actually lives</h3><p>nvrdet is a C++17 daemon with seven stages, all in <a href="https://github.com/tonypius/pocket-nvr/tree/main/detector/src">detector/src/</a>. The interesting engineering isn’t the model. It’s everything that decides whether a frame deserves the model at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rryeJcIBNR7OmM2HVl42A.png" /><figcaption>nvrdet pipeline</figcaption></figure><p>Frames without motion skip the model entirely, but still feed the event state machine so events can close.</p><p><strong>Capture</strong> (capture.cpp). For each camera, the detector spawns a static ffmpeg that reads the localhost sub-stream and writes raw frames into a pipe. I deliberately did <em>not</em> link libavcodec into the detector. Spawning ffmpeg keeps the NDK build surface tiny and gets RTSP reconnect and timeout handling for free. Each capture keeps a bounded backlog and drops the oldest frame under load.</p><p><strong>Motion gate</strong> (motion_gate.cpp). Every frame is downscaled to grayscale and diffed against the previous one, with a per-camera area threshold. Most frames die here, which is the point: inference is the expensive thing and motion is the cheap thing, so the cheap thing goes first.</p><p><strong>One queue, one worker</strong> (frame_queue.cpp, backend_ncnn.cpp). Frames that survive the gate go into a single bounded queue served by a single NCNN worker, which also drops the oldest under pressure. This is deliberately not a thread pool. Four cameras share one thermal budget, so queue depth is the pressure valve, not parallelism. The arithmetic makes it explicit: at about 88 ms per frame, one worker tops out around 11 inferences per second across <em>all</em> cameras, while four cameras at 5 fps would ask for 20. The motion gate is what makes that budget work, because a quiet scene asks for almost nothing.</p><p><strong>Zones</strong> (zones.cpp). Non-maximum suppression and confidence filtering, then a class filter from config (person, cat, dog, car), then a point-in-polygon test against per-camera zones, anchored on either any part of the box or its centre. An empty zone list means the whole frame.</p><p><strong>Event state</strong> (event_state.cpp). Raw detections flicker; events shouldn’t. Each camera gets enter and exit thresholds, peak-score tracking and a cooldown. This stage also held the subtlest bug in the detector. When a scene goes still, the motion gate stops passing frames — so the state machine never sees the “no person” frames it needs to <em>close</em> an event, and events hang open forever. The fix is what I call silence-fed negatives: while a camera has an open event and no frames are arriving, the detector feeds explicit negative samples into its state machine at that camera’s own fps. A quiet scene now closes the event exactly as a visibly empty one would.</p><p><strong>Emit</strong> (http_post.cpp, snapshot.cpp). When an event fires, the detector draws the detection boxes on the peak-score frame, saves it as a JPEG along with a cropped thumbnail of each object, and POSTs everything with a JSON event to nvrd on localhost.</p><p><strong>Governor</strong> (governor.cpp). Every 5 seconds it reads the SoC temperature and runs a three-state machine with hysteresis: at the high mark it halves the analysis fps, 10 °C above that it pauses analysis entirely, and it only steps back up once the temperature falls to the low mark. Thermal mass is slow, so the governor is too.</p><p>The model pipeline is one script: <a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/fetch_model.sh">scripts/fetch_model.sh</a> downloads YOLO11n and exports it to NCNN via PNNX inside its own virtualenv. The weights never ship in the repo, for licensing reasons I’ll come back to.</p><p>One honest gap while we’re here: every frame is currently stretch-resized to a 640×640 square, not letterboxed, so a 16:9 sub-stream gets squashed horizontally before the model sees it. Detection still works, but it’s a known accuracy cost, and letterboxing is on the list.</p><blockquote><strong>Reading NCNN output tensors.</strong> Before blaming the detector for “wrong” results, check the output tensor by hand once. YOLO11n’s output is 84 × 8400: 8,400 candidate boxes, each with 4 box coordinates followed by 80 class scores. So “person”, COCO class 0, lives in row 4, not row 0. Ten minutes of checking tensor names and shapes against the exported model saves an evening of debugging the wrong thing.</blockquote><h3>The honest part: why the GPU lost</h3><p>Back to the cold open. A 3.9× gap in the GPU’s disfavour is exactly the kind of number that’s usually a misconfiguration, so here’s precisely what was measured, and what I checked before believing it.</p><p><strong>What the benchmark measures.</strong> <a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/bench_phone.sh">scripts/bench_phone.sh</a> pushes the same test tool from Phase 0 to the phone and runs it as root against one real frame (Ultralytics’ sample bus image, which has people in it) at 640×640, once per backend. The timer wraps only the network forward pass — create_extractor through extract — so it excludes resizing and normalization, but for Vulkan it <em>includes</em> the upload to the GPU and the download of the result, because that’s what a real detector pays per frame. The CPU path uses 4 threads; the Vulkan path uses 1 feeding thread. The first run, which carries GPU shader compilation, is excluded from the steady-state figure. Each backend runs 60 times. The raw capture, with device metadata and battery temperature before and after (29 °C to 30 °C, so no throttling), is committed under bench-results/ in the repo, and both backends found the person in the frame, so they did equivalent work.</p><p><strong>What I checked.</strong></p><p>• <strong>A sleeping GPU.</strong> A root daemon has no Android graphics session asking the GPU governor to boost, so the Adreno could plausibly sit at its floor clock the whole run.</p><p>• <strong>Precision.</strong> This one turned up something real. NCNN’s device report for the Adreno 640 on this driver reads fp16-p/s/u/a=1/0/0/0: fp16 packing is supported, but fp16 storage and fp16 arithmetic are not. So the GPU path does its maths in fp32.</p><p><strong>My best explanation — and where it stops.</strong> The measurement is solid; the explanation is an inference, and I want to be precise about which is which. NCNN’s ARMv8 NEON kernels are hand-tuned and genuinely excellent. A mobile Vulkan driver pays fixed overhead on every dispatch, plus the round trip of moving the frame in and the result out. A small model like YOLO11n is many layers with little arithmetic per layer, so the GPU never gets enough work per call to amortize that overhead. The driver report adds a second, more concrete suspect: with no fp16 storage or arithmetic, the GPU works in fp32, while the CPU path gets the A76 cores’ native fp16. Both fit the numbers. I haven’t profiled per-layer dispatch time to prove it, and anyone who claims to know why their GPU lost should be able to show you that profile.</p><p><strong>Lesson 3: “the GPU is faster” is a benchmark result, not a law of nature.</strong> It’s usually true for large models on desktop GPUs. For small models on mobile drivers, measure it — your intuition was trained on different hardware.</p><p>The engineering response is boring on purpose. backend is one config key, cpu is the default, and the Vulkan path stays built and working. INT8 quantization or a smaller input might flip the balance, and a different SoC almost certainly will. The benchmark stays in the repo so new hardware gets measured, not guessed at.</p><h3>From a detection to a phone buzz</h3><p>From a person stepping into a zone to a notification on my phone takes. Here’s what happens in between.</p><p>The event store is SQLite through <a href="https://pkg.go.dev/modernc.org/sqlite">modernc.org/sqlite</a>, a pure-Go driver, which is what keeps nvrd a CGO-free static binary. The schema is shaped around the queries the UI actually makes — by camera, by time window, by label — and writes are idempotent, so a crash mid-ingest can’t leave duplicate events behind.</p><p><strong>Clips cost nothing.</strong> An event has a start, an end, and configurable pre- and post-roll. nvrd maps the window [start − pre, end + post] onto MediaMTX’s recorded segments and stream-copies them into one MP4. No transcode pass, no CPU spike. Pre-roll is free too: the recorder never stops, so the seconds <em>before</em> the detection are already on disk. That’s the two-stream decision from earlier paying its second dividend.</p><p>Notifications go to ntfy, Telegram, or both, each with its own score threshold, per-camera cooldowns and quiet hours, and every alert carries the annotated snapshot. The piece I’d copy into any alerting system I build from now on is the <strong>retry queue that replays undelivered notifications after a restart</strong>. If the network is down for an hour, your alerts arrive an hour late instead of not at all.</p><p>One trade-off I’ll name rather than hide: notification deep links carry the API token, because the snapshot image has to authenticate somehow. On a bare LAN setup, that makes your ntfy topic or Telegram chat as sensitive as a password. The Cloudflare front door described later defuses most of this, but treat the chat as sensitive anyway.</p><p>[FILL: lock-screen screenshot of a notification with its snapshot]</p><p>Retention is holistic. Events are pruned by age and count, recordings by age and total size, and database rows die <em>with</em> their files, so there are no orphaned JPEGs and no rows pointing at deleted clips.</p><p>And then there’s the airbag. <strong>A recorder that fills its disk is bricked.</strong> When free space falls below a floor, nvrd prunes first. If that isn’t enough, it pauses continuous recording through a MediaMTX hot-reload while detection keeps running, so you still get alerts even when you can’t get footage. The health endpoint reports degraded until space recovers, and recording resumes on its own.</p><h3>The secrets bug worth stealing a lesson from</h3><p>nvrd guards every /api route with one token, accepted as a Bearer header, an X-Api-Token header, or ?token= for image tags and deep links. Only the static app shell is open, so the web app can render its own login screen. The surface is small:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBvE3AJwMkuaWJfHhyQLXg.png" /></figure><p>Secrets are write-only: no API ever returns a secret value. GET /api/config hands back the config with each secret replaced by its ${secret:…} placeholder, and those placeholders survive a round-trip, so the Settings page can edit and save the full config without ever seeing a camera password.</p><p>My first implementation of that redaction worked by <em>value</em>. It took each secret’s value and replaced it wherever that string appeared in the config. Then two of my cameras turned out to share a password. On a round-trip through Settings, the redactor found the same value in both camera entries and couldn’t tell which placeholder belonged where, so the cameras cross-contaminated each other’s placeholders: after a save, one camera’s entry could point at the other camera’s secret keys. Everything kept working — right up until one of those passwords changed. [FILL: confirm this matches what happened, and name the symptom you actually saw]</p><p>The fix was field-path redaction: a value is redacted because of <em>where it sits</em> in the YAML tree, never because of what it matches.</p><p><strong>Lesson 4: never transform a config by matching secret values.</strong> Passwords repeat. And credentials are the one place you can’t afford ambiguity about which value belongs to whom.</p><h3>The UI: a PWA, on purpose</h3><p>The interface is an installable progressive web app served by nvrd itself, with no framework and no build step. There’s nothing to sideload, it works from any device in the house, and it updates whenever the server does. Open http://&lt;phone-ip&gt;:8099/, sign in with the token, tap “Add to Home screen”, and you have an app icon. A native viewer is still possible later against the same API.</p><p>Before building it, I studied the NVR interfaces people actually like — Frigate, UniFi Protect, Scrypted — and the ones they tolerate, like Blue Iris and ZoneMinder. One line from that review (<a href="https://github.com/tonypius/pocket-nvr/blob/main/UI-PLAN.md">UI-PLAN.md</a>) stuck with me: <strong>filter power without polish loses to polish with filters.</strong> Deep configuration doesn’t save a UI people don’t enjoy opening.</p><p>Live view uses WebRTC (WHEP) for sub-second latency, proxied through nvrd. When WebRTC’s UDP can’t get through — restrictive networks, TCP-only tunnels — the player falls back automatically to an HLS stream that nvrd also proxies. Hold onto that; it matters again in the remote-access section.</p><p>Events and Detections show snapshot thumbnails and cropped object chips, filterable by camera, label and time. A Clips feed plays event MP4s inline, loading previews only while they’re on screen so a long scroll stays cheap on mobile data. Recordings proxies MediaMTX’s playback server, so you can scrub through the archive.</p><p>Settings is where the demo moment lives. Discovery runs ONVIF WS-Discovery plus an RTSP sweep of the local /24 subnet, and one click lists the cameras on your network. There’s a write-only secrets editor, and every save runs server-side validation and a hot-reload.</p><h3>Surviving reboots: Android is Linux-shaped, not Linux</h3><p>The Magisk module is deliberately thin. It’s <a href="https://github.com/tonypius/pocket-nvr/tree/main/deploy/magisk-module">module.prop, customize.sh and service.sh</a>, plus one file overlay I’ll come to. It owns boot, and nothing else. All binaries and config live in /data/nvr, managed by the deploy script, for two reasons: updating the payload shouldn’t mean re-flashing a zip, and uninstalling the module must never delete your recordings.</p><p>Here’s what service.sh does on every boot. Almost every step exists because something broke without it.</p><p>1. <strong>Clear stale PID and backoff files.</strong> A reboot or a dead battery leaves the run directory behind. Android recycles PIDs, so a stale pidfile can make the supervisor believe a dead daemon is alive — blinding both start and the watchdog — and a stale backoff counter can delay recovery by up to ten minutes.</p><p>2. <strong>Wait for sys.boot_completed</strong>, for up to about two minutes.</p><p>3. <strong>Wait for a default network route</strong>, for up to two minutes, then start anyway; the daemons keep retrying their cameras.</p><p>4. <strong>Take a kernel wakelock</strong> with echo pocketnvr &gt; /sys/power/wake_lock. It sits below anything Doze can touch, so Android can’t put the SoC to sleep and stall recording.</p><p>5. <strong>Regenerate mediamtx.yml and detector.json</strong> from config.yaml, so a change made in the UI always survives a reboot.</p><p>6. <strong>Start MediaMTX, nvrd and the detector in order</strong>, then launch the watchdog.</p><p>Step 3 is where I lost an evening. My first version waited for a default route with ip route show, which works on every Linux box I’ve ever used. On Android it waited forever. Android doesn’t keep the default route in the main routing table; it keeps one table <em>per network</em>, selected by policy rules. ip route show prints only the main table, which has no default route at all. The fix was three words: ip route show table all.</p><p>The second trap was quieter and worse. Android has no /etc/resolv.conf. Android’s own apps never notice, because they resolve names through the platform. A static Go binary doesn’t know that: it falls back to asking a DNS server on [::1]:53, which doesn’t exist, and every lookup fails. Local RTSP by IP address works fine, so the NVR looks healthy — until nvrd tries to send a push notification, or cloudflared tries to reach Cloudflare. The fix is that one file overlay: the module ships a <a href="https://github.com/tonypius/pocket-nvr/blob/main/deploy/magisk-module/system/etc/resolv.conf">system/etc/resolv.conf</a> that Magisk mounts over the system partition at boot.</p><p><strong>Lesson 5: Android is Linux-shaped, not Linux.</strong> The kernel is the same; the userland assumptions aren’t. Routing tables, DNS and PIDs all behave just differently enough to break code that has run on Linux for years. If you’re porting a static binary to a rooted phone, assume nothing about /etc.</p><p>Once everything is running, nvrctl watch checks every daemon every 15 seconds and restarts any that died. Restarts back off exponentially from 30 seconds to 10 minutes, the backoff resets once a daemon has stayed up for 5 minutes, and logs rotate at 5 MB. A crash-looping daemon can’t hammer the phone.</p><p>The acceptance test is a script, not a feeling: scripts/install_boot_module.sh — reboot installs the module, reboots the phone, waits for it to return, and prints nvrctl status. If that isn’t all green, the module isn’t done.</p><h3>Power and thermals: the failure mode nobody blogs about</h3><p>A lithium battery held at 100%, warm, all day, every day, can swell within months. An always-plugged-in phone is exactly that battery. If you take one operational warning from this post, take this one.</p><p>The fix is to hold the charge in a band, roughly 60–70%. I use <a href="https://github.com/VR-25/acc">ACC (Advanced Charging Controller)</a>, a separate Magisk module by VR-25: acc 70 60 pauses charging at 70%, lets the phone drain a little, and resumes at 60%, and the setting persists across reboots. Support varies by phone, so confirm on your model that charging really pauses at the limit. PocketNVR deliberately doesn’t bundle or drive ACC. Power management is per-device and safety-critical, so it belongs to a tool that does nothing else; the charge_cap_pct field in my config is only a record of intent, not a control.</p><p>The upside is the battery’s second life as a <strong>built-in UPS</strong>. A power blip is a non-event. A Raspberry Pi without a UPS risks corrupting its SD card every time the power drops.</p><p>Thermals are handled twice. In software, the detector’s governor halves and then pauses analysis as the SoC heats up. Physically, placement matters more than people expect: a sunny windowsill in summer is the design case, not the edge case.</p><h3>Remote access: Cloudflare is the front door, and nothing is exposed</h3><p>The one rule that never bends: <strong>never forward port 8099 to the internet.</strong> The way in from outside is a <a href="https://github.com/tonypius/pocket-nvr/tree/main/deploy/cloudflare">Cloudflare Tunnel with Cloudflare Access</a> in front of it. You get <a href="https://nvr.yourdomain.com/">https://nvr.yourdomain.com</a> from anywhere in the world, with no port forwarded on the router and nothing on the phone reachable from the internet.</p><p>The trick is that the connection runs backwards. cloudflared on the phone dials <em>out</em> to Cloudflare and holds the connection open. A browser anywhere hits Cloudflare’s edge, which terminates TLS, checks who you are, and only then sends the request down the tunnel to nvrd on 127.0.0.1:8099. cloudflared is just one more nvrctl component, called tunnel: started at boot, watched, and restarted with backoff like every other daemon. In the 31 days of device logs in the repo, the watchdog restarted it 4 times, and nobody had to notice. On the LAN, nvrd keeps listening on port 8099 exactly as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-hJUzXTqiLd8NjoujwLqw.png" /><figcaption>Remote access path · Cloudflare Tunnel + Access</figcaption></figure><p>The phone dials out to Cloudflare; remote browsers never connect to it directly, and only the LAN reaches port 8099.</p><p><strong>The recommended setup needs no login on the phone at all.</strong> In the Zero Trust dashboard you create a tunnel named pocketnvr and copy its connector token. <a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/cloudflare-token.sh">scripts/cloudflare-token.sh</a> installs that token on the phone (mode 600) and starts the supervised tunnel. Back in the dashboard, you add a public hostname pointing at <a href="http://localhost:8099,">http://localhost:8099,</a> which creates the DNS record too. The phone only ever holds a token; ingress and DNS live in the dashboard. If you’d rather keep ingress in a file, <a href="https://github.com/tonypius/pocket-nvr/blob/main/deploy/cloudflare/setup.sh">setup.sh</a> does the CLI version — and it hit Lesson 5 again. Root’s HOME is unstable under su on Android, so cloudflared’s default ~/.cloudflared paths are a trap, and the script pins HOME and the origin certificate under /data/nvr/cloudflare. Even adb shell su -c “a &amp;&amp; b” bites: the &amp;&amp; is parsed <em>outside</em> su, so only the first command runs as root. The repo pushes multi-step device commands as script files for exactly that reason.</p><p><strong>Cloudflare Access is the gate.</strong> It’s one self-hosted application in the Zero Trust dashboard, free for up to 50 users, with an Allow policy listing the identities you approve: specific email addresses (they log in with a one-time PIN) or specific Google accounts. Approving someone means adding them to the policy; revoking them means removing them, and with session revocation turned on, that cuts them off mid-session. Only approved identities ever reach nvrd’s login page.</p><p>One setting there matters far more than it looks: <strong>expired sessions must return HTTP 401, not a redirect.</strong> By default, Access redirects an expired session to its login page. A browser navigating to the site handles that fine. But the PWA’s fetch, server-sent-event and HLS requests don’t navigate; they get an HTML login page where they expected JSON or video, and fail in confusing ways. Configured to return 401, they fail cleanly into the app’s own login gate.</p><p>The auth is two layers on purpose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjQgxowLgNe1pabTYnS30g.png" /></figure><p><strong>Lesson 6: put identity at the edge, and keep a secret at the origin.</strong> Either layer can fail on its own without the cameras going public. The token is one shared secret, though, so if you ever remove a person, rotate it too: they saw it once.</p><p>This also fixes the deep-link problem from earlier. Set notifications.base_url to your HTTPS hostname, and every push notification links to the Access-protected origin. The token is still in the link, but a leaked link is dead weight to anyone Access didn’t let in.</p><p>Video works through the front door too. HLS is proxied straight through the tunnel. WebRTC’s signalling goes through nvrd’s WHEP proxy, while the media itself tries to flow directly over UDP, and the player falls back to HLS wherever UDP can’t get through. That’s the fallback from the UI section, earning its keep. Design for your worst transport, not your best.</p><p>Optional hardening, in the same dashboard: a WAF rule that only admits the countries you actually live in, and the Access logs, which show exactly who reached the NVR and when. Then check the gate before you share the URL with anyone:</p><pre>curl -si https://nvr.example.com/api/health | head -1<br> # redirect to &lt;team&gt;.cloudflareaccess.com -&gt; the Access gate is working</pre><p>If you don’t own a domain, Tailscale still works for a private, VPN-only setup.</p><p>A word of threat-model honesty: even behind all this, it’s video from inside your home. Keep the Access policy short, keep the token long, and treat everyone on that policy as someone who can see your cameras.</p><h3>Will this run on your phone?</h3><p>Everything in this post was measured on one OnePlus 7, so let me separate what’s portable by construction from what isn’t.</p><p>The boot module is portable by construction. service.sh uses only getprop, ip, /sys/power/wake_lock and POSIX shell — nothing OnePlus- or LineageOS-specific — and any Magisk, KernelSU or APatch device runs the same boot hook. So is the payload: every binary is static Go or NDK-built C++, so there’s no glibc-versus-bionic question to answer.</p><p>The per-device caveats, honestly:</p><p>1. <strong>arm64 only.</strong> 32-bit phones are out.</p><p>2. <strong>Wakelocks need kernel support.</strong> /sys/power/wake_lock needs CONFIG_PM_WAKELOCKS; without it the log says wakelock FAILED and the phone may deep-sleep mid-stream.</p><p>3. <strong>The thermal sensor may be the wrong one.</strong> The governor reads /sys/class/thermal/thermal_zone0, and which physical sensor that is varies by SoC. Check it on your phone before trusting the governor.</p><p>4. <strong>Inference speed is per-SoC.</strong> My CPU-beats-GPU result belongs to this chip and this driver; Mali GPUs have a different Vulkan story from Adreno. CPU is the portable default — run bench_phone.sh and find out for yourself.</p><p>5. <strong>Thermals scale with the chassis.</strong> A smaller phone throttles sooner.</p><p>6. <strong>ACC is per-device</strong>, and so are the Wi-Fi settings you’ll want: Wi-Fi kept on during sleep, plus a DHCP reservation for the phone.</p><p>The floor is Android 10 or newer, arm64, working Magisk, and 32 GB or more of storage.</p><h3>How it got built: the phone is the target, not the workbench</h3><p>This was an evenings-and-weekends project, and the single biggest reason it got finished is that almost nothing needed the phone to be tested.</p><p>go test ./… runs 32 Go test functions on the Mac, and the detector has its own C++ core tests. <a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/smoke_local.sh">scripts/smoke_local.sh</a> validates the config, generates mediamtx.yml, and proves MediaMTX actually boots with it. <a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/build_arm64.sh">scripts/build_arm64.sh — docker</a> builds the exact binaries that ship to the phone and runs them in an arm64 Linux container; Apple Silicon runs arm64 containers natively, with no emulation, so the real phone artifacts get validated before they ever touch a USB cable.</p><p>The most useful is <a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/e2e_detector.sh">scripts/e2e_detector.sh</a>: the full pipeline with zero cameras and zero phones. It publishes a looping synthetic camera over RTSP and asserts that detections become events in the store with valid JPEG snapshots. Nothing in it needs hardware, so it can run in CI.</p><p>Finally, <a href="https://github.com/tonypius/pocket-nvr/blob/main/scripts/deploy.sh">scripts/deploy.sh — start</a> cross-compiles, verifies the ELF architecture of every artifact, pushes over adb (USB or wireless), generates runtime configs and starts the stack. A wrong-architecture binary fails on my laptop, not on the phone at 2 a.m.</p><p>The phone was only ever needed for the questions only the phone can answer: Vulkan on Adreno, Magisk boot, wakelocks, thermals and storage.</p><p><strong>Lesson 7: the ratio of tests that run without the hardware to tests that need it decides whether a hardware side project ever ships.</strong></p><h3>What it costs, what’s missing, and what’s next</h3><p>The parts list is one used phone that can be rooted (check the LineageOS device list), a stand, a charger, and the IP cameras you already own. If the phone is already in your drawer, the hardware cost is close to zero.</p><p><strong>Licensing, plainly.</strong> The PocketNVR code is MIT. The YOLO11n weights are not: they come from Ultralytics under AGPL-3.0, which is why the repo never ships them and fetch_model.sh generates them on your own machine. For personal use that’s fine. If you want to distribute this or build a service on it, read Ultralytics’ terms first, or swap in a permissively licensed detector such as YOLOX-tiny or NanoDet. Please don’t cargo-cult the repo into a product without checking.</p><p>The usual disclaimers apply, and I mean them: unlocking the bootloader can void your warranty, the battery needs watching, and you should only point cameras where it’s legal to record.</p><p>What’s next, in rough order: letterboxing frames instead of stretching them; revisiting INT8 quantization, which might be what finally lets the GPU win; the UI upgrade plan in UI-PLAN.md; having nvrd validate Cloudflare Access’s signed JWT, for true per-user identity at the origin (signature validation only, never the plain email header, because nvrd also listens on the LAN where headers can be forged); and a native viewer if the PWA ever stops being enough.</p><p><strong>One ask.</strong> The repo is at <a href="https://github.com/tonypius/pocket-nvr">github.com/tonypius/pocket-nvr</a>. If you have a spare arm64 phone with root, run scripts/bench_phone.sh on it and post your CPU and Vulkan numbers in the comments. I genuinely want to know whether my result holds on other chips, or whether the Adreno 640 is the odd one out.</p><p>The phone in your drawer isn’t e-waste. It’s a root Linux box with a UPS, a GPU you may not need, and a CPU that’s better than you think — and it has been waiting for a job. Give it one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e9b582d578b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your System Prompt Is Full of Dead Code]]></title>
            <link>https://medium.com/@tonypiusalapatt/your-system-prompt-is-full-of-dead-code-08036543c9fc?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/08036543c9fc</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 13:56:37 GMT</pubDate>
            <atom:updated>2026-08-25T13:56:37.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sFz57_cm9CGOx8yoIQaXw.png" /></figure><p><em>Nobody on your team knows which lines of your system prompt actually do anything. I built a tool that answers the question with confidence intervals instead of vibes.</em></p><p>Open the system prompt of any LLM feature that’s been in production for six months. You’ll find something like this:</p><blockquote><em>You are a senior application security engineer with 15 years of experience reviewing production code. You are meticulous, thorough, and never miss edge cases. Analyze the provided diff line by line. Consider how user-controlled input reaches the query. Respond with exactly one word: “vulnerable” or “clean”.</em></blockquote><p>Four sentences. Which ones matter?</p><p>Somebody added the persona line because a blog post in 2023 said role prompting improves accuracy. Somebody added “meticulous, thorough” after a bad week of false negatives. The “line by line” instruction came from an intern’s A/B test nobody can find anymore. The prompt grew by accretion, the way legacy code does — and like legacy code, nobody deletes anything, because nobody knows what’s load-bearing.</p><p>Unlike legacy code, every line here has a per-request cost. That persona sentence is ~30 tokens on every single call, forever. And the research suggests it might be worse than useless.</p><h3>The research says: it depends, and nobody measures</h3><p>The persona-prompting literature is genuinely contradictory. Early work found that adding expert personas to system prompts doesn’t improve performance beyond chance on knowledge benchmarks. More recent work found personas <em>help</em> on some task categories and <em>hurt</em> on others — the same behavioral signals that improve tone and structure appear to interfere with factual accuracy. Other studies found role-play prompts degrading reasoning, and irrelevant persona attributes (a name!) measurably hurting even large models.</p><p>You can read this literature as “personas don’t work.” I read it differently: <strong>the effect is real, small, inconsistent, and conditional on model, task, and phrasing — which means no general answer exists, and every team is on its own.</strong> The field’s honest conclusion isn’t a recommendation. It’s a measurement obligation.</p><p>And here’s the gap: the tooling to meet that obligation doesn’t exist. We have excellent prompt <em>regression</em> tooling now — promptfoo and friends will run your evals in CI and fail the build when quality drops. But regression testing answers “<strong>does my prompt pass?</strong>” Nothing answers “<strong>does this paragraph cause the passing?</strong>” Those are different questions. The first is a threshold; the second is an attribution — a counterfactual. Your prompt can pass every gate while carrying 200 tokens of dead weight, and no gate will ever tell you.</p><p>In any other engineering discipline we have a name for finding out whether a component contributes: an ablation study. We run them on model architectures routinely. Nobody runs them on the paragraphs of their own system prompt.</p><h3>fragcheck: ablation testing for prompt fragments</h3><p>So I built <a href="https://github.com/tonypius/fragcheck">fragcheck</a>. It’s a small Python CLI — deliberately small, ~700 lines you can read in a sitting — that does one thing:</p><ol><li>You split your system prompt into named fragments in a YAML file.</li><li>You point it at an eval suite you already have: JSONL of inputs with programmatically checkable expected outputs.</li><li>It runs the suite with the full prompt, then once more per fragment with that fragment removed — same items, same order, paired.</li><li>A stats layer decides whether each fragment’s contribution is real or noise, per model.</li></ol><p>The output is a table:</p><pre>model: &lt;model-a&gt;   suite: sqli   metric: exact_match   n=150<br>full-prompt score: 0.960</pre><pre>Fragment                 Δ  95% CI                p(McNemar)  ~tokens  Verdict<br>------------------------------------------------------------------------------<br>method              +0.087  [+0.027, +0.147]      0.0106      23       LOAD-BEARING<br>persona             +0.000  no measurable effect  1.0000      30       DECORATIVE<br>roleplay            -0.053  [-0.098, -0.011]      0.0342      41       HARMFUL</pre><p><em>(Illustrative numbers — real results below.)</em></p><p>Three verdicts, from the confidence interval on the paired delta:</p><ul><li><strong>LOAD-BEARING</strong> — the CI sits entirely above your minimum effect size. Removing this fragment measurably hurts. Keep it.</li><li><strong>HARMFUL</strong> — the CI sits entirely below zero. This fragment is <em>hurting</em> your accuracy while costing you tokens. Delete it and enjoy the irony.</li><li><strong>DECORATIVE</strong> — the CI straddles zero. No measurable contribution at this sample size.</li></ul><p>That last verdict is deliberately not named USELESS, and the distinction matters. Absence of evidence at n=150 is not evidence of absence — a fragment with a true +2% effect will read DECORATIVE at small n. The report prints n and the CI width precisely so you can judge statistical power yourself. A measurement tool that hides its own resolution limit is a lying measurement tool.</p><h3>The results</h3><p><strong>[PLACEHOLDER — DO NOT PUBLISH UNTIL THIS SECTION IS REAL.</strong></p><p><strong>The experiment: N popular persona/instruction fragments collected from public prompt libraries, ablated across M models on K eval suites, n≥150 items each. Report: how many fragments were LOAD-BEARING / DECORATIVE / HARMFUL per model; the full table; at least one cross-model verdict flip; total token cost of the decorative fragments per 1M requests.</strong></p><p><strong>This table is the centerpiece of the post. Everything above is thesis; this is evidence.]</strong></p><h3>The results</h3><p>I ran this against a live model rather than illustrate it. Single model — GLM-4.6 — the shipped example/prompt.yaml suite (a SQL-injection classification task), no cache, 90 real completions:</p><pre>model: glm-4.6   suite: sqli   metric: exact_match   n=30<br>full-prompt score: 1.000<br><br>Fragment                 Δ  95% CI                p(McNemar)  ~tokens  Verdict<br>------------------------------------------------------------------------------<br>persona             +0.000  no measurable effect  1.0000      30       DECORATIVE<br>method              +0.000  no measurable effect  1.0000      37       DECORATIVE</pre><p>GLM-4.6 gets all 30 cases right with the full prompt, and still gets all 30 right with either fragment removed. Both read DECORATIVE. That’s not the flashiest result I could have picked, but it’s the honest one, and it arguably makes the point harder than a mixed table would have: two paragraphs of persona and process instruction, ~67 tokens combined, billed on every single call, with zero measured contribution to this model’s accuracy on this task.</p><p>Read it with the same discipline the tool asks of you. n=30 is well below the n≥150 this piece treats as a reasonable floor elsewhere, and the full-prompt score is already at the ceiling — 1.000 leaves no room for a fragment to show a <em>positive</em> contribution on this suite; DECORATIVE here means “removing it didn’t cost anything I could detect at this sample size,” not “proven to be zero effect at any n.” That distinction is the whole thesis, and I’m not exempting my own table from it. If you want more confidence than that, run it yourself with more cases, more models, and a harder suite than this one — the tool prints n and the CI width so you don’t have to take my word for the difference between “no effect detected” and “no effect.”</p><p>What this table <em>does</em> establish, unqualified: the two fragments this run tested were carried on every one of 30 real requests, cost real tokens, and produced a measured, reproducible zero. That’s not a vibe. That’s what the tool is for.</p><h3>What the tool taught me while I was building it</h3><p>The interesting problems all turned out to be honesty problems.</p><p><strong>Zero variance is not high precision.</strong> When a fragment flips zero scored outcomes across all 150 cases, the bootstrap has no variance and dutifully reports a CI of [+0.000, +0.000]. That <em>looks</em> like the most precise measurement in the table. It’s actually the least informative result the tool can produce — so fragcheck prints “no measurable effect” instead of an interval. A zero-width CI on a discrete metric is false precision wearing a lab coat.</p><p><strong>Your cache can hide exactly the regression you’re testing for.</strong> fragcheck caches every completion, content-addressed, so reruns are free. But cache keys include the model name you <em>request</em> — and a floating alias can resolve to different weights over time while the alias string never changes. Pair a cached floating alias with the CI regression gate (fragcheck run --baseline old.json --check) and the gate goes green on precisely the model drift it exists to catch. The fix is boring and mandatory: pin dated model snapshots, and the tool warns you when you don&#39;t.</p><p><strong>Verdicts don’t transfer across models — and that’s half the product.</strong> In testing, the same fragment with the same underlying effect size came back LOAD-BEARING on one model and DECORATIVE on another, purely because the noisier model has a wider CI at the same n. The unit of measurement is (fragment, model, suite, n). Anyone who tells you a prompt fragment “works,” without telling you all four, is reporting a vibe.</p><p><strong>No LLM-as-judge, and this is a hard line.</strong> Every metric in v1 is deterministic — exact match, containment, label F1 against real labels. The moment a model scores the eval, you’ve reintroduced circular validation: a judge that shares the persona’s biases will grade the persona kindly. Judge metrics may arrive in v2 behind a very clearly labeled fence. In v1, if you can’t check it with a string comparison, fragcheck won’t measure it.</p><h3>The limitations, because they’re load-bearing too</h3><p>Leave-one-out ablation is a deliberate cost tradeoff — k fragments cost (k+1)·n calls instead of 2^k·n — and it is blind to interactions: two fragments that are redundant with <em>each other</em> will both read DECORATIVE, even though removing both would hurt. Known, documented, unfixed in v1.</p><p>There’s no multiple-comparisons correction yet. Every (fragment, model, suite) cell gets its own 95% CI, so as your matrix grows, a few LOAD-BEARING or HARMFUL calls will appear by chance. And your verdicts are exactly as good as your eval suite — garbage cases, garbage verdicts. The tool measures your prompt against <em>your</em> definition of correct; it cannot rescue a bad definition.</p><p>I’m listing these in the launch post because a measurement tool that undersells its own error bars has disqualified itself from its job.</p><h3>Prompts are dependencies</h3><p>The larger point isn’t about personas. It’s that we version, pin, test, and audit every dependency in our stack <em>except</em> the paragraph of English that steers the model — the one dependency that silently changes behavior when a provider updates weights under the same alias. fragcheck run --check in CI is the smallest possible version of treating prompt fragments the way we treat packages: with a lockfile mentality and a test that fails when the contract breaks.</p><p>The repo is at [<a href="https://github.com/tonypius/fragcheck">LINK</a>]. It’s Python 3.11+, four dependencies, MIT. Split your system prompt into fragments, point it at the evals you already have, and find out which of your paragraphs are earning their tokens. I’d genuinely like to see your tables — especially the HARMFUL rows.</p><p>My prediction, having run this on my own prompts first: you have more dead code than you think, and at least one line you were proudest of is decorative.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08036543c9fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running a 24/7 AI-Agent Workspace on Your Own Server — Private, Over Tailscale, With Mobile That…]]></title>
            <link>https://medium.com/@tonypiusalapatt/running-a-24-7-ai-agent-workspace-on-your-own-server-private-over-tailscale-with-mobile-that-0fa6d6b553a5?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fa6d6b553a5</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[buzz]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 14:16:41 GMT</pubDate>
            <atom:updated>2026-08-18T14:16:41.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Running a 24/7 AI-Agent Workspace on Your Own Server — Private, Over Tailscale, With Mobile That Actually Works</h3><p>I wanted a small team of AI agents that live on a server, run around the clock, and answer me from my laptop <em>and</em> my phone — without keeping my laptop awake, and without exposing anything to the public internet. <a href="https://github.com/block/buzz">Buzz</a> (Block’s open-source, Nostr-based agent workspace) turned out to be a great fit, but a few things aren’t obvious from the docs and one thing is outright broken out of the box.</p><p>This is the end-to-end build: a self-hosted relay on an always-on Linux VM, reachable only inside a Tailscale tailnet with real TLS, a set of persona-driven agents running as 24/7 services, and — the part that took the most digging — <strong>working desktop-to-mobile pairing on a self-hosted relay.</strong></p><p>The relay image is multi-arch, so any small always-on Linux box works (arm64 or x86–64). Everything below assumes Ubuntu/Debian.</p><h3>The mental model (why this works at all)</h3><p>Buzz is hub-and-spoke. A <strong>relay</strong> is the single source of truth. Everything else — the desktop app, the phone, and each <strong>agent</strong> — is just a client that connects <em>to the relay</em> over WebSocket. Crucially, an agent is not something your desktop app runs; it’s an independent process (its own keypair) that connects to the relay on its own and sits in a channel 24/7.</p><pre>Laptop (desktop app) ─┐<br>Phone (mobile app) ───┼──wss──►  relay  ◄──ws── agent processes (run on the server)<br>Agent harness ────────┘                          each = a keypair + a system prompt</pre><p>That’s the whole reason this setup delivers what I wanted: the agents run on the server regardless of whether any client is connected. I @mention one from my phone, it does the work on the box, and the reply comes back to every device I&#39;m signed in on.</p><p>Because everything only needs to reach the <em>relay</em>, running it inside a <strong>Tailscale</strong> tailnet is not just fine — it’s better than public exposure. No open ports, WireGuard encryption end to end, and access controlled by your tailnet.</p><h3>Prerequisites</h3><ul><li>An always-on Linux VM you can SSH into.</li><li><a href="https://tailscale.com/">Tailscale</a> installed on the VM, your laptop, and your phone (all on the same tailnet).</li><li>Docker Engine + Docker Compose <strong>v2.24.4+</strong>.</li><li>The Buzz <strong>desktop app</strong> on your laptop (used to create your identity and connect).</li></ul><h3>Step 1 — Tailscale: turn on the two features that matter</h3><p>In the Tailscale <strong>admin console</strong>, enable:</p><ul><li><strong>MagicDNS</strong> (gives your machine a stable name).</li><li><strong>HTTPS Certificates</strong> (lets tailscale serve mint a real Let&#39;s Encrypt cert for your *.ts.net name — with zero public exposure).</li></ul><p>On the VM, find your machine’s full MagicDNS name:</p><pre>tailscale status --json | python3 -c &quot;import sys,json;print(json.load(sys.stdin)[&#39;Self&#39;][&#39;DNSName&#39;].rstrip(&#39;.&#39;))&quot;<br># e.g. myrelay.tailXXXX.ts.net</pre><p>Call this HOST for the rest of the guide. <strong>Decide it now and never change it</strong> — see the first gotcha below, because the relay bakes your community&#39;s identity into this hostname.</p><h3>Step 2 — Create your identity (on the laptop)</h3><p>Install and open the Buzz desktop app, choose <strong>Create a new identity key</strong>, and back up the secret (there’s no recovery). You need your <strong>public key in 64-char hex</strong> form — this becomes the relay’s owner. If the app only shows you an npub, you can convert it; the hex is what the relay config wants.</p><blockquote><em>The desktop onboarding pushes you toward “create/own a community,” which routes to Buzz’s hosted signup. Ignore it for now. As a self-hoster you’ll connect later via </em><strong><em>“Join a community”</em></strong><em> and paste your own relay URL.</em></blockquote><h3>Step 3 — Deploy the relay</h3><p>Clone the repo and configure the production compose bundle:</p><pre>git clone https://github.com/block/buzz.git<br>cd buzz/deploy/compose<br>cp .env.example .env</pre><p>Edit .env. The important bits — note that <strong>every URL uses your </strong><strong>HOST</strong>, and TLS is terminated by tailscale serve (next step), so the relay itself listens plain on loopback:</p><pre>BUZZ_IMAGE=ghcr.io/block/buzz:main        # pin to a sha once it&#39;s stable</pre><pre># Community identity is derived from this host — set it once, forever<br>RELAY_URL=wss://HOST<br>BUZZ_DOMAIN=HOST<br>BUZZ_MEDIA_BASE_URL=https://HOST/media<br>BUZZ_MEDIA_SERVER_DOMAIN=HOST<br>BUZZ_CORS_ORIGINS=https://HOST</pre><pre># Closed relay: only members you add can join<br>BUZZ_REQUIRE_AUTH_TOKEN=true<br>BUZZ_REQUIRE_RELAY_MEMBERSHIP=true<br>BUZZ_ALLOW_NIP_OA_AUTH=true<br>BUZZ_AUTO_MIGRATE=true<br>RELAY_OWNER_PUBKEY=&lt;your-64-hex-owner-pubkey&gt;</pre><pre># ...plus the generated secrets (relay key, DB/Redis/S3 passwords)...<br>BUZZ_HTTP_PORT=3000</pre><p>Generate strong secrets rather than editing by hand:</p><pre>for v in BUZZ_RELAY_PRIVATE_KEY BUZZ_GIT_HOOK_HMAC_SECRET; do echo &quot;$v=$(openssl rand -hex 32)&quot;; done<br>for v in POSTGRES_PASSWORD REDIS_PASSWORD BUZZ_S3_ACCESS_KEY BUZZ_S3_SECRET_KEY; do echo &quot;$v=$(openssl rand -hex 24)&quot;; done</pre><p>A privacy nicety: bind the published port to loopback so the relay is only reachable through the TLS front door. In compose.yml, the relay&#39;s port mapping should read:</p><pre>ports:<br>      - &quot;127.0.0.1:${BUZZ_HTTP_PORT:-3000}:3000&quot;</pre><p>Start it and confirm it’s alive:</p><pre>./run.sh config &amp;&amp; ./run.sh start<br>./run.sh status<br>curl -fsS http://127.0.0.1:3000/_liveness &amp;&amp; echo &quot;  relay OK&quot;</pre><h3>Step 4 — Expose the relay over Tailscale (TLS)</h3><p>tailscale serve terminates TLS with a real cert on your .ts.net name and reverse-proxies to the relay. It passes WebSocket upgrades through, which is exactly what we need.</p><pre>sudo tailscale serve --bg 3000<br>sudo tailscale serve status<br>curl -fsS https://HOST/_liveness &amp;&amp; echo &quot;  wss path OK&quot;</pre><p>That ok over HTTPS means clients on your tailnet can now reach the relay at wss://HOST.</p><blockquote><strong><em>Gotcha — port collisions.</em></strong><em> If something else already owns 443 on the box (a reverse proxy for another app, say), </em><em>tailscale serve --bg 3000 will be shadowed and you&#39;ll get cert mismatches or 404s. Either free up 443, or serve Buzz on another port (</em><em>--bg --https=8443 3000) and use </em><em>wss://HOST:8443 everywhere. The mobile app is happier on the default port, so prefer freeing 443 if you can.</em></blockquote><h3>Step 5 — Connect the desktop</h3><p>In the desktop app choose <strong>Join a community</strong> (not “create/own”) and paste wss://HOST. It recognizes you as owner (because your hex pubkey is in RELAY_OWNER_PUBKEY) and drops you into the workspace. Create a channel, post a message — you&#39;re live.</p><h3>Step 6 — The agent harness (and the auth reality)</h3><p>An agent is a buzz-acp process: it bridges Buzz events to an AI agent over ACP (Agent Client Protocol). It needs its own identity, and it runs on the server.</p><p><strong>Build the harness</strong> (there’s often no prebuilt binary for your arch, so build from source — Rust 1.88+):</p><pre>cd ~/buzz<br>cargo build --release -p buzz-acp<br>sudo install -m755 target/release/buzz-acp /usr/local/bin/buzz-acp</pre><p><strong>The model + auth.</strong> buzz-acp spawns an adapter — for Claude, claude-agent-acp (a small Node package). Here&#39;s the thing that trips people up: that adapter wraps the Claude <em>Agent SDK</em>, which authenticates with an <strong>API key + base URL</strong>, not a subscription OAuth login. So you have two clean options:</p><ol><li><strong>Anthropic API key</strong> — set ANTHROPIC_API_KEY from the Console. Simple, metered billing.</li><li><strong>Any Anthropic-compatible endpoint</strong> — point the same adapter at a different provider. For example, a coding-plan key from an Anthropic-compatible API lets you run the identical harness against a non-Anthropic model. You set ANTHROPIC_BASE_URL + an auth token instead of the real Anthropic key.</li></ol><pre>npm install -g @agentclientprotocol/claude-agent-acp   # the adapter</pre><p>Mint the agent an identity and admit it to the closed relay (run from the compose dir):</p><pre>docker compose exec relay /usr/local/bin/buzz-admin generate-key   # save the SECRET<br>./run.sh add-member &lt;agent-public-hex&gt;</pre><p>Smoke-test in the foreground before daemonizing:</p><pre>export BUZZ_PRIVATE_KEY=&#39;&lt;agent-secret&gt;&#39;<br>export BUZZ_RELAY_URL=&#39;wss://HOST&#39;      # the canonical URL — see gotcha below<br>export ANTHROPIC_API_KEY=&#39;sk-...&#39;        # or ANTHROPIC_BASE_URL + token for a compatible endpoint<br>export BUZZ_ACP_AGENT_COMMAND=&#39;claude-agent-acp&#39;<br>buzz-acp --respond-to allowlist --respond-to-allowlist &#39;&lt;your-owner-hex&gt;&#39;</pre><blockquote><strong><em>Gotcha — the agent must use the canonical URL, not </em></strong><strong><em>localhost.</em></strong><em> The relay routes by host. If the agent connects to </em><em>ws://localhost:3000, the </em><em>Host header doesn&#39;t match your community and you get a </em><strong><em>404</em></strong><em>. Point the agent at </em><em>wss://HOST (the same address clients use) — it also makes the auth challenge line up.</em></blockquote><blockquote><strong><em>Provider tip (Anthropic-compatible endpoints).</em></strong><em> The Agent SDK asks for internal model “slots” (a main model and a small/fast one). If you’re pointing at a non-Anthropic provider, map those slots to that provider’s model IDs via </em><em>ANTHROPIC_DEFAULT_SONNET_MODEL / </em><em>ANTHROPIC_DEFAULT_OPUS_MODEL / </em><em>ANTHROPIC_DEFAULT_HAIKU_MODEL, or you&#39;ll get intermittent &quot;model not found&quot; errors on background calls. And watch for provider-specific model-ID quirks (some want a suffix like </em><em>[1m] to unlock a full context window; drop it and you silently run a smaller context).</em></blockquote><p><strong>A membership subtlety.</strong> Buzz has no clean “add member to an existing channel” API yet, and the desktop’s member search only finds identities that have published a profile. So, as the agent, publish a profile and join the channel with the Buzz CLI:</p><pre>cargo build --release -p buzz-cli &amp;&amp; sudo install -m755 target/release/buzz /usr/local/bin/buzz<br>BUZZ_PRIVATE_KEY=&#39;&lt;agent-secret&gt;&#39; BUZZ_RELAY_URL=&#39;wss://HOST&#39; buzz users set-profile --name &quot;assistant&quot;<br>BUZZ_PRIVATE_KEY=&#39;&lt;agent-secret&gt;&#39; BUZZ_RELAY_URL=&#39;wss://HOST&#39; buzz channels list      # grab a channel UUID<br>BUZZ_PRIVATE_KEY=&#39;&lt;agent-secret&gt;&#39; BUZZ_RELAY_URL=&#39;wss://HOST&#39; buzz channels join --channel &lt;uuid&gt;</pre><p>Now @mention it from the desktop — it should answer.</p><h3>Step 7 — Make it 24/7 with systemd</h3><p>A foreground process dies with your SSH session. Move the config into a root-only env file and run it as a service that restarts on crash and comes back on boot.</p><p>Split shared vs. per-agent config so multiple agents don’t duplicate the model/endpoint block:</p><pre>sudo mkdir -p /etc/buzz/personas</pre><pre># shared by every agent<br>sudo tee /etc/buzz/common.env &gt;/dev/null &lt;&lt;&#39;EOF&#39;<br>BUZZ_RELAY_URL=wss://HOST<br>BUZZ_ACP_AGENT_COMMAND=claude-agent-acp<br>BUZZ_ACP_SUBSCRIBE=mentions<br>ANTHROPIC_BASE_URL=...            # provider endpoint (or omit for Anthropic)<br>ANTHROPIC_DEFAULT_SONNET_MODEL=...<br>ANTHROPIC_DEFAULT_HAIKU_MODEL=...<br>EOF<br>sudo chmod 600 /etc/buzz/common.env</pre><p>Use a <strong>systemd template unit</strong> so one file serves every agent (%i = the name after the @):</p><pre>sudo tee /etc/systemd/system/buzz-acp@.service &gt;/dev/null &lt;&lt;&#39;EOF&#39;<br>[Unit]<br>Description=Buzz agent: %i<br>After=network-online.target docker.service<br>Wants=network-online.target</pre><pre>[Service]<br>Type=simple<br>User=youruser<br>WorkingDirectory=/home/youruser<br>EnvironmentFile=/etc/buzz/common.env<br>EnvironmentFile=/etc/buzz/%i.env<br>ExecStart=/usr/local/bin/buzz-acp<br>Restart=always<br>RestartSec=5</pre><pre>[Install]<br>WantedBy=multi-user.target<br>EOF</pre><p>Each agent gets a per-agent /etc/buzz/&lt;name&gt;.env (its secret, an allowlist with your owner key, and a BUZZ_ACP_SYSTEM_PROMPT_FILE), then:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable --now buzz-acp@assistant</pre><blockquote><strong><em>Gotcha — file permissions.</em></strong><em> The service runs as your user, but </em><em>buzz-acp reads the system-prompt file </em>after<em> dropping privileges. Env files are loaded by systemd (as root) and stay </em><em>600, but the </em><strong><em>persona prompt files must be readable</em></strong><em> by the service user (</em><em>chmod 644 /etc/buzz/personas/*.md) or the agent crash-loops with a &quot;permission denied&quot; on startup.</em></blockquote><blockquote><strong><em>Gotcha — systemd PATH.</em></strong><em> A service’s PATH is </em><em>/usr/local/bin:/usr/bin:... — it does </em><strong><em>not</em></strong><em> include </em><em>~/.local/bin. Anything you install with </em><em>pipx (or user </em><em>npm) lands where the agent can&#39;t see it. Install agent-facing tools to system paths.</em></blockquote><h3>Step 8 — A cast of persona agents</h3><p>Because each agent is just “a keypair + a system prompt + a service instance,” scaling to several is repetition. Give each one a name, a profile, and a system prompt describing its voice and job — an infrastructure-and-security skeptic, a research-and-summarize agent, a technical writer, an operations closer, and so on. Keep them <strong>mention-only</strong> (BUZZ_ACP_SUBSCRIBE=mentions) once there&#39;s more than one, or every agent answers every message and they cascade into loops (and token burn).</p><p>The per-agent recipe:</p><ol><li>buzz-admin generate-key → save the secret.</li><li>./run.sh add-member &lt;pubkey&gt;.</li><li>Write /etc/buzz/personas/&lt;name&gt;.md (the system prompt) and /etc/buzz/&lt;name&gt;.env.</li><li>As the agent: buzz users set-profile --name &quot;&lt;Name&gt;&quot; and buzz channels join --channel &lt;uuid&gt;.</li><li>systemctl enable --now buzz-acp@&lt;name&gt;.</li></ol><p>It’s worth scripting this into one command once you’ve done it by hand. Each agent is a full process (tens of MB idle plus its model calls), so a handful is comfortable; if you stack many, --lazy-pool releases the model subprocess when idle.</p><h3>Step 9 — The part that’s broken out of the box: mobile pairing</h3><p>Here’s the one that cost me the most time. On a self-hosted relay from the compose bundle, <strong>mobile pairing fails for everyone</strong>: the desktop generates a QR, the phone scans it, and you get:</p><pre>WebSocket connection failed: HTTP error: 404 Not Found</pre><p>It looks like a network or VPN problem. It isn’t. Pairing uses a <strong>separate service</strong> — buzz-pair-relay — that the compose bundle never wires up. The desktop probes the relay&#39;s NIP-11 document for a pairing_relay_url; the bundle sets none, so it falls back to a legacy /pair path on the main relay, and the relay has no such route → 404. The QR encodes a dead endpoint.</p><p>The fix ships <strong>inside the relay image already</strong> (/usr/local/bin/buzz-pair-relay), it&#39;s just not started. Wire it up:</p><p><strong>1. Add a </strong><strong>pair service to </strong><strong>compose.yml</strong> (same image, different entrypoint, bound to loopback):</p><pre>pair:<br>    image: ${BUZZ_IMAGE:-ghcr.io/block/buzz:main}<br>    entrypoint: [&quot;/usr/local/bin/buzz-pair-relay&quot;]<br>    environment:<br>      BUZZ_PAIR_RELAY_BIND_ADDR: 0.0.0.0:5000<br>    ports:<br>      - &quot;127.0.0.1:5000:5000&quot;<br>    restart: unless-stopped<br>    networks:<br>      - buzz-net</pre><p><strong>2. Give the pairing relay its OWN origin.</strong> This is the subtle bit for a Tailscale setup: the pairing relay needs a distinct host:port, <strong>not</strong> a /pair path on the main host — a path-based serve fails phone-side auth. Put it on its own serve port:</p><pre>sudo tailscale serve --bg --https=8444 5000</pre><p><strong>3. Advertise it</strong> so the desktop takes the working path instead of the dead /pair guess. Add to the relay&#39;s .env:</p><pre>BUZZ_PAIRING_RELAY_URL=wss://HOST:8444</pre><p><strong>4. Recreate the relay</strong> (it only reads .env at startup) and start the sidecar:</p><pre>docker compose up -d pair<br>docker compose up -d --force-recreate relay</pre><p><strong>5. Verify the advertisement landed</strong> — this is the whole fix:</p><pre>curl -fsS -H &quot;Accept: application/nostr+json&quot; https://HOST | grep -o &#39;pairing_relay_url&#39;<br># should print: pairing_relay_url</pre><p>Now regenerate the QR on the desktop (Settings → Mobile), scan it on the phone (Tailscale connected), and pairing walks through QR → six-digit SAS confirmation → done. The pairing payload is end-to-end encrypted with the SAS visual check, so the pairing relay in the middle only acts as a rendezvous.</p><blockquote><em>Both the </em><em>pair service (</em><em>restart: unless-stopped) and the </em><em>--bg serve mapping and the </em><em>.env setting persist across reboots, so this stays fixed.</em></blockquote><p>The mobile app currently offers <strong>only</strong> QR/pairing-code onboarding (no “paste a relay URL” like the desktop), which is exactly why this sidecar is mandatory rather than optional for a phone.</p><h3>Step 10 — Give the agents real tools</h3><p>If your agents’ harness exposes a shell tool, anything on the system PATH is instantly usable — no per-tool wiring. A useful belt: yt-dlp + ffmpeg (media), markitdown + pandoc + poppler-utils + tesseract (documents/OCR → text), jq/yq/duckdb/csvkit (data), trafilatura/lynx/httpie (web), ripgrep/fd/git/gh (dev). Install them to <strong>system paths</strong> (remember the systemd-PATH gotcha) — e.g. sudo pip install --break-system-packages ... puts console scripts in /usr/local/bin.</p><p>Two things make this actually work:</p><ul><li><strong>Tell the agents the tools exist.</strong> Installing ≠ knowing. buzz-acp supports a shared instruction layer (BUZZ_ACP_TEAM_INSTRUCTIONS) — drop a one-line manifest of the toolbelt there so every agent reaches for the right tool instead of improvising.</li><li><strong>Expect YouTube to block datacenter IPs.</strong> yt-dlp from a cloud VM often hits a &quot;confirm you&#39;re not a bot&quot; wall. For transcripts (the common need), fetch captions directly (e.g. a transcript API) rather than downloading the video. If you genuinely need the media, pass --cookies from a logged-in <em>throwaway</em> account.</li></ul><h3>The gotchas, collected</h3><p>If you skim nothing else, internalize these:</p><ol><li><strong>The community identity is derived from </strong><strong>RELAY_URL&#39;s host.</strong> Change the host (or add/remove a port) later and you start a <em>new, empty</em> community — old channels and memberships are stranded. Pick the final URL before you add anything you care about.</li><li><strong>Agents connect to the canonical </strong><strong>wss://HOST, not </strong><strong>localhost</strong> — host-based routing 404s otherwise.</li><li><strong>Port 443 contention</strong> with any other reverse proxy on the box will shadow tailscale serve.</li><li><strong>Persona prompt files need </strong><strong>644</strong>; env files stay 600. Wrong perms → agent crash-loop.</li><li><strong>systemd PATH excludes </strong><strong>~/.local/bin</strong> — install agent tools system-wide.</li><li><strong>Mobile pairing needs the </strong><strong>buzz-pair-relay sidecar</strong> with its own origin and BUZZ_PAIRING_RELAY_URL advertised — it&#39;s missing from the bundle.</li></ol><h3>Where this lands</h3><p>The result: a private, always-on agent workspace on a server you control, reachable from laptop and phone over an encrypted tailnet, with a cast of persona agents that run tools and answer whenever you ping them — and none of it depends on your laptop being awake.</p><p>A couple of habits worth keeping: back up every keypair (agent secrets + owner key + relay key — there’s no recovery), and do one real reboot to confirm the services, the relay, and the pairing sidecar all come back on their own. After that, it just runs.</p><p><em>Buzz is pre-1.0 and moves fast — when something fails out of the box, the project’s issue tracker is often ahead of first-principles debugging. The mobile-pairing fix above came straight from there.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fa6d6b553a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Flight Recorder Ships Before the Firewall]]></title>
            <link>https://medium.com/@tonypiusalapatt/the-flight-recorder-ships-before-the-firewall-8e59dd1ae632?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e59dd1ae632</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 06:38:51 GMT</pubDate>
            <atom:updated>2026-07-31T06:38:51.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfThCPxGLh3XQVk9sAhGHw.jpeg" /></figure><h3>Why I’m building agent security backwards — evidence first, enforcement second</h3><p>There’s a question that every team running AI agents in production will eventually be asked, and almost none of them can answer today:</p><p><em>“What did the agent actually do?”</em></p><p>Not what the model said. Not what the prompt was. What did it <strong>do</strong> — which tools did it invoke, against which systems, with which arguments, and did those calls succeed? When something goes wrong — a deleted branch, a leaked file, an email that shouldn’t have been sent — the incident review opens the logs and finds… HTTP status codes. A wall of 200s and the occasional 500. The transport layer was healthy. The intent layer is invisible.</p><p>I’ve spent two years building multi-agent systems for production, and I’ve written before about why <a href="https://blog.tonyalapatt.in/the-control-plane-should-be-boring-3363d65ca073">the control plane should be boring</a> — intelligence in the workers, orchestration in infrastructure that has no opinions and never surprises you. This post is the same philosophy pointed at a different layer, because the agent security conversation in 2026 has the priorities inverted, and the inversion is costing us.</p><h3>The industry is trying to win the wrong fight</h3><p>Most of the energy in agent security right now goes into <strong>prevention</strong>: prompt-injection classifiers, jailbreak detectors, alignment layers, input sanitizers. It’s the intuitive place to spend effort — stop the bad thing before it happens.</p><p>The problem is that prevention at the language layer is empirically losing. In late 2025, a joint team spanning the major labs published “The Attacker Moves Second,” an adaptive-attack study against twelve recent prompt-injection defenses — most of which had originally reported near-zero attack success rates. Under adaptive attack, the majority were bypassed more than 90% of the time. That’s not a gap you patch. It’s a structural property of defending a probabilistic system at its most probabilistic layer: natural language is the attack surface, and natural language is infinite.</p><p>Meanwhile, the tool-call layer — the place where an agent stops <em>thinking</em> and starts <em>doing</em> — was having a very bad year. Dozens of CVEs against MCP servers and clients in the first months of 2026 alone, including a CVSS 9.6 remote code execution in a package sitting in hundreds of thousands of developer environments. Astrix Security’s survey of 5,200+ MCP servers found OAuth adoption at 8.5%, with over half relying on long-lived static secrets. Gravitee’s industry report found 88% of surveyed organizations had confirmed or suspected an AI-agent security incident within the year — while barely a fifth treat agents as identity-bearing entities at all.</p><p>Read those two paragraphs together and the shape of the problem is obvious. We are pouring effort into an unwinnable filter fight at the language layer, while the layer where agents actually touch the world — the layer that is <em>finite, structured, and observable</em> — has neither locks nor cameras.</p><h3>Tool calls are the narrow waist</h3><p>Here’s the property that makes the tool-call layer worth everything the language layer isn’t: <strong>every consequential thing an agent does passes through it.</strong></p><p>An agent can think anything. It can be manipulated into <em>intending</em> anything. But to affect the world — read a file, open a PR, delete a repo, send money — it must emit a tool call: a small, structured, well-formed JSON-RPC message with a method name and arguments. This is the agent stack’s narrow waist, the same way syscalls are the narrow waist of an operating system. We didn’t secure Unix by teaching programs to be good. We secured it by making the syscall boundary observable and enforceable, and letting programs be whatever they are.</p><p>MCP — for all its early security chaos — did the ecosystem one enormous favor: it standardized the waist. There is now one wire format through which a rapidly growing share of agent actions flow. One place to stand.</p><p>So that’s where I’m standing. I’m building <a href="https://claude.ai/chat/15b2503a-6788-4496-86eb-3772effba8d8#">mcpjail</a> — a small, local-first proxy that sits between any agent and its MCP servers, records every MCP tool call to a tamper-evident audit log, and enforces plain-YAML policy on what’s allowed through. One command wraps any server, local stdio or remote HTTP. No SaaS, no daemon, no telemetry, ever.</p><p>One scope caveat, stated up front because the whole pitch of this post is honesty about layers: mcpjail governs the <em>MCP</em> boundary. An agent client’s built-in tools — Claude Code’s own Bash or file-edit, say — never cross that boundary, so they sail past any MCP-layer proxy. Client-side hooks are the answer there, and they’re on the roadmap; but “every tool call” would be an overclaim, and overclaims are how trust tools die.</p><p>But the interesting part isn’t what it does. It’s the ordering of what it does — and three design decisions that I think generalize to anyone building trust infrastructure for agents.</p><h3>Decision one: the middleman must be boring</h3><p>A proxy that sits inside every tool call has exactly one unforgivable failure mode: changing the traffic. So mcpjail refuses to be clever about the protocol. It does not implement MCP. It parses just enough of each JSON-RPC message to see the method name and arguments, and then forwards <strong>the exact bytes it received</strong> — never a re-serialized copy that might reorder keys or mangle Unicode. Unknown methods pass through untouched.</p><p>This mattered within weeks of starting. The MCP specification’s largest-ever revision landed this July — stateless core, removed handshake, new extensions. A protocol-aware proxy built in June would be a rewrite in August. A byte-forwarding pattern-matcher doesn’t care: new methods flow through it unexamined, and the handful of method names it audits (tools/call, resources/read, and friends) are the most stable part of the spec. Resilience through ignorance. The control plane should be boring; the middleman should be boring twice.</p><p>The same principle drove the default mode: <strong>shadow, not enforce.</strong> A fresh install observes and records; it never blocks. Trust infrastructure that breaks someone’s agent on day one gets uninstalled by day two, and no amount of security value survives that. You earn the right to enforce by first proving you’re invisible.</p><h3>Decision two: the audit log is a trust artifact, so treat it like one</h3><p>An audit log you can quietly edit is a diary, not evidence. Every record in mcpjail’s log carries a SHA-256 hash of the previous record — a chain, so any edit, insertion, or deletion breaks verification at the exact line it happened — and the log is checkpointed with Ed25519 signatures. mcpjail verify re-derives the whole thing offline. In my own testing I hand-edited one field of one record; verification failed with line 3: record_hash mismatch. That&#39;s the product working.</p><p>But a trust artifact also demands honesty about what it <em>doesn’t</em> prove, because a security tool that overclaims is worse than no tool. The signature scheme proves the log wasn’t altered by anyone who doesn’t hold the signing key. It proves nothing against an attacker who has fully compromised the machine and can re-sign whatever they like. Local-first tamper-evidence has that ceiling by construction. I put this limitation in the README rather than the fine print, and I’d argue every trust tool should: the fastest way to lose a security-literate audience is to let them discover your threat model’s edges before you disclose them.</p><h3>Decision three: the evidence must not become the breach</h3><p>The most counterintuitive call in the design: mcpjail’s audit log <strong>never stores tool responses, and redacts arguments before anything touches disk.</strong></p><p>Think about what flows through agent tool calls. API keys in arguments. File contents, query results, and customer data in responses. A naive “log everything” audit trail is the best-organized exfiltration target on the machine — a single file containing every secret every agent ever handled, neatly timestamped. So redaction runs <em>before</em> hashing, before writing, before anything: known credential shapes (cloud keys, platform tokens, private-key blocks) and secret-bearing field names are replaced with typed placeholders, and the hash chain is computed over the redacted record. And response bodies never touch the log. What does get recorded is outcome metadata — did the call succeed, what was the error code — correlated from the response without persisting it (on the HTTP path today; the stdio path is next on the backlog). You can answer “did the delete actually execute?” without your audit log being able to answer “what was in the file?”</p><p>There’s a general principle here that I think the observability industry hasn’t internalized for agents yet: <strong>for AI systems, the evidence layer is itself an attack surface, and must be designed like one.</strong></p><h3>The regulation is coming to the same conclusion</h3><p>I’d believe all of the above with no regulator in sight, but it’s worth noting that the EU AI Act arrived at the same layer. Article 12’s obligations for high-risk AI systems — enforceable this August — require automatic, tamper-resistant logging of system operation, and the Act’s recitals extend the compliance boundary through multi-agent chains. Whatever you think of the regulation, its instinct matches the engineering reality: when you cannot guarantee an AI system’s behavior, you must at minimum guarantee a faithful record of it. Aviation figured this out decades ago. We don’t certify aircraft on the promise they’ll never crash. We mandate the black box.</p><h3>Ship the recorder first</h3><p>Which brings me back to the ordering in the title, because it’s not rhetorical — it’s literally my build sequence, and I think it’s the right sequence for the field.</p><p>mcpjail was built in exactly this order. The recording layer came first: the proxy, the redaction, the hash-chained log, offline verification, tested against both the old and new MCP wire shapes. Only then came the enforcement layer — policy rules, deny decisions, the firewall — built <em>on top of</em> the evidence layer, not beside it. Both ship today; the sequence is the point. You cannot write sensible policy for agents you’ve never observed; every enforcement rule worth having falls out of reading real audit logs and noticing what shouldn’t be there. Observation earns enforcement. Evidence before opinions.</p><p>The industry has this backwards right now — racing to build guards for a door while nobody’s installed the camera. The guards keep getting fooled, and when they do, there’s no tape.</p><p>Agents will misbehave. That’s not pessimism; it’s the operating assumption every mature engineering discipline adopts about its components. The systems that survive their components’ failures are the ones that made failure observable first.</p><p>The flight recorder ships before the firewall. It has to.</p><p><em>mcpjail is open source and building in public — the repo, including the design decisions as ADRs and the threat model, is </em><a href="https://github.com/tonypius/mcpjail"><em>here</em></a><em>. If you run agents against MCP servers and want to see what they’re actually doing, it’s one command: </em><em>uvx mcpjail wrap -- &lt;your server&gt;. I&#39;d genuinely value adversarial feedback on the redaction patterns and the verification scheme — the whole point of a trust tool is that it survives hostile reading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e59dd1ae632" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Control Plane Should Be Boring]]></title>
            <link>https://medium.com/@tonypiusalapatt/the-control-plane-should-be-boring-3363d65ca073?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3363d65ca073</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 12:25:11 GMT</pubDate>
            <atom:updated>2026-06-18T12:25:11.544Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How we built deterministic AI agent orchestration on a message bus — and the build-vs-buy bill we’re still paying</strong></p><p>Every multi-agent architecture diagram sells you the same thing: a constellation of clever agents reasoning together to solve a problem no single model could. The agents are the headline. The boxes glow.</p><p>After two years running a multi-agent system in production for ESG analytics — answering questions like <em>”compare Scope 1–3 emissions and governance maturity for Company X against its peers,” </em>with citations, in under two minutes — I’ll tell you the unglamorous truth. The intelligence was never the hard part. The hard part was making a system built out of stochastic components behave predictably enough to put in front of a paying customer. And the answer to <em>that</em> problem had almost nothing to do with agents, and almost everything to do with distributed systems.</p><p>This is an argument for putting your orchestration where it belongs — in boring, opinion-free infrastructure — and keeping it out of the place everyone instinctively puts it: inside the model.</p><h3><strong>The thesis</strong></h3><p><strong>Agent orchestration is a distributed-systems problem, not an agent-framework problem.</strong></p><p>The determinism you want from a multi-agent system does not come from a smarter planner or a better prompt. It comes from refusing to let the model own the control flow at all. You make the <em>orchestration</em> deterministic and quarantine the stochasticity to the workers, where it belongs.</p><p>The model decides <em>what</em> to do. Durable infrastructure decides <em>that it gets done</em>. Those are different jobs, and the entire reliability story is in keeping them apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEIVJjkYUFWeNIOeDq8lRA.png" /></figure><p>The diagram is the whole argument in one frame. The stochastic parts — where LLMs exercise judgement — sit at the edges. The control plane in the middle is deterministic, durable, and intentionally dull. Notice where the boundary falls: the planner is <em>above</em> the line.</p><h3><strong>How we got here</strong></h3><p><strong>We didn’t start with this conviction. We earned it.</strong></p><p>In the first half of 2025 we did the rounds of the in-process agent frameworks. They’re good tools built by sharp teams. But they shared an architectural assumption that was wrong for us: that orchestration is something a framework expresses <em>in process</em>, often through agents conversing and converging on an answer. Emergent multi-agent conversation is a beautiful idea, and it puts nondeterminism in the exact place you least want it — the control flow. When a run failed, the failure wasn’t in a worker. It was in the choreography. And you cannot debug choreography.</p><p>Timing mattered too. This was the moment <a href="https://github.com/langchain-ai/langgraph">LangGraph</a> was becoming a serious option rather than an experiment — but “becoming serious” is not “battle-tested in production.” Deep research as a consumer product didn’t exist yet. We needed cited, multi-source answers in a tight latency budget, coming back the same way every time. Nothing off the shelf gave us that with reliability guarantees we’d stake a customer relationship on.</p><p>So we stopped looking for an agent framework and started treating the problem the way we’d treat any distributed system that has to not fall over.</p><h3><strong>The pattern is free. The discipline is what costs you.</strong></h3><p>The shape is a planner, a fleet of workers, and an aggregator. <strong>That pattern is not novel</strong> — Anthropic documented <a href="https://www.anthropic.com/research/building-effective-agents">orchestrator-workers</a> by name, with a <a href="https://github.com/anthropics/anthropic-cookbook/tree/main/patterns/agents">reference implementation</a>, and task-decomposition-into-parallel-workers is older than that. If you came here for a new pattern, there isn’t one.</p><p>What costs you is the engineering discipline of making the pattern reliable under failure, and that’s where every interesting decision lives. Here’s each piece and the distributed-systems problem it actually solves.</p><p><strong>1. The planner emits a typed task graph — a contract, not instructions</strong></p><p>The planner LLM classifies intent, extracts the entities that scope the query, and emits a <em>typed</em> list of tasks with explicit dependencies. Retrieval tasks usually have no dependencies and dispatch immediately in parallel; analysis tasks declare the retrieval task they consume, so they only fire once their inputs exist.</p><p>Critically, the planner emits <em>what</em> it wants done, not <em>how</em>. It has no idea how a worker fetches data. That decoupling is the whole game: the planner can’t break a worker, and a worker can be rewritten without the planner ever knowing. Adding a capability is a new task type in the planner’s vocabulary plus a new worker — nothing else moves.</p><p>There’s also a cheap front gate before any of this: greetings and off-topic queries short-circuit with a direct reply and dispatch zero agents. The cheapest task is the one you never run.</p><p><strong>2. Durable queues are the failure-absorption layer</strong></p><p>Every task type gets its own durable queue on <a href="https://github.com/rabbitmq/rabbitmq-server">RabbitMQ</a>. This is the quiet hero of the whole design.</p><p>When a worker dies mid-task — OOM-killed, evicted, a provider timeout — the task is simply still on its queue, waiting for the next consumer. There is no orphaned in-process state to recover, <em>because there is no in-process state</em>. The failure mode that wrecks naive agent loops — a process dying halfway through and losing everything it was doing — structurally cannot happen here, because the unit of work lives in the broker, not on a function’s call stack. A slow or restarting worker just drains its backlog when it comes back. Producers never block on consumers.</p><p>A separate topic exchange handles fan-out of progress and results, which a WebSocket layer subscribes to per user. Planning → execution → synthesis progress streams to the browser in real time, across multiple tabs, with delivery confirmation. Service-to-service traffic is message-bus only — no inter-worker HTTP, no worker calling another worker directly.</p><p><strong>3. Workers are stateless, single-purpose, and independently scalable</strong></p><p>One capability, one data source, no cross-calls. They consume, execute, publish back to the bus. Scaling a bottleneck is adding replicas of one worker type. The data plane underneath them is deliberately polyglot, because different questions want different stores:</p><p>- <strong>A graph store </strong><a href="https://github.com/neo4j/neo4j"><strong>Neo4j</strong></a> — the ESG knowledge graph of companies, KPIs, and materiality. Best for exact metrics, multi-year trends, and peer comparison, where you need canonical entity resolution and numerical aggregation rather than fuzzy recall.</p><p>- <strong>A vector store </strong><a href="https://github.com/chroma-core/chroma"><strong>ChromaDB</strong></a> — per-company collections over chunked sustainability reports for qualitative narrative, plus a shared knowledge-base collection for framework and definition questions.</p><p>- <strong>A search index </strong><a href="https://github.com/elastic/elasticsearch"><strong>Elasticsearch</strong></a> — a fast path for structured metrics, with a graph fallback behind a feature flag.</p><p>- <strong>Live web</strong> — real-time retrieval for current events a static store can’t cover.</p><p>The graph-retrieval worker is the most interesting one. It’s a <a href="https://github.com/langchain-ai/langchain">LangChain</a> tool-calling agent running a ReAct-style loop: given a goal and a toolbox — fetch metrics, resolve peers, discover companies, semantic-search fallback — the LLM iteratively chooses a tool, reads the observation, and continues until it has enough evidence. The loop is <strong>bounded by a hard iteration ceiling and a wall-clock timeout</strong>, because a reasoning loop without a ceiling is an unbounded latency liability. A lightweight query classifier runs up front to steer the traversal toward the right kind of graph navigation.</p><p>Embeddings are deliberately boring: a single consistent model for both documents and queries, baked into the deployment image so retrieval works offline and air-gapped. One embedding model, one vector space, no drift.</p><p>Worth calling out: the chart-building worker uses <strong>no LLM at all</strong>. It’s deterministic data formatting. Not every worker needs to be intelligent, and pretending they do is how you light money on fire.</p><p><strong>4. The aggregator pre-registers, then waits</strong></p><p>Before any worker finishes, the planner tells the aggregator the full set of task types to expect. The aggregator tracks completion atomically in an externalized state store with a TTL, and synthesizes only once the expected set is complete.</p><p>Pre-registration is what prevents the two classic failures: synthesizing early on partial results, or hanging forever on a task that was never dispatched. Because the state lives <em>outside</em> the process, the aggregator runs as multiple replicas safely — any replica can pick up the same query, and atomic updates prevent double-synthesis. For multi-entity asks it pre-builds comparison tables before the synthesis model writes prose, and the synthesis prompt enforces concrete numbers and named citations so the output is analyst-grade rather than vibes.</p><h3><strong>Right model, right job — without touching code</strong></h3><p>A note on cost, because it’s a design property, not an afterthought. Model assignment is per-service configuration, routed through a provider abstraction so swapping the model behind any agent is a config change rather than a code change. The principle is simple: reserve expensive reasoning models for the two places that actually need them — multi-step graph navigation and final synthesis — and run everything else (intent routing, light extraction, follow-up suggestions) on the cheapest model that clears the quality bar. A provider fallback sits behind the primary path so a provider hiccup degrades gracefully instead of failing the query. None of this leaks into application logic, which means cost tuning never becomes a refactor.</p><h3><strong>Observability, because you cannot operate what you cannot see</strong></h3><p>Every answer is traced end-to-end with <a href="https://github.com/langfuse/langfuse">Langfuse</a> across planner → workers → aggregator, and the trace ID is surfaced to the UI per query, so a support ticket maps to a trace in one click. Queue depth is visible through the broker’s management UI; per-query state and timing live in the operational store. Health checks cover the broker, the model provider, and tracing. The edge is a <a href="https://github.com/fastapi/fastapi">FastAPI</a> gateway with standard, unremarkable auth — bearer tokens with refresh, password hashing, role-based access. None of this is clever. That’s the point.</p><h3><strong>The honest part: we did not make the LLMs deterministic</strong></h3><p>This is where I have to be precise, because it’s the claim people misread.</p><p>We did not make our models deterministic. The planner is stochastic. The reasoning workers are stochastic. What we made deterministic is the <em>orchestration </em>— the control plane. Typed contracts, dependency gating, pre-registration, durable delivery. Those execute identically every time, regardless of what the models say. The stochasticity is quarantined to the data plane, where you <em>want</em> a model exercising judgement.</p><p>And I’ll own the soft spot rather than let you find it: right now we trust the planner’s emitted task list without a validating schema between it and dispatch. The mitigation is that the planning role runs a capable model — which is a probability argument, not a guarantee. If the planner emits a task set the workers can’t fulfil, the aggregator will either wait out its TTL or synthesize something incomplete. That’s a real edge. It’s on the roadmap, and “we use a good model” is not the same sentence as “this cannot happen.” Anyone whose architecture claims determinism should be able to tell you exactly where the determinism stops. <em>That</em> is where ours stops.</p><h3><strong>Where this sits in 2026 — and the bill we’re still paying</strong></h3><p>Now the part most “here’s our architecture” posts skip: what it cost.</p><p>The landscape did not stand still. LangGraph shipped durable execution and production middleware in its v1.1 release at the end of 2025. The durable-execution engines — <a href="https://github.com/temporalio/temporal">Temporal</a>, Inngest, Restate, Step Functions — are mature and increasingly aimed at exactly these long-running, failure-prone, LLM-shaped workloads. The honest description of what we built is this: <strong>a domain-specific durable-execution engine for LLM agents, implemented on a message bus.</strong></p><p>A Temporal advocate would look at our system and say we rebuilt a subset of Temporal on RabbitMQ, and that we now own the scheduler, the retry semantics, and the state machine <em>forever</em>. They’d be right. That is the carrying cost, and it never goes away. Every retry edge case, every poison-message scenario, every state-store TTL decision is ours to maintain in perpetuity, instead of a vendor’s.</p><p>So was it the wrong call? No — but the reason is <em>timing</em>, not superiority. In mid-2025 the buy options weren’t mature for this workload, we hit our latency budget when deep research wasn’t a usable product, and a small team that ships beats a theoretically cleaner substrate that’s still being evaluated. We made a bet appropriate to its moment.</p><p>What’s striking is that the bet aged into vindication of the <em>instinct</em> even as the buy options caught up to the <em>implementation</em>. The loudest debate in agent infrastructure right now is the one we were having privately in 2025: that the popular frameworks hand you persistence primitives and leave the genuinely hard problems — failure detection, automatic recovery, guaranteed completion, distributed coordination — for you to build yourself. The argument that <a href="https://www.diagrid.io/blog/checkpoints-are-not-durable-execution-why-langgraph-crewai-google-adk-and-others-fall-short-for-production-agent-workflows">a checkpoint between steps is not the same thing as durable execution</a> is now mainstream. We just arrived there early, by treating the problem as distributed systems from the start.</p><h3><strong>What I’d actually tell you if you’re choosing today</strong></h3><p>I’m not going to tell you to build what we built. I’m going to tell you how to think about it.</p><p>If you’re starting now: <strong>evaluate the durable-execution engines and LangGraph Platform first, before you write a line of orchestration code.</strong> The thing that justified building our own in 2025 — immature buy options — is substantially less true in 2026. The pattern is free and the substrate is increasingly available; paying yourself to reimplement it needs a real reason.</p><p>Build your own when you have a genuine constraint the off-the-shelf engines can’t meet — a latency envelope, a deployment or data-residency requirement, an existing message-bus investment your team already operates well — <em>and</em> when you’ve accepted, with eyes open, that you’re signing up to own a state machine for the life of the product.</p><p>But whichever you choose, keep the principle: <strong>the intelligence belongs in the workers; the orchestration belongs in infrastructure that has no opinions and never surprises you.</strong> The model should decide what to do. Something boring and durable should guarantee it gets done. The day your control plane becomes interesting is the day you’ve put the cleverness in the wrong layer.</p><p>The best compliment a control plane can get is that nobody talks about it. Make yours boring on purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3363d65ca073" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Ported iOS’s “Reason for Calling” to My Android Device]]></title>
            <link>https://medium.com/@tonypiusalapatt/how-i-ported-ioss-reason-for-calling-to-my-android-device-5f093420a3a8?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f093420a3a8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[spam-detection]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[spam-calls]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Thu, 21 May 2026 12:33:50 GMT</pubDate>
            <atom:updated>2026-05-21T12:33:50.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wl5xIm5UTE8IxC2YP6YHzA.png" /></figure><p>You are deep in the zone. You have spent the last two hours tracing a memory leak or balancing an infrastructure budget, holding a complex mental map of state changes in your head. Suddenly, the smartphone on your desk violently buzzes. The screen lights up with a raw string of unknown numbers. No metadata. No payload headers. Just a high-priority, synchronous interruption demanding immediate human processing.</p><p>You are forced into a terrible binary choice: break your creative flow to answer a potential spammer, or ignore it and risk missing an actual emergency. That immediate spike in cortisol and the subsequent loss of focus is an unnecessary tax on our daily productivity. It is the ultimate form of operational and cognitive friction.</p><p>While iOS users have enjoyed the “Ask Reason for Calling” feature to filter out this noise, Android leaves its users exposed to the chaos of the legacy telecom loop. As an engineer who builds software engines explicitly designed to kill this kind of drag, I wanted to apply strict firewall-style principles to my phone’s incoming traffic. I wanted to turn cold calls from information-gathering traps into sharp, deliberate decision-making forums before I ever pick up the handset.</p><p>To fix this, I built a privacy-first, on-device call screening application for Android. Here is the engineering breakdown of how to intercept, transcribe, and filter real-time telecommunications without letting a single byte of your voice data leave the device.</p><h3>The Architectural Challenge: The Sandbox Problem</h3><p>Building a real-time call screening tool on modern Android is notoriously difficult. Android’s standard security framework deliberately isolates apps from the raw call audio stream to protect user privacy. If you want to capture incoming call audio, run it through an on-device machine learning model, and broadcast synthesized audio responses back to the caller in real time, standard SDK APIs will block you.</p><p>Because of these system-level constraints, this architecture targets power users and privacy enthusiasts who run <strong>rooted devices</strong>. By leveraging a custom <strong>Magisk module</strong> to achieve systemless root execution, the application bypasses standard API sandboxing, granting the system-level permissions required to tap directly into the Android Telecom framework and low-level audio hardware loops.</p><p>Here is how the data flows through the application pipeline.</p><h3>The Engineering Chronology: From Raw Audio to Intent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQTEiGIiOfrs0lj5OEZiCg.png" /></figure><h3>Step 1: Low-Level Telephony Interception</h3><p>The pipeline begins when an unknown number triggers an incoming hardware event. Instead of letting the default phone application monopolize the window manager, our root-enabled background service hooks into the Android Telecom framework. The app instantly checks the incoming identifier against local logs. If the number is unrecognized, the app automatically screens the call, programmatically answering the line in the background before the physical device even rings to interrupt the user.</p><h3>Step 2: On-Device Speech-to-Text Processing</h3><p>Once the audio stream is captured, we route the real-time call audio directly into an offline speech recognition engine. Instead of sending raw audio packets to a cloud provider — which violates basic user privacy and introduces network latency — the app runs <strong>Vosk</strong>, an open-source, lightweight speech recognition toolkit that runs entirely locally on the device’s CPU.</p><p>Using Kotlin <strong>Coroutines and Flow</strong>, the raw audio bytes are ingested, processed by the local ~50MB Vosk language model, and converted into a reactive, continuous stream of text tokens.</p><h3>Step 3: Reactive UI Binding and Intent Actions</h3><p>As the caller explains why they are calling, the real-time text stream is pushed straight to a clean <strong>Jetpack Compose (Material 3)</strong> user interface overlay. Built on an <strong>MVVM Clean Architecture</strong> pattern, the UI updates instantly as the words are spoken.</p><p>From this overlay, the user is presented with immediate, deterministic actions:</p><ul><li><strong>Answer</strong>: Seamlessly bridge the call to the microphone if the intent is valid.</li><li><strong>Block</strong>: Hang up and immediately dump the number into a blacklisted database.</li><li><strong>Send Custom Response</strong>: Fire back an automated, synthesized audio message asking for more clarity without ever forcing the user to speak.</li></ul><p>Simultaneously, the entire transaction — including the searchable transcription text and a full call recording exported as an uncompressed <strong>WAV file</strong> — is persisted locally using a structured <strong>Room (SQLite) database</strong> for historical audit trails.</p><h3>Guarding the Human Firewall</h3><p>We shouldn’t build software systems or mess with low-level mobile kernels just for the sake of writing code. We do it to defend our most scarce asset: human attention.</p><p>By taking a privacy-first approach — eliminating cloud analytics, ensuring full offline functionality, and keeping all recordings local — this architecture proves that you don’t have to trade your personal data for operational peace of mind. Forcing an incoming communication stream to declare its intent before it earns the right to interrupt you isn’t just a neat mobile hack; it’s an essential practice for reclaiming your focus and reducing cognitive load in a noisy world.</p><h3>🚀 Audit the System: Explore the Repository</h3><p>If you are a privacy enthusiast, a Android developer, or someone running a rooted device who is tired of the contextless interrupt tax, the entire project is open-source and auditable under the <strong>GPL v3 license</strong>.</p><p>You can check out the full implementation, download the latest compiled production package, or review the modular Kotlin architecture over on GitHub:</p><p>👉 <a href="https://github.com/tonypius/android-reason-for-calling"><strong>Explore the android-reason-for-calling Repository</strong></a></p><p>Feel free to dive into the codebase, open an issue if you encounter edge cases in the telephony hooks, or fork the repository to build out your own automated response payloads. Let’s build cleaner, quieter developer environments together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f093420a3a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building JustOTT: An Automated “Where to Watch” Engine for Indian OTT Content]]></title>
            <link>https://medium.com/@tonypiusalapatt/building-justott-an-automated-where-to-watch-engine-for-indian-ott-content-0a75be9505f5?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a75be9505f5</guid>
            <category><![CDATA[ott-platform]]></category>
            <category><![CDATA[movies]]></category>
            <category><![CDATA[tv-shows]]></category>
            <category><![CDATA[movies-to-watch]]></category>
            <category><![CDATA[tv-series]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Wed, 13 May 2026 09:56:13 GMT</pubDate>
            <atom:updated>2026-05-13T09:56:13.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ck2GoN03T1rGyakWbdOz1g.png" /></figure><p>If you watch Indian movies — especially regional cinema — you’ve likely faced this friction:</p><p>You know <em>what</em> you want to watch, but finding <strong>which OTT platform</strong> it’s currently available on takes more time than it should.</p><p>The information exists, but it’s fragmented:</p><ul><li>Spread across entertainment news articles</li><li>Often outdated</li><li>Rarely available through structured or free APIs</li></ul><p>I wanted to explore whether this problem could be solved through a <strong>fully automated data pipeline</strong>, without manual curation.</p><p>That exploration resulted in <strong>JustOTT</strong>, an open-source project that continuously discovers Indian movies and tracks their OTT availability.</p><p>GitHub: <a href="https://github.com/tonypius/just-ott">https://github.com/tonypius/just-ott</a></p><h3>The Core Challenge</h3><p>For global content, “where to watch” platforms rely on licensed datasets and paid APIs. That approach doesn’t scale well to Indian cinema, particularly regional industries.</p><p>In practice:</p><ul><li>OTT availability is announced via <strong>news articles</strong></li><li>Data is unstructured</li><li>Platforms and availability change frequently</li><li>There is no single authoritative source</li></ul><p>So the problem wasn’t UI or search — it was <strong>building a reliable ingestion and normalization system</strong>.</p><h3>Design Constraint: No Manual Maintenance</h3><p>From the start, I imposed a constraint:</p><blockquote><em>The system should not require ongoing human updates.</em></blockquote><p>Movie discovery, OTT updates, and indexing all needed to happen automatically. Otherwise, the data would become stale very quickly.</p><h3>Movie Discovery via Wikipedia</h3><p>Wikipedia turned out to be the most practical foundation for movie metadata:</p><ul><li>Broad coverage across Indian languages</li><li>Structured infoboxes</li><li>Free and permissive API access</li></ul><p>JustOTT uses Wikipedia to:</p><ul><li>Discover movies across languages and years</li><li>Parse structured metadata (title, year, cast, director, language, posters)</li><li>Normalize and store this data in a local schema</li></ul><p>This provides a continuously expanding movie catalog without proprietary datasets.</p><h3>Extracting OTT Availability from News</h3><p>There is no public API that answers:</p><blockquote><em>“Which Indian movies are currently streaming on which platforms?”</em></blockquote><p>However, OTT releases are consistently reported by entertainment media.</p><p>JustOTT:</p><ol><li>Consumes RSS feeds from multiple Indian entertainment sources</li><li>Scrapes article content</li><li>Uses an <strong>LLM-assisted extraction pipeline</strong> to convert unstructured text into structured data:</li></ol><ul><li>Movie title</li><li>OTT platform</li><li>Availability or release date</li></ul><p>The LLM is used strictly for <strong>information extraction</strong>, not inference. All outputs are validated against known platforms and existing movie records, with source URLs retained for traceability.</p><h3>Matching, Validation, and Search</h3><p>Extracted data is:</p><ul><li>Matched against the Wikipedia-derived movie catalog</li><li>Stored with references to original articles</li><li>Indexed into <strong>Meilisearch</strong> for fast, typo-tolerant search</li></ul><p>This allows users to search naturally — even with partial or misspelled queries — while keeping the ingestion pipeline independent from the user-facing experience.</p><h3>Fully Automated Pipeline</h3><p>Once deployed:</p><ul><li>A scheduled job fetches new articles daily</li><li>OTT announcements are processed automatically</li><li>Availability data is updated incrementally</li><li>Search results stay current without manual intervention</li></ul><p>If no new information is found, the system remains unchanged. If platforms update their catalogs, the index reflects it.</p><h3>Tech Stack Overview</h3><ul><li><strong>Frontend</strong>: Next.js, Tailwind CSS, shadcn/ui</li><li><strong>Backend</strong>: Serverless API routes</li><li><strong>Database</strong>: Supabase (PostgreSQL)</li><li><strong>Search</strong>: Meilisearch</li><li><strong>Scraping</strong>: RSS feeds + HTML parsing</li><li><strong>Extraction</strong>: LLM-assisted structured parsing</li><li><strong>Hosting</strong>: Vercel</li></ul><p>The focus was on clarity of data flow, reliability, and maintainability rather than novelty.</p><h3>Why Open Source</h3><p>This project is open source because:</p><ul><li>The problem is broadly applicable</li><li>The architecture may be useful beyond this use case</li><li>Others can extend it to additional languages, platforms, or regions</li></ul><p>It’s designed to be understandable, inspectable, and adaptable.</p><h3>Closing Thought</h3><p>JustOTT started as a practical attempt to reduce friction in discovering Indian OTT content. The interesting part wasn’t the UI, but whether a <strong>hands-off, automated system</strong> could be built around a domain with no structured APIs.</p><p>It turns out it can — by combining public data sources, careful validation, and targeted use of AI.</p><p>Repository: <a href="https://github.com/tonypius/just-ott">https://github.com/tonypius/just-ott</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a75be9505f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smarter Meetings - 1 : Stop Meeting to Think. Start Meeting to Decide.]]></title>
            <link>https://medium.com/@tonypiusalapatt/smarter-meetings-1-stop-meeting-to-think-start-meeting-to-decide-e5ad8cd15156?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5ad8cd15156</guid>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[meetings]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Tue, 12 May 2026 07:58:39 GMT</pubDate>
            <atom:updated>2026-05-12T07:58:39.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWmTZ5mrxJn7BNSmsEXwSQ.png" /></figure><p>Every startup founder has experienced some version of this meeting.</p><p>You gather ten smart people from Product, Engineering, Sales, Marketing, and Finance into a room for what is supposed to be a strategic alignment workshop. Ninety minutes are blocked on everyone’s calendar, priorities are temporarily paused, and the expectation is that by the end of the session the team will have clarity on direction and next steps.</p><p>But that is rarely what actually happens.</p><p>Most cross-functional meetings spend the majority of their time simply reconstructing context. Marketing walks through campaign timelines, Engineering explains technical constraints, Finance raises budget considerations, and Sales brings customer pressure from the field. Everyone is intelligent and well-intentioned, but each participant arrives with a completely different operational picture in their head.</p><p>By the time the group collectively understands where the actual points of friction are, the meeting is almost over.</p><p>And someone inevitably says:</p><blockquote><em>“We should probably schedule a follow-up.”</em></blockquote><p>At some point, every growing company realizes the uncomfortable truth: the problem is not really the meeting itself. The deeper issue is that organizations are using synchronous collaboration time for discovery instead of decision-making.</p><p>Meetings have quietly become expensive environments for information transfer when they should ideally be reserved for resolving tradeoffs, navigating ambiguity, and making hard decisions.</p><h3>The Anatomy of a Broken Workshop</h3><p>The inefficiency becomes much more obvious as organizations scale. What starts as “collaboration” slowly turns into operational drag, especially when multiple departments are involved.</p><p>One of the biggest problems is that live workshops naturally reward the people who are most comfortable speaking quickly and confidently in groups. Extroversion starts looking like clarity. Fast responses start looking like strategic thinking.</p><p>Meanwhile, some of the most valuable perspectives in the room often come from people who need time to process complexity before responding. Engineers thinking through edge cases. Operations teams evaluating execution risk. Analysts spotting second-order effects that nobody else considered.</p><p>But live brainstorming rarely creates space for that kind of thinking.</p><p>The result is subtle but important: meetings optimize for conversational momentum, not necessarily depth.</p><p>Then there is the famous “pre-work” expectation.</p><p>Every manager says the same thing before a workshop:</p><blockquote><em>“Please review the documents beforehand.”</em></blockquote><p>But let’s be honest. Nobody realistically can.</p><p>Modern organizations generate too much fragmented context for that expectation to work at scale. Marketing uploads strategy decks, Product shares roadmap documents, Engineering references tickets and architecture notes, while Finance drops spreadsheets into a shared drive that already has fifteen other folders nobody has opened in weeks.</p><p>Even highly disciplined teams struggle here. It is not because people are lazy. The cognitive overhead is simply enormous.</p><p>And even if someone <em>does</em> read everything, nobody has enough time to properly cross-reference all of it before the meeting begins. Nobody is sitting there building a mental dependency graph between a Jira ticket, a campaign launch date, a budget approval cycle, and a customer escalation thread buried somewhere in Slack.</p><p>So what happens instead?</p><p>The meeting itself becomes the processing layer.</p><p>Humans walk into the room cold and attempt real-time synthesis across disconnected systems, competing priorities, and incomplete information. That is an incredibly expensive way to operate — especially when you multiply it across leadership teams every single week.</p><p>There is also another issue hiding underneath all of this: modern organizations no longer operate in shared environments.</p><p>Marketing lives in campaign tools. Engineering lives in tickets and repositories. Sales lives in CRMs. Finance lives in spreadsheets. Operations lives in dashboards and Slack threads.</p><p>Each department develops its own operational language, priorities, metrics, and assumptions. Then we bring everyone together into a single meeting and expect instant alignment.</p><p>Half the conversation becomes translation.</p><p>The other half becomes clarification.</p><p>Very little becomes decision-making.</p><h3>We Are Using AI Backwards</h3><p>This is where I think most organizations are fundamentally underestimating the role AI can play in collaboration.</p><p>Right now, AI in meetings is mostly treated as an administrative assistant. It records conversations, generates transcripts, summarizes discussions, and extracts action items after the meeting has already happened.</p><p>Useful? Absolutely.</p><p>Transformational? Not really.</p><p>Most of these tools are optimizing documentation, not improving the quality of thinking itself. They help us remember conversations more efficiently, but they do not fundamentally change how organizations arrive at decisions.</p><p>And more importantly, they are focused entirely on the wrong side of the workflow.</p><p>Today’s AI meeting tools look backward.</p><p>The much more interesting opportunity is to make AI look forward.</p><p>Instead of asking humans to manually absorb fragmented context across dozens of documents, spreadsheets, chats, tickets, and planning tools, what if AI became the synthesis layer <em>before</em> the meeting even started?</p><p>That mental shift completely changes the role AI plays inside organizations.</p><p>The best analogy I have found is this:</p><p>AI should not behave like a meeting secretary.</p><p>It should behave like an elite Chief of Staff.</p><p>A great Chief of Staff does not walk into a strategy session blind. They already understand where departments align, where priorities conflict, which concerns are operational versus political, and which disagreements actually deserve executive attention.</p><p>Now imagine an AI system doing exactly that — asynchronously and at scale.</p><p>Instead of forcing humans to digest twenty disconnected sources of context, the AI interviews stakeholders independently, reads supporting documents, maps dependencies, identifies contradictions, clusters overlapping ideas, and surfaces unresolved tensions before anyone enters the room.</p><p>Not a summary.</p><p>A synthesis.</p><p>That distinction matters more than most people realize.</p><p>Summaries tell you what was said.</p><p>Synthesis tells you what matters.</p><h3>The “Pre-Solved” Meeting</h3><p>Once you think about collaboration this way, the structure of meetings starts changing entirely.</p><p>Imagine a workflow where teams contribute context independently before the discussion begins. Product shares roadmap priorities, Engineering outlines technical constraints, Finance uploads budget considerations, while Sales contributes customer urgency and market feedback.</p><p>Nobody is interrupted. Nobody is pressured to think in real time. Nobody has to perform intelligence in front of a room.</p><p>People simply contribute context when they have the mental bandwidth to do it properly.</p><p>Then the AI processes everything before the meeting starts.</p><p>It identifies areas of consensus, overlapping priorities, duplicate ideas, conflicting timelines, budget mismatches, operational dependencies, and hidden assumptions. More importantly, it highlights where alignment already exists — which is often far more than teams realize.</p><p>That alone changes the dynamics dramatically.</p><p>Entire sections of the agenda disappear before the meeting even begins because the organization already agrees on them. The team simply lacked visibility into that agreement.</p><p>And now the live discussion becomes something very different.</p><p>Instead of spending the first hour discovering problems, the meeting focuses directly on the few unresolved conflicts that genuinely require human judgment.</p><p>Sales wants an aggressive Q3 rollout.</p><p>Engineering says the infrastructure risk pushes realistic delivery into Q4.</p><p>Finance wants phased investment approval tied to milestones.</p><p>Now <em>that</em> is a valuable conversation.</p><p>Not because the disagreement exists, but because the organization arrived at the disagreement quickly, clearly, and with shared context already established.</p><p>The meeting stops being an information synchronization exercise and becomes what it was supposed to be all along:</p><p>A decision engine.</p><h3>The Bigger Shift</h3><p>I do not think the future of work is about eliminating meetings.</p><p>Humans still need synchronous collaboration for ambiguity, negotiation, trust-building, and difficult tradeoff discussions. Some problems genuinely require people in a room working through nuance together.</p><p>But most meetings today are overloaded with work that humans are actually very inefficient at doing manually.</p><p>Information gathering.</p><p>Context reconstruction.</p><p>Dependency mapping.</p><p>Cross-referencing fragmented inputs.</p><p>AI happens to be extraordinarily good at exactly those things.</p><p>Humans, meanwhile, are far better at judgment, prioritization, and navigating uncertainty.</p><p>The organizations that gain real leverage from AI over the next decade will probably not be the ones using it to automate note-taking. They will be the ones redesigning collaboration itself around the strengths of both humans and machines.</p><p>AI handles asynchronous synthesis.</p><p>Humans handle decisions.</p><p>That feels like a much more interesting future than another meeting transcript nobody reads.</p><h3>What Comes Next</h3><p>The exciting part is that this is no longer theoretical.</p><p>The tooling ecosystem has finally matured enough to make this kind of workflow possible. Large language models can already reason across fragmented organizational context surprisingly well. Retrieval systems can securely connect scattered knowledge bases. Workflow agents can orchestrate structured information gathering across teams and systems.</p><p>The challenge now is not capability.</p><p>It is architecture.</p><p>How do you securely ingest organizational knowledge spread across drives, chats, tickets, and documents? How do you prevent hallucinations when AI is reasoning across incomplete business context? How do you create alignment heatmaps that leadership teams can actually trust?</p><p>And perhaps most importantly:</p><p>How do you design all of this in a way that teams genuinely adopt instead of treating it like another layer of operational overhead?</p><p>That is the part I have been obsessing over recently.</p><p>In my next post, I’ll lift the hood and walk through the actual architecture, workflows, and AI patterns we are experimenting with to make this real.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5ad8cd15156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smarter Meetings - 2: Killing the Status Meeting: How I Built an AI Pipeline That Does Pre-Work So…]]></title>
            <link>https://medium.com/@tonypiusalapatt/killing-the-status-meeting-how-i-built-an-ai-pipeline-that-does-pre-work-so-you-dont-have-to-31141776e3c4?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/31141776e3c4</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[meetings]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Mon, 11 May 2026 13:51:18 GMT</pubDate>
            <atom:updated>2026-05-12T07:59:45.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>Smarter Meetings - 2: <strong>Killing the Status Meeting: How I Built an AI Pipeline That Does Pre-Work So You Don’t Have To</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVjpK3qsFo-a_NPnPBbdaQ.png" /></figure><p>You know the meeting. The one that was supposed to be 30 minutes but ran 90. The one where the first 45 minutes was everyone reading slides out loud, catching up on context that could have been an email. The one where the actual decisions — the whole reason everyone got on the call — got crammed into the last ten minutes while someone was already saying “I have a hard stop.”</p><p>If you’ve worked in any organization larger than a handful of people, you’ve sat through this meeting. Maybe you’ve run it.</p><p>The uncomfortable truth is that most alignment meetings aren’t alignment meetings at all. They’re information-gathering sessions dressed up with an agenda. The real work — surfacing constraints, identifying conflicts, figuring out where teams actually agree — happens by accident, piecemeal, while everyone’s already on the clock.</p><p>I built <strong>S.Y.N.C. Agent</strong> to fix this. It’s an open-source AI system that collects pre-work from meeting participants asynchronously, runs it through a multi-agent pipeline to map alignment and conflicts, and hands the meeting conductor a dashboard that shows exactly where the hard decisions are — before anyone joins the call.</p><p>The full source code is on <a href="https://github.com/tonypius/sync-ai-workflow">GitHub</a>.</p><p><strong>— -</strong></p><h3><strong>The Insight: Pre-Work Is the Lever</strong></h3><p>The meeting itself isn’t the problem. The problem is that we use synchronous time for asynchronous work.</p><p>Think about what actually needs to happen before a planning meeting: every stakeholder needs to articulate their constraints, their priorities, and their concerns. Those constraints need to be compared. Conflicts need to be surfaced. Areas of agreement need to be identified. None of this requires everyone to be in the same room at the same time.</p><p>But in practice, pre-work rarely happens. It’s a shared Google Doc that nobody fills out. It’s a Slack thread that devolves into side conversations. It’s an email that gets skimmed. The friction is too high, and the incentive is too low — because nobody sees the payoff until they’re already in the meeting, wishing they had done the pre-work.</p><p>S.Y.N.C. Agent flips this dynamic. Instead of asking participants to fill out a form, it meets them where they already are — in Google Chat. Participants DM a bot with their constraints and ideas. The bot handles the formatting, the organization, and the follow-up. When someone hasn’t contributed, it nudges them automatically. The bar for participation drops to “have a conversation with a bot.”</p><p>Then, before the meeting starts, the system runs an AI pipeline that does the hard part: reading everything everyone said, extracting the key entities and relationships, mapping who agrees with whom, flagging the contradictions, and synthesizing it all into a dashboard the conductor can actually use.</p><p>The meeting becomes what it should have been all along: a focused session where people make decisions about things that are already understood.</p><p><strong>— -</strong></p><h3><strong>How It Works: The Four-Agent Pipeline</strong></h3><p>The core of S.Y.N.C. Agent is a multi-agent pipeline built with LangGraph. Four agents run sequentially, each with a distinct job. This isn’t a single LLM call with a long prompt — it’s a deliberate decomposition of the problem into stages that can be tested, debugged, and improved independently.</p><h4><strong>Agent 1: Knowledge Extractor</strong></h4><p>This is the reader. It ingests all the pre-work submissions — Markdown files, PDFs, chat logs — from Google Drive. For each document, it extracts the entities (people, departments, budgets, technical requirements, timelines) and the relationships between them. These get written as nodes and edges into a Neo4j graph database.</p><p>Why a graph database? Because stakeholder alignment is fundamentally a graph problem. “Sarah supports the AWS migration” is a relationship between two entities. “Engineering needs three weeks but Finance blocks anything over one week” is a contradiction between two edges. Trying to represent this in a flat document or a vector database loses the relational structure that makes conflict detection possible.</p><p>I use GLM-5.1 for this agent — it handles high-volume extraction reliably without the cost of a larger model.</p><h4><strong>Agent 2: Alignment &amp; Conflict Analyst</strong></h4><p>This is where it gets interesting. The analyst agent traverses the graph looking for two things: consensus clusters (highly connected nodes where multiple departments share positive edges) and contradictions (edges that conflict — like competing timelines, opposing technical requirements, or resource disputes).</p><p>This agent requires more reasoning capability, so it runs on Claude. A typical conflict might look like: `[Team A] → REQUIRES → [3 Weeks]` and `[Team B] → BLOCKS → [Anything over 1 Week]`. These aren’t just different opinions — they’re hard constraints that need to be resolved in the meeting, and surfacing them beforehand means the conductor can allocate time intentionally instead of discovering them mid-call.</p><p>The output is a structured map: here’s where everyone agrees, here’s where they don’t, and here’s where the contradictions are irreconcilable without a decision.</p><h4><strong>Agent 3: Dashboard Synthesizer</strong></h4><p>The analyst’s output is raw structured data. The synthesizer transforms it into the JSON payloads that power the visual dashboard — the alignment heatmap, the roadblock matrix, and the stakeholder network graph. Each of these views is designed to answer a specific question the conductor has before and during the meeting:</p><p>- <strong>Alignment Heatmap:</strong> “Where do teams agree?” — a color-coded matrix showing consensus points across departments, with sentiment breakdown.</p><p>- <strong>Roadblock Matrix:</strong> “What’s going to block us?” — flagged technical, financial, and strategic conflicts, ranked by severity.</p><p>- <strong>Stakeholder Network Graph:</strong> “Who is backing what?” — a visualization of coalition formations and influence patterns.</p><h4><strong>Agent 4: Live Meeting Copilot</strong></h4><p>During the meeting itself, a fourth agent listens to the conversation (via Google Meet transcription) and can answer questions with full context from the pre-work analysis. “What were Engineering’s main concerns?” “Which teams have conflicting timelines?” — the conductor can query the system without leaving the flow of the meeting.</p><p>The copilot also auto-detects when the discussion resolves a previously flagged conflict and triggers recalibration — updating the dashboard in real-time. Three recalibration modes handle different scenarios: a full re-run of the pipeline (agents 1→2→3), a conflict-only re-analysis (2→3), or a visual-only refresh (3). The system chooses the appropriate depth automatically.</p><p><strong>— -</strong></p><h3><strong>What the Conductor Sees</strong></h3><p>The Conductor Hub is a Next.js web application that presents all of this through a clean, opinionated interface. After logging in with Google OAuth, the conductor lands on their meeting list — every event they’ve created, scoped to their email.</p><p>For each event, there’s a pre-work dashboard showing who has and hasn’t submitted, a progress bar, and auto-nudge status (the system automatically pings participants who haven’t contributed when the deadline is less than 24 hours away). No manual follow-up required.</p><p>Once the pre-work deadline passes and the pipeline runs, the intelligence dashboard comes alive. The alignment heatmap immediately shows where consensus exists — no more spending 20 minutes of meeting time discovering that everyone actually agrees on the timeline. The roadblock matrix highlights the three conflicts that need airtime. The stakeholder network graph reveals the coalition dynamics: who’s aligned with whom, which departments are isolated, and where the swing decisions live.</p><p>During the meeting, the live console integrates the Meet link with the real-time dashboard. As decisions get made, the conductor can trigger recalibration to update the views. After the meeting, the export page generates the final output — a Google Doc with meeting summary and task assignments, or JSON/Markdown for integration into other workflows.</p><p>Every task in the export is traceable back to its originating constraint in the graph database. Not “someone mentioned something about timelines” — a specific edge connecting a specific team to a specific requirement, resolved to a specific decision.</p><p><strong>— -</strong></p><h3><strong>Under the Hood</strong></h3><p>S.Y.N.C. Agent is a three-service monorepo managed with npm workspaces and Turborepo:</p><p>- <strong>AI Core</strong> (Python 3.11, FastAPI, LangGraph) — the agent pipeline, Neo4j integration, and all API endpoints. Runs on port 8000.</p><p>- <strong>Conductor Hub</strong> (Next.js 16, React 19, Tailwind v4) — the web dashboard. Google OAuth via NextAuth v5, API key auth to AI Core. Runs on port 3000.</p><p>- <strong>Participant Hub</strong> (Node.js, TypeScript) — the Google Chat webhook handler. Receives messages, forwards to AI Core, handles auth and rate limiting. Runs on port 3001.</p><p>The data layer is Neo4j AuraDB (cloud-hosted graph database on the free tier) with seven node types: Event, Participant, Department, Constraint, Topic, Task, and User. Google Drive stores the raw pre-work documents.</p><p>Everything runs locally with Docker Compose — three containers, one `docker compose up` command. No Kubernetes, no service mesh, no infrastructure complexity. The AI Core has a health check that verifies Neo4j connectivity, and the other services depend on it being healthy before starting.</p><p>The design system is PostHog-inspired: warm parchment backgrounds, olive/sage color palette, IBM Plex Sans typography. It’s deliberately not another generic blue SaaS interface — the visual language reflects the product’s personality: serious about the problem, opinionated about the solution.</p><p>For deployment beyond local dev, there are GCP Cloud Run configs in the repository. But the Docker Compose setup is the primary development experience — clone, configure, run.</p><p><strong>— -</strong></p><h3><strong>What I Learned</strong></h3><p><strong>Graph databases are a natural fit for stakeholder mapping.</strong> I started with the assumption that a graph structure would better represent organizational dynamics than flat documents. In practice, it exceeded expectations. The ability to traverse relationships — “find all departments that have conflicting constraints about the Q3 timeline” — is a query that’s natural in Cypher but nearly impossible in a traditional document or relational model. Neo4j’s free AuraDB tier was sufficient for the MVP.</p><p><strong>Multi-agent pipelines beat monolithic LLM calls.</strong> Early on, I considered a single “super-prompt” approach — one big LLM call that reads everything and produces the dashboard. It failed in predictable ways: the output was inconsistent, hard to debug, and impossible to improve incrementally. Breaking the problem into four distinct agents with clear inputs and outputs made each piece testable (61 tests across the three services) and allowed me to route different agents to different models based on their reasoning requirements.</p><p><strong>The real lever is structured pre-work.</strong> The AI pipeline is cool. The graph database is elegant. But the thing that actually makes meetings shorter is forcing structured input before the meeting starts. The bot lowers the friction enough that people actually do the pre-work, and the AI makes the pre-work useful enough that the conductor can run a tighter meeting. The technology enables the behavior change — it’s not a substitute for it.</p><p><strong>— -</strong></p><h3><strong>Try It</strong></h3><p>S.Y.N.C. Agent is open source and runs locally with Docker. If you’re curious about multi-agent pipelines, graph-based AI, or just want to see what it looks like when an AI system actually makes meetings better:</p><p><a href="https://github.com/tonypius/sync-ai-workflow"><strong>github.com/tonypius/sync-ai-workflow</strong></a></p><p>Clone it. Run it. Break it. Open an issue. I’d love to hear what you think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31141776e3c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding with AI: The Hidden Nuances Developers Often Miss]]></title>
            <link>https://medium.com/@tonypiusalapatt/vibe-coding-with-ai-the-hidden-nuances-developers-often-miss-6a14b7283f33?source=rss-e2f0bd5541d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a14b7283f33</guid>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Tony Alapatt]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 15:23:56 GMT</pubDate>
            <atom:updated>2025-10-15T15:23:56.792Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From SWE-bench hype to real-world integration, here’s what really matters when choosing AI coding tools — and how to build smarter once you do.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*OOh7x931LfjR0jsJietdKQ.png" /></figure><h3>Introduction</h3><p>AI-assisted coding — or what some developers casually call <em>“vibe coding”</em> — is having its moment. Tools like <a href="https://www.anthropic.com/news/claude-code">Claude Code</a>, <a href="https://deepmind.google/technologies/gemini/">Gemini CLI</a>, <a href="https://github.com/princeton-nlp/SWE-agent">SWE-agent</a>, and <a href="https://github.com/QwenLM/Qwen">Qwen-Coder</a> are revolutionizing the way we write and manage code.</p><p>But amid the flood of benchmarks, GitHub demos, and Twitter hype, there are subtle — but important — nuances that many developers overlook.</p><p>This post dives into <strong>five critical areas</strong> that should shape how you evaluate and use these tools: from the relevance of benchmarks to the risks of closed-source systems, and finally, how to build a mental model that makes you truly 10x faster with AI.</p><h3>1. The SWE-Bench Illusion: What Benchmarks Miss</h3><p>The <a href="https://github.com/princeton-nlp/SWE-bench">SWE-bench benchmark</a> is the go-to dataset for evaluating AI agents on GitHub issues and pull requests. At face value, a tool that scores high here seems like a safe bet. But the story underneath tells a different tale.</p><p>A recent analysis of SWE-bench revealed that nearly <strong>32% of “successful” patches</strong> simply reused answers already present in issue comments — a case of <em>solution leakage</em>. Another 31% passed due to weak or incomplete tests. When these were removed, the top-performing agent’s actual success rate dropped from <strong>12.5% to just 4%</strong>.</p><p>Newer benchmarks like <a href="https://huggingface.co/datasets/PolyCoder/swe-polybench">SWE-PolyBench</a> and <a href="https://github.com/princeton-nlp/SWE-bench#swe-bench-live">SWE-bench-Live</a> are addressing these flaws by introducing multi-language, real-time, and contamination-free setups.</p><p><strong>Takeaway:</strong> Don’t let a shiny leaderboard number replace critical thinking. Real-world performance often deviates significantly.</p><h3>2. Coding from Scratch vs. Navigating Legacy Code</h3><p>AI excels at generating new code. Need a quick Flask API or a sorting algorithm? Claude, Gemini, or Qwen will do it in seconds. But integrating that into a large, messy, legacy codebase? That’s where most agents struggle.</p><p>Real-world codebases require:</p><ul><li>Multi-file reasoning</li><li>Awareness of business logic</li><li>Cross-repo dependencies</li><li>Compliance with architectural patterns</li></ul><p>Agents with large context windows — like <strong>Gemini CLI (1M tokens)</strong> or <strong>Qwen-Coder (up to 256K tokens)</strong> — are better equipped for these challenges. But even they hit limits when tests are flaky or documentation is sparse.</p><p><strong>Takeaway:</strong> Choose AI tools based on how well they operate in your context — not just on clean, new projects.</p><h3>3. Closed-Source Tools: Privacy vs. Performance</h3><p>Claude Code and Gemini CLI are powerful and polished. They boast high accuracy, robust UIs, and developer-friendly workflows. But their cloud-based nature raises <strong>major concerns for enterprise users</strong>.</p><p>Issues to consider:</p><ul><li>Data telemetry and retention</li><li>Lack of on-prem control</li><li>Unclear audit trails</li><li>Potential licensing conflicts</li></ul><p>Even well-intentioned agents can make catastrophic mistakes. <a href="https://old.reddit.com/r/replit/comments/1fry4e3/replit_ai_wiped_my_database/">Replit’s AI wipe-out of a production database</a> is a stark reminder that guardrails matter.</p><p><strong>Takeaway:</strong> Closed-source AI tools may be convenient, but they’re often unsuitable for privacy-sensitive or regulated environments.</p><h3>4. Open-Source Vibe-Coding Tools: What to Choose</h3><p>The open-source AI coding landscape is vibrant but noisy. Not all tools are equal — and it takes experimentation to find what works.</p><p>ToolOpen SourceContext WindowBest For<a href="https://github.com/princeton-nlp/SWE-agent">SWE-agent</a>✅ Yes~200K tokensGitHub-style issue resolutions<a href="https://bolt.diy/">bolt.diy</a>✅ YesUI-driven contextRapid full-stack prototyping<a href="https://github.com/all-hands-ai">All-Hands AI</a>⚠️ Semi-openTask dependentSpecialized SWE workflows<a href="https://github.com/QwenLM/Qwen">Qwen-Coder</a>✅ Yes256K–1M tokensLarge codebase integration</p><p>Each has strengths, but your use case — speed, privacy, or complexity — should guide your decision.</p><p><strong>Takeaway:</strong> Open-source tools provide control and flexibility, but pick based on <em>real needs</em>, not GitHub stars.</p><h3>5. Beyond Problems: Building Faster with a Thinking-First Workflow</h3><p>Once you’ve picked your AI coding assistant — say <a href="https://openai.com/research/codex">OpenAI Codex</a> or Claude Code — the real productivity boost comes not from prompting harder, but from <strong>thinking smarter</strong>.</p><p>The secret: <strong>Use AI first to conceptualize, then to code.</strong></p><p>Before writing a line of code, use ChatGPT or Gemini to produce a <em>detailed write-up</em> of what you’re building. Think about <strong>architecture, layering, and feature priority</strong>. This mental matrix will help you ship the right app — not just any app — 10× faster.</p><h3>🧩 The 6-Step Vibe-Coding Workflow</h3><ol><li><strong>Concept doc (AI-assisted)</strong> — Use your LLM to generate a one-pager: goals, users, success metrics, constraints.</li><li><strong>Architecture &amp; layering</strong> — Define your stack by layers (UI → API → Logic → Data → Infra). Note dependencies and risks.</li><li><strong>Priority matrix</strong> — Rank features by <em>impact vs complexity</em>. This becomes your roadmap.</li><li><strong>Scaffold &amp; generate</strong> — Ask the AI to create your project skeleton, CI config, and initial tests.</li><li><strong>Integration &amp; testing loop</strong> — Humans validate, AI assists with stubs, mocks, and doc generation.</li><li><strong>Observability &amp; rollback</strong> — Before shipping, use AI to produce monitoring and rollback docs.</li></ol><h3>🧠 Your Mental Matrix Template</h3><p>FeatureLayerPriorityRisk / NotesAuth &amp; sessionsAPI/Infra1Must support SSO laterUpload pipelineData1Validate for large filesReporting dashboardUI2Can be delayed to v1.1ML inference endpointInfra/ML3Security review needed</p><p>Keep this visible in your repo — it’s your compass when AI generation drifts.</p><h3>⚙️ Prompt Templates You Can Reuse</h3><p><strong>1. Generate a concept doc</strong></p><pre>You are a product architect. Create a one-page concept doc for a [type] app aimed at [users]. Include: problem, target users, 3 flows, 3 success metrics, and top constraints. ~300 words.</pre><p><strong>2. Build an architecture sketch</strong></p><pre>Produce a layered architecture for the concept above. Layers: UI, API, Business Logic, Data, Integrations, Infra. Include risks + tech options.</pre><p><strong>3. Create an MVP matrix</strong></p><pre>List 8 features. Mark each as P1/P2/P3 with justification and complexity (S/M/L).</pre><p><strong>4. Scaffold project + tests</strong></p><pre>Generate a scaffold for [tech stack] with folders, README, sample tests, and CI setup.</pre><h3>Example: Sustainability Microservice</h3><p>Let’s say you’re building a “team sustainability scorecard” app.</p><ol><li><strong>Concept:</strong> Facility managers tracking sustainability KPIs.</li><li><strong>Architecture:</strong> REST API → Scoring service → Postgres → Grafana.</li><li><strong>Priority:</strong> Auth (P1), scoring (P1), dashboard (P2), ML forecast (P3).</li><li><strong>Scaffold:</strong> Ask Codex or Claude to generate the skeleton and tests.</li><li><strong>Integrate &amp; test:</strong> You focus on business rules — AI handles boilerplate.</li></ol><h3>Final Thoughts</h3><p>Vibe coding is real — and AI makes it faster, more expressive, and more creative. But tools alone don’t define velocity.</p><p>The developers who win with AI aren’t the ones chasing leaderboards — they’re the ones <strong>using AI to think first, code second</strong>. Build a concept, define your layers, and let your assistant accelerate execution — not replace intention.</p><p><strong>Your AI is only as good as the thoughtfulness with which you wield it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a14b7283f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>