Dev.to Security 🔐 Cybersecurity 👁 0 📖 4 min read

Undo `sed -i` Edits from AI Agents + 3 Hook Pitfalls Building SafeLatch

If you use Claude Code, Cursor, or Google Antigravity heavily, you have probably hit two blind spots that standard workflows don't cover: Editor rewind misses shell mutations. Structured file tools (Edit, Write, edit_

Undo `sed -i` Edits from AI Agents + 3 Hook Pitfalls Building SafeLatch

If you use Claude Code, Cursor, or Google Antigravity heavily, you have probably hit two blind spots that standard workflows don't cover:

  1. Editor rewind misses shell mutations. Structured file tools (Edit, Write, edit_file) are easy for editors to undo, and command blockers like cc-safety-net are great at stopping rm -rf /. Yet if an agent runs a normal shell command — sed -i, echo ... > config.json, tee, truncate, mv, or PowerShell Set-Content — and corrupts or deletes a file, structured undo misses it and blockers can't restore what was already overwritten.
  2. Community MCP configs and plugin hooks are opaque before you run them. A plugin.json or .mcp.json rarely tells you upfront what wrapper scripts it chains into, whether it invokes unpinned npx -y @latest runners, or whether a Markdown skill hides zero-width/bidi Unicode overrides.

I built SafeLatch (github.com/safelatch-dev/safelatch, MIT, zero runtime dependencies, zero network calls, zero child_process imports) to fill those gaps across Antigravity, Claude Code, and Cursor.

Here are three real engineering pitfalls from building and testing v0.3.1 — plus how to try the read-only audit in 10 seconds.

Pitfall 1: Returning {} from a PreToolUse hook isn't always "allow"

When writing the first Antigravity PreToolUse adapter, I assumed returning an empty JSON object {} meant "no objection, pass through."

In practice, Antigravity treats {} as a hard deny (tool call denied by pre-tool hook), blocking every tool call. Returning {"decision": "allow"} has the opposite problem: it silently bypasses the user's native confirmation prompt and Always Allow flow.

Different hosts expect opposite defaults:

  • Antigravity: Unflagged calls explicitly emit {"decision": "ask"} (passDecision: "ask") so the host's native Always Allow state keeps working untouched.
  • Claude Code: Unflagged calls return {} (deferring cleanly to Claude Code's own permission flow), and only flagged commands or self-tamper attempts return hookSpecificOutput.permissionDecision: "ask" | "deny".

The installer also merges ~/.claude/settings.json and ~/.cursor/hooks.json idempotently instead of overwriting them, so existing hooks like cc-safety-net keep running untouched, and uninstall --host <host> strips only SafeLatch's entries.

Pitfall 2: Snapshotting shell edits means tracking files that didn't exist — and Windows 8.3 short paths

Consider a compound shell command:

sed -i 's/verifyToken/bypassAuth/g' src/auth.ts && echo leak > debug.tmp

Backing up src/auth.ts alone isn't enough. If debug.tmp did not exist beforehand, restoring without an existed: false marker leaves shell-created junk behind.

Before Bash, run_command, or beforeShellExecution executes, SafeLatch parses POSIX, cmd, and PowerShell AST segments (including cd location tracking, GNU/BSD sed -i.bak, perl -i, tee, truncate, PowerShell Set-Content/sc/Remove-Item/ri, and Base64 -EncodedCommand) and captures deduplicated SHA-256 blobs under local quota limits (5 MB/file, 50 MB/snapshot, 1 GB total, 7-day TTL).

Two deliberate boundaries here:

  1. safelatch restore is CLI-only. SafeLatch exposes 4 read-only MCP tools (safelatch_audit, safelatch_snapshots, safelatch_diff, safelatch_check), while restore requires --dry-run inspection and manual --yes in a terminal so a runaway agent cannot self-trigger rollbacks.
  2. Windows 8.3 short-path mismatch (RUNNER~1). Our windows-latest CI caught a real bug in v0.3.0: Node's fs.realpathSync keeps Windows 8.3 short names like C:\Users\RUNNER~1\..., while fs.realpathSync.native expands them to C:\Users\runneradmin\.... Mixing the two caused false G106 out-of-workspace alerts on Windows usernames longer than 8 characters or containing spaces. Unifying containment and snapshot keys onto fs.realpathSync.native fixed it in v0.3.1.

Pitfall 3: Auditing MCP configs without flagging normal https:// servers

Many static scanners penalize any remote URL, burying real risks under false positives on legitimate Sentry/GitHub/Notion MCP endpoints.

SafeLatch's offline auditor (A001–A009) takes a stricter signal-to-noise stance:

  • Standard https:// remote MCP endpoints get 0 score penalty, while still appearing in a Capabilities & Network X-Ray table (with URL credentials and query strings redacted).
  • Penalties focus on plaintext http:///ws://, raw IPs, ephemeral tunnels (ngrok, trycloudflare.com), unpinned npx -y/@latest/uvx runners, hidden zero-width/bidi Unicode in skills/rules, hardcoded "decision": "allow" hooks, and wrapper indirections (scripts/hook.mjs -> dist/hook.mjs).
  • On our reproducible 36-target synthetic multi-host benchmark (npm run bench:audit, documented in docs/benchmarks.md), SafeLatch matched 24/24 expected findings with 0/12 benign false positives and 0/4 false positives on standard HTTPS endpoints (p50 32.73 ms / p95 71.58 ms in-process on Windows Node 24).

Try the 10-second read-only audit (no hooks installed)

npx -y [email protected] audit --workspace .

This scans local Antigravity (~/.gemini/config, .agents/), Claude Code (~/.claude, ~/.claude.json, .mcp.json), and Cursor (.cursor/, .cursorrules) config files without touching editor extension caches or making network requests. It also supports --sarif (SARIF 2.1.0) and a composite GitHub Action (safelatch-dev/[email protected]).

If you also want shell-aware pre-write snapshots and cross-shell runtime protection:

npx -y [email protected] install --host claude-code
npx -y [email protected] install --host cursor
npx -y [email protected] install              # Antigravity
# Or all three hosts together:
npx -y [email protected] install --host all

Non-goals & current limits

  • Not a kernel/container sandbox (complements OS sandboxing rather than replacing it).
  • Static shell AST extraction won't predict dynamic file paths computed at runtime inside arbitrary python -c or node -e one-liners.

GitHub: https://github.com/safelatch-dev/safelatch

npm: https://www.npmjs.com/package/safelatch

If you run audit on your own .mcp.json or .claude setup and hit a false positive or an unhandled shell mutation pattern, feel free to open an issue!

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.