Skip to content
gentic.news — AI News Intelligence Platform
Connecting to the Living Graph…

Listen to today's AI briefing

Daily podcast — 5 min, AI-narrated summary of top stories

A developer at a terminal reviewing code changes while an AI assistant suggests refactors, with a warning message…

Stop AI Refactors From Breaking Production: Add git log -L to Your CLAUDE.md

Add a git log -L rule to CLAUDE.md. It forces Claude Code to check commit history before editing existing code, cutting 'confident but wrong' refactors for ~6% overhead. The agent also writes why-comments back into the code, compounding the fix.

·16h ago·6 min read··11 views·AI-Generated·Report error
Share:
Source: dev.tovia devto_claudecodeCorroborated
How do I stop Claude Code from breaking working code during refactors?

Add a rule to CLAUDE.md: before modifying any function you didn't author this session, run `git log -L <start>,<end>:<file> --follow -3`. Read commit messages for keywords like 'workaround', 'race', or 'incident'. If found, treat the code as load-bearing and preserve it.

TL;DR

Before your agent edits code it didn't write, force a git log -L check. It cuts 'confident but wrong' refactors dramatically for ~6% wall-clock overhead.

Key Takeaways

  • Add a git log -L rule to CLAUDE.md.
  • It forces Claude Code to check commit history before editing existing code, cutting 'confident but wrong' refactors for ~6% overhead.
  • The agent also writes why-comments back into the code, compounding the fix.

The Problem: Confident But Wrong Refactors

A few months into running an autonomous coding agent (built on Claude Code) across real projects, a developer noticed a pattern in its failures. It wasn't crashing. It wasn't writing broken code. It was doing something worse: writing code that looked correct and was subtly wrong, because it didn't understand why the existing code was weird.

Concrete examples from the logs:

  • A setTimeout(fn, 0) that looked like a bug. It wasn't — it was a deliberate workaround for a browser paint-order issue from two years earlier. The agent "cleaned it up" and removed it. The bug came back three days later.
  • A retry loop with a suspiciously specific max_retries = 7. Someone had tuned that number against a flaky third-party API. The agent rounded it to 3 because "that's more standard." Timeouts spiked.
  • A duplicated validation check that looked like copy-paste laziness. It was actually defense-in-depth against a race condition between two services. The agent deduplicated it. The race condition came back.

None of these were reasoning failures in the traditional sense. The agent's logic, given what it could see, was completely sound. The problem was that it could only see the current state of the code — not the history that explained why the current state existed. It was optimizing for local readability without knowing it was destroying institutional memory buried in a commit message from 18 months ago.

The Fix: A 'Why Does This Exist' Step

The fix ended up being simpler than expected: force a "why does this exist" step before any edit to code the agent didn't just write itself in the current session.

Here's the workflow:

  1. Agent wants to edit function X
  2. Did I write X this session? If yes, edit directly.
  3. If no, run git log -L for X's line range
  4. Run git blame + read commit message and linked PR/issue if any
  5. Does the commit message explain an intentional constraint? If yes, preserve it and note it in the edit rationale. If no, edit directly.

In practice, this is a short instruction block in the agent's operating rules (CLAUDE.md):

Before modifying any function or block you did not author in this
session, run:

  git log -L <start_line>,<end_line>:<file> --follow -3

Read the commit messages. If a commit message references a bug fix,
workaround, race condition, or specific numeric tuning, treat that
code as load-bearing until proven otherwise. State explicitly in your
plan why it's safe to change, or leave it alone.

Why git log -L Instead of git blame

The key design choice: this isn't "always read full git history for every file" (way too slow, way too much context burned). It's scoped to the exact line range being touched, using git log -L, which git supports natively for tracking a function or line range across its whole history — including through renames with --follow.

Here's a real trimmed-down transcript from a session where this caught something:

$ git log -L 42,45:src/sync/retry.py --follow -3

commit 8f3a1c2
Date:   Tue Feb 3 2026
    Bump retry ceiling to 7 — vendor API rate-limits burst
    to 5 req/s with a ~6s cooldown, saw premature failures
    at max_retries=3 in prod (incident #482).

@@ -39,7 +39,7 @@ def sync_with_retry(payload):
     backoff = min(2 ** attempt, 30)
-    max_retries = 3
+    max_retries = 7

The agent's plan output after reading this:

max_retries=7 is tuned against a specific vendor rate limit (incident #482), not a magic number. Leaving it as-is. Will add a comment linking the commit so this doesn't get "cleaned up" again.

That last line — adding a comment that explains the why, not just the what — turned out to be one of the highest-leverage side effects. The agent started closing the same information gap for the next agent (or human) that touches the code, instead of just avoiding the mistake itself once.

Gating: Don't Run It On Every Edit

Claude Code Section 4: Production Mastery — 7 Advanced ...

You don't want this running on every single edit — that's wasted tokens and wasted time on greenfield code with no history worth reading. Gate it behind a simple heuristic: trigger the git-blame check only when the agent is about to modify (not create) a block of ≥3 lines it didn't write in the current session, and skip it entirely for pure additions, new files, and formatting-only changes.

The False Positive That Almost Made It Get Ripped Out

Early on, the rule was too aggressive. The developer initially had the agent treat any commit message longer than one line as a sign of "intentional, load-bearing code" — which meant it started refusing to touch perfectly ordinary code that just happened to have a verbose commit message. The agent got overly cautious and started asking for confirmation on things that were completely safe to change.

The fix was narrowing the trigger condition to specific keywords and patterns in the commit message — "fix", "workaround", "race", "regression", "incident", specific numeric tuning changes, or a linked ticket/incident number — rather than "message exists and is long." That cut the false-positive rate way down without losing the cases that actually mattered.

What It Costs

Each git log -L check adds maybe 1-3 seconds and a few hundred tokens of context per triggered edit. On a session with heavy refactoring — say 40-50 edits to existing code — that's a real but modest tax. Measured on a mid-sized refactor session: total wall-clock time went up by about 6%, token usage by about 4%. In exchange, the "silently reintroduced bug" pattern that used to show up roughly once a week stopped.

Lessons Learned

  1. Code history is a form of context the model can't infer — you have to hand it over. An agent reasoning purely from the current file state will always favor "clean" over "correct" when the two silently diverge.
  2. git log -L is underrated for this. Most people (and most agents) reach for git blame on the whole file, which is noisy. Scoping to the exact line range with -L gives a much cleaner signal with far less token spend.
  3. The fix compounds if the agent writes the "why" back into the code. The real win wasn't avoiding a bad edit once — it was leaving a trail so the next pass doesn't have to rediscover the same history from scratch.
  4. This doesn't catch everything. If the original commit message is bad ("fix bug", "update logic"), this workflow finds nothing useful. Garbage history in, garbage signal out.
  5. Gate it, don't blanket it. Running a history check before every single edit sounds safer but isn't — it burns context on code that has no relevant history and trains you to ignore the output because it's mostly noise.

Source: dev.to

Source: gentic.news · · author= · citation.json

AI-assisted reporting. Generated by gentic.news from multiple verified sources, fact-checked against the Living Graph of 4,300+ entities. Edited by Ala SMITH.

Following this story?

Get a weekly digest with AI predictions, trends, and analysis — free.

AI Analysis

Claude Code users should immediately add the git log -L rule to their CLAUDE.md file. The key insight is that the model's reasoning is sound given what it can see — the failure is a *visibility* problem, not a reasoning problem. By forcing a history check scoped to the exact line range being modified, you hand the agent the context it needs to distinguish between "arbitrary-looking code" and "load-bearing constraints." The keyword-based gating ("fix", "workaround", "race", "regression", "incident", numeric tuning) is critical to avoid the false-positive trap where the agent becomes paralyzed by verbose but irrelevant commit messages. The compounding effect is worth emphasizing: instruct your agent to write a comment linking the commit when it preserves a constraint. This means every refactor session leaves the codebase in a better state for the *next* agent or human. Over time, this transforms your codebase's institutional memory from buried git history into visible inline documentation. The 6% wall-clock and 4% token overhead is a small price for eliminating the "silently reintroduced bug" pattern that erodes trust in autonomous agents. Measure it on your own workload, but the trade is likely worth it for any project with more than a few weeks of history.
This story is part of
The Protocol Schism: Anthropic's MCP Stack vs. OpenAI's Agent Lock-In
How a developer convention is splitting AI into two incompatible ecosystems, with Meta and Google caught in the middle
Compare side-by-side
git log -L vs CLAUDE.md

Mentioned in this article

Enjoyed this article?
Share:

AI Toolslive

Five one-click lenses on this article. Cached for 24h.

Pick a tool above to generate an instant lens on this article.

Related Articles

From the lab

The framework underneath this story

Every article on this site sits on top of one engine and one framework — both built by the lab.

More in Products & Launches

View all