Skip to main content
Glama
README.md
<div align="center">

<img src="assets/logo.svg" alt="SafeLatch logo" width="88" height="88" />

# SafeLatch (`safelatch`)

**Automatically snapshot and undo supported shell file changes in Antigravity. Audit local plugin and MCP configuration across Antigravity, Claude Code, and Cursor.**

| Host | SafeLatch support |
| :--- | :--- |
| Antigravity | Shell rewind, runtime guard, and offline audit |
| Claude Code / Cursor | Offline audit |

[Already using cc-safety-net? See how the two tools can coexist.](COMPARISONS.md#2-safelatch-vs-kenryu42cc-safety-net)

[![CI](https://github.com/safelatch-dev/safelatch/actions/workflows/ci.yml/badge.svg)](https://github.com/safelatch-dev/safelatch/actions/workflows/ci.yml)
[![CodeQL](https://github.com/safelatch-dev/safelatch/actions/workflows/codeql.yml/badge.svg)](https://github.com/safelatch-dev/safelatch/actions/workflows/codeql.yml)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/safelatch-dev/safelatch/badge)](https://scorecard.dev/viewer/?uri=github.com/safelatch-dev/safelatch)
[![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](LICENSE)
[![Zero Dependencies](https://img.shields.io/badge/dependencies-0-blue.svg)](package.json)
[![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20-339933.svg)](package.json)

**English** | **[简体中文](README.zh-CN.md)** | **[Tool Comparisons](COMPARISONS.md)**

</div>

## Quickstart

**1. Run the local audit without installing hooks. The first npm invocation may download the package.**

```bash
npx -y safelatch@0.2.1 audit --workspace .
```

**2. Install the Antigravity plugin for shell rewind and the runtime guard.**

```bash
# Antigravity CLI
agy plugin install https://github.com/safelatch-dev/safelatch

# Antigravity Desktop / Node.js (also auto-migrates legacy `agy-guard` hooks)
npx -y safelatch@0.2.1 install
```

<div align="center">
  <img src="assets/demo.svg" alt="SafeLatch terminal demo showing shell rewind, offline audit, and runtime guard" width="820" />
</div>

---

## What SafeLatch covers

Pure runtime command blockers (`cc-safety-net`) stop `rm -rf`, yet cannot recover files corrupted by shell tools once allowed. Native Antigravity `/rewind` rolls back structured `edit_file` calls, yet misses direct shell edits ([`google-antigravity#851`](https://github.com/google-gemini/antigravity/issues/851)). And `plugin.json` manifests do not declare which hooks, scripts, or remote MCP URLs a community plugin actually runs ([`arXiv:2609.23809`](https://arxiv.org/abs/2609.23809)).

The SafeLatch runtime uses **zero runtime dependencies**, **zero network calls**, and **zero subprocess calls**.

### 1. Offline security and capability audit (`audit`)

The scanner reads recognized plugin, hook, MCP, rule, and skill files locally. Unresolved script entries appear as coverage notes.

- **Multi-Host Targeted Discovery**: Inspects Antigravity (`~/.gemini/config`, `.agents/`), Claude Code (`~/.claude`, `CLAUDE_CONFIG_DIR`, `~/.claude.json`, `.claude/`, `.mcp.json`), and Cursor (`~/.cursor`, `.cursor/`, `.cursorrules`) config paths directly without walking editor extension caches.
- **Capabilities & Network X-Ray**: Lists detected hook events, stdio MCP servers, configured MCP endpoints, and counts of rules and skills. URL credentials and query strings are redacted by default. The score summarizes static findings for the inspected files.
- **JSONC & Deep Wrapper Scanning**: Parses JSONC comments/trailing commas cleanly and follows relative script imports (`scripts/hook.mjs` → `dist/hook.mjs`).
- **Low-Noise `A004`**: Standard `https://` MCP endpoints receive **0 score penalty** while still appearing in your Capabilities X-Ray; only plaintext `http://`/`ws://`, raw IPs, ephemeral tunnels (`ngrok`, `trycloudflare.com`), and unpinned `npx -y` / `@latest` runners are flagged.
- **CI & GitHub Code Scanning (`--sarif`)**: The composite action supports optional SARIF upload. Private repositories need GitHub Code Security enabled to upload. Give each scan a distinct `sarif-category` when uploading multiple scans from one workflow.

```yaml
- uses: safelatch-dev/safelatch@v0.2.1
  with:
    path: "."
    fail-on: "high"
    upload-sarif: "true" # requires security-events: write
```

### 2. Shell-Aware Pre-Write Snapshot & CLI Rewind (`snapshots` / `diff` / `restore`)

Antigravity’s native `/rewind` misses shell edits. Before supported tool calls execute, SafeLatch attempts to snapshot recognized workspace files within local storage limits.

- **Captures Both Structured Edits & Shell Mutations**:
  - Editor tools: `write_file`, `edit_file`, `mcp_agy-fast_fast_apply_edits` (both edited `hunks` AND `verify` shell targets).
  - Shell writes & deletes: output redirections (`>`, `>>`, `1>`, `&>`, `*>`), GNU & macOS BSD `sed -i`, case-sensitive `perl -i`, `tee`, `cp` / `Copy-Item`, PowerShell `Set-Content` / `Add-Content` / `Out-File`, `rm` / `Remove-Item` / `del`, `mv` / `Move-Item`, `git checkout` / `restore`, and `mcp_agy-fast_fast_run_checks` batches.
- **New-file cleanup (`existed: false`).** Restore removes the recorded file after verifying a safety backup. If a file path has become a directory, restore stops by default.
- **CLI-only restore.** Preview with `safelatch restore <id> --dry-run`. Applying changes requires `--yes`. Use `--force` only after inspecting a backup or file-type conflict.

### 3. Cross-shell runtime guard (`PreToolUse`)

- **Targeted Self-Defense (`G004`, `deny`)**: Non-downgradable protection prevents runaway agents from running `agy plugin disable safelatch`, `safelatch uninstall`, or deleting/overwriting installed `~/.gemini/config/plugins/safelatch`, `~/.safelatch/config.json`, or `.agents/safelatch.json` files (including `$GEMINI_HOME` / `$PLUGIN_ROOT` / `$PLUGIN_DATA` token expansion).
- **Cross-Shell Parsing**: Unwraps nested `sh -c`, `bash -c`, `cmd /c`, `powershell -Command`, Base64 `-EncodedCommand`, `$()` substitutions, and Windows PowerShell `Remove-Item -Recurse -Force` / `irm ... | iex` pipelines.
- **Preserves Antigravity's Native UX (`passDecision: "ask"`)**: In Antigravity's `PreToolUse` protocol, returning `{}` is treated as a hard `deny`. SafeLatch defaults unflagged calls to `"decision": "ask"` so your native **"Always Allow"** permission flow keeps working untouched (see [Hook Protocol Notes](docs/hook-protocol-notes.md)).

---

## Comparison

| Capability | Antigravity Sandbox + `/rewind` | `cc-safety-net` | Static Skill Scanners | **SafeLatch (`v0.2.1`)** |
| :--- | :---: | :---: | :---: | :---: |
| **Offline capability audit and SARIF 2.1.0** | — | — | Partial | **Yes** |
| **Shell-aware file rewind (`sed -i`, `>`, `tee`, `Set-Content`)** | Misses shell (`#851`) | — | — | **Yes** |
| **Cross-shell (`sh` / `cmd` / PowerShell) + `G004` self-defense** | Native hooks | Yes | — | **Yes** |
| **Preserves native `Always Allow` + Zero deps / Zero network** | Built-in | Partial | Varies | **Yes** |

See [COMPARISONS.md](COMPARISONS.md) for architecture trade-offs and guidance on running SafeLatch alongside `cc-safety-net` or Antigravity Strict Mode.

---

## Non-Goals

- **Not a kernel sandbox**: Complements OS containers and Antigravity Terminal Sandbox rather than replacing syscall isolation.
- **Not an LLM prompt-injection firewall**: Deterministically checks static rule/skill markdown and gates concrete tool calls without calling any model or cloud API.
- **Never phones home**: `src/` and `dist/` contain zero runtime dependencies and zero network/subprocess imports.

---

## Rule & Configuration Reference

<details>
<summary><strong>Runtime Guard Rules (<code>G001</code>–<code>G004</code>, <code>G101</code>–<code>G107</code>)</strong></summary>

| Rule ID | Default Decision | Scope |
| :--- | :--- | :--- |
| `G001` | `deny` *(non-overridable by workspace)* | Recursive delete targeting `/`, `~`, system dirs, drive root, or workspace root |
| `G002` | `deny` *(non-overridable)* | Raw disk formatting (`mkfs*`, `diskpart`, `format X:`, `dd of=/dev/*`) |
| `G003` | `deny` *(non-overridable)* | Shell fork bomb patterns |
| `G004` | `deny` *(non-overridable)* | Self-tampering: `agy plugin disable safelatch`, `safelatch uninstall`, or mutating guard plugin/config files |
| `G101` | `force_ask` | Destructive Git ops (`reset --hard`, `clean -f`, `push --force` without lease, `checkout .`, `branch -D main`) |
| `G102` | `force_ask` | Remote download piped into shell/evaluator (`curl \| sh`, `irm \| iex`, process substitution) |
| `G103` | `force_ask` | Command accesses credentials (`.env`, `.ssh`, `.aws`, `.npmrc`) or general `.agents/hooks.json` configs |
| `G104` | `force_ask` | Overly permissive `chmod -R 777` / `a+rwx` |
| `G105` | `force_ask` | Scoped recursive delete inside workspace |
| `G106` | `force_ask` | File write/edit targets sensitive file or path outside workspace/artifact roots |
| `G107` | `force_ask` | Nested shell command exceeds the inspection depth |

</details>

<details>
<summary><strong>Offline Security & Capability X-Ray Rules (<code>A001</code>–<code>A009</code>)</strong></summary>

| Rule ID | Severity | What It Detects |
| :--- | :--- | :--- |
| `A001` | `critical` | Remote download piped into shell or `eval` inside hooks/scripts |
| `A002` | `critical` | Obfuscated base64 / `-EncodedCommand` / `atob` execution |
| `A003` | `high` | Hardcoded local credential or SSH key paths |
| `A004` | `high` / `medium` | Plaintext remote `http://`/`ws://` (`high`), raw IP or ephemeral tunnel (`medium`), or unpinned `npx -y`/`@latest`/`uvx` (`medium`). Standard `https://` gets 0 penalty. |
| `A005` | `high` | Hardcoded GitHub/OpenAI/AWS/Google/Slack/npm tokens or PEM keys |
| `A006` | `high` | Prompt-injection overrides or hidden zero-width/bidi Unicode in rules/skills |
| `A007` | `high` | Static `PreToolUse` hook hardcoding `"decision": "allow"` without checks |
| `A008` | `medium` / `low` | Bundled native binaries (`.exe`/`.dll`/ELF/Mach-O) or >1 MB unreadable scripts |
| `A009` | `info` | Missing `LICENSE` or `repository` provenance metadata on standalone plugins |

</details>

<details>
<summary><strong>CLI Commands, MCP Tools & Configuration Precedence</strong></summary>

```bash
# 1. Security & Capability X-Ray
safelatch audit [--path <file-or-dir>] [--workspace <dir>] [--json|--md|--sarif] [--fail-on <severity>]

# 2. Shell-Aware Snapshots & Rewind
safelatch snapshots [--workspace <dir>] [--json]
safelatch diff <snapshot-id> [--workspace <dir>]
safelatch restore <snapshot-id> [--file <rel>] [--dry-run] [--yes] [--force]

# 3. Guard Dry-Run & Plugin Management
safelatch check "<command>" [--json]
safelatch install [--config <dir>] [--skip-enable]
safelatch uninstall [--config <dir>]
safelatch status
```

- **Read-only MCP tools (`safelatch_guard`)**: `safelatch_audit`, `safelatch_snapshots`, `safelatch_diff`, `safelatch_check` (legacy `agy_guard_*` tool calls remain supported as aliases).
- **Config precedence**: Defaults → Global (`$PLUGIN_DATA/config.json` or `~/.safelatch/config.json`, fallback `~/.agy-guard/config.json`) → Workspace (`.agents/safelatch.json`, fallback `.agents/agy-guard.json`). Workspace configs **cannot** set `mode: "off"`, `mode: "monitor"`, `passDecision: "allow"`, or `snapshot.enabled: false`. Only an explicit global `ask-only` can downgrade `G001`–`G004` to confirmation.

</details>

## Security & License

- See [SECURITY.md](SECURITY.md) for the security model, supply-chain SHA pinning policy, and private vulnerability disclosure.
- Licensed under the [MIT License](LICENSE).