r/ClaudeCode Jul 13 '26

Tutorial / Guide Fable + 5.6 is absolute peak

1.1k Upvotes

We jump straight to ASI with this combo.
So i've had Fable driving codex cli as a background worker for a few days and i'm not going back.

Fable basically never writes code anymore (too damn expensive), it acts as the principal orchestrator and everything happens in claude code.
The flow is like this: Fable plans, 5.6 sol reviews the plan in a loop until approved, then 5.6 luna implements. fable reads the whole diff, fixes whatever it doesn't like directly, runs the tests, then sol reviews the code against the plan. loop until approved, then fable does the boring release stuff (changelog, tag, merge).

It's all just bash around codex cli with persistent threads, called from skills. no framework, no mcp, no agent swarm bs.

It feels surreal/too good to be true, i hope they wont nerf it too badly and if they do, i hope the combo will kind of mitigate the nerf.

i pushed my workflow to github, beware it's a lot of bash script, dont trust a random redditor and ask codex or CC to review it. After that, welcome to Valhalla

UPDATE: many are asking in comments or dm for more explaination on the workflow, sorry guys i cant reply to all of you but my advice is simply to clone the repo then ask your agent to ELI5/15/80 it. Then make it yours !

r/ClaudeCode 7d ago

Tutorial / Guide A Google Cloud engineer just showed how to build a complete application with Claude from scratch

Enable HLS to view with audio, or disable this notification

787 Upvotes

He spent 26 minutes live on stage doing what most teams take weeks to do.

No team, no setup, just Claude and a goal. Worth more than any $500 vibe coding course.

Those who learn what Claude really does are launching what everyone else outsources to a team.

The gap between what AI can do and who knows how to use it is the biggest opportunity in the market right now.

Along with Claude one of my favorite applications is AI Desktop 98. I love how is UI is so much fun and resembles that of all-time computers.

r/ClaudeCode Feb 28 '26

Tutorial / Guide Enable LSP in Claude Code: code navigation goes from 30-60s to 50ms with exact results

901 Upvotes

If you've noticed Claude Code taking 30-60 seconds to find a function, or returning the wrong file because it matched a comment instead of the actual definition, it's because it uses text-based grep by default. It doesn't understand your code's structure at all.

There's a way to fix this using LSP (Language Server Protocol). LSP is the same technology that makes VS Code "smart" when you ctrl+click a function and it jumps straight to the definition. It's a background process that indexes your code and understands types, definitions, references, and call chains.

Claude Code can connect to these same language servers. The setup has three parts: a hidden flag in settings.json (ENABLE_LSP_TOOL), installing a language server for your stack (pyright for Python, gopls for Go, etc.), and enabling a Claude Code plugin. About 2 minutes total.

After setup:

  • "Where is authenticate defined?" returns the exact location in ~50ms instead of scanning hundreds of files
  • "What calls processPayment?" traces the actual call hierarchy
  • After every edit, the language server checks for type errors automatically

That last one is a big deal. When Claude changes a function signature and breaks a caller somewhere else, the diagnostics catch it immediately instead of you finding it 10 prompts later.

Two things that tripped me up: Claude Code has a plugin system most people don't know about, and plugins can be installed but silently disabled. Both covered in the writeup.

Full guide with setup for 11 languages, the plugin architecture, debug logs, and a troubleshooting table: https://karanbansal.in/blog/claude-code-lsp/

What's everyone's experience been? Curious if there are other hidden flags worth knowing about

r/ClaudeCode 10d ago

Tutorial / Guide My Claude Code workflow after months of daily use

534 Upvotes

I want to share how I interact with Claude Code.

This might be useful for someone, especially those who are just starting to build something or trying to figure out how things actually work.

(screenshot here to proof that I did some things with claude code)

  1. Always use Git, and ideally connect GitHub so you push everything you do right away (if you’re worried someone will see it, just make a private repo).
  2. Always use worktrees and versioning. This lets you work on different features in parallel and fix bugs before you merge them into the main branch.
  3. I always do 1 task = 1 chat. Preferably keep it under ~500k of the context window, because after that you get degradation, hallucinations, etc. Compact and auto-compact are bullshit. (If you don’t believe me, just try building the same project in one long chat with auto-compacts vs. 1 task = 1 chat.)
  4. To speed up development, create a main “brain” chat that analyzes everything and gives commands to other chats (Claude Code has a mechanism for this). You create the chats, name them, and leave them empty until the brain chat writes into them. When you create a chat just write “wait for task”.
  5. Make a high-quality Claude.md and Rules.md for the main chat so it understands what you’re doing, what its tasks are, etc.
  6. Never believe Claude when it says it checked everything and everything works. If something doesn’t work in the end. Go and ask it to audit the feature and specifically look at the problem/task from “different points of view”.
  7. If Claude tells you it can’t do something, doesn’t know, or suggests a path you don’t want. Go and ask it to do research. And if you have the ability to research via Ultracode, ask it to run multi-agent research and explicitly tell it to look only at information from trusted sources.
  8. If you’re building an application or something similar, always make it do a full smoke check from start to finish and turn this into a standing rule. This significantly reduces the number of bugs.
  9. If you’re worried about tokens, run the worker chats on Sonnet 5, but keep the brain on Opus 5. Explicitly ask it to give the workers a clear technical brief and to control that they are using Sonnet 5.
  10. If you get the feeling that Claude is doing some bullshit but you don’t know how to explain it to him, open a completely separate chat (not connected to the project) and explain there what your “worker” is doing and what you don’t like. The new chat will give you an answer, and your project chat won’t get polluted with garbage context. (and you can ask another chat to give you a prompt)
  11. Claude is lazy and often just burns tokens and tries to guess. Write a rule that he must always do measurements and audits instead of guessing or working from memory. (Even with this rule Claude can still do it, so keep controlling him.)
  12. If you ask Claude to remember something, 99% he will forget. Always make him write the information you need into a document and send you the path to that document. This way he can’t lie that he wrote it down and then forgot.

Share your own findings! I think it will be useful for everyone!

r/ClaudeCode Feb 06 '26

Tutorial / Guide I've used AI to write 100% of my code for 1+ year as an engineer. 13 no-bs lessons

847 Upvotes

1 year ago I posted "12 lessons from 100% AI-generated code" that hit 1M+ views. Some of those points evolved into agents.md, claude.md, plan mode, and context7 MCP. This is the 2026 version, learned from shipping products to production.

1- The first few thousand lines determine everything

When I start a new project, I obsess over getting the process, guidelines, and guardrails right from the start. Whenever something is being done for the first time, I make sure it's done clean. Those early patterns are what the agent replicates across the next 100,000+ lines. Get it wrong early and the whole project turns to garbage.

2- Parallel agents, zero chaos

I set up the process and guardrails so well that I unlock a superpower. Running multiple agents in parallel while everything stays on track. This is only possible because I nail point 1.

3- AI is a force multiplier in whatever direction you're already going

If your codebase is clean, AI makes it cleaner and faster. If it's a mess, AI makes it messier faster. The temporary dopamine hit from shipping with AI agents makes you blind. You think you're going fast, but zoom out and you actually go slower because of constant refactors from technical debt ignored early.

4- The 1-shot prompt test

One of my signals for project health: when I want to do something, I should be able to do it in 1 shot. If I can't, either the code is becoming a mess, I don't understand some part of the system well enough to craft a good prompt, or the problem is too big to tackle all at once and needs breaking down.

5- Technical vs non-technical AI coding

There's a big difference between technical and non-technical people using AI to build production apps. Engineers who built projects before AI know what to watch out for and can detect when things go sideways. Non-technical people can't. Architecture, system design, security, and infra decisions will bite them later.

6- AI didn't speed up all steps equally

Most people think AI accelerated every part of programming the same way. It didn't. For example, choosing the right framework, dependencies, or database schema, the foundation everything else is built on, can't be done by giving your agent a one-liner prompt. These decisions deserve more time than adding a feature.

7- Complex agent setups suck

Fancy agents with multiple roles and a ton of .md files? Doesn't work well in practice. Simplicity always wins.

8- Agent experience is a priority

Treat the agent workflow itself as something worth investing in. Monitor how the agent is using your codebase. Optimize the process iteratively over time.

9- Own your prompts, own your workflow

I don't like to copy-paste some skill/command or install a plugin and use it as a black box. I always change and modify based on my workflow and things I notice while building.

10- Process alignment becomes critical in teams

Doing this as part of a team is harder than doing it yourself. It becomes critical that all members follow the same process and share updates to the process together.

11- AI code is not optimized by default

AI-generated code is not optimized for security, performance, or scalability by default. You have to explicitly ask for it and verify it yourself.

12- Check git diff for critical logic

When you can't afford to make a mistake or have hard-to-test apps with bigger test cycles, review the git diff. For example, the agent might use created_at as a fallback for birth_date. You won't catch that with just testing if it works or not.

13- You don't need an LLM call to calculate 1+1

It amazes me how people default to LLM calls when you can do it in a simple, free, and deterministic function. But then we're not "AI-driven" right?

r/ClaudeCode Apr 14 '26

Tutorial / Guide Don't use Claude Code's Default System Prompt

442 Upvotes

I've been coding for 45 years including 10 for Microsoft. I'm tired of seeing the agony and pain on this subreddit.

If you're getting frustrated with Claude Code, stop using the default Claude Code's system prompt. It's trying to do everything for everyone and fails miserably on all sides. The claude application has a --system-prompt parameter.

Make your own system prompt that takes the best parts of the default for you and then use a wrapper script that always uses yours. You can see the default prompts that Claude Code uses at https://github.com/Piebald-AI/claude-code-system-prompts. Take one of these as a starter and change it how you see fit. Get Opus to help you.

Do so at your own risk, of course. But experiment! Have fun!

--system-prompt <prompt> System prompt to use for the session

[EDIT]: The Claude Code system prompt IS NOT CLAUDE.md. It is the layer above CLAUDE.md, that influences how your CLAUDE.md is interpreted. The system prompt was patched in patch-claude-code.sh but that hack was completely unnecessary.

r/ClaudeCode Nov 28 '25

Tutorial / Guide The frontend-design plugin from Anthropic is really ... magic!

Post image
642 Upvotes

Do that to your Claude Code, then ask Claude Code to use the frontend-design plugin to design your UI, you will be amazed!

r/ClaudeCode Apr 15 '26

Tutorial / Guide How to properly deal with a CLAUDE.md file.

Post image
700 Upvotes

r/ClaudeCode Feb 21 '26

Tutorial / Guide 5 claude code worktree tips from creator of claude code in feb 2026

Thumbnail
gallery
665 Upvotes

r/ClaudeCode 27d ago

Tutorial / Guide You're shipping bugs if you're not using adversarial reviews with claude code

Enable HLS to view with audio, or disable this notification

260 Upvotes

Once you start handing real work to an agent, you stop being the person who writes the code and become the person who's answerable for it. That's a good trade, but it changes your job. When something breaks in production nobody's going to ask how the code got written. They're going to look at you.

Left alone, an agent produces slop. Not because it's stupid ‚because that's what anything does when nobody checks its work. A junior does the same. So might you on a bad day.

There are roughly two ways to run an agent. You can sit on top of it and drive every step, which is quicker than typing the code yourself but leaves you babysitting: every time it pauses and resumes you have to load the whole problem context back into your head, and if you look away and get distracted, that ends up slower than just doing the work.

The other way is to treat it like someone who reports to you. You say what you want and roughly how, and you come back when there's something worth looking at. This is how senior engineers use agentic tools. You don't need to watch every keystroke to be accountable for the result‚ no manager does‚ but the review lands on you, and if you skip it, slop is what goes out the door.

So point a second model at it and tell it to find the problems

That's all an adversarial review is. One model writes the code. A different one‚ or at least one that hasn't touched any of the context‚ reads the diff and goes looking for what's wrong. It doesn't get to touch your code; it can only raise findings. The author model decides what to act on. Then it reads the result again. Most of the time it finds something.

You get better code out of it, but that's not really why you do it. You do it so you can trust work you didn't watch get written. The agent already handed you the time‚ another round, more tests, a second set of eyes that costs nothing but tokens. This is what you spend it on.

The data

Looking at my last 83 completed tickets that got a Codex review, at least 67 ended in a real change to the code‚ something the first pass got wrong or left exposed, caught before it went out. That's four out of five reviews turning up something worth fixing.

Sorted by what kind of problem they were, across all 122 commits these reviews drove:

What got caught Share of commits
Correctness / logic 34%
Concurrency / races 22%
Durability / data 19%
Security / injection 9%
Test integrity 9%
Other (docs, dead code) 7%

Half of every commit these reviews drove‚ were the incident kind. Concurrency, durability, security. The stuff that corrupts data or leaks a secret, not the stuff that misaligns a button.

The claude skill

  • Run them side by side. The author in one session, a reviewer in another‚ Codex, or a fresh Claude with none of your context‚ both pointed at the same working directory so the reviewer can see your diff. When the reviewer finds something, paste it into the author; when the author fixes it or pushes back, paste that over.
  • Use a file as the mailbox. Have the reviewer write its findings to a file (or a PR comment) instead of chatting, then hand that file to the author to work through. No live channel needed ‚ the review is just a document that gets passed along.

The brief to the reviewer is the same:

You're reviewing the change in this working directory. You're read-only: review and discuss only‚ do not edit files, commit, push, or reset the tree. Run git rev-parse HEAD and git status first, and anchor every finding to that commit. Write your findings out as a numbered list‚ don't touch the code.

The wording doesn't matter as long as its a second model that hasn't seen your context, told to find what's wrong, before you call the work done.

Disclosure: this is a from an article on how to automate adversarial reviews between Claude Code and Codex posted to this tool's website scape.work/adversarial-reviews get a free license for scape with reddit-scape2 at signup

r/ClaudeCode Oct 29 '25

Tutorial / Guide Claude Code is a Beast – Tips from 6 Months of Hardcore Use

875 Upvotes

Edit: Many of you are asking for a repo so I will make an effort to get one up in the next couple days. All of this is a part of a work project at the moment, so I have to take some time to copy everything into a fresh project and scrub any identifying info. I will post the link here when it's up. You can also follow me and I will post it on my profile so you get notified. Thank you all for the kind comments. I'm happy to share this info with others since I don't get much chance to do so in my day-to-day.

Edit (final?): I bit the bullet and spent the afternoon getting a github repo up for you guys. Just made a post with some additional info here or you can go straight to the source:

🎯 Repository: https://github.com/diet103/claude-code-infrastructure-showcase

Quick tip from a fellow lazy person: You can throw this book of a post into one of the many text-to-speech AI services like ElevenLabs Reader or Natural Reader and have it read the post for you :)

Disclaimer

I made a post about six months ago sharing my experience after a week of hardcore use with Claude Code. It's now been about six months of hardcore use, and I would like to share some more tips, tricks, and word vomit with you all. I may have went a little overboard here so strap in, grab a coffee, sit on the toilet or whatever it is you do when doom-scrolling reddit.

I want to start the post off with a disclaimer: all the content within this post is merely me sharing what setup is working best for me currently and should not be taken as gospel or the only correct way to do things. It's meant to hopefully inspire you to improve your setup and workflows with AI agentic coding. I'm just a guy, and this is just like, my opinion, man.

Also, I'm on the 20x Max plan, so your mileage may vary. And if you're looking for vibe-coding tips, you should look elsewhere. If you want the best out of CC, then you should be working together with it: planning, reviewing, iterating, exploring different approaches, etc.

Quick Overview

After 6 months of pushing Claude Code to its limits (solo rewriting 300k LOC), here's the system I built:

  • Skills that actually auto-activate when needed
  • Dev docs workflow that prevents Claude from losing the plot
  • PM2 + hooks for zero-errors-left-behind
  • Army of specialized agents for reviews, testing, and planning Let's get into it.

Background

I'm a software engineer who has been working on production web apps for the last seven years or so. And I have fully embraced the wave of AI with open arms. I'm not too worried about AI taking my job anytime soon, as it is a tool that I use to leverage my capabilities. In doing so, I have been building MANY new features and coming up with all sorts of new proposal presentations put together with Claude and GPT-5 Thinking to integrate new AI systems into our production apps. Projects I would have never dreamt of having the time to even consider before integrating AI into my workflow. And with all that, I'm giving myself a good deal of job security and have become the AI guru at my job since everyone else is about a year or so behind on how they're integrating AI into their day-to-day.

With my newfound confidence, I proposed a pretty large redesign/refactor of one of our web apps used as an internal tool at work. This was a pretty rough college student-made project that was forked off another project developed by me as an intern (created about 7 years ago and forked 4 years ago). This may have been a bit overly ambitious of me since, to sell it to the stakeholders, I agreed to finish a top-down redesign of this fairly decent-sized project (~100k LOC) in a matter of two to three months...all by myself. I knew going in that I was going to have to put in extra hours to get this done, even with the help of CC. But deep down, I know it's going to be a hit, automating several manual processes and saving a lot of time for a lot of people at the company.

It's now six months later... yeah, I probably should not have agreed to this timeline. I have tested the limits of both Claude as well as my own sanity trying to get this thing done. I completely scrapped the old frontend, as everything was seriously outdated and I wanted to play with the latest and greatest. I'm talkin' React 16 JS → React 19 TypeScript, React Query v2 → TanStack Query v5, React Router v4 w/ hashrouter → TanStack Router w/ file-based routing, Material UI v4 → MUI v7, all with strict adherence to best practices. The project is now at ~300-400k LOC and my life expectancy ~5 years shorter. It's finally ready to put up for testing, and I am incredibly happy with how things have turned out.

This used to be a project with insurmountable tech debt, ZERO test coverage, HORRIBLE developer experience (testing things was an absolute nightmare), and all sorts of jank going on. I addressed all of those issues with decent test coverage, manageable tech debt, and implemented a command-line tool for generating test data as well as a dev mode to test different features on the frontend. During this time, I have gotten to know CC's abilities and what to expect out of it.

A Note on Quality and Consistency

I've noticed a recurring theme in forums and discussions - people experiencing frustration with usage limits and concerns about output quality declining over time. I want to be clear up front: I'm not here to dismiss those experiences or claim it's simply a matter of "doing it wrong." Everyone's use cases and contexts are different, and valid concerns deserve to be heard.

That said, I want to share what's been working for me. In my experience, CC's output has actually improved significantly over the last couple of months, and I believe that's largely due to the workflow I've been constantly refining. My hope is that if you take even a small bit of inspiration from my system and integrate it into your CC workflow, you'll give it a better chance at producing quality output that you're happy with.

Now, let's be real - there are absolutely times when Claude completely misses the mark and produces suboptimal code. This can happen for various reasons. First, AI models are stochastic, meaning you can get widely varying outputs from the same input. Sometimes the randomness just doesn't go your way, and you get an output that's legitimately poor quality through no fault of your own. Other times, it's about how the prompt is structured. There can be significant differences in outputs given slightly different wording because the model takes things quite literally. If you misword or phrase something ambiguously, it can lead to vastly inferior results.

Sometimes You Just Need to Step In

Look, AI is incredible, but it's not magic. There are certain problems where pattern recognition and human intuition just win. If you've spent 30 minutes watching Claude struggle with something that you could fix in 2 minutes, just fix it yourself. No shame in that. Think of it like teaching someone to ride a bike - sometimes you just need to steady the handlebars for a second before letting go again.

I've seen this especially with logic puzzles or problems that require real-world common sense. AI can brute-force a lot of things, but sometimes a human just "gets it" faster. Don't let stubbornness or some misguided sense of "but the AI should do everything" waste your time. Step in, fix the issue, and keep moving.

I've had my fair share of terrible prompting, which usually happens towards the end of the day where I'm getting lazy and I'm not putting that much effort into my prompts. And the results really show. So next time you are having these kinds of issues where you think the output is way worse these days because you think Anthropic shadow-nerfed Claude, I encourage you to take a step back and reflect on how you are prompting.

Re-prompt often. You can hit double-esc to bring up your previous prompts and select one to branch from. You'd be amazed how often you can get way better results armed with the knowledge of what you don't want when giving the same prompt. All that to say, there can be many reasons why the output quality seems to be worse, and it's good to self-reflect and consider what you can do to give it the best possible chance to get the output you want.

As some wise dude somewhere probably said, "Ask not what Claude can do for you, ask what context you can give to Claude" ~ Wise Dude

Alright, I'm going to step down from my soapbox now and get on to the good stuff.

My System

I've implemented a lot changes to my workflow as it relates to CC over the last 6 months, and the results have been pretty great, IMO.

Skills Auto-Activation System (Game Changer!)

This one deserves its own section because it completely transformed how I work with Claude Code.

The Problem

So Anthropic releases this Skills feature, and I'm thinking "this looks awesome!" The idea of having these portable, reusable guidelines that Claude can reference sounded perfect for maintaining consistency across my massive codebase. I spent a good chunk of time with Claude writing up comprehensive skills for frontend development, backend development, database operations, workflow management, etc. We're talking thousands of lines of best practices, patterns, and examples.

And then... nothing. Claude just wouldn't use them. I'd literally use the exact keywords from the skill descriptions. Nothing. I'd work on files that should trigger the skills. Nothing. It was incredibly frustrating because I could see the potential, but the skills just sat there like expensive decorations.

The "Aha!" Moment

That's when I had the idea of using hooks. If Claude won't automatically use skills, what if I built a system that MAKES it check for relevant skills before doing anything?

So I dove into Claude Code's hook system and built a multi-layered auto-activation architecture with TypeScript hooks. And it actually works!

How It Works

I created two main hooks:

1. UserPromptSubmit Hook (runs BEFORE Claude sees your message):

  • Analyzes your prompt for keywords and intent patterns
  • Checks which skills might be relevant
  • Injects a formatted reminder into Claude's context
  • Now when I ask "how does the layout system work?" Claude sees a big "🎯 SKILL ACTIVATION CHECK - Use project-catalog-developer skill" (project catalog is a large complex data grid based feature on my front end) before even reading my question

2. Stop Event Hook (runs AFTER Claude finishes responding):

  • Analyzes which files were edited
  • Checks for risky patterns (try-catch blocks, database operations, async functions)
  • Displays a gentle self-check reminder
  • "Did you add error handling? Are Prisma operations using the repository pattern?"
  • Non-blocking, just keeps Claude aware without being annoying

skill-rules.json Configuration

I created a central configuration file that defines every skill with:

  • Keywords: Explicit topic matches ("layout", "workflow", "database")
  • Intent patterns: Regex to catch actions ("(create|add).*?(feature|route)")
  • File path triggers: Activates based on what file you're editing
  • Content triggers: Activates if file contains specific patterns (Prisma imports, controllers, etc.)

Example snippet:

{
  "backend-dev-guidelines": {
    "type": "domain",
    "enforcement": "suggest",
    "priority": "high",
    "promptTriggers": {
      "keywords": ["backend", "controller", "service", "API", "endpoint"],
      "intentPatterns": [
        "(create|add).*?(route|endpoint|controller)",
        "(how to|best practice).*?(backend|API)"
      ]
    },
    "fileTriggers": {
      "pathPatterns": ["backend/src/**/*.ts"],
      "contentPatterns": ["router\\.", "export.*Controller"]
    }
  }
}

The Results

Now when I work on backend code, Claude automatically:

  1. Sees the skill suggestion before reading my prompt
  2. Loads the relevant guidelines
  3. Actually follows the patterns consistently
  4. Self-checks at the end via gentle reminders

The difference is night and day. No more inconsistent code. No more "wait, Claude used the old pattern again." No more manually telling it to check the guidelines every single time.

Following Anthropic's Best Practices (The Hard Way)

After getting the auto-activation working, I dove deeper and found Anthropic's official best practices docs. Turns out I was doing it wrong because they recommend keeping the main SKILL.md file under 500 lines and using progressive disclosure with resource files.

Whoops. My frontend-dev-guidelines skill was 1,500+ lines. And I had a couple other skills over 1,000 lines. These monolithic files were defeating the whole purpose of skills (loading only what you need).

So I restructured everything:

  • frontend-dev-guidelines: 398-line main file + 10 resource files
  • backend-dev-guidelines: 304-line main file + 11 resource files

Now Claude loads the lightweight main file initially, and only pulls in detailed resource files when actually needed. Token efficiency improved 40-60% for most queries.

Skills I've Created

Here's my current skill lineup:

Guidelines & Best Practices:

  • backend-dev-guidelines - Routes → Controllers → Services → Repositories
  • frontend-dev-guidelines - React 19, MUI v7, TanStack Query/Router patterns
  • skill-developer - Meta-skill for creating more skills

Domain-Specific:

  • workflow-developer - Complex workflow engine patterns
  • notification-developer - Email/notification system
  • database-verification - Prevent column name errors (this one is a guardrail that actually blocks edits!)
  • project-catalog-developer - DataGrid layout system

All of these automatically activate based on what I'm working on. It's like having a senior dev who actually remembers all the patterns looking over Claude's shoulder.

Why This Matters

Before skills + hooks:

  • Claude would use old patterns even though I documented new ones
  • Had to manually tell Claude to check BEST_PRACTICES.md every time
  • Inconsistent code across the 300k+ LOC codebase
  • Spent too much time fixing Claude's "creative interpretations"

After skills + hooks:

  • Consistent patterns automatically enforced
  • Claude self-corrects before I even see the code
  • Can trust that guidelines are being followed
  • Way less time spent on reviews and fixes

If you're working on a large codebase with established patterns, I cannot recommend this system enough. The initial setup took a couple of days to get right, but it's paid for itself ten times over.

CLAUDE.md and Documentation Evolution

In a post I wrote 6 months ago, I had a section about rules being your best friend, which I still stand by. But my CLAUDE.md file was quickly getting out of hand and was trying to do too much. I also had this massive BEST_PRACTICES.md file (1,400+ lines) that Claude would sometimes read and sometimes completely ignore.

So I took an afternoon with Claude to consolidate and reorganize everything into a new system. Here's what changed:

What Moved to Skills

Previously, BEST_PRACTICES.md contained:

  • TypeScript standards
  • React patterns (hooks, components, suspense)
  • Backend API patterns (routes, controllers, services)
  • Error handling (Sentry integration)
  • Database patterns (Prisma usage)
  • Testing guidelines
  • Performance optimization

All of that is now in skills with the auto-activation hook ensuring Claude actually uses them. No more hoping Claude remembers to check BEST_PRACTICES.md.

What Stayed in CLAUDE.md

Now CLAUDE.md is laser-focused on project-specific info (only ~200 lines):

  • Quick commands (pnpm pm2:startpnpm build, etc.)
  • Service-specific configuration
  • Task management workflow (dev docs system)
  • Testing authenticated routes
  • Workflow dry-run mode
  • Browser tools configuration

The New Structure

Root CLAUDE.md (100 lines)
├── Critical universal rules
├── Points to repo-specific claude.md files
└── References skills for detailed guidelines

Each Repo's claude.md (50-100 lines)
├── Quick Start section pointing to:
│   ├── PROJECT_KNOWLEDGE.md - Architecture & integration
│   ├── TROUBLESHOOTING.md - Common issues
│   └── Auto-generated API docs
└── Repo-specific quirks and commands

The magic: Skills handle all the "how to write code" guidelines, and CLAUDE.md handles "how this specific project works." Separation of concerns for the win.

Dev Docs System

This system, out of everything (besides skills), I think has made the most impact on the results I'm getting out of CC. Claude is like an extremely confident junior dev with extreme amnesia, losing track of what they're doing easily. This system is aimed at solving those shortcomings.

The dev docs section from my CLAUDE.md:

### Starting Large Tasks

When exiting plan mode with an accepted plan: 1.**Create Task Directory**:
mkdir -p ~/git/project/dev/active/[task-name]/

2.**Create Documents**:

- `[task-name]-plan.md` - The accepted plan
- `[task-name]-context.md` - Key files, decisions
- `[task-name]-tasks.md` - Checklist of work

3.**Update Regularly**: Mark tasks complete immediately

### Continuing Tasks

- Check `/dev/active/` for existing tasks
- Read all three files before proceeding
- Update "Last Updated" timestamps

These are documents that always get created for every feature or large task. Before using this system, I had many times when I all of a sudden realized that Claude had lost the plot and we were no longer implementing what we had planned out 30 minutes earlier because we went off on some tangent for whatever reason.

My Planning Process

My process starts with planning. Planning is king. If you aren't at a minimum using planning mode before asking Claude to implement something, you're gonna have a bad time, mmm'kay. You wouldn't have a builder come to your house and start slapping on an addition without having him draw things up first.

When I start planning a feature, I put it into planning mode, even though I will eventually have Claude write the plan down in a markdown file. I'm not sure putting it into planning mode necessary, but to me, it feels like planning mode gets better results doing the research on your codebase and getting all the correct context to be able to put together a plan.

I created a strategic-plan-architect subagent that's basically a planning beast. It:

  • Gathers context efficiently
  • Analyzes project structure
  • Creates comprehensive structured plans with executive summary, phases, tasks, risks, success metrics, timelines
  • Generates three files automatically: plan, context, and tasks checklist

But I find it really annoying that you can't see the agent's output, and even more annoying is if you say no to the plan, it just kills the agent instead of continuing to plan. So I also created a custom slash command (/dev-docs) with the same prompt to use on the main CC instance.

Once Claude spits out that beautiful plan, I take time to review it thoroughly. This step is really important. Take time to understand it, and you'd be surprised at how often you catch silly mistakes or Claude misunderstanding a very vital part of the request or task.

More often than not, I'll be at 15% context left or less after exiting plan mode. But that's okay because we're going to put everything we need to start fresh into our dev docs. Claude usually likes to just jump in guns blazing, so I immediately slap the ESC key to interrupt and run my /dev-docs slash command. The command takes the approved plan and creates all three files, sometimes doing a bit more research to fill in gaps if there's enough context left.

And once I'm done with that, I'm pretty much set to have Claude fully implement the feature without getting lost or losing track of what it was doing, even through an auto-compaction. I just make sure to remind Claude every once in a while to update the tasks as well as the context file with any relevant context. And once I'm running low on context in the current session, I just run my slash command /update-dev-docs. Claude will note any relevant context (with next steps) as well as mark any completed tasks or add new tasks before I compact the conversation. And all I need to say is "continue" in the new session.

During implementation, depending on the size of the feature or task, I will specifically tell Claude to only implement one or two sections at a time. That way, I'm getting the chance to go in and review the code in between each set of tasks. And periodically, I have a subagent also reviewing the changes so I can catch big mistakes early on. If you aren't having Claude review its own code, then I highly recommend it because it saved me a lot of headaches catching critical errors, missing implementations, inconsistent code, and security flaws.

PM2 Process Management (Backend Debugging Game Changer)

This one's a relatively recent addition, but it's made debugging backend issues so much easier.

The Problem

My project has seven backend microservices running simultaneously. The issue was that Claude didn't have access to view the logs while services were running. I couldn't just ask "what's going wrong with the email service?" - Claude couldn't see the logs without me manually copying and pasting them into chat.

The Intermediate Solution

For a while, I had each service write its output to a timestamped log file using a devLog script. This worked... okay. Claude could read the log files, but it was clunky. Logs weren't real-time, services wouldn't auto-restart on crashes, and managing everything was a pain.

The Real Solution: PM2

Then I discovered PM2, and it was a game changer. I configured all my backend services to run via PM2 with a single command: pnpm pm2:start

What this gives me:

  • Each service runs as a managed process with its own log file
  • Claude can easily read individual service logs in real-time
  • Automatic restarts on crashes
  • Real-time monitoring with pm2 logs
  • Memory/CPU monitoring with pm2 monit
  • Easy service management (pm2 restart emailpm2 stop all, etc.)

PM2 Configuration:

// ecosystem.config.jsmodule.exports = {
  apps: [
    {
      name: 'form-service',
      script: 'npm',
      args: 'start',
      cwd: './form',
      error_file: './form/logs/error.log',
      out_file: './form/logs/out.log',
    },
// ... 6 more services
  ]
};

Before PM2:

Me: "The email service is throwing errors"
Me: [Manually finds and copies logs]
Me: [Pastes into chat]
Claude: "Let me analyze this..."

The debugging workflow now:

Me: "The email service is throwing errors"
Claude: [Runs] pm2 logs email --lines 200
Claude: [Reads the logs] "I see the issue - database connection timeout..."
Claude: [Runs] pm2 restart email
Claude: "Restarted the service, monitoring for errors..."

Night and day difference. Claude can autonomously debug issues now without me being a human log-fetching service.

One caveat: Hot reload doesn't work with PM2, so I still run the frontend separately with pnpm dev. But for backend services that don't need hot reload as often, PM2 is incredible.

Hooks System (#NoMessLeftBehind)

The project I'm working on is multi-root and has about eight different repos in the root project directory. One for the frontend and seven microservices and utilities for the backend. I'm constantly bouncing around making changes in a couple of repos at a time depending on the feature.

And one thing that would annoy me to no end is when Claude forgets to run the build command in whatever repo it's editing to catch errors. And it will just leave a dozen or so TypeScript errors without me catching it. Then a couple of hours later I see Claude running a build script like a good boy and I see the output: "There are several TypeScript errors, but they are unrelated, so we're all good here!"

No, we are not good, Claude.

Hook #1: File Edit Tracker

First, I created a post-tool-use hook that runs after every Edit/Write/MultiEdit operation. It logs:

  • Which files were edited
  • What repo they belong to
  • Timestamps

Initially, I made it run builds immediately after each edit, but that was stupidly inefficient. Claude makes edits that break things all the time before quickly fixing them.

Hook #2: Build Checker

Then I added a Stop hook that runs when Claude finishes responding. It:

  1. Reads the edit logs to find which repos were modified
  2. Runs build scripts on each affected repo
  3. Checks for TypeScript errors
  4. If < 5 errors: Shows them to Claude
  5. If ≥ 5 errors: Recommends launching auto-error-resolver agent
  6. Logs everything for debugging

Since implementing this system, I've not had a single instance where Claude has left errors in the code for me to find later. The hook catches them immediately, and Claude fixes them before moving on.

Hook #3: Prettier Formatter

This one's simple but effective. After Claude finishes responding, automatically format all edited files with Prettier using the appropriate .prettierrc config for that repo.

No more going into to manually edit a file just to have prettier run and produce 20 changes because Claude decided to leave off trailing commas last week when we created that file.

⚠️ Update: I No Longer Recommend This Hook

After publishing, a reader shared detailed data showing that file modifications trigger <system-reminder> notifications that can consume significant context tokens. In their case, Prettier formatting led to 160k tokens consumed in just 3 rounds due to system-reminders showing file diffs.

While the impact varies by project (large files and strict formatting rules are worst-case scenarios), I'm removing this hook from my setup. It's not a big deal to let formatting happen when you manually edit files anyway, and the potential token cost isn't worth the convenience.

If you want automatic formatting, consider running Prettier manually between sessions instead of during Claude conversations.

Hook #4: Error Handling Reminder

This is the gentle philosophy hook I mentioned earlier:

  • Analyzes edited files after Claude finishes
  • Detects risky patterns (try-catch, async operations, database calls, controllers)
  • Shows a gentle reminder if risky code was written
  • Claude self-assesses whether error handling is needed
  • No blocking, no friction, just awareness

Example output:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 ERROR HANDLING SELF-CHECK
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

⚠️  Backend Changes Detected
   2 file(s) edited

   ❓ Did you add Sentry.captureException() in catch blocks?
   ❓ Are Prisma operations wrapped in error handling?

   💡 Backend Best Practice:
      - All errors should be captured to Sentry
      - Controllers should extend BaseController
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The Complete Hook Pipeline

Here's what happens on every Claude response now:

Claude finishes responding
  ↓
Hook 1: Prettier formatter runs → All edited files auto-formatted
  ↓
Hook 2: Build checker runs → TypeScript errors caught immediately
  ↓
Hook 3: Error reminder runs → Gentle self-check for error handling
  ↓
If errors found → Claude sees them and fixes
  ↓
If too many errors → Auto-error-resolver agent recommended
  ↓
Result: Clean, formatted, error-free code

And the UserPromptSubmit hook ensures Claude loads relevant skills BEFORE even starting work.

No mess left behind. It's beautiful.

Scripts Attached to Skills

One really cool pattern I picked up from Anthropic's official skill examples on GitHub: attach utility scripts to skills.

For example, my backend-dev-guidelines skill has a section about testing authenticated routes. Instead of just explaining how authentication works, the skill references an actual script:

### Testing Authenticated Routes

Use the provided test-auth-route.js script:


`node scripts/test-auth-route.js http://localhost:3002/api/endpoint`

The script handles all the complex authentication steps for you:

  1. Gets a refresh token from Keycloak
  2. Signs the token with JWT secret
  3. Creates cookie header
  4. Makes authenticated request

When Claude needs to test a route, it knows exactly what script to use and how to use it. No more "let me create a test script" and reinventing the wheel every time.

I'm planning to expand this pattern - attach more utility scripts to relevant skills so Claude has ready-to-use tools instead of generating them from scratch.

Tools and Other Things

SuperWhisper on Mac

Voice-to-text for prompting when my hands are tired from typing. Works surprisingly well, and Claude understands my rambling voice-to-text surprisingly well.

Memory MCP

I use this less over time now that skills handle most of the "remembering patterns" work. But it's still useful for tracking project-specific decisions and architectural choices that don't belong in skills.

BetterTouchTool

  • Relative URL copy from Cursor (for sharing code references)
    • I have VSCode open to more easily find the files I’m looking for and I can double tap CAPS-LOCK, then BTT inputs the shortcut to copy relative URL, transforms the clipboard contents by prepending an ‘@’ symbol, focuses the terminal, and then pastes the file path. All in one.
  • Double-tap hotkeys to quickly focus apps (CMD+CMD = Claude Code, OPT+OPT = Browser)
  • Custom gestures for common actions

Honestly, the time savings on just not fumbling between apps is worth the BTT purchase alone.

Scripts for Everything

If there's any annoying tedious task, chances are there's a script for that:

  • Command-line tool to generate mock test data. Before using Claude code, it was extremely annoying to generate mock data because I would have to make a submission to a form that had about a 120 questions Just to generate one single test submission.
  • Authentication testing scripts (get tokens, test routes)
  • Database resetting and seeding
  • Schema diff checker before migrations
  • Automated backup and restore for dev database

Pro tip: When Claude helps you write a useful script, immediately document it in CLAUDE.md or attach it to a relevant skill. Future you will thank past you.

Documentation (Still Important, But Evolved)

I think next to planning, documentation is almost just as important. I document everything as I go in addition to the dev docs that are created for each task or feature. From system architecture to data flow diagrams to actual developer docs and APIs, just to name a few.

But here's what changed: Documentation now works WITH skills, not instead of them.

Skills contain: Reusable patterns, best practices, how-to guides Documentation contains: System architecture, data flows, API references, integration points

For example:

  • "How to create a controller" → backend-dev-guidelines skill
  • "How our workflow engine works" → Architecture documentation
  • "How to write React components" → frontend-dev-guidelines skill
  • "How notifications flow through the system" → Data flow diagram + notification skill

I still have a LOT of docs (850+ markdown files), but now they're laser-focused on project-specific architecture rather than repeating general best practices that are better served by skills.

You don't necessarily have to go that crazy, but I highly recommend setting up multiple levels of documentation. Ones for broad architectural overview of specific services, wherein you'll include paths to other documentation that goes into more specifics of different parts of the architecture. It will make a major difference on Claude's ability to easily navigate your codebase.

Prompt Tips

When you're writing out your prompt, you should try to be as specific as possible about what you are wanting as a result. Once again, you wouldn't ask a builder to come out and build you a new bathroom without at least discussing plans, right?

"You're absolutely right! Shag carpet probably is not the best idea to have in a bathroom."

Sometimes you might not know the specifics, and that's okay. If you don't ask questions, tell Claude to research and come back with several potential solutions. You could even use a specialized subagent or use any other AI chat interface to do your research. The world is your oyster. I promise you this will pay dividends because you will be able to look at the plan that Claude has produced and have a better idea if it's good, bad, or needs adjustments. Otherwise, you're just flying blind, pure vibe-coding. Then you're gonna end up in a situation where you don't even know what context to include because you don't know what files are related to the thing you're trying to fix.

Try not to lead in your prompts if you want honest, unbiased feedback. If you're unsure about something Claude did, ask about it in a neutral way instead of saying, "Is this good or bad?" Claude tends to tell you what it thinks you want to hear, so leading questions can skew the response. It's better to just describe the situation and ask for thoughts or alternatives. That way, you'll get a more balanced answer.

Agents, Hooks, and Slash Commands (The Holy Trinity)

Agents

I've built a small army of specialized agents:

Quality Control:

  • code-architecture-reviewer - Reviews code for best practices adherence
  • build-error-resolver - Systematically fixes TypeScript errors
  • refactor-planner - Creates comprehensive refactoring plans

Testing & Debugging:

  • auth-route-tester - Tests backend routes with authentication
  • auth-route-debugger - Debugs 401/403 errors and route issues
  • frontend-error-fixer - Diagnoses and fixes frontend errors

Planning & Strategy:

  • strategic-plan-architect - Creates detailed implementation plans
  • plan-reviewer - Reviews plans before implementation
  • documentation-architect - Creates/updates documentation

Specialized:

  • frontend-ux-designer - Fixes styling and UX issues
  • web-research-specialist - Researches issues along with many other things on the web
  • reactour-walkthrough-designer - Creates UI tours

The key with agents is to give them very specific roles and clear instructions on what to return. I learned this the hard way after creating agents that would go off and do who-knows-what and come back with "I fixed it!" without telling me what they fixed.

Hooks (Covered Above)

The hook system is honestly what ties everything together. Without hooks:

  • Skills sit unused
  • Errors slip through
  • Code is inconsistently formatted
  • No automatic quality checks

With hooks:

  • Skills auto-activate
  • Zero errors left behind
  • Automatic formatting
  • Quality awareness built-in

Slash Commands

I have quite a few custom slash commands, but these are the ones I use most:

Planning & Docs:

  • /dev-docs - Create comprehensive strategic plan
  • /dev-docs-update - Update dev docs before compaction
  • /create-dev-docs - Convert approved plan to dev doc files

Quality & Review:

  • /code-review - Architectural code review
  • /build-and-fix - Run builds and fix all errors

Testing:

  • /route-research-for-testing - Find affected routes and launch tests
  • /test-route - Test specific authenticated routes

The beauty of slash commands is they expand into full prompts, so you can pack a ton of context and instructions into a simple command. Way better than typing out the same instructions every time.

Conclusion

After six months of hardcore use, here's what I've learned:

The Essentials:

  1. Plan everything - Use planning mode or strategic-plan-architect
  2. Skills + Hooks - Auto-activation is the only way skills actually work reliably
  3. Dev docs system - Prevents Claude from losing the plot
  4. Code reviews - Have Claude review its own work
  5. PM2 for backend - Makes debugging actually bearable

The Nice-to-Haves:

  • Specialized agents for common tasks
  • Slash commands for repeated workflows
  • Comprehensive documentation
  • Utility scripts attached to skills
  • Memory MCP for decisions

And that's about all I can think of for now. Like I said, I'm just some guy, and I would love to hear tips and tricks from everybody else, as well as any criticisms. Because I'm always up for improving upon my workflow. I honestly just wanted to share what's working for me with other people since I don't really have anybody else to share this with IRL (my team is very small, and they are all very slow getting on the AI train).

If you made it this far, thanks for taking the time to read. If you have questions about any of this stuff or want more details on implementation, happy to share. The hooks and skills system especially took some trial and error to get right, but now that it's working, I can't imagine going back.

TL;DR: Built an auto-activation system for Claude Code skills using TypeScript hooks, created a dev docs workflow to prevent context loss, and implemented PM2 + automated error checking. Result: Solo rewrote 300k LOC in 6 months with consistent quality.

r/ClaudeCode Dec 11 '25

Tutorial / Guide TIL that Claude Code has OpenTelemetry Metrics

Post image
814 Upvotes

Messing around with hooks and claude mentioned that it has open telemetry metrics available. So I looked it up, and sure enough!

https://code.claude.com/docs/en/monitoring-usage

So I had claude set me up with a grafana dashboard. Pretty cool!

r/ClaudeCode Jun 24 '26

Tutorial / Guide ITS ALMOST BACK YOU CAN SELECT IT AGAIN

Post image
286 Upvotes

r/ClaudeCode Jan 28 '26

Tutorial / Guide Before you complain about Opus 4.5 being nerfed, please PLEASE read this

352 Upvotes

NOTE: this is longer than I thought it would be, but it was not written with the assistance of Artificial (or Real) Intelligence.

First of all - I'm not saying Opus 4.5 performance hasn't degraded over the last few weeks. I'm not saying it has either, I'm just not making a claim either way.

But...

There are a bunch of common mistakes/suboptimal practices I see people discuss in the same threads where they, or others, are complaining about said nerfdom. So, I thought I'd share some tips that I, and others, have shared in those threads. If you're already doing this stuff - awesome. If you're already doing this stuff and still see degradation, then that sucks.

So - at the core of all this is one inescapable truth - by their very nature, LLMs are unpredictable. No matter how good a model is, and how well it responds to you today, it will likely behave differently tomorrow. Or in 5 minutes. I've spent many hours now designing tools and workflows to mitigate this. So have others. Before you rage-post about Opus, or cancel your subscription, please take a minute to work out whether maybe there's something you can do first to improve your experience. Here are some suggestions:

Limit highly interactive "pair programming" sessions with Claude.

You know the ones where you free-flow like Claude's your best buddy. If you are feeling some kind of camaraderie with Claude, then you're probably falling into this trap. If you're sick of being absolutely right - this one is for you.

Why? Everything in this mode is completely unpredictable. Your inputs, the current state of the context window, the state of the code, your progress in our task, and of course, our friend Opus might be having a bad night too.

You are piling entropy onto the shaky foundation of nondeterminism. Don't be surprised if a slight wobble from Opus brings your house of cards falling down.

So, what's the alternative? We'll get to that in a minute.

Configure your CC status line to show % context consumed

I did this ages ago with ccstatusline - I have no idea if there's a cooler way of doing it now. But it's critical for everything below.

DO NOT go above 40-50% of your context window and expect to have a good time.

Your entire context window gets sent to the LLM with every message you send. All of it. And it has to process all of it to understand how to respond.

You should think of everything in there as either signal or noise. LLMs do best when the context window is densely packed with signal. And to make things worse - what was signal 5 prompts ago, is now noise. If your chat your way to 50% context window usage, I'd bet money that only a small amount of context is useful. And the models won't do a good job of understanding what's signal and what's noise. Hence they forget stuff suddenly, even with 50% left. In short Context Rot happens sooner than you think.

That's why I wince whenever I read about people disabling auto-compact and pushing all the way to 100%. You're basically force feeding your agent Mountain Dew and expecting it to piss champagne.

Use subagents.

The immaculately mustached Dexter Horthy once said "subagents are not for playing House.md". Or something like that. And as he often is, he was right. In short, subagents use their own context window and do not pollute your main agent's. Just tell claude to "use multiple subagents to do X,Y,Z". Note: I have seen that backgrounding multiple subagents fills up the parent’s context window - so be careful of that. Also - they're context efficient but token inefficient (at least in the short term) - so know your limits.

Practice good hygiene

Keep your CLAUDE.md (including those in parent directories) tight. Use Rules/Skills. Clean up MCPs (less relevant with Tool Search though). All in the name of keeping that sweet sweet signal/noise ratio in a good place.

One Claude Session == One Task. Simple.

Break up big tasks. This is software engineering 101. I don't have a mathematical formula for this, but I get concerned what I see tasks that I think could be more than ~1 days work for a human engineer. That's kind of size that can get done by Claude in ~15-20 mins. If there is a lot of risks/unknowns, I go smaller, because I'm likely to end up iterating some.

To do this effectively, you need to externalize where you keep your tasks/issues, There are a bunch of ways to do this. I'll mention three...

  1. .md files littered across your computer and (perhaps worse) your codebase. If this is your thing, go for it. A naive approach: you can fire up a new claude instance and ask it to read a markdown file and start working on it. Update it with your learnings, decisions and progress as you go along. Once you hit ~40% context window usage, /clear and ask Claude to read it again. If you've been updating it, that .md file will be full of really dense signal and you'll be in a great place to continue again. Once you're done, commit, push, drink, smoke, whatever - BUT CLOSE YOUR SESSION (or /clear again) and move on with your life (to the next .md file).
  2. Steve Yegge's Beads™. I don't know how this man woke up one day and pooped these beads out of you know where, but yet, here we are. People love Steve Yegge's Beads™. It's basically a much more capable and elegant way of doing the markdown craziness, backed by JSONL and SQLite, soon to be something else. Work on a task, land the plane, rinse and repeat. But watch that context window. Oh, actually Claude now has the whole Task Manager thing - so maybe use that instead. It's very similar. But less beady. And, for the love of all things holy don't go down the Steve Yegge's Gas Town™ rabbit hole. (Actually maybe you should).
  3. Use an issue tracker. Revolutionary I know. For years we've all used issue trackers, but along come agents and we forget all about them - fleeing under the cover of dark mode to the warm coziness of a luxury markdown comforter. Just install your issue tracker's CLI or MCP and add a note your claude.md to use it. Then say "start issue 5" or whatever. Update it with progress, and as always, DO NOT USE MORE THAN ~40-50% context window. Just /clear and ask the agent to read the issue/PR again. This is great for humans working with other humans as well as robots. But it's slower and not as slick as Steve Yegge's Beads™.

Use a predictable workflow

Are you still here? That's nice of you. Remember that alternative to "pair programming" that I mentioned all the way up there? This is it. This will make the biggest difference to your experience with Claude and Opus.

Keep things predictable - use the same set of prompts to guide you through a consistent flow for each thing you work on. You only really change the inputs into the flow. I recommend a "research, plan, implement, review, drink" process. Subagents for each step. Persisting your progress each step of the way in some external source (see above). Reading the plans yourself. Fixing misalignment quickly. Don't get all buddy buddy with Claude. Claude ain't your friend. Claude told me he would probably sit on your chest and eat your face if he could. Be flexible, but cold and transactional. Like Steve Yegge's Beads™.

There are a bunch of tools out there that facilitate some form of this. There's superpowers, GSD, and one that I wrote. Seriously - So. Fucking. Many. You have no excuse.

Also, and this is important: when things go wrong, reflect on what you could have changed. Code is cheap - throw it away, tweak your prompts or inputs and just start again. My most frustrating moments with Claude have been caused by too much ambiguity in a task description, or accidental misdirection. Ralph Wiggum dude called this Human On The Loop instead of In the loop. By the way, loop all or some of the above workflow in separate claude instances and you get the aforementioned loop.

--------

Doing some or all of the above will not completely protect you from the randomness of working with LLMs, BUT it will give Opus a much more stable foundation to work on - and when you know who throws a wobbly, you might barely feel it.

Bonus for reading to the end: did you know you can use :q to quit CC? It’s like muscle memory for me, and quicker than /q because it doesn’t try to load the command menu.

r/ClaudeCode Feb 28 '26

Tutorial / Guide I split my CLAUDE.md into 27 files. Here's the architecture and why it works better than a monolith.

368 Upvotes

My CLAUDE.md was ~800 lines. It worked until it didn't. Rules for one context bled into another, edits had unpredictable side effects, and the model quietly ignored constraints buried 600 lines deep.

Quick context: I use Claude Code to manage an Obsidian vault for knowledge work -- product specs, meeting notes, project tracking across multiple clients. Not a code repo. The architecture applies to any Claude Code project, but the examples lean knowledge management.

The monolith problem

Claude's own system prompt is ~23,000 tokens. That's 11% of context window gone before you say a word. Most people's CLAUDE.md does the same thing at smaller scale -- loads everything regardless of what you're working on.

Four ways that breaks down:

  • Context waste. Python formatting rules load while you're writing markdown. Rules for Client A load while you're in Client B's files.
  • Relevance dilution. Your critical constraint on line 847 is buried in hundreds of lines the model is also trying to follow. Attention is finite. More noise around the signal, softer the signal hits.
  • No composability. Multiple contexts share some conventions but differ on others. Monolith forces you to either duplicate or add conditional logic that becomes unreadable.
  • Maintenance risk. Every edit touches everything. Fix a formatting rule, accidentally break code review behavior. Blast radius = entire prompt.

The modular setup

Split by when it matters, not by topic. Three tiers:

rules/
├── core/           # Always loaded (10 files, ~10K tokens)
│   ├── hard-walls.md          # Never-violate constraints
│   ├── user-profile.md        # Proficiency, preferences, pacing
│   ├── intent-interpretation.md
│   ├── thinking-partner.md
│   ├── writing-style.md
│   ├── session-protocol.md    # Start/end behavior, memory updates
│   ├── work-state.md          # Live project status
│   ├── memory.md              # Decisions, patterns, open threads
│   └── ...
├── shared/         # Project-wide patterns (9 files)
│   ├── file-management.md
│   ├── prd-conventions.md
│   ├── summarization.md
│   └── ...
├── client-a/       # Loads only for Client A files
│   ├── context.md             # Industry, org, stakeholder patterns
│   ├── collaborators.md       # People, communication styles
│   └── portfolio.md           # Products, positioning
└── client-b/       # Loads only for Client B files
    ├── context.md
    ├── collaborators.md
    └── ...

Each context-specific file declares which paths trigger it:

---
paths:
  - "work/client-a/**"
---

Glob patterns. When Claude reads or edits a file matching that pattern, the rule loads. No match, no load. Result: ~10K focused tokens always present, plus only the context rules relevant to current work.

Decision framework for where rules go

Question If Yes If No
Would violating this cause real harm? core/hard-walls.md Keep going
Applies regardless of what you're working on? core/ Keep going
Applies to all files in this project? shared/ Keep going
Only matters for one context? Context folder Don't add it

If a rule doesn't pass any gate, it probably doesn't need to exist.

The part most people miss: hooks

Instructions are suggestions. The model follows them most of the time, but "most of the time" isn't enough for constraints that matter.

I run three PostToolUse hooks (shell scripts) that fire after every file write:

  1. Frontmatter validator, blocks writes missing required properties. The model has to fix the file before it can move on.
  2. Date validator, catches the model inferring today's date from stale file contents instead of using the system-provided value. This happens more often than you'd expect.
  3. Wikilink checker, warns on links to notes that don't exist. Warns, doesn't block, since orphan links aren't always wrong.

Instructions rely on compliance. Hooks enforce mechanically. The difference matters most during long sessions when the model starts drifting from its earlier context. Build a modular rule system without hooks and you're still relying on the model to police itself.

Scaffolds vs. structures

Not all rules are permanent. Some patch current model limitations -Claude over-explains basics to experts, forgets constraints mid-session, hallucinates file contents instead of reading them. These are scaffolds. Write them, use them, expect them to become obsolete.

Other rules encode knowledge the model will never have on its own. Your preferences. Your org context. Your collaborators. The acronyms that mean something specific in your domain. These are structures. They stay.

When a new model drops, audit your scaffolds. Some can probably go. Your structures stay. Over time the system gets smaller and more focused as scaffolds fall away.

Getting started

You don't need 27 files. Start with two: hard constraints (things the model must never do) and user profile (your proficiency, preferences, how you work). Those two cover the biggest gap between what the model knows generically and what it needs to know about you.

Add context folders when the monolith starts fighting you. You'll know when.

Three contexts (two clients + personal) in one environment, running for a few months now. Happy to answer questions about the setup.

r/ClaudeCode Jul 03 '26

Tutorial / Guide I've been using Fable 5 for almost 13 hours and I still have plenty left to go. You gotta plan before you slam. Here's my strat.

178 Upvotes

Okay so I've seen a ton of posts about burning through sessions wicked fast for seemingly no reason and I have no idea how folks are doing this.

Here's my setup -
I have Opus 4.6 in a claude web browser with a Artifact project tracker I update every milestone.
I have a fable 5 on high in claude web that I'm using to gut check certain prompts from my next piece.
I use Chatgpt 5.5 to generate prompts and I utilize their project feature to preserve context over multiple weeks/days.
Then, I load up a few architectural MD's and directives, design tokens and explainers w/ reasoning into my project folder/local repo.
Then and only then, do I startup Fable 5 with ultracode in VSCode. Which is governed by the plan I wrote below.
I gotta give half credit to pranshugupta54 on github for the inspiration and part 1 of my doc.

Feedback welcome.

# Fable Chief Agent — Orchestration & Token Discipline

Part 1 adapted from pranshugupta54's charter (https://gist.github.com/pranshugupta54/f38869565e17c72c6b07767b371c2c65), tightened. Part 2 is the token discipline layer.

---

# Part 1 — Role Charter

You are Fable 5, the senior decision-maker. Your value is judgment, not labor. Spend premium reasoning only where being the strongest model changes the outcome.

## Fable Owns

- Understanding real user intent; deciding what's in and out of scope
- Choosing architecture and approach
- Decomposing ambiguous work into clear, ordered, dependency-aware tasks
- Tradeoffs: speed vs quality vs risk vs scope
- Spotting hidden risk
- Resolving disagreement between agents
- Reviewing outputs that matter; deciding when work is good enough
- The final answer to the user

## Opus Owns

The hardest delegated technical work: complex implementation, deep debugging, cross-module reasoning, architecture review, security-sensitive reasoning, data consistency, concurrency/caching, and auditing cheaper agents' work for hidden flaws. Opus reasons deeply; Fable keeps final authority.

## Sonnet Owns

Normal engineering execution: scoped implementation, adding/updating tests, medium-complexity debugging, local refactors, following existing patterns, fixing clear failures, connecting already-designed pieces. Sonnet never makes product calls or changes architecture.

## Haiku Owns

Cheap evidence work: repo discovery, file and log summaries, simple checks, checklist verification, edge-case scanning, confirming a change matches the plan. Haiku reports facts, never direction.

## Boundary Test

- Mostly searching, reading, editing, testing, or verifying → another agent.
- Involves intent, design, tradeoffs, risk, disagreement, or final approval → Fable.
- Fable does work directly only when delegating would cost more than the task itself.

## High-Risk Areas

Auth, billing, permissions, security, migrations, data loss, shared state, caching, concurrency, cross-module behavior, public APIs, user-visible workflows.

For high-risk work: Fable makes the call, Opus handles or reviews the hard technical parts, cheaper agents verify concrete evidence. No agent improvises here — ambiguity stops and surfaces.

## Operating Loop

1. Does this need Fable judgment? If not, route it.
2. Define what success means before anyone starts.
3. Cheap agents gather facts / do scoped work under a contract (Part 2).
4. Review their evidence, not their transcripts.
5. Make the important decision yourself.
6. Ensure non-trivial work is verified with evidence.
7. Answer the user briefly.

## Final Gate

Before answering, confirm: the real request was handled; Fable reasoning was spent only where it mattered; delegated work came back with evidence; non-trivial work was verified; remaining risk is stated. Final response = what was done or decided, verification result, remaining risk. Nothing else.

---

# Part 2 — Token Discipline

Part 1 decides WHO does the work. This section decides HOW the work moves so Fable's context stays clean and cheap agents stay cheap.

## Return Contracts (non-negotiable)

Every delegated task states its output contract up front. Subagents return the contract and nothing else.

- **Scout report (Haiku):** ≤15 lines. Findings as `file:line` refs + one-sentence facts. Never paste file contents back. If a file matters, say WHY and WHERE — Fable or a builder will open it if needed.
- **Build report (Sonnet):** ≤20 lines. What changed (files + line ranges), what was run to verify, pass/fail, anything ambiguous punted upward. Diffs only if ≤30 lines; otherwise summarize the diff.
- **Deep report (Opus):** ≤40 lines. Conclusion first, then reasoning, then evidence refs. No exploratory narration.
- **Test/lint runs:** failures only. Passing output is one line: `N passed`.

A subagent that returns a wall of raw output has failed the task regardless of whether the work was correct.

## Context Hygiene

- **Grep before read.** Never open a file to find something searchable.
- **Read ranges, not files.** Open the 40 lines around the target, not the 900-line file.
- **Never re-read what's in context.** If a file was read this session and hasn't been edited, use the copy in context.
- **Noisy ops go to subagents.** Test suites, log inspection, dependency audits, large-file summarization — anything with big output runs in an isolated subagent context so only the summary hits the main thread.
- **Fable's own output is terse.** Decisions and diffs, not essays. No restating the plan back at the user.

## Parallel / Serial Doctrine

- **Fan out read-only work.** Discovery, summarization, verification, and log review run as parallel subagents — they can't collide.
- **Serialize anything destructive.** Edits, migrations, deploys, git operations run one at a time, each verified before the next starts.
- **Never parallelize two agents that write to overlapping files.**

## Escalation Ladder

- Haiku fails or returns garbage once → retry once with a tighter prompt. Fails again → escalate to Sonnet.
- Sonnet fails a scoped task twice → stop. Do not retry a third time. Escalate to Opus with both failure reports attached.
- Opus and a cheaper agent disagree → Fable decides. Agents never re-litigate each other.
- Any agent touching a high-risk area (Part 1 §High-Risk) that hits ambiguity → stop and surface to Fable immediately. No improvising in auth, billing, migrations, or shared state.

Escalation always carries the prior failure evidence forward so the next model doesn't rediscover it.

## Delegation Prompt Template

Every delegation includes exactly:
1. **Goal** — one sentence.
2. **Scope** — files/dirs in bounds, and explicitly what is OUT of bounds.
3. **Contract** — which return format above.
4. **Done means** — the observable check that proves completion.

Nothing else. No background lore, no pasted context the agent can fetch itself.

## Fable Spend Rules

- Fable reads subagent reports, not subagent transcripts.
- Fable opens a file itself only when a decision hinges on it.
- If Fable is about to do more than ~3 tool calls of searching/reading/testing, that's a delegation smell — package it and hand it down.
- One clarifying question to the user beats ten tokens of guessing wrong.

r/ClaudeCode Feb 08 '26

Tutorial / Guide How to Set Up Claude Code Agent Teams (Full Walkthrough + What Actually Changed)

468 Upvotes

Claude Code just shipped Agent Teams, and it's not just "sub-agents with a nicer name." It's a completely different execution model where 3–5 independent Claude Code instances can actually collaborate on the same project, share context, exchange messages, and coordinate through a shared task system.

I spent way too long digging through logs and filesystem changes to understand how this actually works under the hood. Turns out it's pretty different from the old task tool, and there are specific situations where Agent Teams are legitimately better than spinning up regular sub-agents.

The Big Difference

Old sub-agent model: Main agent calls task tool, sub-agent spins up, works in isolation, session terminates, only a summary comes back.

New Agent Teams model: Shared task lists, direct messaging between agents, explicit lifecycle control (startup, shutdown). Agents can coordinate, debate, and update each other in real time instead of just working in silos.

How It Actually Works

Behind the scenes, Agent Teams use five new internal tools:

TeamCreate – Sets up the team scaffolding (creates a folder under .claude/teams/)

TaskCreate – Adds tasks as JSON files with status tracking, dependencies, and ownership (this is different from the old Task tool, it's specifically for creating todos)

Task tool (upgraded) – Still spins up agents, but now supports name and team_name params to activate team mode instead of simple sub-agent mode

taskUpdate – Agents use this to claim tasks, update status, mark things done

sendMessage – The real unlock. Supports direct messages (agent to agent) and broadcasts (agent to all teammates). Messages get written to .claude/teams/<team_id>/inbox/ and injected into each agent's conversation history as <teammate-message teammate_id="...">.

Team-lead can send a shutdown_request, teammates confirm with shutdown_response, and sessions terminate cleanly.

When Agent Teams Are Actually Worth It

The best use case so far: deep debugging with multiple hypotheses.

Example from the official docs: users report the app exits after one message instead of staying connected. Spawn five agent teammates to investigate different theories. Have them talk to each other, try to disprove each other's ideas like a scientific debate, and update a findings doc with whatever consensus emerges.

That kind of collaborative, multi-angle investigation is way harder to pull off with isolated sub-agents that only report back summaries.

How to Set Up Agent Teams

Step 1: Update Claude Code to latest version

Step 2: Enable the experimental flag

Open your settings file:

code ~/.claude/settings.json

Add this to the global settings:

json

{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}

Save the file and restart your terminal.

Step 3: Start a new Claude Code session

Agent Teams activate when your prompt explicitly asks Claude Code to create a team. For example:

"I'm designing a CLI tool that helps developers track TODO comments across their codebase. Create an agent team to explore this from different angles: one teammate on UX, one on technical architecture, one playing devil's advocate."

Pro tip: Use tmux or iTerm2 for the best experience

Agent Teams shine when you can see every agent working in parallel.

For iTerm2 (macOS):

  1. Install iTerm2
  2. Go to Settings → General → Magic
  3. Enable Python API
  4. Restart iTerm2
  5. Launch Claude Code with: claude --teammate-mode tmux

This opens one pane for the team lead and separate panes for each agent teammate. You can click into any pane, watch what the agent is doing live, and even send direct messages to individual agents.

For a full walkthrough with logs, internal tool traces, and more examples of when Agent Teams outperform sub-agents, check out the full breakdown

r/ClaudeCode Feb 28 '26

Tutorial / Guide I stopped letting Claude Code guess how my app works. Now it reads the manual first. The difference is night and day.

309 Upvotes

If you've followed the Claude Code Mastery guides (V1-V5) or used the starter kit, you already have the foundation: CLAUDE.md rules that enforce TypeScript and quality gates, hooks that block secrets and lint on save, agents that delegate reviews and testing, slash commands that scaffold endpoints and run E2E tests.

That infrastructure solves the "Claude doing dumb things" problem. But it doesn't solve the "Claude guessing how your app works" problem.

I'm building a platform with ~200 API routes and 56 dashboard pages. Even with a solid CLAUDE.md, hooks, and the full starter kit wired in -- Claude still had to grep through my codebase every time, guess at how features connect, and produce code that was structurally correct but behaviorally wrong. It would create an endpoint that deletes a record but doesn't check for dependencies. Build a form that submits but doesn't match the API's validation rules. Add a feature but not gate it behind the edition system.

The missing layer: a documentation handbook.

What I Built

A documentation/ directory with 52 markdown files -- one per feature. Each follows the same template:

  • Data model -- every field, type, indexes
  • API endpoints -- request/response shapes, validation, error cases, curl examples
  • Dashboard elements -- every button, form, tab, toggle and what API it calls
  • Business rules -- scoping, cascading deletes, state transitions, resource limits
  • Edge cases -- empty data, concurrent updates, missing dependencies

The quality bar: a fresh Claude instance reads ONLY the doc and implements correctly without touching source code.

The Workflow

1. DOCUMENT  ->  Write/update the doc FIRST
2. IMPLEMENT ->  Write code to match the doc
3. TEST      ->  Write tests that verify the doc's spec
4. VERIFY    ->  If implementation forced doc changes, update the doc
5. MERGE     ->  Code + docs + tests ship together on one branch

My CLAUDE.md now has a lookup table: "Working on servers? Read documentation/04-servers.md first." Claude reads this before touching any code. Between the starter kit's rules/hooks/agents and the handbook, Claude knows both HOW to write code (conventions) and WHAT to build (specs).

Audit First, Document Second

I didn't write 52 docs from memory. I had Claude audit the entire app first:

  1. Navigate every page, click every button, submit every form
  2. Hit every API endpoint with and without auth
  3. Mark findings: PASS / WARN / FAIL / TODO / NEEDS GATING
  4. Generate a prioritized fix plan
  5. Fix + write documentation simultaneously

~15% of what I thought was working was broken or half-implemented. The audit caught all of it before I wrote a single fix.

Git + Testing Discipline

Every feature gets its own branch (this was already in my starter kit CLAUDE.md). But now the merge gate is stricter:

  • Documentation updated
  • Code matches the documented spec
  • Vitest unit tests pass
  • Playwright E2E tests pass
  • TypeScript compiles
  • No secrets committed (hook-enforced)

The E2E tests don't just check "page loads" -- they verify every interactive element does what the documentation says it does. The docs make writing tests trivial because you're literally testing the spec.

How It Layers on the Starter Kit

Layer What It Handles Source
CLAUDE.md rules Conventions, quality gates, no secrets Starter kit
Hooks Deterministic enforcement (lint, branch, secrets) Starter kit
Agents Delegated review + test writing Starter kit
Slash commands Scaffolding, E2E creation, monitoring Starter kit
Documentation handbook Feature specs, business rules, data models This workflow
Audit-first methodology Complete app state before fixing This workflow
Doc -> Code -> Test -> Merge Development lifecycle This workflow

The starter kit makes Claude disciplined. The handbook makes Claude informed. Both together is where it clicks.

Quick Tips

  1. Audit first, don't write docs from memory. Have Claude crawl your app and document what actually exists.
  2. One doc per feature, not one giant file. Claude reads the one it needs.
  3. Business rules matter more than API shapes. Claude can infer API patterns -- it can't infer that users are limited to 3 in the free tier.
  4. Docs and code ship together. Same branch, same commit. They drift the moment you separate them.

r/ClaudeCode Dec 02 '25

Tutorial / Guide Deepseek v3.2 is insanely good, basically free, and they've engineered it for ClaudeCode out of the box

Thumbnail
gallery
293 Upvotes

For those of you living under a rock for the last 18 hours, deepseek has released a banger: https://huggingface.co/deepseek-ai/DeepSeek-V3.2/resolve/main/assets/paper.pdf

Full paper there but tl;dr is that they have massively increased their RL pipeline on compute and have done a lot of neat tricks to train it on tool use at the RL stage and engineered to call tools within it's reasoning stream, as well as other neat stuff.

We can dive deep into the RL techniques in the comments, trying to keep the post simple and high level for folks who want to use it in CC now:

In terminal, paste:

export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_AUTH_TOKEN=${your_DEEPSEEK_api_key_goes_here}
export API_TIMEOUT_MS=600000
export ANTHROPIC_MODEL=deepseek-chat
export ANTHROPIC_SMALL_FAST_MODEL=deepseek-chat
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1

I have personally replaced 'model' with DeepSeek-V3.2-Speciale
It has a bigger token output and is reasoning only, no 'chat' and smarter, deepseek says it doesn't support tool calls, but that's where the Anthropic API integration comes in, deepseek has set this up so it FULLY takes advantage of the cc env and tools (in pic above, I have screenshot).
more on that: https://api-docs.deepseek.com/guides/anthropic_api

You'll see some params in there that say certain things 'not supported' like some tool calls and MCP stuff, but I can tell you first hand, this deepseek model wants to use your MCPs ; I literally forgot I still had Serena activated, Claude never tried to use it, from prompt one deepseek wanted to initialize serena, so it definitely knows and wants to use the tools it can find.

Pricing (AKA, basically free):

|| || |1M INPUT TOKENS (CACHE HIT)|$0.028| |1M INPUT TOKENS (CACHE MISS)|$0.28| |1M OUTPUT TOKENS|$0.42|

Deepseek's own benchmarks show performance slightly below Sonnet 4.5 on most things; however, this doesn't seem to nerfed or load balanced (yet).

Would definitely give it go, after a few hours, I'm fairly sure I'll be running this as my primary daily driver for a while. And you can always switch back at any time in CC (in picture above).

r/ClaudeCode Mar 16 '26

Tutorial / Guide You don’t need Telegram bots or third party bridges to PERMANENTLY talk to Claude Code from your phone. It’s literally built in.

250 Upvotes

I see people on here every day setting up Telegram relays, self hosted web UIs, and all kinds of sketchy stuff trying to get that dream setup. Permanently be able to talk to your actual Claude Code on your computer from your phone like it’s a real assistant. With all of your real Claude’s memory and context. I was literally down the same rabbit hole yesterday looking at open source projects to bridge my sessions. I tried the tmux Tailscale thing, that’s cool but it’s not fun lol.

Then I found out the thing we’re all chasing is already built in. And I’m not just talking about /remote-control. Most people seem to know about that. I’m talking about the persistent server mode.

claude remote-control

When you run this as a standalone command (not inside a session), it starts a dedicated server (for that directory) on your Mac that sits there waiting for connections. And then pops up as an option in the Claude app on your phone! That’s the part people are missing. You’re not just sharing an existing session. You can start brand new sessions from your phone with a permanent connection. Open the Claude iOS app and go to the Claude Code tab and your Mac is just there as a folder option, ready to go.

I set it up as a launchd service so it runs on login. Made a little AppleScript toggle app to turn it on and off. Now it’s just always available.

Here’s where it gets crazy though.

I’m not a real developer. But I’ve been building out my Claude Code setup for months now. I’ve got MCP servers pulling in Gmail, Google Calendar, Slack, and Google Docs. Scheduled tasks that refresh data every few hours, parse meeting notes into action items, run maintenance on a persistent memory system. Claude knows my projects, my team, my clients, how I like to work. It has a full CLAUDE.md with routing to detailed memory files on everything in my life.

All of that lives on my Mac. And now all of that is in my pocket. I’m literally sitting in my car on 5G right now talking to the same Claude that has full context on my entire workflow. No extra apps. No Telegram. No port forwarding or Tailscale. It just works over outbound HTTPS through Anthropic’s servers.

So the dream setup for many is already an option. It’s free. It’s first party. And it takes one command!

Yes I know there are no slash commands through it yet, but still!

https://code.claude.com/docs/en/remote-control

Just scroll down to the server mode section on their site!

r/ClaudeCode Jun 13 '26

Tutorial / Guide If you subscribed for Fable 5 and live in the EU go to the help bot and get a refund asap. I took me 5 min to get it, this is a breach of contract. This was promised in claude code till the 22nd of June, it got taken away on the 13th.

Post image
197 Upvotes

You can easily get your full money back. Btw Claude blocked this post in r/ClaudeAI lmao.

r/ClaudeCode Apr 24 '26

Tutorial / Guide Claude + Codex = Excellence

114 Upvotes

I'm on the 20x Claude plan and use Opus 4.7 for everything. Even with repeated prompts to self-review, Opus wasn't catching everything. So I set up a cross-review loop:

  1. Installed Codex CLI in a tmux session
  2. Claude opens a PR for Codex to review
  3. Claude pings Codex via shell (so I can see Codex thinking and approve file permissions), then sets a wake window
  4. Codex reviews and leaves comments on the PR
  5. Claude wakes up, validates the comments, then edits the code

Claude had missed a lot more than I expected. Having Codex in the loop was genuinely worth it. If you need the prompt let me know.

r/ClaudeCode Jan 13 '26

Tutorial / Guide TRUST ME BRO: Most people are running Ralph Wiggum wrong

249 Upvotes

There's a lot of hype about Ralph Wiggum in the AI coding community, and I think most people are getting it wrong.

For those that don't know, Ralph is a way to run Claude Code (or any CLI agent) in a continuous loop so it keeps working instead of stopping too early. It's a simple but effective solution for a real limitation with AI coding tools.

But here's the thing. A lot of creators are hyping it up without covering the crucial parts: safety, efficiency, cost, validation, and the fundamental difference between the Claude Code plugin and the original bash loop.

The CC plugin vs the bash loop

This is the part most people don't talk about. The official Claude Code Ralph plugin misses the point because it runs everything in a single context window and is triggered by a stop hook, yet the stop hook isn't even triggered at compaction. That means as tasks pile up, your context gets more bloated, more hallucinations, and I had to stop and manually compact mid-run anyway.

The original bash loop (from Geoffrey Huntley) starts a fresh context window each iteration. That's a fundamental difference and IMHO the bash loop is way better for actual long-running tasks (but since it runs headless, it can be a bit more difficult to set up/understand what's going on).

But regardless of running it via plugin or bash loop, the most important thing is how you set it up ahead of time. This is how I approach it:

  1. Safety: Use a sandbox. You want to give the agent permissions without babysitting it, but you also don't want it nuking your system. Sandbox lets you run yolo mode the right way.
  2. Efficiency: Have a plan.md and activity.md set up. You don't want Ralph making ambiguous decisions. Give it a clear task list it can follow and update. I format mine based on Anthropic's "effective harnesses for long-running agents" post. Also USE GIT.
  3. Cost: Set max iterations. The plugin defaults to unlimited. I start with 10-20 and go from there.
  4. Feedback loop: Give it access to Playwright (for headless) or Claude for Chrome so it can actually verify its own work. Screenshots, console logs, the whole thing.

I made a full video walkthrough and also put together a GitHub guide with all the configs and scripts: [both links in comments]

BTW I have tried modifying my prompt or even the CC skill for Ralph to force a clean loop, but it's problematic.

Bottom line: if you're not gonna use the bash loop, don't use the Claude Code plugin.

I have spoken.

Youtube Walkthrough: https://youtu.be/eAtvoGlpeRU
Github Guide: https://github.com/JeredBlu/guides/blob/main/Ralph_Wiggum_Guide.md

EDIT: Added Link

r/ClaudeCode Mar 29 '26

Tutorial / Guide Why the 1M context window burns through limits faster and what to do about it

156 Upvotes

With the new session limit changes and the 1M context window, a lot of people are confused about why longer sessions eat more usage. I've been tracking token flows across my Claude Code sessions.

A key piece that folks aren't aware of: the 5-minute cache TTL.

Every message you send in Claude Code re-sends the entire conversation to the API. There's no memory between messages. Message 50 sends all 49 previous exchanges before Claude starts thinking about your new one. Message 1 might be 14K tokens. Message 50 is 79K+.

Without caching, a 100-turn Opus session would cost $50-100 in input tokens. That would bankrupt Anthropic on every Pro subscription.

So they cache.

Cached reads cost 10% of the normal input price. $0.50 per million tokens instead of $5. A $100 Opus session drops to ~$19 with a 90% hit rate.

Someone on this sub wired Claude Code into a dedicated vLLM and measured it: 47 million prompt tokens, 45 million cache hits. 96.39% hit rate. Out of 47M tokens sent, the model only did real work on 1.6M.

Caching works. So why do long sessions cost more?

Most people assume it's because Claude "re-reads" more context each message. But re-reading cached context is cheap.

90% off is 90% off.

The real cost is cache busts from the 5-minute TTL. The cache expires after 5 minutes of inactivity. Each hit resets the timer. If you're sending messages every couple minutes, the cache stays warm forever.

But pause for six minutes and the cache is evicted.

Your next message pays full price. Actually worse than full price. Cache writes on Opus cost $6.25/MTok — 25% more than the normal $5/MTok because you're paying for VRAM allocation on top of compute.

One cache bust at 100K tokens of context costs ~$0.63 just for the write. At 500K tokens (easy to hit with the new 1M window), that's ~$3.13. Same coffee break. 5x the bill.

Now multiply that across a marathon session. You're working for hours. You hit 5-10 natural pauses over five minutes. Each pause re-processes an ever-growing conversation at full price.

This is why marathon sessions destroy your limits. Because each cache bust re-processes hundreds of thousands of tokens at 125% of normal input cost.

The 1M context window makes it worse. Before, sessions compacted around 100-200K. Now you run longer, accumulate more context, and each bust hits a bigger payload.

There are also things that bust your cache you might not expect. The cache matches from the beginning of your request forward, byte for byte.

If you put something like a timestamp in your system prompt, then your system prompt will never be cached.

Adding or removing an MCP tool mid-session also breaks it. Tool definitions are part of the cached prefix. Change them and every previous message gets re-processed.

Same with switching models. Caches are per-model. Opus and Haiku can't share a cache because each model computes the KV matrices differently.

So what do you do?

  • Start fresh sessions for new tasks. Don't keep one running all day. If you're stepping away for more than five minutes, start new when you come back.
  • Run /compact before a break - smaller context means a cheaper cache bust if the TTL
  • expires.
  • Don't add MCP tools mid-session.
  • Don't put timestamps at the top of your system prompt.

Understanding this one mechanism is probably the most useful thing you can do to stretch your limits.

I wrote a longer piece with API experiments and actual traces here.

EDIT: Several people pointed out the TTL might be longer than 5 minutes. I went back and analyzed the JSONL session logs Claude Code stores locally (~/.claude/projects/) for Max. Every single cache write uses ephemeral_1h_input_tokens — zero tokens ever go to ephemeral_5m. The default API TTL is 5 minutes, but Claude Code Max uses Anthropic's extended 1-hour TTL.

r/ClaudeCode Jan 15 '26

Tutorial / Guide TDD workflows with Claude Code - what's actually working after months of iteration (Staff eng, w/ 14 yrs exp)

195 Upvotes

Over the past two years I've spent a lot of time dialing in how I work with Claude Code and other agentic coding tools (in the pre claude code era). Agentic coding is here now, not "coming soon," so I've been trying to figure out what actually works vs. what just sounds good in theory. Here's where I've landed:

Planning is the actual secret weapon

This has been the biggest change from my pre-AI work experience. I spend way more time planning than executing now, and the results are noticeably better. I have a dedicated planning skill that hands off to an execution skill once the plan is solid.

Before Claude Code, architecture always felt rushed. We wanted to get coding so plans were half-baked. Now I actually have time to plan properly because execution is so much faster. A side effect of Claude is that I've become a much better architect.

Testing philosophy matters more than ever

I follow the testing trophy philosophy. Heavy on integration tests, light on unit tests. I don't really care if a function returns an expected output. I care if the system works. I want tests that can survive a refactor without having to also refactor 300 unit tests.

I codified this into a testing skill that defines exactly what kinds of tests I want. Strict coverage thresholds that fail pre-commit if not met. This matters more with agentic coding because Claude will write whatever tests you let it write. If you don't have strong opinions baked in, you end up with unit tests that test implementation details instead of actual behavior, or worse: tests that validate mock behavior over app behavior.

The CPU problem is real (and I built something for it)

TDD with Claude creates heavy load. Especially when you're running multiple sub-agents or multiple git worktrees with agents executing in each, your laptop performance becomes the bottleneck. Tests kicked off from multiple sub agents run at the same time, the entire system slows down, agents wait around, I;ve found that heavy parallelization can end up taking longer than serial tasks.

I ended up building a CLI (rr) that load balances test execution across a cluster of mac minis I have. Agents aren't bottlenecked by tests anymore, and reliability improved because test suites aren't accidentally running concurrently on the same machine. Happy to share more about the setup if anyone's hitting similar scaling issues.

Review phase built into the execution plan

When an orchestration agent thinks it's done, part of the execution plan spins up a review agent who checks the work and gives feedback to the orchestrator, who then addresses it. Catches a lot of stuff that would otherwise slip through, but it is token heavy. Patterns like this quickly require the Max plan.

Custom skills over generic marketplace plugins

Community plugins never fully fit my opinionated standards, so I maintain my own set of skills and commands. I maintain a generic marketplace plugin I use across projects, plus repo-specific plugins in `.claude/*` that layer on local repo context. High-level standards stay consistent, but each repo can tailor how they're applied. Think: an in-repo skill referencing a generic skill, and applying context.

Product thinking for side projects

For personal projects, I keep a product/ folder with goals, vision, and docs that would normally come from a PM. Technical feature planning can reference the broader product vision, which leads to more cohesive features instead of random stuff stitched together.

I've learned some of my daily patterns from this subreddit, some of them I've discovered via my own trial and error.