Skip to content

hookCode quality

Block Generated File Edits

A Claude Code hook that refuses edits to files whose first lines say they are generated, so the agent changes the source and not the output.

npx workspacetemplates add block-generated-file-edits --tool claude-code

Writes 1 file to .claude/

.claude/settings.jsonmerge into your file16 lines · 949 BFile
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "node -e \"process.on('uncaughtException',()=>process.exit(0));let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{let j={};try{j=JSON.parse(d)||{}}catch(e){process.exit(0)}const i=j.tool_input||{};const f=String(i.file_path||'');const fs=require('fs');if(!f||!fs.existsSync(f))process.exit(0);let h='';try{h=fs.readFileSync(f,'utf8').slice(0,1500)}catch(e){process.exit(0)}const m=h.split('\\n').slice(0,10).join('\\n').match(/@generated|do not edit|auto-?generated|code generated|generated by|this file is generated/i);if(m){console.error('Blocked: '+f+' is marked as generated ('+m[0]+'). Change the source or the generator and regenerate it instead of editing the output.');process.exit(2)}process.exit(0)})\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

What it does

Generated files get overwritten the next time the generator runs, so any hand edit is lost work. This PreToolUse hook opens the target file before an Edit or Write and looks at its first ten lines for markers such as @generated, DO NOT EDIT or Code generated by.

When it finds one it stops the edit and tells the agent to change the generator input instead. New files and files without a marker pass straight through.

Example

you › Add a field to the User type in src/gen/user.pb.go.

agent › The edit is blocked because the header says Code generated by protoc. The agent edits user.proto and runs the generator instead.

Questions

How does it know a file is generated?
It reads the first ten lines and matches common header phrases like @generated, DO NOT EDIT and auto-generated, ignoring case.
Will it stop me creating a brand new file?
No. A path that does not exist yet is skipped, so only existing marked files are protected.
  • Block Large Writes

    HookCode quality

    Free
  • Block Vendor Edits

    HookCode quality

    Free
  • Ensure Final Newline

    HookCode quality

    Free
  • Format After Edit

    HookCode quality

    Free