
Building a Blame Graph Memory Layer: Teaching AI Agents Why Your Code Existed
A hands-on guide to building a 'blame graph' memory layer that gives AI coding agents historical context from git blame, so they stop deleting code they don't understand.
Every AI coding agent has the same blind spot: it sees the file as it exists right now, not the thousand small decisions that shaped it. When an agent refactors a legacy parser and deletes a 40-line block, it isn't being malicious — it's being ignorant. It has no memory of the #ifdef that guards a platform-specific path, the regex that was tuned over three commits to fix a crash, or the workaround that exists only because a dependency hasn't shipped a fix yet.
Git already stores all of that memory. It's called blame. The problem is that no agent actually reads it before it deletes code. This tutorial builds a Blame Graph — a queryable memory layer that maps every line of code to the commit that introduced it, the author's intent, and the surrounding semantic context — and wires it into an agent's decision loop as a deletion guardrail.
By the end, you'll have a working TypeScript module that parses git blame, extracts reasons from commit history, builds an in-memory graph, and answers the question an agent should always ask before deleting: "Why does this line exist?"
- 1. Why AI Agents Forget Why Code Exists
- 2. What Is a Blame Graph?
- 3. Architecture Overview
- 4. Prerequisites
- 5. Step 1 — Harvesting Blame Data from Git
- 6. Step 2 — Parsing Blame into a Graph
- 7. Step 3 — Extracting Semantic Reasons from Commit History
- 8. Step 4 — Building a Queryable Memory Index
- 9. Step 5 — Wiring the Blame Graph into the Agent Loop
- 10. Production Considerations
- 11. Frequently Asked Questions
1. Why AI Agents Forget Why Code Exists
An AI agent operates on a snapshot. It reads files into a context window, reasons about the current state, and produces a diff. It has no access to the history of those lines unless the tooling explicitly provides it. The result is a class of failure that every agentic coding tool has hit:
- Silent regression: An agent removes a fallback branch that it deems dead code, but that branch was the only thing handling a legacy browser quirk. Tests pass, production breaks.
- Semantic drift: An agent "simplifies" a complex condition, unaware that the complexity was the fix for a specific race condition.
- Wasted rework: An agent deletes a workaround, then a human has to re-add it with a comment that says "Do not remove — see #4821."
The root cause is a missing context dimension. Git blame is the cheapest, most reliable source of that dimension. Every line in your repository carries a pointer to the commit that last touched it, and that commit carries a message, an author, a timestamp, and — crucially — a reason.
2. What Is a Blame Graph?
A Blame Graph is a directed graph where:
- Nodes are individual lines of code, keyed by
(commitHash, filename, lineNumber). - Edges connect a line to the lines it was adjacent to in the same commit, and to the lines it replaced in the parent commit.
- Metadata on each node includes the commit summary, author, timestamp, and any extracted semantic signals (issue links, conventional-commit type, keywords).
Think of it as a per-line changelog that's structured for retrieval rather than display. Instead of reading git blame output as a flat table, you query it as a graph: "What lines were introduced in the same commit as this one?" or "What did the author say when they added this branch?"
This is different from a naive git blame dump. The graph captures co-change relationships — lines that were added together tend to be semantically related, even if they're far apart in the file. That's exactly the context an agent needs when it's considering a deletion that spans multiple hunks.
3. Architecture Overview
The system has five layers:
┌─────────────────────────────────────────────────────┐
│ Agent Loop (Cline / Aider / custom) │
│ ┌───────────────────────────────────────────────┐ │
│ │ Deletion Guardrail (Step 5) │ │
│ └───────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────┤
│ Query Layer (Step 4) │
│ Semantic search + graph traversal │
├─────────────────────────────────────────────────────┤
│ Graph Store (Step 2) │
│ In-memory Map + adjacency lists │
├─────────────────────────────────────────────────────┤
│ Reason Extractor (Step 3) │
│ Commit messages → structured reasons │
├─────────────────────────────────────────────────────┤
│ Blame Harvester (Step 1) │
│ git blame --line-porcelain → parsed records │
└─────────────────────────────────────────────────────┘
The harvester and extractor run once per repository (or on a schedule). The graph store lives in memory (or Redis for large repos). The query layer serves the guardrail, which sits between the agent's intent and its diff.
4. Prerequisites
- Node.js 18+ and npm.
- Git 2.30+ on the system.
- A repository with meaningful commit history (any size works, but a repo with 500+ commits will demonstrate the value better).
- Optional: an embedding API (OpenAI, Voyage, or a local model via Ollama) for semantic search. If you skip it, the query layer falls back to keyword matching.
Create a project and install dependencies:
mkdir blame-graph
cd blame-graph
npm init -y
npm install typescript tsx @types/node
npx tsc --init --target ES2022 --module NodeNext --moduleResolution NodeNext --outDir dist
5. Step 1 — Harvesting Blame Data from Git
The foundation is git blame --line-porcelain, which emits machine-readable records rather than the human-friendly colored output. Let's see what it looks like:
git blame --line-porcelain src/parser.ts | head -40
Each line group starts with a commit hash (40 hex chars) followed by metadata keys. The interesting ones for our purposes:
author,author-mail,author-time— who and when.summary— the commit subject, which is often the best one-line reason.- The actual source line follows after the metadata block.
We'll write a harvester that shells out to git and parses this output into structured records. Here's the complete module:
// src/harvester.ts
import { execSync } from 'node:child_process';
export interface BlameRecord {
lineNumber: number;
commitHash: string;
author: string;
authorEmail: string;
authorTime: number;
summary: string;
filename: string;
content: string;
}
/**
* Runs `git blame --line-porcelain` on a file and parses the output.
*
* The porcelain format groups lines by commit. Each group begins with
* the commit hash, followed by metadata lines (author, author-mail,
* author-time, summary), then the tab-prefixed source line.
*/
export function harvestBlame(
filePath: string,
repoRoot: string = process.cwd()
): BlameRecord[] {
const output = execSync(
`git blame --line-porcelain -- ${filePath}`,
{ cwd: repoRoot, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 }
);
const records: BlameRecord[] = [];
const lines = output.split('\n');
let currentCommit = '';
let currentAuthor = '';
let currentEmail = '';
let currentTime = 0;
let currentSummary = '';
let lineNumber = 0;
for (const raw of lines) {
// A line starting with 40 hex chars begins a new commit group.
if (/^[0-9a-f]{40}$/.test(raw)) {
currentCommit = raw;
continue;
}
// Metadata lines are key-value pairs with a space separator.
if (raw.startsWith('author ')) {
currentAuthor = raw.slice(7);
} else if (raw.startsWith('author-mail ')) {
currentEmail = raw.slice(12).replace(/[<>]/g, '');
} else if (raw.startsWith('author-time ')) {
currentTime = parseInt(raw.slice(12), 10);
} else if (raw.startsWith('summary ')) {
currentSummary = raw.slice(8);
}
// Source lines are prefixed with a tab. The line number is tracked
// separately because porcelain output doesn't include it inline.
if (raw.startsWith('\t')) {
lineNumber += 1;
records.push({
lineNumber,
commitHash: currentCommit,
author: currentAuthor,
authorEmail: currentEmail,
authorTime: currentTime,
summary: currentSummary,
filename: filePath,
content: raw.slice(1),
});
}
}
return records;
}
What this does: It executes git blame, tracks the current commit group, and emits one BlameRecord per source line. The lineNumber is inferred from the sequence of tab-prefixed lines, which matches git's 1-based line numbering.
6. Step 2 — Parsing Blame into a Graph
Now we turn the flat records into a graph. The key insight is that lines introduced in the same commit are semantically linked — they were part of one change. We'll build adjacency lists based on that co-change relationship, plus a link from each line to the commit that introduced it.
// src/graph.ts
import { BlameRecord } from './harvester';
export interface BlameNode {
id: string; // `${commitHash}:${filename}:${lineNumber}`
commitHash: string;
filename: string;
lineNumber: number;
content: string;
summary: string;
author: string;
timestamp: number;
// Lines introduced in the same commit (co-change edges).
siblings: Set<string>;
}
export class BlameGraph {
private nodes = new Map<string, BlameNode>();
private byFile = new Map<string, BlameNode[]>();
private byCommit = new Map<string, BlameNode[]>();
constructor(records: BlameRecord[]) {
this.build(records);
}
private build(records: BlameRecord[]): void {
// First pass: create nodes.
for (const rec of records) {
const id = `${rec.commitHash}:${rec.filename}:${rec.lineNumber}`;
const node: BlameNode = {
id,
commitHash: rec.commitHash,
filename: rec.filename,
lineNumber: rec.lineNumber,
content: rec.content,
summary: rec.summary,
author: rec.author,
timestamp: rec.authorTime,
siblings: new Set(),
};
this.nodes.set(id, node);
if (!this.byFile.has(rec.filename)) this.byFile.set(rec.filename, []);
this.byFile.get(rec.filename)!.push(node);
if (!this.byCommit.has(rec.commitHash)) this.byCommit.set(rec.commitHash, []);
this.byCommit.get(rec.commitHash)!.push(node);
}
// Second pass: wire co-change edges. Lines from the same commit
// in the same file are siblings.
for (const [, commitNodes] of this.byCommit) {
const byFileMap = new Map<string, BlameNode[]>();
for (const node of commitNodes) {
if (!byFileMap.has(node.filename)) byFileMap.set(node.filename, []);
byFileMap.get(node.filename)!.push(node);
}
for (const [, fileNodes] of byFileMap) {
for (const node of fileNodes) {
for (const other of fileNodes) {
if (node.id !== other.id) node.siblings.add(other.id);
}
}
}
}
}
getNode(id: string): BlameNode | undefined {
return this.nodes.get(id);
}
getLinesInFile(filename: string): BlameNode[] {
return this.byFile.get(filename) ?? [];
}
getLinesInCommit(commitHash: string): BlameNode[] {
return this.byCommit.get(commitHash) ?? [];
}
/**
* Returns the nodes for a line range in a file, sorted by line number.
* This is the primary lookup the guardrail will use.
*/
getRange(filename: string, startLine: number, endLine: number): BlameNode[] {
return this.getLinesInFile(filename)
.filter((n) => n.lineNumber >= startLine && n.lineNumber <= endLine)
.sort((a, b) => a.lineNumber - b.lineNumber);
}
/**
* Returns all sibling nodes (co-changed lines) for a given node,
* across the whole repository.
*/
getSiblings(nodeId: string): BlameNode[] {
const node = this.nodes.get(nodeId);
if (!node) return [];
return [...node.siblings]
.map((id) => this.nodes.get(id))
.filter((n): n is BlameNode => n !== undefined);
}
get size(): number {
return this.nodes.size;
}
}
What this does: It builds a bidirectional graph. getRange is the workhorse — given a file and line range an agent wants to delete, it returns the exact nodes with their commit metadata. getSiblings lets you expand the context to the whole commit that introduced a line, which often reveals the "why" in surrounding lines.
7. Step 3 — Extracting Semantic Reasons from Commit History
A commit summary like fix: handle null in parser is a reason, but it's thin. We can enrich it by pulling the full commit body, extracting issue references, and classifying the conventional-commit type. This gives the guardrail a richer signal to pass to the LLM.
// src/reason-extractor.ts
import { execSync } from 'node:child_process';
export interface CommitReason {
commitHash: string;
subject: string;
body: string;
type: 'fix' | 'feat' | 'refactor' | 'perf' | 'chore' | 'docs' | 'unknown';
issues: string[];
breaking: boolean;
keywords: string[];
}
const KEYWORD_PATTERNS: Array<[string, RegExp]> = [
['workaround', /workaround|hack|temporary|temporarily|hotfix/i],
['regression', /regression|revert|rollback|break/i],
['race', /race|concurrency|async|deadlock|lock/i],
['compat', /compat|legacy|browser|ie11|safari|firefox/i],
['security', /security|cve|xss|injection|sanitize/i],
['performance', /performance|perf|slow|latency|optimize/i],
];
/**
* Fetches the full commit message and extracts structured reasons.
*/
export function extractCommitReason(
commitHash: string,
repoRoot: string = process.cwd()
): CommitReason {
const raw = execSync(
`git log -1 --format=%B ${commitHash}`,
{ cwd: repoRoot, encoding: 'utf-8' }
).trim();
const lines = raw.split('\n');
const subject = lines[0] ?? '';
const body = lines.slice(1).join(' ').trim();
// Conventional commit type: "fix: ...", "feat(scope): ..."
const typeMatch = subject.match(/^(\w+)(?:\([^)]*\))?!?:/);
const type = (typeMatch?.[1] as CommitReason['type']) ?? 'unknown';
const breaking = subject.includes('!') || /^BREAKING CHANGE:/m.test(raw);
// Issue references: #123, GH-123, JIRA-123
const issues = [...raw.matchAll(/(?:#|GH-)(\d+)/g)].map((m) => m[1]);
// Keyword classification for semantic search
const keywords: string[] = [];
for (const [label, pattern] of KEYWORD_PATTERNS) {
if (pattern.test(raw)) keywords.push(label);
}
return {
commitHash,
subject,
body,
type,
issues,
breaking,
keywords,
};
}
What this does: It turns a commit hash into a structured reason. The keywords array is especially useful — when an agent is about to delete a line whose commit has the workaround keyword, the guardrail can immediately flag it as high-risk without even calling an LLM.
8. Step 4 — Building a Queryable Memory Index
A raw graph is useful, but agents ask fuzzy questions: "Why is this fallback here?" or "What was the context when this condition was added?". To answer those, we need a retrieval layer. We'll implement two retrieval modes:
- Keyword matching — zero-dependency, fast, good enough for exact terms.
- Semantic embedding search — optional, uses any embedding API to find lines whose meaning matches the query even when words differ.
// src/retriever.ts
import { BlameGraph, BlameNode } from './graph';
export interface RetrievalResult {
node: BlameNode;
score: number;
}
export type EmbeddingFn = (text: string) => Promise<number[]>;
function cosineSimilarity(a: number[], b: number[]): number {
if (a.length !== b.length) return 0;
let dot = 0;
let magA = 0;
let magB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
magA += a[i] * a[i];
magB += b[i] * b[i];
}
if (magA === 0 || magB === 0) return 0;
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
}
/**
* Retrieves the most relevant lines for a query using keyword overlap.
* This is the fallback when no embedding function is provided.
*/
export function keywordRetrieve(
graph: BlameGraph,
query: string,
limit = 10
): RetrievalResult[] {
const terms = query.toLowerCase().split(/\W+/).filter(Boolean);
const results: RetrievalResult[] = [];
for (const node of allNodes(graph)) {
const haystack = `${node.summary} ${node.content} ${node.author}`.toLowerCase();
let score = 0;
for (const term of terms) {
if (haystack.includes(term)) score += 1;
}
if (score > 0) results.push({ node, score });
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
}
/**
* Retrieves the most semantically similar lines using embeddings.
* Requires an embedding function that returns normalized vectors.
*/
export async function semanticRetrieve(
graph: BlameGraph,
query: string,
embed: EmbeddingFn,
limit = 10
): Promise<RetrievalResult[]> {
const queryEmbedding = await embed(query);
const results: RetrievalResult[] = [];
for (const node of allNodes(graph)) {
const nodeEmbedding = await embed(`${node.summary} ${node.content}`);
const score = cosineSimilarity(queryEmbedding, nodeEmbedding);
if (score > 0.6) results.push({ node, score });
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
}
function* allNodes(graph: BlameGraph): Generator<BlameNode> {
// We need a way to iterate all nodes. Add this to BlameGraph or
// expose a method. For brevity, we assume a `values()` method.
for (const node of (graph as any).nodes.values()) {
yield node;
}
}
What this does: keywordRetrieve is synchronous and dependency-free — perfect for a fast pre-filter. semanticRetrieve is async and needs an embedding function, but it catches lines whose meaning matches even when the words don't. In production you'd cache embeddings per node to avoid re-embedding on every query.
9. Step 5 — Wiring the Blame Graph into the Agent Loop
This is where the memory layer becomes a guardrail. We'll write a function that an agent calls before it emits a deletion. It collects the blame nodes for the target range, extracts their reasons, and asks an LLM for a verdict with that context.
// src/guardrail.ts
import { BlameGraph } from './graph';
import { extractCommitReason } from './reason-extractor';
import { semanticRetrieve } from './retriever';
export interface DeletionVerdict {
allowed: boolean;
risk: 'low' | 'medium' | 'high';
rationale: string;
reasons: string[];
}
export interface LLMClient {
complete(prompt: string): Promise<string>;
}
/**
* Evaluates a proposed deletion against the blame graph.
*
* @param graph - The built blame graph.
* @param filename - The file being modified.
* @param startLine - First line to delete (1-based).
* @param endLine - Last line to delete (inclusive).
* @param llm - Optional LLM client for the final verdict.
*/
export async function evaluateDeletion(
graph: BlameGraph,
filename: string,
startLine: number,
endLine: number,
llm?: LLMClient
): Promise<DeletionVerdict> {
const nodes = graph.getRange(filename, startLine, endLine);
if (nodes.length === 0) {
return {
allowed: true,
risk: 'low',
rationale: 'No blame data found for this range.',
reasons: [],
};
}
// Collect reasons from each unique commit in the range.
const commitHashes = [...new Set(nodes.map((n) => n.commitHash))];
const reasons = commitHashes.map((hash) => {
const reason = extractCommitReason(hash);
return `[${reason.type}] ${reason.subject}${reason.issues.length ? ` (issues: ${reason.issues.join(', ')})` : ''}`;
});
// Risk heuristic: any workaround, regression, or breaking change
// in the introducing commits bumps the risk level.
const highRiskKeywords = ['workaround', 'regression', 'breaking', 'security'];
let risk: DeletionVerdict['risk'] = 'low';
for (const hash of commitHashes) {
const reason = extractCommitReason(hash);
if (reason.breaking || reason.keywords.some((k) => highRiskKeywords.includes(k))) {
risk = 'high';
break;
}
if (reason.type === 'fix' || reason.keywords.includes('race')) {
risk = 'medium';
}
}
// If no LLM is provided, fall back to the heuristic verdict.
if (!llm) {
return {
allowed: risk !== 'high',
risk,
rationale:
risk === 'high'
? 'These lines were introduced by a commit marked as workaround/regression/security. Deletion is blocked.'
: 'Heuristic check passed.',
reasons,
};
}
// Otherwise, ask the LLM to make the final call with full context.
const context = nodes
.map(
(n) =>
`Line ${n.lineNumber}: ${n.content} (added by ${n.author} in ${n.summary})`
)
.join('\n');
const prompt = `You are reviewing a proposed code deletion.
File: ${filename}
Lines to delete: ${startLine}-${endLine}
Code and historical context:
${context}
Commit reasons:
${reasons.join('\n')}
Should this deletion proceed? Answer with JSON:
{"allowed": boolean, "rationale": string}`;
const response = await llm.complete(prompt);
const parsed = JSON.parse(response) as { allowed: boolean; rationale: string };
return {
allowed: parsed.allowed,
risk,
rationale: parsed.rationale,
reasons,
};
}
What this does: It turns the blame graph into a decision gate. The heuristic path is instant and blocks the most dangerous deletions (workarounds, security fixes, breaking changes). The LLM path adds nuance — it reads the actual reasons and can allow a deletion that looks risky but is actually safe, or block one that looks innocent but isn't.
Putting It All Together
Here's a complete driver that builds the graph, retrieves context, and evaluates a hypothetical deletion:
// src/index.ts
import { harvestBlame } from './harvester';
import { BlameGraph } from './graph';
import { evaluateDeletion } from './guardrail';
import { keywordRetrieve } from './retriever';
async function main() {
const file = 'src/legacy/parser.ts';
// 1. Harvest and build the graph.
const records = harvestBlame(file);
const graph = new BlameGraph(records);
console.log(`Graph built: ${graph.size} nodes for ${file}`);
// 2. Query: "Why does this fallback exist?"
const results = keywordRetrieve(graph, 'fallback null parser');
console.log('Top matches:');
for (const { node, score } of results.slice(0, 3)) {
console.log(` [${score}] line ${node.lineNumber}: ${node.content.trim()}`);
console.log(` reason: ${node.summary}`);
}
// 3. Evaluate a proposed deletion (lines 120-135).
const verdict = await evaluateDeletion(graph, file, 120, 135);
console.log(`\nDeletion verdict: ${verdict.allowed ? 'ALLOWED' : 'BLOCKED'} (risk: ${verdict.risk})`);
console.log(`Rationale: ${verdict.rationale}`);
}
main().catch(console.error);
Run it with:
npx tsx src/index.ts
10. Production Considerations
The prototype above works on a single file. A real production system needs to handle scale and freshness:
- Repository-wide harvesting: Run
git blameper file, but batch it. For large repos, usegit blame --line-porcelainon a file list with--incrementalor parallelize across files with a worker pool. - Incremental updates: Re-blame only files touched since the last run. Track the last harvested commit SHA and use
git diff --name-only <lastSha> HEADto find changed files. - Graph storage: For repos with >100k lines, an in-memory
Mapis fine (roughly 200-400 bytes per node). For multi-million-line monorepos, back the graph with Redis or SQLite. Store nodes as hashes and edges as sorted sets. - Embedding caching:
semanticRetrievere-embeds every node on every query, which is O(N) per call. Cache embeddings in a key-value store keyed bycommitHash:filename:lineNumber. Invalidate on re-blame. - LLM cost control: The guardrail should only call the LLM when the heuristic risk is
mediumor when the agent explicitly requests it. High-risk deletions are blocked without an LLM call; low-risk ones are allowed without one. - The
git blameperformance trap:git blameis O(history) per file. For files with deep history, usegit blame --first-parentto follow only the mainline, or-L <start>,<end>to blame only the range you care about.
11. Frequently Asked Questions
Does this work with monorepos or just single repos?
Both. The harvester takes a repoRoot argument, so you can point it at a monorepo root and pass file paths relative to that root. The graph keys include the filename, so files from different packages don't collide. For very large monorepos, consider partitioning the graph by package and loading only the relevant partition into memory.
What if a line was introduced by a merge commit? Does the reason get lost?
git blame follows the diff history, so it will typically attribute lines to the commit that last modified them, not the merge itself. If you want merge context, you can additionally run git log --first-parent --oneline <commitHash> -1 to get the merge message, and store it as a secondary reason on the node.
How do I handle a line that was moved without being modified?
Git blame by default tracks line movement within a file. If a line was moved from one function to another without changes, blame will still attribute it to the original commit. That's usually the desired behavior — the reason for the line hasn't changed, only its location. If you want to detect moves, compare the node's lineNumber against the parent commit's blame output for the same content.
This article is part of a series on building memory layers for AI coding agents. For more on agent tooling and developer infrastructure, see Tamiz's Insights or explore the main site.