Skip to content

feat(guardrails): Phase 1 deterministic safety enforcement (GUARD-001) - #315

Merged
vybe merged 3 commits into
mainfrom
feature/140-agent-guardrails
Apr 15, 2026
Merged

vybe merged 3 commits into
mainfrom
feature/140-agent-guardrails

Conversation

@dolho

@dolho dolho commented Apr 13, 2026

Copy link
Copy Markdown
Contributor

Summary

Phase 1 of Agent Guardrails (#140): layered, infrastructure-level safety enforcement for autonomous agents. Claude Code hooks fire even under --dangerously-skip-permissions, so the base image ships deterministic deny-lists that agents cannot opt out of.

  • Hooks baked into the base image (/opt/trinity/hooks/, root-owned 0555) — PreToolUse on Bash and Edit|Write|NotebookEdit|MultiEdit, PostToolUse on Bash for credential-pattern logging.
  • --max-turns on every Claude Code invocation — chat mode now passes it (default 50); task mode picks up max_turns_task from config (default 20) when callers don't specify.
  • Backend endpoint GET/PUT /api/agents/{name}/guardrails with strict whitelist validation. Per-agent overrides are bounded numbers + literal substring lists (no regex from users).
  • POST /stop + POST /start triggers a container recreate via check_guardrails_env_matches(), matching the existing pattern used for API keys / resource limits / full-capabilities.
  • Fail-closed on hook errors; structured events written to /logs/guardrails.jsonl (pattern names only — never matched values).

Test plan

Unit (tests/unit/test_guardrails.py, 50 cases, all green):

  • 17 baseline deny cases match (rm -rf /, curl | sh, git push -f, mkfs.ext4, fork bombs, etc.)
  • 14 false-positive guards pass (rm -rf ./build, chmod +x, git push origin main, etc.)
  • Router payload validator: accept + 9 distinct reject paths (wrong type, out-of-range, oversized list, oversized string, bool-as-int, scalar-as-list, etc.)
  • write-runtime-config.py sanitises overrides (clamps numbers, ignores malformed JSON, drops junk list items)
  • Migration is idempotent

End-to-end on a live Trinity instance:

  • Fresh agent boots with baseline config (max_turns_chat=50, max_turns_task=20, extra_bash_deny=[])
  • PUT /guardrails + POST /stop + POST /start flows overrides into /opt/trinity/guardrails-runtime.json
  • Real chat that triggers a benign per-agent deny rule gets blocked by the hook; agent sees the deny message; guardrails.jsonl records the structured event
  • [Chat] Limiting to 10 agentic turns log line confirms --max-turns injection on every chat
  • Direct hook invocation in-container denies rm -rf /, chmod 777, curl | sh, git push -f, mkfs.ext4 and allows ls -la, normal curl
  • Agent (uid 1000) cannot write to /opt/trinity/ — filesystem-level Permission denied
  • Invalid payloads return 400 with specific error messages
  • Unauthenticated → 401, bogus token → 401, non-existent agent → 404

Deferred to follow-ups

Rollout notes

  • Requires base image rebuild: ./scripts/deploy/build-base-image.sh
  • Existing agents don't pick up hooks until recreated (not just restarted). A plain docker restart reuses the old image. Delete + recreate or change any setting that triggers recreate_container_with_updated_config.

Closes #140 (Phase 1)

🤖 Generated with Claude Code

#140)

Ship Claude Code hooks, per-agent CLI budget controls, and a backend
override endpoint so dangerous bash commands and credential-file writes
can be blocked at the infrastructure layer — not at the model layer.
Hooks fire deterministically even under --dangerously-skip-permissions.

Base image:
- /opt/trinity/hooks/{lib,bash-guardrail,file-guardrail,output-scanner}.py
  shipped root-owned 0555; guardrails-baseline.json 0444
- ~/.claude/settings.json pre-registers PreToolUse + PostToolUse hooks
- startup.sh calls write-runtime-config.py via sudo to render
  /opt/trinity/guardrails-runtime.json (root-owned) merging baseline with
  the AGENT_GUARDRAILS env var — agent user cannot rewrite
- Fail-closed on hook errors; logs to /logs/guardrails.jsonl

Agent server (docker/base-image/agent_server/services/claude_code.py):
- _load_guardrails() reads runtime config on every invocation
- Chat mode now always passes --max-turns (default 50)
- Task mode falls back to guardrails' max_turns_task (default 20)
  when no caller value is provided
- Both paths pick up disallowed_tools from the config

Backend:
- New agent_ownership.guardrails_config TEXT column (schema + idempotent
  migration), SecurityMixin get/set helpers, db wrapper
- GET/PUT /api/agents/{name}/guardrails with strict whitelist validation
  (bounded numbers; literal substring lists, ≤50 × ≤256 chars; no regex)
- Agent creation serialises overrides into AGENT_GUARDRAILS env var
- check_guardrails_env_matches() in helpers.py, wired into lifecycle.py
  start_agent so POST /stop + /start recreates the container when
  overrides change — matches the existing pattern used for API keys,
  resource limits, and full-capabilities

Tests (tests/unit/test_guardrails.py — 50 cases, all passing):
- Baseline bash deny-list: 17 deny cases + 14 false-positive guards
- Baseline credential pattern presence
- Router payload validator: accept + 9 reject paths
- write-runtime-config.py sanitisation: baseline fallback, overrides,
  number clamping, malformed JSON, junk list items
- Migration idempotency on in-memory SQLite

End-to-end verified on a live Trinity instance with a real agent:
baseline + per-agent override both trigger real Claude Code tool-call
denies with structured JSON log events.

Deferred to follow-ups:
- Chat-mode wall-clock subprocess timeout (#313)
- Credential env masking (GUARD-004)
- Guardrails tab + fleet dashboard (GUARD-005)
- Network egress controls (GUARD-006)

Closes #140 (Phase 1)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@dolho
dolho force-pushed the feature/140-agent-guardrails branch from 7c01293 to d28121d Compare April 13, 2026 13:10
@dolho
dolho requested a review from vybe April 13, 2026 13:11
vybe and others added 2 commits April 15, 2026 14:30
Document GET/PUT /api/agents/{name}/guardrails endpoints added in
GUARD-001 Phase 1 implementation.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants