# edit_path_guard.ps1 -- PreToolUse guard for Claude Code (matcher: Edit|Write|MultiEdit|NotebookEdit). # # Blocks the agent's built-in editor on files that must never be rewritten wholesale: # 1) append-only journals: _journal.md, *_log.md -- they only grow via '>>' / Add-Content # (a shell command, which this matcher does NOT cover, so appending keeps working). # A full rewrite by the editor races a neighbour tab and silently drops its line. # 2) secrets files: .env, .env.local, ... (templates .env.example / .sample / .template are allowed). # 3) private SSH material inside a .ssh folder (public keys *.pub are allowed). # # Setup: put this file into \_shared\hooks\ and register it in .claude\settings.json # of EVERY project (project settings are not inherited from parent folders) -- see settings-hooks.json. # Runs under PowerShell 7 (pwsh). The source is kept ASCII-only on purpose: Windows PowerShell 5.1 # reads a file without BOM as the ANSI code page, and a single Cyrillic letter breaks parsing -- # the guard then silently never runs. After any change run test_guards.ps1. # # On macOS / Linux: ask the agent to port this file to bash or python by this header; the contract # below stays the same. # # Contract: JSON on stdin (tool_input.file_path). To block: print a permissionDecision=deny payload # and exit 0. Any parse error -> exit 0 without output (fail-open): the guard protects against a # footgun, a glitch in it must not stop real work. Test it, so that fail-open never goes unnoticed. # --- CONFIGURE: names of append-only files (wildcards allowed) --- $AppendOnly = @('_journal.md', '*_log.md') $ErrorActionPreference = 'Stop' try { $raw = [Console]::In.ReadToEnd() if ([string]::IsNullOrWhiteSpace($raw)) { exit 0 } $data = $raw | ConvertFrom-Json $fp = [string]$data.tool_input.file_path if ([string]::IsNullOrWhiteSpace($fp)) { exit 0 } $norm = ($fp -replace '/', '\') $low = $norm.ToLower() $leaf = ($norm -split '\\')[-1].ToLower() $blocked = $null foreach ($pat in $AppendOnly) { if ($leaf -like $pat) { $blocked = "append-only file ($leaf) -- add a line with '>>' or Add-Content, never rewrite it with the editor." break } } if (-not $blocked) { if ( ($low -match '\\\.ssh\\') -and ($leaf -notlike '*.pub') -and ($leaf -notlike '*.md') ) { $blocked = 'private SSH material under .ssh\ -- do not edit it with the agent; change it manually.' } elseif ( ($leaf -eq '.env') -or ($leaf -like '*.env') -or ( ($leaf -like '.env.*') -and ($leaf -notlike '*.example') -and ($leaf -notlike '*.sample') -and ($leaf -notlike '*.template') ) ) { $blocked = 'secrets file (.env) -- editing it with the agent is disabled; change it manually.' } } if ($blocked) { $payload = @{ hookSpecificOutput = @{ hookEventName = 'PreToolUse' permissionDecision = 'deny' permissionDecisionReason = "Blocked by edit_path_guard: $blocked" } } Write-Output ($payload | ConvertTo-Json -Depth 5 -Compress) } exit 0 } catch { exit 0 # fail-open }