@exponencial/agent-safe-guard
v1.1.0
Published
Native safety hooks and governance skills for AI coding agents.
Maintainers
Readme
agent-safe-guard
Native safety hooks for AI coding agents on Linux. The current runtime integrates with Claude Code hooks; the policy model is designed for agent skills, VS Code-style assistants, Codex-style workflows, and OpenClaw-like developer agents.
agent-safe-guard sits between Claude Code and its tool calls. It blocks destructive commands, trims noisy output, guards large reads, enforces subagent budgets, records audit events, and exposes a native rule/package console.
Why
AI coding agents execute shell commands, read files, and make permission decisions on your behalf. Without guardrails, a single hallucinated rm -rf / or a leaked .env read can cause real damage. agent-safe-guard adds a fail-closed enforcement layer that runs before every tool call reaches your system.
Current Release
- Linux-first, native-only runtime (C++20 daemon + hook clients)
- Source install today
.deband AppImage planned- Windows and macOS on the roadmap behind a transport abstraction
What It Does
- Blocks destructive shell patterns (
rm -rf /, fork bombs,curl | bash, force pushes to protected branches) - Requires quiet flags for commands that would flood context
- Denies bundled, generated, binary, or oversized
Readtargets - Compresses large
Readoutputs into structural summaries - Auto-decides safe vs unsafe permission requests
- Masks secrets and credentials in file reads
- Injects a ranked tree-sitter repo map at SessionStart so Claude stops re-reading files every session (new — see Repo Map below)
- Tracks session metrics, rule matches, tool latency, compaction, and subagent usage
- Supports extension rule packages from remote catalogs with SHA256 integrity checks
- Lets you inspect and override policy at the package and rule level with
asg-cli
Screenshots
Rules
Browse packages and their rules. Toggle individual rules on/off.

Rule Detail
Inspect rule metadata, match stats, and override state.

Catalog
Sync extension packages from remote catalogs and install them.

Package Detail
View installed package info, version, tags, and contained rules.

Settings
Toggle defense features and see what each one controls. Includes the Repo Map Primer (tree-sitter SessionStart context — see Repo Map).

Quick Start
Requirements:
- Linux (x86_64)
jqcoreutilscmake3.20+- A C++20 compiler (
g++10+ orclang++13+)
Installation from source:
git clone https://github.com/exponencialadm/agent-safe-guard.git
cd agent-safe-guard
git submodule update --init --recursive # required — tree-sitter grammars + doctest + bats
cmake -S . -B build/native -DSG_BUILD_NATIVE=ON
cmake --build build/native -j$(nproc)
./build/native/native/asg-installInstall from npm as an explicit, no-postinstall launcher:
npm exec --yes @exponencial/agent-safe-guard -- --help
npm exec --yes @exponencial/agent-safe-guard -- skills --list
npm exec --yes @exponencial/agent-safe-guard -- skills --force
npm exec --yes @exponencial/agent-safe-guard -- installThe npm package does not compile or install hooks during npm install. It only
ships the launcher and skill pack. Native installation starts only when you run
agent-safe-guard install or the equivalent npm exec command.
Or use the local source installer wrapper after cloning:
./scripts/install-from-source.shNotes:
- The installer creates native hook symlinks in
~/.claude/hooks/asg-*. - It installs
asg-cli,asg-statusline,asg-repomap,asg-install, andasg-uninstallinto~/.local/bin. - It attempts to install and enable user
systemdsocket units forsgd. ~/.local/binshould be on yourPATH.- Start a new Claude Code session after install.
If your environment does not have a working systemd --user session, use the manual daemon path:
./build/native/native/asg-install --no-enable-systemd-user
./build/native/native/sgd --socket /tmp/agent-safe-guard/sgd.sockThe native clients already probe /tmp/agent-safe-guard/sgd.sock, so this manual mode works without extra hook changes.
Verify The Install
Check the installed entrypoints:
ls -l ~/.claude/hooks/asg-pre-tool-use
ls -l ~/.local/bin/asg-cli ~/.local/bin/asg-install ~/.local/bin/asg-uninstallCheck the public CLIs:
asg-install --help
asg-uninstall --help
asg-cli --print-rulesEveryday Commands
Install or reinstall:
asg-installOpen the policy console:
asg-cliPrint package and rule state non-interactively:
asg-cli --print-rulesUninstall hooks and launchers while preserving local config/state:
asg-uninstallHow It Works
Hot-path enforcement is native:
- Claude Code emits a hook event as JSON on stdin.
- A native hook client (
sg-hook-*) forwards the payload tosgdover a Unix socket. - The daemon evaluates built-in rules and compiled catalog patterns, then returns hook JSON.
- Claude Code receives the decision (deny, allow, modify output, stop session).
All enforcement is fail-closed: if the daemon is unreachable, hook clients deny the tool call rather than letting it through.
Repository layout:
config.env # Default thresholds and limits
native/ # Native daemon, hook clients, CLI tools
queries/ # Tree-sitter tag queries (TS/JS) for the repo map
hooks/ # Legacy/reference Bash implementation, not installed
systemd/ # User systemd socket + service unit templates
third_party/ # Pinned submodules (tree-sitter + grammars, doctest)
docs/ # Architecture, roadmap, and feature docs
tests/ # bats-core integration tests (547 tests)
screenshots/ # README assetsConfiguration And State
Main config files and state directories:
~/.claude/.safeguard/config.env~/.claude/.safeguard/features.env~/.claude/.safeguard/policy/packages.json~/.claude/.safeguard/policy/installed.json~/.claude/.safeguard/policy/catalogs.json~/.claude/.safeguard/policy/stats/~/.claude/.statusline/events.jsonl
Useful event inspection commands:
rg '"event_type":"rule_match"' ~/.claude/.statusline/events.jsonl
rg '"event_type":"blocked"' ~/.claude/.statusline/events.jsonl
rg '"event_type":"permission_decision"' ~/.claude/.statusline/events.jsonl
rg '"event_type":"read_guard"' ~/.claude/.statusline/events.jsonlTesting
Install does not require git submodules. Tests do.
git submodule update --init --recursive
make native-build
make testUseful test targets:
make test— all 547 tests, parallelmake test-unit— unit tests onlymake test-integration— integration tests onlymake coverage— with line coverage reportmake test-native-pre-smoke— pre-tool-use smoke tests against native daemonmake test-native-rule-audit— verify all rules compile and match expected inputs
The test suite runs in isolated temp homes. It does not touch your real ~/.claude state.
Repo Map Primer
A port of aider's RepoMap to native C++20, integrated with the existing daemon.
At session start, the daemon walks your repo with tree-sitter, ranks files by cross-reference PageRank, and injects a compact path:line kind name map of the top files into Claude's additionalContext. Claude starts every session already knowing where the classes, interfaces, functions, and methods live — no warm-up Read/Grep volleys needed.

Toggle live from asg-cli → Settings → "Repo Map Primer".
Example. After this lands, asking "does this repo have a Promises class?" on a fresh session gets answered instantly from the primer, no file I/O:
> o repo tem uma classe Promises? em qual arquivo e linha?
Sim, há duas cópias — ambas definem class Promises na linha 4:
- app-gps-INOVA/src/Promises.js:4
- app-gps-SAMU/src/Promises.js:4How it works
- Tree-sitter parses each
.ts/.mts/.cts/.js/.mjs/.cjsfile (TSX + more languages planned for v0.3). Declaration files (.d.ts) are skipped. - A file graph is built from cross-file identifier references, weighted by name-shape heuristics.
- Hand-rolled PageRank (50 iters, damping 0.85) ranks files.
- The top-N tags are rendered as
rel_path:line kind subkind namelines, sized underSG_REPOMAP_MAX_TOKENS(default 4096) via binary search on N. Per-file tag cap (default 40) keeps barrel re-exports from starving the budget. - Results are cached at
<repo>/.asg-repomap/tags.v1.bin. On git repos, first build appends.asg-repomap/to.git/info/exclude. Subsequent session-starts mtime-check each file and only reparse what changed — typical warm update is under 100 ms even on 3k-file repos.
Measurements
On Ryzen 9 9950X3D, single-threaded, against real TS/JS working repos:
| Repo size | Cold build | Warm update | Cache | Render (budget 4096) | |--- |--- |--- |--- |--- | | 370 source files | 3.3 s | 10 ms | 1.0 MB | 4 files / 160 tags | | 1 227 source files | 10.0 s | 40 ms | 3.1 MB | 3 files / 120 tags | | 3 235 source files | 21.6 s | 100 ms | 6.8 MB | 3 files / 120 tags |
Render itself is sub-200 ms once the cache exists.
Configure
All knobs are optional. Defaults ship enabled.
# ~/.claude/.safeguard/features.env
SG_FEATURE_REPOMAP=1 # toggle the SessionStart injection
# ~/.claude/.safeguard/config.env (or env vars)
SG_REPOMAP_MAX_TOKENS=4096 # chars/4 budget for the injected map
SG_REPOMAP_MAX_FILE_BYTES=524288 # skip source files > 512 KB
SG_REPOMAP_MAX_TAGS_PER_FILE=40 # per-file tag cap (0 = unlimited)Toggle interactively via asg-cli → Settings tab → "Repo Map Primer".
Use the CLI directly
The asg-repomap binary is useful on its own for debugging, scripting, or pre-warming caches:
asg-repomap build --root ~/src/my-repo # full cache build
asg-repomap update --root ~/src/my-repo # incremental (mtime-skip)
asg-repomap render --root ~/src/my-repo # print the map
asg-repomap render --root ~/src/my-repo --budget 8192
asg-repomap stats --root ~/src/my-repo # files, tags, cache size
asg-repomap clean --root ~/src/my-repo # rm -rf .asg-repomap/
asg-repomap build --file some.ts --tags # single-file inspectionFull details in docs/repomap.md.
Extension Packages (Catalog)
agent-safe-guard supports installing additional rule packages from remote catalogs. The default catalog is hosted at exponencialadm/agent-safe-guard-rules.
Sync and install via the asg-cli Catalog tab, or non-interactively:
asg-cli --catalog-sync
asg-cli --catalog-install cloud-defenseCatalog packages use SHA256 integrity checks. The daemon compiles catalog rule patterns into regex matchers at startup.
Codex Skill Pack
This repository ships an installable Codex skill pack:
skills/agent-safe-guard— install and operate native hooks.skills/iso-ai-governance— orchestrate ISO 27001/42001 governance for AI agents, skills, extensions, MCPs, evidence, and enforcement.skills/agent-inventory— discover agents, skills, MCP configs, and editor extensions.skills/extension-risk-audit— audit VS Code/Cursor/Windsurf extension risk.skills/evidence-sync— package scan results as ISO evidence envelopes.skills/ai-policy-pack— render a practical AI-agent governance policy baseline.skills/iso-remediacao— turn npm audit output into ISO 27001 A.8.8 evidence.
Install the pack locally:
./scripts/install-skill-pack.sh --forceOr through npm:
npm exec --yes @exponencial/agent-safe-guard -- skills --forceRoadmap
Distribution and platform planning lives in docs/distribution-roadmap.md.
Current direction:
- Ship a clean source release first
- Add
.debpackaging for Debian/Ubuntu users - Add AppImage for portable Linux installs
- Keep Windows and macOS on the roadmap as exploratory work behind a transport/service abstraction checkpoint
Documentation
- native/README.md — native runtime, protocol, event logging
- docs/repomap.md — repo map algorithm, CLI, configuration, measurements
- docs/rule-engine-architecture.md — phase model, ModSecurity-style engine
- docs/policy-catalog-console-plan.md — catalog and console UX design
- docs/distribution-roadmap.md — packaging and platform plan
- docs/memory-safety.md — non-negotiable memory & resource safety contract for contributors (mandatory reading before any allocator-touching diff)
Contributing
See CONTRIBUTING.md. Diffs that allocate, iterate,
or accept external input must satisfy the memory-safety
contract — make test is wired to refuse green
output without an ASan + UBSan pass.
Security
For vulnerability reports, see SECURITY.md.
License
MIT. See LICENSE.
