<?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 Ashmit Biswas on Medium]]></title>
        <description><![CDATA[Stories by Ashmit Biswas on Medium]]></description>
        <link>https://medium.com/@ashmitbbiswas?source=rss-dedb2b307718------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qOTBtws2BxVk-B6Q--m7eQ.jpeg</url>
            <title>Stories by Ashmit Biswas on Medium</title>
            <link>https://medium.com/@ashmitbbiswas?source=rss-dedb2b307718------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:25:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashmitbbiswas/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[Worktrees across repos, take two. This time, it’s multi-agent too.]]></title>
            <link>https://medium.com/@ashmitbbiswas/worktrees-across-repos-take-two-this-time-its-multi-agent-too-9a3f78d13b27?source=rss-dedb2b307718------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a3f78d13b27</guid>
            <category><![CDATA[multi-repo]]></category>
            <category><![CDATA[git-worktree]]></category>
            <category><![CDATA[multi-agent]]></category>
            <category><![CDATA[agent-harness]]></category>
            <category><![CDATA[ai-orchestration]]></category>
            <dc:creator><![CDATA[Ashmit Biswas]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 03:33:44 GMT</pubDate>
            <atom:updated>2026-11-04T03:33:44.601Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The first version gave agents better tools for managing worktrees. What they needed was to never manage them at all.</em></p><p>Back in April, I wrote about <a href="https://medium.com/@ashmitbbiswas/git-worktrees-are-great-managing-them-across-3-repos-is-not-12262be5ddb0">why Git worktrees are great, and why managing them across three repos is not</a>. That post introduced Canopy, a CLI that treated a feature as one thing across every repo it touched: one command to switch to it, one to see its state, one to clean it up.</p><p>The CLI kept growing after that post. The biggest addition was an MCP server that put every command in front of an AI agent as a typed tool, so the agent could drive multi-repo work as safely as I could. That layer is the part I got wrong, and the reason I have rebuilt Canopy from scratch as a VS Code extension <strong>that asks much less of the agent</strong>.</p><h3>The agent contract</h3><p>Over multiple iterations, I grew the original CLI to expose 43 MCP tools. Then 60+, then cut it down to 15. Every one took a feature and a repo as parameters, returned JSON, and failed with a structured error that named what was expected, what was found, and how to fix it. The README called it an <em>agent contract</em>, and the pitch went like this:</p><pre># Brittle: the agent builds the path and parses stderr<br>bash(&quot;cd ~/work/.canopy/worktrees/sin-7/test-api &amp;&amp; git status&quot;)</pre><pre># Path-safe: Canopy owns the path and returns structured data<br>mcp__canopy__feature_status(feature=&quot;sin-7-empty-state&quot;)</pre><p>The idea was sound as far as it went. Agents lose their shell state between tool calls, build paths wrong, and burn context re-reading git status. Give them typed tools that own the paths, and those mistakes go away. I installed git hooks to catch drift between calls, cached workspace state so the agent read it instead of re-deriving it, and registered a skill telling Claude Code to prefer Canopy&#39;s tools over raw git.</p><h3>Why it did not work</h3><p>The contract only held if the agent chose to honor it, and an agent does not have to.</p><ul><li><strong>Tools are suggestions.</strong> A model that knows git well will reach for git. A skill that says &quot;use the Canopy tools&quot; competes with everything else in the context, and the further a session runs, the more it loses.</li><li><strong>The agent still had to know where it was.</strong> Every tool took a feature parameter, so the agent had to track which feature it was working on, across turns and through compactions. Getting that wrong was the exact class of mistake the tools existed to prevent.</li><li><strong>Every tool cost context.</strong> Forty-three tool descriptions sit in the context before the agent has done anything, and every call returns JSON the agent has to read and keep track of.</li><li><strong>It assumed one agent.</strong> The contract was written for Claude Code. Codex, Grok, and the rest each had their own way of running tools, and none of them came with my skill.</li></ul><p>The deeper problem was where Canopy sat. It was a tool the agent called, below the agent. Everything depended on the agent’s judgment: when to call Canopy, with which feature, and whether to trust the answer. I was trying to steer the agent from inside its own toolbox.</p><h3>The new mental model: a harness, not a toolbox</h3><p>The new Canopy sits above the agents instead of below them. It is the harness they run in. It starts each agent’s CLI itself, decides which folder the agent works in, decides which files it may write, writes what it is told at the start of each turn, and records what it actually did. The agent never has to know about worktrees, because it is already in the right one.</p><blockquote>The first Canopy asked the agent to manage the workspace. The new one manages the workspace and puts the agent in it.</blockquote><p>Concretely, when a chat works on a lane (a feature, as a branch in every repo that has it):</p><ul><li>The agent’s working folder <em>is</em> the lane’s worktree. There is no path for it to build and nothing to cd into.</li><li>Its writes are bounded to the lane’s folders. An edit outside them is refused with a message pointing at the same file inside the lane.</li><li>On its first turn it gets a short brief: the lane’s goal, where its plan and notes live, and its checkouts. On later turns it gets only what changed since it last ran.</li><li>After each turn Canopy snapshots the working tree, so it knows what changed whether or not the agent says so.</li></ul><p>None of this depends on the agent cooperating, and none of it costs the agent a tool call. The worktree management did not go away. It moved inside Canopy, where it belongs.</p><h3>One chat, many providers</h3><p>Owning the harness made the other big change possible. The new Canopy runs Claude, Codex, Grok, and other ACP agents side by side, each through its own official CLI and your own sign-in, in one group chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzZo7r0Rr0pNEvijGubX9A.gif" /></figure><p>You talk to one agent, the lead. You set a roster once: who researches, who implements, who reviews. When work belongs to another role, the lead hands it over, without being asked.</p><p>MCP is still in the picture, which I find a little funny. The lead gets six tools from Canopy instead of forty-three: delegate, answer_delegate, message_delegate, ask_user, stop_work, and commit_work. They are for working with teammates, not for driving Git. The bookkeeping is Canopy&#39;s job now.</p><h3>Handoffs the delegate can act on</h3><p>A handoff carries the task, what “done” means, and the lead’s findings and plan. The lead does the research, or delegates it, and the implementer gets a plan it can start on, instead of rediscovering the codebase on someone else’s tokens. Canopy adds whatever the delegate missed in the chat, word for word, and the lane’s brief. A handoff without enough context is refused, and the lead is told what is missing.</p><h3>Facts, not claims</h3><p>This is the part I care about most. When a delegate says it is done, that is a claim. Canopy records what actually happened: the files that changed, from its own snapshots, and the commands that ran. It runs your check command itself, and the delegate does not get to say whether it passed. It also watches for background work: if the delegate started something that is still running, Canopy waits for it to finish before telling the lead. The lead then judges the report against that record.</p><h3>The rest of the loop</h3><ul><li><strong>Phases.</strong> A multi-phase plan is handed over one phase at a time. The next phase starts only when the last one reports done and its checks pass, so a delegate cannot drift through a whole plan on a bad start.</li><li><strong>Questions.</strong> A delegate’s question goes to the lead first. If the chat already answers it, the lead answers. Product decisions come to you.</li><li><strong>Roles are enforced.</strong> Only the implementer can write. Everyone else is read-only, and a write that slips through anyway is flagged with an undo.</li><li><strong>You are always in the loop.</strong> @mention any agent and the message goes straight away, even mid-turn. Watch each delegate&#39;s work stream live, and stop or redirect it from its card.</li><li><strong>Undo per agent.</strong> Every delegate’s changes are snapshotted, so you can undo one agent’s work and keep everyone else’s.</li></ul><h3>Lanes: the part that survived</h3><p>The heart of the old Canopy was never the MCP layer. It was the idea that a feature is one thing, even when it spans three repos, and that you should be able to switch to it, see it, and clean it up as one thing. That idea is still at the center of the new Canopy. It is just built in now, instead of handed to the agent as tools.</p><p>The new Canopy calls it a <strong>lane</strong>. A lane is a unit of work: one branch, in every repo of your workspace that has it, with one goal, one plan, and one set of notes. Open a folder that holds several repos and Canopy finds them on its own. From then on you work in lanes, not in repos.</p><ul><li><strong>A chat works in its lane.</strong> Its agents work in that lane’s worktrees, in every repo the lane spans, and share its goal, plan, and notes. Two chats on two lanes can work at the same time without touching each other’s files.</li><li><strong>A lane grows as the work does.</strong> If an agent needs to change a repo the lane has not touched yet, Canopy brings that repo into the lane: it creates the branch and a worktree there, sets it up, and points the agent at the new path. The agent never has to ask.</li><li><strong>A lane keeps its chats current.</strong> When a lane moves to another folder, gains a repo, gets new commits, or has its plan updated, every chat on it is told on its next turn, so no agent keeps working in a folder its lane has left.</li><li><strong>Every move covers every repo.</strong> Creating, switching, parking, and warming a lane happen in all of its repos together, or in none of them. This was canopy switch&#39;s whole promise, and it still holds.</li></ul><p>The difference is who keeps track. The old Canopy needed the agent to say which feature it meant on every call. Now Canopy already knows, because it put the agent in the lane in the first place.</p><h3>How a worktree switch works now</h3><p>This is the other cornerstone of the original Canopy that I couldn’t let go of, and probably why you’re reading this post: worktrees are great, but managing them across multiple repos is not. My personal hell is testing several full-stack features the day before a release and forgetting to switch branches when I switch between chats. The result is a tangle of unrelated changes, diffs I can’t split out, and a dev server running code from the wrong feature. By the time I notice, I’ve lost an hour working out which change belongs where, at exactly the moment time is at a premium.</p><p>Canopy follows the way I like to work. The main checkout of my codebase is the one that runs the server, so features take turns in it: a worktree swaps in, gets tested, and swaps back out.</p><p>Before the switch itself, three things work differently from the old CLI.</p><ul><li><strong>Worktrees live in numbered slots.</strong> The old Canopy gave every feature its own folder, .canopy/worktrees/&lt;feature&gt;/&lt;repo&gt;/, so a feature&#39;s path changed every time it moved, and every terminal, editor window, and dev server config pointing at it broke. Now each repo has a few generic slots, .worktrees/wt-1, wt-2, and so on, and a slot holds whichever lane is there. When lanes trade places, the folders stay put and only the branches move, so paths, terminals, and installed dependencies keep working.</li><li><strong>Canopy no longer keeps its own record of Git.</strong> The old CLI installed git hooks that wrote down what was checked out where, so it could spot drift between commands. That record could itself drift. Now Canopy reads it straight from Git every time and keeps nothing to fall out of date. The only things it stores are what Git can’t know: each lane’s goal, plan, and notes.</li><li><strong>Worktree Slots are set up once and reused.</strong> The first time a lane needs a worktree in a repo, Canopy creates a slot, copies your env files over from the main checkout (.env* by default, configurable per repo), and runs that repo&#39;s setup command, say pnpm install. That is the expensive part, and it happens once per slot, not once per feature.<br>After that, the slot outlives the lanes that pass through it. Parking a lane detaches its slot but leaves the folder, the env files, and the installed dependencies in place. The next lane that needs a worktree takes the free slot and checks its branch out there, and Canopy reruns setup only if the lockfile changed between the two branches. Most of the time a new lane is ready in about the time it takes Git to switch branches.<br>Slots are capped, four per repo by default. When they’re all taken, Canopy asks which lane to park. It never evicts one on its own, and it won’t park a lane with uncommitted work. The .worktrees folder goes into Git&#39;s local exclude file, so it never shows up in git status or a commit.</li></ul><p>The catch is that a branch can be checked out in only one place at a time, so the swap is where worktrees hurt most. Say you have auth-flow in your main folders with the dev server running, export-timeouts in worktrees, and you want to run export-timeouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8wDNvKMyfLZWYccCftViw.png" /></figure><p>Clicking <strong>Run in primary </strong>runs the switch as a transaction:</p><ol><li><strong>Preflight, changing nothing.</strong> Every repo in the lane is checked and classified. Clean, or uncommitted work that applies cleanly: go ahead. A merge or rebase in progress, a detached HEAD, a locked worktree: stop and explain. Untracked files that would collide, or a branch held by a worktree Canopy did not create: ask. All repos pass, or none of them move.</li><li><strong>Wait.</strong> If a chat on either lane is mid-turn, the switch waits for that turn to end. It never yanks a folder out from under a working agent.</li><li><strong>Snapshot.</strong> Uncommitted work on both sides, untracked files included, goes into named stashes. Each stash is pinned with its own ref, so a stray git stash clear cannot lose it, and a recovery journal is written to disk.</li><li><strong>Swap.</strong> The slot’s worktree is detached to free the incoming branch. The main folder switches to it, and the outgoing lane is checked out in the slot it left. The two folders trade branches and keep their installed dependencies. Each side’s work is restored on top.</li><li><strong>Settle.</strong> Both sides are verified. Setup reruns only where a lockfile changed, and the chats on both lanes are told where their lane went.</li></ol><p>If any step fails, both sides are restored from the snapshot. If VS Code crashes partway, the journal is still there next time, and Canopy offers to undo the half-finished switch. On a real clone with a dev server running, the whole switch takes about a third of a second.</p><p>The same machinery covers the rest of a lane’s life. <strong>Park</strong> frees a lane’s slot and keeps its branch. <strong>Warm up</strong> puts a cold lane back in a slot, with your env files copied and your setup command run. <strong>New worktree</strong> can start a lane from a GitHub or Linear issue: Canopy names the branch, seeds the goal and notes from the issue, and opens a chat on it.</p><h3>What else is new</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILxcvy0msbgSPJmsgIT8CQ.png" /></figure><ul><li><strong>Setup</strong> in three steps: connect your agents, choose the roster, and tell Canopy how to prepare new worktrees for each repo.</li><li><strong>Review</strong> for every chat: who did what, each report, the files and checks behind it, the diff, undo per agent, and a pull request through your own gh login.</li><li><strong>Your own accounts.</strong> Canopy runs the CLIs on your machine, signed in your way. It never reads, stores, or forwards your credentials, and never calls a provider’s API itself.</li><li><strong>Native to VS Code.</strong> Chats in the sidebar or in tabs that come back after a reload, the full composer for whichever agent you are talking to, and colors from your own theme.</li></ul><p>Canopy is for you if you already pay for more than one coding agent, work across more than one repo, or have ever lost an afternoon to a branch you forgot to switch.<br>What I’m curious to know is how other devs approach testing features across multiple worktrees. My personal opinion is that setting up throwaway worktrees to be able to run local servers isn’t worth the effort, but I would like that notion challenged. If you are reading this and approach this problem a different way, let me know in the comments!</p><p>You can try out Canopy by installing it from the <a href="https://marketplace.visualstudio.com/items?itemName=SingularityInc.canopy">VS Code Marketplace</a>, or read the code on <a href="https://github.com/ashmitb95/canopy">GitHub</a>.</p><p>The original CLI still lives at <a href="https://github.com/ashmitb95/canopy-cli">ashmitb95/canopy-cli</a>.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3f78d13b27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google’s Open Knowledge Format: When Your AI Agent Needs a Library Card]]></title>
            <link>https://medium.com/@ashmitbbiswas/googles-open-knowledge-format-when-your-ai-agent-needs-a-library-card-ac70d550083c?source=rss-dedb2b307718------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac70d550083c</guid>
            <category><![CDATA[open-knowledge-format]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[front-matter]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Ashmit Biswas]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 03:02:46 GMT</pubDate>
            <atom:updated>2026-06-19T03:02:46.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctIpGoiNvCULZWxd0HqFUg.png" /></figure><p>I have a Claude Code plugin with 10+ skills. Each skill has references: conventions, component inventories, pattern libraries. At some point last week I realized half of those references were lying to me. Not maliciously. They just hadn’t been updated since March.</p><p>The problem with monolithic convention files: they drift. You write 300 lines of “here’s every component in the design system” and within two sprints, three components have been renamed and one got deleted entirely. Your AI agent reads the file, trusts it, and writes code against ghosts.</p><p>So I went looking for a better structure. And I found OKF.</p><h3>What Is OKF?</h3><p>Open Knowledge Format is a spec from Google Cloud Platform for representing knowledge as markdown files with YAML frontmatter. One concept per file. Minimal schema. Version-control friendly.</p><p>Here’s what a concept file looks like:</p><pre>---<br>type: Convention<br>title: No Abbreviated Variables<br>tags: [naming, frontend, backend]<br>timestamp: 2025-06-19T00:00:00Z<br>---</pre><pre>Every variable, parameter, and arrow function argument must use its full<br>domain noun. No single-char, two-char, or common abbreviations.</pre><pre>**Fails:** `p =&gt;`, `doc =&gt;`, `msg =&gt;`, `cc =&gt;`<br>**Use:** `paragraph =&gt;`, `document =&gt;`, `message =&gt;`, `contentControl =&gt;`</pre><p>That’s it. The only <em>required</em> field is type. Everything else (title, tags, description, timestamp) is recommended but optional. Producers can add custom fields. Consumers must tolerate missing ones.</p><p>The philosophy: readable by humans without tooling, parseable by agents without bespoke SDKs.</p><h3>The Structure</h3><p>OKF organizes knowledge into <strong>bundles</strong>: directories of markdown files with two reserved filenames:</p><ul><li>index.md is a directory listing for progressive disclosure (agents read this first, dive deeper only when relevant)</li><li>log.md is a chronological change history</li></ul><p>Everything else is a concept document. One idea, one file. Cross-link with standard markdown links.</p><pre>knowledge/conventions/<br>├── index.md                    # what&#39;s in here, one line per file<br>├── log.md                      # when things changed<br>├── naming-no-abbreviations.md<br>├── dry-no-duplicated-logic.md<br>├── styling-icon-sizing.md<br>├── hooks-barrel-imports.md<br>└── ...</pre><p>The key insight: index.md gives agents a table of contents without forcing them to read 22 files. They scan the index, match against the files they&#39;re about to touch, and only load what&#39;s relevant.</p><h3>Why I Got Excited</h3><p>My quality gate skill was reading a 300-line conventions file on every commit. Most of it was irrelevant. If I’m editing a Python API route, I don’t need to know about Tailwind icon sizing classes.</p><p>OKF gave me a filtering mechanism. Tag each rule with [frontend], [backend], or [both]. The gate reads the index, matches tags against changed file extensions, loads only what applies. Faster, more focused, less noise.</p><p>I built a 22-file bundle. Migrated every convention from the monolith into its own file. Wrote the index. Added cross-links. Felt productive.</p><h3>Why I Ripped It Out</h3><p>Here’s the thing about 22 files: you now have 22 files.</p><p>Each one needs frontmatter. Each one needs to stay in sync. The index needs updating when you add or remove a rule. The log.md needs entries. You&#39;ve traded one maintenance problem (a drifting monolith) for another (a drifting bundle with more surface area).</p><p>For my use case (a Claude Code plugin where the conventions are read by a single skill) the overhead wasn’t justified. The skill was already smart enough to scan a single file and decide what’s relevant. It didn’t need me to pre-filter with tags and indexes.</p><p>What I actually needed was simpler: bake the three rules that matter most directly into the skill, and point it at the repo’s existing convention file for everything else. Two sources, zero bundle maintenance.</p><h3>When OKF Is the Right Tool</h3><p>I pulled it out of my plugin. That doesn’t mean it’s bad. It means my problem wasn’t big enough for it.</p><p>OKF shines when:</p><p><strong>Multiple consumers read the same knowledge.</strong> If your conventions are consumed by a linter, a code review bot, an onboarding agent, AND a quality gate, each needing different subsets, the one-file-per-concept structure with tag-based filtering pays for itself. The alternative is every consumer parsing the same monolith and hoping their regex holds up.</p><p><strong>The knowledge changes at different rates.</strong> Some conventions are stable for years (naming rules). Others rotate monthly (which API version to target). When they’re in the same file, a git diff shows “conventions.md changed” with zero signal about what actually moved. Separate files give you granular history.</p><p><strong>Cross-linking carries semantic weight.</strong> When “no abbreviated variables” needs to reference “the naming exceptions list” which references “Python-specific overrides,” that’s a graph, not a document. OKF’s cross-linking makes the relationships navigable. A monolith makes them invisible.</p><p><strong>Progressive disclosure matters.</strong> If your knowledge base has 50+ entries and agents only need 3–5 per task, the index-then-filter-then-load pattern saves real tokens. At 22 entries, the savings are marginal. At 200, they’re significant.</p><h3>When It’s Overkill</h3><p><strong>Single consumer.</strong> One skill reading one file? Just use the file.</p><p><strong>Small rule sets.</strong> Under ~15 rules, a well-structured markdown document with clear headings is easier to maintain and just as parseable.</p><p><strong>Stable knowledge.</strong> If your conventions haven’t changed in 6 months, the drift problem that OKF solves doesn’t exist yet.</p><p><strong>No filtering needed.</strong> If every consumer needs every rule every time, the index and tags add ceremony without value.</p><h3>The Middle Ground</h3><p>What I landed on is a hybrid that takes OKF’s best idea (separation of concerns) without the full spec:</p><ol><li><strong>Bake universal rules into the consumer.</strong> The three conventions that apply everywhere (naming, DRY, file placement) live in the skill definition itself. No file to drift. No index to maintain. They just run.</li><li><strong>Point to the source of truth for everything else.</strong> The skill reads the repo’s own code-conventions/SKILL.md, a single file maintained by the team, in the repo where the code lives, reviewed in the same PRs as the code it governs.</li><li><strong>Reserve OKF for when scale demands it.</strong> If that conventions file grows past 50 rules, or a second consumer shows up that needs a filtered subset, that’s the signal to decompose into a bundle.</li></ol><h3>Keeping a Bundle Honest With CI</h3><p>OKF solves the structure problem. It doesn’t solve the staleness problem. You can have beautifully separated, tagged, cross-linked concept files that still reference functions that were renamed three weeks ago.</p><p>The fix is CI. A GitHub Action (or equivalent) that runs on every PR and validates the bundle against the actual codebase:</p><p><strong>1. Path assertions.</strong> If a concept file references a directory or file path, verify it exists:</p><pre># .github/workflows/knowledge-lint.yml<br>- name: Validate knowledge references<br>  run: |<br>    grep -rh &quot;packages/&quot; knowledge/conventions/*.md | while read -r line; do<br>      path=$(echo &quot;$line&quot; | grep -oP &#39;`[^`]+`&#39; | tr -d &#39;`&#39;)<br>      [ -e &quot;$path&quot; ] || echo &quot;::error::Dead path: $path&quot;<br>    done</pre><p><strong>2. Frontmatter schema checks.</strong> Enforce that every concept has the required type field and any team-mandated fields (like tags or timestamp):</p><pre>- name: Validate frontmatter<br>  run: |<br>    for f in knowledge/conventions/*.md; do<br>      yq -f extract &#39;.type&#39; &quot;$f&quot; &gt; /dev/null || echo &quot;::error::Missing type in $f&quot;<br>    done</pre><p><strong>3. Staleness alerts.</strong> Flag concept files whose timestamp is older than a threshold. Not a hard failure, just a warning that someone should re-verify the rule still applies:</p><pre>- name: Check for stale concepts<br>  run: |<br>    threshold=$(date -d &#39;90 days ago&#39; +%s)<br>    for f in knowledge/conventions/*.md; do<br>      ts=$(yq -f extract &#39;.timestamp&#39; &quot;$f&quot; 2&gt;/dev/null)<br>      [ -z &quot;$ts&quot; ] &amp;&amp; continue<br>      file_epoch=$(date -d &quot;$ts&quot; +%s)<br>      [ &quot;$file_epoch&quot; -lt &quot;$threshold&quot; ] &amp;&amp; echo &quot;::warning::Stale: $f (last updated $ts)&quot;<br>    done</pre><p><strong>4. Index sync.</strong> Verify that every concept file in the directory has a corresponding entry in index.md, and vice versa. Orphaned files mean the index drifted. Orphaned index entries mean someone deleted a file but didn&#39;t update the listing.</p><p>This is the piece that makes OKF viable long-term. Without it, you’re trusting humans to remember to update markdown files, which is exactly the problem you were trying to solve in the first place.</p><p>The <a href="https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/HEAD/okf/SPEC.md">spec</a> is short. You can read it in 10 minutes.</p><p>To create a minimal bundle:</p><pre>mkdir -p knowledge/conventions</pre><p>Write your first concept:</p><pre>---<br>type: Convention<br>title: Use Size Utilities for Icons<br>tags: [frontend, styling]<br>---</pre><pre>Use `size-N` (e.g., `size-4`) instead of `h-N w-N` for icon dimensions.<br>Single utility, same result, consistent grep target.</pre><p>Write your index:</p><pre>---<br>type: Index<br>---</pre><pre># Conventions</pre><pre>- [Icon Sizing](./styling-icon-sizing.md) – size-N over h-N w-N<br>- [Barrel Imports](./hooks-barrel-imports.md) – import from barrel, not direct path<br>- [No Abbreviations](./naming-no-abbreviations.md) – full domain nouns only</pre><p>The beauty: it’s just markdown. No build step. No tooling. cat and grep are your SDK.</p><h3>The Takeaway</h3><p>OKF isn’t a framework. It’s a filing system. The spec exists to answer one question: <em>how should I organize knowledge so that both humans and agents can find what they need without reading everything?</em></p><p>If you have a lot of knowledge, many consumers, and different access patterns, use it. If you have a dozen rules and one skill, don’t. The format you can maintain is always better than the format you should maintain.</p><p>I spent a night building a 22-file bundle and the following day tearing it down. Both attempts were useful. The first taught me what OKF can do. The second taught me that the right abstraction is the smallest one that solves the problem you actually have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac70d550083c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Spent a Weekend Making Techno With Code. Here’s What I Learned.]]></title>
            <link>https://medium.com/@ashmitbbiswas/i-spent-a-weekend-making-techno-with-code-heres-what-i-learned-c8470e7a68e5?source=rss-dedb2b307718------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8470e7a68e5</guid>
            <category><![CDATA[music]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[strudel]]></category>
            <category><![CDATA[techno]]></category>
            <dc:creator><![CDATA[Ashmit Biswas]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 05:07:20 GMT</pubDate>
            <atom:updated>2026-06-10T06:31:55.368Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An experiment with Strudel — by someone who cannot play an instrument.</em></p><p>Up front, so we’re clear: I’m not going to pretend I know what makes music <em>good</em>. I don’t. I can’t play an instrument — my musical career peaked while trying to match Chester Bennington’s vocals to Numb in the sixth grade and went downhill from there, literally the moment my mom heard my tone-deaf screaming. This isn’t a guide from someone who knows what they’re doing. It’s a weekend experiment with a tool called Strudel, and I’m sharing what I stumbled into — mostly so the next curious person can skip the parts where I was confused.</p><p>With that out of the way: you can build a whole evolving track by writing code, layer by layer, and it’s a stupid amount of fun.</p><h3>What Is Strudel?</h3><p>Strudel is a live-coding music environment that runs in your browser — a JavaScript port of TidalCycles, the pattern language from the algorave scene, with zero setup. Go to <a href="https://strudel.cc/">strudel.cc</a>, type, hit play. Everything below runs there as-is.</p><pre>setcps(0.5)<br>s(&quot;bd*4&quot;)</pre><p>A kick, four times a bar. bd is a bass-drum sample; *4 repeats it across the cycle. One note on tempo: cps is <em>cycles per second</em>. With four beats to a cycle, 0.5 cps is 120 BPM. That&#39;s the only math in this whole post.</p><p>Now let’s actually build something — one layer at a time, because that’s how a track comes together, and it’s also the easiest way to understand what each piece is <em>doing</em>.</p><h3>Layer 1 — Drums (this is most of your groove)</h3><p>The thing that surprised me first: the groove lives almost entirely in the drums. Get these right and a track feels good before you’ve added a single melodic note.</p><p>Start with the kick and give it real character with a drum machine:</p><pre>s(&quot;bd*4&quot;).bank(&quot;RolandTR909&quot;)</pre><p>.bank(&quot;RolandTR909&quot;) swaps the generic kick for the actual 909 — the drum machine techno is basically built on. Now add hats and a clap:</p><pre>stack(<br>  s(&quot;bd*4&quot;).bank(&quot;RolandTR909&quot;),<br>  s(&quot;hh*8&quot;).bank(&quot;RolandTR909&quot;).gain(0.5),<br>  s(&quot;~ cp ~ cp&quot;).bank(&quot;RolandTR909&quot;)<br>)</pre><p>Two things worth talking through. The hats are hh*8 — eighth notes, driving the track forward. The clap is &quot;~ cp ~ cp&quot;, where ~ means <em>silence</em> — so it lands on beats 2 and 4, the backbeat. That backbeat is doing a lot of psychological work; it&#39;s the thing your head nods to.</p><p>A few things to try right here, because small drum changes change <em>everything</em>:</p><pre>s(&quot;~ hh ~ hh&quot;)        // offbeat hats — instant house feel<br>s(&quot;hh*16&quot;)            // double-time hats — more urgent, more energy<br>s(&quot;hh:0 hh:1 hh:2&quot;)   // &#39;:n&#39; picks different hat samples for variation</pre><p>And the trick I liked most — placing hits by position instead of drawing them out:</p><pre>s(&quot;bd&quot;).beat(&quot;0,7,10&quot;, 16)     // kick on steps 0, 7, 10 of 16<br>s(&quot;sd&quot;).beat(&quot;4,12&quot;, 16)       // snare on the backbeat</pre><p>beat(&quot;positions&quot;, steps) says &quot;out of 16 sixteenth-notes, hit these.&quot; It&#39;s a cleaner way to think about rhythm than counting tildes. You can even nudge a layer toward variation:</p><pre>s(&quot;hh*8&quot;).beat(&quot;0,2,4,6&quot;, 8).sometimesBy(0.3, x =&gt; x.speed(2))</pre><p>sometimesBy(0.3, ...) does something 30% of the time — here, occasionally double-speeding a hat into a little roll. That bit of randomness is what keeps a loop from feeling stamped out by a machine. (More on that obsession later.)</p><h3>Layer 2 — Bass (where it starts to feel like techno)</h3><p>Now the low end. A plain sawtooth works:</p><pre>note(&quot;c2 eb2 g2 c2&quot;).s(&quot;sawtooth&quot;).lpf(600)</pre><p>But the squelchy, rubber-band acid bass — the sound a thousand tracks chase — has a specific recipe, and it’s worth understanding <em>why</em> it works:</p><pre>note(&quot;c2 c2 c3 c2 eb2 c2 g2 c2&quot;).s(&quot;sawtooth&quot;)<br>  .lpf(200).lpenv(2).lpq(12)</pre><ul><li>lpf(200) — a <em>low</em> cutoff, so most of the brightness is filtered out.</li><li>lpenv(2) — a filter <em>envelope</em>: every note briefly opens the filter and shuts it. That movement is the &quot;wah.&quot;</li><li>lpq(12) — high resonance, which is the squelch itself (the Roland TB-303 sound).</li></ul><p>The bit I had backwards for an embarrassing while: the brightness shouldn’t come from a <em>high</em> static filter — it comes from a <em>low</em> one that the envelope keeps opening and closing. Movement, not volume. Once that clicked, everything sounded more like the records I was trying to copy.</p><h3>Layer 3 — Melody, and one oscillator becoming ten</h3><p>A lead is just notes higher up. But here’s where I learned that <em>how</em> you shape a sound matters more than <em>which</em> notes you play.</p><p>Same melody, four completely different instruments — just by changing the oscillator:</p><pre>note(&quot;c4 eb4 g4 c5&quot;).s(&quot;sawtooth&quot;)   // buzzy, bright<br>note(&quot;c4 eb4 g4 c5&quot;).s(&quot;square&quot;)     // hollow, retro<br>note(&quot;c4 eb4 g4 c5&quot;).s(&quot;triangle&quot;)   // soft, flutey<br>note(&quot;c4 eb4 g4 c5&quot;).s(&quot;supersaw&quot;)   // huge, detuned, trance-y</pre><p>Then the envelope — attack, decay, sustain, release — decides whether a note <em>plucks</em>, <em>stabs</em>, or <em>swells</em>:</p><pre>// a sharp pluck<br>note(&quot;c4 eb4 g4 c5&quot;).s(&quot;sawtooth&quot;).attack(0.01).decay(0.2).sustain(0)</pre><pre>// a slow, washy pad<br>note(&quot;c4 eb4 g4 c5&quot;).s(&quot;triangle&quot;).attack(0.4).sustain(0.8).release(0.6)</pre><p>attack is how fast a note fades <em>in</em>, release how slowly it fades <em>out</em>. Fast attack + no sustain = a stab. Slow attack + long release = a pad. Same notes, totally different feel. This was the moment Strudel stopped feeling like a drum machine and started feeling like an instrument.</p><h3>Layer 4 — Space and grit (effects)</h3><p>Dry sounds feel like they’re happening inside your laptop. Effects put them in a room:</p><pre>note(&quot;c4 eb4 g4 c5&quot;).s(&quot;sawtooth&quot;)<br>  .room(0.4)        // reverb — depth, &quot;size&quot;<br>  .delay(0.5)       // echoes — rhythmic space<br>  .distort(1.5)     // grit, aggression<br>  .pan(sine)        // drifts left↔right over time</pre><p>room is reverb (how big the space feels), delay is echo (great for filling gaps in a sparse melody), distort adds dirt. And pan(sine) is a small thing that does a lot — it slowly moves the sound across the stereo field, so it feels <em>alive</em> instead of stuck dead-center. Hold that thought.</p><h3>Of course it sounded like a robot. The surprising part was the fix.</h3><p>So I had all four layers — and it was, technically, music. It was also lifeless. <em>Generated.</em> Like a machine reciting what techno is supposed to be.</p><p>That wasn’t a shock. If typing stack(...) reliably produced good music, everyone would be doing this and the charts would look very different. The robotic sound is the <strong>default</strong> — it&#39;s the price of admission, not a plot twist.</p><p>What I didn’t see coming was what pulled it out of the uncanny valley. I’d assumed it would take the thing I plainly don’t have — musical taste, better chords, theory I never learned. It didn’t. The two things that moved the needle most weren’t musical at all. They were almost mechanical — which means you don’t need to be a musician to get past the robot. You need two structural tricks.</p><p><strong>One: a hardcoded loop gets boring fast.</strong> A fixed string of notes, identical every bar, turns into wallpaper after eight bars. The fix felt backwards — <em>make it more random, not less:</em></p><pre>n(irand(8).segment(16)).scale(&quot;c2:minor&quot;)<br>  .s(&quot;sawtooth&quot;).lpf(200).lpenv(2).lpq(12)</pre><p>irand(8) picks random numbers; .scale(&quot;c2:minor&quot;) snaps every one to the C-minor scale. Different notes every bar, but always in key. The scale is the leash; the randomness is the dog. I expected chaos. To my ear it was the opposite — alive.</p><p><strong>Two: nothing should ever sit still.</strong> Watching people who actually do this, I noticed they’re <em>never</em> leaving a knob alone. So instead of static numbers, feed parameters a moving signal:</p><pre>s(&quot;hh*8&quot;).decay(tri.range(0.02, 0.12))                       // hats that breathe<br>note(&quot;c2&quot;).s(&quot;sawtooth&quot;).lpf(sine.range(200, 1200).slow(8))  // a filter that drifts<br>s(&quot;pulse&quot;).fm(time).fmh(time)                                // a riser that climbs forever</pre><p>tri, sine, perlin, time are continuous signals you can plug into almost anything. The day I swapped static numbers for movement, the whole thing came alive — to me, at least. Whatever &quot;soul&quot; I felt was missing, that was it: not a missing layer, the absence of motion.</p><p>And notice what neither fix required: a single thing I learned in a music class I never took. <em>That’s</em> the part that actually surprised me.</p><h3>Putting it together (and making it evolve)</h3><p>Stack the layers and you have a loop. But a track isn’t a loop — it’s layers coming <em>in and out</em> over time. A few ways to get there:</p><pre>// &#39;&lt;...&gt;&#39; steps through options each cycle — the bass changes every bar<br>note(&quot;&lt;c2 eb2 g2 f2&gt;&quot;).s(&quot;sawtooth&quot;).lpf(300)</pre><pre>// &#39;every&#39; does something on a schedule — a fill every 4th bar<br>s(&quot;bd*4&quot;).every(4, x =&gt; x.fast(2))</pre><pre>// &#39;mask&#39; gates a layer on/off — hats only in the second half<br>s(&quot;hh*16&quot;).mask(&quot;0 1&quot;)</pre><p>That’s the whole arrangement game: decide what’s playing, when, and let things enter, build, drop, and strip back. (This is the rabbit hole I’m still happily lost in.)</p><h3>The whole thing, in one block</h3><p>Stack everything we just built and you’ve got a complete, living track. Paste this into <a href="https://strudel.cc/">strudel.cc</a> and hit play:</p><pre>setcps(0.55) // ~132 BPM</pre><pre>stack(<br>  // drums<br>  s(&quot;bd*4&quot;).bank(&quot;RolandTR909&quot;),<br>  s(&quot;hh*8&quot;).bank(&quot;RolandTR909&quot;).gain(0.5)<br>    .decay(tri.range(0.02, 0.12)),              // hats that breathe<br>  s(&quot;~ cp ~ cp&quot;).bank(&quot;RolandTR909&quot;).gain(0.7),</pre><pre>  // acid bass — generative, low filter + envelope + resonance, drifting cutoff<br>  n(irand(8).segment(16)).scale(&quot;c2:minor&quot;)<br>    .s(&quot;sawtooth&quot;)<br>    .lpf(sine.range(180, 900).slow(8))          // the filter moves on its own<br>    .lpenv(2).lpq(12)<br>    .gain(0.8),</pre><pre>  // lead — a square &#39;stab&#39; in the same key, with echo and space<br>  n(irand(8).segment(8)).scale(&quot;c4:minor&quot;)<br>    .s(&quot;square&quot;)<br>    .attack(0.01).decay(0.18).sustain(0)<br>    .delay(0.4).room(0.3)<br>    .degradeBy(0.3)                             // leave gaps<br>    .gain(0.4)<br>)</pre><p>Nothing in there is hardcoded, and nothing sits still — the notes re-roll every bar (always in key), the hats breathe, the filter drifts on its own. That’s the entire lesson in one block. From here it’s yours: change the scale, swap the oscillator, push the tempo, mute a layer. Break it. That’s the fun part.</p><h3>Where I learned all this</h3><p>Honestly? By studying the live-coding sets of <a href="https://www.youtube.com/@Switch-Angel"><strong>Switch Angel</strong></a> — frame by frame, reading the actual code off the screen as she built tracks. I’m a beginner who learned by copying someone who very much isn’t. If you want into Strudel, skip the docs and watch someone <em>perform</em> with it. Go watch her; she’s brilliant.</p><h3>The thing it turned into</h3><p>I wired all of this into a small project I call <strong>musaic</strong> — a generative DJ in the browser. Hit “new track” and it rolls a fresh tempo, key, bassline, and sound palette, holds that as the track’s identity, then arranges it on the fly. No two tracks the same. Open source and very unfinished: <a href="https://github.com/ashmitb95/musaic">github.com/ashmitb95/musaic</a>.</p><h3>Go make some noise</h3><p>The barrier is basically gone. <a href="https://strudel.cc/">strudel.cc</a> — no install, no account, no instrument. Paste s(&quot;bd*4&quot;) and start stacking.</p><p>Two things I’d tell myself on day one — not as music advice (I have none), just what worked for me: <strong>don’t hardcode anything, and don’t let a number sit still.</strong> Everything past that is taste, and I’m still working on mine.</p><p>Cheers!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmWPQfiHQJBicgbmaI0vHA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8470e7a68e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Worktrees Are Great. Managing Them Across 3 Repos Is Not.]]></title>
            <link>https://medium.com/@ashmitbbiswas/git-worktrees-are-great-managing-them-across-3-repos-is-not-12262be5ddb0?source=rss-dedb2b307718------2</link>
            <guid isPermaLink="false">https://medium.com/p/12262be5ddb0</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-worktree]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Ashmit Biswas]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 04:31:03 GMT</pubDate>
            <atom:updated>2026-11-04T03:43:35.329Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Update: This post describes the original Canopy CLI. I’ve since rebuilt Canopy from scratch as a VS Code extension, with feature lanes, numbered worktree slots, and multiple coding agents working in one chat. The follow-up explains what I got wrong the first time and how it works now: </em><a href="https://medium.com/@ashmitbbiswas/worktrees-across-repos-take-two-this-time-its-multi-agent-too-9a3f78d13b27"><em>Worktrees across repos, take two</em></a><em>.</em></p><p><em>The CLI has moved to </em><a href="https://github.com/ashmitb95/canopy-cli"><em>ashmitb95/canopy-cli</em></a><em>, and the commands below work with it. If you’re looking for a way to actually manage worktrees across repos day to day and use VS Code, I think you’ll find the new version far more usable. Do check out the write-up and the </em><a href="https://github.com/ashmitb95/canopy"><em>new repo</em></a><em>. I’m actually happy with this one!</em></p><p>I’ve always gravitated toward monorepo-style structures. Not because I have strong opinions about repo topology, but because working across the stack is just easier when everything’s in one place. Shared context, one branch, one checkout, one IDE window. You build a feature end-to-end without thinking about coordination.</p><p>But monorepos come with their own baggage, and the product I work on is split across three repositories — an API, a frontend, and a shared infra repo. Every feature touches at least two of them. That’s fine architecturally. It’s terrible for version control.</p><p>And I should confess something: I am a plebeian who uses GUI tools to manage git. Fork, specifically.</p><p>I know, I know. Real engineers use git rebase -i in a 80x24 terminal that tells them to fuck off in ASCII characters when they want to revert a singular console.log line in a diff of 400+ line changes. <br>Fork gives me the superpowers to go get dirty with code and come back and clean it up with nothing but a cigarette and a dream, or purge it if it&#39;s beyond repair and FUBAR.</p><p>The problem is, Fork shows you one repo at a time. And when you&#39;re using worktrees, each worktree is its own directory — so Fork treats each one as a separate repo. Three features across two repos means six Fork tabs, six branch trees, six sets of uncommitted changes to mentally track. You lose the &quot;at a glance&quot; that made Fork appealing in the first place.</p><p>Git worktrees helped — separate directories for each feature, each on its own branch, coexisting peacefully. I can have ENG-412-add-oauth2-login open in one window and fix-nav-bug in another. No stashing. No &quot;which repo was I on again?&quot;</p><p>Except the UX for managing worktrees across multiple repos doesn’t exist. Git doesn’t know that my api and ui repos are related. It certainly doesn&#39;t know that when I create a worktree in one, I probably want one in the other too. So the ritual goes:</p><pre>cd ~/product/api<br>git worktree add ../.worktrees/api-eng412 -b ENG-412-add-oauth2-login<br>cd ~/product/ui<br>git worktree add ../.worktrees/ui-eng412 -b ENG-412-add-oauth2-login<br># now open both in Fork somehow<br># remember where they are<br># weeks later, remember to clean up both</pre><p>Multiply this by five active features and three repos. Now add the fact that I never clean up stale worktrees because the friction is too high. My .worktrees directory looked like a git graveyard.</p><p>So I came up with Canopy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_z4l274pn50npCiaQ6tGw.png" /></figure><h3>What It Actually Does</h3><p>Canopy is a CLI tool that coordinates Git worktrees across multiple repositories. You define your workspace once in a canopy.toml:</p><pre>[workspace]<br>name = &quot;my-product&quot;<br>[[repos]]<br>name = &quot;api&quot;<br>path = &quot;./api&quot;<br>role = &quot;backend&quot;<br>lang = &quot;python&quot;<br>[[repos]]<br>name = &quot;ui&quot;<br>path = &quot;./ui&quot;<br>role = &quot;frontend&quot;<br>lang = &quot;typescript&quot;</pre><p>Then everything operates at the workspace level:</p><pre>canopy worktree ENG-412-add-oauth2-login ENG-412</pre><p>That one command creates a worktree in every repo, on the same branch, in a structured directory. It also talks to Linear via MCP (more on that later), fetches the issue title and URL, and stores the link in metadata. Your workspace now looks like this:</p><pre>my-product/<br>├── api/                              ← main, untouched<br>├── ui/                               ← main, untouched<br>└── .canopy/worktrees/<br>    └── ENG-412-add-oauth2-login/<br>        ├── api/                      ← worktree, ENG-412 branch<br>        └── ui/                       ← worktree, ENG-412 branch</pre><p>Main stays clean. Your feature lives in its own directory. No stashing, no switching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FRBDlal90KrZwlBRZYUYg.png" /></figure><h3>The Part That Makes Daily Life Better</h3><p>Creating worktrees is the flashy bit, but the quality-of-life stuff is what I actually reach for every day.</p><p><strong>Alias resolution.</strong> I never type ENG-412-add-oauth2-login after the initial creation. Every command accepts ENG-412 and resolves it automatically. It matches on prefix, or on the Linear issue ID if one is stored. When it resolves, the CLI shows you what happened:</p><pre>ENG-412 → ENG-412-add-oauth2-login</pre><p>If the prefix is ambiguous (two features start with ENG-4), it tells you. No silent wrong matches.</p><p><strong>IDE integration.</strong> canopy code ENG-412 generates a .code-workspace file with both repo directories and opens VS Code. canopy cursor ENG-412 does the same for Cursor. I use this dozens of times a week.</p><p><strong>The worktree dashboard.</strong> canopy worktree with no arguments shows you everything — every feature, every repo, dirty file counts, ahead/behind status, which branches are checked out where. It&#39;s the &quot;what&#39;s the state of things&quot; command. The one I run first thing in the morning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Jo08DE_CDameTbpX4bS0Q.png" /></figure><p><strong>Preflight.</strong> This one came from a frustration with how I was committing. I used to have a canopy stage command that would git add -A &amp;&amp; git commit across all repos. Convenient, sure. Also dangerous. It bypassed pre-commit hooks entirely, and it encouraged lazy commit messages because the tool made committing <em>too</em> easy.</p><p>So I killed it. Replaced it with canopy preflight:</p><pre>canopy preflight</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTgKCH1O70cp3xhGmbdiIA.png" /></figure><p>This stages your changes and runs pre-commit hooks across all repos in your feature. If hooks pass, it tells you “Ready to commit.” If they fail, it shows you what failed. Either way, it does <em>not</em> commit. That’s your job. You write the message, you decide when. Canopy gets you to the point where a commit would be clean, then stops.</p><p>I also killed canopy commit entirely. If you want to commit, use git. Canopy handles everything up to that point.</p><p><strong>Cleanup.</strong> canopy done ENG-412 removes worktrees across all repos, deletes the branches, and archives the feature metadata. One command. This is the reason I no longer have 30 stale worktrees lying around.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8iVPvwp6swV8Bt_evkd9Q.png" /></figure><h3>The MCP Server</h3><p>This is the part I’m most excited about, and the part that probably sounds the most over-engineered until you use it.</p><p>Every Canopy operation is also exposed as an MCP tool. 27 of them, over stdio transport. When I’m working with Claude Code, the agent can call feature_switch, worktree_info, preflight, review_comments — the same operations I use from the CLI.</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;canopy&quot;: {<br>      &quot;command&quot;: &quot;canopy-mcp&quot;,<br>      &quot;env&quot;: { &quot;CANOPY_ROOT&quot;: &quot;/path/to/workspace&quot; }<br>    }<br>  }<br>}</pre><p>Why does this matter? Because without it, an AI agent working on your multi-repo project has to run git status in each repo, parse the text output, and hope it correctly understood which branch is checked out where. With Canopy, it calls one tool and gets structured JSON:</p><pre>{<br>  &quot;repos&quot;: {<br>    &quot;api&quot;: {<br>      &quot;branch&quot;: &quot;ENG-412-add-oauth2-login&quot;,<br>      &quot;dirty_count&quot;: 2,<br>      &quot;ahead&quot;: 3,<br>      &quot;behind&quot;: 0<br>    },<br>    &quot;ui&quot;: {<br>      &quot;branch&quot;: &quot;ENG-412-add-oauth2-login&quot;,<br>      &quot;dirty_count&quot;: 0,<br>      &quot;ahead&quot;: 1,<br>      &quot;behind&quot;: 0<br>    }<br>  }<br>}</pre><p>The agent knows exactly what’s going on. No parsing. No guessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsLq2sJijTIyErJYlvHegA.png" /></figure><h3>Canopy Is Also an MCP Client</h3><p>This is the design decision I’m most opinionated about. Canopy never calls external APIs directly. Not Linear’s API. Not GitHub’s API. Not anything.</p><p>Instead, it spawns external MCP servers as subprocesses and calls their tools via the standard MCP protocol. When you run canopy worktree ENG-412-add-oauth2-login ENG-412, Canopy spawns the Linear MCP server, calls getIssue, gets the title and URL, and stores them. When you run canopy review ENG-412, it spawns the GitHub MCP server, finds the PRs, and fetches unresolved review comments.</p><pre>{<br>  &quot;linear&quot;: {<br>    &quot;command&quot;: &quot;npx&quot;,<br>    &quot;args&quot;: [&quot;-y&quot;, &quot;@modelcontextprotocol/server-linear&quot;],<br>    &quot;env&quot;: { &quot;LINEAR_API_KEY&quot;: &quot;lin_api_...&quot; }<br>  }<br>}</pre><p>Zero external API dependencies in the codebase. Any MCP server can be plugged in via config. The integrations work through the same protocol AI agents use to talk to Canopy itself. MCP all the way down.</p><p>Is this over-engineered for a CLI tool? Maybe. But I never have to think about API authentication flows, SDK version mismatches, or rate limiting for services I’m not even the primary consumer of. The MCP server maintainers handle that. I just call tools.</p><h3>What This Is Not</h3><p>Canopy is not a monorepo tool. If you’ve already consolidated into a monorepo, you don’t need this. It’s for teams that have deliberately separate repos and want to coordinate work across them.</p><p>It’s not a git replacement. It uses real git branches and real git worktrees. No virtual branches, no proprietary abstractions. git log still works. git status still works. Everything Canopy creates is standard git that any tool can understand.</p><p>It’s not trying to be GitButler or any of the visual branch management tools. It’s a CLI for people who live in the terminal and want their multi-repo workflow to feel as smooth as working in a single repo.</p><h3>The Numbers</h3><p>187 tests, all running against real temporary Git repositories. No mocks. When I say “worktree creation works,” I mean a test actually runs git worktree add in a temp directory and verifies the result. The full suite runs in about 2 seconds.</p><p>27 MCP tools. Python 3.10+. MIT licensed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bl8ZM_7_cNXvKE0-SJZA0g.png" /></figure><h3>The Honest Assessment</h3><p>I built this for myself. My setup — 2–3 repos, Linear for issue tracking, Claude Code as my daily driver — is the sweet spot. If you work in a single repo, you don’t need this; a <a href="https://github.com/obra/superpowers/blob/main/skills/using-git-worktrees/SKILL.md">Claude Code skill for worktrees</a> handles that fine. If you don’t use worktrees at all, the problem Canopy solves doesn’t exist for you.</p><p>But if you work across multiple repos daily, and you’ve ever found yourself running the same git commands in three directories, and you’ve ever had a stale worktree that you forgot to clean up, and you’ve ever wished git worktree understood that your repos are part of the same product — this might save you the same friction it saves me.</p><pre>git clone https://github.com/ashmitb95/canopy.git<br>cd canopy &amp;&amp; pip install -e .<br>cd ~/your-workspace/<br>canopy init<br>canopy worktree my-first-feature<br>canopy code my-first-feature</pre><p><a href="https://github.com/ashmitb95/canopy">github.com/ashmitb95/canopy</a></p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12262be5ddb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Pinescript to Production: How to Build a Trading System That Actually Works]]></title>
            <link>https://medium.com/@ashmitbbiswas/from-pinescript-to-production-how-to-build-a-trading-system-that-actually-works-cb10a50da4e8?source=rss-dedb2b307718------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb10a50da4e8</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[trading-strategy]]></category>
            <category><![CDATA[live-trading]]></category>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[python-trading]]></category>
            <dc:creator><![CDATA[Ashmit Biswas]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 20:45:24 GMT</pubDate>
            <atom:updated>2026-03-15T20:45:24.906Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A developer’s guide to translating strategies into code, backtesting without fooling yourself, and running the same logic live without surprises.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4TpA0386tikf35QFZIQWw.png" /></figure><p>You’ve got a strategy that looks good on paper. Maybe it came from a parameter sweep, maybe you spotted a pattern and validated it manually. Either way, there’s this moment of optimism: “I just need to code this up and let it run.”</p><p>What follows is usually six months of discovering everything you didn’t think about. The backtest that looked clean produces garbage live. The simulation “works” but disagrees with the backtest. Bugs hide for weeks because your live code and test code diverged three refactors ago. I’ve been through every one of these, and this post is about how to avoid them, or at least recognize them faster.</p><h3>Start With Architecture, Not Strategy Code</h3><p>The single biggest mistake I made early on was writing strategy logic directly inside my execution loop. Buy signal? Call the broker. Stop loss hit? Call the broker again. It worked, technically. But it was impossible to test, impossible to extend, and every change risked breaking something in production.</p><p>The fix is embarrassingly simple, and it’s the same pattern software engineers have used for decades: <strong>separate what changes from what doesn’t.</strong></p><p>Your strategy logic (how you detect entries, when you exit, how you size positions) changes constantly. You’re always tuning, always experimenting. Your execution infrastructure (how orders get placed, where price data comes from, how candles get aggregated) should be stable.</p><p>The way to achieve this is <strong>adapters</strong>. Three abstractions do most of the work:</p><h3>The Execution Adapter</h3><p>Define an interface for placing orders. Then implement it twice:</p><ul><li><strong>Paper executor</strong>: Fills orders instantly at current price plus some slippage model. Used for backtesting, simulation, and paper trading. No broker connection needed — except for maybe tracking realtime price movement if you would like to do so.</li><li><strong>Live executor</strong>: Routes orders to your actual broker API.</li></ul><p>Both implement the same methods: place_order(), get_order_status(), cancel_order(). Your strategy code calls these methods and genuinely does not know, or care, whether it&#39;s placing a real order or a simulated one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElraZsjyAgE4fUH1flJOmQ.png" /></figure><p>This isn’t clean architecture for its own sake. It’s the difference between “I can test a new exit rule in 30 seconds” and “I need to set up a paper trading session and wait for market hours.” The feedback loop determines how fast you iterate, and how fast you iterate determines whether you find edge before the market takes it away.</p><h3>The Data Source Adapter</h3><p>Same idea, applied to price data:</p><ul><li><strong>Database source</strong>: Reads historical prices from your data store. Used by backtests and simulations.</li><li><strong>Live source</strong>: Queries your broker’s API or WebSocket for real-time prices.</li></ul><p>Both implement get_price(). Your strategy asks &quot;what&#39;s the current price of this instrument?&quot; and gets an answer, regardless of whether that answer came from a database row timestamped six months ago or a live quote that arrived 50 milliseconds ago.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQ2Z8cWHwIDG0kE37ZP38g.png" /></figure><p>When you swap between modes (backtest, simulation, live), you’re swapping <em>adapters</em>, not rewriting strategy code. The strategy stays identical. That’s the whole game.</p><h3>The Broker Adapter</h3><p>This one is specific to multi-broker setups, and it matters more than you’d expect.</p><p>Different brokers have different APIs, different order types, different symbol formats, different rate limits. If your strategy code knows about any of this, you’re locked into one broker forever. And you <em>will</em> need to switch. Your primary broker will have downtime on a critical day. Their API will change. Their fees will go up. A competitor will offer better fills or lower latency.</p><p>The broker adapter sits between your execution layer and the actual broker SDK. It handles:</p><ul><li><strong>Symbol translation</strong>: Your internal representation (“NIFTY 25000 CE weekly”) maps to whatever format each broker expects. One broker might want NIFTY2503125000CE, another wants NIFTY-25000-CE-27MAR. The adapter handles the conversion.</li><li><strong>Order type mapping</strong>: Market orders, limit orders, stop-loss orders. The semantics are the same across brokers, but the API calls differ.</li><li><strong>Connection management</strong>: Authentication, session handling, reconnection logic. Each broker has its own flow. Your strategy doesn’t need to know about any of it.</li></ul><p>I currently support two brokers, and there was a period where I had to switch primary broker mid-week because of API instability. That switch was a config change, not a code change. Without the adapter layer, it would have been a frantic rewrite under pressure.</p><h3>The Three Engines You Actually Need</h3><p>Most people start with a backtest script. Then they write a live trading bot. Then they realize the two don’t agree, and they build some kind of simulation mode. By the end, they’ve got three separate implementations of the same strategy, each with its own subtle bugs.</p><p>Here’s what actually works: <strong>build three engines, but share the strategy core.</strong></p><h3>1. The Backtest Engine</h3><p>This is your workhorse for research. It processes historical data as fast as possible, with no waiting, no real-time constraints. It loops through candles, runs your strategy logic, records trades, and spits out metrics.</p><p>The backtest engine is optimized for throughput. You need to run thousands of parameter combinations across years of data. Anything that adds latency per candle (network calls, database writes, UI updates) gets stripped out. The backtest engine should be lean, almost ruthless in what it doesn’t do.</p><p>But critically, the <em>strategy logic</em> it executes is the same code your live engine runs. Not a reimplementation. Not a “simplified version for testing.” The actual strategy module, imported and called identically.</p><h3>2. The Simulation Engine</h3><p>This is the one most people skip, and it’s the one that saves you the most pain.</p><p>A simulation engine replays historical data through your <strong>live trading engine</strong>, the same engine that will run in production. It feeds candles one at a time, respects timing, and exercises the full lifecycle: initialization, candle processing, signal generation, order placement (via the paper executor), position monitoring, and daily resets.</p><p>Why bother when you already have a backtest? Because your backtest doesn’t test your infrastructure. It tests your strategy logic in isolation. The simulation tests <em>everything</em>: your candle aggregation, your state management, your initialization sequence, your recovery logic. Bugs that hide in a clean backtest loop show up immediately when you feed the same data through the production engine.</p><p>The simulation engine should be a thin wrapper. Its only job is:</p><ol><li>Load historical data from the database</li><li>Feed it candle-by-candle to the live engine</li><li>Optionally control speed (real-time, 2x, instant)</li></ol><p>That’s it. If your simulation engine has strategy logic in it, you’ve already lost. You’re maintaining two implementations again.</p><h4>Simulation Frees You From Market Hours</h4><p>There’s a practical benefit to the simulation engine that’s easy to overlook: <strong>you can develop and debug your live engine at midnight on a Sunday.</strong></p><p>Your live engine normally only runs during market hours. Without a simulation mode, testing a change to your live engine means waiting for the next trading session. That’s a brutal feedback loop when you’re debugging a candle aggregation bug or a state management issue.</p><p>The simulation engine solves this. Feed it last Tuesday’s data, and your live engine processes it exactly as if the market were open. Every initialization step fires. Every candle flows through the same pipeline. Every daily reset triggers at the right boundary. You get full end-to-end coverage of your production code path without needing the market to cooperate.</p><p>I’ve caught more bugs running weekend simulations than I have during live sessions. The live session is stressful; you’re monitoring P&amp;L, watching for fills, managing risk. The simulation is calm. You can pause it, inspect state, step through candle by candle. It turns your live engine into something testable, and testable code is code you can actually trust.</p><h3>3. The Live Engine</h3><p>This is the full system: broker connections, WebSocket feeds, real-time candle aggregation, order management, state persistence, crash recovery. It’s the most complex component, and that’s exactly why you want to test it with the simulation engine before real money touches it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lK5_q2aFg_ckHth6Op3Ew.png" /></figure><p>The key insight is the dependency direction. The live engine doesn’t know about the backtest engine. The simulation engine depends on the live engine (it’s a wrapper around it). The backtest engine shares strategy modules with the live engine but has its own execution loop optimized for speed. Strategy code flows into all three. Infrastructure code lives in only one.</p><h3>The Central Config: Your System’s Brain</h3><p>Configuration deserves its own section because it’s the single most common source of divergence between engines. I’ve had backtests and live runs disagree on results, spent hours hunting for a code bug, and eventually discovered the problem was a risk-reward ratio set to 2.5 in one config and 3.0 in another.</p><h3>One Source of Truth</h3><p>Your config should have layers:</p><ul><li><strong>Base config</strong>: Parameters shared across all modes. Strategy thresholds, risk ratios, indicator settings, position sizing rules, feature flags. This is the single source of truth. When you change a parameter here, it propagates to backtest, simulation, and live automatically.</li><li><strong>Backtest config</strong>: Extends base with backtest-specific options (date ranges, false breakout limits, sweep parameters).</li><li><strong>Live config</strong>: Extends base with live-specific options (broker selection, paper mode flag, WebSocket source, recovery settings).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6sHjBOOGU9m1uKHutNV-A.png" /></figure><p>The inheritance matters. If your base config says risk_reward_ratio = 2.5, every engine uses 2.5 unless explicitly overridden. You never end up in a situation where you mistakenly tweaked the backtest config and forgot to update live.</p><h3>Feature Flags Live in the Base</h3><p>When you add a new capability (a new filter, a new exit rule, a different lot sizing mode), gate it with a boolean in the base config. use_trailing_stops = True. require_engulfing_confirmation = False. This way you can toggle features consistently across all engines, and you can A/B test by running backtests with the flag on vs. off.</p><p>The alternative is scattering if statements through your strategy code, and three months later nobody remembers which combination of conditions represents &quot;the current production config.&quot; A central config with named flags makes the active configuration self-documenting.</p><h3>Version Everything</h3><p>Every backtest, every simulation, every live session should record the exact configuration used. When you look at results from two months ago, you need to know what parameters produced them. Store the full config object alongside the trade log. Without this, you’ll run a great backtest, forget what settings you used, and spend a week trying to reproduce it.</p><h3>Backtesting: The Part Everyone Gets Wrong</h3><p>Backtesting is not “did my strategy make money on historical data.” That’s trivially easy to achieve. Just overfit hard enough and any strategy prints. Backtesting is “does this strategy have a robust edge that will survive forward?”</p><h3>Use a Strategy Orchestrator, Not a Giant If-Else</h3><p>If you’re running multiple strategies (or even multiple entry conditions within one strategy), route candles through an orchestrator rather than nesting conditions. This keeps strategies independent and interchangeable, while still allowing cross-strategy coordination like preventing simultaneous entries.</p><p>This pays off immediately in backtesting because you can enable/disable strategies via config flags and compare results cleanly.</p><h3>Process Days in Isolation</h3><p>This is subtle but important. Each trading day should be a fresh context. Initialize strategy state, process all candles for the day, close any open positions, record results. Then reset.</p><p>Why? Because live trading resets daily. Your engine starts fresh each morning. If your backtest carries hidden state across days (an indicator buffer that never resets, a flag that persisted from yesterday’s trade) your backtest will produce results that your live engine can never replicate.</p><p>The exception is things that <em>should</em> persist: your equity curve, your capital balance, your lot sizing state. Those carry over. Strategy-specific state doesn’t.</p><h3>Slippage and Fees Are Not Optional</h3><p>I know. Everyone says this. People still skip it.</p><p>If you’re trading options, slippage matters more than you think. A 0.1% slippage model on each leg will shave 5–15% off your annual returns depending on your trade frequency. Brokerage fees, exchange charges, transaction taxes: these aren’t rounding errors on high-frequency strategies. Model them or your backtest is fiction.</p><p>The paper executor is the right place for this. Build slippage into the simulated fill price. Buy orders fill slightly above the requested price. Sell orders fill slightly below. This way every mode (backtest, simulation, paper) automatically includes realistic execution costs.</p><h3>Track Options P&amp;L, Not Just Spot P&amp;L</h3><p>If you’re trading derivatives (and most systematic strategies do), your backtest needs to price the actual instruments you’d trade. A 50-point move in spot doesn’t translate linearly to options P&amp;L. Delta, theta decay, and moneyness all matter.</p><p>This means your backtest needs access to historical options data, or at minimum a pricing model that estimates option prices from spot movement. The latter is imperfect but better than ignoring it entirely.</p><h3>Historical Data: The Foundation Everything Sits On</h3><p>Your strategy is only as good as the data you test it on. Data quality problems are insidious because they don’t throw errors. They just silently corrupt your results.</p><h3>What You Need</h3><p>For intraday strategies, you want minute-level candles at minimum: open, high, low, close, volume. Cover at least 2 years, ideally more. You need enough data that your parameter sweep produces statistically meaningful results across multiple market regimes (trending, ranging, high-vol, low-vol).</p><p>Store it in a database, not flat files. You’ll be querying date ranges, joining with options data, and running parallel backtests. A SQLite database works fine for most retail operations. It’s fast, portable, and needs zero infrastructure.</p><h3>Historical Context Matters</h3><p>Here’s a mistake that cost me weeks of debugging: my backtest calculated support/resistance levels correctly because it had the full dataset available. My live engine calculated them wrong on its first day because it had no history loaded.</p><p>Every mode needs access to sufficient historical context for indicator calculation. If your strategy uses a 20-day moving average, your engine needs at least 20 days of prior data available at initialization, whether it’s loading from a database (backtest/simulation) or fetching from an API on startup (live).</p><p>Build this into your initialization sequence. Don’t assume history is available. Load it explicitly, validate it, and fail loudly if it’s insufficient.</p><h3>The Stale Data Trap</h3><p>Live data feeds drop. WebSockets disconnect. APIs rate-limit you. Your options price lookup returns yesterday’s close instead of today’s mid.</p><p>You need staleness checks. If a price quote is more than N seconds old, treat it as unavailable rather than using stale data to make trading decisions. In backtesting this isn’t an issue (all data comes from the same snapshot), but in live trading, stale data is a silent killer. I’ve seen positions opened on option prices that were 30 minutes old. The actual fill was nowhere close.</p><h3>Simulation: Your Most Important Testing Mode</h3><p>I touched on this above, but it’s worth its own section because most people underinvest here.</p><p>The simulation engine exists for one reason: <strong>to guarantee that your live engine behaves identically on historical data as your backtest claims it should.</strong></p><h3>The Parity Problem</h3><p>Here’s the scenario that burns people. You run a backtest. It shows a Profit Factor of 1.6 over two years. Looks solid. You deploy live. After a month, your live results don’t match. Not even close.</p><p>Was the strategy overfit? Maybe. But more often, the live engine just <em>behaves differently</em> than the backtest. Different candle aggregation. Different initialization order. An off-by-one in your timing logic. A state reset that happens in backtest but not live. A race condition that can’t exist in a synchronous backtest loop but absolutely exists in an async live engine.</p><p>The simulation engine catches these. Feed the same historical data through your live engine and compare the trades against your backtest output. They should match. If they don’t, you have a bug, and you want to find it now, not after it’s cost you real money.</p><h3>How to Build It</h3><p>The simulation engine should be a data feeder attached to your live engine:</p><ol><li><strong>Load data</strong>: Pull candles from your database for the target date range.</li><li><strong>Preserve full context</strong>: Keep the complete dataset available for S/R calculation, even though you’re only simulating a subset.</li><li><strong>Feed candle-by-candle</strong>: Send one candle at a time to the live engine’s processing pipeline. This exercises the exact same code path as a real tick arriving from a WebSocket.</li><li><strong>Handle day boundaries</strong>: At end of day, trigger the same cleanup your live engine does. At start of day, trigger the same initialization.</li><li><strong>Speed control</strong>: Let it run at configurable speed. Real-time for visual monitoring, instant for batch comparison.</li></ol><p>The simulation engine should have almost zero logic of its own. If you find yourself adding strategy-related code to the simulation layer, stop. That code belongs in the strategy module where all three engines can share it.</p><h3>What Simulation Catches That Backtests Don’t</h3><ul><li><strong>Initialization bugs</strong>: Your live engine loads historical data, connects to brokers, sets up candle buffers. If any of this is wrong, the simulation will show incorrect trades on day one.</li><li><strong>State management</strong>: The live engine carries state across candles: indicator buffers, pending signals, active positions. Bugs in state management are invisible in a clean backtest loop.</li><li><strong>Candle aggregation</strong>: If your live engine aggregates 1-minute ticks into 5-minute candles, that aggregation logic needs to match what your backtest assumes. Simulation tests this directly.</li><li><strong>Async timing</strong>: Race conditions, out-of-order processing, delayed callbacks. These don’t exist in backtests. They absolutely exist in production.</li><li><strong>Recovery logic</strong>: What happens when your engine restarts mid-day? Does it reconstruct state correctly? Simulate a crash by stopping and restarting the simulation mid-session.</li></ul><h3>Keeping Code Paths Identical</h3><p>This is the meta-principle that ties everything together. The reason you build adapters, share strategy modules, and run simulations is to <strong>guarantee that the code executing your strategy is identical across all modes.</strong></p><h3>Configuration, Not Code Branches</h3><p>Don’t branch on mode inside strategy logic. No if is_backtest: do_this else: do_that. Instead, inject different adapters at initialization and let the strategy code run identically regardless.</p><p>The only place you should branch on mode is in infrastructure code. Should I connect to a WebSocket? No, if simulating. Should I persist state to the database? Yes, if live. Should I skip broker initialization? Yes, if simulating. Strategy logic never asks what mode it’s in.</p><h3>The Litmus Test</h3><p>Here’s how you know your architecture is right: take a random trading day from your historical data. Run it through the backtest engine. Run it through the simulation engine. Compare the trades. They should be identical: same entries, same exits, same P&amp;L (minus any slippage model differences).</p><p>If they’re not, you have a code path divergence. Find it and fix it before you go live. This comparison should be automated. Run it weekly as a regression test. It’s the highest-value test you can write.</p><h3>When to Refactor: Managing Tech Debt Before It Manages You</h3><p>There’s a tension in trading system development that doesn’t exist in most software projects. You want to iterate fast because the market doesn’t wait. But every shortcut you take makes the next change harder, and eventually you’re spending more time working around your own code than improving your strategy.</p><p>I recently went through a major refactor, splitting a monolithic live engine into separate modules: lifecycle management, candle processing, position monitoring, signal generation, state recovery. Each became its own file with clear responsibilities. It was a week of work that produced zero new features. But the three features I built <em>after</em> the refactor each took a day instead of a week.</p><h3>The Right Time to Refactor</h3><p><strong>Not at the start.</strong> When you’re prototyping a new strategy, write messy code. You don’t know what the final shape will be, and premature abstraction is worse than no abstraction. Get it working. Prove the concept.</p><p><strong>Not during a crisis.</strong> If your live system is misbehaving, fix the bug. Don’t refactor your way to a fix. That’s how you introduce three new bugs while solving one.</p><p><strong>After you’ve stabilized but before you scale.</strong> The sweet spot is when your strategy is validated, your backtest results are stable, and you’re about to add complexity: a second strategy, a new instrument, more sophisticated exit logic. That’s the moment where the monolith will start fighting you, and that’s when splitting into modules pays for itself immediately.</p><h3>What to Extract First</h3><p>If you can only refactor one thing, make it the strategy module. Pull your entry logic, exit logic, and signal generation out of whatever engine loop they’re embedded in. Give them clean inputs (a candle, current state) and clean outputs (a signal, or nothing). Once the strategy is a self-contained module, everything else becomes easier: testing, backtesting on new data, running multiple strategies, comparing variants.</p><p>After that, the highest-leverage extractions are usually:</p><ul><li><strong>State management</strong>: Active positions, pending signals, daily P&amp;L tracking. This state is referenced everywhere. Centralizing it prevents inconsistencies.</li><li><strong>Indicator calculation</strong>: Your RSI, Supertrend, Bollinger Bands, whatever. These should be independent modules that accept candles and return values. No strategy logic inside them.</li><li><strong>Configuration</strong>: If your constants are scattered across files, consolidate them. A single config module that all engines import is worth more than any clever refactor of execution code.</li></ul><h3>The Refactoring Test</h3><p>A good refactor doesn’t change behavior. Run your backtest before and after. The trade list should be identical, down to the timestamp and P&amp;L. If it’s not, you’ve introduced a regression, and you need to find it before moving on. This is why having the simulation parity test matters so much. It turns refactoring from “I hope this still works” into “I can prove this still works.”</p><h3>State Recovery: The Thing Nobody Thinks About Until It’s Too Late</h3><p>Your live engine will crash. Your machine will restart. Your cloud provider will recycle your instance. Your broker’s API will hang and your process will get killed by a watchdog.</p><p>When it comes back up mid-session, what happens?</p><p>If the answer is “it starts fresh and doesn’t know about the position it opened 20 minutes ago,” you have a serious problem. An orphaned position with no stop-loss monitoring will ruin your day faster than any bad strategy.</p><h3>What State Recovery Needs</h3><ul><li><strong>Reconstruct active positions</strong>: Read from your database. Know what’s open, at what price, with what stop-loss.</li><li><strong>Rebuild indicator state</strong>: You can’t just start calculating RSI from the current candle. You need to replay today’s candles to rebuild your indicator buffers to their correct state.</li><li><strong>Replay, don’t recalculate</strong>: Feed recovered candles through the same strategy code path. This ensures indicators, opening ranges, and support/resistance levels are all consistent with what they were before the crash.</li><li><strong>Prevent duplicate entries</strong>: Recovered signals shouldn’t trigger new orders. Mark them as display-only and let only new signals generate trades.</li></ul><p>The simulation engine is your best friend here. Simulate a mid-day restart: run the simulation engine for part of a day, kill it, restart it with recovery logic, and verify it produces the same results as an uninterrupted run.</p><h3>Practical Tips That Took Me Too Long to Learn</h3><h3>1. Log Everything, Aggregate Later</h3><p>In live mode, log every candle, every signal evaluation, every order event. Store it structured (JSON or database rows, not print statements). When something goes wrong, and it will, you need to reconstruct exactly what happened, candle by candle.</p><p>In backtesting, don’t log. It’ll slow you down by an order of magnitude. But in simulation and live? Log aggressively. Disk is cheap. Debugging blind is not.</p><h3>2. Fail Loudly</h3><p>If your data source returns garbage, throw an exception. Don’t fall through to a default value. Don’t estimate. In backtesting, you can afford to estimate (the backtest can still run). In live trading, a bad price means a bad trade. It’s better to skip a signal than to enter on a stale or estimated price.</p><h3>3. Separate Strategy Research From Strategy Execution</h3><p>Your Jupyter notebooks and parameter sweeps are research tools. They’re messy by design because you’re exploring. But when something works, extract the core logic into a clean module that your engine can import. Don’t deploy notebook code. Don’t refactor your engine to look like a notebook.</p><p>Research generates hypotheses. The engine executes validated ones. Keep them separate.</p><h3>4. Don’t Optimize Your Engine Prematurely</h3><p>Your first version will be slow. That’s fine. A backtest that takes 5 minutes per year of data is plenty fast for strategy development. Optimize later, when you need to run 10,000 parameter combinations for a sweep. And when you do optimize, optimize the backtest engine. That’s the one where speed matters. The live engine processes one candle per minute. It doesn’t need to be fast.</p><h3>5. Test Edge Cases on Expiry Days</h3><p>If you trade derivatives, expiry days are different. Liquidity dries up. Spreads widen. Time decay accelerates. Your strategy might need different parameters: tighter stops, earlier exits, reduced position sizes. Don’t discover this with real money. Simulate expiry days specifically and compare metrics against regular days.</p><h3>Conclusion</h3><p>Translating a strategy into code is an architecture decision that determines how fast you can iterate, how confidently you can deploy, and how quickly you can recover when things go wrong.</p><p>The core principles are straightforward: share strategy code across all modes, use adapters to swap infrastructure without touching logic, centralize configuration so nothing drifts, run simulations to catch code path divergence, and refactor when the cost of not refactoring exceeds the cost of doing it.</p><p>The hardest part isn’t any individual concept. It’s the discipline to build the foundation before you start optimizing entries. Everyone wants to jump straight to strategy tuning. But the traders who actually make it to production, and stay there, are the ones who invested in the plumbing first.</p><p>Build the system right once. Then iterate on strategy forever.</p><p><em>Follow for more on systematic trading, backtesting, and the gap between theory and live markets.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb10a50da4e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Most Breakout Strategies Fail — And What FVGs and Market Structure Can Do About It]]></title>
            <link>https://medium.com/@ashmitbbiswas/why-most-breakout-strategies-fail-and-what-fvgs-and-market-structure-can-do-about-it-b4f3ed61cbfd?source=rss-dedb2b307718------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4f3ed61cbfd</guid>
            <category><![CDATA[fair-value-gap]]></category>
            <category><![CDATA[intraday-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[market-structure]]></category>
            <dc:creator><![CDATA[Ashmit Biswas]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 15:59:20 GMT</pubDate>
            <atom:updated>2026-03-20T01:28:05.073Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding Fair Value Gaps, Market Structure Shifts, and building algorithmic strategies that survive real markets.</em></p><p>Every trader has lived this moment: price breaks a key level, you enter, and within minutes it reverses straight through your stop loss. The breakout was a lie. The level was real, but the move wasn’t.</p><p>After backtesting thousands of breakout signals across years of data, I’ve learned something uncomfortable: most breakouts fail, not because the levels are wrong, but because we enter without asking <em>why</em> price is moving. Fair Value Gaps and Market Structure analysis are two concepts that answer that question — and when combined correctly, they can separate real moves from traps.</p><p>But here’s the catch: these concepts are easy to understand and dangerously easy to misapply. This post covers what actually works when you put them under the pressure of rigorous backtesting — and what sounds great on annotated charts but falls apart in practice.</p><h3>Fair Value Gaps: The Footprint of Aggressive Money</h3><p>A Fair Value Gap (FVG) is a three-candle pattern where the middle candle moves so aggressively that the wicks of the surrounding candles don’t overlap. There’s a literal gap in the price auction.</p><p><strong>Bullish FVG:</strong> Candle 1’s high sits below Candle 3’s low. The space between them is the FVG zone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iwik_BGPs5Ks5FmIBQac3w.png" /></figure><p><strong>Bearish FVG:</strong> Candle 1’s low sits above Candle 3’s high. Same idea, flipped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_EyLjMnwE2F0KmoxqxWGw.png" /></figure><h3>Why FVGs Matter</h3><p>An FVG tells you that one side of the market completely overwhelmed the other. Price moved so fast that no transactions happened at those intermediate levels. Three things worth noting:</p><ol><li><strong>Institutional footprint.</strong> Retail doesn’t create gaps on liquid instruments. FVGs on major indices or high-volume assets almost always reflect institutional order flow. Somebody big wanted in, and they wanted in <em>now</em>.</li><li><strong>Unfinished business.</strong> Markets tend to revisit price levels where transactions were skipped. An unfilled FVG acts like a magnet — price frequently returns to test the zone before continuing. This, incidentally, gives you a much better entry than chasing the breakout.</li><li><strong>Displacement proof.</strong> If price breaks a key level <em>and</em> creates an FVG through it, that breakout has real force behind it. A breakout without displacement is just price drifting past a line on your chart.</li></ol><h3>The FVG Trap: More Isn’t Better</h3><p>The mistake I see everywhere — and made myself — is treating FVGs as a binary pass/fail. “No FVG on the breakout? Skip the trade.”</p><p>Sounds logical. In practice, it kills your strategy. A lot of the best moves don’t produce a three-candle gap. Price just slices clean through in one candle. No FVG, but it’s a completely valid move. Requiring FVGs on every trade filtered out a quarter of my signals, and the ones it removed were a mix of winners and losers. Fewer trades, no improvement in edge.</p><p>What actually works is treating FVGs as <em>confluence</em>, not a requirement. If there’s an FVG at your entry zone, great — bump up your confidence. If there isn’t one, don’t kill the trade over it. Let other confirmation carry the weight.</p><h3>Practical FVG Detection</h3><p>If you’re building this into code, a few hard-won lessons:</p><ul><li><strong>Timeframe matters enormously.</strong> On 1-minute candles, you’ll find FVGs everywhere — most of them mean nothing. On 15-minute candles, you’ll miss FVGs that form on the breakout itself. <strong>3–5 minute aggregation</strong> is the sweet spot for intraday strategies. But honestly, the bigger win is making sure your higher timeframe trend aligns first. Identify direction on the daily or 4H, <em>then</em> look for FVGs on the execution timeframe in that same direction. An FVG against the prevailing trend is a trap, not an opportunity.</li><li><strong>Minimum gap size.</strong> A 2-point gap on a 24,000-level index is noise, not displacement. Set a floor — something like 0.02–0.05% of instrument price. Adjust for your instrument’s volatility.</li><li><strong>Recency.</strong> An FVG from 30 candles ago has been priced in. Keep a short window — 3–5 aggregated candles is usually sufficient for breakout confirmation.</li><li><strong>Filled FVGs are dead FVGs.</strong> Once price trades through the entire gap zone, the imbalance has been resolved. Take it off your list.</li></ul><h3>Market Structure Shifts: When Trends Actually Change</h3><p>Market structure is just the pattern of highs and lows. That’s it. And that simplicity is exactly what makes it powerful.</p><p><strong>Uptrend structure:</strong> Higher highs and higher lows. Each swing low holds above the previous one.</p><p><strong>Downtrend structure:</strong> Lower highs and lower lows. Each rally fails below the previous peak.</p><p><strong>Market Structure Shift (MSS):</strong> The moment this pattern breaks:</p><ul><li>In an uptrend: price makes a <strong>lower low</strong> (breaks below a prior swing low). The trend has shifted.</li><li>In a downtrend: price makes a <strong>higher high</strong> (breaks above a prior swing high). Sellers have lost control.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ww4bNf7YNxZ00Ni5ioemWg.png" /></figure><h3>Why Structure Beats Indicators</h3><p>I spent a long time using moving average crossovers, RSI divergences, all the standard stuff. They work, sometimes. The problem is lag. By the time your 20-period MA crosses, the move is half over — or it’s about to reverse and you’re catching the top.</p><p>Market structure doesn’t lag because there’s nothing to calculate. Price made a lower low. That’s a fact, not an interpretation filtered through a lookback window. You can argue about what “significant” means, but you can’t argue about whether it happened.</p><h3>Change of Character vs. Break of Structure</h3><p>These get used interchangeably online. They shouldn’t.</p><p><strong>Break of Structure (BOS):</strong> Price continues the existing trend by taking out the last significant high (in an uptrend) or low (in a downtrend). This <em>confirms</em> trend continuation.</p><p><strong>Change of Character (ChoCH):</strong> Price reverses and takes out a significant level in the <em>opposite</em> direction of the prevailing trend. This is your early warning that the trend might be done.</p><p>If you’re trading breakouts, you want BOS — confirmation that the existing move has legs. For mean-reversion or counter-trend strategies, you’re watching for ChoCH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGfXg9v_61FSd0IPoa4TxA.png" /></figure><h3>The Practical Challenge: Defining “Significant” Swings</h3><p>This is where most people get stuck. Too small a lookback and every tiny wiggle registers as a swing, generating noise. Too large and you miss legitimate structure changes for hours.</p><p>What’s worked for me:</p><ul><li><strong>Pivot lookback of 3–5 candles</strong> on a 5-minute chart. Enough to filter noise, responsive enough to catch real shifts.</li><li><strong>Minimum swing distance</strong> — if two swing highs are 3 points apart on a 24,000-level index, they’re basically the same level. Set a floor to prevent clustering.</li><li><strong>Multi-timeframe validation</strong> — a structure shift on your entry timeframe is stronger when the higher timeframe trend agrees. But be careful: a 15-minute trend filter will veto half your valid trades. A 5-minute structure check is usually the right granularity.</li></ul><h3>Combining FVGs and Market Structure: The Right Way</h3><p>You’ve probably seen the YouTube version of this: “Wait for market structure shift, find the FVG in the impulse leg, enter on the retest of the FVG zone.” It’s a beautiful framework. Looks perfect on annotated charts.</p><p>Run it through a backtest and it usually falls apart.</p><p>The issue is <strong>filter stacking</strong>. Each condition you add removes trades. Your base strategy takes 750 trades? Add an RSI filter and you’re at 640. Add an FVG gate and you’re at 550. Add HTF alignment and you’re at 430. Add a candle pattern check and you’re at 370. Stack all of them and you’re at 285 — barely a third of your original sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnfR9nTUi2A7OH0M0-IufQ.png" /></figure><p>Each filter felt reasonable in isolation. Together, they murdered your opportunity set. And the trades they removed weren’t all losers — they were a random mix. You haven’t improved your edge. You’ve just cut your sample size until the remaining trades <em>look</em> better by chance.</p><h3>So how should you actually use these concepts?</h3><p><strong>Use FVGs as confluence, not as a gate.</strong> If an FVG overlaps your entry zone, that upgrades the signal. If there’s no FVG, the trade isn’t automatically dead — other forms of confirmation can carry it.</p><p><strong>Focus on confirmation at the point of entry.</strong> This is the big one. Instead of screening <em>before</em> a signal fires, invest in confirming <em>at the moment of entry</em>. An engulfing candle at a retest is worth more than a pre-flight checklist of five conditions that each remove 15% of trades.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBegyIzz7NYVY4R7GFkB8w.png" /></figure><p><strong>Be skeptical of timeframe sensitivity.</strong> If your concept only works on one specific candle interval but degrades on slightly different intervals, you’re curve-fitting to noise. Real edges survive reasonable parameter variation. If yours doesn’t, you’ve discovered an artifact, not a signal.</p><h3>Parameter Sweeps: The Most Underrated Tool in Strategy Development</h3><p>This is the part most trading content skips entirely. You’ve got a concept, you’ve picked some numbers, the backtest looks decent. But how do you know those numbers are right? How do you know they’re not the <em>only</em> numbers that work?</p><p>A parameter sweep answers this. Instead of running one backtest with your chosen settings, you run hundreds — every combination of your key parameters across historical data. Then you plot the results as a heatmap and look at the shape.</p><h3>What a parameter sweep looks like</h3><p>Pick two parameters — your risk:reward ratio and your minimum signal threshold, say — and test every combo. Plot Profit Factor as the color on a grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYGbTg_9n6heunrrkjkvPg.png" /></figure><p>See that broad green zone? That’s a <strong>plateau</strong> — a wide range of parameter combinations that all produce decent results. This is what you want. It means the edge comes from the underlying market phenomenon, not from one magic number. You can pick any point in that sweet spot and trade with confidence.</p><h3>Plateaus vs. spikes: the overfitting test</h3><p>Now compare that to what an overfitted parameter space looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lte37VCY5rUBYLnQ0yUEgA.png" /></figure><p>Left: plateau. Performance degrades gradually as you move away from the center. Right: spike. One green cell surrounded by a sea of red. The strategy <em>only</em> works at exactly those settings.</p><p>That spike is the most dangerous thing in backtesting. It’ll show up at the top of your leaderboard looking like the best result. But it’s an artifact — a coincidental alignment of parameters and historical data. Move one notch in any direction and the edge vanishes. It will not work live.</p><p><strong>If your sweep produces a spike, walk away.</strong> If it produces a plateau, pick the center of it and you’re probably fine.</p><h3>Look through multiple lenses</h3><p>Same parameters can look very different depending on what you measure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvBQ1XLuxeeXxUDrKdLo7w.png" /></figure><p>The sweet spot is where Profit Factor, Sharpe, and drawdown all agree. If your highest-PF region overlaps with your worst-drawdown region, you’ve found parameters that win big but also occasionally blow up. That’s not a usable edge.</p><h3>How to run a sweep in practice</h3><ol><li><strong>Identify your 2–3 most impactful parameters.</strong> You can’t sweep everything — the combinatorial explosion makes it impractical. Pick the ones that most directly affect entry quality and risk sizing.</li><li><strong>Define a reasonable grid.</strong> 8–12 steps per parameter is enough to reveal the landscape shape. For two parameters that’s 64–144 combinations — very manageable.</li><li><strong>Run on a meaningful sample.</strong> A sweep on 3 months of data is worthless. Each cell needs 100+ trades to mean anything, which usually means 1–2 years of data minimum.</li><li><strong>Parallelize.</strong> Each combination is independent. Run 5–10 at once. What takes 8 hours sequentially finishes in under an hour.</li><li><strong>Read the heatmap, not the leaderboard.</strong> Sorting by “best Profit Factor” and picking the top row is the worst thing you can do. Look at the <em>shape</em>. Is the winner surrounded by other winners, or is it an island? Pick the center of the plateau, not the global maximum.</li><li><strong>Validate out-of-sample.</strong> Find your sweet spot on training data, then run it on data you haven’t touched. If the plateau holds, ship it. If it collapses, you’ve overfit.</li></ol><h3>Building Strategies That Survive: Principles</h3><h3>1. Validate Before You Commit</h3><p>If a concept only works at one exact setting, it’s not real. Sweep it. If it degrades with slight parameter changes, it’s curve-fitted and it’ll break live. The backtest that kills your idea is worth more than the one that confirms it.</p><h3>2. Beware the Filter Stack</h3><p>Each filter sounds reasonable. Together they kill opportunity. Test each in isolation. Measure marginal improvement. If it drops 25% of trades for a 2% win rate bump, skip it.</p><h3>3. The Best Filter is Entry Timing, Not Entry Blocking</h3><p>Waiting for confirmation at the entry point — retest plus a commitment candle — consistently beats pre-screening. You lose some trades that run immediately, but you dodge most of the fakeouts. That’s a trade I’ll take every time.</p><h3>4. Simplicity Compounds, Complexity Breaks</h3><p>Five parameters will out-of-sample more reliably than twenty-five. Every parameter is a degree of freedom for overfitting. Less is genuinely more.</p><h3>5. Your Edge Is in the Exits, Not the Entries</h3><p>Spend 80% of your time on trailing stops, lock levels, and position sizing. A mediocre entry with great trade management beats a perfect entry with a static SL/TP every time.</p><p>Trailing stop locks — where you ratchet your stop up as the trade moves in your favor — are the single highest-leverage improvement I’ve made to a strategy. Converting a fraction of breakeven scratches into small wins compounds faster than you’d expect.</p><h3>6. Respect the Non-Stationarity</h3><p>What works in a trending market fails in a range. What works in low vol blows up in high vol. Build regime awareness into your strategy — not as another filter, but as a way to adjust parameters. Tighten in chop, widen in trends, reduce size in drawdowns.</p><h3>7. Measure What Matters</h3><p>Win rate alone is meaningless. A 30% win rate with 4:1 R:R prints money. A 60% win rate with 0.8:1 R:R doesn’t. Track:</p><ul><li><strong>Profit Factor</strong> (gross wins / gross losses) — above 1.5 is where I get interested</li><li><strong>Sharpe Ratio</strong> — the one number I’d keep if I could only have one</li><li><strong>Maximum Drawdown</strong> — can you psychologically survive it? That’s the real question.</li><li><strong>Calmar Ratio</strong> (annual return / max drawdown) — how efficiently you’re getting paid for the pain</li></ul><h3>Conclusion</h3><p>FVGs and Market Structure describe real things — institutional imbalance, trend inflection. They’re not made-up TA nonsense.</p><p>But there’s a gap between “this is a real phenomenon” and “this improves my strategy.” That gap is where most people lose money. They bolt on concepts because they sound right, without testing whether they actually help.</p><p>Sweep your parameters. Test in isolation before stacking. Confirm at the entry, don’t gate before it. And if the heatmap shows a spike instead of a plateau, have the discipline to walk away.</p><p>The market doesn’t reward complexity. It rewards consistency — and the ability to survive being wrong, because you will be, a lot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4f3ed61cbfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code Hooks: A Practical Guide to Not Staring at Your Terminal]]></title>
            <link>https://medium.com/@ashmitbbiswas/claude-code-hooks-a-practical-guide-to-not-staring-at-your-terminal-71873d2f3f06?source=rss-dedb2b307718------2</link>
            <guid isPermaLink="false">https://medium.com/p/71873d2f3f06</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[claude-hooks]]></category>
            <category><![CDATA[claude-cli]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Ashmit Biswas]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 00:36:30 GMT</pubDate>
            <atom:updated>2026-02-18T01:43:56.573Z</atom:updated>
            <content:encoded><![CDATA[<p>Good design is invisible. You only notice it when using something worse.</p><p><a href="https://cursor.sh/"><strong>Cursor</strong></a> might be expensive, but that notification icon on the menu bar was a beacon my eyes would track all day, waiting for it to tell me some work I had queued needed my attention, while I spent that time binging the downfall of humanity, and Heikin Ashi candles on Youtube (mutually exclusive to each other) or just doomscrolling on Instagram.</p><p>Until, I moved to Claude. The transition was almost smooth, results almost similar since I’ve always used Opus since it came out. I was definitely surprised about how Claude has hourly quotas, which took getting used to.</p><p>Objectively, after having used Claude Code for a good while now, I can say it is so much more tunable if you are opinionated as a developer.<br>Indexing my project beforehand to speed up execution is nice, but <strong>grep </strong>was made to save humanity (you learn to love it the hard way sifting through 50MB log files) and I’m glad Claude prefers it. Engineering lives in log outputs, not code comments.</p><p>While that may be great, I still miss my notification icon. Turns out, a notification icon is a much bigger challenge that involves building native apps that can live in your Menu Bar, something Cursor could do as a standalone app, but we cannot. The next best thing? Something akin to the pop you get when your order executes on Zerodha’s Kite and your heart skips a beat. Well… something less anxiety-inducing perhaps.<br>Enter Claude Hooks.</p><h3>What Are Claude Code Hooks?</h3><p>Claude Code has a <a href="https://docs.anthropic.com/en/docs/claude-code/hooks">hooks system</a> that lets you run shell commands in response to specific events. This is familiar territory. Exactly like React hooks, but instead for the lifecycle of Claude’s execution loop.</p><p>The hooks that we care about, specifically for notifications:<br>Stop— Claude finishes responding (end of turn)<br>PermissionRequest— Claude is about to ask for tool approval<br>PreToolUse— Claude is about to use a specific tool<br>PostToolUse — After a tool finishes executing<br>Notification— Claude sends a notification event</p><p>Each hook receives a JSON payload on stdin with context about what&#39;s happening. Your script reads it, does whatever it wants, and exits.</p><p>Hooks are configured in ~/.claude/settings.json:</p><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;Stop&quot;: [<br>      {<br>        &quot;hooks&quot;: [<br>          {<br>            &quot;type&quot;: &quot;command&quot;,<br>            &quot;command&quot;: &quot;node /path/to/your/script.js&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>That’s it. When Claude stops responding, it runs your script.</p><h3>Step 1: The “Task Completed” Hook</h3><p>The simplest and most useful hook. When Claude finishes a task, play a sound so you know it’s done.</p><p>Create a file called on-stop.js:</p><pre>#!/usr/bin/env node<br>const { execSync } = require(&quot;child_process&quot;);</pre><pre>let raw = &quot;&quot;;<br>process.stdin.setEncoding(&quot;utf-8&quot;);<br>process.stdin.on(&quot;data&quot;, (chunk) =&gt; (raw += chunk));<br>process.stdin.on(&quot;end&quot;, () =&gt; {<br>  let input = {};<br>  try { input = JSON.parse(raw); } catch { process.exit(0); }</pre><pre>  // Don&#39;t fire if another stop hook is already running<br>  if (input.stop_hook_active) process.exit(0);</pre><pre>  // Play the Hero sound on macOS<br>  try {<br>    execSync(&#39;afplay &quot;/System/Library/Sounds/Hero.aiff&quot;&#39;, { stdio: &quot;ignore&quot; });<br>  } catch {}</pre><pre>  // Show a macOS notification<br>  try {<br>    execSync(`osascript -e &#39;display notification &quot;Claude has finished the task.&quot; with title &quot;Claude Code&quot;&#39;`, { stdio: &quot;ignore&quot; });<br>  } catch {}</pre><pre>  process.exit(0);<br>});</pre><p>Register it in ~/.claude/settings.json:</p><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;Stop&quot;: [<br>      {<br>        &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;node /path/to/on-stop.js&quot; }]<br>      }<br>    ]<br>  }<br>}</pre><p>Restart Claude Code, give it a task, and walk away. There will be a chime when Claude finishes.</p><h3>Step 2: The “Needs Permission” Hook</h3><p>Claude frequently pauses to ask for permission before running commands, editing files, or using tools. If you’re not watching, you won’t see the permission dialog, and Claude just… waits.</p><p>The PermissionRequest hook fires right when this happens:</p><pre>#!/usr/bin/env node<br>const { execSync } = require(&quot;child_process&quot;);</pre><pre>let raw = &quot;&quot;;<br>process.stdin.setEncoding(&quot;utf-8&quot;);<br>process.stdin.on(&quot;data&quot;, (chunk) =&gt; (raw += chunk));<br>process.stdin.on(&quot;end&quot;, () =&gt; {<br>  let input = {};<br>  try { input = JSON.parse(raw); } catch { process.exit(0); }</pre><pre>  const tool = input.tool_name || &quot;a tool&quot;;</pre><pre>  // Play Glass sound — distinct from the completion sound<br>  try {<br>    execSync(&#39;afplay &quot;/System/Library/Sounds/Glass.aiff&quot;&#39;, { stdio: &quot;ignore&quot; });<br>  } catch {}</pre><pre>  try {<br>    execSync(`osascript -e &#39;display notification &quot;Claude needs permission to use ${tool}.&quot; with title &quot;Claude Code&quot;&#39;`, { stdio: &quot;ignore&quot; });<br>  } catch {}</pre><pre>  process.exit(0);<br>});</pre><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;PermissionRequest&quot;: [<br>      {<br>        &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;node /path/to/on-permission.js&quot; }]<br>      }<br>    ]<br>  }<br>}</pre><p>Same here as the Stop notification, but a different chime for when Claude needs permission for a specific tool use.</p><h3>Step 3: The “Asking a Question” Hook</h3><p>Sometimes Claude doesn’t need permission — it needs your <em>input</em>. It’ll ask a question via the AskUserQuestion tool: &quot;Which database should I use?&quot; or &quot;Do you want me to include tests?&quot;</p><p>This is where PreToolUse comes in. It fires before any tool execution, and you can filter it to specific tools using the matcher field:</p><pre>#!/usr/bin/env node<br>const { execSync } = require(&quot;child_process&quot;);</pre><pre>let raw = &quot;&quot;;<br>process.stdin.setEncoding(&quot;utf-8&quot;);<br>process.stdin.on(&quot;data&quot;, (chunk) =&gt; (raw += chunk));<br>process.stdin.on(&quot;end&quot;, () =&gt; {<br>  // Play Funk sound — yet another distinct sound<br>  try {<br>    execSync(&#39;afplay &quot;/System/Library/Sounds/Funk.aiff&quot;&#39;, { stdio: &quot;ignore&quot; });<br>  } catch {}</pre><pre>  try {<br>    execSync(`osascript -e &#39;display notification &quot;Claude is asking you a question.&quot; with title &quot;Claude Code&quot;&#39;`, { stdio: &quot;ignore&quot; });<br>  } catch {}</pre><pre>  process.exit(0);<br>});</pre><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;PreToolUse&quot;: [<br>      {<br>        &quot;matcher&quot;: &quot;AskUserQuestion&quot;,<br>        &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;node /path/to/on-question.js&quot; }]<br>      }<br>    ]<br>  }<br>}</pre><p>The matcher field is the key here. Without it, PreToolUse would fire for <em>every</em> tool call — every file read, every grep, every edit. With &quot;matcher&quot;: &quot;AskUserQuestion&quot;, it only fires when Claude is specifically asking you something.</p><p>Something interesting but predictable about this hook is that since it’s a pretool use hook with a matcher, there is a latency between when this hook triggers a notification, and when the question finally appears for the user. Minimal, but noticeable.</p><h3>The Gotcha: Avoiding Double-Fires</h3><p>Nothing with vibe-coding is ever as simple as it should be so here is the nuance with this specific problem statement: You want to fire different chimes for when Claude needs to ask you for user input vs. when it needs you to provide the permission to use a certain tool.<br>However, when Claude uses AskUserQuestion, it triggers <em>both</em> the PreToolUse hook (because AskUserQuestion is a tool) <em>and</em> the PermissionRequest hook (because using a tool requires permission).</p><p>That means two sounds would play simultaneously. Now we don’t like that, but we also do not like slop. Well, at least below the very low standards we set for ourselves of course.</p><p>The fix: in the permission hook, skip AskUserQuestion:</p><pre>// In on-permission.js, right after parsing input:<br>if (input.tool_name === &quot;AskUserQuestion&quot;) process.exit(0);</pre><p>Now AskUserQuestion is handled exclusively by the PreToolUse hook, and everything else goes through PermissionRequest. Clean separation.</p><h3>Putting It All Together</h3><p>Here’s the complete settings.json with all three hooks:</p><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;Stop&quot;: [<br>      {<br>        &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;node ~/.claude/hooks/on-stop.js&quot; }]<br>      }<br>    ],<br>    &quot;PermissionRequest&quot;: [<br>      {<br>        &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;node ~/.claude/hooks/on-permission.js&quot; }]<br>      }<br>    ],<br>    &quot;PreToolUse&quot;: [<br>      {<br>        &quot;matcher&quot;: &quot;AskUserQuestion&quot;,<br>        &quot;hooks&quot;: [{ &quot;type&quot;: &quot;command&quot;, &quot;command&quot;: &quot;node ~/.claude/hooks/on-question.js&quot; }]<br>      }<br>    ]<br>  }<br>}</pre><p>Three hooks, three scripts, three distinct sounds.</p><h3>What Else Can You Build With Hooks?</h3><p>The principle extends to any usecase that plays around Claude’s different states. Hooks give you a programmatic interface into Claude Code’s lifecycle. Therefore, some ideas that follow:</p><ul><li>Auto-commit: Use a Stop hook to auto-stage and commit after every completed task</li><li>Logging: Track which tools Claude uses most with a PostToolUse hook that appends to a log file</li><li>Cost tracking: Parse the Stop hook payload to track token usage across sessions</li><li>Slack/Discord alerts: Replace osascript with a webhook call to get notifications on your phone</li><li>Guardrails: Use PreToolUse to block specific commands or tools — return a non-zero exit code to prevent execution</li><li>Auto-review: Run a linter or type-checker in a PostToolUse hook after every file edit</li></ul><h3>Try Out the Plugin:</h3><p>If you just want the notifier without building it yourself:</p><p>VSCode:</p><pre>code --install-extension SingularityInc.claude-notifier</pre><p>CLI / Terminal / Vim:</p><pre>curl -fsSL https://raw.githubusercontent.com/ashmitb95/claude-notifier/main/install.sh | bash</pre><p>The extension auto-configures everything. The CLI installer copies the hooks and updates your settings. You can now go back to binging your favorite TV show while Claude works for you.</p><p>Cheers!</p><p>Source code: <a href="https://github.com/ashmitb95/claude-notifier">github.com/ashmitb95/claude-notifier</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-fWIk5b1EfYXDmAwd9gmQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71873d2f3f06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>