Skip to content

Agent Guardrails: Deterministic safety enforcement for autonomous execution (GUARD-001) #140

Closed

Description

@vybe

Summary

Implement deterministic safety guardrails for autonomous agent execution inside Trinity containers. Agents running with --dangerously-skip-permissions can currently execute any command, access any file, and reach any network host. While Docker isolation provides a baseline boundary, we need layered enforcement inside the container to prevent costly mistakes — destructive commands, credential leaks, runaway loops, and unauthorized access.

Design principle: Trinity controls the base image, agent-server.py, and the deployment pipeline. Guardrails are injected at the infrastructure level and cannot be opted out of by agents. This is not about advisory instructions (CLAUDE.md) — it's about deterministic enforcement (hooks, CLI flags, OS restrictions).

Context & Research

Research across Claude Code, OpenAI Codex, and Gemini CLI ecosystems reveals industry convergence on a layered defense model:

Layer Mechanism Trinity Status
OS/Container isolation Docker containers ✅ Already have this
Deterministic tool-call rules Claude Code hooks, policy engines ❌ Not implemented
CLI budget/scope controls --max-turns, --allowedTools, timeouts ⚠️ Partial (task mode only)
Advisory instructions --append-system-prompt ✅ Already have this
Post-execution validation Output scanning, credential detection ❌ Not implemented

Real-world incidents driving this:

  • Users lost entire machines to rm -rf from Claude Code
  • Replit agent deleted a production database despite explicit code freeze
  • AWS Kiro agent caused a 13-hour outage from a minor bug fix task
  • CVE-2025-59536: Malicious repo hooks executed arbitrary commands on clone

Key finding: Claude Code hooks fire deterministically even in --dangerously-skip-permissions mode. This is our primary enforcement mechanism.

Requirements (GUARD-001 through GUARD-006)

Full spec in docs/memory/requirements.md Section 28.

Phase 1 — Foundation (this issue)

GUARD-002: Hook Injection in Base Image

  • Install hook scripts at /opt/trinity/hooks/ in the base image Dockerfile
  • Configure ~/.claude/settings.json with PreToolUse and PostToolUse hooks
  • Bash deny-list (PreToolUse on Bash):
    • rm -rf / or rm -rf ~ (destructive deletion)
    • chmod 777 (permission blowout)
    • curl | sh or wget | sh (arbitrary code execution)
    • git push --force (irreversible git operations)
    • kill -9 on system processes
    • Patterns matching production domains (configurable)
  • File protection (PreToolUse on Edit/Write/Read):
    • Block writes to .env, .mcp.json, ~/.ssh/*, ~/.aws/*
    • Block reads of credential files via cat, head, tail, less
  • Output scanning (PostToolUse on Bash):
    • Detect leaked credentials in stdout/stderr (patterns: sk-, ghp_, AKIA, sk-ant-, bearer tokens)
    • Log detection events to /logs/guardrails.jsonl
  • All blocked actions logged with reason, tool name, and sanitized input

GUARD-003: CLI Budget & Scope Controls

  • Inject --max-turns on all Claude Code invocations (chat + task), not just task mode
    • Default: 50 for chat, 20 for tasks (configurable per agent)
  • Add execution timeout in claude_code.py: kill subprocess after configurable limit (default: 30 min)
  • Support --disallowedTools for globally banning tools per agent
  • Per-agent guardrail configuration via backend API: PUT /api/agents/{name}/guardrails
  • Configuration stored in agent DB record, read by agent-server at execution time

Phase 2 — Credential Protection (GUARD-004)

  • Prevent agents from inspecting their own credentials (.env, .mcp.json, SSH keys)
  • Mask env/printenv output for sensitive variables
  • PostToolUse scanning for credential values in command output

Phase 3 — Observability (GUARD-005)

  • Guardrail event log with structured JSON (agent, action, reason, timestamp)
  • Vector pipeline integration for centralized guardrail log collection
  • Backend API for querying guardrail events
  • Frontend: Guardrails tab on Agent Detail, fleet stats on Operating Room

Phase 4 — Network Controls (GUARD-006)

  • Per-agent domain allowlists for outbound network access
  • DNS-level or proxy-based filtering
  • Lower priority — Docker isolation already provides baseline

Implementation Plan (Phase 1)

Base Image Changes (docker/base-image/)

  1. Create /opt/trinity/hooks/bash-guardrail.sh:

    • Read JSON from stdin, extract tool_input.command
    • Match against deny-list patterns (regex)
    • Return {"hookSpecificOutput": {"permissionDecision": "deny", ...}} on match
    • Log blocked action to /logs/guardrails.jsonl
  2. Create /opt/trinity/hooks/file-guardrail.sh:

    • Block writes to credential paths
    • Block reads of credential files via shell commands
  3. Create /opt/trinity/hooks/output-scanner.sh:

    • Scan PostToolUse output for credential patterns
    • Log warnings (non-blocking — informational only in Phase 1)
  4. Create ~/.claude/settings.json in Dockerfile:

    {
      "hooks": {
        "PreToolUse": [
          {"matcher": "Bash", "hooks": [{"type": "command", "command": "/opt/trinity/hooks/bash-guardrail.sh"}]},
          {"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "/opt/trinity/hooks/file-guardrail.sh"}]}
        ],
        "PostToolUse": [
          {"matcher": "Bash", "hooks": [{"type": "command", "command": "/opt/trinity/hooks/output-scanner.sh"}]}
        ]
      }
    }
  5. Update startup.sh to merge agent-specific hook overrides if present

Agent Server Changes (agent_server/services/claude_code.py)

  1. Add --max-turns to chat mode invocations (currently only on task mode)
  2. Add execution timeout (subprocess kill after configurable limit)
  3. Read guardrail config from agent state/config for per-agent overrides
  4. Support --disallowedTools flag

Backend Changes (src/backend/)

  1. Add guardrails column to agent DB schema (JSON blob)
  2. Add PUT /api/agents/{name}/guardrails endpoint
  3. Pass guardrail config to agent container via env var or config mount

Acceptance Criteria

  • Base image includes hook scripts at /opt/trinity/hooks/
  • ~/.claude/settings.json pre-configured with guardrail hooks
  • rm -rf /, chmod 777, curl | sh blocked with logged reason
  • Writes to .env and .mcp.json blocked by file guardrail hook
  • --max-turns applied to all Claude Code invocations
  • Execution timeout kills runaway processes
  • Blocked actions logged to /logs/guardrails.jsonl
  • Per-agent guardrail configuration via backend API
  • Existing agents continue to function (no false positives on normal operations)
  • Base image rebuild required (./scripts/deploy/build-base-image.sh)

Files to Change

File Change
docker/base-image/Dockerfile Install hook scripts, create settings.json
docker/base-image/hooks/bash-guardrail.sh New — Bash command deny-list
docker/base-image/hooks/file-guardrail.sh New — Credential file protection
docker/base-image/hooks/output-scanner.sh New — Post-execution credential scanning
docker/base-image/startup.sh Merge agent-specific hook overrides
docker/base-image/agent_server/services/claude_code.py Add --max-turns to chat, execution timeout, --disallowedTools
src/backend/database.py Add guardrails column to agents
src/backend/routers/agents.py Add guardrails endpoint
docs/memory/requirements.md Section 28 (already added)

References

Metadata

Metadata

Assignees

Labels

complexity-mediumpriority-p1type-feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions