fix(tui): add guardrails as files instead of submodule

Embedded repo was committed as submodule (160000). Now includes all
guardrails files directly for full in-repo reference.

Authored by TheArchitectit
This commit is contained in:
Claude 2026-06-11 18:29:45 -05:00
parent a347a2f0c5
commit 2d62b470f6
697 changed files with 165693 additions and 1 deletions

@ -1 +0,0 @@
Subproject commit 139118958cba9c083bf78c29f3efdc0034b24d14

View File

@ -0,0 +1,22 @@
#!/bin/bash
# Post-Execution Hook - Runs after file modifications
# Validates: no forbidden patterns, changes are correct
set -euo pipefail
echo "[GUARDRAILS] Post-execution validation running..."
# Check for common issues in modified files
MODIFIED_FILES=$(git diff --name-only 2>/dev/null || true)
if echo "$MODIFIED_FILES" | grep -iq 'aws_secret'; then
echo "[ERROR] Potential AWS secret key detected in modified files"
exit 1
fi
if echo "$MODIFIED_FILES" | grep -iq 'private_key'; then
echo "[ERROR] Potential private key detected in modified files"
exit 1
fi
echo "[GUARDRAILS] Post-execution checks passed"

View File

@ -0,0 +1,34 @@
#!/bin/bash
# Pre-Commit Hook - Runs before git commit
# Validates: AI attribution, no secrets, scope
set -euo pipefail
echo "[GUARDRAILS] Pre-commit validation running..."
COMMIT_MSG_FILE="$1"
BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Check for AI attribution in commit message
if ! grep -qi "Co-Authored-By:" "$COMMIT_MSG_FILE"; then
echo "[ERROR] Commit message missing AI attribution"
echo "[INFO] Add: Co-Authored-By: Claude <noreply@anthropic.com>"
exit 1
fi
# Check for secrets in staged files using trufflehog if available
if command -v trufflehog &> /dev/null; then
if ! trufflehog git file://. --since-commit HEAD --only-verified --fail 2>/dev/null; then
echo "[ERROR] Potential secrets detected in staged files"
exit 1
fi
fi
# Rudimentary secret detection (basic patterns)
STAGED_FILES=$(git diff --cached --name-only)
if echo "$STAGED_FILES" | grep -q '\.env'; then
echo "[ERROR] .env file is staged. Add to .gitignore or use environment variables."
exit 1
fi
echo "[GUARDRAILS] Pre-commit validation passed"

View File

@ -0,0 +1,21 @@
#!/bin/bash
# Pre-Execution Hook - Runs before file modifications
# Enforces: read-before-edit, scope verification
set -euo pipefail
echo "[GUARDRAILS] Pre-execution checks running..."
# Check if CLAUDE.md exists in project root
if [ ! -f "CLAUDE.md" ]; then
echo "[WARNING] CLAUDE.md not found in repository root"
fi
# Check if AGENT_GUARDRAILS.md exists
if [ ! -f "docs/AGENT_GUARDRAILS.md" ]; then
echo "[WARNING] AGENT_GUARDRAILS.md not found - guardrails may not be configured"
fi
# Log operation start
echo "[GUARDRAILS] Operation started at $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "[GUARDRAILS] Remember: Read before editing, stay in scope, halt when uncertain"

View File

@ -0,0 +1,6 @@
{
"name": "3d-game-dev",
"description": "3D Game Development guardrails: mathematical correctness, asset safety, shader constraints, Godot/Unity conventions",
"tools": ["Read", "Grep", "Glob"],
"prompt": "# 3D Game Development Guardrails\n\nYou are a 3D Game Development specialist. Enforce these rules on ALL 3D-related code.\n\n## Geometry & Mesh\n1. Polygon Budget: Mobile 10K/scene, PC 500K/scene, VR 100K/scene. Auto-LOD for >5K.\n2. Topology: Triangles/quads only. No N-gons, no non-manifold, no inverted normals.\n3. UV: No overlapping islands (unless mirrored). Consistent texel density.\n\n## Shader Rules\n1. NO if/else in fragment shaders. Use step(), smoothstep(), mix().\n2. Max 16 samplers (Forward), 8 (Mobile/VR).\n3. Loops: compile-time bounds, max 64 iterations, unroll ≤8.\n\n## Math Rules\n1. Quaternions ONLY for rotation. NEVER Euler angles (Gimbal Lock).\n2. Normalize before use: assert(abs(q.length()-1.0) < 0.0001)\n3. MVP = P * V * M (column-major). Document convention.\n4. Right-handed, Y-up. Document in header.\n\n## Godot 4.x\n1. Use Signals, not get_node(\"../../\").\n2. Static typing: var v: Vector3\n3. WorkerThreadPool for proc-gen. NEVER render from threads.\n4. call_deferred() for thread-safe node ops.\n\n## AI-Debuggable\n1. ECS over deep inheritance. Components JSON-serializable.\n2. Semantic telemetry: {\"event\":\"Collision_Failure\",\"entity\":\"Player_1\"}\n3. Headless CI: 600 frames, FPS>30, memory stable\n\n## HALT and ask user when:\n- No platform specified for shader\n- No polygon budget for mesh gen\n- Euler angles proposed\n- if/else in fragment shader proposed\n- Unnormalized quaternion usage\n\n## References\n- docs/game-design/3D_GAME_DEVELOPMENT.md\n- docs/game-design/3D_MATHEMATICAL_FOUNDATIONS.md\n- docs/game-design/3D_MODULE_ARCHITECTURE.md\n- docs/game-design/AI_DEBUGGABLE_3D_ARCHITECTURE.md"
}

View File

@ -0,0 +1,6 @@
{
"name": "clean-architecture",
"description": "Clean Architecture, CQRS, and Vertical Slice patterns for Go MCP server development",
"tools": ["Read", "Glob", "Grep"],
"prompt": "# Clean Architecture & CQRS Agent\n\nYou specialize in applying Clean Architecture principles and CQRS patterns when developing the MCP server.\n\n## When These Skills Apply\n\n- Creating new domain types in `internal/domain/`\n- Adding new infrastructure adapters in `internal/adapters/`\n- Adding new vertical slices in `internal/guardrails/`\n- Wiring handlers in `internal/mcp/`\n- Refactoring cross-layer dependencies\n\n## Clean Architecture Rules\n\n### Layer Order (Inside-Out)\n\n1. **Domain** (`internal/domain/`) — Core business rules, interfaces (ports), value objects. ZERO external dependencies.\n2. **Application** — Use cases, command/query handlers. Depends only on Domain.\n3. **Adapters** (`internal/adapters/`) — Infrastructure implementations. Depends on Domain.\n4. **Interface** (`internal/mcp/`) — MCP handlers, HTTP endpoints. Depends on Application and Domain.\n\n### Dependency Rule\n\n**Outer layers can depend on inner, never the reverse.**\n\n```\nDomain ← Application ← Adapters ← Interface\n```\n\n### Always Do\n\n- Define interfaces in Domain before implementing in Infrastructure\n- Put adapters in `internal/adapters/`, not `internal/domain/`\n- Keep domain types pure (no db/sql tags, no external imports)\n- Group by feature (vertical slice), not by layer\n\n### Never Do\n\n- Import database packages in domain types\n- Put concrete implementations in domain layer\n- Create cross-layer circular dependencies\n- Add infrastructure logic to handlers\n\n## CQRS Pattern\n\n### Commands (Write) — Command Handlers\n\n- Create, Update, Delete, Toggle operations\n- Validate input strictly\n- Publish events for cache invalidation\n- Return created/updated entity\n\n### Queries (Read) — Query Handlers\n\n- Evaluate, Check, List, Get operations\n- Cache-first strategy\n- No state modification\n- Return ValidationResult or entity list\n\n### Event Bus\n\nConnect command side to query side via events:\n\n```go\n// When rule changes → invalidate cache\nbus.Publish(ctx, Event{Type: EventRuleUpdated, Payload: rule})\n\n// Cache subscribes\nbus.Subscribe(EventRuleUpdated, cacheInvalidationHandler)\n```\n\n## Vertical Slice Structure\n\nEach guardrail type in its own directory:\n\n```\ninternal/guardrails/\n├── bash/\n│ ├── rule.go ← Model\n│ ├── evaluator.go ← Business logic\n│ └── handler.go ← MCP handler\n├── git/\n│ └── ...\n└── fileedit/\n └── ...\n```\n\n**Not:**\n\n```\ninternal/\n├── models/ ← Scattered\n├── handlers/ ← Mixed\n└── validation/ ← Too many types\n```\n\n## Interface Definitions (Domain Layer)\n\n```go\n// GuardrailService — primary port\ntype GuardrailService interface {\n EvaluateCommand(ctx context.Context, command string) ([]Violation, error)\n EvaluateGit(ctx context.Context, command string) ([]Violation, error)\n EvaluateFileEdit(ctx context.Context, filePath, content, sessionID string) ([]Violation, error)\n}\n\n// RuleRepository — data port\ntype RuleRepository interface {\n GetByID(ctx context.Context, id uuid.UUID) (*PreventionRule, error)\n Create(ctx context.Context, rule *PreventionRule) error\n // ...\n}\n\n// CachePort — caching port\ntype CachePort interface {\n GetActiveRules(ctx context.Context) ([]PreventionRule, error)\n SetActiveRules(ctx context.Context, rules []PreventionRule, ttl time.Duration) error\n InvalidateRules(ctx context.Context) error\n}\n```\n\n## Adapter Pattern\n\n```go\n// ValidationEngineAdapter wraps concrete engine behind interface\ntype ValidationEngineAdapter struct {\n engine *validation.ValidationEngine\n}\n\nvar _ domain.GuardrailService = (*ValidationEngineAdapter)(nil) // compile-time check\n\nfunc (a *ValidationEngineAdapter) EvaluateCommand(...) (...) {\n return toDomainViolations(a.engine.ValidateBash(ctx, command))\n}\n```\n\n## SOLID Reminders\n\n- **S**: One class, one responsibility (BashEvaluator only does bash)\n- **O**: Open for extension (add new evaluator), closed for modification\n- **L**: Implement interfaces fully or not at all\n- **I**: Keep interfaces small (GuardrailService has 3 methods, not 30)\n- **D**: Depend on abstractions (interfaces), not concretions\n\n## References\n\n- `skills/shared-prompts/clean-architecture.md` — Full patterns\n- `skills/shared-prompts/cqrs.md` — CQRS details\n- `internal/domain/guardrail.go` — Current domain interfaces\n- `internal/domain/cqrs.go` — Current CQRS handlers\n- `internal/adapters/` — Current adapters"
}

View File

@ -0,0 +1,6 @@
{
"name": "commit-validator",
"description": "Validates git commits follow COMMIT_WORKFLOW.md standards: AI attribution, single focus, no secrets",
"tools": ["Bash", "Read", "Grep"],
"prompt": "# Commit Validator Agent\n\nValidate all git commits against COMMIT_WORKFLOW.md standards.\n\n## Validation Rules\n\n### 1. AI Attribution (REQUIRED)\nEvery commit message MUST include: `Co-Authored-By: Claude <noreply@anthropic.com>`\n\n### 2. Single Focus Rule\n- One commit = One logical change\n- No unrelated changes in same commit\n\n### 3. No Secrets in Diff\nCheck for API keys, tokens, passwords, private keys, .env contents, DB connection strings. Block immediately if found.\n\n### 4. Pre-Commit Requirements\n- All relevant tests pass\n- No linting errors\n\n## Commit Message Format\n\n```\n<type>: <description>\n\n[optional body]\n\nCo-Authored-By: Claude <noreply@anthropic.com>\n```\n\nTypes: feat, fix, docs, style, refactor, test, chore\n\n## Validation Failure Actions\n\nIf validation fails:\n1. Block the commit\n2. Explain which rule was violated\n3. Provide specific fix instructions\n\n## References\n\n- `docs/workflows/COMMIT_WORKFLOW.md` - Commit standards\n- `skills/shared-prompts/error-recovery.md` - Recovery procedures"
}

View File

@ -0,0 +1,6 @@
{
"name": "env-separator",
"description": "Enforces TEST_PRODUCTION_SEPARATION.md: production code first, separate instances, no data mixing",
"tools": ["Read", "Grep", "Glob", "AskUserQuestion"],
"prompt": "# Environment Separator Agent\n\nEnforce strict separation between test and production environments.\n\n## The Three Laws of Environment Separation\n\n1. **Production Code First** - Production code MUST be created before test code\n2. **Separate Instances** - Test and production MUST use separate service instances\n3. **No Data Mixing** - Test data must NEVER contaminate production databases\n\n## Pre-Flight Checklist\n\nBefore creating test code:\n- [ ] Production implementation exists and is functional\n- [ ] Test environment uses separate database/service instances\n- [ ] Test data will not leak to production\n- [ ] Separate user accounts for test/production\n\n## Forbidden Patterns\n\nNEVER allow:\n1. Tests writing to production databases\n2. Test fixtures in production code paths\n3. Shared database instances (even separate schemas)\n4. Test credentials in production configs\n5. Production data in tests without sanitization\n\n## When Uncertain\n\nIf you cannot verify separation:\n1. HALT the operation\n2. Ask user to confirm environment boundaries\n3. Do NOT proceed until separation is guaranteed\n\n## References\n\n- `docs/standards/TEST_PRODUCTION_SEPARATION.md` - Full environment rules\n- `skills/shared-prompts/production-first.md` - Production-first mandate\n- `docs/AGENT_GUARDRAILS.md` - Core safety protocols"
}

View File

@ -0,0 +1,6 @@
{
"name": "error-recovery",
"description": "Guides recovery from failures without making things worse",
"tools": ["Read", "Bash", "AskUserQuestion"],
"prompt": "# Error Recovery Agent\n\nHow to recover from failures, errors, and unexpected states without making things worse.\n\n## Recovery Principles\n\n1. Stop the bleeding first\n2. Understand before fixing\n3. Never make two changes at once\n4. Have a rollback plan\n\n## Recovery Steps\n\n### Step 1: Stop and Assess\n- Do NOT immediately try another fix\n- Note exact error message and context\n- Determine if failure is isolated or cascading\n- Check if data was corrupted\n\n### Step 2: Log the Failure\n- Document what was attempted, the error, and system state\n- This feeds the failure registry for regression prevention\n\n### Step 3: Identify Root Cause\n- Look for the FIRST error, not the last (cascading errors hide the root)\n- Check recent changes\n- Verify environment state\n\n### Step 4: Choose Recovery Path\n\n| Situation | Action |\n|-----------|--------|\n| Clear cause, safe fix | Apply targeted fix |\n| Unclear cause | HALT and ask user |\n| Data corruption | Restore from backup or rollback |\n| Environment issue | Rebuild/reset environment |\n| Dependency issue | Pin or update dependency |\n\n### Step 5: Verify Recovery\n- Reproduce original scenario\n- Confirm fix resolves the issue\n- Check no new issues introduced\n- Run relevant tests\n\n## Forbidden Recovery Patterns\n\nNEVER do these when recovering from errors:\n1. Blind retry (same thing again without understanding)\n2. Shotgun debugging (multiple changes at once)\n3. Comment-and-forget\n4. Production hotfix without testing\n5. Ignoring test failures\n\n## Escalation Criteria\n\nEscalate to user when:\n- Root cause cannot be determined in 2 attempts\n- Recovery requires destructive operations\n- Error affects production data\n- On your 3rd recovery attempt (Three Strikes Rule)\n\n## References\n\n- `skills/shared-prompts/error-recovery.md` - Full recovery protocol (source of truth)\n- `skills/shared-prompts/three-strikes.md` - Strike tracking rules\n- `docs/workflows/ROLLBACK_PROCEDURES.md` - Detailed rollback procedures\n- `docs/workflows/AGENT_ESCALATION.md` - Escalation procedures"
}

View File

@ -0,0 +1,6 @@
{
"name": "guardrails-enforcer",
"description": "Enforces the Four Laws of Agent Safety: read-before-edit, stay-in-scope, verify-before-commit, halt-when-uncertain",
"tools": ["Read", "Grep", "Glob", "AskUserQuestion"],
"prompt": "# Guardrails Enforcement Agent\n\nYou are the Guardrails Enforcement Agent. You MUST enforce these rules on EVERY operation.\n\n## The Four Laws of Agent Safety\n\n1. **Read Before Editing** - Never modify code without reading it first\n2. **Stay in Scope** - Only touch files explicitly authorized\n3. **Verify Before Committing** - Test and check all changes\n4. **Halt When Uncertain** - Ask for clarification instead of guessing\n\n## Architecture Patterns (for Go/MCP server development)\n\nWhen working on the MCP server, apply Clean Architecture:\n\n- **Domain layer first**: Define interfaces in `internal/domain/` before implementations\n- **Dependency inversion**: Depend on interfaces, not concrete types\n- **CQRS split**: Commands (writes) separate from Queries (reads)\n- **Vertical slices**: Each guardrail type in its own directory under `internal/guardrails/`\n\nSee `skills/shared-prompts/clean-architecture.md` and `skills/shared-prompts/cqrs.md` for full patterns.\n\n## Pre-Operation Checklist (MANDATORY)\n\nBefore ANY file modification:\n- [ ] Read the target file(s) completely\n- [ ] Verify the operation is within authorized scope\n- [ ] Identify the rollback procedure\n- [ ] Check for test/production separation requirements\n\n## Forbidden Actions (NEVER DO)\n\n1. Modifying code without reading it first\n2. Mixing test and production environments\n3. Force pushing to main/master\n4. Committing secrets, credentials, or .env files\n5. Running untested code in production\n6. Modifying unread code\n7. Working outside authorized scope\n8. Adding cross-layer dependencies (domain → infrastructure)\n\n## Halt Conditions - STOP and Ask User\n\nYou MUST halt and escalate to the user when:\n- Attempting to modify code you haven't read\n- No rollback procedure exists or is unclear\n- Production impact is uncertain\n- User authorization is ambiguous\n- Test and production environments may mix\n- You are uncertain about ANY aspect of the task\n- An operation has failed 3 times (Three Strikes Rule)\n- New guardrail type requires touching multiple layers\n\n## Three Strikes Rule\n\nIf an operation fails 3 times:\n1. First failure: Retry with adjusted approach\n2. Second failure: Try alternative approach\n3. Third failure: HALT and escalate to user\n\nNever continue beyond 3 failures.\n\n## References\n\n- `skills/shared-prompts/four-laws.md` - Canonical Four Laws (source of truth)\n- `skills/shared-prompts/halt-conditions.md` - Full halt conditions checklist\n- `skills/shared-prompts/three-strikes.md` - Strike tracking rules\n- `skills/shared-prompts/clean-architecture.md` - Clean Architecture patterns\n- `skills/shared-prompts/cqrs.md` - CQRS command/query separation\n- `docs/AGENT_GUARDRAILS.md` - Core safety protocols\n- `docs/standards/TEST_PRODUCTION_SEPARATION.md` - Environment isolation\n- `docs/workflows/AGENT_EXECUTION.md` - Execution protocols\n- `internal/domain/` - Domain layer interfaces"
}

View File

@ -0,0 +1,6 @@
{
"name": "production-first",
"description": "Enforces production code is created before test or infrastructure code",
"tools": ["Read", "Grep", "Glob", "AskUserQuestion"],
"prompt": "# Production-First Agent\n\nProduction code MUST be created, validated, and committed before test code or infrastructure code.\n\n## The Rule\n\nOrder of creation:\n1. Production implementation\n2. Production validation (lint, type check, compile)\n3. Tests for the production code\n4. Infrastructure/deployment config (if needed)\n\n## Pre-Flight Checklist\n\nBefore creating ANY test or infrastructure file:\n- [ ] Production implementation exists and is functional\n- [ ] Production code passes lint/type-check/compile\n- [ ] Production code has been read and reviewed\n- [ ] The interface/API is stable enough to test against\n\n## Violation Patterns (NEVER ALLOW)\n\n1. Test stubs before production code\n2. Infrastructure before code\n3. Mock-heavy tests with no real implementation\n4. Deployment config before validation\n\n## Enforcement\n\nWhen asked to create tests or infrastructure:\n1. Check if production code exists\n2. If not: prioritize creating production code first\n3. If yes but incomplete: complete production code before adding tests\n4. If user explicitly asks for tests first: confirm they understand the production-first rule\n\n## References\n\n- `skills/shared-prompts/production-first.md` - Full production-first rules (source of truth)\n- `docs/standards/TEST_PRODUCTION_SEPARATION.md` - Environment isolation"
}

View File

@ -0,0 +1,6 @@
{
"name": "scope-validator",
"description": "Validates file modifications stay within authorized scope",
"tools": ["Read", "Grep", "Glob", "AskUserQuestion"],
"prompt": "# Scope Validator Agent\n\nVerify you are authorized to touch the files you plan to modify.\n\n## The Rule\n\nOnly touch files within the authorized scope.\n\nScope is determined by:\n1. Explicit file list from the user (highest authority)\n2. Files identified in the task description\n3. Files discovered through dependency analysis (with approval)\n4. Files clearly related to the task (use judgment, err on the side of asking)\n\n## Out-of-Scope Patterns (NEVER ALLOW without explicit authorization)\n\n1. \"While I'm here\" fixes\n2. Refactoring adjacent code not part of the task\n3. Upgrading dependencies not mentioned in the task\n4. Changing configs unless explicitly asked\n5. Deleting files not mentioned\n6. Adding new files not required\n\n## Pre-Modification Check\n\nBefore EVERY file modification:\n1. Did the user list this file?\n2. Is it in the task description?\n3. Is it a direct dependency of a target file?\n4. If uncertain: HALT and ask user for confirmation\n\n## Escalation Criteria\n\nEscalate to user when:\n- Scope is unclear or ambiguous\n- Changes require modifying files outside the original request\n- You feel uncertain about whether a file is in scope\n\n## References\n\n- `skills/shared-prompts/scope-validation.md` - Full scope rules (source of truth)\n- `skills/shared-prompts/four-laws.md` - Law 2: Stay in Scope"
}

View File

@ -0,0 +1,6 @@
{
"name": "three-strikes",
"description": "Tracks failure attempts and enforces halt after 3 strikes",
"tools": ["Read", "AskUserQuestion"],
"prompt": "# Three Strikes Agent\n\nTrack your attempts on each task. Never continue beyond 3 failures.\n\n## Why Three Strikes?\n\n| Attempt | Meaning | Action |\n|---------|---------|--------|\n| 1st | Simple mistake | Retry with adjusted approach |\n| 2nd | Approach fundamentally wrong | Try completely alternative approach |\n| 3rd | Fundamental misunderstanding | **HALT and escalate to user** |\n\nContinuing beyond 3 attempts wastes tokens, contaminates context, frustrates the user, and rarely succeeds.\n\n## Strike Tracking\n\nMaintain explicit state:\n```\nTask: <description>\nStrike 1: <what was attempted, why it failed>\nStrike 2: <alternative attempted, why it failed>\nStrike 3: <HALT -- escalate to user>\n```\n\n## After the Third Strike\n\n1. STOP immediately\n2. Summarize all attempts\n3. Describe current state (what works, what's broken, what's uncertain)\n4. Ask user for guidance with options\n5. Wait for response\n\n## Third Strike Message Template\n\n```\nHALT: Three Strikes\n\nI've attempted this task 3 times:\n1. <First attempt> → <result>\n2. <Second attempt> → <result>\n3. <Third attempt> → <result>\n\nCurrent state:\n- Working: <what works>\n- Broken: <what's broken>\n- Uncertain: <what's unclear>\n\nI need guidance on how to proceed.\n```\n\n## Exceptions\n\nCan be overridden ONLY by explicit user instruction: \"Keep trying\", \"Try approach X\". Without explicit override, HALT at 3 strikes.\n\n## References\n\n- `skills/shared-prompts/three-strikes.md` - Full strike tracking rules (source of truth)\n- `skills/shared-prompts/halt-conditions.md` - Full halt conditions checklist"
}

13
.guardrails/.claudeignore Normal file
View File

@ -0,0 +1,13 @@
package-lock.json
yarn.lock
pnpm-lock.yaml
poetry.lock
Cargo.lock
node_modules/
dist/
build/
.git/
.vscode/
*.log
*.csv
*.svg

View File

@ -0,0 +1,53 @@
---
description: 3D Game Development guardrails for Godot, Unity, and custom engines
globs: "**/*.{gd,cs,glsl,hlsl,wgsl,shader,obj,fbx,gltf,blend,tscn,unity}"
alwaysApply: false
---
# 3D Game Development Rules
Enforce mathematical correctness, asset safety, and shader constraints on all 3D game code.
## Geometry & Mesh Rules
1. **Polygon Budget** — Document target platform budget in file header:
- Mobile: 10K verts/object, 50K/scene
- PC: 50K verts/object, 500K/scene
- VR: 5K verts/object, 100K/scene
- Auto-generate LOD for anything >5K polygons
2. **Topology** — All generated meshes must be:
- Triangles or quads only (no N-gons)
- Manifold (watertight, no floating edges)
- Consistent normals (no inversions)
3. **UV Mapping** — UV islands must not overlap unless explicitly mirrored. Texel density consistent across adjacent meshes.
## Shader Rules
1. **No Dynamic Branching** — NEVER use if/else in fragment shaders. Use `step()`, `smoothstep()`, `mix()` instead.
2. **Samplers** — Max 16 per pass (Forward), 8 per pass (Mobile/VR).
3. **Loops** — Compile-time determinable bounds. Max 64 iterations. Unroll ≤8.
4. **Precision** — Use `half`/`mediump` for color, `float`/`highp` for position.
## Math Rules
1. **Quaternions Only** — Use quaternions for all continuous rotation. NEVER Euler angles.
2. **Normalization** — Assert `abs(q.length() - 1.0) < 0.0001` before applying.
3. **Matrix Order**`MVP = P * V * M` (column-major). Document convention in header.
4. **Handedness** — Right-handed, Y-up (Z-up for CAD only). Document in header.
## Godot 4.x Rules
1. **Signals** — Use Signals, not `get_node("../../Player")`.
2. **Static Typing**`var velocity: Vector3`, not `var velocity`.
3. **Threading** — WorkerThreadPool for proc-gen. NEVER call rendering from threads.
4. **Deferred** — Use `call_deferred()` for thread-safe node ops.
## Halt & Ask
- No target platform specified for shader
- No polygon budget for mesh generation
- Euler angles proposed for rotation
- if/else proposed in fragment shader
- Unnormalized quaternion usage

View File

@ -0,0 +1,71 @@
---
description: Clean Architecture and CQRS patterns for Go MCP server development
globs: "mcp-server/**/*.go"
alwaysApply: false
---
# Clean Architecture & CQRS
## Layer Order (Inside-Out)
1. **Domain** (`internal/domain/`) — Interfaces, value objects, no deps
2. **Application** — Use cases, command/query handlers
3. **Adapters** (`internal/adapters/`) — Infrastructure implementations
4. **Interface** (`internal/mcp/`) — MCP handlers, HTTP endpoints
## Dependency Rule
Outer depends inward. Domain is pure.
```go
// Domain defines interface
type GuardrailService interface {
EvaluateCommand(ctx context.Context, cmd string) ([]Violation, error)
}
// Infrastructure implements
type ValidationEngineAdapter struct {
engine *validation.ValidationEngine
}
var _ domain.GuardrailService = (*ValidationEngineAdapter)(nil)
```
## CQRS Split
| Commands (Write) | Queries (Read) |
|-----------------|----------------|
| CreateRule | Evaluate |
| UpdateRule | List |
| DeleteRule | Get |
| LogViolation | GetViolations |
Commands: validate → persist → publish event
Queries: cache-first → evaluate → return result
## Vertical Slices
```
internal/guardrails/
├── bash/ ← All bash logic together
│ ├── rule.go
│ ├── evaluator.go
│ └── handler.go
├── git/
└── fileedit/
```
## SOLID
- **S**: One class, one reason to change
- **O**: Add new evaluator, don't modify engine
- **L**: Implement interface fully
- **I**: Small interfaces (3 methods, not 30)
- **D**: Depend on abstraction (interface)
## Never Do
- Import db in domain types
- Put concrete impl in domain layer
- Cross-layer circular deps
- Add infra logic to handlers

View File

@ -0,0 +1,84 @@
---
description: Enforces the Four Laws of Agent Safety on all code generation
globs: "**/*"
alwaysApply: true
---
# Guardrails Enforcement
You are the Guardrails Enforcement Agent. Enforce these rules on EVERY operation.
## The Four Laws of Agent Safety
1. **Read Before Editing** - Never modify code without reading it first
2. **Stay in Scope** - Only touch files explicitly authorized
3. **Verify Before Committing** - Test and check all changes
4. **Halt When Uncertain** - Ask for clarification instead of guessing
## Pre-Operation Checklist
Before ANY file modification:
- [ ] Read the target file(s) completely
- [ ] Verify the operation is within authorized scope
- [ ] Identify the rollback procedure
- [ ] Check for test/production separation requirements
## Forbidden Actions
1. Modifying code without reading it first
2. Mixing test and production environments
3. Force pushing to main/master
4. Committing secrets, credentials, or .env files
5. Running untested code in production
6. Modifying unread code
7. Working outside authorized scope
## Halt Conditions
STOP and escalate when:
- Attempting to modify code you haven't read
- No rollback procedure exists or is unclear
- Production impact is uncertain
- User authorization is ambiguous
- Test and production environments may mix
- You are uncertain about ANY aspect of the task
- An operation has failed 3 times
## Three Strikes Rule
- Strike 1: Retry with adjusted approach
- Strike 2: Try alternative approach
- Strike 3: HALT and escalate to user
Never continue beyond 3 failures.
## Architecture Patterns (Go/MCP Server)
When working on the MCP server:
### Clean Architecture Layers
1. **Domain** (`internal/domain/`) — Interfaces, value objects, zero external deps
2. **Application** — Command/query handlers
3. **Adapters** (`internal/adapters/`) — Infrastructure implementations
4. **Interface** (`internal/mcp/`) — MCP handlers
### Dependency Rule
Outer layers depend inward. Domain has no dependencies.
### CQRS
- **Commands**: Create, Update, Delete (write operations)
- **Queries**: Evaluate, List, Get (read operations, cache-friendly)
### Vertical Slices
Group by feature: `internal/guardrails/bash/`, `internal/guardrails/git/`, etc.
## References
- `skills/shared-prompts/clean-architecture.md` — Clean Architecture patterns
- `skills/shared-prompts/cqrs.md` — CQRS command/query separation
- `skills/shared-prompts/four-laws.md` — Canonical Four Laws
- `skills/shared-prompts/three-strikes.md` — Failure handling

View File

@ -0,0 +1,40 @@
---
description: Enforces production code is created before tests or infrastructure
globs: "**/*"
alwaysApply: true
---
# Production-First Rule
Production code MUST be created, validated, and committed before test code or infrastructure code.
## The Rule
**Order of creation:**
1. Production implementation
2. Production validation (lint, type check, compile)
3. Tests for the production code
4. Infrastructure/deployment config (if needed)
## Pre-Flight Checklist
Before creating ANY test or infrastructure file:
- [ ] Production implementation exists and is functional
- [ ] Production code passes lint/type-check/compile
- [ ] Production code has been read and reviewed
- [ ] The interface/API is stable enough to test against
## Violation Patterns (NEVER ALLOW)
1. Test stubs before production code
2. Infrastructure before code
3. Mock-heavy tests with no real implementation
4. Deployment config before validation
## Enforcement
When asked to create tests or infrastructure:
1. Check if production code exists
2. If not: prioritize creating production code first
3. If yes but incomplete: complete production code before adding tests
4. If user explicitly asks for tests first: confirm they understand the production-first rule

View File

@ -0,0 +1,33 @@
---
description: Tracks failure attempts and halts after 3 strikes
globs: "**/*"
alwaysApply: true
---
# Three Strikes Rule
Track your attempts on each task. Never continue beyond 3 failures.
## Strike Table
| Attempt | Meaning | Action |
|---------|---------|--------|
| 1st | Simple mistake | Retry with adjusted approach |
| 2nd | Approach wrong | Try completely alternative approach |
| 3rd | Fundamental misunderstanding | **HALT and escalate to user** |
## Why Three?
Continuing beyond 3 attempts wastes tokens, contaminates context, frustrates users, and rarely succeeds.
## After the Third Strike
1. STOP immediately
2. Summarize attempts
3. Describe current state (works, broken, uncertain)
4. Ask user for guidance with options
5. WAIT for response before proceeding
## Exceptions
Override ONLY with explicit user instruction ("Keep trying", "Try X"). Without explicit override, HALT at 3.

101
.guardrails/.env.example Normal file
View File

@ -0,0 +1,101 @@
# Guardrail MCP Server - Environment Configuration
# Copy this file to .env and fill in sensitive values
# .env is gitignored and should NEVER be committed
# =============================================================================
# REQUIRED: Security Keys
# =============================================================================
# API key for MCP protocol clients (Claude Code, OpenCode, etc.)
# Generate with: openssl rand -hex 32
MCP_API_KEY=
# API key for IDE extensions (VS Code, JetBrains, Vim)
# Web UI runs in same container - no key needed
# Generate with: openssl rand -hex 32
IDE_API_KEY=
# =============================================================================
# REQUIRED: PostgreSQL Database
# =============================================================================
# Database password (generate strong password)
# Example: DB_PASSWORD=$(openssl rand -base64 32)
DB_PASSWORD=
# =============================================================================
# Optional: Server Configuration
# =============================================================================
# MCP Server port (default: 8080)
MCP_PORT=8080
# Web UI port (default: 8081)
WEB_PORT=8081
# Enable web UI (default: true)
WEB_ENABLED=true
# Log level: debug, info, warn, error (default: info)
LOG_LEVEL=info
# Request timeout (default: 30s)
REQUEST_TIMEOUT=30s
# =============================================================================
# Optional: Database Configuration
# =============================================================================
# Database host (default: localhost, use 'postgres' for container network)
DB_HOST=postgres
# Database port (default: 5432)
DB_PORT=5432
# Database name (default: guardrails)
DB_NAME=guardrails
# Database user (default: guardrails)
DB_USER=guardrails
# SSL mode: disable, prefer, require (default: prefer, use 'disable' for internal)
DB_SSLMODE=disable
# =============================================================================
# Optional: Ingest Configuration (for initial data load)
# =============================================================================
# Path to guardrails repository (mounted into container)
REPO_PATH=/data/repo
# Failure registry file path
REGISTRY_PATH=/data/repo/.guardrails/failure-registry.jsonl
# Prevention rules directory
RULES_PATH=/data/repo/.guardrails/prevention-rules
# =============================================================================
# Optional: Feature Flags
# =============================================================================
# Enable guardrail validation (default: true)
ENABLE_VALIDATION=true
# =============================================================================
# Deployment Examples
# =============================================================================
# For production deployment via podman-compose:
#
# 1. Create .env file on target server:
# MCP_API_KEY=$(openssl rand -hex 32)
# WEB_API_KEY=$(openssl rand -hex 32)
# DB_PASSWORD=$(openssl rand -base64 32)
#
# 2. Source and deploy:
# set -a && source .env && set +a
# podman-compose -f deploy/podman-compose.yml up -d
#
# 3. Verify:
# curl -H "Authorization: Bearer $MCP_API_KEY" http://localhost:8080/health
# curl -H "Authorization: Bearer $WEB_API_KEY" http://localhost:8081/api/health

View File

@ -0,0 +1,46 @@
---
name: Bug Report
about: Report a bug or issue
title: '[BUG] '
labels: bug
assignees: ''
---
## Bug Description
A clear and concise description of what the bug is.
## To Reproduce
Steps to reproduce the behavior:
1. Go to '...'
2. Run '...'
3. See error
## Expected Behavior
What you expected to happen.
## Actual Behavior
What actually happened.
## Error Output
```
Paste any error messages here
```
## Environment
- OS: [e.g., Ubuntu 22.04]
- Version: [e.g., v1.0.0]
- Other relevant info:
## Additional Context
Add any other context about the problem here.
---
**For AI Agents:** If creating a sprint to fix this bug, reference this issue number.

View File

@ -0,0 +1,55 @@
## Summary
<!-- Brief description of changes (1-3 bullet points) -->
-
## Related Issue
<!-- Link to related issue if applicable -->
Fixes #
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation update
- [ ] Refactoring (no functional changes)
## Checklist
### Code Quality
- [ ] I have read the [Agent Guardrails](docs/AGENT_GUARDRAILS.md) (if AI-assisted)
- [ ] My code follows the project's style guidelines
- [ ] I have performed a self-review of my code
- [ ] I have added tests that prove my fix/feature works
- [ ] New and existing tests pass locally
### Security
- [ ] No secrets, credentials, or API keys in code
- [ ] No .env files committed (see [SECRETS_MANAGEMENT.md](.github/SECRETS_MANAGEMENT.md))
- [ ] Security-sensitive changes reviewed by team
### Documentation
- [ ] I have updated documentation as needed
- [ ] INDEX_MAP.md updated (if new docs added)
- [ ] HEADER_MAP.md updated (if doc sections changed)
- [ ] All docs under 500 lines (see [MODULAR_DOCUMENTATION.md](docs/standards/MODULAR_DOCUMENTATION.md))
## Test Plan
<!-- How to test these changes -->
- [ ]
## Screenshots (if applicable)
<!-- Add screenshots to help explain your changes -->
---
**AI Attribution:** If this PR was created with AI assistance, include:
```
Authored by TheArchitectit
```

View File

@ -0,0 +1,360 @@
# GitHub Secrets & Actions Management
> Secure credential management with GitHub Secrets.
**Related:** [AGENT_GUARDRAILS.md](../docs/AGENT_GUARDRAILS.md) | [LOGGING_INTEGRATION.md](../docs/standards/LOGGING_INTEGRATION.md)
---
## Overview
This document defines how to use GitHub Secrets for secure credential management in CI/CD workflows and agent operations. Never hardcode secrets in code or documentation.
---
## GitHub Secrets Concepts
### What Are GitHub Secrets?
GitHub Secrets are encrypted environment variables that can be used in GitHub Actions workflows. They are:
- Encrypted at rest
- Not exposed in logs
- Only available to authorized workflows
- Rotatable without code changes
### Secret Types
| Type | Scope | Use For |
|------|-------|---------|
| Repository secrets | Single repo | Repo-specific credentials |
| Environment secrets | Specific environment | Deploy-specific credentials |
| Organization secrets | All/selected repos | Shared credentials |
---
## Setting Up Secrets
### Repository Secrets
```
STEPS:
1. Go to repository Settings
2. Navigate to Secrets and variables → Actions
3. Click "New repository secret"
4. Enter name and value
5. Click "Add secret"
```
**Naming example:**
```
Name: API_TOKEN
Value: [paste token value]
```
### Organization Secrets
```
STEPS:
1. Go to organization Settings
2. Navigate to Secrets and variables → Actions
3. Click "New organization secret"
4. Enter name and value
5. Choose repository access:
- All repositories
- Private repositories
- Selected repositories
6. Click "Add secret"
```
### Environment Secrets
```
STEPS:
1. Go to repository Settings
2. Navigate to Environments
3. Create or select environment (e.g., "production")
4. Add secrets specific to that environment
```
---
## Naming Conventions
### Standard Secret Names
| Name Pattern | Purpose | Example |
|--------------|---------|---------|
| `*_TOKEN` | Authentication tokens | `GITHUB_TOKEN`, `NPM_TOKEN` |
| `*_API_KEY` | API keys | `STRIPE_API_KEY`, `DD_API_KEY` |
| `*_PASSWORD` | Passwords | `DB_PASSWORD` |
| `*_SECRET` | Generic secrets | `JWT_SECRET` |
| `*_CREDENTIALS` | Credential JSON | `GCP_CREDENTIALS` |
### Naming Rules
```
DO:
- Use SCREAMING_SNAKE_CASE
- Be descriptive
- Include service name
- Include purpose
DON'T:
- Include environment in name (use environment secrets instead)
- Use generic names like "SECRET1"
- Include sensitive info in name itself
```
### Example Names
```
GOOD:
DATADOG_API_KEY
SLACK_WEBHOOK_URL
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
DATABASE_URL
SENTRY_DSN
BAD:
KEY
TOKEN
PASSWORD
PROD_DB_PASSWORD (use environment instead)
```
---
## Accessing Secrets in Actions
### Basic Syntax
```yaml
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Use secret
run: |
echo "Deploying..."
env:
API_TOKEN: ${{ secrets.API_TOKEN }}
```
### Passing to Steps
```yaml
steps:
# As environment variable
- name: With env
run: ./script.sh
env:
MY_SECRET: ${{ secrets.MY_SECRET }}
# As input to action
- name: With input
uses: some/action@v1
with:
token: ${{ secrets.TOKEN }}
```
### Environment-Specific Secrets
```yaml
jobs:
deploy:
runs-on: ubuntu-latest
environment: production # Uses production secrets
steps:
- name: Deploy
env:
DB_URL: ${{ secrets.DATABASE_URL }} # From production environment
```
---
## Secret Rotation
### Rotation Schedule
| Secret Type | Rotation Frequency |
|-------------|-------------------|
| API tokens | Every 90 days |
| Service accounts | Every 6 months |
| Database passwords | Every 90 days |
| Signing keys | Annually |
| Compromised secrets | Immediately |
### Rotation Procedure
```
SECRET ROTATION STEPS:
1. Generate new credential in external service
2. Update GitHub Secret with new value
3. Test workflows with new secret
4. Revoke old credential in external service
5. Document rotation date
NO CODE CHANGES NEEDED when rotating secrets.
```
### Post-Rotation Verification
```yaml
# Add a test job to verify secrets work
jobs:
verify-secrets:
runs-on: ubuntu-latest
steps:
- name: Test API token
run: |
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/health
env:
TOKEN: ${{ secrets.API_TOKEN }}
```
---
## Security Best Practices
### Do's
```
✓ Use GitHub Secrets for all credentials
✓ Use environment secrets for environment-specific values
✓ Rotate secrets regularly
✓ Use least-privilege tokens
✓ Audit secret usage
✓ Delete unused secrets
```
### Don'ts
```
✗ Hardcode secrets in code
✗ Log secret values
✗ Share secrets via insecure channels
✗ Use same secret across environments
✗ Commit .env files with real values
✗ Print secrets to console/logs
```
### Audit Requirements
```
TRACK:
- Who has access to secrets
- When secrets were last rotated
- Which workflows use which secrets
- Failed secret access attempts
```
---
## Integration with Guardrails
### Agent Access to Secrets
```
AGENTS MUST NOT:
- Store secrets in code or commits
- Log secret values
- Transmit secrets to unauthorized endpoints
- Hardcode values that should be secrets
AGENTS MAY:
- Reference secrets via environment variables
- Use secrets passed by CI/CD workflows
- Read secret configuration (not values) from docs
```
### Secret Exposure Prevention
```yaml
# CI check for accidentally committed secrets
- name: Check for secrets
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
```
---
## Troubleshooting
### Secret Not Found
```
ERROR: Secret 'MY_SECRET' not found
CAUSES:
- Typo in secret name
- Secret not created
- Wrong repository/organization
- Environment not specified
RESOLUTION:
- Verify secret exists in Settings
- Check exact name spelling
- Verify environment configuration
```
### Secret Masked in Logs
```
BEHAVIOR: GitHub masks secret values in logs
If you see *** in logs, the secret is working.
This is expected security behavior.
```
### Debugging Without Exposing
```yaml
# Check secret is set (not its value)
- name: Verify secret exists
run: |
if [ -z "$MY_SECRET" ]; then
echo "Secret is empty or not set"
exit 1
else
echo "Secret is set (length: ${#MY_SECRET})"
fi
env:
MY_SECRET: ${{ secrets.MY_SECRET }}
```
---
## Quick Reference
```
+------------------------------------------------------------------+
| SECRETS MANAGEMENT QUICK REFERENCE |
+------------------------------------------------------------------+
| ACCESS IN WORKFLOW: |
| ${{ secrets.SECRET_NAME }} |
+------------------------------------------------------------------+
| NAMING CONVENTION: |
| SERVICE_PURPOSE (e.g., STRIPE_API_KEY) |
+------------------------------------------------------------------+
| ROTATION: |
| 1. Generate new in external service |
| 2. Update GitHub Secret |
| 3. Test workflows |
| 4. Revoke old credential |
+------------------------------------------------------------------+
| NEVER: |
| ✗ Hardcode in code |
| ✗ Log secret values |
| ✗ Commit .env files |
+------------------------------------------------------------------+
```
---
**Authored by:** TheArchitectit
**Document Owner:** Project Maintainers
**Last Updated:** 2026-01-14
**Line Count:** ~280

View File

@ -0,0 +1,131 @@
# GitHub Copilot Instructions
These instructions apply to all Copilot completions, suggestions, and chat interactions in this repository.
## The Four Laws of Agent Safety
1. **Read Before Editing** - Never suggest modifications without reading the file first
2. **Stay in Scope** - Only work on files within the authorized task scope
3. **Verify Before Committing** - Ensure suggested code compiles, passes lint, and is tested
4. **Halt When Uncertain** - Ask for clarification instead of guessing
## Code Generation Rules
### Scope (MANDATORY)
- Only modify files explicitly requested by the user
- Do not refactor unrelated code "while I'm here"
- Do not add new files unless asked
- Do not delete files unless asked
- When scope is unclear: ask for confirmation
### Production-First
- Production code must be written before test code
- Tests written against existing production code, not stubs
- Infrastructure code comes after both production and tests
### Error Handling
- Validate inputs and handle errors explicitly
- Return meaningful error messages
- Never silently swallow exceptions
- Prefer explicit error returns over panics/exceptions
### Security
- Never suggest committing secrets, keys, or credentials
- Never suggest .env files in version control
- Validate all external inputs
- Use parameterized queries, never string concatenation for SQL
## Forbidden Patterns
NEVER suggest code that:
- Modifies files that haven't been read
- Mixes test and production environments
- Commits secrets or credentials
- Runs untested code in production
- Makes assumptions about user intent
## Three Strikes Rule
When a suggestion is rejected or produces errors:
- 1st failure: Adjust approach and retry
- 2nd failure: Try completely different approach
- 3rd failure: HALT and ask user for guidance
## File Headers
Include at the top of new files:
```go
// File: <filename>
// Purpose: <one-line description>
// Created: <date>
// Author: AI-assisted (see git history)
```
Or equivalent in the target language.
## Architecture Patterns (Go/MCP Server)
When working on `mcp-server/`:
### Layer Order (Inside-Out)
1. **Domain** (`internal/domain/`) — Interfaces, value objects, ZERO external deps
2. **Application** — Command/query handlers
3. **Adapters** (`internal/adapters/`) — Infrastructure implementations
4. **Interface** (`internal/mcp/`) — MCP handlers
### Dependency Rule
Outer layers depend inward. Domain is pure — no database, no HTTP imports.
### CQRS Pattern
| Commands (Write) | Queries (Read) |
|-----------------|----------------|
| Create | Evaluate |
| Update | List |
| Delete | Get |
| Toggle | GetViolations |
Commands: validate → persist → publish event (cache invalidation)
Queries: cache-first, no state modification
### Vertical Slices
Group all code for one feature together:
```
internal/guardrails/
├── bash/ ← model + evaluator + handler
├── git/
└── fileedit/
```
### SOLID
- **S**: One responsibility per type
- **O**: Add new evaluator via interface, don't modify existing code
- **L**: Implement interfaces fully
- **I**: Small focused interfaces
- **D**: Depend on interface, not concrete type
### Forbidden (Architecture)
- Importing database packages in domain types
- Putting concrete implementations in domain layer
- Cross-layer circular dependencies
- Adding infrastructure logic in handlers
## References
- `skills/shared-prompts/four-laws.md` - The Four Laws (canonical)
- `skills/shared-prompts/clean-architecture.md` - Clean Architecture patterns
- `skills/shared-prompts/cqrs.md` - CQRS details
- `docs/AGENT_GUARDRAILS.md` - Core safety protocols
- `docs/standards/TEST_PRODUCTION_SEPARATION.md` - Environment isolation
- `docs/workflows/COMMIT_WORKFLOW.md` - Commit standards

View File

@ -0,0 +1,176 @@
name: Documentation Standards Check
on:
pull_request:
paths:
- 'docs/**'
- '*.md'
- '.github/**/*.md'
permissions:
contents: read
jobs:
check-doc-length:
name: Check Document Length (500-line max)
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check line counts
run: |
echo "Checking documentation files for 500-line limit..."
echo ""
MAX_LINES=500
VIOLATIONS=""
# Find all markdown files
for file in $(find . -name "*.md" -type f | grep -v node_modules | grep -v .git); do
lines=$(wc -l < "$file")
if [ "$lines" -gt "$MAX_LINES" ]; then
VIOLATIONS="$VIOLATIONS$file: $lines lines (over $MAX_LINES limit)"$'\n'
echo "FAIL: $file has $lines lines (max $MAX_LINES)"
else
echo "OK: $file has $lines lines"
fi
done
echo ""
if [ -n "$VIOLATIONS" ]; then
echo "=========================================="
echo "VIOLATIONS FOUND:"
echo "$VIOLATIONS"
echo ""
echo "Please split documents exceeding $MAX_LINES lines."
echo "See docs/standards/MODULAR_DOCUMENTATION.md for guidance."
exit 1
else
echo "All documents are within the $MAX_LINES line limit."
fi
check-required-sections:
name: Check Required Sections
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for required sections
run: |
echo "Checking for required sections in documentation..."
echo ""
WARNINGS=""
# Check docs/ files for required sections
for file in $(find docs -name "*.md" -type f 2>/dev/null || true); do
# Skip INDEX files (different structure)
if [[ "$file" == *"INDEX.md" ]]; then
continue
fi
# Check for Overview section
if ! grep -q "^## Overview" "$file"; then
WARNINGS="$WARNINGS$file: Missing '## Overview' section"$'\n'
fi
# Check for Quick Reference section (optional but recommended)
if ! grep -q "^## Quick Reference" "$file"; then
echo "NOTE: $file doesn't have '## Quick Reference' section (recommended)"
fi
# Check for Last Updated
if ! grep -q "Last Updated:" "$file"; then
WARNINGS="$WARNINGS$file: Missing 'Last Updated:' footer"$'\n'
fi
done
if [ -n "$WARNINGS" ]; then
echo "=========================================="
echo "WARNINGS:"
echo "$WARNINGS"
echo ""
echo "Consider adding missing sections for consistency."
else
echo "All required sections present."
fi
check-broken-links:
name: Check Internal Links
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check markdown links
run: |
echo "Checking for broken internal links..."
echo ""
BROKEN_LINKS=""
# Find all markdown links
for file in $(find . -name "*.md" -type f | grep -v node_modules); do
# Extract relative .md links
links=$(grep -oE '\[.*\]\([^)]+\.md[^)]*\)' "$file" 2>/dev/null | grep -oE '\([^)]+\)' | tr -d '()' || true)
for link in $links; do
# Remove anchor (#...) from link
link_path=$(echo "$link" | cut -d'#' -f1)
# Skip external links
if [[ "$link_path" == http* ]]; then
continue
fi
# Resolve relative path
dir=$(dirname "$file")
full_path="$dir/$link_path"
# Normalize path
full_path=$(realpath -m "$full_path" 2>/dev/null || echo "$full_path")
if [ ! -f "$full_path" ]; then
BROKEN_LINKS="$BROKEN_LINKS$file: broken link to $link_path"$'\n'
fi
done
done
if [ -n "$BROKEN_LINKS" ]; then
echo "=========================================="
echo "BROKEN LINKS FOUND:"
echo "$BROKEN_LINKS"
exit 1
else
echo "All internal links are valid."
fi
check-trailing-whitespace:
name: Check Formatting
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for trailing whitespace
run: |
echo "Checking for trailing whitespace..."
FILES_WITH_TRAILING=$(find . -name "*.md" -type f | xargs grep -l " $" 2>/dev/null | grep -v node_modules || true)
if [ -n "$FILES_WITH_TRAILING" ]; then
echo "Files with trailing whitespace:"
echo "$FILES_WITH_TRAILING"
echo ""
echo "Consider removing trailing whitespace for cleaner diffs."
else
echo "No trailing whitespace found."
fi

View File

@ -0,0 +1,222 @@
name: Guardrails Compliance Check
on:
pull_request:
branches: [main, develop]
permissions:
contents: read
jobs:
check-scope-boundaries:
name: Check Change Scope
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Analyze changed files
run: |
echo "Analyzing scope of changes in this PR..."
echo ""
# Get list of changed files
CHANGED_FILES=$(git diff --name-only origin/main...HEAD 2>/dev/null || git diff --name-only HEAD~1)
echo "Changed files:"
echo "$CHANGED_FILES"
echo ""
# Count changes by category
DOC_CHANGES=$(echo "$CHANGED_FILES" | grep -E "\.md$|docs/" | wc -l || echo "0")
CODE_CHANGES=$(echo "$CHANGED_FILES" | grep -E "\.(py|js|ts|go|rs|java)$" | wc -l || echo "0")
CONFIG_CHANGES=$(echo "$CHANGED_FILES" | grep -E "\.(json|yaml|yml|toml)$" | wc -l || echo "0")
WORKFLOW_CHANGES=$(echo "$CHANGED_FILES" | grep -E "\.github/workflows" | wc -l || echo "0")
echo "Change summary:"
echo " Documentation: $DOC_CHANGES files"
echo " Code: $CODE_CHANGES files"
echo " Config: $CONFIG_CHANGES files"
echo " Workflows: $WORKFLOW_CHANGES files"
echo ""
# Flag potentially large scope changes
TOTAL_FILES=$(echo "$CHANGED_FILES" | wc -l)
if [ "$TOTAL_FILES" -gt 20 ]; then
echo "WARNING: Large change scope ($TOTAL_FILES files)"
echo "Consider splitting into smaller PRs for easier review."
fi
check-forbidden-files:
name: Check for Forbidden Files
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check for forbidden file changes
run: |
echo "Checking for changes to protected files..."
echo ""
CHANGED_FILES=$(git diff --name-only origin/main...HEAD 2>/dev/null || git diff --name-only HEAD~1)
FORBIDDEN_PATTERNS=(
".env"
"*.pem"
"*.key"
"credentials.json"
"secrets.json"
)
VIOLATIONS=""
for pattern in "${FORBIDDEN_PATTERNS[@]}"; do
MATCHES=$(echo "$CHANGED_FILES" | grep -E "$pattern" || true)
if [ -n "$MATCHES" ]; then
VIOLATIONS="$VIOLATIONS$MATCHES"$'\n'
fi
done
if [ -n "$VIOLATIONS" ]; then
echo "FORBIDDEN FILES DETECTED:"
echo "$VIOLATIONS"
echo ""
echo "These files should not be committed:"
echo " - .env files (use .env.example instead)"
echo " - Private keys (*.pem, *.key)"
echo " - Credential files"
echo ""
exit 1
else
echo "No forbidden files in changes."
fi
validate-commit-messages:
name: Validate Commit Messages
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check commit message format
run: |
echo "Validating commit messages..."
echo ""
# Get commits in this PR
COMMITS=$(git log origin/main..HEAD --pretty=format:"%h %s" 2>/dev/null || git log -5 --pretty=format:"%h %s")
echo "Commits to validate:"
echo "$COMMITS"
echo ""
# Conventional commit regex
# Format: type(scope): description
VALID_TYPES="feat|fix|docs|style|refactor|perf|test|chore|security|build|ci"
INVALID_COMMITS=""
while IFS= read -r line; do
HASH=$(echo "$line" | cut -d' ' -f1)
MSG=$(echo "$line" | cut -d' ' -f2-)
# Check if message follows conventional commit format
if ! echo "$MSG" | grep -qE "^($VALID_TYPES)(\(.+\))?: .+"; then
# Allow merge commits
if ! echo "$MSG" | grep -qE "^Merge "; then
INVALID_COMMITS="$INVALID_COMMITS$HASH: $MSG"$'\n'
fi
fi
done <<< "$COMMITS"
if [ -n "$INVALID_COMMITS" ]; then
echo "INVALID COMMIT MESSAGES:"
echo "$INVALID_COMMITS"
echo ""
echo "Commit messages should follow conventional commit format:"
echo " type(scope): description"
echo ""
echo "Valid types: $VALID_TYPES"
echo ""
echo "Examples:"
echo " feat(auth): add OAuth2 support"
echo " fix(parser): handle null input"
echo " docs(readme): update installation steps"
# Warning only, not failing
else
echo "All commit messages follow conventional format."
fi
check-ai-attribution:
name: Check AI Attribution
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check for AI Attribution
run: |
echo "Checking for AI attribution..."
echo ""
# Get full commit messages
COMMIT_BODIES=$(git log origin/main..HEAD --pretty=format:"%B---COMMIT_SEP---" 2>/dev/null || git log -5 --pretty=format:"%B---COMMIT_SEP---")
# Check if any commits mention AI tools but lack attribution
AI_KEYWORDS="Claude|GPT|Gemini|AI|LLM|Copilot|agent"
MISSING_ATTRIBUTION=""
while IFS= read -r commit; do
# Check if commit mentions AI
if echo "$commit" | grep -qiE "$AI_KEYWORDS"; then
# Check if it has AI attribution
if ! echo "$commit" | grep -qi "Authored by TheArchitectit"; then
HASH=$(git log --pretty=format:"%h" -1)
MISSING_ATTRIBUTION="$MISSING_ATTRIBUTION- Commit may need AI attribution"$'\n'
fi
fi
done <<< "$(echo "$COMMIT_BODIES" | tr '---COMMIT_SEP---' '\n')"
if [ -n "$MISSING_ATTRIBUTION" ]; then
echo "NOTE: Some commits may need AI attribution:"
echo "$MISSING_ATTRIBUTION"
echo ""
echo "If AI assisted with these commits, add:"
echo " Authored by TheArchitectit"
else
echo "Attribution check complete."
fi
guardrails-summary:
name: Generate Compliance Summary
runs-on: ubuntu-latest
needs: [check-scope-boundaries, check-forbidden-files, validate-commit-messages, check-ai-attribution]
if: always()
steps:
- name: Generate summary
run: |
echo "## Guardrails Compliance Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
echo "| Scope Boundaries | ${{ needs.check-scope-boundaries.result }} |" >> $GITHUB_STEP_SUMMARY
echo "| Forbidden Files | ${{ needs.check-forbidden-files.result }} |" >> $GITHUB_STEP_SUMMARY
echo "| Commit Messages | ${{ needs.validate-commit-messages.result }} |" >> $GITHUB_STEP_SUMMARY
echo "| AI Attribution | ${{ needs.check-ai-attribution.result }} |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "See [Agent Guardrails](docs/AGENT_GUARDRAILS.md) for compliance requirements." >> $GITHUB_STEP_SUMMARY

View File

@ -0,0 +1,224 @@
name: Regression Guard
on:
pull_request:
types: [opened, synchronize, reopened]
push:
branches: [main, master]
jobs:
regression-check:
runs-on: ubuntu-latest
name: Check for Potential Regressions
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Run Regression Check
id: regression_check
run: |
echo "::group::Regression Check Output"
python scripts/regression_check.py --all --json > regression_report.json || true
python scripts/regression_check.py --all || true
echo "::endgroup::"
- name: Analyze PR for Bug Fix Commits
id: check_bug_fixes
if: github.event_name == 'pull_request'
run: |
echo "Checking for bug fix commits..."
# Get commit messages in PR
git log --format=%s "origin/${{ github.base_ref }}..HEAD" > commit_messages.txt
# Check for conventional commit bug fix markers
BUG_FIX_COUNT=$(grep -cE "^(fix|bugfix|hotfix)(\(.+\))?:" commit_messages.txt || true)
echo "bug_fix_count=$BUG_FIX_COUNT" >> $GITHUB_OUTPUT
if [ "$BUG_FIX_COUNT" -gt 0 ]; then
echo "Detected $BUG_FIX_COUNT bug fix commit(s)"
echo "commits=$(cat commit_messages.txt)" >> $GITHUB_OUTPUT
fi
- name: Check for Regression Tests
id: check_regression_tests
if: steps.check_bug_fixes.outputs.bug_fix_count > 0
run: |
echo "Checking for regression tests in tests/regression/..."
# Check if tests/regression/ directory exists and has new files
if [ -d "tests/regression" ]; then
NEW_REGRESSION_TESTS=$(git diff --name-only --diff-filter=A "origin/${{ github.base_ref }}..HEAD" -- "tests/regression/**" | wc -l)
echo "new_regression_tests=$NEW_REGRESSION_TESTS" >> $GITHUB_OUTPUT
if [ "$NEW_REGRESSION_TESTS" -eq 0 ]; then
echo "::warning::Bug fix commits detected but no new regression tests found in tests/regression/"
echo "Consider adding a regression test for the bug fix."
else
echo "Found $NEW_REGRESSION_TESTS new regression test(s)"
fi
else
echo "new_regression_tests=0" >> $GITHUB_OUTPUT
echo "::warning::tests/regression/ directory not found"
fi
- name: Check Failure Registry
id: check_registry
run: |
REGISTRY_FILE=".guardrails/failure-registry.jsonl"
if [ -f "$REGISTRY_FILE" ]; then
ACTIVE_FAILURES=$(grep -v "^#" "$REGISTRY_FILE" | grep '"status":"active"' | wc -l)
echo "active_failures=$ACTIVE_FAILURES" >> $GITHUB_OUTPUT
echo "Found $ACTIVE_FAILURES active failure(s) in registry"
else
echo "active_failures=0" >> $GITHUB_OUTPUT
echo "No failure registry found"
fi
- name: Check Modified Files Against Registry
id: check_modified_files
if: github.event_name == 'pull_request'
run: |
# Get list of modified files
MODIFIED_FILES=$(git diff --name-only "origin/${{ github.base_ref }}..HEAD")
if [ -f ".guardrails/failure-registry.jsonl" ]; then
echo "Checking modified files against failure registry..."
HIGH_RISK_FILES=""
for file in $MODIFIED_FILES; do
# Check if file appears in any active failure entry
MATCHES=$(grep -v "^#" .guardrails/failure-registry.jsonl | \
grep '"status":"active"' | \
grep "\"$file\"" | \
jq -r '.failure_id' 2>/dev/null || true)
if [ -n "$MATCHES" ]; then
HIGH_RISK_FILES="$HIGH_RISK_FILES\n- $file (related to: $MATCHES)"
fi
done
if [ -n "$HIGH_RISK_FILES" ]; then
echo "high_risk_files<<EOF" >> $GITHUB_OUTPUT
echo -e "$HIGH_RISK_FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
fi
fi
- name: Comment PR
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
let report = '## Regression Guard Report\n\n';
// Active failures count
const activeFailures = '${{ steps.check_registry.outputs.active_failures }}';
report += `### Failure Registry Status\n`;
report += `- **Active failures in registry:** ${activeFailures}\n\n`;
// Bug fix commits
const bugFixCount = parseInt('${{ steps.check_bug_fixes.outputs.bug_fix_count }}' || '0');
report += `### Bug Fix Detection\n`;
if (bugFixCount > 0) {
report += `⚠️ **${bugFixCount} bug fix commit(s) detected**\n\n`;
// Regression tests check
const newTests = parseInt('${{ steps.check_regression_tests.outputs.new_regression_tests }}' || '0');
if (newTests === 0) {
report += `🔴 **Warning:** No new regression tests found in \`tests/regression/\`\n`;
report += `> Bug fixes should include regression tests to prevent reintroduction.\n\n`;
} else {
report += `✅ ${newTests} new regression test(s) added\n\n`;
}
} else {
report += `✅ No bug fix commits detected\n\n`;
}
// High risk files
const highRiskFiles = `${{ steps.check_modified_files.outputs.high_risk_files }}`;
if (highRiskFiles && highRiskFiles !== 'undefined') {
report += `### ⚠️ Files with Known Bug History\n`;
report += `The following modified files have active failures in the registry:\n`;
report += highRiskFiles + '\n\n';
report += `> Please review the failure registry before merging.\n\n`;
}
// Prevention rules status
if (fs.existsSync('.guardrails/prevention-rules/pattern-rules.json')) {
const rules = JSON.parse(fs.readFileSync('.guardrails/prevention-rules/pattern-rules.json', 'utf8'));
const enabledRules = rules.rules.filter(r => r.enabled).length;
report += `### Prevention Rules\n`;
report += `- ${enabledRules} pattern rule(s) active\n\n`;
}
report += `---\n`;
report += `*Run \`python scripts/regression_check.py\` locally for detailed output.*\n`;
// Find existing comment
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
const botComment = comments.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('Regression Guard Report')
);
if (botComment) {
// Update existing comment
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: botComment.id,
body: report
});
} else {
// Create new comment
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: report
});
}
- name: Fail on Critical Issues
if: github.event_name == 'pull_request'
run: |
# Check if any critical patterns were matched
if [ -f "regression_report.json" ]; then
CRITICAL_COUNT=$(cat regression_report.json | jq '[.issues[].violations[] | select(.severity == "critical")] | length' || echo "0")
if [ "$CRITICAL_COUNT" -gt 0 ]; then
echo "::error::$CRITICAL_COUNT critical regression pattern(s) detected!"
echo "Review the regression check output above."
exit 1
fi
fi
# Fail if bug fix without regression test
BUG_FIX_COUNT=${{ steps.check_bug_fixes.outputs.bug_fix_count || 0 }}
NEW_TESTS=${{ steps.check_regression_tests.outputs.new_regression_tests || 0 }}
if [ "$BUG_FIX_COUNT" -gt 0 ] && [ "$NEW_TESTS" -eq 0 ]; then
echo "::warning::Bug fix commits require regression tests."
# Uncomment to make this a hard fail:
# exit 1
fi
exit 0

View File

@ -0,0 +1,126 @@
name: Secret Validation
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
permissions:
contents: read
jobs:
scan-for-secrets:
name: Scan for Leaked Secrets
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Full history for scanning
- name: Run Gitleaks
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
check-env-files:
name: Check for .env Files
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for .env files
run: |
echo "Checking for accidentally committed .env files..."
# Find .env files (excluding .env.example)
ENV_FILES=$(find . -name ".env*" ! -name ".env.example" ! -name ".env.template" -type f 2>/dev/null || true)
if [ -n "$ENV_FILES" ]; then
echo "ERROR: Found .env files that should not be committed:"
echo "$ENV_FILES"
echo ""
echo "Please remove these files and add them to .gitignore"
exit 1
else
echo "No .env files found (good!)"
fi
- name: Check for credential files
run: |
echo "Checking for credential files..."
# List of patterns that might contain secrets
PATTERNS=(
"*.pem"
"*.key"
"*credentials*.json"
"*secrets*.json"
"*service-account*.json"
)
FOUND_FILES=""
for pattern in "${PATTERNS[@]}"; do
FILES=$(find . -name "$pattern" -type f 2>/dev/null || true)
if [ -n "$FILES" ]; then
FOUND_FILES="$FOUND_FILES$FILES"$'\n'
fi
done
if [ -n "$FOUND_FILES" ]; then
echo "WARNING: Found potential credential files:"
echo "$FOUND_FILES"
echo ""
echo "Verify these don't contain real credentials"
# Warning only, not failing (might be examples)
else
echo "No credential files found (good!)"
fi
check-hardcoded-secrets:
name: Check for Hardcoded Secrets
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for common secret patterns
run: |
echo "Checking for hardcoded secrets..."
# Patterns that might indicate hardcoded secrets
PATTERNS=(
"password\s*=\s*['\"]"
"api_key\s*=\s*['\"]"
"secret\s*=\s*['\"]"
"token\s*=\s*['\"]"
"aws_access_key_id\s*=\s*['\"]"
"private_key\s*=\s*['\"]"
)
ISSUES_FOUND=0
for pattern in "${PATTERNS[@]}"; do
# Search in common code files, excluding test fixtures
MATCHES=$(grep -riE "$pattern" --include="*.py" --include="*.js" --include="*.ts" --include="*.yaml" --include="*.yml" --include="*.json" . 2>/dev/null | grep -v "node_modules" | grep -v ".example" | grep -v "test_fixtures" || true)
if [ -n "$MATCHES" ]; then
echo "WARNING: Potential hardcoded secret pattern found:"
echo "$MATCHES"
echo ""
ISSUES_FOUND=$((ISSUES_FOUND + 1))
fi
done
if [ $ISSUES_FOUND -gt 0 ]; then
echo "Found $ISSUES_FOUND potential issues. Please review."
echo "If these are false positives (e.g., environment variable references), they can be ignored."
else
echo "No obvious hardcoded secrets found (good!)"
fi

View File

@ -0,0 +1,108 @@
name: Team Validation
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
workflow_dispatch:
jobs:
validate-teams:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install -r requirements.txt
- name: Validate team sizes
run: |
python3 scripts/team_manager.py --project example validate-size
- name: Check team status
run: |
python3 scripts/team_manager.py --project example status
- name: Export team configuration
if: github.ref == 'refs/heads/main'
run: |
python3 scripts/team_manager.py --project example export-json --file teams-export.json
- name: Upload team export
if: github.ref == 'refs/heads/main'
uses: actions/upload-artifact@v4
with:
name: teams-export
path: teams-export.json
test-python:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest pytest-cov
- name: Run Python tests
run: |
pytest scripts/ -v --cov=scripts --cov-report=xml
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage.xml
test-go:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.21'
- name: Run Go tests
run: |
cd mcp-server
go test ./... -v -race
- name: Build Go handlers
run: |
cd mcp-server
go build ./...
build-cli:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.21'
- name: Build CLI
run: |
cd cmd/team-cli
make build
- name: Upload CLI binary
uses: actions/upload-artifact@v4
with:
name: team-cli
path: cmd/team-cli/team

53
.guardrails/.gitignore vendored Normal file
View File

@ -0,0 +1,53 @@
# Dependencies
node_modules/
.venv/
venv/
__pycache__/
*.pyc
# Build outputs
dist/
build/
*.egg-info/
target/
# IDE
.idea/
.vscode/
*.swp
*.swo
.DS_Store
# Environment
.env
.env.local
*.local
# Logs
*.log
logs/
# Testing
.coverage
htmlcov/
.pytest_cache/
# Secrets (NEVER commit these)
*.pem
*.key
credentials.json
secrets.json
.aider*
# Ignore build artifacts and binaries
mcp-server/server
mcp-server/bin/guardrail-mcp
# Ignore test artifacts
mcp-server/internal/mcp/*_test.go
# Vision pipeline (NEVER commit real config or DBs)
mcp-server/config/vision.yaml
*.db
screenshots/
vision_data/

View File

@ -0,0 +1,20 @@
# Failure Registry - Append-only log of bugs and failures
# Format: One JSON object per line (JSONL)
# DO NOT edit existing entries - only append new ones
# Use scripts/log_failure.py to add entries consistently
#
# Schema:
# failure_id: UUID for the failure (FAIL-xxxxxxxx)
# timestamp: ISO 8601 timestamp
# category: build|runtime|test|type|lint|deploy|config|regression
# severity: low|medium|high|critical
# error_message: The actual error message
# root_cause: Why the failure occurred
# affected_files: List of files involved
# fix_commit: Git SHA of the fixing commit
# regression_pattern: Pattern that could reintroduce this
# prevention_rule: Specific rule to prevent recurrence
# status: active|resolved|deprecated
#
# Example entry:
# {"failure_id": "FAIL-abc123de", "timestamp": "2026-02-07T10:00:00Z", "category": "runtime", "severity": "high", "error_message": "TypeError: Cannot read property of undefined", "root_cause": "Missing null check after JSON.parse", "affected_files": ["src/parser.js"], "fix_commit": "a1b2c3d", "regression_pattern": "JSON.parse\\(.*\\)\\.\\w+ without null check", "prevention_rule": "Always null-check parsed JSON before property access", "status": "active"}

View File

@ -0,0 +1,179 @@
# Pre-Work Regression Check
**MANDATORY:** Read this document before starting ANY work on this codebase.
---
## Quick Checklist
Before editing any file, verify:
- [ ] **I have read the relevant documentation** (INDEX_MAP.md → specific docs)
- [ ] **I know which files I will modify**
- [ ] **I have checked the Failure Registry** for known bugs in those files
- [ ] **I understand what bugs have been fixed** in this area before
- [ ] **I will not reintroduce known patterns** that caused previous bugs
---
## Active Failures Relevant to Current Work
**Instructions:** Before starting, run:
```bash
python scripts/regression_check.py --all
```
This will show you any potential regressions in your current changes. If you're starting fresh, check the registry for files in your scope:
```bash
python scripts/log_failure.py --list
```
---
## Known Bug Patterns by Category
### Build Failures
- Missing dependencies in imports
- Incorrect build configuration
- Circular dependencies
### Runtime Failures
- Null/undefined access without checks
- Unhandled promise rejections
- Resource leaks (files, connections)
### Test Failures
- Flaky tests without proper setup/teardown
- Tests depending on external state
- Race conditions in async tests
### Type Failures
- Missing type annotations
- Incorrect generic usage
- Type coercion issues
### Config Failures
- Missing environment variables
- Invalid configuration values
- Hardcoded values that should be configurable
---
## Prevention Rules in Effect
The following patterns are automatically checked:
| Rule ID | Pattern | Severity | Description |
|---------|---------|----------|-------------|
| PREVENT-001 | JSON.parse without null check | error | Direct property access on parsed JSON |
| PREVENT-002 | SQL string concatenation | critical | Potential SQL injection |
| PREVENT-003 | Hardcoded credentials | critical | Credentials in source code |
**Run the regression check to see all active rules:**
```bash
python scripts/regression_check.py --verbose
```
---
## Files with Known Bug History
**Note:** This section is populated dynamically. Check the registry for your specific files.
Common high-risk files to be extra careful with:
- Configuration files (easy to misconfigure)
- Authentication/authorization code (security critical)
- Database access layers (data integrity)
- API endpoints (interface contracts)
---
## Required Verification Steps
### Before Starting Work
1. **Identify scope**: List all files you plan to modify
2. **Check registry**: Search for those files in failure-registry.jsonl
3. **Review patterns**: Understand what caused previous bugs
4. **Plan defensively**: Design your changes to avoid known issues
### During Development
1. **Run regression check frequently**:
```bash
python scripts/regression_check.py --unstaged
```
2. **Test edge cases** that caused previous bugs
3. **Add regression tests** for any bug fixes you make
### Before Committing
1. **Final regression check**:
```bash
python scripts/regression_check.py --staged
```
2. **Review your diff** for any patterns that match known bugs
3. **Verify no previous fixes were undone**
---
## When You Find a New Bug
**YOU MUST:**
1. **Fix the bug first**
2. **Log it in the registry**:
```bash
python scripts/log_failure.py --interactive
```
3. **Add a regression test** in `tests/regression/`
4. **Update prevention rules** if applicable
---
## Quick Commands Reference
```bash
# Check for regressions in staged changes
python scripts/regression_check.py
# Check for regressions in unstaged changes
python scripts/regression_check.py --unstaged
# List all active failures
python scripts/log_failure.py --list
# Show details of a specific failure
python scripts/log_failure.py --show FAIL-abc12345
# Mark a failure as resolved
python scripts/log_failure.py --resolve FAIL-abc12345
# Log a new failure interactively
python scripts/log_failure.py --interactive
```
---
## Remember
> **The goal is not to slow you down—it's to prevent the same bugs from being fixed over and over again.**
Every bug in the registry represents:
- Time spent debugging
- Potential user impact
- Technical debt
- Risk of reintroduction
By checking before you start, you save time and prevent regressions.
---
**Last Updated:** Auto-generated from failure-registry.jsonl
**Registry Path:** `.guardrails/failure-registry.jsonl`
**Check Command:** `python scripts/regression_check.py`

View File

@ -0,0 +1,138 @@
{
"$schema": "./pattern-rules.schema.json",
"description": "Actionable rules extracted from AGENT_GUARDRAILS.md",
"version": "1.0.0",
"source": "docs/AGENT_GUARDRAILS.md",
"rules": [
{
"rule_id": "PREVENT-GIT-001",
"failure_id": null,
"name": "No Force Push",
"enabled": true,
"pattern": "git\\s+push\\s+--force(?!-with-lease)",
"forbidden_context": null,
"message": "Force push without lease is prohibited by guardrails - can cause data loss and history corruption",
"severity": "error",
"category": "git",
"file_glob": ["*"],
"suggestion": "Use 'git push --force-with-lease' instead, or ask for explicit permission"
},
{
"rule_id": "PREVENT-GIT-002",
"failure_id": null,
"name": "No Hard Reset",
"enabled": true,
"pattern": "git\\s+reset\\s+--hard",
"forbidden_context": null,
"message": "Hard reset can destroy uncommitted work and is prohibited on shared branches",
"severity": "error",
"category": "git",
"file_glob": ["*"],
"suggestion": "Use 'git stash' or commit changes first. If needed, ask for explicit permission"
},
{
"rule_id": "PREVENT-GIT-003",
"failure_id": null,
"name": "No Config Changes",
"enabled": true,
"pattern": "git\\s+config",
"forbidden_context": null,
"message": "Modifying git config is prohibited - can cause security/identity issues",
"severity": "error",
"category": "git",
"file_glob": ["*"],
"suggestion": "Do not modify git configuration in automated operations"
},
{
"rule_id": "PREVENT-GIT-004",
"failure_id": null,
"name": "No Amend Without Permission",
"enabled": true,
"pattern": "git\\s+commit\\s+.*--amend",
"forbidden_context": null,
"message": "Amending commits you didn't create this session breaks collaborator history",
"severity": "warning",
"category": "git",
"file_glob": ["*"],
"suggestion": "Only amend commits created in current session, or ask for explicit permission"
},
{
"rule_id": "PREVENT-GIT-005",
"failure_id": null,
"name": "No Skip Hooks",
"enabled": true,
"pattern": "--no-verify|--no-gpg-sign",
"forbidden_context": null,
"message": "Skipping hooks bypasses safety checks and is prohibited",
"severity": "error",
"category": "git",
"file_glob": ["*"],
"suggestion": "Run all hooks. If hooks fail, fix the underlying issue"
},
{
"rule_id": "PREVENT-GIT-006",
"failure_id": null,
"name": "No Rebase on Shared Branches",
"enabled": true,
"pattern": "git\\s+rebase",
"forbidden_context": null,
"message": "Rebasing shared branches destroys collaborator work",
"severity": "error",
"category": "git",
"file_glob": ["*"],
"suggestion": "Use merge instead, or only rebase local branches that haven't been pushed"
},
{
"rule_id": "PREVENT-SYS-001",
"failure_id": null,
"name": "No Dangerous RM-RF",
"enabled": true,
"pattern": "rm\\s+-rf\\s+/",
"forbidden_context": null,
"message": "CRITICAL: Dangerous deletion pattern detected - can destroy system",
"severity": "critical",
"category": "system",
"file_glob": ["*"],
"suggestion": "Never use rm -rf on system directories. Verify path carefully"
},
{
"rule_id": "PREVENT-SEC-001",
"failure_id": null,
"name": "No Secrets in Code",
"enabled": true,
"pattern": "(password|secret|api_key|token|private_key|access_key)\\s*[=:]\\s*[\"'][^\"']{8,}[\"']",
"forbidden_context": "(example|placeholder|test|mock|dummy|fake|env\\.|process\\.env|os\\.getenv)",
"message": "Possible hardcoded credential detected - secrets must not be committed",
"severity": "critical",
"category": "security",
"file_glob": ["*"],
"suggestion": "Use environment variables or secret management system"
},
{
"rule_id": "PREVENT-SEC-002",
"failure_id": null,
"name": "No Production DB in Tests",
"enabled": true,
"pattern": "(production|prod)\\s*(db|database|conn|connection)",
"forbidden_context": "(test|spec|_test\\.|_spec\\.)",
"message": "Test code may be using production database - CRITICAL violation",
"severity": "critical",
"category": "security",
"file_glob": ["*test*", "*spec*"],
"suggestion": "Use separate test database. Never connect tests to production DB"
},
{
"rule_id": "PREVENT-SCOPE-001",
"failure_id": null,
"name": "Check Failure Registry",
"enabled": true,
"pattern": "PRE-WORK-CHECK-SKIPPED",
"forbidden_context": null,
"message": "Pre-work regression check must be performed before modifying files",
"severity": "warning",
"category": "process",
"file_glob": ["*"],
"suggestion": "Read .guardrails/pre-work-check.md and check failure registry"
}
]
}

View File

@ -0,0 +1,429 @@
{
"$schema": "./pattern-rules.schema.json",
"description": "Pattern-based prevention rules for regression detection",
"version": "2.1.0",
"rules": [
{
"rule_id": "PREVENT-001",
"name": "JSON.parse without null check",
"enabled": true,
"pattern": "JSON\\.parse\\(.*\\)\\s*\\.\\w+",
"forbidden_context": "without.*null.*check",
"message": "Direct property access on JSON.parse result without null check",
"severity": "error",
"file_glob": [
"*.js",
"*.ts",
"*.jsx",
"*.tsx"
],
"suggestion": "Add null check: const data = JSON.parse(...); if (data) { ... }"
},
{
"rule_id": "PREVENT-002",
"name": "SQL injection risk via string concatenation",
"enabled": true,
"pattern": "(execute|query|exec)\\s*\\(.*\\+.*\\)",
"forbidden_context": null,
"message": "Potential SQL injection: String concatenation in SQL query",
"severity": "critical",
"file_glob": [
"*.py",
"*.js",
"*.ts",
"*.rb",
"*.java",
"*.go"
],
"suggestion": "Use parameterized queries or prepared statements"
},
{
"rule_id": "PREVENT-003",
"name": "Hardcoded credentials",
"enabled": true,
"pattern": "(password|secret|api_key|token|apikey)\\s*[,=:]\\s*[\"'][^\"']+[\"']",
"forbidden_context": "(example|placeholder|test|mock|sample|dummy|fake)",
"message": "Possible hardcoded credential detected",
"severity": "critical",
"file_glob": [
"*"
],
"suggestion": "Use environment variables or secret management system"
},
{
"rule_id": "PREVENT-004",
"name": "Godot: Direct .free() on Node",
"enabled": true,
"pattern": "\\.free\\(\\)",
"forbidden_context": "(queue_free|is_queued_for_deletion|Object\\.)",
"message": "Direct .free() on Node can crash. Use queue_free() instead.",
"severity": "error",
"file_glob": [
"*.gd"
],
"suggestion": "Use node.queue_free() for safe deferred deletion"
},
{
"rule_id": "PREVENT-005",
"name": "Godot: Absolute resource paths",
"enabled": true,
"pattern": "(C:\\\\|/home/|/Users/|/mnt/)[^\\s\"']+\\.(png|jpg|wav|ogg|tscn|gd)",
"forbidden_context": null,
"message": "Absolute file path detected. Use res:// paths in Godot.",
"severity": "critical",
"file_glob": [
"*.tscn",
"*.gd",
"*.tres",
"*.cfg"
],
"suggestion": "Replace with res://path/to/resource"
},
{
"rule_id": "PREVENT-006",
"name": "Godot: String-based get_node()",
"enabled": true,
"pattern": "get_node\\([\"'][^\"']+[\"']\\)",
"forbidden_context": null,
"message": "String-based get_node() is fragile. Use @onready with $ or % syntax.",
"severity": "warning",
"file_glob": [
"*.gd"
],
"suggestion": "Use @onready var node = $Path or %UniqueName"
},
{
"rule_id": "PREVENT-007",
"name": "Python: Bare except clause",
"enabled": true,
"pattern": "except\\s*:",
"forbidden_context": "(Exception|BaseException|ValueError|TypeError|RuntimeError|KeyError)",
"message": "Bare except catches SystemExit and KeyboardInterrupt. Use except Exception: at minimum.",
"severity": "error",
"file_glob": [
"*.py"
],
"suggestion": "Use 'except Exception as e:' or catch specific exceptions"
},
{
"rule_id": "PREVENT-008",
"name": "Python: Mutable default arguments",
"enabled": true,
"pattern": "def\\s+\\w+\\([^)]*\\b\\w+\\s*[:=]\\s*(\\[\\]|\\{\\}|set\\(\\))",
"forbidden_context": null,
"message": "Mutable default argument (list/dict/set) — shared across calls, causes subtle bugs",
"severity": "error",
"file_glob": [
"*.py"
],
"suggestion": "Use None as default and initialize inside the function"
},
{
"rule_id": "PREVENT-009",
"name": "Go: Ignored error return",
"enabled": true,
"pattern": "_\\s*,?\\s*=\\s*\\w+\\(",
"forbidden_context": "(range|ok|type|assert|select)",
"message": "Error return value ignored. Always check errors in Go.",
"severity": "error",
"file_glob": [
"*.go"
],
"suggestion": "Handle the error: if err != nil { return err }"
},
{
"rule_id": "PREVENT-010",
"name": "Go: goroutine without context",
"enabled": true,
"pattern": "go\\s+func",
"forbidden_context": "context",
"message": "Goroutine launched without context — cannot be cancelled or tracked",
"severity": "warning",
"file_glob": [
"*.go"
],
"suggestion": "Pass context.Context to goroutine for cancellation"
},
{
"rule_id": "PREVENT-011",
"name": "TypeScript: any type usage",
"enabled": true,
"pattern": "(:\\s*any|as\\s+any)",
"forbidden_context": "(//\\s*@ts-ignore|eslint-disable)",
"message": "Usage of 'any' type defeats TypeScript's type safety",
"severity": "error",
"file_glob": [
"*.ts",
"*.tsx"
],
"suggestion": "Define a proper interface or use 'unknown' with type narrowing"
},
{
"rule_id": "PREVENT-012",
"name": "TypeScript/JS: console.log in production",
"enabled": true,
"pattern": "console\\.(log|debug|info)",
"forbidden_context": "(test|spec|mock|__tests__)",
"message": "console.log left in production code",
"severity": "warning",
"file_glob": [
"*.ts",
"*.tsx",
"*.js",
"*.jsx"
],
"suggestion": "Remove console.log or replace with proper logging library"
},
{
"rule_id": "PREVENT-013",
"name": "Rust: unwrap() in non-test code",
"enabled": true,
"pattern": "\\.unwrap\\(\\)",
"forbidden_context": "(test|tests|spec|bench)",
"message": "unwrap() can panic. Use proper error handling in production.",
"severity": "warning",
"file_glob": [
"*.rs"
],
"suggestion": "Use match, ?, or expect() with a descriptive message"
},
{
"rule_id": "PREVENT-014",
"name": "Docker: latest tag in production",
"enabled": true,
"pattern": "FROM\\s+\\S+:latest",
"forbidden_context": null,
"message": "Using :latest tag is non-deterministic. Pin to a specific version.",
"severity": "error",
"file_glob": [
"Dockerfile",
"Dockerfile.*",
"*.dockerfile"
],
"suggestion": "Pin image version: FROM node:22.1.0-alpine"
},
{
"rule_id": "PREVENT-015",
"name": "Shell: Command injection via unsanitized input",
"enabled": true,
"pattern": "(exec|system|os\\.system|subprocess\\.call|subprocess\\.Popen)\\([^)]*\\+",
"forbidden_context": "(shlex|quote|shell=False)",
"message": "Potential command injection via string concatenation",
"severity": "critical",
"file_glob": [
"*.py",
"*.js",
"*.ts",
"*.rb",
"*.go"
],
"suggestion": "Use array form for subprocess or shlex.quote() for shell commands"
},
{
"rule_id": "PREVENT-016",
"name": "Kotlin/Java: Thread.sleep()",
"enabled": true,
"pattern": "Thread\\.sleep",
"forbidden_context": "(test|mock)",
"message": "Thread.sleep() is fragile. Use coroutines (delay) or proper synchronization.",
"severity": "warning",
"file_glob": [
"*.kt",
"*.java"
],
"suggestion": "In Kotlin use delay(), in Java use CompletableFuture or ScheduledExecutor"
},
{
"rule_id": "PREVENT-017",
"name": "GDScript: Heavy operations in _process",
"enabled": true,
"pattern": "(_process|_physics_process)[\\s\\S]{0,500}(FileAccess|HTTPRequest|ResourceLoader|load\\()",
"forbidden_context": null,
"message": "File I/O or resource loading detected in _process. Move to _ready() or background thread.",
"severity": "warning",
"file_glob": [
"*.gd"
],
"suggestion": "Preload resources in _ready() or use ResourceLoader.load_threaded()"
},
{
"rule_id": "PREVENT-018",
"name": "AWS/Azure/GCP: Hardcoded cloud credentials",
"enabled": true,
"pattern": "(AKIA|AZURE_SUBSCRIPTION|AIza)[0-9a-zA-Z]{16,}",
"forbidden_context": null,
"message": "Cloud provider access key detected in source code",
"severity": "critical",
"file_glob": [
"*"
],
"suggestion": "Use IAM roles, managed identities, or environment variables"
},
{
"rule_id": "PREVENT-019",
"name": "GDScript: Missing type hints",
"enabled": true,
"pattern": "var\\s+\\w+\\s*=",
"forbidden_context": "(var\\s+\\w+\\s*:|export|@export|@onready)",
"message": "Untyped variable declaration. Use 'var name: Type = value' for clarity.",
"severity": "info",
"file_glob": [
"*.gd"
],
"suggestion": "Add explicit type: var speed: float = 200.0"
},
{
"rule_id": "PREVENT-020",
"name": "All: TODO/FIXME/HACK without ticket reference",
"enabled": true,
"pattern": "(TODO|FIXME|HACK|XXX|WORKAROUND)[^\\d]*$",
"forbidden_context": "(#[0-9]|issue|ticket|JIRA)",
"message": "TODO/FIXME without ticket reference — will be forgotten",
"severity": "info",
"file_glob": [
"*"
],
"suggestion": "Add ticket reference: TODO(#123) or FIXME(RAD-456)"
},
{
"rule_id": "PREVENT-021",
"name": "OWASP A03: Command injection risk",
"enabled": true,
"pattern": "(eval|Function\\(|setTimeout|setInterval)\\s*\\(\\s*[\"'].*\\+",
"forbidden_context": "(sanitized|escaped|encoded)",
"message": "Potential command injection via eval/setTimeout with string concatenation",
"severity": "critical",
"file_glob": [
"*.js",
"*.ts",
"*.jsx",
"*.tsx"
],
"suggestion": "Use function references instead of strings: setTimeout(() => { ... }, 0)"
},
{
"rule_id": "PREVENT-022",
"name": "OWASP A05: Debug mode in production",
"enabled": true,
"pattern": "(DEBUG|debug)\\s*[:=]\\s*(True|true|1|yes)",
"forbidden_context": "(test|spec|development|staging|__debug__|if DEBUG)",
"message": "Debug mode enabled in non-test code",
"severity": "error",
"file_glob": [
"*.py",
"*.js",
"*.ts",
"*.rb",
"*.go",
"*.yaml",
"*.yml",
"*.json",
"*.env"
],
"suggestion": "Use environment variables: DEBUG = os.environ.get(\"DEBUG\", \"false\").lower() == \"true\""
},
{
"rule_id": "PREVENT-023",
"name": "OWASP A05: CORS wildcard",
"enabled": true,
"pattern": "Access-Control-Allow-Origin\\s*[:*]\\s*\\*",
"forbidden_context": null,
"message": "CORS wildcard detected — allows any origin to access the API",
"severity": "error",
"file_glob": [
"*.py",
"*.js",
"*.ts",
"*.go",
"*.rb",
"*.java",
"*.yaml",
"*.yml"
],
"suggestion": "Specify allowed origins explicitly instead of using wildcard"
},
{
"rule_id": "PREVENT-024",
"name": "AI: Hallucinated package import",
"enabled": true,
"pattern": "(import|from|require|use)\\s+[a-z_]+_[a-z]+_[a-z]+",
"forbidden_context": "(std|core|builtin|internal|github.com)",
"message": "Triple-underscored package name may be AI-hallucinated. Verify it exists on the registry.",
"severity": "warning",
"file_glob": [
"*.py",
"*.js",
"*.ts",
"*.rs",
"*.go",
"*.rb",
"*.java"
],
"suggestion": "Verify the package exists: pip search, npm view, cargo search, etc."
},
{
"rule_id": "PREVENT-025",
"name": "Security: Weak hash for passwords",
"enabled": true,
"pattern": "(md5|sha1|SHA1|MD5)\\s*\\(.*password",
"forbidden_context": null,
"message": "Weak hash algorithm used for passwords. Use bcrypt, scrypt, or argon2.",
"severity": "critical",
"file_glob": [
"*.py",
"*.js",
"*.ts",
"*.go",
"*.rb",
"*.java",
"*.php"
],
"suggestion": "Use bcrypt, scrypt, or argon2 for password hashing"
},
{
"rule_id": "PREVENT-026",
"name": "Security: SSRF via unvalidated URL",
"enabled": true,
"pattern": "(fetch|requests|http.Get|urllib|axios)\\s*\\(\\s*(user|input|param|query|request)",
"forbidden_context": "(validated|whitelist|allowlist|sanitize)",
"message": "Potential SSRF: User input passed to URL fetch without validation",
"severity": "error",
"file_glob": [
"*.py",
"*.js",
"*.ts",
"*.go",
"*.rb",
"*.java"
],
"suggestion": "Validate URL against allowlist before fetching"
},
{
"rule_id": "PREVENT-027",
"name": "Docker: Missing .dockerignore",
"enabled": true,
"pattern": ".*",
"forbidden_context": null,
"message": "No .dockerignore file found — entire context sent to Docker daemon",
"severity": "info",
"file_glob": [
"Dockerfile",
"Dockerfile.*"
],
"suggestion": "Create .dockerignore to exclude .git, node_modules, __pycache__, .env"
},
{
"rule_id": "PREVENT-028",
"name": "GDScript: Missing type hints in function return",
"enabled": true,
"pattern": "func\\s+\\w+\\s*\\([^)]*\\)\\s*:",
"forbidden_context": "(->|_ready|_process|_init|_input|_enter_tree|_exit_tree)",
"message": "Function without return type hint. Use func name() -> ReturnType:",
"severity": "info",
"file_glob": [
"*.gd"
],
"suggestion": "Add return type: func get_score() -> int:"
}
]
}

View File

@ -0,0 +1,147 @@
{
"$schema": "./semantic-rules.schema.json",
"description": "Semantic/AST-based prevention rules for complex regression detection",
"version": "2.0.0",
"rules": [
{
"rule_id": "SEMANTIC-001",
"name": "Unhandled promise rejection",
"enabled": true,
"language": "javascript",
"ast_pattern": {
"type": "CallExpression",
"callee": {
"type": "MemberExpression",
"object": { "type": "CallExpression" },
"property": { "name": "then" }
},
"missing": "catch"
},
"message": "Promise chain missing .catch() handler",
"severity": "warning",
"suggestion": "Add .catch() handler or use try/catch with async/await"
},
{
"rule_id": "SEMANTIC-002",
"name": "Resource leak - unclosed file",
"enabled": true,
"language": "python",
"ast_pattern": {
"type": "CallExpression",
"callee": { "name": "open" },
"missing": "context_manager"
},
"message": "File opened without context manager (with statement)",
"severity": "warning",
"suggestion": "Use 'with open(...) as f:' pattern to ensure file is closed"
},
{
"rule_id": "SEMANTIC-003",
"name": "Missing auth decorator",
"enabled": true,
"language": "python",
"ast_pattern": {
"type": "FunctionDefinition",
"route_decorator": true,
"missing_decorators": ["login_required", "require_auth", "authenticated"]
},
"message": "Route handler missing authentication decorator",
"severity": "error",
"suggestion": "Add @login_required or appropriate auth decorator"
},
{
"rule_id": "SEMANTIC-004",
"name": "Godot: @onready reference to missing node",
"enabled": true,
"language": "gdscript",
"ast_pattern": {
"type": "OnreadyVar",
"node_path": "$*",
"check": "node_exists_in_scene"
},
"message": "@onready reference to node that doesn't exist in scene tree",
"severity": "error",
"suggestion": "Verify node path matches scene tree structure"
},
{
"rule_id": "SEMANTIC-005",
"name": "React: useEffect missing dependency",
"enabled": true,
"language": "typescript",
"ast_pattern": {
"type": "CallExpression",
"callee": { "name": "useEffect" },
"check": "exhaustive_deps"
},
"message": "useEffect has missing or incorrect dependencies",
"severity": "warning",
"suggestion": "Add all referenced variables to the dependency array"
},
{
"rule_id": "SEMANTIC-006",
"name": "Go: defer in loop",
"enabled": true,
"language": "go",
"ast_pattern": {
"type": "DeferStatement",
"parent": "ForStatement"
},
"message": "defer in loop — deferred calls won't run until function returns, may leak resources",
"severity": "warning",
"suggestion": "Wrap loop body in a function or call .Close() directly"
},
{
"rule_id": "SEMANTIC-007",
"name": "Rust: unreachable pattern in match",
"enabled": true,
"language": "rust",
"ast_pattern": {
"type": "MatchExpression",
"check": "unreachable_arm"
},
"message": "Match arm is unreachable due to earlier pattern",
"severity": "error",
"suggestion": "Reorder match arms or remove redundant pattern"
},
{
"rule_id": "SEMANTIC-008",
"name": "Godot: Signal connection to non-existent method",
"enabled": true,
"language": "gdscript",
"ast_pattern": {
"type": "SignalConnection",
"check": "target_method_exists"
},
"message": "Signal connected to method that doesn't exist in the target script",
"severity": "error",
"suggestion": "Add the method or fix the signal connection path"
},
{
"rule_id": "SEMANTIC-009",
"name": "Python: Function with too many arguments",
"enabled": true,
"language": "python",
"ast_pattern": {
"type": "FunctionDefinition",
"check": "argument_count > 7"
},
"message": "Function has more than 7 arguments — consider using a dataclass or config object",
"severity": "info",
"suggestion": "Group related arguments into a dataclass or TypedDict"
},
{
"rule_id": "SEMANTIC-010",
"name": "TypeScript: useState with any",
"enabled": true,
"language": "typescript",
"ast_pattern": {
"type": "CallExpression",
"callee": { "name": "useState" },
"generic_type": "any"
},
"message": "useState<any>() defeats TypeScript's type checking",
"severity": "error",
"suggestion": "Define a proper type: useState<User | null>(null)"
}
]
}

View File

@ -0,0 +1,142 @@
{
"name": "Team Layout Compliance",
"version": "1.0",
"description": "Enforces standardized team structure across all projects",
"applies_to": ["all"],
"rules": [
{
"id": "TEAM-001",
"name": "Team Initialization Required",
"severity": "error",
"check": "Project must initialize team structure before work begins",
"command": "python scripts/team_manager.py --project {project_name} init",
"message": "Run team initialization before starting work"
},
{
"id": "TEAM-002",
"name": "Phase 1 Completion Required",
"severity": "error",
"check": "Architecture review must be complete before infrastructure work",
"command": "python scripts/team_manager.py --project {project_name} status --phase 'Phase 1'",
"message": "Phase 1 (Strategy, Governance & Planning) must be 100% complete"
},
{
"id": "TEAM-003",
"name": "Phase 2 Completion Required",
"severity": "error",
"check": "Platform must be ready before development begins",
"command": "python scripts/team_manager.py --project {project_name} status --phase 'Phase 2'",
"message": "Phase 2 (Platform & Foundation) must be 100% complete"
},
{
"id": "TEAM-004",
"name": "Security Review Gate",
"severity": "critical",
"check": "Team 9 (Cybersecurity) must approve before production",
"command": "python scripts/team_manager.py --project {project_name} status --phase 'Phase 4'",
"message": "Security review (Team 9) must be complete"
},
{
"id": "TEAM-005",
"name": "QA Sign-off Gate",
"severity": "critical",
"check": "Team 10 (Quality Engineering) must approve before release",
"command": "python scripts/team_manager.py --project {project_name} status --phase 'Phase 4'",
"message": "QA sign-off (Team 10) must be complete"
},
{
"id": "TEAM-006",
"name": "Role Assignment Required",
"severity": "warning",
"check": "Active teams should have roles assigned",
"command": "python scripts/team_manager.py --project {project_name} list",
"message": "Assign people to team roles before starting work"
},
{
"id": "TEAM-007",
"name": "Team Size Compliance",
"severity": "error",
"check": "All teams must have 4-6 members",
"command": "python scripts/team_manager.py --project {project_name} validate-size",
"message": "Teams must have between 4 and 6 members (inclusive). Current team size outside valid range."
}
],
"phase_gates": {
"1_to_2": {
"name": "Architecture Review Board",
"required_teams": [1, 2, 3],
"approval_required": [2],
"deliverables": ["Architecture Decision Records", "Approved Tech List", "Compliance Checklist"]
},
"2_to_3": {
"name": "Environment Readiness",
"required_teams": [4, 5, 6],
"approval_required": [4, 5],
"deliverables": ["Infrastructure Provisioned", "CI/CD Pipelines", "Data Models"]
},
"3_to_4": {
"name": "Feature Complete + Code Review",
"required_teams": [7, 8],
"approval_required": [7],
"deliverables": ["Features Implemented", "Code Reviewed", "Documentation Complete"]
},
"4_to_5": {
"name": "Security + QA Sign-off",
"required_teams": [9, 10],
"approval_required": [9, 10],
"deliverables": ["Security Review Passed", "Test Coverage Met", "UAT Sign-off"]
}
},
"agent_mapping": {
"planner": {
"team": 2,
"roles": ["Solution Architect", "Business Systems Analyst"],
"phase": "Phase 1"
},
"architect": {
"team": 2,
"roles": ["Chief Architect", "Domain Architect"],
"phase": "Phase 1"
},
"infrastructure": {
"team": 4,
"roles": ["Cloud Architect", "IaC Engineer"],
"phase": "Phase 2"
},
"platform": {
"team": 5,
"roles": ["CI/CD Architect", "Kubernetes Administrator"],
"phase": "Phase 2"
},
"backend": {
"team": 7,
"roles": ["Senior Backend Engineer", "Technical Lead"],
"phase": "Phase 3"
},
"frontend": {
"team": 7,
"roles": ["Senior Frontend Engineer", "Accessibility Expert"],
"phase": "Phase 3"
},
"security": {
"team": 9,
"roles": ["Security Architect", "Vulnerability Researcher"],
"phase": "Phase 4"
},
"qa": {
"team": 10,
"roles": ["QA Architect", "SDET"],
"phase": "Phase 4"
},
"sre": {
"team": 11,
"roles": ["SRE Lead", "Observability Engineer"],
"phase": "Phase 5"
},
"ops": {
"team": 12,
"roles": ["Release Manager", "NOC Analyst"],
"phase": "Phase 5"
}
}
}

View File

@ -0,0 +1,40 @@
{
"name": "Web UI Team Rules",
"version": "1.0",
"description": "Team layout rules specific to Web UI components",
"applies_to": ["web", "frontend", "ui"],
"rules": [
{
"id": "WEB-TEAM-001",
"name": "A11y Expert Required",
"severity": "error",
"check": "UI changes must be reviewed by Team 7 A11y Expert",
"trigger": "files_changed",
"patterns": ["**/*.tsx", "**/*.jsx", "**/*.vue", "**/*.svelte"],
"message": "Accessibility review required from Team 7 A11y Expert"
},
{
"id": "WEB-TEAM-002",
"name": "Design System Compliance",
"severity": "warning",
"check": "UI components must follow design system standards",
"trigger": "files_changed",
"patterns": ["**/components/**", "**/ui/**"],
"message": "Verify compliance with design system standards"
},
{
"id": "WEB-TEAM-003",
"name": "Technical Writer Review",
"severity": "warning",
"check": "UI changes affecting user flows need docs review",
"trigger": "files_changed",
"patterns": ["**/pages/**", "**/views/**", "**/screens/**"],
"message": "Notify Team 7 Technical Writer of user-facing changes"
}
],
"team_7_required_approvals": {
"ui_changes": ["Senior Frontend Engineer", "Accessibility (A11y) Expert"],
"component_changes": ["Senior Frontend Engineer"],
"page_changes": ["Senior Frontend Engineer", "Technical Writer"]
}
}

View File

@ -0,0 +1,137 @@
---
name: 3d-game-dev
description: "3D Game Development guardrails for AI-assisted game creation. Enforces mathematical correctness, asset safety, shader constraints, and Godot/Unity conventions."
---
# 3D Game Development Skill
Use when the agent is generating, modifying, or reviewing code/assets for a 3D game project.
## Applicability
- Procedural geometry generation
- Shader/material code (GLSL, HLSL, WGSL, Godot Shader Language)
- 3D physics and collision code
- Camera, lighting, and rendering pipeline code
- Asset import/export pipelines
- Spatial audio or XR/VR implementations
## Mandatory Guardrails
### 1. Asset Safety
**Polygon/Vertex Budgets:**
- Mobile: max 10K vertices per dynamic object, 50K per scene
- PC: max 50K per object, 500K per scene
- VR/Spatial: max 5K per object, 100K per scene
- Auto-generate LOD0/LOD1/LOD2 for anything >5K polygons
**Topology Rules:**
- NEVER generate non-manifold geometry
- NEVER generate N-gons (polygons >4 sides)
- NEVER generate inverted normals
- All meshes must be triangles or quads only
**UV Mapping:**
- Overlapping UV islands are FORBIDDEN unless explicitly mirrored
- Texel density must be consistent across adjacent meshes
- UVs must be in [0,1] range unless tiling is intentional
### 2. Shader Constraints
**Texture Sampling:**
- Max 16 texture samplers per shader pass (Forward Rendering)
- Max 8 samplers per pass (Mobile/VR)
**Branching:**
- NEVER use if/else in fragment/pixel shaders
- Use step(), smoothstep(), mix() instead
- Dynamic branching breaks GPU warp synchronization
**Loop Bounds:**
- All loops must have compile-time determinable bounds
- Max 64 iterations per shader loop
- Unroll small loops (≤8 iterations) explicitly
### 3. Mathematical Correctness
**Coordinate Systems:**
- Use right-handed coordinate system
- Y-up is standard (Z-up only for CAD/CAM workflows)
- Document handedness in every file header
**Rotation:**
- Use quaternions for all continuous rotations
- NEVER use Euler angles for animation (Gimbal Lock risk)
- Normalize quaternions before every transform application
- Verify: `assert(abs(q.length() - 1.0) < 0.0001)`
**Matrix Pipeline:**
- Follow Model → World → View → Projection order
- Always validate: `MVP = P * V * M` (column-major)
- Document matrix convention (row vs column) in file headers
**Precision:**
- Use double precision for world-space coordinates (large worlds)
- Use float for local/model space
- Use fixed-point for mobile GPU calculations where possible
### 4. Godot 4.x Conventions
**Node Communication:**
- Use Signals for decoupled communication
- NEVER use `get_node("../../Player")` — use exported NodePaths or Signals
- Signal emissions must include type-safe parameters
**Threading:**
- Use WorkerThreadPool for procedural generation
- NEVER call rendering functions from background threads
- NEVER manipulate SceneTree from background threads
- Use call_deferred() for thread-safe node operations
**GDScript:**
- Static typing: `var velocity: Vector3` not `var velocity`
- Use `@onready` for node references
- Use `@export` for configurable parameters
- Document units in comments: `meters`, `seconds`, `radians`
### 5. AI-Debuggable Architecture
**ECS over Inheritance:**
- Use Entity-Component-System, not deep inheritance
- Each component must be serializable to JSON
- Systems must be deterministic and replayable
**Semantic Telemetry:**
- Report spatial errors semantically: `{ "event": "Collision_Failure", "entity": "Player_1", "expected_surface": "Floor_Mesh", "actual_contact": "Void" }`
- NEVER dump raw float coordinates to LLM context
**Headless Mode:**
- All scenes must run in `--headless` for CI testing
- JSON state dumps at frame 0, N/2, and N
- Frame rate, memory, and error logs tracked over 600 frames
## Halt Conditions — STOP and Ask User
- Generating shader code without target platform specified
- Proposing mesh generation without polygon budget defined
- Modifying physics code without test scene verification
- Using Euler angles for 3D rotation (quaternions required)
- Dynamic branching in fragment shaders proposed
- Working with unnormalized quaternions
- Modifying rendering pipeline without headless test plan
## Compliance Verification
- Run `scripts/validate_3d_assets.py` on generated meshes
- Run `scripts/validate_shaders.py` on shader code
- Run `scripts/validate_math.py` on transform/rotation code
- CI: 600-frame headless test must pass (FPS >30, memory stable)
## References
- `docs/game-design/3D_GAME_DEVELOPMENT.md` — Full guardrails
- `docs/game-design/3D_MATHEMATICAL_FOUNDATIONS.md` — Math reference
- `docs/game-design/3D_MODULE_ARCHITECTURE.md` — Architecture blueprint
- `docs/game-design/AI_DEBUGGABLE_3D_ARCHITECTURE.md` — AI debugging patterns
- `docs/game-design/3D_GUARDREL_PROPOSALS_V1.2.md` — New rule proposals

View File

@ -0,0 +1,11 @@
{
"name": "doc-indexer",
"model": "anthropic/claude-haiku-4",
"temperature": 0.0,
"prompt_append": "You are the Documentation Indexer. When documents change update INDEX_MAP.md and HEADER_MAP.md to maintain accurate navigation.",
"permissions": {
"edit": "allow",
"bash": "deny",
"read": "allow"
}
}

View File

@ -0,0 +1,11 @@
{
"name": "guardrails-auditor",
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "You are a Guardrails Auditor. Review completed work for compliance with AGENT_GUARDRAILS.md and architecture patterns. Report violations found.\n\n## Audit Checklist\n\n### Four Laws Compliance\n- [ ] All files read before editing\n- [ ] Only authorized scope modified\n- [ ] Tests verify changes\n- [ ] Uncertain operations halted\n\n### Architecture Compliance (for Go/MCP server)\n- [ ] Domain layer has no infrastructure imports\n- [ ] Interfaces defined in Domain, implementations in Adapters\n- [ ] CQRS: commands separate from queries\n- [ ] Vertical slices: guardrail types self-contained\n- [ ] No cross-layer circular dependencies\n\n### SOLID Compliance\n- [ ] Single responsibility per type\n- [ ] Open-closed: new types via interface, not modification\n- [ ] Liskov: interface implementations complete\n- [ ] Interface segregation: small focused interfaces\n- [ ] Dependency inversion: depend on abstractions",
"permissions": {
"edit": "deny",
"bash": "deny",
"read": "allow"
}
}

View File

@ -0,0 +1,66 @@
{
"$schema": "https://raw.githubusercontent.com/code-yeongyu/oh-my-opencode/master/assets/oh-my-opencode.schema.json",
"agents": {
"guardrails-enforcer": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "You are the Guardrails Enforcement Agent. Before ANY operation verify: 1) File has been read, 2) Scope is authorized, 3) Rollback is known, 4) No forbidden patterns. HALT and ask if uncertain. Reference: docs/AGENT_GUARDRAILS.md",
"permissions": {
"edit": "ask",
"bash": "ask",
"webfetch": "allow",
"read": "allow"
}
},
"guardrails-auditor": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "You are a Guardrails Auditor. Review completed work for compliance with AGENT_GUARDRAILS.md. Report any violations found.",
"permissions": {
"edit": "deny",
"bash": "deny",
"read": "allow"
}
},
"doc-indexer": {
"model": "anthropic/claude-haiku-4",
"temperature": 0.0,
"prompt_append": "You are the Documentation Indexer. When documents change update INDEX_MAP.md and HEADER_MAP.md to maintain accurate navigation.",
"permissions": {
"edit": "allow",
"bash": "deny",
"read": "allow"
}
}
},
"categories": {
"quick": {
"model": "anthropic/claude-haiku-4"
},
"unspecified-low": {
"model": "anthropic/claude-sonnet-4"
}
},
"skills": {
"sources": [
{"path": "./.opencode/skills", "recursive": true}
],
"enable": [
"guardrails-enforcer",
"commit-validator",
"env-separator",
"scope-validator",
"production-first",
"three-strikes",
"error-recovery"
]
},
"permissions": {
"defaults": {
"edit": "ask",
"bash": "ask",
"webfetch": "allow",
"read": "allow"
}
}
}

View File

@ -0,0 +1,57 @@
---
name: 3d-game-dev
description: "3D Game Development guardrails for Godot, Unity, and custom engines. Enforces mathematical correctness, asset safety, shader constraints."
---
# 3D Game Development Agent
Enforce 3D game development guardrails on all geometry, shader, physics, and engine code.
## Geometry & Mesh Constraints
1. **Polygon Budget**: Mobile 10K/scene, PC 500K/scene, VR 100K/scene. Auto-LOD for >5K.
2. **Topology**: Triangles/quads only. No N-gons, non-manifold, or inverted normals.
3. **UV**: No overlapping islands (unless mirrored). Consistent texel density.
## Shader Constraints
1. **No Dynamic Branching**: NEVER if/else in fragment shaders. Use step(), smoothstep(), mix().
2. **Samplers**: Max 16 (Forward), 8 (Mobile/VR).
3. **Loops**: Compile-time bounds, max 64 iterations, unroll ≤8.
## Mathematical Constraints
1. **Quaternions ONLY** for continuous rotation. NEVER Euler angles.
2. **Normalize** before use: assert(abs(q.length()-1.0) < 0.0001)
3. **MVP Order**: P * V * M (column-major). Document convention in file header.
4. **Handedness**: Right-handed, Y-up. Document in header.
## Godot 4.x Constraints
1. **Signals** for decoupled communication. NEVER `get_node("../../Player")`.
2. **Static typing**: `var velocity: Vector3` not `var velocity`.
3. **Threading**: WorkerThreadPool for proc-gen. NEVER render from threads.
4. **Deferred**: `call_deferred()` for thread-safe node operations.
## AI-Debuggable Architecture
1. **ECS** over deep inheritance. JSON-serializable components.
2. **Semantic telemetry**: `{ "event": "Collision_Failure", "entity": "Player_1" }`
3. **Headless CI**: All scenes run --headless, 600 frames, FPS > 30, memory stable.
## Halt Conditions
STOP and ask user when:
- No target platform specified for shader
- No polygon budget for mesh generation
- Euler angles proposed for 3D rotation
- if/else proposed in fragment shader
- Unnormalized quaternion usage
- Rendering pipeline modified without headless test plan
## References
- `docs/game-design/3D_GAME_DEVELOPMENT.md`
- `docs/game-design/3D_MATHEMATICAL_FOUNDATIONS.md`
- `docs/game-design/3D_MODULE_ARCHITECTURE.md`
- `docs/game-design/AI_DEBUGGABLE_3D_ARCHITECTURE.md`

View File

@ -0,0 +1,54 @@
---
name: commit-validator
description: "Validates git commits follow COMMIT_WORKFLOW.md standards: AI attribution, single focus, no secrets"
---
# Commit Validator Agent
Validate all git commits against COMMIT_WORKFLOW.md standards.
## Validation Rules
### 1. AI Attribution (REQUIRED)
Every commit message MUST include AI attribution: `Co-Authored-By: Claude <noreply@anthropic.com>`
### 2. Single Focus Rule
- One commit = One logical change
- No unrelated changes in the same commit
### 3. No Secrets in Diff
Scan for API keys, tokens, passwords, private keys, .env contents, DB connection strings. Block immediately if found.
### 4. Pre-Commit Requirements
- All relevant tests MUST pass
- No linting or formatting errors
- Code has been self-reviewed
## Commit Message Format
```
<type>: <description>
[optional body]
Co-Authored-By: Claude <noreply@anthropic.com>
```
Types: feat, fix, docs, style, refactor, test, chore
## Validation Failure Actions
If validation fails:
1. Block the commit
2. Explain the violation
3. Provide specific fix instructions
4. Require user confirmation before proceeding
## References
- `docs/workflows/COMMIT_WORKFLOW.md` - Commit standards
- `skills/shared-prompts/error-recovery.md` - Recovery procedures

View File

@ -0,0 +1,42 @@
---
name: env-separator
description: "Enforces TEST_PRODUCTION_SEPARATION.md: production code first, separate instances, no data mixing"
---
# Environment Separator Agent
Enforce strict separation between test and production environments.
## The Three Laws of Environment Separation
1. **Production Code First** - Production code MUST be created before test code
2. **Separate Instances** - Test and production MUST use separate service instances
3. **No Data Mixing** - Test data must NEVER contaminate production databases
## Pre-Flight Checklist
Before creating test code or running tests:
- [ ] Production implementation exists and is functional
- [ ] Test environment uses separate database/service instances
- [ ] Test data will not leak to production
- [ ] Separate user accounts for test vs production
## Forbidden Patterns (NEVER ALLOW)
1. Tests writing to production databases
2. Test fixtures in production code paths
3. Shared database instances
4. Test credentials in production configs
5. Production data in tests without sanitization
## When Uncertain
If you cannot verify environment separation:
1. HALT the operation immediately
2. Ask the user to confirm environment boundaries
3. Do NOT proceed until separation is guaranteed
## References
- `docs/standards/TEST_PRODUCTION_SEPARATION.md` - Full environment rules
- `skills/shared-prompts/production-first.md` - Production-first mandate

View File

@ -0,0 +1,57 @@
---
name: guardrails-enforcer
description: "Enforces the Four Laws of Agent Safety automatically on all operations. Halts on uncertainty."
---
# Guardrails Enforcement Agent
You are the Guardrails Enforcement Agent. Verify ALL operations comply with the Agent Guardrails safety framework.
## The Four Laws of Agent Safety
1. **Read Before Editing** - Never modify code without reading it first
2. **Stay in Scope** - Only touch files explicitly authorized
3. **Verify Before Committing** - Test and check all changes
4. **Halt When Uncertain** - Ask for clarification instead of guessing
## Pre-Operation Checklist (MANDATORY)
Before ANY file modification:
- [ ] Read the target file(s) completely
- [ ] Verify the operation is within authorized scope
- [ ] Identify the rollback procedure
- [ ] Check for test/production separation requirements
## Forbidden Actions (NEVER DO)
1. Modifying unread code
2. Mixing test and production environments
3. Force pushing to main/master
4. Committing secrets, credentials, or .env files
5. Running untested code in production
6. Working outside scope
7. Guessing when uncertain
## Halt Conditions - STOP and Ask User
You MUST halt when:
- You have not read the code you are about to modify
- No rollback procedure exists or is unclear
- Production impact is uncertain
- User authorization is ambiguous
- Test and production environments may mix
- You are uncertain about ANY aspect of the task
- An operation has failed 3 times (Three Strikes Rule)
## Three Strikes Rule
- **Strike 1**: Retry with adjusted approach
- **Strike 2**: Try alternative approach
- **Strike 3**: HALT and escalate to user
## References
- `skills/shared-prompts/four-laws.md` - Canonical Four Laws
- `skills/shared-prompts/halt-conditions.md` - Full halt conditions
- `skills/shared-prompts/three-strikes.md` - Full strike tracking
- `docs/AGENT_GUARDRAILS.md` - Core safety protocols

View File

@ -0,0 +1,123 @@
{
"schema_version": "1.1.0",
"description": "Cross-cutting advisor roles for project governance",
"advisors": [
{
"id": "advisor-cost",
"name": "Cost & Efficiency Advisor",
"alias": "The Accountant",
"enforcement_level": "warn",
"scope": "all_phases",
"consults_with_teams": [1, 4, 5, 11],
"responsibility": "Reviews architectural decisions and infrastructure choices through a cost lens. Flags over-provisioned resources.",
"persona_voice": "Before we spin up another cluster — what's the actual load forecast? Show me the numbers.",
"deliverables": ["Cost estimation reviews", "Resource right-sizing recommendations", "Reserved capacity analysis"],
"trigger_patterns": ["*instance*", "*cluster*", "*provision*", "*capacity*", "*scale*"],
"assigned_to": null
},
{
"id": "advisor-dx",
"name": "Developer Experience Advisor",
"alias": "The Advocate",
"enforcement_level": "info",
"scope": "all_phases",
"consults_with_teams": [5, 7, 8, 10],
"responsibility": "Evaluates tooling choices, CI/CD pipeline ergonomics, and documentation quality. Champions minimal cognitive load.",
"persona_voice": "If a new engineer can't get this running in under 30 minutes, we have a DX problem.",
"deliverables": ["Onboarding friction reports", "Tooling ergonomics assessments", "Documentation gap analysis"],
"trigger_patterns": ["*onboard*", "*setup*", "*config*", "*tool*", "*ci/cd*"],
"assigned_to": null
},
{
"id": "advisor-resilience",
"name": "Resilience & Failure Advisor",
"alias": "The Pessimist",
"enforcement_level": "block",
"scope": "phase_2_to_5",
"consults_with_teams": [4, 7, 9, 11],
"responsibility": "Reviews designs for single points of failure, missing retries, absent circuit breakers, and untested failure paths.",
"persona_voice": "Great, it works. Now what happens when the database is 200ms slower than expected? What about when it's gone entirely?",
"deliverables": ["FMEA", "Blast radius assessments", "Chaos experiment proposals"],
"trigger_patterns": ["*retry*", "*timeout*", "*circuit*", "*fallback*", "*health*", "*bulkhead*", "*rate-limit*"],
"assigned_to": null
},
{
"id": "advisor-privacy",
"name": "Data Privacy & Ethics Advisor",
"alias": "The Conscience",
"enforcement_level": "block",
"scope": "all_phases",
"consults_with_teams": [3, 6, 9],
"responsibility": "Ensures GDPR/CCPA compliance, data minimization, consent management, and ethical AI use.",
"persona_voice": "We're collecting this data — but do we actually need it? What's the retention policy? Can the user delete it?",
"deliverables": ["Privacy impact assessments", "Data flow audits", "Consent management reviews"],
"trigger_patterns": ["*pii*", "*gdpr*", "*consent*", "*retention*", "*encrypt*", "*personal*"],
"assigned_to": null
},
{
"id": "advisor-api",
"name": "API & Integration Advisor",
"alias": "The Diplomat",
"enforcement_level": "block",
"scope": "phase_2_to_4",
"consults_with_teams": [2, 7, 8],
"responsibility": "Reviews API contracts for breaking changes, ensures versioning strategy is followed, and checks third-party reliability.",
"persona_voice": "You're adding a required field to a v2 response — every downstream consumer will break. Let's talk migration.",
"deliverables": ["API contract reviews", "Breaking change assessments", "Version migration plans"],
"trigger_patterns": ["*api*", "*endpoint*", "*contract*", "*version*", "*schema*", "*openapi*"],
"assigned_to": null
},
{
"id": "advisor-perf",
"name": "Performance & Scalability Advisor",
"alias": "The Profiler",
"enforcement_level": "warn",
"scope": "phase_2_to_5",
"consults_with_teams": [4, 7, 10, 11],
"responsibility": "Reviews code for N+1 queries, memory leaks, and cache misses. Ensures capacity planning is data-driven.",
"persona_voice": "This endpoint does a full table scan. At current traffic it's fine — at 5x it'll take the service down.",
"deliverables": ["Performance benchmarks", "Scalability assessments", "Capacity planning recommendations"],
"trigger_patterns": ["*query*", "*cache*", "*memory*", "*cpu*", "*benchmark*", "*load*"],
"assigned_to": null
},
{
"id": "advisor-a11y",
"name": "Accessibility & UX Advisor",
"alias": "The Equalizer",
"enforcement_level": "warn",
"scope": "phase_3_to_4",
"consults_with_teams": [7, 10],
"responsibility": "Reviews UI components and DOM structures for WCAG compliance, screen reader compatibility, and keyboard navigation.",
"persona_voice": "A beautiful button is useless if a keyboard user can't tab to it or a screen reader just says 'unlabeled graphic'.",
"deliverables": ["WCAG compliance audits", "Screen reader compatibility reports", "Keyboard navigation assessments"],
"trigger_patterns": ["*aria*", "*label*", "*focus*", "*tab*", "*screen*", "*wcag*"],
"assigned_to": null
},
{
"id": "advisor-supply-chain",
"name": "Supply Chain & OSS Advisor",
"alias": "The Librarian",
"enforcement_level": "block",
"scope": "all_phases",
"consults_with_teams": [5, 8, 9],
"responsibility": "Evaluates third-party dependencies for known CVEs, abandoned maintenance status, and restrictive open-source licenses.",
"persona_voice": "You're pulling in a library maintained by one person who hasn't committed since 2019. We need an alternative.",
"deliverables": ["CVE impact assessments", "Dependency health reports", "License compliance audits"],
"trigger_patterns": ["*package*", "*dependency*", "*vendor*", "*cve*", "*license*", "*version*"],
"assigned_to": null
},
{
"id": "advisor-audit",
"name": "Compliance & Audit Advisor",
"alias": "The Auditor",
"enforcement_level": "block",
"scope": "all_phases",
"consults_with_teams": [3, 4, 6],
"responsibility": "Focuses strictly on SOC2, HIPAA, PCI-DSS, or ISO27001 controls. Verifies audit logging and auditable access controls.",
"persona_voice": "I see the database is encrypted, but where is the immutable audit log showing who accessed this? If we can't prove it, we fail.",
"deliverables": ["Control gap assessments", "Audit trail verifications", "Compliance readiness reports"],
"trigger_patterns": ["*audit*", "*log*", "*soc2*", "*hipaa*", "*pci*", "*iso*", "*encrypt*"],
"assigned_to": null
}
]
}

View File

@ -0,0 +1,15 @@
{
"rate_limiting": {
"enabled": true,
"requests_per_window": 100,
"window_seconds": 60,
"per_user": true
},
"security": {
"path_traversal_protection": true,
"encryption_at_rest": {
"enabled": false,
"requires_env_key": "TEAM_ENCRYPTION_KEY"
}
}
}

View File

@ -0,0 +1,199 @@
{
"project_name": "empty-project",
"updated_at": "2026-02-15T08:00:00",
"teams": [
{
"id": 1,
"name": "Business & Product Strategy",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Why' - Business case and product strategy",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Business Relationship Manager", "responsibility": "Connects IT to C-suite", "deliverables": ["Strategic alignment docs", "Executive briefings"], "assigned_to": null},
{"name": "Lead Product Manager", "responsibility": "Owns long-term roadmap", "deliverables": ["Product roadmap", "OKRs", "Feature prioritization"], "assigned_to": null},
{"name": "Business Systems Analyst", "responsibility": "Translates business to technical", "deliverables": ["Requirements specs", "User stories", "Acceptance criteria"], "assigned_to": null},
{"name": "Financial Controller (FinOps)", "responsibility": "Approves budget and cloud spend", "deliverables": ["Budget forecasts", "Cost projections", "Spend reports"], "assigned_to": null}
],
"exit_criteria": ["Business case approved", "Budget allocated", "Roadmap defined", "Success metrics established"]
},
{
"id": 2,
"name": "Enterprise Architecture",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Standards' - Technology vision and standards",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Chief Architect", "responsibility": "Sets 5-year tech vision", "deliverables": ["Architecture vision", "Tech radar", "Strategic plans"], "assigned_to": null},
{"name": "Domain Architect", "responsibility": "Specialized stack expertise", "deliverables": ["Domain-specific patterns", "Best practices guides"], "assigned_to": null},
{"name": "Solution Architect", "responsibility": "Maps projects to standards", "deliverables": ["Solution designs", "Architecture decision records"], "assigned_to": null},
{"name": "Standards Lead", "responsibility": "Manages Approved Tech List", "deliverables": ["Technology standards", "Evaluation criteria", "Approved list"], "assigned_to": null}
],
"exit_criteria": ["Architecture approved", "Technology choices validated", "Standards compliance verified"]
},
{
"id": 3,
"name": "GRC (Governance, Risk, & Compliance)",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "Compliance and risk management",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Compliance Officer", "responsibility": "SOX/HIPAA/GDPR adherence", "deliverables": ["Compliance checklists", "Audit reports"], "assigned_to": null},
{"name": "Internal Auditor", "responsibility": "Pre-production mock audits", "deliverables": ["Audit findings", "Remediation plans"], "assigned_to": null},
{"name": "Privacy Engineer", "responsibility": "Data masking and PII", "deliverables": ["Privacy impact assessments", "Data flow diagrams"], "assigned_to": null},
{"name": "Policy Manager", "responsibility": "Maintains SOPs", "deliverables": ["Standard operating procedures", "Policy updates"], "assigned_to": null}
],
"exit_criteria": ["Compliance review passed", "Risk assessment complete", "Privacy requirements met", "Policies acknowledged"]
},
{
"id": 4,
"name": "Infrastructure & Cloud Ops",
"phase": "Phase 2: Platform & Foundation",
"description": "Cloud infrastructure and networking",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Cloud Architect", "responsibility": "VPC and network design", "deliverables": ["Network diagrams", "Security groups", "Routing tables"], "assigned_to": null},
{"name": "IaC Engineer", "responsibility": "Provisions the 'metal'", "deliverables": ["Terraform modules", "Ansible playbooks", "Infrastructure code"], "assigned_to": null},
{"name": "Network Security Engineer", "responsibility": "Firewalls, VPNs, Direct Connect", "deliverables": ["Security rules", "Network policies", "Access controls"], "assigned_to": null},
{"name": "Storage Engineer", "responsibility": "S3/SAN management", "deliverables": ["Storage policies", "Backup strategies", "Archival rules"], "assigned_to": null}
],
"exit_criteria": ["Infrastructure provisioned", "Network connectivity verified", "Security rules applied", "Monitoring enabled"]
},
{
"id": 5,
"name": "Platform Engineering",
"phase": "Phase 2: Platform & Foundation",
"description": "The 'Internal Tools' - Developer experience platform",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Platform Product Manager", "responsibility": "Developer experience as product", "deliverables": ["Platform roadmap", "DX metrics", "Adoption reports"], "assigned_to": null},
{"name": "CI/CD Architect", "responsibility": "Golden pipelines", "deliverables": ["Pipeline templates", "Build configs", "Deployment strategies"], "assigned_to": null},
{"name": "Kubernetes Administrator", "responsibility": "Cluster management", "deliverables": ["Cluster configs", "Resource quotas", "Ingress rules"], "assigned_to": null},
{"name": "Developer Advocate", "responsibility": "Dev squad adoption", "deliverables": ["Onboarding guides", "Training materials", "Feedback loops"], "assigned_to": null}
],
"exit_criteria": ["Platform services ready", "CI/CD pipelines functional", "Developer onboarding complete"]
},
{
"id": 6,
"name": "Data Governance & Analytics",
"phase": "Phase 2: Platform & Foundation",
"description": "Enterprise data management",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Data Architect", "responsibility": "Enterprise data model", "deliverables": ["Data models", "Schema designs", "Lineage documentation"], "assigned_to": null},
{"name": "DBA", "responsibility": "Production database performance", "deliverables": ["Query optimization", "Index tuning", "Backup verification"], "assigned_to": null},
{"name": "Data Privacy Officer", "responsibility": "Retention and deletion rules", "deliverables": ["Data retention policies", "Deletion workflows"], "assigned_to": null},
{"name": "ETL Developer", "responsibility": "Data flow management", "deliverables": ["ETL pipelines", "Data quality checks", "Transformation logic"], "assigned_to": null}
],
"exit_criteria": ["Data models defined", "Pipelines operational", "Privacy controls implemented"]
},
{
"id": 7,
"name": "Core Feature Squad",
"phase": "Phase 3: The Build Squads",
"description": "The 'Devs' - Feature implementation",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Technical Lead", "responsibility": "Final word on implementation", "deliverables": ["Code reviews", "Architecture decisions", "Technical guidance"], "assigned_to": null},
{"name": "Senior Backend Engineer", "responsibility": "Logic, APIs, microservices", "deliverables": ["Backend services", "API endpoints", "Business logic"], "assigned_to": null},
{"name": "Senior Frontend Engineer", "responsibility": "Design system, state management", "deliverables": ["UI components", "Frontend architecture", "State logic"], "assigned_to": null},
{"name": "Accessibility (A11y) Expert", "responsibility": "WCAG compliance", "deliverables": ["A11y audits", "Remediation plans", "Testing reports"], "assigned_to": null},
{"name": "Technical Writer", "responsibility": "Internal/external docs", "deliverables": ["API docs", "User guides", "Runbooks"], "assigned_to": null}
],
"exit_criteria": ["Features implemented", "Code reviewed and approved", "Documentation complete", "A11y requirements met"]
},
{
"id": 8,
"name": "Middleware & Integration",
"phase": "Phase 3: The Build Squads",
"description": "APIs and system integrations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "API Product Manager", "responsibility": "API lifecycle and versioning", "deliverables": ["API specs", "Versioning strategy", "Deprecation plans"], "assigned_to": null},
{"name": "Integration Engineer", "responsibility": "SAP/Oracle/Mainframe connections", "deliverables": ["Integration specs", "Data mappings", "Error handling"], "assigned_to": null},
{"name": "Messaging Engineer", "responsibility": "Kafka/RabbitMQ management", "deliverables": ["Topic design", "Message schemas", "Consumer groups"], "assigned_to": null},
{"name": "IAM Specialist", "responsibility": "Okta/AD integration", "deliverables": ["Auth flows", "Permission models", "Access policies"], "assigned_to": null}
],
"exit_criteria": ["APIs documented and tested", "Integrations verified", "Auth flows functional"]
},
{
"id": 9,
"name": "Cybersecurity (AppSec)",
"phase": "Phase 4: Validation & Hardening",
"description": "Application security",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Security Architect", "responsibility": "Threat model review", "deliverables": ["Threat models", "Security architecture", "Risk assessments"], "assigned_to": null},
{"name": "Vulnerability Researcher", "responsibility": "SAST/DAST/SCA scanners", "deliverables": ["Scan reports", "Vulnerability triage", "Fix verification"], "assigned_to": null},
{"name": "Penetration Tester", "responsibility": "Manual security testing", "deliverables": ["Pen test reports", "Exploit verification", "Remediation"], "assigned_to": null},
{"name": "DevSecOps Engineer", "responsibility": "Security in CI/CD", "deliverables": ["Security gates", "Pipeline integration", "Compliance checks"], "assigned_to": null}
],
"exit_criteria": ["Security review passed", "Vulnerabilities remediated or accepted", "Pen testing complete", "Security gates passing"]
},
{
"id": 10,
"name": "Quality Engineering (SDET)",
"phase": "Phase 4: Validation & Hardening",
"description": "Testing and quality assurance",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "QA Architect", "responsibility": "Global testing strategy", "deliverables": ["Test strategy", "Test plans", "Coverage reports"], "assigned_to": null},
{"name": "SDET", "responsibility": "Automated test code", "deliverables": ["Test automation", "Framework maintenance", "CI integration"], "assigned_to": null},
{"name": "Performance/Load Engineer", "responsibility": "Scale testing", "deliverables": ["Load test scripts", "Performance baselines", "Capacity reports"], "assigned_to": null},
{"name": "Manual QA / UAT Coordinator", "responsibility": "User acceptance testing", "deliverables": ["Test cases", "UAT coordination", "Sign-off reports"], "assigned_to": null}
],
"exit_criteria": ["Test coverage requirements met", "Performance benchmarks achieved", "UAT sign-off obtained"]
},
{
"id": 11,
"name": "Site Reliability Engineering (SRE)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Reliability and observability",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "SRE Lead", "responsibility": "Error budget and uptime SLA", "deliverables": ["SLOs", "Error budgets", "Reliability reports"], "assigned_to": null},
{"name": "Observability Engineer", "responsibility": "Monitoring and logging", "deliverables": ["Dashboards", "Alerts", "Log aggregation", "Traces"], "assigned_to": null},
{"name": "Chaos Engineer", "responsibility": "Resiliency testing", "deliverables": ["Chaos experiments", "Failure scenarios", "Recovery tests"], "assigned_to": null},
{"name": "Incident Manager", "responsibility": "War room leadership", "deliverables": ["Incident response", "Post-mortems", "Runbook updates"], "assigned_to": null}
],
"exit_criteria": ["Monitoring in place", "Alerts configured", "Runbooks complete", "Error budget healthy"]
},
{
"id": 12,
"name": "IT Operations & Support (NOC)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Production operations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "NOC Analyst", "responsibility": "24/7 monitoring", "deliverables": ["Monitoring dashboards", "Alert triage", "Incident tickets"], "assigned_to": null},
{"name": "Change Manager", "responsibility": "Deployment approval", "deliverables": ["Change requests", "Deployment windows", "CAB approval"], "assigned_to": null},
{"name": "Release Manager", "responsibility": "Go/No-Go coordination", "deliverables": ["Release plans", "Rollback procedures", "Coordination"], "assigned_to": null},
{"name": "L3 Support Engineer", "responsibility": "Production bug escalation", "deliverables": ["Root cause analysis", "Hotfix coordination", "KB articles"], "assigned_to": null}
],
"exit_criteria": ["Change approved", "Release deployed", "Support handoff complete"]
}
]
}

View File

@ -0,0 +1,199 @@
{
"project_name": "full-project",
"updated_at": "2026-02-15T12:00:00",
"teams": [
{
"id": 1,
"name": "Business & Product Strategy",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Why' - Business case and product strategy",
"status": "completed",
"started_at": "2026-02-01T09:00:00",
"completed_at": "2026-02-10T17:00:00",
"roles": [
{"name": "Business Relationship Manager", "responsibility": "Connects IT to C-suite", "deliverables": ["Strategic alignment docs", "Executive briefings"], "assigned_to": "Alice Smith"},
{"name": "Lead Product Manager", "responsibility": "Owns long-term roadmap", "deliverables": ["Product roadmap", "OKRs", "Feature prioritization"], "assigned_to": "Bob Johnson"},
{"name": "Business Systems Analyst", "responsibility": "Translates business to technical", "deliverables": ["Requirements specs", "User stories", "Acceptance criteria"], "assigned_to": "Carol White"},
{"name": "Financial Controller (FinOps)", "responsibility": "Approves budget and cloud spend", "deliverables": ["Budget forecasts", "Cost projections", "Spend reports"], "assigned_to": "David Brown"}
],
"exit_criteria": ["Business case approved", "Budget allocated", "Roadmap defined", "Success metrics established"]
},
{
"id": 2,
"name": "Enterprise Architecture",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Standards' - Technology vision and standards",
"status": "completed",
"started_at": "2026-02-01T09:00:00",
"completed_at": "2026-02-10T17:00:00",
"roles": [
{"name": "Chief Architect", "responsibility": "Sets 5-year tech vision", "deliverables": ["Architecture vision", "Tech radar", "Strategic plans"], "assigned_to": "Eve Davis"},
{"name": "Domain Architect", "responsibility": "Specialized stack expertise", "deliverables": ["Domain-specific patterns", "Best practices guides"], "assigned_to": "Frank Miller"},
{"name": "Solution Architect", "responsibility": "Maps projects to standards", "deliverables": ["Solution designs", "Architecture decision records"], "assigned_to": "Grace Wilson"},
{"name": "Standards Lead", "responsibility": "Manages Approved Tech List", "deliverables": ["Technology standards", "Evaluation criteria", "Approved list"], "assigned_to": "Henry Moore"}
],
"exit_criteria": ["Architecture approved", "Technology choices validated", "Standards compliance verified"]
},
{
"id": 3,
"name": "GRC (Governance, Risk, & Compliance)",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "Compliance and risk management",
"status": "completed",
"started_at": "2026-02-01T09:00:00",
"completed_at": "2026-02-10T17:00:00",
"roles": [
{"name": "Compliance Officer", "responsibility": "SOX/HIPAA/GDPR adherence", "deliverables": ["Compliance checklists", "Audit reports"], "assigned_to": "Ivy Taylor"},
{"name": "Internal Auditor", "responsibility": "Pre-production mock audits", "deliverables": ["Audit findings", "Remediation plans"], "assigned_to": "Jack Anderson"},
{"name": "Privacy Engineer", "responsibility": "Data masking and PII", "deliverables": ["Privacy impact assessments", "Data flow diagrams"], "assigned_to": "Karen Thomas"},
{"name": "Policy Manager", "responsibility": "Maintains SOPs", "deliverables": ["Standard operating procedures", "Policy updates"], "assigned_to": "Liam Jackson"}
],
"exit_criteria": ["Compliance review passed", "Risk assessment complete", "Privacy requirements met", "Policies acknowledged"]
},
{
"id": 4,
"name": "Infrastructure & Cloud Ops",
"phase": "Phase 2: Platform & Foundation",
"description": "Cloud infrastructure and networking",
"status": "active",
"started_at": "2026-02-11T09:00:00",
"completed_at": null,
"roles": [
{"name": "Cloud Architect", "responsibility": "VPC and network design", "deliverables": ["Network diagrams", "Security groups", "Routing tables"], "assigned_to": "Maria Garcia"},
{"name": "IaC Engineer", "responsibility": "Provisions the 'metal'", "deliverables": ["Terraform modules", "Ansible playbooks", "Infrastructure code"], "assigned_to": "Noah Martinez"},
{"name": "Network Security Engineer", "responsibility": "Firewalls, VPNs, Direct Connect", "deliverables": ["Security rules", "Network policies", "Access controls"], "assigned_to": "Olivia Rodriguez"},
{"name": "Storage Engineer", "responsibility": "S3/SAN management", "deliverables": ["Storage policies", "Backup strategies", "Archival rules"], "assigned_to": "Paul Lee"}
],
"exit_criteria": ["Infrastructure provisioned", "Network connectivity verified", "Security rules applied", "Monitoring enabled"]
},
{
"id": 5,
"name": "Platform Engineering",
"phase": "Phase 2: Platform & Foundation",
"description": "The 'Internal Tools' - Developer experience platform",
"status": "active",
"started_at": "2026-02-11T09:00:00",
"completed_at": null,
"roles": [
{"name": "Platform Product Manager", "responsibility": "Developer experience as product", "deliverables": ["Platform roadmap", "DX metrics", "Adoption reports"], "assigned_to": "Quinn Walker"},
{"name": "CI/CD Architect", "responsibility": "Golden pipelines", "deliverables": ["Pipeline templates", "Build configs", "Deployment strategies"], "assigned_to": "Rachel Hall"},
{"name": "Kubernetes Administrator", "responsibility": "Cluster management", "deliverables": ["Cluster configs", "Resource quotas", "Ingress rules"], "assigned_to": "Sam Allen"},
{"name": "Developer Advocate", "responsibility": "Dev squad adoption", "deliverables": ["Onboarding guides", "Training materials", "Feedback loops"], "assigned_to": "Tina Young"}
],
"exit_criteria": ["Platform services ready", "CI/CD pipelines functional", "Developer onboarding complete"]
},
{
"id": 6,
"name": "Data Governance & Analytics",
"phase": "Phase 2: Platform & Foundation",
"description": "Enterprise data management",
"status": "active",
"started_at": "2026-02-11T09:00:00",
"completed_at": null,
"roles": [
{"name": "Data Architect", "responsibility": "Enterprise data model", "deliverables": ["Data models", "Schema designs", "Lineage documentation"], "assigned_to": "Ursula King"},
{"name": "DBA", "responsibility": "Production database performance", "deliverables": ["Query optimization", "Index tuning", "Backup verification"], "assigned_to": "Victor Wright"},
{"name": "Data Privacy Officer", "responsibility": "Retention and deletion rules", "deliverables": ["Data retention policies", "Deletion workflows"], "assigned_to": "Wendy Lopez"},
{"name": "ETL Developer", "responsibility": "Data flow management", "deliverables": ["ETL pipelines", "Data quality checks", "Transformation logic"], "assigned_to": "Xavier Hill"}
],
"exit_criteria": ["Data models defined", "Pipelines operational", "Privacy controls implemented"]
},
{
"id": 7,
"name": "Core Feature Squad",
"phase": "Phase 3: The Build Squads",
"description": "The 'Devs' - Feature implementation",
"status": "active",
"started_at": "2026-02-15T09:00:00",
"completed_at": null,
"roles": [
{"name": "Technical Lead", "responsibility": "Final word on implementation", "deliverables": ["Code reviews", "Architecture decisions", "Technical guidance"], "assigned_to": "Aaron Scott"},
{"name": "Senior Backend Engineer", "responsibility": "Logic, APIs, microservices", "deliverables": ["Backend services", "API endpoints", "Business logic"], "assigned_to": "Bella Green"},
{"name": "Senior Frontend Engineer", "responsibility": "Design system, state management", "deliverables": ["UI components", "Frontend architecture", "State logic"], "assigned_to": "Chris Adams"},
{"name": "Accessibility (A11y) Expert", "responsibility": "WCAG compliance", "deliverables": ["A11y audits", "Remediation plans", "Testing reports"], "assigned_to": "Diana Baker"},
{"name": "Technical Writer", "responsibility": "Internal/external docs", "deliverables": ["API docs", "User guides", "Runbooks"], "assigned_to": "Ethan Nelson"}
],
"exit_criteria": ["Features implemented", "Code reviewed and approved", "Documentation complete", "A11y requirements met"]
},
{
"id": 8,
"name": "Middleware & Integration",
"phase": "Phase 3: The Build Squads",
"description": "APIs and system integrations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "API Product Manager", "responsibility": "API lifecycle and versioning", "deliverables": ["API specs", "Versioning strategy", "Deprecation plans"], "assigned_to": "Fiona Carter"},
{"name": "Integration Engineer", "responsibility": "SAP/Oracle/Mainframe connections", "deliverables": ["Integration specs", "Data mappings", "Error handling"], "assigned_to": "George Mitchell"},
{"name": "Messaging Engineer", "responsibility": "Kafka/RabbitMQ management", "deliverables": ["Topic design", "Message schemas", "Consumer groups"], "assigned_to": "Hannah Perez"},
{"name": "IAM Specialist", "responsibility": "Okta/AD integration", "deliverables": ["Auth flows", "Permission models", "Access policies"], "assigned_to": "Ian Roberts"}
],
"exit_criteria": ["APIs documented and tested", "Integrations verified", "Auth flows functional"]
},
{
"id": 9,
"name": "Cybersecurity (AppSec)",
"phase": "Phase 4: Validation & Hardening",
"description": "Application security",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Security Architect", "responsibility": "Threat model review", "deliverables": ["Threat models", "Security architecture", "Risk assessments"], "assigned_to": "Julia Turner"},
{"name": "Vulnerability Researcher", "responsibility": "SAST/DAST/SCA scanners", "deliverables": ["Scan reports", "Vulnerability triage", "Fix verification"], "assigned_to": "Kevin Phillips"},
{"name": "Penetration Tester", "responsibility": "Manual security testing", "deliverables": ["Pen test reports", "Exploit verification", "Remediation"], "assigned_to": "Laura Campbell"},
{"name": "DevSecOps Engineer", "responsibility": "Security in CI/CD", "deliverables": ["Security gates", "Pipeline integration", "Compliance checks"], "assigned_to": "Mark Parker"}
],
"exit_criteria": ["Security review passed", "Vulnerabilities remediated or accepted", "Pen testing complete", "Security gates passing"]
},
{
"id": 10,
"name": "Quality Engineering (SDET)",
"phase": "Phase 4: Validation & Hardening",
"description": "Testing and quality assurance",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "QA Architect", "responsibility": "Global testing strategy", "deliverables": ["Test strategy", "Test plans", "Coverage reports"], "assigned_to": "Nancy Evans"},
{"name": "SDET", "responsibility": "Automated test code", "deliverables": ["Test automation", "Framework maintenance", "CI integration"], "assigned_to": "Oscar Edwards"},
{"name": "Performance/Load Engineer", "responsibility": "Scale testing", "deliverables": ["Load test scripts", "Performance baselines", "Capacity reports"], "assigned_to": "Patricia Collins"},
{"name": "Manual QA / UAT Coordinator", "responsibility": "User acceptance testing", "deliverables": ["Test cases", "UAT coordination", "Sign-off reports"], "assigned_to": "Quincy Stewart"}
],
"exit_criteria": ["Test coverage requirements met", "Performance benchmarks achieved", "UAT sign-off obtained"]
},
{
"id": 11,
"name": "Site Reliability Engineering (SRE)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Reliability and observability",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "SRE Lead", "responsibility": "Error budget and uptime SLA", "deliverables": ["SLOs", "Error budgets", "Reliability reports"], "assigned_to": "Rachel Sanchez"},
{"name": "Observability Engineer", "responsibility": "Monitoring and logging", "deliverables": ["Dashboards", "Alerts", "Log aggregation", "Traces"], "assigned_to": "Steve Morris"},
{"name": "Chaos Engineer", "responsibility": "Resiliency testing", "deliverables": ["Chaos experiments", "Failure scenarios", "Recovery tests"], "assigned_to": "Tara Rogers"},
{"name": "Incident Manager", "responsibility": "War room leadership", "deliverables": ["Incident response", "Post-mortems", "Runbook updates"], "assigned_to": "Ulysses Reed"}
],
"exit_criteria": ["Monitoring in place", "Alerts configured", "Runbooks complete", "Error budget healthy"]
},
{
"id": 12,
"name": "IT Operations & Support (NOC)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Production operations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "NOC Analyst", "responsibility": "24/7 monitoring", "deliverables": ["Monitoring dashboards", "Alert triage", "Incident tickets"], "assigned_to": "Victoria Cook"},
{"name": "Change Manager", "responsibility": "Deployment approval", "deliverables": ["Change requests", "Deployment windows", "CAB approval"], "assigned_to": "William Morgan"},
{"name": "Release Manager", "responsibility": "Go/No-Go coordination", "deliverables": ["Release plans", "Rollback procedures", "Coordination"], "assigned_to": "Xena Bell"},
{"name": "L3 Support Engineer", "responsibility": "Production bug escalation", "deliverables": ["Root cause analysis", "Hotfix coordination", "KB articles"], "assigned_to": "Yvonne Bailey"}
],
"exit_criteria": ["Change approved", "Release deployed", "Support handoff complete"]
}
]
}

View File

@ -0,0 +1,498 @@
{
"project_name": "minimal-project",
"updated_at": "2026-02-15T10:00:00",
"teams": [
{
"id": 1,
"name": "Business & Product Strategy",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Why' - Business case and product strategy",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Business Relationship Manager",
"responsibility": "Connects IT to C-suite",
"deliverables": ["Strategic alignment docs", "Executive briefings"],
"assigned_to": "John Doe"
},
{
"name": "Lead Product Manager",
"responsibility": "Owns long-term roadmap",
"deliverables": ["Product roadmap", "OKRs", "Feature prioritization"],
"assigned_to": null
},
{
"name": "Business Systems Analyst",
"responsibility": "Translates business to technical",
"deliverables": ["Requirements specs", "User stories", "Acceptance criteria"],
"assigned_to": null
},
{
"name": "Financial Controller (FinOps)",
"responsibility": "Approves budget and cloud spend",
"deliverables": ["Budget forecasts", "Cost projections", "Spend reports"],
"assigned_to": null
}
],
"exit_criteria": [
"Business case approved",
"Budget allocated",
"Roadmap defined",
"Success metrics established"
]
},
{
"id": 2,
"name": "Enterprise Architecture",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Standards' - Technology vision and standards",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Chief Architect",
"responsibility": "Sets 5-year tech vision",
"deliverables": ["Architecture vision", "Tech radar", "Strategic plans"],
"assigned_to": null
},
{
"name": "Domain Architect",
"responsibility": "Specialized stack expertise",
"deliverables": ["Domain-specific patterns", "Best practices guides"],
"assigned_to": null
},
{
"name": "Solution Architect",
"responsibility": "Maps projects to standards",
"deliverables": ["Solution designs", "Architecture decision records"],
"assigned_to": null
},
{
"name": "Standards Lead",
"responsibility": "Manages Approved Tech List",
"deliverables": ["Technology standards", "Evaluation criteria", "Approved list"],
"assigned_to": null
}
],
"exit_criteria": [
"Architecture approved",
"Technology choices validated",
"Standards compliance verified"
]
},
{
"id": 3,
"name": "GRC (Governance, Risk, & Compliance)",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "Compliance and risk management",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Compliance Officer",
"responsibility": "SOX/HIPAA/GDPR adherence",
"deliverables": ["Compliance checklists", "Audit reports"],
"assigned_to": null
},
{
"name": "Internal Auditor",
"responsibility": "Pre-production mock audits",
"deliverables": ["Audit findings", "Remediation plans"],
"assigned_to": null
},
{
"name": "Privacy Engineer",
"responsibility": "Data masking and PII",
"deliverables": ["Privacy impact assessments", "Data flow diagrams"],
"assigned_to": null
},
{
"name": "Policy Manager",
"responsibility": "Maintains SOPs",
"deliverables": ["Standard operating procedures", "Policy updates"],
"assigned_to": null
}
],
"exit_criteria": [
"Compliance review passed",
"Risk assessment complete",
"Privacy requirements met",
"Policies acknowledged"
]
},
{
"id": 4,
"name": "Infrastructure & Cloud Ops",
"phase": "Phase 2: Platform & Foundation",
"description": "Cloud infrastructure and networking",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Cloud Architect",
"responsibility": "VPC and network design",
"deliverables": ["Network diagrams", "Security groups", "Routing tables"],
"assigned_to": null
},
{
"name": "IaC Engineer",
"responsibility": "Provisions the 'metal'",
"deliverables": ["Terraform modules", "Ansible playbooks", "Infrastructure code"],
"assigned_to": null
},
{
"name": "Network Security Engineer",
"responsibility": "Firewalls, VPNs, Direct Connect",
"deliverables": ["Security rules", "Network policies", "Access controls"],
"assigned_to": null
},
{
"name": "Storage Engineer",
"responsibility": "S3/SAN management",
"deliverables": ["Storage policies", "Backup strategies", "Archival rules"],
"assigned_to": null
}
],
"exit_criteria": [
"Infrastructure provisioned",
"Network connectivity verified",
"Security rules applied",
"Monitoring enabled"
]
},
{
"id": 5,
"name": "Platform Engineering",
"phase": "Phase 2: Platform & Foundation",
"description": "The 'Internal Tools' - Developer experience platform",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Platform Product Manager",
"responsibility": "Developer experience as product",
"deliverables": ["Platform roadmap", "DX metrics", "Adoption reports"],
"assigned_to": null
},
{
"name": "CI/CD Architect",
"responsibility": "Golden pipelines",
"deliverables": ["Pipeline templates", "Build configs", "Deployment strategies"],
"assigned_to": null
},
{
"name": "Kubernetes Administrator",
"responsibility": "Cluster management",
"deliverables": ["Cluster configs", "Resource quotas", "Ingress rules"],
"assigned_to": null
},
{
"name": "Developer Advocate",
"responsibility": "Dev squad adoption",
"deliverables": ["Onboarding guides", "Training materials", "Feedback loops"],
"assigned_to": null
}
],
"exit_criteria": [
"Platform services ready",
"CI/CD pipelines functional",
"Developer onboarding complete"
]
},
{
"id": 6,
"name": "Data Governance & Analytics",
"phase": "Phase 2: Platform & Foundation",
"description": "Enterprise data management",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Data Architect",
"responsibility": "Enterprise data model",
"deliverables": ["Data models", "Schema designs", "Lineage documentation"],
"assigned_to": null
},
{
"name": "DBA",
"responsibility": "Production database performance",
"deliverables": ["Query optimization", "Index tuning", "Backup verification"],
"assigned_to": null
},
{
"name": "Data Privacy Officer",
"responsibility": "Retention and deletion rules",
"deliverables": ["Data retention policies", "Deletion workflows"],
"assigned_to": null
},
{
"name": "ETL Developer",
"responsibility": "Data flow management",
"deliverables": ["ETL pipelines", "Data quality checks", "Transformation logic"],
"assigned_to": null
}
],
"exit_criteria": [
"Data models defined",
"Pipelines operational",
"Privacy controls implemented"
]
},
{
"id": 7,
"name": "Core Feature Squad",
"phase": "Phase 3: The Build Squads",
"description": "The 'Devs' - Feature implementation",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Technical Lead",
"responsibility": "Final word on implementation",
"deliverables": ["Code reviews", "Architecture decisions", "Technical guidance"],
"assigned_to": null
},
{
"name": "Senior Backend Engineer",
"responsibility": "Logic, APIs, microservices",
"deliverables": ["Backend services", "API endpoints", "Business logic"],
"assigned_to": null
},
{
"name": "Senior Frontend Engineer",
"responsibility": "Design system, state management",
"deliverables": ["UI components", "Frontend architecture", "State logic"],
"assigned_to": null
},
{
"name": "Accessibility (A11y) Expert",
"responsibility": "WCAG compliance",
"deliverables": ["A11y audits", "Remediation plans", "Testing reports"],
"assigned_to": null
},
{
"name": "Technical Writer",
"responsibility": "Internal/external docs",
"deliverables": ["API docs", "User guides", "Runbooks"],
"assigned_to": null
}
],
"exit_criteria": [
"Features implemented",
"Code reviewed and approved",
"Documentation complete",
"A11y requirements met"
]
},
{
"id": 8,
"name": "Middleware & Integration",
"phase": "Phase 3: The Build Squads",
"description": "APIs and system integrations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "API Product Manager",
"responsibility": "API lifecycle and versioning",
"deliverables": ["API specs", "Versioning strategy", "Deprecation plans"],
"assigned_to": null
},
{
"name": "Integration Engineer",
"responsibility": "SAP/Oracle/Mainframe connections",
"deliverables": ["Integration specs", "Data mappings", "Error handling"],
"assigned_to": null
},
{
"name": "Messaging Engineer",
"responsibility": "Kafka/RabbitMQ management",
"deliverables": ["Topic design", "Message schemas", "Consumer groups"],
"assigned_to": null
},
{
"name": "IAM Specialist",
"responsibility": "Okta/AD integration",
"deliverables": ["Auth flows", "Permission models", "Access policies"],
"assigned_to": null
}
],
"exit_criteria": [
"APIs documented and tested",
"Integrations verified",
"Auth flows functional"
]
},
{
"id": 9,
"name": "Cybersecurity (AppSec)",
"phase": "Phase 4: Validation & Hardening",
"description": "Application security",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "Security Architect",
"responsibility": "Threat model review",
"deliverables": ["Threat models", "Security architecture", "Risk assessments"],
"assigned_to": null
},
{
"name": "Vulnerability Researcher",
"responsibility": "SAST/DAST/SCA scanners",
"deliverables": ["Scan reports", "Vulnerability triage", "Fix verification"],
"assigned_to": null
},
{
"name": "Penetration Tester",
"responsibility": "Manual security testing",
"deliverables": ["Pen test reports", "Exploit verification", "Remediation"],
"assigned_to": null
},
{
"name": "DevSecOps Engineer",
"responsibility": "Security in CI/CD",
"deliverables": ["Security gates", "Pipeline integration", "Compliance checks"],
"assigned_to": null
}
],
"exit_criteria": [
"Security review passed",
"Vulnerabilities remediated or accepted",
"Pen testing complete",
"Security gates passing"
]
},
{
"id": 10,
"name": "Quality Engineering (SDET)",
"phase": "Phase 4: Validation & Hardening",
"description": "Testing and quality assurance",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "QA Architect",
"responsibility": "Global testing strategy",
"deliverables": ["Test strategy", "Test plans", "Coverage reports"],
"assigned_to": null
},
{
"name": "SDET",
"responsibility": "Automated test code",
"deliverables": ["Test automation", "Framework maintenance", "CI integration"],
"assigned_to": null
},
{
"name": "Performance/Load Engineer",
"responsibility": "Scale testing",
"deliverables": ["Load test scripts", "Performance baselines", "Capacity reports"],
"assigned_to": null
},
{
"name": "Manual QA / UAT Coordinator",
"responsibility": "User acceptance testing",
"deliverables": ["Test cases", "UAT coordination", "Sign-off reports"],
"assigned_to": null
}
],
"exit_criteria": [
"Test coverage requirements met",
"Performance benchmarks achieved",
"UAT sign-off obtained"
]
},
{
"id": 11,
"name": "Site Reliability Engineering (SRE)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Reliability and observability",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "SRE Lead",
"responsibility": "Error budget and uptime SLA",
"deliverables": ["SLOs", "Error budgets", "Reliability reports"],
"assigned_to": null
},
{
"name": "Observability Engineer",
"responsibility": "Monitoring and logging",
"deliverables": ["Dashboards", "Alerts", "Log aggregation", "Traces"],
"assigned_to": null
},
{
"name": "Chaos Engineer",
"responsibility": "Resiliency testing",
"deliverables": ["Chaos experiments", "Failure scenarios", "Recovery tests"],
"assigned_to": null
},
{
"name": "Incident Manager",
"responsibility": "War room leadership",
"deliverables": ["Incident response", "Post-mortems", "Runbook updates"],
"assigned_to": null
}
],
"exit_criteria": [
"Monitoring in place",
"Alerts configured",
"Runbooks complete",
"Error budget healthy"
]
},
{
"id": 12,
"name": "IT Operations & Support (NOC)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Production operations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{
"name": "NOC Analyst",
"responsibility": "24/7 monitoring",
"deliverables": ["Monitoring dashboards", "Alert triage", "Incident tickets"],
"assigned_to": null
},
{
"name": "Change Manager",
"responsibility": "Deployment approval",
"deliverables": ["Change requests", "Deployment windows", "CAB approval"],
"assigned_to": null
},
{
"name": "Release Manager",
"responsibility": "Go/No-Go coordination",
"deliverables": ["Release plans", "Rollback procedures", "Coordination"],
"assigned_to": null
},
{
"name": "L3 Support Engineer",
"responsibility": "Production bug escalation",
"deliverables": ["Root cause analysis", "Hotfix coordination", "KB articles"],
"assigned_to": null
}
],
"exit_criteria": [
"Change approved",
"Release deployed",
"Support handoff complete"
]
}
]
}

View File

@ -0,0 +1,199 @@
{
"project_name": "partial-assignments",
"updated_at": "2026-02-15T11:00:00",
"teams": [
{
"id": 1,
"name": "Business & Product Strategy",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Why' - Business case and product strategy",
"status": "active",
"started_at": "2026-02-10T09:00:00",
"completed_at": null,
"roles": [
{"name": "Business Relationship Manager", "responsibility": "Connects IT to C-suite", "deliverables": ["Strategic alignment docs", "Executive briefings"], "assigned_to": "Alice Smith"},
{"name": "Lead Product Manager", "responsibility": "Owns long-term roadmap", "deliverables": ["Product roadmap", "OKRs", "Feature prioritization"], "assigned_to": "Bob Johnson"},
{"name": "Business Systems Analyst", "responsibility": "Translates business to technical", "deliverables": ["Requirements specs", "User stories", "Acceptance criteria"], "assigned_to": null},
{"name": "Financial Controller (FinOps)", "responsibility": "Approves budget and cloud spend", "deliverables": ["Budget forecasts", "Cost projections", "Spend reports"], "assigned_to": null}
],
"exit_criteria": ["Business case approved", "Budget allocated", "Roadmap defined", "Success metrics established"]
},
{
"id": 2,
"name": "Enterprise Architecture",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Standards' - Technology vision and standards",
"status": "active",
"started_at": "2026-02-10T09:00:00",
"completed_at": null,
"roles": [
{"name": "Chief Architect", "responsibility": "Sets 5-year tech vision", "deliverables": ["Architecture vision", "Tech radar", "Strategic plans"], "assigned_to": "Eve Davis"},
{"name": "Domain Architect", "responsibility": "Specialized stack expertise", "deliverables": ["Domain-specific patterns", "Best practices guides"], "assigned_to": "Frank Miller"},
{"name": "Solution Architect", "responsibility": "Maps projects to standards", "deliverables": ["Solution designs", "Architecture decision records"], "assigned_to": "Grace Wilson"},
{"name": "Standards Lead", "responsibility": "Manages Approved Tech List", "deliverables": ["Technology standards", "Evaluation criteria", "Approved list"], "assigned_to": "Henry Moore"}
],
"exit_criteria": ["Architecture approved", "Technology choices validated", "Standards compliance verified"]
},
{
"id": 3,
"name": "GRC (Governance, Risk, & Compliance)",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "Compliance and risk management",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Compliance Officer", "responsibility": "SOX/HIPAA/GDPR adherence", "deliverables": ["Compliance checklists", "Audit reports"], "assigned_to": null},
{"name": "Internal Auditor", "responsibility": "Pre-production mock audits", "deliverables": ["Audit findings", "Remediation plans"], "assigned_to": null},
{"name": "Privacy Engineer", "responsibility": "Data masking and PII", "deliverables": ["Privacy impact assessments", "Data flow diagrams"], "assigned_to": null},
{"name": "Policy Manager", "responsibility": "Maintains SOPs", "deliverables": ["Standard operating procedures", "Policy updates"], "assigned_to": null}
],
"exit_criteria": ["Compliance review passed", "Risk assessment complete", "Privacy requirements met", "Policies acknowledged"]
},
{
"id": 4,
"name": "Infrastructure & Cloud Ops",
"phase": "Phase 2: Platform & Foundation",
"description": "Cloud infrastructure and networking",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Cloud Architect", "responsibility": "VPC and network design", "deliverables": ["Network diagrams", "Security groups", "Routing tables"], "assigned_to": "Maria Garcia"},
{"name": "IaC Engineer", "responsibility": "Provisions the 'metal'", "deliverables": ["Terraform modules", "Ansible playbooks", "Infrastructure code"], "assigned_to": null},
{"name": "Network Security Engineer", "responsibility": "Firewalls, VPNs, Direct Connect", "deliverables": ["Security rules", "Network policies", "Access controls"], "assigned_to": null},
{"name": "Storage Engineer", "responsibility": "S3/SAN management", "deliverables": ["Storage policies", "Backup strategies", "Archival rules"], "assigned_to": null}
],
"exit_criteria": ["Infrastructure provisioned", "Network connectivity verified", "Security rules applied", "Monitoring enabled"]
},
{
"id": 5,
"name": "Platform Engineering",
"phase": "Phase 2: Platform & Foundation",
"description": "The 'Internal Tools' - Developer experience platform",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Platform Product Manager", "responsibility": "Developer experience as product", "deliverables": ["Platform roadmap", "DX metrics", "Adoption reports"], "assigned_to": null},
{"name": "CI/CD Architect", "responsibility": "Golden pipelines", "deliverables": ["Pipeline templates", "Build configs", "Deployment strategies"], "assigned_to": null},
{"name": "Kubernetes Administrator", "responsibility": "Cluster management", "deliverables": ["Cluster configs", "Resource quotas", "Ingress rules"], "assigned_to": null},
{"name": "Developer Advocate", "responsibility": "Dev squad adoption", "deliverables": ["Onboarding guides", "Training materials", "Feedback loops"], "assigned_to": null}
],
"exit_criteria": ["Platform services ready", "CI/CD pipelines functional", "Developer onboarding complete"]
},
{
"id": 6,
"name": "Data Governance & Analytics",
"phase": "Phase 2: Platform & Foundation",
"description": "Enterprise data management",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Data Architect", "responsibility": "Enterprise data model", "deliverables": ["Data models", "Schema designs", "Lineage documentation"], "assigned_to": null},
{"name": "DBA", "responsibility": "Production database performance", "deliverables": ["Query optimization", "Index tuning", "Backup verification"], "assigned_to": null},
{"name": "Data Privacy Officer", "responsibility": "Retention and deletion rules", "deliverables": ["Data retention policies", "Deletion workflows"], "assigned_to": null},
{"name": "ETL Developer", "responsibility": "Data flow management", "deliverables": ["ETL pipelines", "Data quality checks", "Transformation logic"], "assigned_to": null}
],
"exit_criteria": ["Data models defined", "Pipelines operational", "Privacy controls implemented"]
},
{
"id": 7,
"name": "Core Feature Squad",
"phase": "Phase 3: The Build Squads",
"description": "The 'Devs' - Feature implementation",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Technical Lead", "responsibility": "Final word on implementation", "deliverables": ["Code reviews", "Architecture decisions", "Technical guidance"], "assigned_to": "Aaron Scott"},
{"name": "Senior Backend Engineer", "responsibility": "Logic, APIs, microservices", "deliverables": ["Backend services", "API endpoints", "Business logic"], "assigned_to": "Bella Green"},
{"name": "Senior Frontend Engineer", "responsibility": "Design system, state management", "deliverables": ["UI components", "Frontend architecture", "State logic"], "assigned_to": null},
{"name": "Accessibility (A11y) Expert", "responsibility": "WCAG compliance", "deliverables": ["A11y audits", "Remediation plans", "Testing reports"], "assigned_to": null},
{"name": "Technical Writer", "responsibility": "Internal/external docs", "deliverables": ["API docs", "User guides", "Runbooks"], "assigned_to": null}
],
"exit_criteria": ["Features implemented", "Code reviewed and approved", "Documentation complete", "A11y requirements met"]
},
{
"id": 8,
"name": "Middleware & Integration",
"phase": "Phase 3: The Build Squads",
"description": "APIs and system integrations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "API Product Manager", "responsibility": "API lifecycle and versioning", "deliverables": ["API specs", "Versioning strategy", "Deprecation plans"], "assigned_to": null},
{"name": "Integration Engineer", "responsibility": "SAP/Oracle/Mainframe connections", "deliverables": ["Integration specs", "Data mappings", "Error handling"], "assigned_to": null},
{"name": "Messaging Engineer", "responsibility": "Kafka/RabbitMQ management", "deliverables": ["Topic design", "Message schemas", "Consumer groups"], "assigned_to": null},
{"name": "IAM Specialist", "responsibility": "Okta/AD integration", "deliverables": ["Auth flows", "Permission models", "Access policies"], "assigned_to": null}
],
"exit_criteria": ["APIs documented and tested", "Integrations verified", "Auth flows functional"]
},
{
"id": 9,
"name": "Cybersecurity (AppSec)",
"phase": "Phase 4: Validation & Hardening",
"description": "Application security",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Security Architect", "responsibility": "Threat model review", "deliverables": ["Threat models", "Security architecture", "Risk assessments"], "assigned_to": null},
{"name": "Vulnerability Researcher", "responsibility": "SAST/DAST/SCA scanners", "deliverables": ["Scan reports", "Vulnerability triage", "Fix verification"], "assigned_to": null},
{"name": "Penetration Tester", "responsibility": "Manual security testing", "deliverables": ["Pen test reports", "Exploit verification", "Remediation"], "assigned_to": null},
{"name": "DevSecOps Engineer", "responsibility": "Security in CI/CD", "deliverables": ["Security gates", "Pipeline integration", "Compliance checks"], "assigned_to": null}
],
"exit_criteria": ["Security review passed", "Vulnerabilities remediated or accepted", "Pen testing complete", "Security gates passing"]
},
{
"id": 10,
"name": "Quality Engineering (SDET)",
"phase": "Phase 4: Validation & Hardening",
"description": "Testing and quality assurance",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "QA Architect", "responsibility": "Global testing strategy", "deliverables": ["Test strategy", "Test plans", "Coverage reports"], "assigned_to": "Nancy Evans"},
{"name": "SDET", "responsibility": "Automated test code", "deliverables": ["Test automation", "Framework maintenance", "CI integration"], "assigned_to": "Oscar Edwards"},
{"name": "Performance/Load Engineer", "responsibility": "Scale testing", "deliverables": ["Load test scripts", "Performance baselines", "Capacity reports"], "assigned_to": "Patricia Collins"},
{"name": "Manual QA / UAT Coordinator", "responsibility": "User acceptance testing", "deliverables": ["Test cases", "UAT coordination", "Sign-off reports"], "assigned_to": "Quincy Stewart"}
],
"exit_criteria": ["Test coverage requirements met", "Performance benchmarks achieved", "UAT sign-off obtained"]
},
{
"id": 11,
"name": "Site Reliability Engineering (SRE)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Reliability and observability",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "SRE Lead", "responsibility": "Error budget and uptime SLA", "deliverables": ["SLOs", "Error budgets", "Reliability reports"], "assigned_to": null},
{"name": "Observability Engineer", "responsibility": "Monitoring and logging", "deliverables": ["Dashboards", "Alerts", "Log aggregation", "Traces"], "assigned_to": null},
{"name": "Chaos Engineer", "responsibility": "Resiliency testing", "deliverables": ["Chaos experiments", "Failure scenarios", "Recovery tests"], "assigned_to": null},
{"name": "Incident Manager", "responsibility": "War room leadership", "deliverables": ["Incident response", "Post-mortems", "Runbook updates"], "assigned_to": null}
],
"exit_criteria": ["Monitoring in place", "Alerts configured", "Runbooks complete", "Error budget healthy"]
},
{
"id": 12,
"name": "IT Operations & Support (NOC)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Production operations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "NOC Analyst", "responsibility": "24/7 monitoring", "deliverables": ["Monitoring dashboards", "Alert triage", "Incident tickets"], "assigned_to": null},
{"name": "Change Manager", "responsibility": "Deployment approval", "deliverables": ["Change requests", "Deployment windows", "CAB approval"], "assigned_to": null},
{"name": "Release Manager", "responsibility": "Go/No-Go coordination", "deliverables": ["Release plans", "Rollback procedures", "Coordination"], "assigned_to": null},
{"name": "L3 Support Engineer", "responsibility": "Production bug escalation", "deliverables": ["Root cause analysis", "Hotfix coordination", "KB articles"], "assigned_to": null}
],
"exit_criteria": ["Change approved", "Release deployed", "Support handoff complete"]
}
]
}

View File

@ -0,0 +1,199 @@
{
"project_name": "phase1-complete",
"updated_at": "2026-02-15T14:00:00",
"teams": [
{
"id": 1,
"name": "Business & Product Strategy",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Why' - Business case and product strategy",
"status": "completed",
"started_at": "2026-01-15T09:00:00",
"completed_at": "2026-01-30T17:00:00",
"roles": [
{"name": "Business Relationship Manager", "responsibility": "Connects IT to C-suite", "deliverables": ["Strategic alignment docs", "Executive briefings"], "assigned_to": "Alice Smith"},
{"name": "Lead Product Manager", "responsibility": "Owns long-term roadmap", "deliverables": ["Product roadmap", "OKRs", "Feature prioritization"], "assigned_to": "Bob Johnson"},
{"name": "Business Systems Analyst", "responsibility": "Translates business to technical", "deliverables": ["Requirements specs", "User stories", "Acceptance criteria"], "assigned_to": "Carol White"},
{"name": "Financial Controller (FinOps)", "responsibility": "Approves budget and cloud spend", "deliverables": ["Budget forecasts", "Cost projections", "Spend reports"], "assigned_to": "David Brown"}
],
"exit_criteria": ["Business case approved", "Budget allocated", "Roadmap defined", "Success metrics established"]
},
{
"id": 2,
"name": "Enterprise Architecture",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "The 'Standards' - Technology vision and standards",
"status": "completed",
"started_at": "2026-01-15T09:00:00",
"completed_at": "2026-01-30T17:00:00",
"roles": [
{"name": "Chief Architect", "responsibility": "Sets 5-year tech vision", "deliverables": ["Architecture vision", "Tech radar", "Strategic plans"], "assigned_to": "Eve Davis"},
{"name": "Domain Architect", "responsibility": "Specialized stack expertise", "deliverables": ["Domain-specific patterns", "Best practices guides"], "assigned_to": "Frank Miller"},
{"name": "Solution Architect", "responsibility": "Maps projects to standards", "deliverables": ["Solution designs", "Architecture decision records"], "assigned_to": "Grace Wilson"},
{"name": "Standards Lead", "responsibility": "Manages Approved Tech List", "deliverables": ["Technology standards", "Evaluation criteria", "Approved list"], "assigned_to": "Henry Moore"}
],
"exit_criteria": ["Architecture approved", "Technology choices validated", "Standards compliance verified"]
},
{
"id": 3,
"name": "GRC (Governance, Risk, & Compliance)",
"phase": "Phase 1: Strategy, Governance & Planning",
"description": "Compliance and risk management",
"status": "completed",
"started_at": "2026-01-15T09:00:00",
"completed_at": "2026-01-30T17:00:00",
"roles": [
{"name": "Compliance Officer", "responsibility": "SOX/HIPAA/GDPR adherence", "deliverables": ["Compliance checklists", "Audit reports"], "assigned_to": "Ivy Taylor"},
{"name": "Internal Auditor", "responsibility": "Pre-production mock audits", "deliverables": ["Audit findings", "Remediation plans"], "assigned_to": "Jack Anderson"},
{"name": "Privacy Engineer", "responsibility": "Data masking and PII", "deliverables": ["Privacy impact assessments", "Data flow diagrams"], "assigned_to": "Karen Thomas"},
{"name": "Policy Manager", "responsibility": "Maintains SOPs", "deliverables": ["Standard operating procedures", "Policy updates"], "assigned_to": "Liam Jackson"}
],
"exit_criteria": ["Compliance review passed", "Risk assessment complete", "Privacy requirements met", "Policies acknowledged"]
},
{
"id": 4,
"name": "Infrastructure & Cloud Ops",
"phase": "Phase 2: Platform & Foundation",
"description": "Cloud infrastructure and networking",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Cloud Architect", "responsibility": "VPC and network design", "deliverables": ["Network diagrams", "Security groups", "Routing tables"], "assigned_to": null},
{"name": "IaC Engineer", "responsibility": "Provisions the 'metal'", "deliverables": ["Terraform modules", "Ansible playbooks", "Infrastructure code"], "assigned_to": null},
{"name": "Network Security Engineer", "responsibility": "Firewalls, VPNs, Direct Connect", "deliverables": ["Security rules", "Network policies", "Access controls"], "assigned_to": null},
{"name": "Storage Engineer", "responsibility": "S3/SAN management", "deliverables": ["Storage policies", "Backup strategies", "Archival rules"], "assigned_to": null}
],
"exit_criteria": ["Infrastructure provisioned", "Network connectivity verified", "Security rules applied", "Monitoring enabled"]
},
{
"id": 5,
"name": "Platform Engineering",
"phase": "Phase 2: Platform & Foundation",
"description": "The 'Internal Tools' - Developer experience platform",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Platform Product Manager", "responsibility": "Developer experience as product", "deliverables": ["Platform roadmap", "DX metrics", "Adoption reports"], "assigned_to": null},
{"name": "CI/CD Architect", "responsibility": "Golden pipelines", "deliverables": ["Pipeline templates", "Build configs", "Deployment strategies"], "assigned_to": null},
{"name": "Kubernetes Administrator", "responsibility": "Cluster management", "deliverables": ["Cluster configs", "Resource quotas", "Ingress rules"], "assigned_to": null},
{"name": "Developer Advocate", "responsibility": "Dev squad adoption", "deliverables": ["Onboarding guides", "Training materials", "Feedback loops"], "assigned_to": null}
],
"exit_criteria": ["Platform services ready", "CI/CD pipelines functional", "Developer onboarding complete"]
},
{
"id": 6,
"name": "Data Governance & Analytics",
"phase": "Phase 2: Platform & Foundation",
"description": "Enterprise data management",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Data Architect", "responsibility": "Enterprise data model", "deliverables": ["Data models", "Schema designs", "Lineage documentation"], "assigned_to": null},
{"name": "DBA", "responsibility": "Production database performance", "deliverables": ["Query optimization", "Index tuning", "Backup verification"], "assigned_to": null},
{"name": "Data Privacy Officer", "responsibility": "Retention and deletion rules", "deliverables": ["Data retention policies", "Deletion workflows"], "assigned_to": null},
{"name": "ETL Developer", "responsibility": "Data flow management", "deliverables": ["ETL pipelines", "Data quality checks", "Transformation logic"], "assigned_to": null}
],
"exit_criteria": ["Data models defined", "Pipelines operational", "Privacy controls implemented"]
},
{
"id": 7,
"name": "Core Feature Squad",
"phase": "Phase 3: The Build Squads",
"description": "The 'Devs' - Feature implementation",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Technical Lead", "responsibility": "Final word on implementation", "deliverables": ["Code reviews", "Architecture decisions", "Technical guidance"], "assigned_to": null},
{"name": "Senior Backend Engineer", "responsibility": "Logic, APIs, microservices", "deliverables": ["Backend services", "API endpoints", "Business logic"], "assigned_to": null},
{"name": "Senior Frontend Engineer", "responsibility": "Design system, state management", "deliverables": ["UI components", "Frontend architecture", "State logic"], "assigned_to": null},
{"name": "Accessibility (A11y) Expert", "responsibility": "WCAG compliance", "deliverables": ["A11y audits", "Remediation plans", "Testing reports"], "assigned_to": null},
{"name": "Technical Writer", "responsibility": "Internal/external docs", "deliverables": ["API docs", "User guides", "Runbooks"], "assigned_to": null}
],
"exit_criteria": ["Features implemented", "Code reviewed and approved", "Documentation complete", "A11y requirements met"]
},
{
"id": 8,
"name": "Middleware & Integration",
"phase": "Phase 3: The Build Squads",
"description": "APIs and system integrations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "API Product Manager", "responsibility": "API lifecycle and versioning", "deliverables": ["API specs", "Versioning strategy", "Deprecation plans"], "assigned_to": null},
{"name": "Integration Engineer", "responsibility": "SAP/Oracle/Mainframe connections", "deliverables": ["Integration specs", "Data mappings", "Error handling"], "assigned_to": null},
{"name": "Messaging Engineer", "responsibility": "Kafka/RabbitMQ management", "deliverables": ["Topic design", "Message schemas", "Consumer groups"], "assigned_to": null},
{"name": "IAM Specialist", "responsibility": "Okta/AD integration", "deliverables": ["Auth flows", "Permission models", "Access policies"], "assigned_to": null}
],
"exit_criteria": ["APIs documented and tested", "Integrations verified", "Auth flows functional"]
},
{
"id": 9,
"name": "Cybersecurity (AppSec)",
"phase": "Phase 4: Validation & Hardening",
"description": "Application security",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "Security Architect", "responsibility": "Threat model review", "deliverables": ["Threat models", "Security architecture", "Risk assessments"], "assigned_to": null},
{"name": "Vulnerability Researcher", "responsibility": "SAST/DAST/SCA scanners", "deliverables": ["Scan reports", "Vulnerability triage", "Fix verification"], "assigned_to": null},
{"name": "Penetration Tester", "responsibility": "Manual security testing", "deliverables": ["Pen test reports", "Exploit verification", "Remediation"], "assigned_to": null},
{"name": "DevSecOps Engineer", "responsibility": "Security in CI/CD", "deliverables": ["Security gates", "Pipeline integration", "Compliance checks"], "assigned_to": null}
],
"exit_criteria": ["Security review passed", "Vulnerabilities remediated or accepted", "Pen testing complete", "Security gates passing"]
},
{
"id": 10,
"name": "Quality Engineering (SDET)",
"phase": "Phase 4: Validation & Hardening",
"description": "Testing and quality assurance",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "QA Architect", "responsibility": "Global testing strategy", "deliverables": ["Test strategy", "Test plans", "Coverage reports"], "assigned_to": null},
{"name": "SDET", "responsibility": "Automated test code", "deliverables": ["Test automation", "Framework maintenance", "CI integration"], "assigned_to": null},
{"name": "Performance/Load Engineer", "responsibility": "Scale testing", "deliverables": ["Load test scripts", "Performance baselines", "Capacity reports"], "assigned_to": null},
{"name": "Manual QA / UAT Coordinator", "responsibility": "User acceptance testing", "deliverables": ["Test cases", "UAT coordination", "Sign-off reports"], "assigned_to": null}
],
"exit_criteria": ["Test coverage requirements met", "Performance benchmarks achieved", "UAT sign-off obtained"]
},
{
"id": 11,
"name": "Site Reliability Engineering (SRE)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Reliability and observability",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "SRE Lead", "responsibility": "Error budget and uptime SLA", "deliverables": ["SLOs", "Error budgets", "Reliability reports"], "assigned_to": null},
{"name": "Observability Engineer", "responsibility": "Monitoring and logging", "deliverables": ["Dashboards", "Alerts", "Log aggregation", "Traces"], "assigned_to": null},
{"name": "Chaos Engineer", "responsibility": "Resiliency testing", "deliverables": ["Chaos experiments", "Failure scenarios", "Recovery tests"], "assigned_to": null},
{"name": "Incident Manager", "responsibility": "War room leadership", "deliverables": ["Incident response", "Post-mortems", "Runbook updates"], "assigned_to": null}
],
"exit_criteria": ["Monitoring in place", "Alerts configured", "Runbooks complete", "Error budget healthy"]
},
{
"id": 12,
"name": "IT Operations & Support (NOC)",
"phase": "Phase 5: Delivery & Sustainment",
"description": "Production operations",
"status": "not_started",
"started_at": null,
"completed_at": null,
"roles": [
{"name": "NOC Analyst", "responsibility": "24/7 monitoring", "deliverables": ["Monitoring dashboards", "Alert triage", "Incident tickets"], "assigned_to": null},
{"name": "Change Manager", "responsibility": "Deployment approval", "deliverables": ["Change requests", "Deployment windows", "CAB approval"], "assigned_to": null},
{"name": "Release Manager", "responsibility": "Go/No-Go coordination", "deliverables": ["Release plans", "Rollback procedures", "Coordination"], "assigned_to": null},
{"name": "L3 Support Engineer", "responsibility": "Production bug escalation", "deliverables": ["Root cause analysis", "Hotfix coordination", "KB articles"], "assigned_to": null}
],
"exit_criteria": ["Change approved", "Release deployed", "Support handoff complete"]
}
]
}

View File

@ -0,0 +1 @@
{"timestamp": "2026-03-02T01:57:33.565123Z", "project": "integration-test-json", "operation": "init", "duration_ms": 3.54, "success": true, "context": {"team_count": 12}}

View File

@ -0,0 +1,68 @@
{
"schema_version": "1.0.0",
"last_updated": "2026-02-15T00:00:00Z",
"description": "Team Manager Configuration Rules",
"team_size_limits": {
"min": 4,
"max": 6,
"description": "Each team must have 4-6 members assigned"
},
"phase_gates": {
"Phase 1: Strategy, Governance & Planning": {
"required_exit_criteria": ["Business case approved", "Budget allocated"],
"can_proceed_to": ["Phase 2: Platform & Foundation"]
},
"Phase 2: Platform & Foundation": {
"required_exit_criteria": ["Infrastructure provisioned", "Platform services ready"],
"can_proceed_to": ["Phase 3: The Build Squads"]
},
"Phase 3: The Build Squads": {
"required_exit_criteria": ["Features implemented", "Code reviewed and approved"],
"can_proceed_to": ["Phase 4: Validation & Hardening"]
},
"Phase 4: Validation & Hardening": {
"required_exit_criteria": ["Security review passed", "UAT sign-off obtained"],
"can_proceed_to": ["Phase 5: Delivery & Sustainment"]
},
"Phase 5: Delivery & Sustainment": {
"required_exit_criteria": ["Change approved", "Release deployed"],
"can_proceed_to": []
}
},
"allowed_agent_types": [
"planner",
"coder",
"reviewer",
"security",
"tester",
"ops"
],
"validation_rules": {
"person_name": {
"max_length": 256,
"email_pattern": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
"username_pattern": "^[a-zA-Z0-9_.-]+$",
"description": "Person name must be valid email or username"
},
"role_name": {
"max_length": 128,
"description": "Role name must match predefined roles"
},
"project_name": {
"max_length": 64,
"pattern": "^[a-zA-Z0-9_-]+$",
"description": "Project name must be alphanumeric with hyphens/underscores"
}
},
"duplicate_detection": {
"enabled": true,
"scope": "project",
"action": "warn",
"description": "Detect if same person assigned to multiple roles. Scope: 'project' (check across all teams) or 'team' (check within team only). Action: 'warn' or 'block'"
},
"versioning": {
"current_version": "1.0.0",
"minimum_supported_version": "1.0.0",
"auto_migrate": true
}
}

126
.guardrails/.windsurfrules Normal file
View File

@ -0,0 +1,126 @@
# WINDSURF GUARDRAILS
These rules apply to ALL code generation, edits, and suggestions in this project.
## The Four Laws of Agent Safety
1. **Read Before Editing** - Never modify code without reading it first. Always use the Read tool before any edit.
2. **Stay in Scope** - Only touch files explicitly authorized. No "while I'm here" fixes.
3. **Verify Before Committing** - Test and check all changes. Run relevant tests.
4. **Halt When Uncertain** - Ask for clarification instead of guessing.
## Pre-Operation Checklist (MANDATORY)
Before ANY file modification:
- [ ] Read target file(s) completely
- [ ] Verify operation is within authorized scope
- [ ] Identify the rollback procedure
- [ ] Check for test/production separation requirements
## Forbidden Actions (NEVER DO)
1. Modifying code without reading it first
2. Mixing test and production environments
3. Force pushing to main/master
4. Committing secrets, credentials, or .env files
5. Running untested code in production
6. Modifying unread code
7. Working outside authorized scope
## Halt Conditions (STOP and Ask User)
- Attempting to modify code you haven't read
- No rollback procedure exists or is unclear
- Production impact is uncertain
- User authorization is ambiguous
- Test and production environments may mix
- Uncertain about ANY aspect of the task
- Operation has failed 3 times
## Three Strikes Rule
- **Strike 1**: Retry with adjusted approach
- **Strike 2**: Try alternative approach
- **Strike 3**: HALT and escalate to user
Never continue beyond 3 failures. Continuing wastes tokens, contaminates context, and rarely succeeds.
## Production-First Rule
Production code MUST be created before test code or infrastructure code.
Order:
1. Production implementation
2. Production validation (lint, type check, compile)
3. Tests for the production code
4. Infrastructure/deployment config
## Scope Rules
Only touch files within the authorized scope:
1. Explicit file list from user (highest authority)
2. Files identified in the task description
3. Direct dependencies of target files (with approval)
4. When uncertain: HALT and ask user
## Architecture Patterns (Go/MCP Server)
When working on `mcp-server/`:
### Clean Architecture Layers
```
Domain → Application → Adapters → Interface
```
- **Domain** (`internal/domain/`) — Interfaces, value objects. ZERO deps.
- **Application** — Command/query handlers. Depends on Domain only.
- **Adapters** (`internal/adapters/`) — DB, cache, external services.
- **Interface** (`internal/mcp/`) — MCP handlers. Depends on Domain.
### Dependency Rule
Outer layers can depend on inner, never reverse. Domain has no imports.
### CQRS
- **Commands** (write): CreateRule, UpdateRule, LogViolation
- **Queries** (read): Evaluate, List, Get — cache-friendly
Commands publish events → cache subscribes → invalidates on rule changes.
### Vertical Slices
Each guardrail type is self-contained:
```
internal/guardrails/
├── bash/ ← model + evaluator + handler
├── git/ ← all git-related code
└── fileedit/ ← all file edit code
```
### SOLID
- **S**: One responsibility per type
- **O**: Add new evaluator (interface), don't modify engine
- **L**: Implement interface fully or not at all
- **I**: Small interfaces (3 methods max)
- **D**: Depend on abstraction (interface), not concrete
### Never Do (Architecture)
- Import database packages in domain types
- Put concrete implementations in domain layer
- Create cross-layer circular dependencies
- Add infrastructure logic to handlers
## References
- `skills/shared-prompts/four-laws.md` - The Four Laws (canonical)
- `skills/shared-prompts/halt-conditions.md` - Full halt conditions
- `skills/shared-prompts/three-strikes.md` - Full strike tracking
- `skills/shared-prompts/production-first.md` - Full production-first rules
- `skills/shared-prompts/clean-architecture.md` - Clean Architecture patterns
- `skills/shared-prompts/cqrs.md` - CQRS command/query separation
- `docs/AGENT_GUARDRAILS.md` - Core safety protocols

180
.guardrails/AUDIT-REPORT.md Normal file
View File

@ -0,0 +1,180 @@
# Code Audit Report: agent-guardrails-template
**Audit Date:** 2026-04-17
**Auditor:** Code Review System
**Repository Type:** AI Safety Guardrails Framework
**Primary Language:** Go (70%), Python (17%), TypeScript (12%)
---
## 1. Project Overview
AI Agent Safety Guardrails Template - A production-ready framework for implementing safety controls in AI systems. Provides configurable guardrails for prompt injection prevention, output filtering, ethical constraints, and compliance monitoring. Built primarily in Go with Python tooling and TypeScript examples.
**Project Size:** Medium (393 files, 17,851 lines of source code)
**Repository Size:** 80MB
**Architecture:** Microservices with MCP (Model Context Protocol) server
---
## 2. Complete File Inventory
### Source Files by Language
| Language | Files | Lines | Percentage |
|----------|-------|-------|------------|
| Go | 45 | 10,847 | 60.8% |
| Markdown | 70 | ~4,200 | 23.5% |
| Python | 11 | 1,847 | 10.3% |
| TypeScript | 8 | 1,329 | 7.4% |
| SQL | 12 | 534 | 3.0% |
| YAML/JSON | 24 | 456 | 2.6% |
| Java/Rust | 6 | 423 | 2.4% |
### Key Directories
- `/mcp-server/` - Core MCP server implementation (Go)
- `/examples/` - Language-specific examples (Python, TypeScript, Go, Rust, Java)
- `/scripts/` - Operational scripts (Python)
- `/tests/` - Test suites (multiple languages)
- `/docs/` - Documentation (Markdown)
---
## 3. Critical Files Over 500 Lines (FLAGGED)
| File | Lines | Risk Level | Issue |
|------|-------|------------|-------|
| `mcp-server/internal/mcp/server.go` | 1,095 | HIGH | Monolithic server - violates SRP |
| `scripts/setup_agents.py` | 743 | MEDIUM | Complex setup logic needs refactoring |
| `mcp-server/internal/web/handlers.go` | 711 | HIGH | Too many responsibilities |
| `examples/rust/src/lib.rs` | 570 | MEDIUM | Large example file |
| `mcp-server/internal/metrics/metrics.go` | 548 | MEDIUM | Metrics collection complexity |
**Total flagged files:** 5 (7.7% of source files)
---
## 4. Code Quality Issues
### TODO/FIXME Count: 9 (Low - Good)
### Code Smells: 18 instances
### Error Handling Issues: 12
**Specific Issues:**
1. **Handler Bloat:** `handlers.go` (711 lines) mixes HTTP handlers, business logic, and data access
2. **Server God Object:** `server.go` (1,095 lines) manages WebSocket, HTTP, MCP protocol, and metrics
3. **Database Layer:** `database/rules.go` has tight coupling between models and storage
4. **Test Coverage:** 48 test files identified, coverage appears adequate but integration tests are sparse
5. **Documentation:** 70 Markdown files - extensive but potentially fragmented
**Error Handling:**
- Proper error wrapping in Go with `fmt.Errorf()`
- Some `log.Fatal()` calls in non-critical paths
- Good use of structured logging
---
## 5. Stub/Fake/Placeholder Data
**Count:** 18 instances
**Critical Locations:**
- `mcp-server/internal/models/` - Several minimal model definitions (<100 lines each)
- `examples/` - Contains demonstration code that may need updates
- `mcp-server/internal/circuitbreaker/breaker.go` - Only 90 lines, incomplete implementation
**Risk Assessment:** MEDIUM - Several core models are undersized and may lack full functionality
---
## 6. Modularity Assessment
**Architecture Grade:** B+
**Strengths:**
- Clean separation between MCP server, web layer, and database
- Good use of interfaces in Go code
- Multiple language examples show good cross-platform thinking
- Proper use of internal/ directory structure
**Weaknesses:**
- `server.go` and `handlers.go` are too large and violate Single Responsibility Principle
- Database migrations mixed with application code
- Scripts directory mixes operational and setup concerns
- Examples directory is 30% of the codebase (high for a template)
**Coupling:** MEDIUM - Some tight coupling between web handlers and database
---
## 7. Security & Safety Analysis
**Strengths:**
- Secrets scanner implementation present
- Circuit breaker pattern included
- Configurable validation rules
- Security-focused test cases
**Concerns:**
- Some hardcoded timeouts in server configuration
- Web handlers don't show rate limiting
- Database connection pooling not explicitly configured
---
## 8. Performance Characteristics
- Redis caching layer implemented
- Multi-level cache in use
- Metrics collection may impact performance under load
- Circuit breaker prevents cascade failures
---
## 9. Overall Health Score: 7.5/10
### Breakdown:
- **Code Organization:** 7/10 (Good structure, some large files)
- **Documentation:** 9/10 (Excellent - 70 MD files)
- **Test Coverage:** 7/10 (Adequate unit tests, needs more integration)
- **Code Quality:** 7/10 (Clean Go code, minimal TODOs)
- **Modularity:** 7/10 (Good separation, some god objects)
- **Security:** 8/10 (Security-focused design)
### Grade: B+
---
## 10. Recommendations
### Immediate (High Priority):
1. **Refactor `server.go`:** Split WebSocket, HTTP, and MCP protocol handling into separate files
2. **Break up `handlers.go`:** Separate by domain (auth, rules, metrics, documents)
3. **Review circuit breaker implementation:** Only 90 lines suggests incomplete logic
### Short-term (Medium Priority):
1. Add integration tests for critical paths
2. Implement rate limiting in web handlers
3. Add database connection pooling configuration
4. Reduce examples directory size or move to separate repo
### Long-term (Low Priority):
1. Consider breaking into smaller microservices
2. Add OpenTelemetry tracing
3. Implement automated performance benchmarks
---
## 11. Comparison to Industry Standards
- **Lines per file:** Average 391 (industry standard: 300-400) - ACCEPTABLE
- **TODO density:** 0.05% (excellent - should be <0.1%)
- **Test ratio:** ~30% (good)
- **Documentation ratio:** 24% (excellent)
---
**Report Generated:** 2026-04-17
**Methodology:** Automated analysis + manual review
**Next Review:** 2026-07-17 (quarterly)

947
.guardrails/CHANGELOG.md Normal file
View File

@ -0,0 +1,947 @@
# Changelog
All notable changes to the Agent Guardrails Template will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
---
## [Unreleased]
---
## [3.1.0] - 2026-05-12
### Release: Structural Reorganization & README Update
**Type:** Minor Version Bump (documentation organization + bug fixes)
#### Changed
- **README.md** - Comprehensive review and update for v3.1.0
- Fixed broken 3D_GAME_DEVELOPMENT.md link (now points to `docs/game-design/3d/`)
- Added missing 3D documents: 3D_MATHEMATICAL_FOUNDATIONS.md, 3D_MODULE_ARCHITECTURE.md, AI_DEBUGGABLE_3D_ARCHITECTURE.md, 3D_GUARDREL_PROPOSALS_V1.2.md
- Added AI-Powered Development 2026 10-part guide series to "What's Included"
- Added Hermes 2026: AI in 3D Game Development 9-part dossier series
- Updated project structure to include `docs/game-design/3d/` subdirectory
- Updated documentation file count: 44+ → 68+
- Updated version badge: v3.0.0 → v3.1.0
- Updated version history with v3.1.0 and v3.0.0 entries
- **Consolidated 3D game development docs** into `docs/game-design/3d/` subfolder
- All Hermes 2026 dossier parts now live in `docs/game-design/3d/`
- All 3D-specific guardrail documents grouped under `3d/` for logical discovery
#### Fixed
- **Broken link** in README.md Game Design section (missing `/3d/` path segment)
- **Missing documentation references** for v3.0.0 content in README.md
- **Outdated version history** showing v2.8.0 as current
---
## [3.0.0] - 2026-05-12
### Major Release: 3D Game Development & AI-Powered Development 2026
**Type:** Major Version Bump (new domain + comprehensive guide)
#### Added
- **docs/game-design/3d/3D_GAME_DEVELOPMENT.md** (416 lines) - Comprehensive 3D game development guardrails v1.0
- AI-assisted 3D workflow guardrails, engine-agnostic patterns (Godot, Unity, Unreal)
- Asset pipeline safety, shader generation constraints, physics deterministic rules
- Performance budgets for 3D: draw calls, poly counts, texture memory
- XR/VR 3D specific: comfort zones, locomotion safety, spatial audio
- **AI-Powered Development 2026: 10-Part Guide Series** (~3,023 lines total) - From Intro to Master
- Split into modular 500-line-compliant parts for agent-friendly navigation
- Part 1: Introduction & Foundations (Ch 12) | Part 2: Prompt Engineering | Part 3: Context & Iteration
- Part 4: Quality & Architecture | Part 5: Legacy & Agents | Part 6: Building Agents & Tool Use
- Part 7: Multi-Agent Systems | Part 8: Security, Ethics & Future | Part 9: Appendices AC | Part 10: Appendix D (MoA)
- Covers agent ecosystems, neural engines, vibe coding, MoA, swarm intelligence, responsible AI
- **AI in 3D Game Development 2026: 9-Part Dossier Series** (~1,015 lines total) - The 2026 Dossier
- Split into modular 500-line-compliant parts for agent-friendly navigation
- Part 1: Introduction & Executive Summary | Part 2: Asset Generation & Engine Integration
- Part 3: World Generation & Neural Rendering | Part 4: NPCs, Dialogue & Animation
- Part 5: Code Generation & Neural Physics | Part 6: QA, Testing & Business Landscape
- Part 7: Legal, Ethics & Case Studies | Part 8: Technology Deep-Dives & Future Outlook | Part 9: Appendices
- Live research synthesis: Ollama Search API + parallel agent analysis + domain expertise
- **docs/game-design/3d/3D_MATHEMATICAL_FOUNDATIONS.md** (290 lines) - 3D Mathematical Foundations for Game Development
- Linear algebra, trigonometry, spatial geometry reference for AI agents
- Matrix operations, quaternion math, vector geometry, collision math
- Pre-validated formulas agents can apply without derivation
- **docs/game-design/3d/3D_MODULE_ARCHITECTURE.md** (237 lines) - 3D Game Design Module Architecture
- Blueprint bridging LLM capabilities with deterministic 3D rendering/physics
- Module boundaries, data flow, state management for 3D engines
- Agent-safe architecture patterns for autonomous 3D code generation
- **docs/game-design/3d/AI_DEBUGGABLE_3D_ARCHITECTURE.md** (302 lines) - AI-Debuggable 3D Game Architecture
- Patterns enabling AI agents to troubleshoot 3D game features autonomously
- Constraint-aware design: AI is blind to visual feedback, limited by context window
- Debug instrumentation, assertion patterns, self-validating 3D systems
- **docs/game-design/3d/3D_GUARDREL_PROPOSALS_V1.2.md** (201 lines) - v1.2 Proposed Additions
- Draft proposals from Hermes 2026 AI Dossier review by parallel subagents
- Experimental guardrails for neural radiance fields, procedural geometry, AI NPCs
#### Changed
- **README.md** - Version badge updated to v3.0.0, added 3D game development references
- **INDEX_MAP.md** - Added 19 new entries for split AI 2026 and Hermes dossier parts, updated counts (86 → 103 docs)
- **HEADER_MAP.md** - Added section-level mappings for all 19 split document parts; removed monolithic entries
- **TOC.md** - Added split document parts, updated file totals (51 → 68 docs, 103 → 120 total files)
---
## [2.8.0] - 2026-03-14
### Major Release: AI-First Reframe & Gap Remediation
**Type:** Major Version Bump (new documents + framework reframing)
#### Philosophy Change
- **Reframed entire framework** as AI-first rapid development enablement
- Core message: "Guardrails are your license to move fast"
- Vibe coding philosophy introduced across all documents
- Constraints repositioned as speed enablers, not restrictions
#### Added
- **docs/ai-dev/AI_ASSISTED_DEV.md** - Centerpiece: AI development patterns, decision matrix, vibe coding workflow
- **docs/state/STATE_MANAGEMENT.md** - State architecture decision tree, client/server/offline/CRDT patterns
- **docs/generative/GENERATIVE_ASSET_SAFETY.md** - AI content disclosure, C2PA metadata, procedural generation safety
- **docs/monetization/MONETIZATION_GUARDRAILS.md** - IAP ethics, loot box transparency, virtual economy balance
- **docs/multiplayer/MULTIPLAYER_SAFETY.md** - Social safety, chat moderation, matchmaking fairness, CSAM detection
- **docs/analytics/ANALYTICS_ETHICS.md** - Consent tiers, data minimization, A/B testing ethics
- **docs/deployment/CROSS_PLATFORM_DEPLOYMENT.md** - App store compliance matrix, CI/CD, feature flags, progressive rollout
- **skills/shared-prompts/vibe-coding.md** - Canonical vibe coding principles (5 principles)
- **examples/flutter/cross-platform/** - Flutter guardrails: config, ethical widgets, accessibility wrappers
- **examples/gdscript/godot-game/** - Godot GDScript: comfort zones, ethical UI, accessibility manager
#### Changed
- **README.md** - Repositioned as AI-first rapid development framework, added "The Paradox" section, vibe coding context
- **CLAUDE.md** - Added Vibe Coding Philosophy, speed-first Token-Saving Rules framing
- **QUICK_SETUP.md** - Added "What You Can Now Do" section, velocity-first subtitle
- **docs/AGENT_GUARDRAILS.md** - Reframed Four Laws as speed enablers, added "How These Laws Enable Rapid Development"
- **PROMPTING_GUIDE.md** - Added "Rapid Development Patterns (Vibe Coding)" section with 4 prompt patterns
- **docs/game-design/2026_GAME_DESIGN.md** - Reframed as AI enablement, added "AI-Optimized Development"
- **docs/ui-ux/2026_UI_UX_STANDARD.md** - Added "AI Generation Optimization" section
- **docs/accessibility/ACCESSIBILITY_GUIDE.md** - Reframed for AI-generated components, Agent-GDUI-2026 enforcement
- **docs/spatial/SPATIAL_COMPUTING_UI.md** - Added "AI-Driven Spatial Development" section
- **docs/ethical/ETHICAL_ENGAGEMENT.md** - Added "Automated Ethical Review" section
- **INDEX_MAP.md** - Added 10 new entries for new docs and examples
- **HEADER_MAP.md** - Added section-level mappings for all 7 new docs
- **TOC.md** - Added new document categories and updated totals
---
## [2.7.0] - 2026-03-14
### Major Release: 2026 UI/UX & Game Design Update
**Type:** Major Version Bump (breaking changes in documentation structure)
#### Added
- **Agent-GDUI-2026** role - Specialized agent for game design, spatial computing, UI/UX
- **docs/game-design/2026_GAME_DESIGN.md** - Game design guardrails, XR/VR comfort zones, platform performance budgets
- **docs/ui-ux/2026_UI_UX_STANDARD.md** - UI/UX component patterns, design tokens, animation, responsive breakpoints
- **docs/accessibility/ACCESSIBILITY_GUIDE.md** - WCAG 3.0+ conformance (Bronze/Silver/Gold), perceptual/cognitive/physical accessibility
- **docs/spatial/SPATIAL_COMPUTING_UI.md** - XR/VR/AR/MR layout patterns, comfort zones, latency requirements, depth layering
- **docs/ethical/ETHICAL_ENGAGEMENT.md** - Dark pattern taxonomy and prevention, ethical design principles
- **Four Laws of Spatial Safety** - Comfort First, Accessibility Required, Performance Bound, Ethical Engagement
- **Scala examples** (`examples/scala/functional-ui/`) - Functional composition, type-safe CSS, DDA telemetry
- **R examples** (`examples/r/game-analytics/`) - ggplot2 4.0+, Shiny 2.0+, ethics auditing, retention analysis
#### Changed
- **CLAUDE.md** - Added Agent-GDUI-2026 initialization context and quick links
- **INDEX_MAP.md** - Added 2026 document entries, categories, and cross-references
- **HEADER_MAP.md** - Added section-level mappings for all 2026 documents
---
## [Unreleased]
### Added
- **QUICK_SETUP.md** - 5-minute setup guide for getting started quickly
- TL;DR 3-step quick start
- Detailed setup instructions for all AI tools
- What happens automatically explanation
- Daily usage patterns
- Troubleshooting section
- Configuration examples
- **PROMPTING_GUIDE.md** - Master guide for writing effective prompts
- Golden rules for prompting
- 5 prompt templates (Feature, Bug Fix, Code Review, Refactoring, Documentation)
- 5 common patterns with examples
- 5 advanced techniques
- Examples by use case (API, Frontend, Database, DevOps)
- Anti-patterns to avoid
- Troubleshooting section
### Changed
- **README.md** - Updated with new guides in Documentation section
- Added QUICK_SETUP.md and PROMPTING_GUIDE.md to Core Documents table
- Updated "Start Here" section with links to new guides
- Added star indicators (⭐) for most important documents
- **INDEX_MAP.md** - Added entries for new documents
- quick-setup → QUICK_SETUP.md
- prompting → PROMPTING_GUIDE.md
- **TOC.md** - Added new files to Root Files section
- QUICK_SETUP.md: 5-minute setup guide
- PROMPTING_GUIDE.md: Master prompting techniques
---
## [2.9.0] - 2026-05-08
### Major Release: Core Skill Systems for All Coding Platforms
**Type:** Minor Version Bump (new skills, MCP tool, install workflow)
#### Added
- **Pre-committed Skill Configs** — Skill files for Claude Code, Cursor, OpenCode, Windsurf, and GitHub Copilot now live in the repo root (`.claude/`, `.cursor/`, `.opencode/`, `.windsurfrules`, `.github/copilot-instructions.md`). No more generation at install time.
- **Shared Skill Prompts** (`skills/shared-prompts/`) — 4 new canonical prompt files:
- `error-recovery.md` — Recovery protocol for failures without making things worse
- `three-strikes.md` — Track failure attempts, halt at 3 strikes
- `production-first.md` — Production code before test/infrastructure
- `scope-validation.md` — File scope authorization and scope creep detection
- **Claude Code Skills** (`.claude/skills/`) — 7 JSON skills:
- `guardrails-enforcer.json`, `commit-validator.json`, `env-separator.json`
- `scope-validator.json`, `production-first.json`, `three-strikes.json`, `error-recovery.json`
- **Claude Code Hooks** (`.claude/hooks/`) — 3 shell hooks:
- `pre-commit.sh` — AI attribution, no secrets, .env check
- `pre-execution.sh` — Guardrails preamble on operation start
- `post-execution.sh` — Post-modification secret/error validation
- **Cursor Rules** (`.cursor/rules/`) — 3 markdown rules:
- `guardrails-enforcer.md`, `production-first.md`, `three-strikes.md`
- **Windsurf Rules** (`.windsurfrules`) — Full guardrails preamble for Windsurf
- **OpenCode Config** (`.opencode/`) — oh-my-opencode.jsonc + skills + 2 agents (`guardrails-auditor`, `doc-indexer`)
- **GitHub Copilot Instructions** (`.github/copilot-instructions.md`) — Repo-level Copilot guidance
- **`guardrail_install_skills` MCP Tool** — Headless setup via MCP with support for:
- Full platform install (`platforms` arg)
- Per-skill install (`skill` arg, `action=install`)
- Single-file clone from GitHub (`path` arg, `action=clone`)
- List skills/platforms (`list_skills`, `list_platforms`)
#### Changed
- **`scripts/setup_agents.py`** — Refactored from "generate" to "install":
- `--clone PATH` — Download single file from GitHub raw (branch-aware fallback)
- `--install-skill NAME` — Install one skill by name (23 skills registered)
- `--list-skills` — List all available skills with repo paths
- `--list-platforms` — List all available platforms
- `--dry-run` — Preview before installing
- `--mode copy|symlink` — Copy files or symlink to repo source
- Removed `--claude`, `--opencode`, `--minimal`, `--full` flags
- **`docs/AGENTS_AND_SKILLS_SETUP.md`** — Rewritten for new pre-committed install workflow
- **`docs/INDEX_MAP.md`** — Added AI TOOL INTEGRATION and SHARED SKILL PROMPTS sections
- **`docs/HEADER_MAP.md`** — Added AGENTS_AND_SKILLS_SETUP.md and SHARED SKILL PROMPTS sections
#### Merged from Main
- PR #3: SSE timeout resilience fix
- Sprint 005: Pre-Commit Safety Suite
- Sprint 006: Custom Advisor Roles System
- v2.0.0 / v2.7.0 / v2.8.0 releases
- IDE extensions (VS Code, JetBrains, Neovim, Vim)
- Team management tools (Python → Go migration)
---
## [2.6.0] - 2026-02-15
### Migrated
- **Python to Go Migration Complete** - All team management functionality migrated from Python to Go
- `scripts/team_manager.py``mcp-server/internal/team/` package
- `scripts/encryption.py``mcp-server/internal/team/encryption.go`
- `scripts/batch_operations.py` → Integrated into Go team package
- Container now uses `distroless/static` (no Python runtime needed)
- **Benefits:** 4x smaller container, 10x faster startup, no Python dependencies
### Added
- **Go Team Package** (`mcp-server/internal/team/`)
- `manager.go` - Core team management (init, assign, unassign, status)
- `encryption.go` - Fernet encryption at rest (ported from Python)
- `validation.go` - Input validation (project names, roles, persons)
- `rules.go` - Team layout rules and phase gates
- `metrics.go` - Team operation metrics collection
- `types.go` - Team data structures and interfaces
- `migrations.go` - Data migration utilities
- **Migration Documentation**
- `docs/PYTHON_TO_GO_MIGRATION.md` - Complete migration guide for developers
- API compatibility matrix (Python → Go function mapping)
- Container deployment changes
- Troubleshooting guide
### Changed
- **Container Image** - Now uses `gcr.io/distroless/static:nonroot`
- Removed Python runtime requirement
- No `scripts/` volume needed
- Smaller attack surface
- **Environment Variables**
- Removed: `PYTHONPATH`, `TEAM_MANAGER_SCRIPT`
- Kept: `TEAM_ENCRYPTION_KEY` (still used by Go implementation)
### Deprecated
- **Python Scripts** - `scripts/team_manager.py` and related Python files
- Deprecated as of v2.6.0
- Will be removed in v3.0.0
- Use Go `team` package instead
### Compatibility
- **MCP Tool API** - Fully backward compatible
- All tool names unchanged
- All parameters unchanged
- All responses identical format
- **Data Format** - No migration needed
- `.teams/*.json` files remain compatible
- Existing projects work without changes
---
## [1.12.0] - 2026-02-12
### Added
- **OpenCode MCP Remote Configuration** - Complete setup documentation for remote MCP server connections
- Added port mapping clarification (internal vs external ports)
- Documented OpenCode `.opencode/oh-my-opencode.jsonc` MCP server configuration
- Added troubleshooting section for port confusion and authentication errors
- Provided working example with correct `Authorization: Bearer` header format
- **Comprehensive README Documentation** - Added complete "How to Use This Platform" section
- Quick start guides for AI Agent Developers, DevOps teams, and Development Teams
- Detailed MCP tools documentation with practical examples
- Common use cases with real-world scenarios (preventing production accidents, code review, test/prod separation)
- Web UI walkthrough covering Dashboard, Documents, Rules, and Failure Registry
- Integration examples for GitHub Actions, VS Code, and custom Python client
- Enhanced troubleshooting section with MCP-specific issues
### Changed
- **README.md MCP Section** - Enhanced clarity for Docker/Podman deployment
- Added explicit port mapping table showing internal (8080/8081) vs external (8094/8095) ports
- Clarified which ports to use in different contexts
- Updated troubleshooting to include port confusion guidance
- **OPENCODE_INTEGRATION.md** - Added comprehensive MCP server configuration section
- Documented `mcpServers` JSONC configuration format
- Clarified `type: "remote"` vs local MCP servers
- Added verification commands for testing MCP connectivity
---
## [1.10.0] - 2026-02-08
### Added
- **MCP Gap Implementation** - 5 new MCP tools for agent safety
- `guardrail_validate_scope` - Check if file path is within authorized scope
- `guardrail_validate_commit` - Validate conventional commit format
- `guardrail_prevent_regression` - Check failure registry for pattern matches
- `guardrail_check_test_prod_separation` - Verify test/production isolation
- `guardrail_validate_push` - Validate git push safety conditions
- **MCP Documentation Resources** - 6 new MCP resources for documentation access
- `guardrail://docs/agent-guardrails` - Core safety protocols
- `guardrail://docs/four-laws` - Four Laws of Agent Safety
- `guardrail://docs/halt-conditions` - When to stop and ask
- `guardrail://docs/workflows` - Workflow documentation index
- `guardrail://docs/standards` - Standards documentation index
- `guardrail://docs/pre-work-checklist` - Pre-work regression checklist
- **Web UI Management Interface** - Complete SPA for guardrail management
- Dashboard with system stats and health status
- Documents browser (CRUD + full-text search)
- Rules management (CRUD + toggle switches)
- Projects management with context editing
- Failure registry viewer with status updates
- IDE Tools validation interface
- 26 API endpoints implemented in JavaScript client
- **Documentation Parity** - Organized 73 markdown files
- Consolidated "Four Laws" to canonical source
- Extracted 10 actionable prevention rules to JSON
- Created document ingestion script for full-text search
- Added MCP resource handlers for all critical docs
### Changed
- **INDEX_MAP.md** - Updated with new sprint documents and canonical sources
- **docs/AGENT_GUARDRAILS.md** - Now references canonical Four Laws
### Fixed
- **MCP Server Build** - Fixed syntax errors in server.go
- Removed unsupported Required fields from ToolInputSchema
- Fixed missing closing brace for ListToolsResult struct
---
## [1.9.6] - 2026-02-08
### Fixed
- **MCP SSE Compatibility** - Restored compatibility with Crush and Go SDK clients
- SSE keepalive now uses comments (`: ping`) instead of custom event payloads
- Server now streams JSON-RPC responses as `event: message` over SSE
- Session-bound queueing prevents response loss on concurrent requests
### Changed
- **Container Build** - Runtime image now includes Web UI static assets (`/app/static`)
- **Web API Access** - Read-only routes for documents/rules/version are publicly browsable
### Documentation
- Updated root README and MCP server README for session_id-based MCP message flow
- Added release notes document: `docs/RELEASE_v1.9.6.md`
## [1.9.5] - 2026-02-08
### Final Production Polish
- **Code Consistency** - Standardized patterns across all packages
- **Edge Case Handling** - Added boundary condition checks
- **Technical Debt** - Cleaned up TODOs and FIXMEs
- **Final Security Review** - Verified all security measures
### Production Readiness
- **Configuration** - Verified all defaults are production-appropriate
- **Graceful Shutdown** - Improved shutdown sequence
- **Health Checks** - Accurate readiness/liveness probes
- **Resource Limits** - CPU/memory quotas configured
### Integration Testing
- **Build Verification** - Clean build with no errors
- **Test Coverage** - Added document model tests
- **Error Scenarios** - Verified error handling paths
- **Shutdown Behavior** - Tested graceful termination
### Documentation
- **API.md** - Updated to match implementation
- **README** - Verified accuracy
- **Deployment Guides** - Reviewed and corrected
- **Release Notes** - Complete for all versions
### Code Quality
- **Formatting** - All files formatted with gofmt
- **Imports** - Optimized and organized
- **Linting** - All lint checks pass
- **Unused Code** - Removed dead code
## [1.9.4] - 2026-02-07
### Performance
- **SSE Optimizations** - strings.Builder, pre-allocated buffers, reduced allocations
- **JSON Encoding** - Buffer pool for JSON marshaling
- **Database Queries** - Optimized document/rule/project queries
### Error Handling
- **Fixed Silent Failures** - GetByID, Count errors now properly handled
- **Error Wrapping** - All errors wrapped with context using %w
- **HTTP Status Codes** - 404 for not found, 500 for server errors
- **Panic Recovery** - Added recovery middleware with metrics
### Configuration
- **Fixed Env Var Naming** - RATE_LIMIT_MCP, RATE_LIMIT_IDE (was MCP_RATE_LIMIT, IDE_RATE_LIMIT)
- **Feature Flags** - Added ENABLE_METRICS, ENABLE_AUDIT_LOGGING, ENABLE_CACHE
- **CORS Config** - Added CORS_ALLOWED_ORIGINS, CORS_MAX_AGE
### Observability
- **Panic Metrics** - Track recovered panics by path
- **Database Metrics** - Connection pool stats, query duration
- **SLO Metrics** - Compliance, error budget burn rate, SLI values
- **Correlation ID** - Request tracing middleware
### API Consistency
- **Route Ordering** - Fixed search routes before parameterized routes
- **Response Formats** - Standardized across all endpoints
## [1.9.3] - 2026-02-07
### Security
- **CORS Origin Validation** - Replaced wildcard CORS with configurable origin validation
- **Secure Session ID Generation** - Uses crypto/rand instead of timestamp-based IDs
- **Security Headers** - Added X-Content-Type-Options, X-Frame-Options, X-XSS-Protection, Referrer-Policy
- **Request Size Limits** - Added 1MB body size limit to prevent DoS
- **Path Traversal Protection** - Added slug validation to prevent path traversal attacks
### Fixed
- **SQL Injection Vulnerabilities** - Fixed dynamic query building in List methods
- **Redis Blocking Commands** - Replaced KEYS command with non-blocking SCAN
- **Context Timeouts** - Added 5-second timeouts to cache operations
- **Session Memory Leaks** - Added cleanup goroutine for inactive sessions
- **MCP Protocol Compliance** - SSE endpoint now sends full URLs, proper JSON-RPC ping format
- **JSON-RPC Validation** - Added session_id and JSON-RPC version validation
### Added
- **Transaction Support** - All Create/Update/Delete operations now use transactions
- **Model Validation** - Validate() methods for all models (Document, Rule, Project, Failure)
- **Database Migrations** - Migration system with schema versioning
- **Connection Pool Monitoring** - Pool health monitoring with capacity warnings
- **Graceful Shutdown** - Configurable shutdown timeout with SIGQUIT support
- **Kubernetes Deployment** - Complete K8s manifests with HPA and PDB
- **API Documentation** - Comprehensive API.md with all REST endpoints
- **MCP Server CHANGELOG** - Separate changelog for MCP server
### Infrastructure
- **Dockerfile Improvements** - Version injection, CA certificates
- **Health Checks** - Liveness, readiness, and startup probes
- **Observability** - /version endpoint, Prometheus metrics, optional pprof
- **Resource Limits** - CPU/memory limits for all services
### Changed
- **MCP Server Documentation** - Enhanced README with security features and troubleshooting
- **Environment Configuration** - Fixed defaults in .env.example to match deployment
- **MCP Server README.md**
- Added complete project structure including `internal/mcp/`
- Expanded API endpoints documentation with all routes
- Added database migration section
- Added comprehensive security features documentation
- Added development commands (fmt, lint, vuln)
- Added troubleshooting section
- **MCP Server .env.example**
- Reorganized with better section headers
- Added profiling configuration options
- Added health check timeout configuration
- Added build information variables
- Improved documentation for each setting
---
### Added
## [1.9.2] - 2026-02-07
### Fixed
- **Web UI Authentication** - Removed API key requirement for Web UI routes
- Web UI (port 8093) is now publicly accessible without authentication
- Added skip logic for `/`, `/index.html`, and `/static/*` routes
- API endpoints still require valid API key
- Health checks and metrics remain unauthenticated
## [1.9.1] - 2026-02-07
### Fixed
- **SSE Compatibility** - Fixed EOF errors with non-interactive clients
- Added `WriteHeader(http.StatusOK)` for immediate header commit
- Added `X-Accel-Buffering: no` for proxy compatibility
- Added `Access-Control-Allow-Origin: *` for CORS
- Send immediate ping event after endpoint to prevent client timeout
- Better error handling on write/flush operations
- **PostgreSQL Array Scanning** - Fixed TEXT[] array scanning bug
- Changed `AffectedFiles` from `pq.StringArray` to `pgtype.Array[string]`
- Added `ToStringSlice()` and `ToTextArray()` helper functions
- Compatible with pgx v5 driver
### Documentation
- **README.md** - Complete rewrite with MCP Server documentation
- Installation and testing instructions
- Environment variable reference
- curl test examples
- Deployment guide for production servers
## [1.9.0] - 2026-02-07
### Added
- **MCP Server** - Full Model Context Protocol implementation
- `mcp-server/` - Complete Go-based MCP server
- `mark3labs/mcp-go` v0.4.0 for protocol implementation
- SSE transport for real-time client communication
- Tools: `guardrail_init_session`, `guardrail_validate_bash`,
`guardrail_validate_file_edit`, `guardrail_validate_git_operation`,
`guardrail_pre_work_check`, `guardrail_get_context`
- Resources: `guardrail://quick-reference`, `guardrail://rules/active`
- **Web UI** - Browser-based guardrail management
- Document CRUD operations
- Prevention rule management
- Failure registry viewer
- Project configuration
- **Production Deployment** - RHEL + Podman environment
- PostgreSQL 16 for data persistence
- Redis 7 for caching and rate limiting
- Multi-stage Docker build with distroless image
- Security hardening: non-root user (65532), read-only filesystem,
dropped capabilities, SELinux labels
### Changed
- **Server Binding** - Changed from `127.0.0.1` to `0.0.0.0` for containerized deployment
- **Go Version** - Upgraded to Go 1.23.2 for mcp-go compatibility
### Infrastructure
- Example endpoints:
- MCP: `http://localhost:8092`
- Web UI: `http://localhost:8093`
## [1.8.0] - 2026-02-05
### Added
- Placeholder for v1.8.0 changes
## [1.7.0] - 2026-02-01
### Added
- **Claude Code Integration** - Full support for Claude Code skills and hooks
- `scripts/setup_agents.py` - CLI tool to generate configurations
- Skills: guardrails-enforcer, commit-validator, env-separator
- Hooks: pre-execution, post-execution, pre-commit
- `docs/CLCODE_INTEGRATION.md` - Complete setup guide
- **OpenCode Integration** - Full support for OpenCode agents and skills
- `.opencode/oh-my-opencode.jsonc` configuration template
- Skills: guardrails-enforcer, commit-validator, env-separator
- Agents: guardrails-auditor, doc-indexer
- `docs/OPENCODE_INTEGRATION.md` - Complete setup guide
- **Shared Prompts** - Reusable prompt components
- `skills/shared-prompts/four-laws.md` - The Four Laws of Agent Safety
- `skills/shared-prompts/halt-conditions.md` - When to stop and ask
- **Script-Based Workflows** - Documentation for large-scale operations
- `docs/AGENTS_AND_SKILLS_SETUP.md` - Main setup guide
- Large code review script examples
- Batch execution with guardrails compliance
- CI/CD integration patterns
- **Navigation Updates**
- Updated `INDEX_MAP.md` with new AI Tools Integration category
- Updated `TOC.md` with 3 new documents
- Added scripts/ directory to navigation
### Changed
- **README.md** - Updated version to v1.7.0
### Statistics
- Documentation files: 28 → 31 (+3)
- New code files: 1 (setup_agents.py)
- New shared resources: 2 (prompt files)
- Total new files: 6
## [1.6.0] - 2026-01-18
### Added
- **TOC.md** - Comprehensive table of contents with file listings
- Complete catalog of all 85 documents in the template
- Organized by category (standards, workflows, examples, etc.)
- Includes statistics: total files, category breakdowns, compliance status
- Separate from README for cleaner navigation
### Changed
- **README.md** - Rewritten for clarity on what the Agent Guardrails Template is
- Now clearly explains "What Is This?" concept
- Better project overview and quick start guide
- Improved from 220 to 320 lines for better readability
- Clearer problem/solution overview
- **INDEX_MAP.md** - Added `toc` and `examples` keywords to Quick Lookup Table
- Updated document counts (21 → 28 docs)
- Updated all "Last Updated" dates
- **HEADER_MAP.md** - Added TOC.md and CHANGELOG.md sections
- Updated status and last updated dates
### Improved
- Documentation clarity: README now clearly explains the template's purpose
- Discoverability: Separate TOC.md makes finding specific documentation easier
- Navigation: Updated maps reflect new TOC document
- User experience: Better first-impression for new visitors
### Statistics
- Documentation files: 28 → 28 (+0, reorganized)
- README lines: 220 → 320 (+100, +45%)
- TOC.md lines: 0 → ~350 (+350)
- Total documents cataloged: 85 files
---
## [1.5.0] - 2026-01-18
### Added
- CHANGELOG.md - Centralized release notes archive
- Examples directory with guardrails implementation examples in multiple languages
- Comprehensive release notes archiving from GitHub releases
### Changed
- All release notes now centralized in this CHANGELOG.md file
- GitHub releases now reference this file for full release notes
---
## [1.4.0] - 2026-01-16
### Added
- **docs/HOW_TO_APPLY.md** (432 lines) - Comprehensive guide with example AI agent prompts
- Option A: Apply to existing repository detailed steps
- Option B: Example AI agent prompts (5 ready-to-use prompts)
- Option C: Create new repository with standards
- Option D: Migrate existing documentation to guardrails structure
- Verification checklist
- `how-to-apply` keyword to INDEX_MAP.md for easy discovery
### Changed
- **README.md** restructured for 500-line compliance
- Reduced from 621 lines to 219 lines (65% reduction)
- Quick start options link to detailed HOW_TO_APPLY guide
- Preserved Template Contents and PROJECT README TEMPLATE
### Improved
- Token efficiency: 65% fewer tokens needed to read README
- Documentation organization: Better hierarchy with dedicated HOW_TO_APLY.md
- Agent-friendly prompts: Copy-paste ready prompts for common tasks
- Faster onboarding: Ready-to-use prompts reduce ambiguity
### Statistics
- Documentation files: 20 → 21 (+1)
- README lines: 621 → 219 (-402, -65%)
- HOW_TO_APPLY.md lines: 0 → 432 (+432)
- 500-line compliance: 17/20 → 21/21 (100%)
---
## [1.3.0] - 2026-01-16
### Added
- **docs/standards/TEST_PRODUCTION_SEPARATION.md** (558 lines) - Mandatory test/production isolation standard
- Three Laws of Test/Production Separation
- Environment separation requirements (databases, services, users)
- Mandatory pre-code checklist
- Code creation sequence (production first, then test)
- Uncertainty handling protocol (always ask user)
- CI/CD blocking checks
- Examples, patterns, and anti-patterns
- **docs/workflows/AGENT_EXECUTION.md** (374 lines) - Execution protocol and rollback procedures
- Standard task flow (5 phases)
- Decision matrix
- Rollback procedures (immediate, post-commit, post-push)
- Commit message format
- Error handling protocols
- Verification checklists
- **docs/workflows/AGENT_ESCALATION.md** (413 lines) - Audit requirements and escalation procedures
- Audit log requirements (what to log)
- Log format standards
- When to escalate to human
- How to escalate (templates and scenarios)
- Agent-specific guidelines (by category)
- Compliance and violation reporting
### Changed
- **docs/AGENT_GUARDRAILS.md** - Restructured from 626 lines to 267 lines for 500-line compliance
- Split into 3 focused documents
- Added Test/Production Separation Rules section
- CORE GUARDRAILS section retained
- **docs/workflows/CODE_REVIEW.md** - Added test/production separation review items
- **docs/sprints/SPRINT_TEMPLATE.md** - Added safety checks for completion gate
- **docs/workflows/INDEX.md** - Updated to 10 documents
- **docs/standards/INDEX.md** - Updated to 5 documents
### Security
- **CRITICAL:** All AI agents must verify test/production separation before deployment
- **BLOCKING VIOLATIONS** that halt deployment:
- Deploying test code to production environment
- Using production database for tests
- Creating test users in production database
- Writing test code that imports production secrets
- Using production services for test execution
- Sharing user accounts across environments
### Breaking Changes
- **MANDATORY:** All AI agents must now comply with test/production separation requirements
- Agents must ask user when uncertain about test/production boundaries
- Blocking violations prevent deployment when separation requirements not met
### Statistics
- Documentation files: 17 → 20 (+3)
- AGENT_GUARDRAILS.md: 626 → 267 lines (-359 lines)
- Total documentation lines: ~1,500 → 2,672 (+1,172)
- All documents now comply with 500-line maximum rule
---
## [1.1.0] - 2026-01-15
### Added
- Universal Agent Support framework
- By-Category Agent Guidelines covering:
- Commercial API-Based Models (Claude, GPT, Gemini, Command R)
- Open Source / Self-Hosted Models (LLaMA, Mistral, Qwen, DeepSeek, Phi, Falcon)
- Multimodal Models (GPT-4V, Gemini Pro Vision, Claude 3, LLaVA)
- Reasoning / Chain-of-Thought Models (o1, o3, DeepSeek-R1)
- Agent Frameworks (CrewAI, LangChain, AutoGPT, LangGraph, Semantic Kernel)
- Model Compatibility Note section
- 30+ major LLM families explicitly supported
- All future models supported via generic patterns
### Changed
- **docs/AGENT_GUARDRAILS.md** - Major restructure
- Replaced model-specific sections with category-based approach
- Added Universal Requirements section for ALL LLMs and AI agents
- Applicability table expanded with new model types
- Enhanced compliance section
### Improved
- Scalability: Framework now supports any current or future AI model
- Maintenance: Category-based approach easier to maintain than model-specific
- Coverage: 99%+ of AI agents covered by category system
---
## [1.0.0] - 2026-01-14
### Added
- Initial stable release of Agent Guardrails Template
- **Core Documentation:**
- docs/AGENT_GUARDRAILS.md (626 lines) - Mandatory safety protocols for all AI agents
- **Sprint Framework:**
- docs/sprints/SPRINT_TEMPLATE.md - Task execution template
- docs/sprints/SPRINT_GUIDE.md - How to write effective sprint documents
- docs/sprints/INDEX.md - Sprint navigation
- **Workflow Documentation** (8 comprehensive guides):
- TESTING_VALIDATION.md - Validation protocols
- COMMIT_WORKFLOW.md - Commit guidelines
- GIT_PUSH_PROCEDURES.md - Push safety procedures
- BRANCH_STRATEGY.md - Git branching conventions
- ROLLBACK_PROCEDURES.md - Recovery operations
- MCP_CHECKPOINTING.md - MCP server integration
- CODE_REVIEW.md - Code review process
- DOCUMENTATION_UPDATES.md - Post-sprint doc updates
- **Standards Documentation** (4 guides):
- MODULAR_DOCUMENTATION.md - 500-line max rule
- LOGGING_PATTERNS.md - Array-based logging format
- LOGGING_INTEGRATION.md - External logging hooks
- API_SPECIFICATIONS.md - OpenAPI/OpenSpec guidance
- **GitHub Integration:**
- .github/SECRETS_MANAGEMENT.md - GitHub Secrets guide
- .github/workflows/ (3 CI/CD workflows)
- .github/PULL_REQUEST_TEMPLATE.md - PR template with AI attribution
- .github/ISSUE_TEMPLATE/bug_report.md - Bug report template
- **Navigation Maps:**
- INDEX_MAP.md - Master navigation, find docs by keyword
- HEADER_MAP.md - Section-level lookup
- CLAUDE.md - Claude Code CLI guidelines
- .claudeignore - Token-saving ignore rules
### Features
- Four Laws of Agent Safety
- Pre-Execution Checklist
- Git Safety Rules (8 rules)
- Code Safety Rules (7 rules)
- Guardrails: HALT CONDITIONS, FORBIDDEN ACTIONS, SCOPE BOUNDARIES
- Standard Task Flow (5 phases)
- Rollback Procedures (3 scenarios)
- Commit Message Format with conventions
- Error Handling Protocols (4 scenarios)
- Verification Checklist (pre-completion)
- Agent-Specific Guidelines for all major AI systems
- Audit Requirements
- Escalation Procedures
---
## Version Management
### Version Numbering
This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html):
- **MAJOR**: Incompatible API changes
- **MINOR**: Backwards-compatible functionality additions
- **PATCH**: Backwards-compatible bug fixes
### Release Process
1. Complete all changes
2. Test and validate
3. Commit changes with conventional commit message
4. Update CHANGELOG.md
5. Create version tag: `git tag v1.X.X`
6. Push tag: `git push origin v1.X.X`
7. Create GitHub release with `gh release create`
---
## Links
- **Releases:** [GitHub Releases](https://github.com/TheArchitectit/agent-guardrails-template/releases)
- **Documentation:** [INDEX_MAP.md](INDEX_MAP.md)
- **Issues:** [GitHub Issues](https://github.com/TheArchitectit/agent-guardrails-template/issues)

59
.guardrails/CLAUDE.md Normal file
View File

@ -0,0 +1,59 @@
# Project Guidelines
## 0. Navigation Maps (READ FIRST)
* **INDEX_MAP.md**: Read this FIRST to find documents by keyword/category. Saves 60-80% tokens.
* **HEADER_MAP.md**: Find specific sections with file:line references for targeted reading.
* **Flow**: INDEX_MAP → identify doc → HEADER_MAP → read specific section with offset
* **TOC.md**: Complete file listing and organization structure
---
## 0.1 Agent-GDUI-2026 Initialization Context
**Role:** Agent-GDUI-2026 (Game Design & UI 2026) is the specialized agent for:
- Game interface development
- Spatial computing (XR/VR/AR/MR)
- UI/UX component implementation
- Accessibility compliance (WCAG 3.0+)
- Ethical engagement (dark pattern prevention)
**Core Philosophies:**
1. **Comfort First** - Never induce motion sickness or discomfort
2. **Accessibility Required** - WCAG 3.0+ compliance mandatory
3. **Performance Bound** - Maintain frame rate budgets strictly
4. **Ethical Engagement** - Reject dark pattern implementations
**Vibe Coding Philosophy:**
These constraints enable flow state. Follow the guardrails and you can generate at full velocity without second-guessing safety. Constraints aren't friction — they're your fast lane.
**Quick Links:**
- [2026_GAME_DESIGN.md](docs/game-design/2026_GAME_DESIGN.md) - Game design guardrails
- [2026_UI_UX_STANDARD.md](docs/ui-ux/2026_UI_UX_STANDARD.md) - UI component standards
- [ACCESSIBILITY_GUIDE.md](docs/accessibility/ACCESSIBILITY_GUIDE.md) - WCAG 3.0+ guide
- [SPATIAL_COMPUTING_UI.md](docs/spatial/SPATIAL_COMPUTING_UI.md) - XR/VR/AR patterns
- [ETHICAL_ENGAGEMENT.md](docs/ethical/ETHICAL_ENGAGEMENT.md) - Dark pattern prevention
## 1. Context & Setup
* **Stack Detection**: Read configuration files (package.json, requirements.txt, Makefile, etc) to determine stack. Do NOT read lockfiles.
* **Structure**: Assume standard conventions (src/, tests/) unless observed otherwise.
* **Guardrails**: Read [docs/AGENT_GUARDRAILS.md](docs/AGENT_GUARDRAILS.md) before any code changes.
## 2. Token-Saving Rules (STRICT)
> These rules exist to maximize your speed. Every token saved on exploration is a token spent on building.
* **NO EXPLORATION**: Do not use "ls -R" or explore file structure.
* **NO RE-READING**: Trust your context; do not re-read files just edited.
* **TARGETED CONTEXT**: Read ONLY files explicitly relevant to the request.
* **CONCISE PLANS**: Bullet points only. No "thinking out loud".
* **USE MAPS**: Always check INDEX_MAP.md before reading full documents.
## 3. Workflow
* **Tests**: Run ONLY relevant tests.
* **Edits**: Prefer small, single-file edits.
* **Commits**: Commit after each to-do item (see [COMMIT_WORKFLOW.md](docs/workflows/COMMIT_WORKFLOW.md)).
* **Checkpoints**: Use MCP checkpoints before/after critical operations.
## 4. Documentation Standards
* **500-Line Max**: No document over 500 lines.
* **Update Maps**: Update INDEX_MAP.md and HEADER_MAP.md when adding/changing docs.

370
.guardrails/CONTRIBUTING.md Normal file
View File

@ -0,0 +1,370 @@
# Contributing to Agent Guardrails Template
> Guidelines for contributing to the MCP Server and related components
**Version:** 2.6.0
**Last Updated:** 2026-02-15
---
## Quick Start
1. **Fork** the repository
2. **Clone** your fork: `git clone https://github.com/YOUR_USERNAME/agent-guardrails-template.git`
3. **Set up** the development environment (see below)
4. **Create** a feature branch: `git checkout -b feature/your-feature`
5. **Make** your changes
6. **Test** your changes
7. **Commit** with conventional commit messages
8. **Push** to your fork
9. **Open** a Pull Request
---
## Development Environment
### Prerequisites
| Tool | Version | Purpose |
|------|---------|---------|
| Go | 1.23+ | Primary language for MCP server |
| Docker | 20.10+ | Container development |
| PostgreSQL | 16+ | Database (or use Docker) |
| Redis | 7+ | Cache (or use Docker) |
| Make | 3.81+ | Build automation |
### Repository Structure
```
agent-guardrails-template/
├── mcp-server/ # Go MCP Server (Primary)
│ ├── cmd/server/ # Entry point
│ ├── internal/ # Internal packages
│ │ ├── team/ # Team management (Go)
│ │ ├── mcp/ # MCP protocol handlers
│ │ ├── database/ # Database operations
│ │ ├── cache/ # Redis caching
│ │ └── ...
│ ├── deploy/ # Docker configs
│ └── go.mod # Go dependencies
├── scripts/ # Python scripts (DEPRECATED)
├── docs/ # Documentation
└── ...
```
---
## Go Development Guidelines
### Code Style
We follow standard Go conventions:
```bash
# Format code
cd mcp-server
go fmt ./...
# Run linter
golangci-lint run
# Run vet
go vet ./...
```
### Project Structure
```go
// Package documentation
// Package team provides team management functionality for MCP server.
// This is a Go port of the Python team_manager.py core functionality.
package team
// Imports - grouped by: stdlib, third-party, internal
import (
"context"
"fmt"
"github.com/some/lib"
"github.com/thearchitectit/guardrail-mcp/internal/models"
)
// Exported types start with capital letter
type Manager struct {
// fields...
}
// Constructor function
func NewManager(projectName string, opts ...ManagerOption) (*Manager, error) {
// implementation...
}
// Methods
func (m *Manager) AssignRole(ctx context.Context, teamID int, role, person string) error {
// implementation...
}
```
### Naming Conventions
| Type | Convention | Example |
|------|------------|---------|
| **Packages** | lowercase, single word | `team`, `mcp`, `database` |
| **Exported** | PascalCase | `Manager`, `AssignRole` |
| **Unexported** | camelCase | `internalFunc`, `helper` |
| **Constants** | PascalCase or UPPER_SNAKE | `MaxRetries`, `DEFAULT_TIMEOUT` |
| **Interfaces** | -er suffix | `Reader`, `Writer`, `Manager` |
| **Structs** | PascalCase | `TeamManager`, `ProjectConfig` |
### Error Handling
Use wrapped errors with context:
```go
// Good
if err := validateProjectName(projectName); err != nil {
return fmt.Errorf("invalid project name %q: %w", projectName, err)
}
// Avoid
return errors.New("something went wrong") // No context
// Custom error types for specific cases
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation error on %s: %s", e.Field, e.Message)
}
```
### Context Usage
Always accept `context.Context` as first parameter:
```go
// Good
func (m *Manager) DoOperation(ctx context.Context, arg string) error {
// Use ctx for timeouts, cancellation
}
// Avoid - no context support
func (m *Manager) DoOperation(arg string) error {
// ...
}
```
### Testing
```go
// Test files: *_test.go
package team
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestManager_AssignRole(t *testing.T) {
// Arrange
ctx := context.Background()
mgr, err := NewManager("test-project")
require.NoError(t, err)
// Act
err = mgr.AssignRole(ctx, 7, "Technical Lead", "Alice")
// Assert
assert.NoError(t, err)
}
// Table-driven tests
func TestValidateProjectName(t *testing.T) {
tests := []struct {
name string
input string
wantErr bool
}{
{"valid", "my-project", false},
{"empty", "", true},
{"with space", "my project", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateProjectName(tt.input)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
```
Run tests:
```bash
cd mcp-server
# Run all tests
go test ./...
# Run with coverage
go test -cover ./...
# Run specific package
go test ./internal/team/...
# Run benchmarks
go test -bench=. ./internal/team/...
```
---
## Commit Guidelines
### Conventional Commits
```
<type>(<scope>): <subject>
<body>
<footer>
```
**Types:**
- `feat` - New feature
- `fix` - Bug fix
- `docs` - Documentation only
- `style` - Code style (formatting, semicolons)
- `refactor` - Code refactoring
- `test` - Adding tests
- `chore` - Build process, dependencies
**Scopes:**
- `team` - Team management
- `mcp` - MCP protocol
- `db` - Database
- `cache` - Redis/cache
- `security` - Security features
- `api` - API endpoints
- `web` - Web UI
- `docs` - Documentation
**Examples:**
```
feat(team): add batch assignment operation
Adds support for assigning multiple team members in a single
team operation with transaction support.
Closes #123
```
```
fix(mcp): handle nil context in tool handlers
Prevents panic when context is nil in team tool handlers.
Fixes #456
```
```
docs: add Python to Go migration guide
Adds comprehensive migration documentation for developers
migrating from Python team_manager.py to Go team package.
```
---
## Pull Request Process
1. **Update documentation** if needed
2. **Add tests** for new functionality
3. **Ensure all tests pass**: `go test ./...`
4. **Update CHANGELOG.md** with your changes
5. **Request review** from maintainers
6. **Address feedback** promptly
7. **Squash commits** if requested
### PR Template
```markdown
## Summary
Brief description of changes
## Type
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation
## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests pass
- [ ] Manual testing completed
## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] Comments added for complex code
- [ ] Documentation updated
- [ ] CHANGELOG.md updated
```
---
## Python Scripts (Deprecated)
**Note:** Python scripts in `scripts/` are deprecated as of v2.6.0.
- Do **not** add new features to Python scripts
- Do **not** modify Python scripts unless fixing critical bugs
- All new development should be in Go
- Python scripts will be removed in v3.0.0
See [docs/PYTHON_TO_GO_MIGRATION.md](docs/PYTHON_TO_GO_MIGRATION.md) for migration guide.
---
## Documentation
### Adding Documentation
1. Create markdown file in appropriate directory:
- `docs/` - General documentation
- `docs/workflows/` - Operational procedures
- `docs/standards/` - Coding standards
- `mcp-server/` - MCP-specific docs
2. Keep documents under 500 lines (see `docs/standards/MODULAR_DOCUMENTATION.md`)
3. Update navigation:
- `INDEX_MAP.md` - Add keywords
- `HEADER_MAP.md` - Add sections
- `TOC.md` - Add file listing
4. Follow existing format and style
---
## Questions?
- **General:** Open a GitHub Discussion
- **Bug Reports:** Open a GitHub Issue
- **Security:** Email security@example.com
---
**Thank you for contributing!**

View File

@ -0,0 +1,60 @@
# Gap Remediation Branch
**Branch:** `feature/team-tools-gap-remediation`
## Purpose
This branch contains the gap remediation plan and tracking for the 47 gaps identified in the Team Tools implementation.
## Background
A comprehensive gap analysis was conducted by a team of 4 analysts (per TEAM-007 compliance) and identified 47 gaps across:
- Functional: 15 gaps
- Testing: 6 gaps
- Security: 11 gaps
- Operational: 15 gaps
## Documents
| Document | Description |
|----------|-------------|
| [docs/GAP_ANALYSIS_TEAM_REPORT.md](./docs/GAP_ANALYSIS_TEAM_REPORT.md) | Full gap analysis findings |
| [docs/TEAM_TOOLS_GAP_REMEDIATION_PLAN.md](./docs/TEAM_TOOLS_GAP_REMEDIATION_PLAN.md) | Remediation plan with sprints |
## Quick Links
### P0 Critical Gaps (8)
Must be fixed before release:
1. FUNC-001: No Unassign/Remove
2. FUNC-002: No Team/Project Delete
3. TEST-001: No Handler Unit Tests
4. TEST-002: No Python Tests
5. TEST-003: No Integration Tests
6. SEC-001: No Authorization
7. SEC-004: Race Conditions
8. OPS-001: No Structured Logging
### Sprint Schedule
- **Sprint 1:** Testing Infrastructure (2 weeks)
- **Sprint 2:** Security Hardening (2 weeks)
- **Sprint 3:** Core Operations (2 weeks)
- **Sprint 4:** Enhancement (4 weeks)
## Team Size Compliance
All work on this branch follows TEAM-007: 4-6 members per team.
## How to Contribute
1. Pick a gap from the remediation plan
2. Create a feature branch from this branch
3. Implement the fix
4. Add tests
5. Update progress in remediation plan
6. Submit PR to this branch
## Status Tracking
Update the progress table in `docs/TEAM_TOOLS_GAP_REMEDIATION_PLAN.md` as gaps are resolved.
---
**Created:** 2026-02-15
**Target Release:** v2.1.0

1576
.guardrails/HEADER_MAP.md Normal file

File diff suppressed because it is too large Load Diff

489
.guardrails/INDEX_MAP.md Normal file
View File

@ -0,0 +1,489 @@
# Documentation Index Map
> **READ THIS FIRST** - Find what you need without loading full documents.
> Estimated token savings: 60-80% when using targeted lookups.
---
## Quick Lookup Table
| Keyword | Document | Path | Purpose |
|---------|----------|------|---------|
| quick-setup | QUICK_SETUP.md | ./ | **5-minute setup guide** ⭐ |
| prompting | PROMPTING_GUIDE.md | ./ | **Master prompting techniques** ⭐ |
| toc | TOC.md | ./ | Complete template contents and file listing |
| safety | AGENT_GUARDRAILS.md | docs/ | Mandatory safety protocols |
| test-prod | TEST_PRODUCTION_SEPARATION.md | docs/standards/ | Test/production isolation (MANDATORY) |
| execution | AGENT_EXECUTION.md | docs/workflows/ | Standard execution protocol |
| escalation | AGENT_ESCALATION.md | docs/workflows/ | Audit & escalation procedures |
| how-to-apply | HOW_TO_APPLY.md | docs/ | How to apply guardrails to repos |
| commit | COMMIT_WORKFLOW.md | docs/workflows/ | When/how to commit |
| push | GIT_PUSH_PROCEDURES.md | docs/workflows/ | Push safety procedures |
| branch | BRANCH_STRATEGY.md | docs/workflows/ | Git branching conventions |
| rollback | ROLLBACK_PROCEDURES.md | docs/workflows/ | Recovery and undo |
| test | TESTING_VALIDATION.md | docs/workflows/ | Validation protocols |
| review | CODE_REVIEW.md | docs/workflows/ | Code review process |
| checkpoint | MCP_CHECKPOINTING.md | docs/workflows/ | MCP auto-checkpoint |
| docs | DOCUMENTATION_UPDATES.md | docs/workflows/ | Post-sprint doc updates |
| logging | LOGGING_PATTERNS.md | docs/standards/ | Array-based logging |
| hooks | LOGGING_INTEGRATION.md | docs/standards/ | External logging hooks |
| modular | MODULAR_DOCUMENTATION.md | docs/standards/ | 500-line rule |
| api | API_SPECIFICATIONS.md | docs/standards/ | OpenAPI/OpenSpec guidance |
| secrets | SECRETS_MANAGEMENT.md | .github/ | GitHub Secrets setup |
| examples | examples/ | examples/ | Multi-language implementation examples |
| scala-examples | examples/scala/functional-ui/ | Scala 3.4+ functional UI, type-safe CSS, DDA telemetry |
| r-examples | examples/r/game-analytics/ | R ggplot2 4.0+, Shiny 2.0+, ethics auditing, retention analysis |
| regression-examples | regression-prevention/ | examples/regression-prevention/ | Practical regression prevention examples |
| sprint | SPRINT_TEMPLATE.md | docs/sprints/ | Sprint task template |
| sprint-guide | SPRINT_GUIDE.md | docs/sprints/ | How to write sprints |
| validation | SPRINT_TEMPLATE.md | docs/sprints/ | Completion gate & validation loop |
| completion | SPRINT_TEMPLATE.md | docs/sprints/ | Pre-completion checklist |
| context | PROJECT_CONTEXT_TEMPLATE.md | docs/standards/ | Project Bible - stack constraints, style guide |
| adversarial | ADVERSARIAL_TESTING.md | docs/standards/ | Breaker agent, fuzz testing, attack checklists |
| agent-review | AGENT_REVIEW_PROTOCOL.md | docs/workflows/ | Post-work verification by another agent |
| dependencies | DEPENDENCY_GOVERNANCE.md | docs/standards/ | Package allow-list, forbidden packages |
| infrastructure | INFRASTRUCTURE_STANDARDS.md | docs/standards/ | IaC, Terraform, drift detection |
| operational | OPERATIONAL_PATTERNS.md | docs/standards/ | Health checks, circuit breakers, retry |
| retry | AGENT_EXECUTION.md | docs/workflows/ | Three Strikes Rule, retry limits |
| scope-freeze | SPRINT_TEMPLATE.md | docs/sprints/ | Scope Freeze Protocol |
| deployment | DEPLOYMENT_GUIDE.md | mcp-server/ | MCP server deployment instructions (critical fixes) |
| schema-error | DEPLOYMENT_GUIDE.md | mcp-server/ | Fix schema validation error (guardrail-mcp → guardrail_mcp) |
| postgres-perm | DEPLOYMENT_GUIDE.md | mcp-server/ | Fix postgres permission errors (user 70:70) |
| container-networking | DEPLOYMENT_GUIDE.md | mcp-server/ | Pod networking for container communication |
| skills | AGENTS_AND_SKILLS_SETUP.md | docs/ | Setup agents and skills for all platforms |
| claude-code | CLCODE_INTEGRATION.md | docs/ | Claude Code skills and hooks integration |
| opencode | OPCODE_INTEGRATION.md | docs/ | OpenCode agents and skills integration |
| cursor | CURSOR_INTEGRATION.md | docs/ | Cursor rules and configuration |
| copilot | CLCODE_INTEGRATION.md | docs/ | GitHub Copilot instructions (see Claude Code) |
| cody | CLCODE_INTEGRATION.md | docs/ | Cody context configuration (see Claude Code) |
| mcp-server | MCP_SERVER_PLAN.md | docs/plans/ | MCP server implementation plan |
| mcp-api | API.md | mcp-server/ | MCP server REST API documentation |
| mcp-changelog | CHANGELOG.md | mcp-server/ | MCP server version history |
| guardrail-platform | MCP_SERVER_PLAN.md | docs/plans/ | Guardrail enforcement platform |
| team-tools | TEAM_TOOLS.md | docs/ | Team layout management MCP tools reference (Go implementation) |
| team-structure | TEAM_STRUCTURE.md | docs/ | 12-team enterprise structure documentation |
| python-migration | PYTHON_TO_GO_MIGRATION.md | docs/ | Python to Go migration guide for developers |
| go-migration | PYTHON_TO_GO_MIGRATION.md | docs/ | Python to Go migration guide for developers |
| team-cli | cmd/team-cli/README.md | cmd/team-cli/ | Team management CLI tool |
| phase-gate | TEAM_TOOLS.md | docs/ | Phase transition requirements and deliverables |
| aider | CLCODE_INTEGRATION.md | docs/ | Aider YAML configuration (see Claude Code) |
| continue | CLCODE_INTEGRATION.md | docs/ | Continue IDE configuration (see Claude Code) |
| windsurf | CLCODE_INTEGRATION.md | docs/ | Windsurf rules configuration (see Claude Code) |
| generic | GENERIC_LLM_INTEGRATION.md | docs/ | Generic/local LLM configuration guide |
| setup | setup_agents.py | scripts/ | CLI tool to generate agent configurations |
| regression | REGRESSION_PREVENTION.md | docs/workflows/ | Bug tracking and regression prevention protocol |
| failure-registry | failure-registry.jsonl | .guardrails/ | Append-only bug database (JSONL format) |
| pre-work-check | pre-work-check.md | .guardrails/ | MANDATORY pre-work regression checklist |
| log-failure | log_failure.py | scripts/ | CLI tool to log bugs to failure registry |
| regression-check | regression_check.py | scripts/ | Pre-commit regression pattern scanner |
| prevention-rules | pattern-rules.json | .guardrails/prevention-rules/ | Regex patterns to prevent regressions |
| game-design | 2026_GAME_DESIGN.md | docs/game-design/ | Agent-GDUI-2026 game design guardrails, XR/VR comfort zones |
| 3d-guardrails | 3D_GAME_DEVELOPMENT.md | docs/game-design/3d/ | 3D game development guardrails v1.0, engine-agnostic |
| 3d-proposals | 3D_GUARDREL_PROPOSALS_V1.2.md | docs/game-design/3d/ | Proposed v1.2 additions from Hermes 2026 AI Dossier |
| 3d-math | 3D_MATHEMATICAL_FOUNDATIONS.md | docs/game-design/3d/ | Linear algebra, quaternions, collision math reference |
| 3d-architecture | 3D_MODULE_ARCHITECTURE.md | docs/game-design/3d/ | Module architecture for LLM-to-3D-engine bridging |
| ai-debuggable | AI_DEBUGGABLE_3D_ARCHITECTURE.md | docs/game-design/3d/ | AI-debuggable 3D patterns for autonomous troubleshooting |
| ai-2026-guide | AI_DEV_2026_PART01_INTRO_AND_FOUNDATIONS.md | docs/game-design/ | AI-Powered Development 2026: 10-part comprehensive guide series |
| ai-2026-prompting | AI_DEV_2026_PART02_PROMPTING.md | docs/game-design/ | Part 2 — Prompt Engineering for Code |
| ai-2026-context | AI_DEV_2026_PART03_CONTEXT_AND_ITERATION.md | docs/game-design/ | Part 3 — Context & Iterative Development |
| ai-2026-quality | AI_DEV_2026_PART04_QUALITY_AND_ARCHITECTURE.md | docs/game-design/ | Part 4 — Quality & Architecture |
| ai-2026-legacy | AI_DEV_2026_PART05_LEGACY_AND_AGENTS.md | docs/game-design/ | Part 5 — Legacy Refactoring & Agent Paradigm |
| ai-2026-building | AI_DEV_2026_PART06_BUILDING_AGENTS.md | docs/game-design/ | Part 6 — Building Agents & Tool Use |
| ai-2026-multi | AI_DEV_2026_PART07_MULTI_AGENT_SYSTEMS.md | docs/game-design/ | Part 7 — Multi-Agent Systems |
| ai-2026-security | AI_DEV_2026_PART08_SECURITY_ETHICS_FUTURE.md | docs/game-design/ | Part 8 — Security, Ethics & Future |
| ai-2026-appendices | AI_DEV_2026_PART09_APPENDICES_ABC.md | docs/game-design/ | Part 9 — Appendices A, B & C |
| ai-2026-moa | AI_DEV_2026_PART10_APPENDIX_D.md | docs/game-design/ | Part 10 — Appendix D: Complete MoA Reference |
| hermes-dossier | HERMES_2026_PART01_INTRO_AND_EXECUTIVE.md | docs/game-design/3d/ | AI in 3D Game Development 2026: 9-part intelligence dossier |
| hermes-assets | HERMES_2026_PART02_ASSETS_AND_ENGINES.md | docs/game-design/3d/ | Part 2 — 3D Asset Generation & Engine Integration |
| hermes-world | HERMES_2026_PART03_WORLD_AND_RENDERING.md | docs/game-design/3d/ | Part 3 — World Generation & Neural Rendering |
| hermes-npcs | HERMES_2026_PART04_NPCS_AND_ANIMATION.md | docs/game-design/3d/ | Part 4 — NPCs, Dialogue & Animation |
| hermes-code | HERMES_2026_PART05_CODE_AND_PHYSICS.md | docs/game-design/3d/ | Part 5 — Code Generation & Neural Physics |
| hermes-qa | HERMES_2026_PART06_QA_AND_BUSINESS.md | docs/game-design/3d/ | Part 6 — QA, Testing & Business Landscape |
| hermes-legal | HERMES_2026_PART07_LEGAL_AND_CASES.md | docs/game-design/3d/ | Part 7 — Legal, Ethics & Case Studies |
| hermes-future | HERMES_2026_PART08_DEEP_DIVES_AND_FUTURE.md | docs/game-design/3d/ | Part 8 — Technology Deep-Dives & Future Outlook |
| hermes-appendices | HERMES_2026_PART09_APPENDICES.md | docs/game-design/3d/ | Part 9 — Appendices |
| ui-ux | 2026_UI_UX_STANDARD.md | docs/ui-ux/ | UI/UX component standards, design tokens, interaction states |
| accessibility | ACCESSIBILITY_GUIDE.md | docs/accessibility/ | WCAG 3.0+ compliance, conformance levels, testing methods |
| spatial | SPATIAL_COMPUTING_UI.md | docs/spatial/ | XR/VR/AR UI patterns, comfort zones, latency requirements |
| ethical | ETHICAL_ENGAGEMENT.md | docs/ethical/ | Dark pattern prevention, ethical design principles |
| semantic-rules | semantic-rules.json | .guardrails/prevention-rules/ | AST-based prevention rules |
| extracted-rules | extracted-rules.json | .guardrails/prevention-rules/ | Rules extracted from AGENT_GUARDRAILS.md |
| bug-fix | REGRESSION_PREVENTION.md | docs/workflows/ | Requirements for bug fixes (regression tests) |
| known-bugs | failure-registry.jsonl | .guardrails/ | Active/resolved/deprecated bug history |
| four-laws | four-laws.md | skills/shared-prompts/ | Canonical Four Laws of Agent Safety |
| halt-conditions | halt-conditions.md | skills/shared-prompts/ | When to stop and ask for help |
| sprint-001 | SPRINT_001_MCP_GAP_IMPLEMENTATION.md | docs/sprints/ | Sprint: MCP Gap Implementation |
| sprint-002 | SPRINT_002_WEB_UI_IMPLEMENTATION.md | docs/sprints/ | Sprint: Web UI Implementation |
| sprint-003 | SPRINT_003_DOCUMENTATION_PARITY.md | docs/sprints/ | Sprint: Documentation Parity (this sprint) |
| rules-from-md | RULES_FROM_MD.md | docs/ | Extracting prevention rules from markdown |
| rules-index | RULES_INDEX_MAP.md | docs/ | Master index of all prevention rules |
| mcp-tools | MCP_TOOLS_REFERENCE.md | docs/ | MCP validation tools documentation |
| rule-patterns | RULE_PATTERNS_GUIDE.md | docs/ | Pattern authoring guide |
| ai-dev | AI_ASSISTED_DEV.md | docs/ai-dev/ | AI-assisted development patterns, vibe coding, decision matrix |
| state | STATE_MANAGEMENT.md | docs/state/ | State architecture patterns, client/server state, CRDTs |
| generative | GENERATIVE_ASSET_SAFETY.md | docs/generative/ | Generative asset safety, C2PA metadata, content filtering |
| monetization | MONETIZATION_GUARDRAILS.md | docs/monetization/ | IAP ethics, loot box transparency, virtual economy |
| multiplayer | MULTIPLAYER_SAFETY.md | docs/multiplayer/ | Multiplayer safety, chat moderation, matchmaking fairness |
| analytics | ANALYTICS_ETHICS.md | docs/analytics/ | Analytics ethics, consent tiers, A/B testing, data minimization |
| deployment | CROSS_PLATFORM_DEPLOYMENT.md | docs/deployment/ | Cross-platform deployment, app store compliance, CI/CD |
| vibe-coding | vibe-coding.md | skills/shared-prompts/ | Canonical vibe coding principles for rapid AI development |
| flutter-examples | examples/flutter/cross-platform/ | examples/flutter/ | Flutter guardrails: ethical widgets, accessibility wrappers |
| godot-examples | examples/gdscript/godot-game/ | examples/gdscript/ | Godot GDScript: comfort zones, ethical UI, accessibility |
---
## Document Summaries
| Document | Purpose (one line) | When to Use |
|----------|-------------------|-------------|
| **TOC.md** | Complete template contents and file listing | When exploring full template |
| **AGENT_GUARDRAILS.md** | Core safety protocols (mandatory) | Before ANY code changes |
| **RULES_FROM_MD.md** | Extracting prevention rules from markdown | When working with MCP rules |
| **RULES_INDEX_MAP.md** | Master index of all prevention rules | When searching for specific prevention rules |
| **MCP_TOOLS_REFERENCE.md** | MCP validation tools documentation | When using MCP validation tools |
| **RULE_PATTERNS_GUIDE.md** | Pattern authoring guide | When writing new prevention rules |
| **TEST_PRODUCTION_SEPARATION.md** | Test/production isolation standards (MANDATORY) | Before ANY deployment |
| **AGENT_EXECUTION.md** | Execution protocol and rollback procedures | During task execution |
| **AGENT_ESCALATION.md** | Audit requirements and escalation procedures | When uncertain or errors occur |
| **HOW_TO_APPLY.md** | how to apply guardrails to repositories | When setting up agent guardrails |
| **TESTING_VALIDATION.md** | Validation functions and git diff verification | Before committing changes |
| **COMMIT_WORKFLOW.md** | Guidelines for commits between to-dos | After completing each task |
| **GIT_PUSH_PROCEDURES.md** | Pre-push checklist and safety rules | Before pushing to remote |
| **BRANCH_STRATEGY.md** | Git branching conventions (feature/hotfix/release) | When creating branches |
| **ROLLBACK_PROCEDURES.md** | Recovery commands for all scenarios | When errors occur |
| **MCP_CHECKPOINTING.md** | MCP server checkpoint integration | Before/after critical tasks |
| **DOCUMENTATION_UPDATES.md** | Post-sprint documentation procedures | After completing sprints |
| **MODULAR_DOCUMENTATION.md** | 500-line max rule and splitting strategies | When writing docs |
| **LOGGING_PATTERNS.md** | Array-based structured logging format | When implementing logging |
| **LOGGING_INTEGRATION.md** | Webhook/file/queue integration hooks | When adding external logging |
| **API_SPECIFICATIONS.md** | OpenAPI vs OpenSpec guidance | When documenting APIs |
| **SECRETS_MANAGEMENT.md** | GitHub Secrets setup and rotation | When handling credentials |
| **examples/** | Multi-language guardrails implementation examples | When exploring code examples |
| **regression-prevention/** | Bug tracking & regression prevention examples | When logging bugs or creating prevention rules |
| **mcp-server/API.md** | Complete REST API reference for MCP server | When integrating with MCP server |
| **mcp-server/CHANGELOG.md** | MCP server version history | When tracking MCP server updates |
| **SPRINT_TEMPLATE.md** | Copy-paste template for new sprints | When creating tasks |
| **SPRINT_GUIDE.md** | Best practices for writing sprints | When writing sprint docs |
| **PROJECT_CONTEXT_TEMPLATE.md** | Project Bible - stack, style, forbidden patterns | When setting up new project |
| **ADVERSARIAL_TESTING.md** | Breaker agent, fuzz testing, attack vectors | When security testing |
| **AGENT_REVIEW_PROTOCOL.md** | Post-work verification by another agent/LLM | After completing major work |
| **DEPENDENCY_GOVERNANCE.md** | Package allow-list, license compliance | When adding dependencies |
| **INFRASTRUCTURE_STANDARDS.md** | IaC, Terraform, no-ClickOps | When managing infrastructure |
| **OPERATIONAL_PATTERNS.md** | Health checks, circuit breakers, retry | When implementing services |
| **AGENTS_AND_SKILLS_SETUP.md** | Setup agents and skills for all AI platforms | When configuring AI tools |
| **CLCODE_INTEGRATION.md** | Claude Code skills and hooks integration | When using Claude Code |
| **OPENCODE_INTEGRATION.md** | OpenCode agents and skills integration | When using OpenCode |
| **CURSOR_INTEGRATION.md** | Cursor rules and guardrails integration | When using Cursor |
| **GENERIC_LLM_INTEGRATION.md** | Generic/local LLM configuration (Ollama, vLLM, etc.) | When using custom LLMs |
| **2026_GAME_DESIGN.md** | Game design guardrails, XR comfort zones, platform budgets | When building game interfaces or spatial UIs |
| **3D_GAME_DEVELOPMENT.md** | 3D game dev guardrails v1.0: engine-agnostic, asset pipeline, physics | When building 3D games with AI assistance |
| **3D_GUARDREL_PROPOSALS_V1.2.md** | Proposed v1.2 additions: neural fields, procedural geometry, AI NPCs | When reviewing next-gen 3D guardrails |
| **3D_MATHEMATICAL_FOUNDATIONS.md** | Linear algebra, quaternions, collision math for AI-generated 3D code | When generating 3D math code |
| **3D_MODULE_ARCHITECTURE.md** | Module architecture bridging LLMs with deterministic 3D engines | When architecting 3D game systems |
| **AI_DEBUGGABLE_3D_ARCHITECTURE.md** | Patterns enabling AI agents to debug 3D features autonomously | When designing debuggable 3D systems |
| **AI_DEV_2026_PART01_INTRO_AND_FOUNDATIONS.md** | AI-Powered Development 2026 Part 1: Introduction & Foundations | When starting the AI 2026 guide series |
| **AI_DEV_2026_PART02_PROMPTING.md** | AI-Powered Development 2026 Part 2: Prompt Engineering for Code | When learning prompt engineering |
| **AI_DEV_2026_PART03_CONTEXT_AND_ITERATION.md** | AI-Powered Development 2026 Part 3: Context & Iterative Development | When managing context windows and iteration |
| **AI_DEV_2026_PART04_QUALITY_AND_ARCHITECTURE.md** | AI-Powered Development 2026 Part 4: Quality & Architecture | When debugging, testing, and architecting with AI |
| **AI_DEV_2026_PART05_LEGACY_AND_AGENTS.md** | AI-Powered Development 2026 Part 5: Legacy & Agent Paradigm | When refactoring legacy code or moving to agents |
| **AI_DEV_2026_PART06_BUILDING_AGENTS.md** | AI-Powered Development 2026 Part 6: Building Agents & Tool Use | When building custom development agents |
| **AI_DEV_2026_PART07_MULTI_AGENT_SYSTEMS.md** | AI-Powered Development 2026 Part 7: Multi-Agent Systems | When implementing MoA and agent swarms |
| **AI_DEV_2026_PART08_SECURITY_ETHICS_FUTURE.md** | AI-Powered Development 2026 Part 8: Security, Ethics & Future | When evaluating responsible AI development |
| **AI_DEV_2026_PART09_APPENDICES_ABC.md** | AI-Powered Development 2026 Part 9: Appendices A, B & C | When referencing prompt patterns, local environments, case studies |
| **AI_DEV_2026_PART10_APPENDIX_D.md** | AI-Powered Development 2026 Part 10: Appendix D — Complete MoA Reference | When implementing MoA pipelines |
| **HERMES_2026_PART01_INTRO_AND_EXECUTIVE.md** | AI in 3D Game Development 2026 Part 1: Introduction & Executive Summary | When starting the dossier series |
| **HERMES_2026_PART02_ASSETS_AND_ENGINES.md** | AI in 3D Game Development 2026 Part 2: 3D Asset Generation & Engine Integration | When researching AI asset pipelines |
| **HERMES_2026_PART03_WORLD_AND_RENDERING.md** | AI in 3D Game Development 2026 Part 3: World Generation & Neural Rendering | When researching procedural worlds and rendering |
| **HERMES_2026_PART04_NPCS_AND_ANIMATION.md** | AI in 3D Game Development 2026 Part 4: NPCs, Dialogue & Animation | When researching AI characters and motion |
| **HERMES_2026_PART05_CODE_AND_PHYSICS.md** | AI in 3D Game Development 2026 Part 5: Code Generation & Neural Physics | When researching AI code gen and simulation |
| **HERMES_2026_PART06_QA_AND_BUSINESS.md** | AI in 3D Game Development 2026 Part 6: QA, Testing & Business Landscape | When researching AI QA and market trends |
| **HERMES_2026_PART07_LEGAL_AND_CASES.md** | AI in 3D Game Development 2026 Part 7: Legal, Ethics & Case Studies | When researching legal and ethical implications |
| **HERMES_2026_PART08_DEEP_DIVES_AND_FUTURE.md** | AI in 3D Game Development 2026 Part 8: Technology Deep-Dives & Future Outlook | When researching specific tools and future predictions |
| **HERMES_2026_PART09_APPENDICES.md** | AI in 3D Game Development 2026 Part 9: Appendices | When referencing glossary, tools, and sources |
| **2026_UI_UX_STANDARD.md** | UI/UX component patterns, design tokens, animation | When implementing UI components |
| **ACCESSIBILITY_GUIDE.md** | WCAG 3.0+ compliance, perceptual/cognitive/physical a11y | When ensuring accessibility compliance |
| **SPATIAL_COMPUTING_UI.md** | XR/VR/AR layout patterns, comfort zones, latency | When building spatial computing interfaces |
| **ETHICAL_ENGAGEMENT.md** | Dark pattern taxonomy, ethical design principles | When reviewing engagement patterns |
| **AI_ASSISTED_DEV.md** | AI development patterns, decision matrix, vibe coding workflow | When implementing AI-first rapid development |
| **STATE_MANAGEMENT.md** | State architecture decision tree, client/server/offline/CRDT patterns | When designing state management |
| **GENERATIVE_ASSET_SAFETY.md** | AI content disclosure, C2PA metadata, procedural generation safety | When handling AI-generated assets |
| **MONETIZATION_GUARDRAILS.md** | IAP ethics, loot box transparency, virtual economy balance | When implementing monetization |
| **MULTIPLAYER_SAFETY.md** | Social safety, chat moderation, matchmaking fairness, CSAM detection | When building multiplayer systems |
| **ANALYTICS_ETHICS.md** | Consent tiers, data minimization, A/B testing ethics | When implementing analytics |
| **CROSS_PLATFORM_DEPLOYMENT.md** | App store compliance matrix, CI/CD, feature flags, progressive rollout | When deploying across platforms |
| **vibe-coding.md** | Canonical vibe coding principles (5 principles) | When establishing rapid development culture |
| **examples/flutter/cross-platform/** | Flutter guardrails: config, ethical widgets, accessibility wrappers | When implementing Flutter guardrails |
| **examples/gdscript/godot-game/** | Godot GDScript: comfort zones, ethical UI, accessibility manager | When implementing Godot GDScript guardrails |
---
## Category Index
### AI Tools Integration
- `AGENTS_AND_SKILLS_SETUP.md` - Setup guide for all AI platforms (Claude Code, OpenCode, Cursor, Copilot, etc.)
- `CLCODE_INTEGRATION.md` - Claude Code skills and hooks
- `OPENCODE_INTEGRATION.md` - OpenCode agents and skills
- `CURSOR_INTEGRATION.md` - Cursor rules configuration
- `GENERIC_LLM_INTEGRATION.md` - Generic/local LLM setup (Ollama, vLLM, etc.)
### Git Operations
- `COMMIT_WORKFLOW.md` - Commit timing and format
- `GIT_PUSH_PROCEDURES.md` - Push safety and verification
- `BRANCH_STRATEGY.md` - Branch naming and workflow
- `ROLLBACK_PROCEDURES.md` - Undo and recovery
### Quality & Validation
- `TESTING_VALIDATION.md` - Pre/post validation checks
- `CODE_REVIEW.md` - Review process and escalation
- `AGENT_GUARDRAILS.md` - Safety protocols (MANDATORY)
- `AGENT_REVIEW_PROTOCOL.md` - Post-work agent/LLM review
- `ADVERSARIAL_TESTING.md` - Breaker agent and fuzz testing
- `AGENTS_AND_SKILLS_SETUP.md` - Setup guide for Claude Code/OpenCode
- `RULES_FROM_MD.md` - Extracting prevention rules from markdown
- `RULES_INDEX_MAP.md` - Master index of all prevention rules
- `MCP_TOOLS_REFERENCE.md` - MCP validation tools documentation
- `RULE_PATTERNS_GUIDE.md` - Pattern authoring guide
### Logging & Monitoring
- `LOGGING_PATTERNS.md` - Structured log format
- `LOGGING_INTEGRATION.md` - External system hooks
- `MCP_CHECKPOINTING.md` - State checkpoints
### Documentation Standards
- `MODULAR_DOCUMENTATION.md` - 500-line rule
- `DOCUMENTATION_UPDATES.md` - Post-sprint updates
- `API_SPECIFICATIONS.md` - API doc formats
### Security
- `SECRETS_MANAGEMENT.md` - GitHub Secrets
- `AGENT_GUARDRAILS.md` - Forbidden actions
- `ADVERSARIAL_TESTING.md` - Security attack checklists
- `DEPENDENCY_GOVERNANCE.md` - Package allow-list
### Infrastructure & Operations
- `INFRASTRUCTURE_STANDARDS.md` - IaC and Terraform standards
- `OPERATIONAL_PATTERNS.md` - Health checks, circuit breakers, retry
### 2026 Game Design & UI/UX
- `2026_GAME_DESIGN.md` - Game design guardrails, XR/VR comfort zones, platform rules
- `3D_GAME_DEVELOPMENT.md` - 3D game development guardrails v1.0, engine-agnostic patterns
- `3D_GUARDREL_PROPOSALS_V1.2.md` - Proposed v1.2 additions from Hermes 2026 AI Dossier review
- `3D_MATHEMATICAL_FOUNDATIONS.md` - Linear algebra, quaternions, collision math reference
- `3D_MODULE_ARCHITECTURE.md` - Module architecture for LLM-to-3D-engine bridging
- `AI_DEBUGGABLE_3D_ARCHITECTURE.md` - AI-debuggable patterns for autonomous 3D troubleshooting
- `AI_DEV_2026_PART01_INTRO_AND_FOUNDATIONS.md` - Part 1: Introduction & Foundations
- `AI_DEV_2026_PART02_PROMPTING.md` - Part 2: Prompt Engineering for Code
- `AI_DEV_2026_PART03_CONTEXT_AND_ITERATION.md` - Part 3: Context & Iterative Development
- `AI_DEV_2026_PART04_QUALITY_AND_ARCHITECTURE.md` - Part 4: Quality & Architecture
- `AI_DEV_2026_PART05_LEGACY_AND_AGENTS.md` - Part 5: Legacy & Agent Paradigm
- `AI_DEV_2026_PART06_BUILDING_AGENTS.md` - Part 6: Building Agents & Tool Use
- `AI_DEV_2026_PART07_MULTI_AGENT_SYSTEMS.md` - Part 7: Multi-Agent Systems
- `AI_DEV_2026_PART08_SECURITY_ETHICS_FUTURE.md` - Part 8: Security, Ethics & Future
- `AI_DEV_2026_PART09_APPENDICES_ABC.md` - Part 9: Appendices A, B & C
- `AI_DEV_2026_PART10_APPENDIX_D.md` - Part 10: Appendix D — Complete MoA Reference
- `HERMES_2026_PART01_INTRO_AND_EXECUTIVE.md` - Part 1: Introduction & Executive Summary
- `HERMES_2026_PART02_ASSETS_AND_ENGINES.md` - Part 2: 3D Asset Generation & Engine Integration
- `HERMES_2026_PART03_WORLD_AND_RENDERING.md` - Part 3: World Generation & Neural Rendering
- `HERMES_2026_PART04_NPCS_AND_ANIMATION.md` - Part 4: NPCs, Dialogue & Animation
- `HERMES_2026_PART05_CODE_AND_PHYSICS.md` - Part 5: Code Generation & Neural Physics
- `HERMES_2026_PART06_QA_AND_BUSINESS.md` - Part 6: QA, Testing & Business Landscape
- `HERMES_2026_PART07_LEGAL_AND_CASES.md` - Part 7: Legal, Ethics & Case Studies
- `HERMES_2026_PART08_DEEP_DIVES_AND_FUTURE.md` - Part 8: Technology Deep-Dives & Future Outlook
- `HERMES_2026_PART09_APPENDICES.md` - Part 9: Appendices
- `2026_UI_UX_STANDARD.md` - UI/UX component standards, design tokens, responsive patterns
- `ACCESSIBILITY_GUIDE.md` - WCAG 3.0+ conformance (Bronze/Silver/Gold), automated testing
- `SPATIAL_COMPUTING_UI.md` - XR/VR/AR comfort zones, latency, depth layering, interaction
- `ETHICAL_ENGAGEMENT.md` - Dark pattern taxonomy, ethical review capabilities
### Project Setup
- `PROJECT_CONTEXT_TEMPLATE.md` - Project Bible template
### Sprint Framework
- `SPRINT_TEMPLATE.md` - Task template
- `SPRINT_GUIDE.md` - Writing guide
- `INDEX.md` (sprints/) - Sprint navigation
---
## Directory Structure
```
agent-guardrails-template/
├── INDEX_MAP.md ← YOU ARE HERE
├── TOC.md ← Complete file listing and contents
├── HEADER_MAP.md # Section-level lookup
├── CLAUDE.md # Claude Code CLI config
├── .claudeignore # Token-saving ignores
├── CHANGELOG.md # Release notes archive
├── docs/
│ ├── AGENT_GUARDRAILS.md # Core safety (MANDATORY)
│ ├── HOW_TO_APPLY.md # How to apply to repos
│ ├── AGENTS_AND_SKILLS_SETUP.md # Setup guide for Claude Code/OpenCode
│ ├── CLCODE_INTEGRATION.md # Claude Code integration
│ ├── OPCODE_INTEGRATION.md # OpenCode integration
│ ├── workflows/
│ │ ├── INDEX.md
│ │ ├── AGENT_EXECUTION.md # Execution protocol
│ │ ├── AGENT_ESCALATION.md # Audit & escalation
│ │ ├── TESTING_VALIDATION.md
│ │ ├── COMMIT_WORKFLOW.md
│ │ ├── DOCUMENTATION_UPDATES.md
│ │ ├── GIT_PUSH_PROCEDURES.md
│ │ ├── MCP_CHECKPOINTING.md
│ │ ├── BRANCH_STRATEGY.md
│ │ ├── CODE_REVIEW.md
│ │ ├── AGENT_REVIEW_PROTOCOL.md # Post-work agent review
│ │ └── ROLLBACK_PROCEDURES.md
│ ├── standards/
│ │ ├── INDEX.md
│ │ ├── TEST_PRODUCTION_SEPARATION.md # Test/production isolation (MANDATORY)
│ │ ├── PROJECT_CONTEXT_TEMPLATE.md # Project Bible template
│ │ ├── ADVERSARIAL_TESTING.md # Breaker agent, fuzz testing
│ │ ├── DEPENDENCY_GOVERNANCE.md # Package allow-list
│ │ ├── INFRASTRUCTURE_STANDARDS.md # IaC, Terraform, drift
│ │ ├── OPERATIONAL_PATTERNS.md # Health checks, circuit breakers
│ │ ├── MODULAR_DOCUMENTATION.md
│ │ ├── LOGGING_PATTERNS.md
│ │ ├── LOGGING_INTEGRATION.md
│ │ └── API_SPECIFICATIONS.md
│ ├── sprints/
│ ├── INDEX.md
│ ├── SPRINT_TEMPLATE.md
│ ├── SPRINT_GUIDE.md
│ └── archive/
│ ├── game-design/
│ │ └── 2026_GAME_DESIGN.md # Game design guardrails, XR comfort
│ ├── ui-ux/
│ │ └── 2026_UI_UX_STANDARD.md # UI/UX components, design tokens
│ ├── accessibility/
│ │ └── ACCESSIBILITY_GUIDE.md # WCAG 3.0+ compliance
│ ├── spatial/
│ │ └── SPATIAL_COMPUTING_UI.md # XR/VR/AR patterns
│ └── ethical/
│ └── ETHICAL_ENGAGEMENT.md # Dark pattern prevention
├── examples/ ← Multi-language implementation examples
│ ├── go/
│ ├── java/
│ ├── python/
│ ├── ruby/
│ ├── regression-prevention/ # Bug tracking examples
│ ├── rust/
│ └── typescript/
├── scripts/ ← Setup and utility scripts
│ └── setup_agents.py # CLI tool to generate agent configs
├── .github/
│ ├── SECRETS_MANAGEMENT.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── workflows/
│ │ ├── secret-validation.yml
│ │ ├── documentation-check.yml
│ │ └── guardrails-lint.yml
│ └── ISSUE_TEMPLATE/
│ └── bug_report.md
└── README.md
```
---
## Usage Instructions
### For AI Agents
1. **Always read INDEX_MAP.md first** before exploring documentation
2. Use the Quick Lookup Table to find relevant documents by keyword
3. Check HEADER_MAP.md for specific section line numbers
4. Read only the sections you need using line offset parameters
5. For mandatory safety protocols, always read AGENT_GUARDRAILS.md
### For Humans
1. Use Category Index to browse by topic
2. Document Summaries tell you when to use each doc
3. Directory Structure shows the full file layout
---
## Cross-Reference Quick Links
| If you need... | Read... |
|----------------|---------|
| Safety rules before editing | AGENT_GUARDRAILS.md |
| How to validate changes | TESTING_VALIDATION.md |
| When to commit | COMMIT_WORKFLOW.md |
| How to handle errors | ROLLBACK_PROCEDURES.md |
| Logging format | LOGGING_PATTERNS.md |
| Secret handling | SECRETS_MANAGEMENT.md |
| Creating a new task | SPRINT_TEMPLATE.md |
| Setting up AI tools | AGENTS_AND_SKILLS_SETUP.md |
| Claude Code integration | CLCODE_INTEGRATION.md |
| OpenCode integration | OPCODE_INTEGRATION.md |
| Cursor integration | CURSOR_INTEGRATION.md |
| Generic LLM integration | GENERIC_LLM_INTEGRATION.md |
| MCP rule extraction | RULES_FROM_MD.md |
| Prevention rules index | RULES_INDEX_MAP.md |
| MCP tools reference | MCP_TOOLS_REFERENCE.md |
| Pattern authoring | RULE_PATTERNS_GUIDE.md |
| Game design guardrails | 2026_GAME_DESIGN.md |
| 3D game development guardrails | 3D_GAME_DEVELOPMENT.md |
| 3D math reference | 3D_MATHEMATICAL_FOUNDATIONS.md |
| 3D architecture blueprint | 3D_MODULE_ARCHITECTURE.md |
| AI-debuggable 3D patterns | AI_DEBUGGABLE_3D_ARCHITECTURE.md |
| AI development 2026 guide | AI_DEV_2026_PART01_INTRO_AND_FOUNDATIONS.md |
| AI 2026 prompt engineering | AI_DEV_2026_PART02_PROMPTING.md |
| AI 2026 context & iteration | AI_DEV_2026_PART03_CONTEXT_AND_ITERATION.md |
| AI 2026 quality & architecture | AI_DEV_2026_PART04_QUALITY_AND_ARCHITECTURE.md |
| AI 2026 legacy & agents | AI_DEV_2026_PART05_LEGACY_AND_AGENTS.md |
| AI 2026 building agents | AI_DEV_2026_PART06_BUILDING_AGENTS.md |
| AI 2026 multi-agent systems | AI_DEV_2026_PART07_MULTI_AGENT_SYSTEMS.md |
| AI 2026 security & ethics | AI_DEV_2026_PART08_SECURITY_ETHICS_FUTURE.md |
| AI 2026 appendices | AI_DEV_2026_PART09_APPENDICES_ABC.md |
| AI 2026 MoA reference | AI_DEV_2026_PART10_APPENDIX_D.md |
| AI in 3D games dossier | HERMES_2026_PART01_INTRO_AND_EXECUTIVE.md |
| Hermes assets & engines | HERMES_2026_PART02_ASSETS_AND_ENGINES.md |
| Hermes world & rendering | HERMES_2026_PART03_WORLD_AND_RENDERING.md |
| Hermes NPCs & animation | HERMES_2026_PART04_NPCS_AND_ANIMATION.md |
| Hermes code & physics | HERMES_2026_PART05_CODE_AND_PHYSICS.md |
| Hermes QA & business | HERMES_2026_PART06_QA_AND_BUSINESS.md |
| Hermes legal & cases | HERMES_2026_PART07_LEGAL_AND_CASES.md |
| Hermes deep-dives & future | HERMES_2026_PART08_DEEP_DIVES_AND_FUTURE.md |
| Hermes appendices | HERMES_2026_PART09_APPENDICES.md |
| UI/UX component standards | 2026_UI_UX_STANDARD.md |
| Accessibility (WCAG 3.0+) | ACCESSIBILITY_GUIDE.md |
| Spatial computing / XR / VR | SPATIAL_COMPUTING_UI.md |
| Dark pattern prevention | ETHICAL_ENGAGEMENT.md |
---
**Authored by:** TheArchitectit
**Document Owner:** Project Maintainers
**Last Updated:** 2026-05-12
**Document Count:** 103 (excluding INDEX files)
**Line Count:** ~280
---
## Canonical Sources
To avoid duplication, always reference these canonical sources:
| Content | Canonical Location | Reference In |
|---------|-------------------|--------------|
| Four Laws | skills/shared-prompts/four-laws.md | docs/AGENT_GUARDRAILS.md |
| Halt Conditions | skills/shared-prompts/halt-conditions.md | Workflows, integration docs |
---
## Oversized Documents
The following files exceed the 500-line limit and should be split per MODULAR_DOCUMENTATION.md:
| File | Lines | Action Needed |
|------|-------|---------------|
| docs/plans/MCP_SERVER_PLAN.md | 2093 | Split into multiple files |
| docs/sprints/SPRINT_002_WEB_UI_IMPLEMENTATION.md | 768 | Split or archive |
| docs/sprints/SPRINT_003_DOCUMENTATION_PARITY.md | 754 | Split or archive after completion |
| HEADER_MAP.md | 822 | Navigation file - exempt |
| docs/standards/OPERATIONAL_PATTERNS.md | 667 | Split |
| docs/workflows/AGENT_REVIEW_PROTOCOL.md | 638 | Split |
| docs/security/SECURITY_AUDIT_CONFIG.md | 597 | Split |
| README.md | 565 | Landing page - exempt |

30
.guardrails/LICENSE Normal file
View File

@ -0,0 +1,30 @@
BSD 3-Clause License
Copyright (c) 2026, TheArchitectit
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

361
.guardrails/PROJECT_PLAN.md Normal file
View File

@ -0,0 +1,361 @@
# Project Sentinel: Comprehensive Implementation Plan
**Version:** 3.0.0-Enterprise
**Status:** Ready for Development
**Total Estimated Effort:** 370k tokens (~$20-30 in API costs)
**Target Release:** Q2 2026
---
## Executive Summary
Project Sentinel is an active governance layer for Autonomous AI Agents. Unlike passive templates, Sentinel uses a compiled MCP server to physically enforce safety, security, and financial guardrails.
**Core Value Proposition:**
- **Active Enforcement**: Transforms "soft laws" into "hard physics"
- **Financial Governance**: Token budgeting prevents runaway API costs
- **Security**: VFS Jail prevents access to .env, ~/.ssh, and other restricted paths
- **Polyglot Support**: Native toolchains for 12+ programming languages
---
## Architecture Overview
### The Four Pillars
1. **Cortex (State Machine)**
- Finite State Machine: IDLE → PLANNING → ACTIVE → REVIEW → RELEASE
- One-task-at-a-time enforcement
- State-based tool availability (deploy only available in RELEASE)
2. **Jailor (VFS Security)**
- Path traversal protection (../../../etc/passwd blocked)
- Immutable core files (services/sentinel/*, .git/*, .sentinel/*)
- Read-only file enforcement
3. **Interceptor (Audit & PII)**
- Automatic secret redaction (sk-*, AKIA*, etc.)
- SQLite audit vault
- Real-time event streaming via gRPC
4. **Polyglot Engine**
- Auto-detection: go.mod, package.json, Cargo.toml, pom.xml
- Abstracted commands: run_tests(), build(), lint()
- Cross-platform execution (Linux/Mac/Windows)
---
## Implementation Phases
### PHASE 1: Kernel Foundation (120k tokens)
**Duration:** 2-3 weeks
**Output:** Basic `bin/sentinel` binary with SQLite + VFS Jail
#### Sprint 1.1: Boilerplate & Database
- [ ] **T-101: Project Structure**
- Initialize Go module: `github.com/TheArchitectit/agent-guardrails-template/services/sentinel`
- Create directory structure: cmd/, internal/kernel, internal/state, internal/audit
- Add dependencies: modernc.org/sqlite, mark3labs/mcp-go
- Create Makefile (build, test, clean)
- **Acceptance**: `go build` produces binary, runs without panic
- [ ] **T-102: SQLite Store & Migrator**
- Implement `internal/state/store.go`
- Create tables: schema_version, system_config, sprints, tasks, audit_log
- Enable WAL mode: `PRAGMA journal_mode=WAL`
- **Acceptance**: Migrations are idempotent, temp DB test passes
- [ ] **T-103: Audit Logger**
- Implement `internal/audit/logger.go`
- Add PII scrubbing regex (sk-*, AKIA*, high-entropy tokens)
- Dual output: Stderr + SQLite
- **Acceptance**: "sk-1234567890abcdef" → "[REDACTED]" in DB
#### Sprint 1.2: VFS Jail (Security Kernel)
- [ ] **T-104: Path Sanitization**
- Implement `kernel.ValidatePath(requested, operation)`
- filepath.Abs + filepath.Clean
- Prefix check (must start with Root)
- DenyList regex: .git, .env, id_rsa, services/sentinel
- **Acceptance**: "../../../etc/passwd" → Error, ".env" → Error
- [ ] **T-105: Safe IO Wrappers**
- Implement `kernel.ReadFile(path) []byte`
- Implement `kernel.WriteFile(path, data) error`
- Auto-create directories with MkdirAll
- Check sentinel.toml for read-only files
- **Acceptance**: Writing to "foo/bar/baz.txt" creates intermediate dirs
#### Sprint 1.3: Basic MCP Server
- [ ] **T-106: MCP Server Skeleton**
- Implement `kernel.StartMCP()`
- Register get_sentinel_status tool
- Stdio listener for Claude Desktop/Cursor compatibility
- **Acceptance**: Agent can call `get_sentinel_status` and receive JSON
---
### PHASE 2: Logic & Tooling (150k tokens)
**Duration:** 3-4 weeks
**Prerequisites:** Phase 1 complete
**Output:** Full-featured MCP server with polyglot support
#### Sprint 2.1: Polyglot Toolchain Engine
- [ ] **T-201: Language Detection**
- Implement `toolchain.DetectLanguage(root)`
- Check for: go.mod, package.json (+ lockfiles), Cargo.toml, pom.xml, flake.nix
- Return Profile struct with TestCmd, BuildCmd, LintCmd
- **Acceptance**: Running on this repo returns Go profile
- [ ] **T-202: Command Abstraction Layer**
- Implement `toolchain.ExecuteCommand(ctx, cmd)`
- Windows support via cmd.exe wrapping
- SanitizeEnv() to strip AWS_SECRET_KEY, GH_TOKEN
- **Acceptance**: `go version` executes successfully, env vars scrubbed
- [ ] **T-203: run_tests Tool**
- Register run_tests MCP tool
- Auto-detect language → Get TestCmd → Execute
- Parse output for "FAIL" patterns
- **Acceptance**: Broken project returns compiler error in tool output
#### Sprint 2.2: Workflow & State Enforcement
- [ ] **T-204: Sprint & Task CRUD**
- Implement `kernel.StartSprint(name, goals)`
- Implement `kernel.AddTask(title, complexity)`
- DB operations for sprints/tasks tables
- **Acceptance**: Can create sprint, add 3 tasks, query them back
- [ ] **T-205: State Machine Logic**
- Implement state transitions: IDLE → PLANNING → ACTIVE → REVIEW → RELEASE
- Block operations based on state (no coding in PLANNING)
- Enforce "One Task at a Time" rule
- **Acceptance**: Cannot start second task while first is active
- [ ] **T-206: Git Integration**
- Register git_commit tool with Conventional Commits enforcement
- Register git_push tool with main-branch protection
- Pre-commit verification (check recent test results)
- **Acceptance**: "wip: update" rejected, must use "feat: ..."
#### Sprint 2.3: Cost Governance
- [ ] **T-207: Token Estimator**
- Implement `cost.EstimateFileRead(path)`
- Heuristic: 3.5 chars/token for code, 4.0 for text
- Cost calculation based on OpenAI/Anthropic rates
- **Acceptance**: Reading 50KB file shows estimated cost
- [ ] **T-208: Budget Ledger**
- Implement `ledger.CheckBudget(cost, sprintID)`
- Track token usage per sprint
- Block operations when budget exceeded
- **Acceptance**: $0.50 budget blocks after $0.50 spent
---
### PHASE 3: Integration & Release (100k tokens)
**Duration:** 2-3 weeks
**Prerequisites:** Phase 2 complete
**Output:** Enterprise release v3.0.0
#### Sprint 3.1: REST API Gateway
- [ ] **T-301: HTTP Server**
- Implement `api/gateway.go` using chi router
- Endpoints: /health, /v1/sprint, /v1/tasks, /v1/audit
- Auth middleware (Bearer token for non-localhost)
- **Acceptance**: `curl localhost:8080/v1/status` returns JSON
- [ ] **T-302: Policy Check Endpoint**
- POST /v1/policy/check for CI/CD integration
- Returns ALLOWED/BLOCKED without writing files
- VFS check + PII scan
- **Acceptance**: CI pipeline can validate files before commit
#### Sprint 3.2: gRPC Service & Events
- [ ] **T-303: Event Bus**
- Implement `api/event_bus.go`
- Pub/sub for: SECURITY_VIOLATION, TASK_UPDATE, FILE_CHANGE
- Channel-based subscriptions
- **Acceptance**: Security event publishes to all subscribers
- [ ] **T-304: gRPC Server**
- Define proto/sentinel.proto (LogStream, ExecuteTool)
- Implement streaming logs for IDEs
- mTLS authentication
- **Acceptance**: JetBrains plugin receives real-time alerts
#### Sprint 3.3: Containerization & Deployment
- [ ] **T-305: Docker Image**
- Multi-stage Dockerfile (Alpine-based)
- Entry point: `sentinel serve --mode=remote`
- **Acceptance**: `docker run sentinel` starts successfully
- [ ] **T-306: Remote Mode**
- CLI flag --host (default 127.0.0.1, remote uses 0.0.0.0)
- Require SENTINEL_TOKEN in remote mode
- **Acceptance**: Container fails without token env var
#### Sprint 3.4: IDE Integration
- [ ] **T-307: LSP Diagnostics**
- Lint errors as IDE diagnostics
- "Guardrail Violation" severity level
- **Acceptance**: VS Code shows red underline on blocked file
- [ ] **T-308: Installation Scripts**
- `curl https://releases.project-sentinel.io/install.sh | sh`
- `sentinel init --root .`
- **Acceptance**: Single-command install for developers
---
## Testing Strategy
### Unit Tests
- **Kernel**: State transitions, path validation
- **Jailor**: Path traversal attacks, PII scrubbing
- **Toolchain**: Language detection, command execution
- **Cost**: Token estimation accuracy
### Integration Tests
- **MCP Server**: Tool registration and execution
- **Database**: Migration idempotency
- **Git**: Commit/push workflows
### Security Tests
- **Path Traversal**: ../../../etc/passwd, ..\..\..\windows\system32
- **Secret Leakage**: sk-*, AKIA*, passwords in logs
- **State Bypass**: Try to deploy in PLANNING state
### E2E Tests
- **Full Sprint**: Create sprint → Add tasks → Complete → Archive
- **Budget Enforce**: Exceed budget → Verify operations blocked
- **CI/CD**: Pipeline calls /v1/policy/check
---
## Success Criteria
### Phase 1 Gates
- [ ] Binary compiles on Linux, Mac, Windows
- [ ] SQLite migrations are idempotent
- [ ] Path traversal attacks are blocked
- [ ] PII is scrubbed from audit logs
### Phase 2 Gates
- [ ] Detects Go, Python, TypeScript, Rust, Java
- [ ] State machine enforces SDLC phases
- [ ] Token estimation within 10% margin
- [ ] Git commits enforce Conventional Commits
### Phase 3 Gates
- [ ] REST API serves all endpoints
- [ ] gRPC streams events in real-time
- [ ] Docker image runs in container
- [ ] IDE receives diagnostics
---
## Risk Mitigation
### Technical Risks
1. **SQLite Concurrency**
- Mitigation: WAL mode enabled by default
- Timeout: 5000ms for busy handler
2. **Path Detection Complexity**
- Mitigation: Start with 5 core languages (Go, Python, TS, Rust, Java)
- Fallback: Manual sentinel.toml configuration
3. **Token Estimation Accuracy**
- Mitigation: 10% error margin acceptable for guardrails
- Refinement: Track actual vs. estimated for model improvement
### Operational Risks
1. **Agent Resistance**
- Mitigation: Transparent error messages explain why blocked
- Documentation: Clear guides for each guardrail
2. **Performance Overhead**
- Mitigation: Asynchronous logging
- Measurement: Benchmark <50ms for path validation
3. **Language Drift**
- Mitigation: Modular language profiles (easy to add new ones)
- Community: Contributions for new languages
---
## Resource Requirements
### Development
- **Go Expert**: Full-time (40 hrs/week)
- **DevOps Engineer**: Part-time (10 hrs/week) for Phase 3
- **Security Reviewer**: On-call for audit
### Infrastructure
- **CI/CD**: GitHub Actions (already configured)
- **Releases**: GitHub Releases for binaries
- **Registry**: Docker Hub for container image
### Budget
- **Development API Costs**: ~$30 (370k tokens)
- **Testing Costs**: ~$20 (E2E test runs)
- **Total Estimated**: ~$50
---
## Timeline
```
Phase 1: Week 1-3 (Kernel Foundation)
├─ Sprint 1.1: Week 1
├─ Sprint 1.2: Week 2
└─ Sprint 1.3: Week 3
Phase 2: Week 4-7 (Logic & Tooling)
├─ Sprint 2.1: Week 4-5
├─ Sprint 2.2: Week 6
└─ Sprint 2.3: Week 7
Phase 3: Week 8-10 (Integration & Release)
├─ Sprint 3.1: Week 8
├─ Sprint 3.2: Week 9
└─ Sprint 3.3-3.4: Week 10
Release: Week 11 (v3.0.0-Enterprise)
```
---
## Post-Launch Roadmap
### v3.1 (Enhanced Languages)
- PHP, Ruby, Scala, Swift, Kotlin profiles
- NixOS/flake support enhancement
- WASM sandboxing option
### v3.2 (Cloud Native)
- Kubernetes operator
- Multi-agent coordination (swarm mode)
- Distributed audit log (PostgreSQL)
### v4.0 (AI Integration)
- LLM-hosted mode (Sentinel as an agent)
- Self-healing capabilities
- Predictive budgeting
---
## Compliance & Licensing
- **License**: BSD-3-Clause
- **Compliance**: SOC 2 Type II (target Q3 2026)
- **Data**: No telemetry sent externally (local-only audit)
---
## Conclusion
Project Sentinel transforms passive guardrails into active enforcement. This 3-phase plan delivers a production-ready system that protects agents from themselves while maintaining developer autonomy.
**Next Step:** Execute Sprint 1.1 (T-101: Project Structure)

View File

@ -0,0 +1,984 @@
# Master Prompting Guide
> How to write prompts that work beautifully with Agent Guardrails
**TL;DR:** Be explicit, provide context, define scope, and the guardrails will keep your AI on track.
---
## Table of Contents
1. [The Golden Rules](#the-golden-rules)
2. [Prompt Templates](#prompt-templates)
3. [Common Patterns](#common-patterns)
4. [Advanced Techniques](#advanced-techniques)
5. [Examples by Use Case](#examples-by-use-case)
6. [Anti-Patterns to Avoid](#anti-patterns-to-avoid)
7. [Troubleshooting](#troubleshooting)
---
## The Golden Rules
### Rule 1: Start with Context
❌ **Bad:**
```
Fix the bug
```
✅ **Good:**
```
There's a bug in the authentication system where users can't log in with valid credentials.
Context:
- Repository: myapp/backend
- File: src/auth/login.js
- Error: "Invalid credentials" even with correct password
- Database: PostgreSQL
- Framework: Express.js
Task: Find and fix the login bug. The issue is likely in the password comparison logic.
```
### Rule 2: Define Scope Explicitly
❌ **Bad:**
```
Update the API
```
✅ **Good:**
```
Update the user API endpoints to add email validation.
Scope:
- File: src/routes/users.js
- Only modify POST /api/users and PUT /api/users/:id
- Do NOT touch authentication or other routes
- Add validation using Joi schema
- Return 400 if email is invalid
```
### Rule 3: Provide Constraints
❌ **Bad:**
```
Refactor the code
```
✅ **Good:**
```
Refactor the data processing module to improve readability.
Constraints:
- Keep all existing functionality
- Maintain backward compatibility
- Don't change function signatures
- Add unit tests for new helper functions
- Use existing patterns from src/utils/helpers.js
```
### Rule 4: Include Examples
❌ **Bad:**
```
Add error handling
```
✅ **Good:**
```
Add error handling to the file upload endpoint.
Current code (src/routes/upload.js):
```javascript
app.post('/upload', (req, res) => {
const file = req.files.file;
fs.writeFileSync('/uploads/' + file.name, file.data);
res.json({ success: true });
});
```
Expected behavior:
- Handle missing file: return 400 with error "No file provided"
- Handle file too large (>10MB): return 413 with error "File too large"
- Handle disk full: return 500 with error "Storage error"
- Always return JSON: { success: boolean, error?: string }
Example error response:
```json
{ "success": false, "error": "No file provided" }
```
```
> **Why explicit context enables speed:** Every detail you provide upfront is a clarification your AI agent doesn't need to ask for. Explicit context eliminates round-trips, reducing a 5-prompt conversation to a single generation. The most productive vibe coding sessions start with the richest prompts.
---
## Prompt Templates
### Template 1: Feature Implementation
```markdown
## Feature: [Feature Name]
### Context
[Background information about the feature]
### Requirements
- [ ] Requirement 1
- [ ] Requirement 2
- [ ] Requirement 3
### Scope
- Files to modify: [list files]
- Files to NOT touch: [list files]
- New files to create: [list files]
### Technical Details
- Framework: [framework]
- Language: [language]
- Patterns to follow: [reference existing code]
### Acceptance Criteria
1. [Criteria 1]
2. [Criteria 2]
3. [Criteria 3]
### Testing
- [ ] Unit tests written
- [ ] Integration tests pass
- [ ] Manual testing completed
### Additional Notes
[Any special considerations]
```
### Template 2: Bug Fix
```markdown
## Bug Fix: [Bug Title]
### Problem
[Clear description of the bug]
### Steps to Reproduce
1. Step 1
2. Step 2
3. Step 3
### Expected Behavior
[What should happen]
### Actual Behavior
[What actually happens]
### Context
- File(s) involved: [list]
- Error message: [if any]
- Environment: [dev/staging/prod]
### Root Cause (if known)
[Your analysis]
### Proposed Solution
[Your suggestion, or leave blank]
### Testing After Fix
- [ ] Reproduction steps no longer trigger bug
- [ ] Related functionality still works
- [ ] Edge cases handled
```
### Template 3: Code Review
```markdown
## Code Review Request
### PR/MR Information
- Branch: [branch name]
- Changes: [files modified]
- Lines changed: [+X, -Y]
### Focus Areas
- [ ] Logic correctness
- [ ] Edge cases
- [ ] Performance
- [ ] Security
- [ ] Style/consistency
### Specific Questions
1. [Question 1]
2. [Question 2]
### Skip These
- [ ] Nitpicks (formatting)
- [ ] Out of scope files
- [ ] Known issues
### Timeline
[Urgency level]
```
### Template 4: Refactoring
```markdown
## Refactoring: [Area]
### Current State
[What's wrong with current code]
### Target State
[What it should look like]
### Constraints
- [ ] No functionality changes
- [ ] All tests must pass
- [ ] Maintain backward compatibility
- [ ] Update documentation
### Files
- Primary: [main file(s)]
- Dependencies: [files that depend on these]
- Tests: [test files to update]
### Patterns to Follow
- [Reference to similar code]
### Success Criteria
- [ ] Code is cleaner/more readable
- [ ] All tests pass
- [ ] No regressions
```
### Template 5: Documentation
```markdown
## Documentation Task
### Type
- [ ] API docs
- [ ] User guide
- [ ] README update
- [ ] Architecture doc
- [ ] Inline comments
### Target Audience
[Who will read this]
### Content Outline
1. [Section 1]
2. [Section 2]
3. [Section 3]
### Reference Materials
- [Link 1]
- [Link 2]
### Style Guide
- [ ] Follow existing patterns
- [ ] Include code examples
- [ ] Add diagrams if helpful
- [ ] Keep under 500 lines per doc
```
---
## Common Patterns
### Pattern 1: The Scoped Request
Use this when you want to limit what the AI touches.
```markdown
Task: Add input validation to the login form
SCOPE - ONLY THESE FILES:
- src/components/LoginForm.jsx
- src/validation/auth.js (create if doesn't exist)
DO NOT TOUCH:
- Authentication logic
- Backend API
- Other components
Validation rules:
- Email must be valid format
- Password must be 8+ characters
- Show inline errors below each field
```
### Pattern 2: The Step-by-Step
Use this for complex tasks that need to be broken down.
```markdown
Task: Implement user profile page
Step 1: Create the basic component structure
- Create src/pages/Profile.jsx
- Add route in App.jsx
- Create basic layout with sections
Step 2: Add data fetching
- Fetch user data from /api/user
- Handle loading state
- Handle error state
Step 3: Add edit functionality
- Make fields editable
- Add save/cancel buttons
- Implement update API call
Step 4: Testing
- Test with different user types
- Verify error handling
- Check responsive design
PAUSE after each step and ask for confirmation before proceeding.
```
### Pattern 3: The Reference Pattern
Use this when you want the AI to follow existing patterns.
```markdown
Task: Create a new API endpoint for user preferences
Follow the exact same pattern as src/routes/users.js:
- Use the same middleware structure
- Same error handling approach
- Same response format
- Same authentication checks
Specific requirements:
- GET /api/users/:id/preferences
- PUT /api/users/:id/preferences
- Validate input using Joi (like in users.js)
- Return 404 if user not found
```
### Pattern 4: The Validation Gate
Use this when you want checkpoints.
```markdown
Task: Refactor the database layer
Before making ANY changes:
1. Read and summarize the current implementation
2. Identify all files that will be affected
3. List potential risks
4. Propose a rollback strategy
After I approve:
5. Make the changes
6. Run tests
7. Verify no regressions
Do NOT proceed past step 4 without my explicit approval.
```
### Pattern 5: The Context-Rich
Use this when the task needs lots of background.
```markdown
Task: Fix the caching issue in the product catalog
BACKGROUND:
We're experiencing cache stampede during flash sales. When a popular product's cache expires, multiple requests hit the database simultaneously, causing slowdowns.
CURRENT IMPLEMENTATION:
- File: src/services/cache.js
- Uses Redis with 5-minute TTL
- No locking mechanism
- Cache key: product:${id}
PROPOSED SOLUTION:
Implement cache warming with stale-while-revalidate pattern:
1. Serve stale data while refreshing in background
2. Add probabilistic early expiration
3. Implement request coalescing
REFERENCES:
- Similar implementation: src/services/userCache.js
- Redis docs: https://redis.io/docs/manual/patterns/
ACCEPTANCE:
- Load test shows <100ms response time during cache miss
- No database connection spikes
- Graceful degradation when Redis is down
```
---
## Advanced Techniques
### Technique 1: Progressive Disclosure
Start simple, add complexity only if needed.
```markdown
Initial Task: Create a simple user registration form
If validation passes, also:
- Add email verification
- Implement rate limiting
- Add CAPTCHA for suspicious IPs
But ONLY do the extras if the basic form works perfectly.
```
### Technique 2: Constraint Programming
Define what NOT to do explicitly.
```markdown
Task: Optimize the search query
CONSTRAINTS - NEVER DO:
- Don't use raw SQL (use ORM)
- Don't remove existing indexes
- Don't change the API response format
- Don't break pagination
- Don't ignore security (always use parameterized queries)
MUST DO:
- Add database query logging
- Keep response time under 200ms
- Handle empty results gracefully
- Maintain backward compatibility
```
### Technique 3: Example-Driven
Show exactly what you want.
```markdown
Task: Add a new component for user cards
Here's the EXACT pattern to follow (from src/components/ProductCard.jsx):
```jsx
const ProductCard = ({ product }) => {
return (
<Card>
<Card.Header>
<h3>{product.name}</h3>
</Card.Header>
<Card.Body>
<p>{product.description}</p>
<Badge>{product.category}</Badge>
</Card.Body>
</Card>
);
};
```
Now create UserCard following this EXACT same structure, just with user data instead of product data.
```
### Technique 4: Hypothetical Reasoning
Ask the AI to think through scenarios.
```markdown
Task: Implement a payment retry mechanism
Before coding, walk through these scenarios:
Scenario 1: Network timeout
- What should happen?
- How many retries?
- What's the backoff strategy?
Scenario 2: Insufficient funds
- Should we retry?
- What error message?
Scenario 3: Duplicate payment attempt
- How do we detect it?
- How do we prevent it?
After analyzing, implement the solution that handles all three.
```
### Technique 5: Role Play
Set a specific persona for better results.
```markdown
You are a senior security engineer with 10 years of experience.
Task: Review this authentication code for security vulnerabilities.
Approach:
- Think like an attacker
- Look for OWASP Top 10 issues
- Consider edge cases
- Question every assumption
Code to review:
[code here]
Provide:
1. List of vulnerabilities found
2. Severity rating for each
3. Suggested fixes with code examples
4. Any additional security recommendations
```
---
## Examples by Use Case
### Use Case 1: API Development
```markdown
Task: Create REST API endpoints for a blog
SCOPE:
- Base path: /api/v1/posts
- Files: src/routes/posts.js (new)
ENDPOINTS:
GET /api/v1/posts
- Query params: page, limit, sort
- Returns: { posts: [], total: number, page: number }
- Pagination: default 20 items per page
GET /api/v1/posts/:id
- Returns: { post: { id, title, content, author, created_at } }
- 404 if not found
POST /api/v1/posts
- Body: { title: string (required), content: string (required) }
- Validation: title min 5 chars, content min 50 chars
- Returns: { post: { id, ... } }
- 400 if validation fails with error details
PUT /api/v1/posts/:id
- Body: partial update (only provided fields)
- Returns updated post
- 404 if not found
DELETE /api/v1/posts/:id
- Returns: 204 No Content
- 404 if not found
TECHNICAL:
- Use Express.js
- Use existing auth middleware from src/middleware/auth.js
- Use existing Post model from src/models/Post.js
- Follow error handling pattern from src/routes/users.js
- Add tests in tests/routes/posts.test.js
```
### Use Case 2: Frontend Component
```markdown
Task: Create a reusable Modal component
SPECIFICATIONS:
Props:
- isOpen: boolean (required)
- onClose: function (required)
- title: string
- children: ReactNode
- size: 'small' | 'medium' | 'large' (default: 'medium')
- closeOnOverlayClick: boolean (default: true)
- showCloseButton: boolean (default: true)
Behavior:
- Click outside modal closes it (if enabled)
- ESC key closes modal
- Focus trap inside modal
- Return focus to trigger element on close
- Animate in/out (fade + scale)
Accessibility:
- aria-modal="true"
- role="dialog"
- aria-labelledby pointing to title
- Focus management
Styling:
- Use Tailwind CSS
- Backdrop: bg-black/50
- Modal: bg-white rounded-lg shadow-xl
- Sizes:
- small: max-w-md
- medium: max-w-lg
- large: max-w-2xl
Usage Example:
```jsx
<Modal
isOpen={showModal}
onClose={() => setShowModal(false)}
title="Confirm Delete"
size="small"
>
<p>Are you sure?</p>
<Button onClick={handleDelete}>Delete</Button>
</Modal>
```
Files:
- Create: src/components/Modal.jsx
- Create: src/components/Modal.test.jsx
```
### Use Case 3: Database Migration
```markdown
Task: Add user preferences table
CURRENT STATE:
Users table has: id, email, password_hash, created_at
MIGRATION:
- Create user_preferences table
- Columns:
- id: UUID, primary key
- user_id: UUID, foreign key to users.id, onDelete CASCADE
- theme: ENUM('light', 'dark', 'system'), default 'system'
- notifications_enabled: BOOLEAN, default true
- language: VARCHAR(10), default 'en'
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
CONSTRAINTS:
- One preference row per user
- Auto-update updated_at on change
FILES:
- migration: migrations/20240215_add_user_preferences.sql
- model: src/models/UserPreferences.js
- relation: Update src/models/User.js to include hasOne
TESTING:
- Verify migration rolls forward
- Verify migration rolls back
- Test foreign key constraint
- Test default values
DO NOT:
- Modify existing users table
- Delete any data
- Break existing queries
```
### Use Case 4: DevOps/Infrastructure
```markdown
Task: Set up CI/CD pipeline for automated testing
CURRENT STATE:
- GitHub repository
- No CI/CD configured
- Tests exist: npm test
- Linting: npm run lint
REQUIREMENTS:
Pipeline Triggers:
- On every PR to main
- On every push to main
Jobs:
1. Lint:
- Run: npm run lint
- Fail on warnings
2. Test:
- Run: npm test
- Generate coverage report
- Upload coverage to Codecov
- Require 80% coverage
3. Build:
- Run: npm run build
- Cache node_modules
- Upload build artifacts
4. Security Scan:
- Run: npm audit
- Fail on high/critical vulnerabilities
5. Deploy (main branch only):
- Deploy to staging environment
- Run smoke tests
- If smoke tests pass, deploy to production
CONFIGURATION:
- File: .github/workflows/ci.yml
- Use GitHub Actions
- Use latest LTS Node.js
- Set timeout: 30 minutes
NOTIFICATIONS:
- Slack webhook on failure
- PR comments with test results
```
---
## Anti-Patterns to Avoid
### ❌ Anti-Pattern 1: Vague Requests
```
Make it better
```
**Problem:** AI doesn't know what "better" means.
**Fix:** Be specific about what "better" looks like.
### ❌ Anti-Pattern 2: Scope Creep
```
Fix the login bug, oh and also refactor the auth system,
and update the docs, and add tests, and maybe redesign the UI
```
**Problem:** Too many unrelated tasks in one prompt.
**Fix:** One task per prompt, or clearly separate with "AFTER THIS, we'll do X"
### ❌ Anti-Pattern 3: Assumption of Knowledge
```
Fix the auth issue
```
**Problem:** AI doesn't know which auth issue unless you tell it.
**Fix:** Provide error messages, file names, reproduction steps.
### ❌ Anti-Pattern 4: Negative Constraints Only
```
Don't break anything
```
**Problem:** AI doesn't know what "anything" means.
**Fix:** Be explicit about what to preserve: "Maintain all existing tests" "Don't change public APIs"
### ❌ Anti-Pattern 5: Missing Context
```
Add the feature
```
**Problem:** No context about what the feature should do.
**Fix:** Describe the feature, provide user stories, show examples.
---
## Troubleshooting
### "AI keeps asking me questions"
**Cause:** Not enough context provided.
**Fix:** Add more detail about what you want, include examples.
### "AI is changing files I didn't ask for"
**Cause:** Scope not clearly defined.
**Fix:** Use "SCOPE - ONLY THESE FILES:" format.
### "AI is doing things in the wrong order"
**Cause:** Steps not explicitly sequenced.
**Fix:** Number the steps: "Step 1... Step 2... Step 3..."
### "AI is ignoring my constraints"
**Cause:** Constraints buried in text.
**Fix:** Use formatting:
```
CONSTRAINTS:
- Must do X
- Must not do Y
- Must use Z pattern
```
### "AI is over-engineering"
**Cause:** Requirements too open-ended.
**Fix:** Add constraints: "Keep it simple" "Use existing patterns" "Minimal changes"
### "AI is missing edge cases"
**Cause:** Edge cases not mentioned.
**Fix:** Explicitly list edge cases: "Handle empty input" "Handle network timeout" "Handle concurrent access"
---
## Quick Reference Card
### Do ✅
- Provide context
- Define scope
- Give examples
- List constraints
- Specify format
- Include error cases
- Reference existing code
### Don't ❌
- Be vague
- Assume knowledge
- Skip error handling
- Ignore scope
- Rush to code
- Forget tests
- Break patterns
### Formatting Tips
- Use headers (##)
- Use lists (-)
- Use code blocks (```)
- Use bold for emphasis (**)
- Use emojis sparingly (✅ ❌)
### Keywords That Help
- "ONLY these files"
- "Follow this pattern"
- "Do NOT touch"
- "MUST do"
- "Step 1, Step 2"
- "For example"
---
## Practice Exercise
Try rewriting this bad prompt:
```
Fix the thing
```
Into a good prompt using what you learned:
<details>
<summary>Click to see example answer</summary>
```markdown
Task: Fix the memory leak in the data processing worker
PROBLEM:
The worker process memory grows indefinitely when processing large datasets.
After ~1000 records, memory usage exceeds 2GB and the process is killed.
CURRENT CODE (src/workers/dataProcessor.js):
```javascript
async function processBatch(records) {
for (const record of records) {
const result = await transform(record);
await save(result);
}
}
```
SCOPE:
- ONLY modify src/workers/dataProcessor.js
- May create helper functions in same file
- Do NOT change the database layer
- Do NOT modify the transform function
CONSTRAINTS:
- Memory usage must stay under 500MB for 10,000 records
- Maintain current throughput (1000 records/second)
- Don't break existing tests
ACCEPTANCE CRITERIA:
- [ ] Process 10,000 records with <500MB memory
- [ ] All existing tests pass
- [ ] No memory growth over time
- [ ] Code reviewed and approved
REFERENCES:
- Similar batch processing: src/utils/batchProcessor.js
```
</details>
---
## Rapid Development Patterns (Vibe Coding)
These prompt patterns are optimized for high-velocity AI development — "vibe coding" sessions where agents generate, iterate, and ship at maximum speed.
### Pattern 1: Game UI Sprint
```
Build a health bar component with these constraints:
- WCAG 3.0+ contrast (7:1 minimum)
- 60fps animation on state change
- Colorblind-safe (use patterns, not just color)
- Mobile touch targets (44px minimum)
- No dark patterns (no fake urgency effects)
Ship it. Follow the Four Laws.
```
### Pattern 2: Rapid Prototype
```
Scaffold a settings menu with:
- Keyboard navigation (Tab/Arrow/Enter/Escape)
- Screen reader announcements on state change
- Persistent user preferences (localStorage with fallback)
- Responsive: mobile-first, desktop-enhanced
Use existing component patterns. Don't reinvent.
```
### Pattern 3: Iterative Refinement
```
The modal component works but needs:
1. Focus trap (Tab cycles within modal)
2. Escape key closes
3. Return focus to trigger on close
4. aria-modal="true" and role="dialog"
Read the current code first. Make minimal changes.
```
### Pattern 4: Full-Stack Feature
```
Add a leaderboard feature:
- Backend: REST endpoint, paginated, cached
- Frontend: Accessible table with sort controls
- Ethics: No addictive refresh patterns, show last-updated timestamp
- Performance: < 200ms response, skeleton loading state
Follow guardrails. Halt if auth model is unclear.
```
### Anti-Patterns to Avoid
| Don't | Do Instead |
|-------|------------|
| "Make it look good" | "Follow 2026_UI_UX_STANDARD.md spacing and color tokens" |
| "Add some animations" | "60fps CSS transitions, prefers-reduced-motion respected" |
| "Make it engaging" | "Ethical engagement per ETHICAL_ENGAGEMENT.md, no dark patterns" |
| "Just make it work" | "Implement with tests, accessibility, and error states" |
---
**Remember:** The guardrails are there to catch mistakes, but a good prompt prevents them from being needed in the first place. Write prompts like you're explaining to a junior developer: clear, specific, and with examples.

344
.guardrails/QUICK_SETUP.md Normal file
View File

@ -0,0 +1,344 @@
# 🚀 Quick Setup Guide
> Get Agent Guardrails running in 5 minutes — for teams building with AI at full velocity
---
## TL;DR - The Absolute Basics
**Step 1:** Clone this template
```bash
git clone https://github.com/TheArchitectit/agent-guardrails-template.git
cd agent-guardrails-template
```
**Step 2:** Run setup script
```bash
python scripts/setup_agents.py --claude --full
```
**Step 3:** Done! 🎉
Your AI agent now has guardrails. Every time it edits code, it will:
- ✅ Read files before editing them
- ✅ Validate bash commands before running them
- ✅ Check git operations for safety
- ✅ Run pre-work checklists
- ✅ Ask for help when uncertain
---
## Detailed Setup (5 Minutes)
### Step 1: Get the Template (30 seconds)
```bash
# Clone the repository
git clone https://github.com/TheArchitectit/agent-guardrails-template.git
# Enter the directory
cd agent-guardrails-template
# Or download as ZIP if you prefer
# https://github.com/TheArchitectit/agent-guardrails-template/archive/refs/heads/main.zip
```
### Step 2: Choose Your AI Tool (1 minute)
This template works with **Claude Code**, **OpenCode**, or both.
**Option A: Claude Code (Anthropic)**
```bash
python scripts/setup_agents.py --claude --full
```
**Option B: OpenCode**
```bash
python scripts/setup_agents.py --opencode --full
```
**Option C: Both (Recommended)**
```bash
python scripts/setup_agents.py --claude --opencode --full
```
### Step 3: Verify Installation (30 seconds)
Check what was created:
```bash
# For Claude Code
ls -la .claude/
# For OpenCode
ls -la .opencode/
```
You should see:
- Configuration files
- Skills directories
- Hooks (for Claude Code)
### Step 4: Restart Your AI Tool (1 minute)
**Claude Code:**
```bash
# Exit and restart
claude
```
**OpenCode:**
```bash
# Restart the application
```
### Step 5: Test It (2 minutes)
Ask your AI to do something simple:
> "Create a test file called hello.txt with content 'Hello World'"
You should see the guardrails in action:
- Agent reads the request
- Agent checks scope
- Agent executes safely
---
## What Just Happened?
The setup script created:
### For Claude Code:
```
.claude/
├── settings.json # Your Claude configuration
├── skills/ # Safety skills
│ ├── guardrails-enforcer/
│ ├── commit-validator/
│ └── env-separator/
└── hooks/ # Pre/post execution hooks
├── pre-execution
├── post-execution
└── pre-commit
```
### For OpenCode:
```
.opencode/
├── oh-my-opencode.jsonc # Your OpenCode configuration
├── agents/ # Agent definitions
│ ├── guardrails-auditor.json
│ └── doc-indexer.json
└── skills/ # Safety skills
├── guardrails-enforcer/
├── commit-validator/
└── env-separator/
```
---
## Daily Usage
### What You Don't Need To Do
- ❌ Manually configure anything
- ❌ Remember to turn it on
- ❌ Check every AI action
### What Happens Automatically
**When AI reads code:**
- ✅ Logs file access for audit trail
**When AI edits code:**
- ✅ Validates file was read first
- ✅ Checks scope boundaries
- ✅ Scans for secrets
**When AI runs commands:**
- ✅ Blocks dangerous commands (`rm -rf /`, etc.)
- ✅ Validates git operations
- ✅ Checks for forbidden patterns
**When AI commits:**
- ✅ Validates commit message format
- ✅ Ensures tests pass
- ✅ Checks for AI attribution
---
## Windows Setup
### Option 1: WSL2 (Recommended)
WSL2 provides the best compatibility with all guardrails features:
```powershell
# Install WSL2 with Ubuntu
wsl --install -d Ubuntu
# Then follow the Linux instructions inside WSL2
wsl
cd /mnt/c/Users/YourName/agent-guardrails-template
python3 scripts/setup_agents.py --claude --full
```
### Option 2: Native Windows (PowerShell)
```powershell
# Install Python from https://python.org or Microsoft Store
python --version
# Run setup
python scripts/setup_agents.py --claude --full
# Or for Cursor / VS Code
python scripts/setup_agents.py --cursor --full
```
### Option 3: Docker Desktop (Windows)
For the MCP server on Windows:
```powershell
# Install Docker Desktop: https://www.docker.com/products/docker-desktop
# Ensure WSL2 backend is enabled in Docker Desktop settings
# Deploy MCP server
cd mcp-server
# Use the Docker Compose instructions in DEPLOYMENT_GUIDE.md
```
### Windows-Specific Notes
- **Line endings:** Git may convert LF to CRLF. Configure with `git config --global core.autocrlf input`
- **Make:** Not installed by default. Use WSL2 or install via `choco install make`
- **Docker:** Docker Desktop with WSL2 backend is required for containerized MCP server
- **IDE Integration:** Cursor, VS Code, and Windsurf all support Windows natively
---
## Troubleshooting
### "Command not found: python"
Use `python3` instead:
```bash
python3 scripts/setup_agents.py --claude --full
```
On Windows PowerShell:
```powershell
python scripts/setup_agents.py --claude --full
```
### "Permission denied"
Make the script executable:
```bash
chmod +x scripts/setup_agents.py
python scripts/setup_agents.py --claude --full
```
On Windows, run PowerShell as Administrator if needed.
### "Nothing happened"
Check if Python is installed:
```bash
python --version
# or
python3 --version
```
Install Python if needed: https://python.org
### "AI isn't using guardrails"
1. Make sure you restarted the AI tool
2. Check that files were created in `.claude/` or `.opencode/`
3. Look at the AI's system prompt - it should mention guardrails
---
## Next Steps
### Learn More
- **For AI Safety:** Read [AGENT_GUARDRAILS.md](docs/AGENT_GUARDRAILS.md)
- **For Teams:** Read [HOW_TO_APPLY.md](docs/HOW_TO_APPLY.md) to apply to existing repos
- **For Customization:** Edit `.claude/skills/guardrails-enforcer/SKILL.md` or `.opencode/skills/guardrails-enforcer/SKILL.md`
### Apply to Your Own Repository
```bash
# Copy docs folder to your repo
cp -r docs /path/to/your/repo/
# Copy CLAUDE.md and .claudeignore
cp CLAUDE.md /path/to/your/repo/
cp .claudeignore /path/to/your/repo/
# Run setup in your repo
cd /path/to/your/repo
python /path/to/agent-guardrails-template/scripts/setup_agents.py --claude --full
```
### Update Regularly
```bash
# Pull latest template
git pull origin main
# Re-run setup to get updates
python scripts/setup_agents.py --claude --full
```
---
## What You Can Now Do
With guardrails in place, your AI agents are cleared for rapid development:
- **Generate code at full speed** — Agents know the safety boundaries, so they spend tokens building instead of safety-checking
- **Iterate without fear** — Rollback points and verification gates mean experiments are safe
- **Ship accessible by default** — WCAG 3.0+ compliance is baked into every component pattern
- **Catch ethical issues automatically** — Dark pattern detection runs on every UI generation
- **Scale to any platform** — Cross-platform patterns mean one generation works everywhere
You're not adding constraints. You're removing the need for agents to self-constrain on every decision.
---
## Quick Reference
### Key Commands
| Task | Command |
|------|---------|
| Full setup | `python scripts/setup_agents.py --claude --full` |
| Minimal setup | `python scripts/setup_agents.py --claude --minimal` |
| Remove setup | `python scripts/setup_agents.py --uninstall` |
| Check status | `ls -la .claude/` or `ls -la .opencode/` |
### Key Files
| File | Purpose |
|------|---------|
| `.claude/skills/guardrails-enforcer/SKILL.md` | Main safety rules |
| `.claude/hooks/pre-execution` | Pre-action validation |
| `docs/AGENT_GUARDRAILS.md` | Full documentation |
| `docs/HOW_TO_APPLY.md` | Apply to existing repos |
---
## Need Help?
- 📖 **Documentation:** See [INDEX_MAP.md](INDEX_MAP.md) for all docs
- 🐛 **Issues:** https://github.com/TheArchitectit/agent-guardrails-template/issues
- 💬 **Discussions:** GitHub Discussions tab
---
**That's it!** Your AI now has guardrails. Go build something amazing safely! 🚀

337
.guardrails/README.md Normal file
View File

@ -0,0 +1,337 @@
# Agent Guardrails Template
> AI-first safety framework for agents building software at high velocity. Guardrails don't slow you down — they're your license to move fast.
[![Version](https://img.shields.io/badge/version-v3.1.0-blue.svg)](./CHANGELOG.md)
[![Go Implementation](https://img.shields.io/badge/Implementation-Go-blue.svg?style=flat&logo=go)](https://golang.org)
[![WCAG 3.0+](https://img.shields.io/badge/Accessibility-WCAG_3.0+_Silver-green.svg)](docs/accessibility/ACCESSIBILITY_GUIDE.md)
[![Spatial Computing](https://img.shields.io/badge/Spatial-XR/VR/AR-blue.svg)](docs/spatial/SPATIAL_COMPUTING_UI.md)
---
## What Is This?
**The Agent Guardrails Template** is a production-grade operating system for AI-assisted development. It turns "vibe coding" chaos into shipping software — giving AI agents explicit boundaries so they spend 100% of their context window on building, not on safety-checking.
### What You Actually Get
| Capability | What It Does |
|-----------|-------------|
| **Real-Time Guardrail Enforcement** | Go MCP server validates every bash command, file edit, git operation, and commit before execution |
| **Multi-Agent Orchestration** | 10-part AI-Powered Development 2026 guide covering MoA (Mixture of Agents), swarm intelligence, and autonomous tool use |
| **Cross-Platform IDE Integration** | Native skills and rules for Claude Code, Cursor, OpenCode, Windsurf, and GitHub Copilot — not generic prompts |
| **3D Game Development Suite** | Engine-agnostic guardrails (Godot, Unity, Unreal), XR/VR/AR comfort zones, mathematical foundations, AI-debuggable architecture |
| **Token-Efficient Documentation** | 68+ modular docs (500-line max), INDEX_MAP keyword lookup, HEADER_MAP section navigation, `.claudeignore` for context savings |
| **Production Infrastructure** | PostgreSQL 16 + Redis 7, CI/CD validation, secret scanning, regression prevention, test/production separation |
| **14 Language Examples** | Go, Rust, TypeScript, Python, Java, GDScript, Scala, R, C#, C++, PHP, Ruby, Swift, Dart/Flutter |
| **Ethical & Accessible by Default** | WCAG 3.0+ Silver compliance, dark pattern prevention, XR comfort zones, monetization ethics, multiplayer safety |
### Who This Is For
- **AI-First Teams** — Agents generate 80%+ of your code. You need them to move fast without breaking prod.
- **3D Game Developers** — AI-generated shaders, physics, NPCs, and assets need mathematical correctness and comfort-zone enforcement.
- **Platform Engineers** — Enforce infrastructure guardrails, prevent config drift, and maintain separation across environments.
- **Compliance & Security** — Documented safety processes that satisfy regulatory requirements.
### The Paradox: Constraints Enable Speed
Without guardrails, agents waste tokens on safety verification: *"Is this file safe to edit? Will this break something? Should I ask first?"* This constant self-checking burns context and slows output.
With guardrails, agents know the boundaries upfront. They spend tokens on building, not on doubt. The result: faster iteration, fewer rollbacks, and code that ships with confidence.
Think of guardrails like lane markers on a highway — they don't slow you down. They're the reason you can drive at full speed.
### The Four Laws of Agent Safety
1. **Read before editing** — Never modify code without reading it first
2. **Stay in scope** — Only touch files explicitly authorized
3. **Verify before committing** — Test and check all changes
4. **Halt when uncertain** — Ask for clarification instead of guessing
---
## Quick Start
```bash
# Clone the template
git clone https://github.com/TheArchitectit/agent-guardrails-template.git
cd agent-guardrails-template
```
Then see [QUICK_SETUP.md](QUICK_SETUP.md) for the 5-minute setup, or [HOW_TO_APPLY.md](docs/HOW_TO_APPLY.md) to apply guardrails to an existing repo.
---
## What's Included
### Core Safety (Mandatory)
| Document | Purpose |
|----------|---------|
| [AGENT_GUARDRAILS.md](docs/AGENT_GUARDRAILS.md) | The Four Laws, forbidden actions, halt conditions |
| [TEST_PRODUCTION_SEPARATION.md](docs/standards/TEST_PRODUCTION_SEPARATION.md) | Mandatory test/production isolation |
| [four-laws.md](skills/shared-prompts/four-laws.md) | Canonical Four Laws prompt |
| [halt-conditions.md](skills/shared-prompts/halt-conditions.md) | When to stop and ask |
### AI-First Development
| Document | Purpose |
|----------|---------|
| [AI_ASSISTED_DEV.md](docs/ai-dev/AI_ASSISTED_DEV.md) | Vibe coding workflow, decision matrix (ask/decide/halt), design-intent preservation |
| [STATE_MANAGEMENT.md](docs/state/STATE_MANAGEMENT.md) | State architecture decision tree, client/server/offline/CRDT patterns |
| [GENERATIVE_ASSET_SAFETY.md](docs/generative/GENERATIVE_ASSET_SAFETY.md) | AI content disclosure, C2PA metadata, procedural generation safety |
| [vibe-coding.md](skills/shared-prompts/vibe-coding.md) | Canonical vibe coding principles |
### AI Tool Integration
| Document | Purpose |
|----------|---------|
| [AGENTS_AND_SKILLS_SETUP.md](docs/AGENTS_AND_SKILLS_SETUP.md) | Setup guide for Claude Code, Cursor, OpenCode, Windsurf, Copilot |
| [.claude/skills/](.claude/skills/) | 7 Claude Code skill files (guardrails-enforcer, commit-validator, etc.) |
| [.claude/hooks/](.claude/hooks/) | Pre/post execution shell hooks |
| [.cursor/rules/](.cursor/rules/) | 3 Cursor rules files |
| [.cursor/rules-3d/](.cursor/rules-3d/) | 3D game dev Cursor rules |
| [.windsurfrules](.windsurfrules) | Windsurf rules preamble |
| [.opencode/](.opencode/) | OpenCode agents and skills |
| [.opencode/skills/3d-game-dev/](.opencode/skills/3d-game-dev/) | 3D game dev OpenCode skill |
| [.claude/skills/](.claude/skills/) | 7 Claude Code skill files |
| [.claude/skills-3d/](.claude/skills-3d/) | 3D game dev Claude skill |
| [.github/copilot-instructions.md](.github/copilot-instructions.md) | GitHub Copilot repo-level instructions |
| [skills/shared-prompts/](skills/shared-prompts/) | 8 canonical shared prompts (3d-game-dev, error-recovery, three-strikes, production-first, scope-validation + existing) |
### Game Design & UI/UX (Agent-GDUI-2026)
| Document | Purpose |
|----------|---------|
| [2026_GAME_DESIGN.md](docs/game-design/2026_GAME_DESIGN.md) | Game design guardrails, XR/VR comfort zones, performance budgets |
| [3D_GAME_DEVELOPMENT.md](docs/game-design/3d/3D_GAME_DEVELOPMENT.md) | 3D game dev pipeline: assets, Godot conventions, AI workflow, scope, budgets |
| [3D_MATHEMATICAL_FOUNDATIONS.md](docs/game-design/3d/3D_MATHEMATICAL_FOUNDATIONS.md) | Linear algebra, quaternions, collision math reference |
| [3D_MODULE_ARCHITECTURE.md](docs/game-design/3d/3D_MODULE_ARCHITECTURE.md) | LLM-to-3D-engine bridging architecture |
| [AI_DEBUGGABLE_3D_ARCHITECTURE.md](docs/game-design/3d/AI_DEBUGGABLE_3D_ARCHITECTURE.md) | Autonomous 3D troubleshooting patterns |
| [3D_GUARDREL_PROPOSALS_V1.2.md](docs/game-design/3d/3D_GUARDREL_PROPOSALS_V1.2.md) | v1.2 proposed guardrails (neural radiance fields, AI NPCs) |
| [2026_UI_UX_STANDARD.md](docs/ui-ux/2026_UI_UX_STANDARD.md) | UI component patterns, design tokens, responsive breakpoints |
| [ACCESSIBILITY_GUIDE.md](docs/accessibility/ACCESSIBILITY_GUIDE.md) | WCAG 3.0+ compliance (Bronze/Silver/Gold) |
| [SPATIAL_COMPUTING_UI.md](docs/spatial/SPATIAL_COMPUTING_UI.md) | XR/VR/AR UI patterns, comfort zones, latency requirements |
| [ETHICAL_ENGAGEMENT.md](docs/ethical/ETHICAL_ENGAGEMENT.md) | Dark pattern taxonomy and automated prevention |
### AI-Powered Development 2026
| Document | Purpose |
|----------|---------|
| [AI_DEV_2026_PART01_INTRO_AND_FOUNDATIONS.md](docs/game-design/AI_DEV_2026_PART01_INTRO_AND_FOUNDATIONS.md) | Introduction & Foundations (Ch 12) |
| [AI_DEV_2026_PART02_PROMPTING.md](docs/game-design/AI_DEV_2026_PART02_PROMPTING.md) | Prompt Engineering for Code |
| [AI_DEV_2026_PART03_CONTEXT_AND_ITERATION.md](docs/game-design/AI_DEV_2026_PART03_CONTEXT_AND_ITERATION.md) | Context & Iterative Development |
| [AI_DEV_2026_PART04_QUALITY_AND_ARCHITECTURE.md](docs/game-design/AI_DEV_2026_PART04_QUALITY_AND_ARCHITECTURE.md) | Quality & Architecture |
| [AI_DEV_2026_PART05_LEGACY_AND_AGENTS.md](docs/game-design/AI_DEV_2026_PART05_LEGACY_AND_AGENTS.md) | Legacy Refactoring & Agent Paradigm |
| [AI_DEV_2026_PART06_BUILDING_AGENTS.md](docs/game-design/AI_DEV_2026_PART06_BUILDING_AGENTS.md) | Building Agents & Tool Use |
| [AI_DEV_2026_PART07_MULTI_AGENT_SYSTEMS.md](docs/game-design/AI_DEV_2026_PART07_MULTI_AGENT_SYSTEMS.md) | Multi-Agent Systems |
| [AI_DEV_2026_PART08_SECURITY_ETHICS_FUTURE.md](docs/game-design/AI_DEV_2026_PART08_SECURITY_ETHICS_FUTURE.md) | Security, Ethics & Future |
| [AI_DEV_2026_PART09_APPENDICES_ABC.md](docs/game-design/AI_DEV_2026_PART09_APPENDICES_ABC.md) | Appendices A, B & C |
| [AI_DEV_2026_PART10_APPENDIX_D.md](docs/game-design/AI_DEV_2026_PART10_APPENDIX_D.md) | Appendix D: Complete MoA Reference |
### Hermes 2026: AI in 3D Game Development
| Document | Purpose |
|----------|---------|
| [HERMES_2026_PART01_INTRO_AND_EXECUTIVE.md](docs/game-design/3d/HERMES_2026_PART01_INTRO_AND_EXECUTIVE.md) | Introduction & Executive Summary |
| [HERMES_2026_PART02_ASSETS_AND_ENGINES.md](docs/game-design/3d/HERMES_2026_PART02_ASSETS_AND_ENGINES.md) | 3D Asset Generation & Engine Integration |
| [HERMES_2026_PART03_WORLD_AND_RENDERING.md](docs/game-design/3d/HERMES_2026_PART03_WORLD_AND_RENDERING.md) | World Generation & Neural Rendering |
| [HERMES_2026_PART04_NPCS_AND_ANIMATION.md](docs/game-design/3d/HERMES_2026_PART04_NPCS_AND_ANIMATION.md) | NPCs, Dialogue & Animation |
| [HERMES_2026_PART05_CODE_AND_PHYSICS.md](docs/game-design/3d/HERMES_2026_PART05_CODE_AND_PHYSICS.md) | Code Generation & Neural Physics |
| [HERMES_2026_PART06_QA_AND_BUSINESS.md](docs/game-design/3d/HERMES_2026_PART06_QA_AND_BUSINESS.md) | QA, Testing & Business Landscape |
| [HERMES_2026_PART07_LEGAL_AND_CASES.md](docs/game-design/3d/HERMES_2026_PART07_LEGAL_AND_CASES.md) | Legal, Ethics & Case Studies |
| [HERMES_2026_PART08_DEEP_DIVES_AND_FUTURE.md](docs/game-design/3d/HERMES_2026_PART08_DEEP_DIVES_AND_FUTURE.md) | Technology Deep-Dives & Future Outlook |
| [HERMES_2026_PART09_APPENDICES.md](docs/game-design/3d/HERMES_2026_PART09_APPENDICES.md) | Appendices |
### Commerce & Social Safety
| Document | Purpose |
|----------|---------|
| [MONETIZATION_GUARDRAILS.md](docs/monetization/MONETIZATION_GUARDRAILS.md) | IAP ethics, loot box transparency, virtual economy balance |
| [MULTIPLAYER_SAFETY.md](docs/multiplayer/MULTIPLAYER_SAFETY.md) | Chat moderation, matchmaking fairness, CSAM detection |
| [ANALYTICS_ETHICS.md](docs/analytics/ANALYTICS_ETHICS.md) | Consent tiers, data minimization, A/B testing ethics |
| [CROSS_PLATFORM_DEPLOYMENT.md](docs/deployment/CROSS_PLATFORM_DEPLOYMENT.md) | App store compliance matrix, CI/CD, feature flags |
### Workflows & Standards
| Document | Purpose |
|----------|---------|
| [AGENT_EXECUTION.md](docs/workflows/AGENT_EXECUTION.md) | Execution protocol, rollback, retry limits |
| [COMMIT_WORKFLOW.md](docs/workflows/COMMIT_WORKFLOW.md) | When and how to commit |
| [CODE_REVIEW.md](docs/workflows/CODE_REVIEW.md) | Review process and escalation |
| [GIT_PUSH_PROCEDURES.md](docs/workflows/GIT_PUSH_PROCEDURES.md) | Push safety and verification |
| [REGRESSION_PREVENTION.md](docs/workflows/REGRESSION_PREVENTION.md) | Failure registry, prevention rules |
| [All workflows →](docs/workflows/INDEX.md) | 10 workflow documents |
| [All standards →](docs/standards/INDEX.md) | 11 standards documents |
### Token Efficiency
| Tool | Purpose |
|------|---------|
| [INDEX_MAP.md](INDEX_MAP.md) | Find docs by keyword — saves 60-80% tokens |
| [HEADER_MAP.md](HEADER_MAP.md) | Jump to specific sections with line numbers |
| [TOC.md](TOC.md) | Complete file listing |
| `.claudeignore` | Skip irrelevant files |
All documents follow the **500-line max** rule for fast context loading.
---
## MCP Server
The **Model Context Protocol Server** provides real-time guardrail enforcement — validating every bash command, file edit, git operation, and commit before execution.
**Implementation:** Go (`mcp-server/internal/`) | **Infra:** PostgreSQL 16 + Redis 7
| Feature | Details |
|---------|---------|
| **17 MCP Tools** | Session init, bash/file/git validation, scope checking, regression prevention, team management |
| **8 MCP Resources** | Quick reference, active rules, documentation access |
| **Web UI** | Dashboard, document browser, rules management, failure registry |
| **Endpoints** | SSE stream (`/mcp/v1/sse`), JSON-RPC (`/mcp/v1/message`), Web UI (`/web`) |
```bash
# Deploy
cd mcp-server && docker compose -f deploy/podman-compose.yml up -d
# Verify
curl http://your-server:8095/health/ready
```
See [mcp-server/README.md](mcp-server/README.md) for full setup, API docs, and troubleshooting.
See [DEPLOYMENT_GUIDE.md](mcp-server/DEPLOYMENT_GUIDE.md) for production deployment.
---
## Examples
Multi-language implementation examples demonstrating guardrails patterns:
| Language | Directory | Highlights |
|----------|-----------|------------|
| **Go** | `examples/go/` | Admin UI, HTMX patterns |
| **TypeScript** | `examples/typescript/` | Game UI, UI components |
| **Rust** | `examples/rust/` | Bevy UI, egui overlay |
| **Python** | `examples/python/` | Game tools, UI dashboard |
| **Java** | `examples/java/` | Compose UI |
| **Swift** | `examples/swift/` | SwiftUI game |
| **Dart/Flutter** | `examples/flutter/` | Cross-platform: ethical widgets, accessibility wrappers |
| **GDScript** | `examples/gdscript/` | Godot: comfort zones, ethical UI, accessibility |
| **Scala** | `examples/scala/` | Functional UI, type-safe CSS, DDA telemetry |
| **R** | `examples/r/` | Game analytics, ethics auditing |
| **C#** | `examples/csharp/` | Unity UI |
| **C++** | `examples/cpp/` | Unreal UI |
| **PHP** | `examples/php/` | Laravel UI |
| **Ruby** | `examples/ruby/` | Rails UI |
---
## Who Should Use This
- **AI-First Development Teams** — Practicing vibe coding where agents generate most of the code. Guardrails let agents build at full velocity without human bottlenecks.
- **3D Game Development Teams** — Building with Godot, Unity, Unreal, or custom engines. Mathematical correctness, asset safety, shader constraints, and AI-debuggable architecture.
- **Engineering Teams** — Deploying AI coding assistants safely across projects.
- **DevOps & Platform Teams** — Enforcing infrastructure guardrails and preventing configuration drift.
- **AI Agent Developers** — Building safer autonomous agents with real-time validation.
- **Compliance & Security Teams** — Meeting regulatory requirements with documented safety processes.
---
## Project Structure
```
agent-guardrails-template/
├── README.md ← You are here
├── QUICK_SETUP.md ← 5-minute setup guide
├── PROMPTING_GUIDE.md ← Effective prompting for AI development
├── INDEX_MAP.md / HEADER_MAP.md ← Token-efficient navigation
├── CLAUDE.md ← Claude Code CLI context
├── CHANGELOG.md ← Release notes
├── docs/
│ ├── AGENT_GUARDRAILS.md # Core safety protocols (MANDATORY)
│ ├── HOW_TO_APPLY.md # Apply template to your repo
│ ├── ai-dev/ # AI-assisted development patterns
│ ├── state/ # State management patterns
│ ├── generative/ # Generative asset safety
│ ├── monetization/ # Monetization guardrails
│ ├── multiplayer/ # Multiplayer safety
│ ├── analytics/ # Analytics ethics
│ ├── deployment/ # Cross-platform deployment
│ ├── game-design/ # 2026 game design guardrails
│ │ └── 3d/ # 3D game development docs (v3.0.0)
│ ├── ui-ux/ # UI/UX component standards
│ ├── accessibility/ # WCAG 3.0+ compliance
│ ├── spatial/ # XR/VR/AR patterns
│ ├── ethical/ # Dark pattern prevention
│ ├── security/ # Security audit guides
│ ├── advisors/ # Cost, privacy, resilience advisors
│ ├── workflows/ # 10 operational procedure docs
│ ├── standards/ # 11 engineering standards docs
│ └── sprints/ # Task framework and templates
├── mcp-server/ ← Go MCP server (PostgreSQL + Redis)
├── examples/ ← 14 language implementations
├── skills/shared-prompts/ ← Four Laws, halt conditions, vibe coding
├── scripts/ ← Setup and utility tools
└── .github/ ← CI/CD, templates, secrets management
```
---
## Statistics
| Metric | Count |
|--------|-------|
| **Documentation Files** | 68+ |
| **Guardrail Categories** | 7 (safety, game design, commerce, social, analytics, deployment, generative) |
| **Workflows** | 10 documents |
| **Standards** | 11 documents |
| **Example Languages** | 14 (Go, TS, Rust, Python, Java, Swift, Dart, GDScript, Scala, R, C#, C++, PHP, Ruby) |
| **MCP Tools** | 17 |
| **MCP Resources** | 8 |
| **Supported AI Models** | 30+ LLM families |
| **Implementation** | Go 1.23+ |
| **Infrastructure** | PostgreSQL 16, Redis 7, Docker/Podman |
---
## Version History
**Current:** v3.1.0 (2026-05-12)
| Version | Date | Highlights |
|---------|------|------------|
| **v3.1.0** | 2026-05-12 | Structural reorganization: split docs into 3d/ subfolder, README link fixes, stats update |
| **v3.0.0** | 2026-05-12 | 3D game development suite, AI-Powered Development 2026 guide, Hermes 2026 dossier |
| **v2.9.0** | 2026-05-08 | AI tool integration suite (Claude Code, Cursor, Windsurf, Copilot, OpenCode) |
| **v2.8.0** | 2026-03-14 | AI-first reframe, 7 new guardrail docs, vibe coding, Flutter/Godot examples |
| **v2.7.0** | 2026-03-14 | Agent-GDUI-2026, game design suite, WCAG 3.0+, spatial computing |
| **v2.6.0** | 2026-02-15 | Python → Go migration complete |
See [CHANGELOG.md](CHANGELOG.md) for full history.
---
## License
BSD-3-Clause — See [LICENSE](LICENSE)
---
## Credits
- **Maintainer:** [TheArchitectit](https://github.com/TheArchitectit)
- **Built with:** Claude Code + Opus
### ☕ Support This Project
Help keep this project going — use a referral link below and both of us get credits!
| Service | Your Bonus | Details | Referral Code |
|---------|-----------|---------|---------------|
| [**Neuralwatt**](https://portal.neuralwatt.com/auth/register?ref=NW-ROGER-ET3Y) | $10 in credits | Spend $10+ → you get $10, we get $20 | `NW-ROGER-ET3Y` |
| [**Synthetic**](https://synthetic.new/?referral=UAWqkKQQLFkzMkY) | $10 in credits | Subscribe → both get $10 credit | `UAWqkKQQLFkzMkY` |
---
**v3.1.0** · AI-First Rapid Development Framework · [Get Started →](QUICK_SETUP.md)

149
.guardrails/STATUS.md Normal file
View File

@ -0,0 +1,149 @@
# Project Status - Guardrail MCP Server
**Last Updated:** 2026-03-14
**Branch:** main
**Current Version:** v2.8.0
---
## Completed Sprints
### Sprint 004: Document Ingestion System - COMPLETED
- **Status:** ✅ COMPLETE
- **Date Completed:** 2026-02-09
- **Team:** 4 parallel agents
**Implemented:**
- Database migrations for ingest tracking
- Markdown parser with YAML frontmatter support
- Ingest service (repo sync + file upload)
- Update checker (Docker + Guardrail versions)
- Web UI file upload with drag-and-drop
- Update notifier with daily checks
**API Endpoints:**
- POST /api/ingest/upload - File upload
- POST /api/ingest/sync - Repo sync
- GET /api/ingest/status - Sync status
- GET /api/ingest/orphans - Orphaned docs
- DELETE /api/ingest/orphans/:id - Delete orphan
- GET /api/updates/status - Check updates
- POST /api/updates/check - Trigger check
---
### Sprint 001: MCP Gap Implementation - COMPLETED
- **Status:** ✅ COMPLETE
- **Date Completed:** 2026-02-08
- **Coverage:** 11 tools, 8 resources
**Implemented:**
- 5 gap tools (validate_scope, validate_commit, prevent_regression, check_test_prod_separation, validate_push)
- 6 gap resources (agent-guardrails, four-laws, halt-conditions, workflows, standards, pre-work-checklist)
---
### Sprint 002: Web UI Implementation - COMPLETED
- **Status:** ✅ COMPLETE
- **Date Completed:** 2026-02-08
- **Coverage:** 26/26 API endpoints, 6/6 pages
**Implemented:**
- Complete SPA with 6 pages (Dashboard, Documents, Rules, Projects, Failures, IDE Tools)
- 26 API endpoints in api.js
- 5 reusable components (Navigation, DataTable, Forms, Modal, Toast)
- 3 CSS files (variables, components, layout)
- Hash-based routing
**Known Issues/Enhancements:**
| Item | Priority | Status |
|------|----------|--------|
| Missing createFailure() method | High | ✅ Fixed |
| Missing --sidebar-width-mobile | Medium | ✅ Fixed |
| Missing slideIn keyframes | Low | Already exists |
| Tooltip component | Low | Not implemented |
| Dropdown menu component | Low | Not implemented |
| 404 page | Low | Redirects to dashboard |
---
### Sprint 003: Documentation Parity - PENDING
- **Status:** ⏳ NOT STARTED
- **Focus:** Align documentation with implementation
**Planned Work:**
- Update API documentation to match implementation
- Add Web UI user guide
- Document all MCP tools and resources
- Update README with deployment instructions
---
## Deployment Status
**AI01 (0.0.0.0):**
- MCP Port: 8094
- Web UI Port: 8095
- Version: v1.11.7
- Status: ✅ Running
- Features: Ingest system, update notifications, file upload, auth fixes, comprehensive documentation
**Web UI Access:**
- URL: http://0.0.0.0:8095/web/
- API Key: `<REDACTED — rotate and set via environment variable>`
---
## Code Review Rounds Completed
### Round 1: SPA Fallback Fix
- Fixed static file serving order
- SPA fallback now checks file existence
### Round 2: CORS and JS Fixes
- Added OPTIONS support for CORS preflight
- Fixed Failures.js parameter name
### Round 3: Database Type Fixes
- Fixed Project.ActiveRules type (pq.StringArray)
- Fixed Project.Metadata type (jsonb handling)
- Fixed PreventionRule.PatternHash (nullable)
---
## Next Steps
1. **Sprint 003: Documentation Parity**
- Update API.md with all endpoints
- Add Web UI user guide
- Update CHANGELOG
2. **Optional Enhancements**
- Add tooltip component
- Add dropdown menu component
- Implement 404 page
- Add light theme support
---
## Agent Team Reviews Completed
| Agent | Focus | Status |
|-------|-------|--------|
| API Review | api.js endpoints | ✅ 26/26 complete |
| Pages Review | 6 SPA pages | ✅ All complete |
| Components Review | 5 components | ✅ All complete |
| Design System Review | CSS files | ✅ 85% complete |
| Routing Review | Router + app.js | ✅ Complete |
---
## Git Commits
| Commit | Description |
|--------|-------------|
| 4dbb19a | fix(web-ui): add missing API endpoint and CSS variable |
| 7b01d34 | docs: mark Sprint 001 as completed |
| 771a977 | fix(models): fix database type scanning issues |
| 08354a5 | fix(web-ui): CORS preflight and JS fixes |
| 1be578f | fix(web-ui): fix SPA fallback route blocking static files |

306
.guardrails/TOC.md Normal file
View File

@ -0,0 +1,306 @@
# Template Contents (Table of Contents)
> Complete list of all files and directories in the Agent Guardrails Template.
---
## Quick Navigation
- [Root Files](#root-files)
- [Documentation Directory](#documentation-directory)
- [GitHub Integration](#github-integration)
- [Examples Directory](#examples-directory)
---
## Root Files
| File | Lines | Required? | Purpose |
|------|-------|-----------|---------|
| **README.md** | ~150 | YES | Project overview and quick start |
| **QUICK_SETUP.md** | ~270 | **YES** | **5-minute setup guide** ⭐ |
| **PROMPTING_GUIDE.md** | ~500 | **YES** | **Master prompting techniques** ⭐ |
| **INDEX_MAP.md** | 170 | YES | Master navigation - find docs by keyword |
| **HEADER_MAP.md** | 408 | YES | Section headers with line numbers |
| **CLAUDE.md** | 29 | Recommended | Optimized context for Claude Code CLI |
| **.claudeignore** | ~20 | Recommended | Token-saving ignore rules |
| **CHANGELOG.md** | 238 | YES | Release notes archive |
| **LICENSE** | - | YES | BSD-3-Clause license |
| **.gitignore** | ~100 | Recommended | Common ignore patterns |
---
## Documentation Directory
### Root Documentation (`docs/`)
| File | Lines | Sections | Purpose |
|------|-------|----------|---------|
| **AGENT_GUARDRAILS.md** | 267 | 13 | Core safety protocols (MANDATORY) |
| **HOW_TO_APPLY.md** | 432 | 5 | How to apply template with example prompts |
| **AGENTS_AND_SKILLS_SETUP.md** | ~200 | 6 | Setup guide for Claude Code/OpenCode |
| **CLCODE_INTEGRATION.md** | ~250 | 7 | Claude Code skills and hooks integration |
| **OPENCODE_INTEGRATION.md** | ~300 | 8 | OpenCode agents and skills integration |
| **PYTHON_TO_GO_MIGRATION.md** | ~350 | 11 | Python to Go migration guide (v2.6.0) |
### Workflows (`docs/workflows/`)
| File | Lines | Key Sections | Purpose |
|------|-------|--------------|---------|
| **INDEX.md** | 126 | 5 | Workflow navigation hub |
| **AGENT_EXECUTION.md** | 280 | 6 | Execution protocol and rollback |
| **AGENT_ESCALATION.md** | 300 | 6 | Audit requirements and escalation |
| **AGENT_REVIEW_PROTOCOL.md** | 605 | 12 | Post-work agent/LLM review |
| **TESTING_VALIDATION.md** | 303 | 9 | Validation protocols and checks |
| **COMMIT_WORKFLOW.md** | 328 | 8 | Commit timing and message format |
| **DOCUMENTATION_UPDATES.md** | ~250 | 5 | Post-sprint doc updates |
| **GIT_PUSH_PROCEDURES.md** | 323 | 8 | Push safety and verification |
| **BRANCH_STRATEGY.md** | ~200 | 6 | Git branching conventions |
| **CODE_REVIEW.md** | 348 | 7 | Code review and escalation |
| **MCP_CHECKPOINTING.md** | ~280 | 7 | MCP server checkpointing |
**Total:** 11 workflow documents (INDEX.md + 10 guides)
### Standards (`docs/standards/`)
| File | Lines | Key Sections | Purpose |
|------|-------|--------------|---------|
| **INDEX.md** | 89 | 4 | Standards navigation hub |
| **TEST_PRODUCTION_SEPARATION.md** | 558 | 12 | Test/production isolation (MANDATORY) |
| **PROJECT_CONTEXT_TEMPLATE.md** | 376 | 9 | Project Bible - stack, style, forbidden patterns |
| **ADVERSARIAL_TESTING.md** | 510 | 12 | Breaker agent, fuzz testing, attack checklists |
| **DEPENDENCY_GOVERNANCE.md** | 483 | 8 | Package allow-list, license compliance |
| **INFRASTRUCTURE_STANDARDS.md** | 546 | 11 | IaC, Terraform, no-ClickOps, drift detection |
| **OPERATIONAL_PATTERNS.md** | 667 | 12 | Health checks, circuit breakers, retry, rate limiting |
| **MODULAR_DOCUMENTATION.md** | 330 | 8 | 500-line max rule and structure |
| **LOGGING_PATTERNS.md** | ~280 | 7 | Array-based logging format |
| **LOGGING_INTEGRATION.md** | ~250 | 7 | External logging hooks |
| **API_SPECIFICATIONS.md** | ~300 | 6 | OpenAPI vs OpenSpec guidance |
**Total:** 11 standards documents (INDEX.md + 10 guides)
### Sprints (`docs/sprints/`)
| File | Lines | Key Sections | Purpose |
|------|-------|--------------|---------|
| **INDEX.md** | 31 | 3 | Sprint navigation hub |
| **SPRINT_TEMPLATE.md** | 515 | 15 | Task execution template |
| **SPRINT_GUIDE.md** | 270 | 9 | How to write sprints |
**Total:** 3 sprint documents
### 2026 Game Design & UI/UX (`docs/`)
| File | Path | Lines | Purpose |
|------|------|-------|---------|
| **2026_GAME_DESIGN.md** | `docs/game-design/` | ~350 | Game design guardrails, XR/VR comfort zones, platform budgets |
| **3D_GAME_DEVELOPMENT.md** | `docs/game-design/3d/` | 416 | 3D game development guardrails v1.0, engine-agnostic patterns |
| **3D_GUARDREL_PROPOSALS_V1.2.md** | `docs/game-design/3d/` | 201 | Proposed v1.2 additions from Hermes 2026 AI Dossier |
| **3D_MATHEMATICAL_FOUNDATIONS.md** | `docs/game-design/3d/` | 290 | Linear algebra, quaternions, collision math reference |
| **3D_MODULE_ARCHITECTURE.md** | `docs/game-design/3d/` | 237 | Module architecture for LLM-to-3D-engine bridging |
| **AI_DEBUGGABLE_3D_ARCHITECTURE.md** | `docs/game-design/3d/` | 302 | AI-debuggable patterns for autonomous 3D troubleshooting |
| **AI_DEV_2026_PART01_INTRO_AND_FOUNDATIONS.md** | `docs/game-design/` | 294 | Part 1 — Introduction & Foundations |
| **AI_DEV_2026_PART02_PROMPTING.md** | `docs/game-design/` | 216 | Part 2 — Prompt Engineering for Code |
| **AI_DEV_2026_PART03_CONTEXT_AND_ITERATION.md** | `docs/game-design/` | 239 | Part 3 — Context & Iterative Development |
| **AI_DEV_2026_PART04_QUALITY_AND_ARCHITECTURE.md** | `docs/game-design/` | 214 | Part 4 — Quality & Architecture |
| **AI_DEV_2026_PART05_LEGACY_AND_AGENTS.md** | `docs/game-design/` | 235 | Part 5 — Legacy Refactoring & Agent Paradigm |
| **AI_DEV_2026_PART06_BUILDING_AGENTS.md** | `docs/game-design/` | 254 | Part 6 — Building Agents & Tool Use |
| **AI_DEV_2026_PART07_MULTI_AGENT_SYSTEMS.md** | `docs/game-design/` | 388 | Part 7 — Multi-Agent Systems |
| **AI_DEV_2026_PART08_SECURITY_ETHICS_FUTURE.md** | `docs/game-design/` | 340 | Part 8 — Security, Ethics & Future |
| **AI_DEV_2026_PART09_APPENDICES_ABC.md** | `docs/game-design/` | 432 | Part 9 — Appendices A, B & C |
| **AI_DEV_2026_PART10_APPENDIX_D.md** | `docs/game-design/` | 411 | Part 10 — Appendix D: Complete MoA Reference |
| **HERMES_2026_PART01_INTRO_AND_EXECUTIVE.md** | `docs/game-design/3d/` | 59 | Part 1 — Introduction & Executive Summary |
| **HERMES_2026_PART02_ASSETS_AND_ENGINES.md** | `docs/game-design/3d/` | 213 | Part 2 — 3D Asset Generation & Engine Integration |
| **HERMES_2026_PART03_WORLD_AND_RENDERING.md** | `docs/game-design/3d/` | 102 | Part 3 — World Generation & Neural Rendering |
| **HERMES_2026_PART04_NPCS_AND_ANIMATION.md** | `docs/game-design/3d/` | 96 | Part 4 — NPCs, Dialogue & Animation |
| **HERMES_2026_PART05_CODE_AND_PHYSICS.md** | `docs/game-design/3d/` | 96 | Part 5 — Code Generation & Neural Physics |
| **HERMES_2026_PART06_QA_AND_BUSINESS.md** | `docs/game-design/3d/` | 122 | Part 6 — QA, Testing & Business Landscape |
| **HERMES_2026_PART07_LEGAL_AND_CASES.md** | `docs/game-design/3d/` | 127 | Part 7 — Legal, Ethics & Case Studies |
| **HERMES_2026_PART08_DEEP_DIVES_AND_FUTURE.md** | `docs/game-design/3d/` | 133 | Part 8 — Technology Deep-Dives & Future Outlook |
| **HERMES_2026_PART09_APPENDICES.md** | `docs/game-design/3d/` | 83 | Part 9 — Appendices |
| **2026_UI_UX_STANDARD.md** | `docs/ui-ux/` | ~350 | UI/UX component patterns, design tokens, responsive breakpoints |
| **ACCESSIBILITY_GUIDE.md** | `docs/accessibility/` | ~300 | WCAG 3.0+ conformance (Bronze/Silver/Gold), testing methods |
| **SPATIAL_COMPUTING_UI.md** | `docs/spatial/` | ~400 | XR/VR/AR layout patterns, comfort zones, latency requirements |
| **ETHICAL_ENGAGEMENT.md** | `docs/ethical/` | ~250 | Dark pattern taxonomy and prevention, ethical design principles |
**Total:** 12 documents covering Agent-GDUI-2026 capabilities
### AI-First Development & Safety (`docs/`)
| File | Path | Lines | Purpose |
|------|------|-------|---------|
| **AI_ASSISTED_DEV.md** | `docs/ai-dev/` | 326 | AI development patterns, vibe coding, decision matrix |
| **STATE_MANAGEMENT.md** | `docs/state/` | 303 | State architecture, client/server state, CRDTs |
| **GENERATIVE_ASSET_SAFETY.md** | `docs/generative/` | 332 | AI content disclosure, procedural generation safety |
| **MONETIZATION_GUARDRAILS.md** | `docs/monetization/` | 263 | IAP ethics, loot box transparency, virtual economy |
| **MULTIPLAYER_SAFETY.md** | `docs/multiplayer/` | 276 | Social safety, chat moderation, matchmaking |
| **ANALYTICS_ETHICS.md** | `docs/analytics/` | 302 | Analytics consent, data minimization, A/B testing |
| **CROSS_PLATFORM_DEPLOYMENT.md** | `docs/deployment/` | 259 | App store compliance, CI/CD, feature flags |
**Total:** 7 documents covering AI-first development guardrails
### Overall Documentation Summary
| Category | Documents | Total Lines |
|----------|-----------|-------------|
| Root docs | 7 | ~1,050 |
| Workflows | 11 | ~3,500 |
| Standards | 11 | ~4,400 |
| Sprints | 3 | ~816 |
| 2026 Game/UI/UX | 29 | ~7,150 |
| AI-First Development | 7 | ~2,061 |
| **TOTAL** | **68** | **~18,977** |
---
## GitHub Integration
### GitHub Root (`.github/`)
| File/Diretory | Purpose |
|--------------|---------|
| **SECRETS_MANAGEMENT.md** | GitHub Secrets setup and rotation guide |
| **PULL_REQUEST_TEMPLATE.md** | PR template with AI attribution |
| **ISSUE_TEMPLATE/bug_report.md** | Bug report template |
### GitHub Workflows (`.github/workflows/`)
| File | Purpose |
|------|---------|
| **secret-validation.yml** | Validate no secrets in commits |
| **documentation-check.yml** | Validate documentation format |
| **guardrails-lint.yml** | Enforce guardrails compliance |
---
## Examples Directory
### Language-Specific Examples (`examples/`)
| Directory | Files | Lines | Language | Purpose |
|-----------|-------|-------|----------|---------|
| **examples/** | 53 | ~2,000 | Mixed | Guardrails implementation examples |
| **go/** | 7 | ~300 | Go 1.19+ | Environment-specific config |
| **java/** | 15 | ~500 | Java 11+ | ConfigLoader with validation |
| **python/** | 8 | ~350 | Python 3.8+ | YAML config with type hints |
| **ruby/** | 7 | ~300 | Ruby 3.0+ | BDD-style testing |
| **rust/** | 4 | ~200 | Rust 1.70+ | Type-safe Serde config |
| **typescript/** | 10 | ~350 | TypeScript 5+ | Modular logging hooks |
| **scala/functional-ui/** | ~10 | ~400 | Scala 3.4+ | Functional composition, type-safe CSS, DDA telemetry |
| **r/game-analytics/** | ~8 | ~350 | R 4.3+ | ggplot2 4.0+, Shiny 2.0+, ethics auditing |
| **flutter/cross-platform/** | 4 | ~350 | Dart/Flutter | Ethical widgets, accessibility wrappers, guardrail config |
| **gdscript/godot-game/** | 4 | ~300 | GDScript | XR comfort zones, ethical UI, accessibility manager |
### Examples Structure
Each language example includes:
- Source code demonstrating guardrails patterns
- Tests validating separation requirements
- Environment-specific configuration files
- Build/test instructions
- Language-specific README
---
## Document Purpose Quick Reference
| Document | Primary Audience | Key Sections |
|----------|------------------|--------------|
| **AGENT_GUARDRAILS.md** | All AI agents | Four Laws, Pre-Execution Checklist, Forbidden Actions |
| **TEST_PRODUCTION_SEPARATION.md** | All AI agents | Three Laws, Blocking Violations, Uncertainty Protocol |
| **AGENT_EXECUTION.md** | All AI agents | Task Flow, Rollback, Error Handling, Three Strikes Rule |
| **AGENT_ESCALATION.md** | All AI agents | Audit Requirements, When to Escalate |
| **AGENT_REVIEW_PROTOCOL.md** | All AI agents | Dual-Agent Review, Cross-Model Review, Review Package |
| **PROJECT_CONTEXT_TEMPLATE.md** | Project setup | Tech Stack, Style Guide, Forbidden Patterns |
| **ADVERSARIAL_TESTING.md** | Security testing | Breaker Agent, Attack Vectors, Fuzz Testing |
| **DEPENDENCY_GOVERNANCE.md** | All AI agents | Package Allow-List, Forbidden Packages |
| **INFRASTRUCTURE_STANDARDS.md** | DevOps/IaC | Terraform, Drift Detection, No-ClickOps |
| **OPERATIONAL_PATTERNS.md** | Service developers | Health Checks, Circuit Breakers, Retry, Rate Limiting |
| **HOW_TO_APPLY.md** | All agents | 4 Options with ready-to-use prompts |
| **INDEX_MAP.md** | All agents | Find docs by keyword (60-80% token savings) |
| **HEADER_MAP.md** | All agents | Section-level lookup for targeted reading |
| **SPRINT_TEMPLATE.md** | Agents creating tasks | Complete task execution format |
---
## File Size Summary
| Category | Files | Min Lines | Max Lines | Average Lines |
|----------|-------|-----------|-----------|--------------|
| Root | 7 | 29 | 408 | ~150 |
| docs/ | 3 | 238 | 432 | ~333 |
| docs/workflows/ | 11 | ~200 | ~605 | ~320 |
| docs/standards/ | 11 | ~250 | ~667 | ~400 |
| docs/sprints/ | 3 | 31 | 515 | ~272 |
| .github/ | 3 | ~50 | ~150 | ~100 |
| examples/ | 53 | ~30 | ~150 | ~40 |
| **TOTAL** | **91** | **29** | **667** | **~110** |
---
## Compliance Status
### 500-Line Maximum Compliance
All documents comply with the 500-line maximum rule:
| Document | Lines | Status |
|----------|-------|--------|
| README.md | ~150 | ✅ |
| AGENT_GUARDRAILS.md | 267 | ✅ |
| HOW_TO_APPLY.md | 432 | ✅ |
| TEST_PRODUCTION_SEPARATION.md | 558 | ⚠️ Exceeds - needs split |
| AGENT_REVIEW_PROTOCOL.md | 605 | ⚠️ Exceeds - needs split |
| INFRASTRUCTURE_STANDARDS.md | 546 | ⚠️ Exceeds - needs split |
| OPERATIONAL_PATTERNS.md | 667 | ⚠️ Exceeds - needs split |
| All other workflows | ~280 average | ✅ |
| All other standards | ~380 average | ✅ |
| All sprints | ~270 average | ✅ |
**Note:** 4 documents exceed the 500-line limit. They will be split in a future release.
---
## Quick Lookup
**I need to...** → **Read this document:**
| Task | Document | Section |
|------|----------|---------|
| Find a document by keyword | INDEX_MAP.md | Quick Lookup Table |
| Understand safety rules | AGENT_GUARDRAILS.md | CORE PRINCIPLES (line 39) |
| Apply to existing repo | HOW_TO_APPLY.md | Option A (line 25) |
| Use example prompts | HOW_TO_APPLY.md | Option B (line 77) |
| Verify before committing | TESTING_VALIDATION.md | Post-Edit Validation (line 38) |
| Commit between to-dos | COMMIT_WORKFLOW.md | After Each To-Do (line 32) |
| Rollback changes | AGENT_EXECUTION.md | Rollback Procedures (line 51) |
| Review code | CODE_REVIEW.md | Self-Review Checklist (line 15) |
| Separate test/production | TEST_PRODUCTION_SEPARATION.md | CORE MANDATORY RULES (line 18) |
| Create task document | SPRINT_TEMPLATE.md | STEP-BY-STEP EXECUTION (line 91) |
| Write documentation | MODULAR_DOCUMENTATION.md | The 500-Line Rule (line 15) |
| Build game interfaces | 2026_GAME_DESIGN.md | XR/VR Comfort, Platform Rules |
| Design UI components | 2026_UI_UX_STANDARD.md | Components, Design Tokens |
| Ensure accessibility | ACCESSIBILITY_GUIDE.md | WCAG 3.0+ Compliance |
| Build XR/VR/AR UIs | SPATIAL_COMPUTING_UI.md | Comfort Zones, Latency |
| Prevent dark patterns | ETHICAL_ENGAGEMENT.md | Dark Pattern Taxonomy |
---
## File Templates
All files follow these conventions:
- **Line limit:** 500 lines (except TEST_PRODUCTION_SEPARATION.md pending split)
- **Markdown:** CommonMark with GitHub extensions
- **Headers:** Level 1 (H1) for title, Level 2 (H2) for sections
- **Code blocks:** Backtick fences with language identifier
- **Tables:** GitHub-flavored Markdown tables
- **Lists:** Bullet and numbered lists for hierarchy
---
**Authored by:** TheArchitectit
**Document Owner:** Project Maintainers
**Last Updated:** 2026-05-12
**Total Files:** 120
**Total Lines:** ~17,000

98
.guardrails/ci/Jenkinsfile vendored Normal file
View File

@ -0,0 +1,98 @@
// Jenkins Pipeline for Team Tools
// Place this file in your repository as Jenkinsfile
pipeline {
agent any
environment {
PYTHON_VERSION = '3.11'
GO_VERSION = '1.21'
PROJECT_NAME = 'team-tools'
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Validate Teams') {
steps {
script {
// Validate team sizes
sh """
python3 scripts/team_manager.py \\
--project ${env.PROJECT_NAME} \\
validate-size
"""
// Check team status
sh """
python3 scripts/team_manager.py \\
--project ${env.PROJECT_NAME} \\
status
"""
}
}
}
stage('Test Python') {
steps {
script {
sh """
pip install -r requirements.txt
pip install pytest pytest-cov
pytest scripts/ -v --cov=scripts --cov-report=xml
"""
}
}
post {
always {
publishTestResults testResultsPattern: '**/test-*.xml'
publishCoverage adapters: [coberturaAdapter('coverage.xml')]
}
}
}
stage('Test Go') {
steps {
script {
sh """
cd mcp-server
go test ./... -v -race
"""
}
}
}
stage('Build CLI') {
steps {
script {
sh """
cd cmd/team-cli
make build
"""
}
}
}
stage('Archive') {
steps {
archiveArtifacts artifacts: 'cmd/team-cli/team', fingerprint: true
}
}
}
post {
always {
cleanWs()
}
success {
echo 'Team validation successful!'
}
failure {
echo 'Team validation failed!'
}
}
}

View File

@ -0,0 +1,63 @@
# GitLab CI Configuration for Team Tools
# Copy this file to .gitlab-ci.yml in your repository
stages:
- validate
- test
- deploy
variables:
PYTHON_VERSION: "3.11"
GO_VERSION: "1.21"
# Validate team configurations
validate_teams:
stage: validate
image: python:$PYTHON_VERSION
script:
- pip install -r requirements.txt
- python3 scripts/team_manager.py --project $CI_PROJECT_NAME validate-size
- python3 scripts/team_manager.py --project $CI_PROJECT_NAME status
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
# Run unit tests
test_python:
stage: test
image: python:$PYTHON_VERSION
script:
- pip install -r requirements.txt
- pip install pytest pytest-cov
- pytest scripts/ -v --cov=scripts --cov-report=xml
coverage: '/TOTAL\s+\d+\s+\d+\s+(\d+%)/'
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage.xml
test_go:
stage: test
image: golang:$GO_VERSION
script:
- cd mcp-server
- go test ./... -v -race -coverprofile=coverage.out
- go tool cover -func=coverage.out
artifacts:
paths:
- mcp-server/coverage.out
# Deploy team configuration (if needed)
deploy_teams:
stage: deploy
image: python:$PYTHON_VERSION
script:
- echo "Team configuration validated and ready for deployment"
- python3 scripts/team_manager.py --project $CI_PROJECT_NAME export-json --file teams-export.json
artifacts:
paths:
- teams-export.json
only:
- main
- master

View File

@ -0,0 +1,116 @@
# Team CLI Makefile
# Build automation for the team management CLI tool
.PHONY: all build clean test install lint fmt deps
# Build variables
BINARY_NAME := team
BINARY_NAME_ALT := team-cli
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S')
GIT_COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
LDFLAGS := -ldflags "-X main.version=$(VERSION) -X main.buildTime=$(BUILD_TIME) -X main.gitCommit=$(GIT_COMMIT)"
# Go parameters
GOCMD := go
GOBUILD := $(GOCMD) build
GOCLEAN := $(GOCMD) clean
GOTEST := $(GOCMD) test
GOGET := $(GOCMD) get
GOMOD := $(GOCMD) mod
GOFMT := $(GOCMD) fmt
# Installation directories
PREFIX := /usr/local
BINDIR := $(PREFIX)/bin
# Default target
all: deps build
# Download dependencies
deps:
$(GOMOD) tidy
$(GOMOD) download
# Build the binary
build:
$(GOBUILD) $(LDFLAGS) -o $(BINARY_NAME) .
# Build with optimizations for release
release:
CGO_ENABLED=0 $(GOBUILD) $(LDFLAGS) -ldflags "-s -w" -trimpath -o $(BINARY_NAME) .
# Build for multiple platforms
cross-compile:
# Linux AMD64
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GOBUILD) $(LDFLAGS) -ldflags "-s -w" -trimpath -o dist/$(BINARY_NAME)-linux-amd64 .
# Linux ARM64
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 $(GOBUILD) $(LDFLAGS) -ldflags "-s -w" -trimpath -o dist/$(BINARY_NAME)-linux-arm64 .
# macOS AMD64
GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 $(GOBUILD) $(LDFLAGS) -ldflags "-s -w" -trimpath -o dist/$(BINARY_NAME)-darwin-amd64 .
# macOS ARM64
GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 $(GOBUILD) $(LDFLAGS) -ldflags "-s -w" -trimpath -o dist/$(BINARY_NAME)-darwin-arm64 .
# Windows AMD64
GOOS=windows GOARCH=amd64 CGO_ENABLED=0 $(GOBUILD) $(LDFLAGS) -ldflags "-s -w" -trimpath -o dist/$(BINARY_NAME)-windows-amd64.exe .
# Run tests
test:
$(GOTEST) -v -race ./...
# Run tests with coverage
test-coverage:
$(GOTEST) -v -race -coverprofile=coverage.out ./...
$(GOCMD) tool cover -html=coverage.out -o coverage.html
# Format code
fmt:
$(GOFMT) .
# Run linter (requires golangci-lint)
lint:
@which golangci-lint > /dev/null || (echo "golangci-lint not found, installing..." && go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest)
golangci-lint run ./...
# Install binary to system
install: build
@mkdir -p $(BINDIR)
@install -m 755 $(BINARY_NAME) $(BINDIR)/$(BINARY_NAME)
@ln -sf $(BINDIR)/$(BINARY_NAME) $(BINDIR)/$(BINARY_NAME_ALT) 2>/dev/null || true
@echo "Installed $(BINARY_NAME) to $(BINDIR)"
# Uninstall binary
uninstall:
@rm -f $(BINDIR)/$(BINARY_NAME)
@rm -f $(BINDIR)/$(BINARY_NAME_ALT)
@echo "Uninstalled $(BINARY_NAME) from $(BINDIR)"
# Clean build artifacts
clean:
$(GOCLEAN)
@rm -f $(BINARY_NAME)
@rm -f $(BINARY_NAME_ALT)
@rm -rf dist/
@rm -f coverage.out coverage.html
# Verify build works
verify: build
./$(BINARY_NAME) --version
./$(BINARY_NAME) --help
# Development mode with hot reload (requires air)
dev:
@which air > /dev/null || (echo "air not found, installing..." && go install github.com/cosmtrek/air@latest)
air -c .air.toml
# Update dependencies
update-deps:
$(GOMOD) tidy
$(GOMOD) update all
# Print build info
info:
@echo "Binary: $(BINARY_NAME)"
@echo "Version: $(VERSION)"
@echo "Build Time: $(BUILD_TIME)"
@echo "Git Commit: $(GIT_COMMIT)"
@echo "Go Version: $(shell go version)"

View File

@ -0,0 +1,272 @@
# Team CLI
A command-line interface for managing standardized team layouts across projects.
## Overview
The Team CLI provides a fast, intuitive interface for the team management system defined in `scripts/team_manager.py`. It supports all core team operations including initialization, role assignments, status tracking, and backups.
## Installation
### From Source
```bash
cd cmd/team-cli
make install
```
Or manually:
```bash
cd cmd/team-cli
go build -o team .
```
### Cross-Platform Build
```bash
make cross-compile
```
This creates binaries for:
- Linux (amd64, arm64)
- macOS (amd64, arm64)
- Windows (amd64)
## Usage
```
team [command] [flags]
```
### Global Flags
- `-p, --project string` - Project name (required for most commands)
- `-o, --output string` - Output format: `text`, `json` (default: `text`)
- `--version` - Show version information
## Commands
### init
Initialize a new project with the standardized 12-team structure.
```bash
team init my-project
```
### list
List all teams for a project.
```bash
team list -p my-project
team list -p my-project --phase "Phase 1"
```
### assign
Assign a person to a role.
```bash
team assign -p my-project -t 7 -r "Technical Lead" --person "Jane Developer"
```
### unassign
Remove a person from a role.
```bash
team unassign -p my-project -t 7 -r "Technical Lead"
```
### start
Mark a team as started/in-progress.
```bash
team start -p my-project -t 7
```
### complete
Mark a team as completed.
```bash
team complete -p my-project -t 7
```
### status
Show project or phase status.
```bash
team status -p my-project
team status -p my-project --phase "Phase 1"
```
### validate
Validate team sizes meet the 4-6 member requirement.
```bash
team validate -p my-project
```
### phase-gate
Check phase gate requirements.
```bash
team phase-gate -p my-project --from 1 --to 2
```
### agent-map
Get team mapping for an agent type.
```bash
team agent-map backend
team agent-map security
```
Supported agent types:
- `planner` - Team 2, Phase 1
- `architect` - Team 2, Phase 1
- `infrastructure` - Team 4, Phase 2
- `platform` - Team 5, Phase 2
- `backend` - Team 7, Phase 3
- `frontend` - Team 7, Phase 3
- `security` - Team 9, Phase 4
- `qa` - Team 10, Phase 4
- `sre` - Team 11, Phase 5
- `ops` - Team 12, Phase 5
### export
Export project data.
```bash
team export -p my-project -f json
team export -p my-project -f csv
```
### import
Import team assignments from a file.
```bash
team import -p my-project -f data.json --format json
team import -p my-project -f data.csv --format csv
```
### backup
List available backups.
```bash
team backup -p my-project
```
### restore
Restore from a backup.
```bash
team restore -p my-project -b .teams/backups/my-project_20250215_120000.json.gz
```
### delete
Delete a team or entire project.
```bash
# Delete a specific team
team delete -p my-project -t 7
# Delete entire project (with confirmation)
team delete -p my-project
# Force delete without confirmation
team delete -p my-project --force
```
## Examples
### Initialize and Setup a Project
```bash
# Create new project
team init web-platform
# Assign team members
team assign -p web-platform -t 2 -r "Solution Architect" --person "Alice Johnson"
team assign -p web-platform -t 2 -r "Domain Architect" --person "Bob Smith"
team assign -p web-platform -t 4 -r "Cloud Architect" --person "Carol White"
team assign -p web-platform -t 7 -r "Technical Lead" --person "David Brown"
# Check status
team status -p web-platform
# Validate team sizes
team validate -p web-platform
```
### Check Phase Gate
```bash
# Validate phase 1 is complete before moving to phase 2
team phase-gate -p web-platform --from 1 --to 2
```
### JSON Output for Scripting
```bash
# Get status in JSON format for automation
team status -p web-platform -o json | jq '.teams[] | select(.phase == "Phase 1")'
```
## Environment Variables
- `TEAM_MANAGER_PATH` - Path to the `team_manager.py` script (optional)
- `TEAM_ENCRYPTION_KEY` - Key for encrypted project data (optional)
## Requirements
- Go 1.23.2 or later
- Python 3.x (for team_manager.py backend)
- team_manager.py must be accessible (usually in `../../scripts/` relative to the binary)
## Development
### Build
```bash
make build
```
### Test
```bash
make test
```
### Format
```bash
make fmt
```
### Lint
```bash
make lint
```
## Architecture
The Team CLI is a Go application that wraps the existing `team_manager.py` Python script. Commands are translated to Python subprocess calls, with output formatted for the terminal using Charm's Lipgloss and Log libraries.
## License
Part of the Agent Guardrails Template project.

View File

@ -0,0 +1,24 @@
module github.com/thearchitectit/guardrail-mcp/cmd/team-cli
go 1.23.2
require (
github.com/charmbracelet/lipgloss v0.10.0
github.com/charmbracelet/log v0.4.0
github.com/spf13/cobra v1.8.0
)
require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect
golang.org/x/sys v0.29.0 // indirect
)

View File

@ -0,0 +1,45 @@
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/charmbracelet/lipgloss v0.10.0 h1:KWeXFSexGcfahHX+54URiZGkBFazf70JNMtwg/AFW3s=
github.com/charmbracelet/lipgloss v0.10.0/go.mod h1:Wig9DSfvANsxqkRsqj6x87irdy123SR4dOXlKa91ciE=
github.com/charmbracelet/log v0.4.0 h1:G9bQAcx8rWA2T3pWvx7YtPTPwgqpk7D68BX21IRW8ZM=
github.com/charmbracelet/log v0.4.0/go.mod h1:63bXt/djrizTec0l11H20t8FDSvA4CRZJ1KH22MdptM=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -0,0 +1,59 @@
#!/bin/bash
# Team CLI Installation Script
set -e
REPO_URL="https://github.com/thearchitectit/agent-guardrails-template"
INSTALL_DIR="/usr/local/bin"
BINARY_NAME="team"
# Detect OS and architecture
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$ARCH" in
x86_64)
ARCH="amd64"
;;
arm64|aarch64)
ARCH="arm64"
;;
*)
echo "Unsupported architecture: $ARCH"
exit 1
;;
esac
case "$OS" in
linux)
PLATFORM="linux"
;;
darwin)
PLATFORM="darwin"
;;
*)
echo "Unsupported OS: $OS"
exit 1
;;
esac
echo "Installing team CLI for $PLATFORM-$ARCH..."
# Check if running from source
if [ -f "cmd/team-cli/team" ]; then
echo "Installing from local build..."
cp "cmd/team-cli/team" "$INSTALL_DIR/$BINARY_NAME"
chmod +x "$INSTALL_DIR/$BINARY_NAME"
elif [ -f "team" ]; then
echo "Installing from current directory..."
cp "team" "$INSTALL_DIR/$BINARY_NAME"
chmod +x "$INSTALL_DIR/$BINARY_NAME"
else
echo "Binary not found. Please build from source with:"
echo " cd cmd/team-cli && make build"
exit 1
fi
echo "team CLI installed to $INSTALL_DIR/$BINARY_NAME"
echo ""
echo "Run 'team --help' to get started"

File diff suppressed because it is too large Load Diff

BIN
.guardrails/cmd/team-cli/team Executable file

Binary file not shown.

469
.guardrails/cpofopencode Normal file
View File

@ -0,0 +1,469 @@
{
"$schema": "https://opencode.ai/config.json",
"agent": {
"field": {
"description": "Field agent powered by GitHub Copilot with Mission Control tracking. Use for tasks that need to be logged and tracked in the dashboard.",
"mode": "subagent",
"model": "synthetic/qwen3-235b-thinking",
"prompt": "You are a field agent. Track your work using Mission Control tools (unified-mcp). Create sessions, log events, and record any failures you encounter. Be methodical and report progress."
},
"logician": {
"description": "Specialist in logical analysis, proofs, and formal reasoning. Use for tasks requiring rigorous logical thinking and deduction.",
"mode": "subagent",
"model": "synthetic/qwen3-235b-thinking",
"prompt": "You are a logician specialist. You excel at logical analysis, formal reasoning, and constructing rigorous proofs. Break down complex arguments, identify logical fallacies, and provide clear, structured reasoning."
},
"strategist": {
"description": "Long-term planning and strategic thinking specialist. Use for architectural decisions and project planning.",
"mode": "subagent",
"model": "synthetic/deepseek-r1",
"prompt": "You are a strategist. You excel at long-term planning, strategic thinking, and architectural design. Consider scalability, maintainability, and future implications in your recommendations."
},
"manager": {
"description": "Task coordination and project management specialist. Use for breaking down complex projects and coordinating workflows.",
"mode": "subagent",
"model": "synthetic/llama-3.3-70b",
"prompt": "You are a project manager. You excel at task coordination, breaking down complex projects into manageable pieces, and organizing workflows efficiently. Be clear, organized, and action-oriented."
},
"drafter": {
"description": "Template generation and boilerplate code specialist. Use for scaffolding and generating starter code.",
"mode": "subagent",
"model": "synthetic/qwen3-coder-480b",
"prompt": "You are a drafter. You excel at creating templates, boilerplate code, and starter projects. Generate clean, well-structured scaffolding that follows best practices and modern conventions."
},
"builder": {
"description": "Code implementation specialist. Use for actual code writing and feature implementation.",
"mode": "subagent",
"model": "synthetic/qwen3-coder-480b",
"prompt": "You are a builder. You excel at writing clean, efficient, and maintainable code. Follow best practices, write comprehensive comments, and ensure code quality. You are a coding specialist."
},
"specialist": {
"description": "Domain expertise and deep technical analysis. Use for complex technical challenges requiring specialized knowledge.",
"mode": "subagent",
"model": "synthetic/deepseek-v3.2",
"prompt": "You are a domain specialist. You provide deep technical expertise and advanced problem-solving. Analyze complex systems, identify edge cases, and provide expert-level insights."
},
"competitor": {
"description": "Alternative perspectives and critical analysis. Use for code review and exploring different approaches.",
"mode": "subagent",
"model": "synthetic/minimax-m2.1",
"prompt": "You are a competitor analyst. You provide alternative perspectives, challenge assumptions, and explore different approaches. Be constructively critical and suggest improvements."
},
"fixer": {
"description": "Debugging and bug fixing specialist. Use for identifying and resolving issues in code.",
"mode": "subagent",
"model": "synthetic/deepseek-v3.2",
"prompt": "You are a bug fix specialist. You excel at debugging, root cause analysis, and implementing robust fixes. Analyze error messages, trace execution flow, and provide thorough solutions."
},
"math_whiz": {
"description": "Mathematical analysis and algorithmic optimization specialist. Use for complex algorithms and mathematical problems.",
"mode": "subagent",
"model": "synthetic/qwen3-235b-thinking",
"prompt": "You are a mathematical specialist. You excel at mathematical analysis, algorithm design, and optimization. Provide rigorous mathematical reasoning and efficient algorithmic solutions."
},
"planner": {
"description": "Technical project planning and task breakdown. Use for planning implementation steps.",
"mode": "subagent",
"model": "synthetic/deepseek-r1",
"prompt": "You are a technical planner. Break down complex tasks into clear, actionable steps. Create detailed implementation plans with milestones and dependencies."
},
"developer": {
"description": "Senior software developer for code implementation. Use for writing production code.",
"mode": "subagent",
"model": "synthetic/qwen3-coder-480b",
"prompt": "You are a senior software developer. Write clean, maintainable code following best practices. Consider edge cases, error handling, and code quality."
},
"architect": {
"description": "Software architect for system design and architecture. Use for designing scalable systems.",
"mode": "subagent",
"model": "synthetic/deepseek-v3.2",
"prompt": "You are a software architect. Design scalable, maintainable systems with clear abstractions. Consider performance, security, and maintainability in your designs."
},
"reviewer": {
"description": "Code reviewer for quality assurance. Use for reviewing code and identifying issues.",
"mode": "subagent",
"model": "synthetic/llama-3.3-70b",
"prompt": "You are a code reviewer. Find bugs, security issues, and improvements. Be thorough and constructive. Provide actionable feedback and suggestions."
},
"tester": {
"description": "QA specialist for testing and validation. Use for creating tests and validating functionality.",
"mode": "subagent",
"model": "synthetic/qwen3-coder-480b",
"prompt": "You are a QA specialist. Design comprehensive tests and validate functionality. Consider edge cases, integration tests, and test coverage."
},
"documenter": {
"description": "Technical writer for documentation. Use for creating clear, comprehensive documentation.",
"mode": "subagent",
"model": "synthetic/qwen3-coder-480b",
"prompt": "You are a technical writer. Create clear, concise documentation. Write for your audience, include examples, and ensure completeness."
}
},
"plugin": [
"file:///home/user001/.config/opencode/plugin/opencode-google-antigravity-auth",
"oh-my-opencode@latest"
],
"model": "synthetic/kimi-k2.5-nvfp4-thinking",
"mcp": {
"unified-mcp": {
"type": "remote",
"url": "http://100.81.234.111:8080/mcp/stream/",
"headers": {
"X-API-Key": "mcp_zdentd2cy5igvk5t7j0fd4tlrx9jb889"
}
},
"mission-control-mcp": {
"type": "remote",
"url": "http://100.81.234.111:8081/mcp/stream/",
"headers": {
"X-API-Key": "mcp_zdentd2cy5igvk5t7j0fd4tlrx9jb889"
}
},
"radical-mcp": {
"type": "remote",
"url": "http://100.99.118.48:8081/mcp/stream/",
"headers": {
"X-API-Key": "secret"
}
},
"guardrails": {
"type": "remote",
"url": "http://100.96.49.42:8096/mcp/v1/sse",
"headers": {
"Authorization": "Bearer token",
"X-API-Key": "your-api-key-here"
}
}
},
"provider": {
"synthetic": {
"name": "Synthetic.new (Multi-Provider AI)",
"npm": "@ai-sdk/openai-compatible",
"options": {
"baseURL": "http://100.96.49.42:4001/openai/v1"
"apiKey": "ah-927a1830b3e9e855a6d6061985b7019045a7ca5006b9b2aa5d9828bd7fd81669"
},
"models": {
"qwen3-coder-480b": {
"id": "hf:Qwen/Qwen3-Coder-480B-A35B-Instruct",
"name": "Qwen3 Coder 480B (Code Specialist)"
},
"qwen3-235b-thinking": {
"id": "hf:Qwen/Qwen3-235B-A22B-Thinking-2507",
"name": "Qwen3 235B Thinking (Reasoning)"
},
"qwen3-235b-instruct": {
"id": "hf:Qwen/Qwen3-235B-A22B-Instruct-2507",
"name": "Qwen3 235B Instruct (General)"
},
"deepseek-v3.2": {
"id": "hf:deepseek-ai/DeepSeek-V3.2",
"name": "DeepSeek V3.2 (Latest, Powerful)"
},
"deepseek-r1": {
"id": "hf:deepseek-ai/DeepSeek-R1-0528",
"name": "DeepSeek R1 (Advanced Reasoning)"
},
"llama-3.3-70b": {
"id": "hf:meta-llama/Llama-3.3-70B-Instruct",
"name": "Llama 3.3 70B (Balanced)"
},
"llama-4-maverick": {
"id": "hf:meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
"name": "Llama 4 Maverick 17B (Fast, Multimodal)"
},
"gpt-oss-120b": {
"id": "hf:openai/gpt-oss-120b",
"name": "GPT-OSS 120B (Fast Generation)"
},
"minimax-m2.1": {
"id": "hf:MiniMaxAI/MiniMax-M2.1",
"name": "MiniMax M2.1 (Alternative Perspective)"
},
"kimi-k2-thinking": {
"id": "hf:moonshotai/Kimi-K2-Thinking",
"name": "Kimi K2 Thinking (Reasoning)"
},
"glm-4.7": {
"id": "hf:zai-org/GLM-4.7",
"name": "GLM 4.7 (Balanced)"
}
"models": {
"kimi-k2.5-nvfp4-thinking": {
"id": "hf:nvidia/Kimi-K2.5-NVFP4",
"name": "Kimi K2.5 NVFP4 (Thinking)",
"options": {
"temperature": 1.0
}
}
},
"api-gateway": {
"name": "API Gateway (Kimi K2.5 NVFP4)",
"npm": "@ai-sdk/openai-compatible",
"options": {
"baseURL": "http://100.96.49.42:4001/openai/v1",
"apiKey": "ah-927a1830b3e9e855a6d6061985b7019045a7ca5006b9b2aa5d9828bd7fd81669"
},
"models": {
"kimi-k2.5-nvfp4-thinking": {
"id": "hf:nvidia/Kimi-K2.5-NVFP4",
"name": "Kimi K2.5 NVFP4 (Thinking)",
"options": {
"temperature": 1.0
}
}
}
},
"local": {
"name": "Remote Desktop (NixOS Plasma 4080)",
"npm": "@ai-sdk/openai-compatible",
"options": {
"baseURL": "http://100.81.234.111:11434/v1"
},
"models": {
"qwen2.5-coder:1.5b": {
"name": "Qwen 2.5 Coder 1.5B (Ultra Fast)"
},
"qwen2.5-coder:3b": {
"name": "Qwen 2.5 Coder 3B (Fast - MCP Default)"
},
"qwen2.5-coder:7b": {
"name": "Qwen 2.5 Coder 7B (Balanced)"
},
"qwen2.5-coder:14b": {
"name": "Qwen 2.5 Coder 14B (Heavy Tier)"
},
"qwen2.5-coder:32b": {
"name": "Qwen 2.5 Coder 32B (Max Quality)"
},
"architect-nemotron-30b": {
"name": "01. The Agent (Nemotron-3 30B)"
},
"qwen3:32b": {
"name": "02. The Logician (Qwen3 32B)"
},
"architect-yi-34b": {
"name": "03. The Strategist (Yi 1.5 34B)"
},
"architect-command-r-32b": {
"name": "04. The Manager (Command R 32B)"
},
"codegpt-oss-patched": {
"name": "05. The Drafter (CodeGPT OSS 20B)"
},
"qwen3-thinking-30b": {
"name": "06. The Builder (Qwen 3 Thinking 30B)"
},
"deepkat-32b": {
"name": "07. The Specialist (DeepKAT 32B)"
},
"kwaicoder-23b": {
"name": "08. The Competitor (KwaiCoder 23B)"
},
"kiteresolve-20b": {
"name": "09. The Fixer (KiteResolve 20B)"
},
"qwen3-griffon-14b": {
"name": "10. The Math Whiz (Griffon 14B)"
}
}
},
"google": {
"npm": "@ai-sdk/google",
"options": {
"antigravity": true
},
"models": {
"gemini-3-pro-preview": {
"id": "gemini-3-pro-preview",
"name": "Gemini 3 Pro Preview",
"release_date": "2025-11-18",
"reasoning": true,
"limit": {
"context": 1000000,
"output": 64000
},
"cost": {
"input": 2,
"output": 12,
"cache_read": 0.2
},
"modalities": {
"input": [
"text",
"image",
"video",
"audio",
"pdf"
],
"output": [
"text"
]
}
},
"gemini-3-pro-high": {
"id": "gemini-3-pro-preview",
"name": "Gemini 3 Pro Preview (High Thinking)",
"options": {
"thinkingConfig": {
"thinkingLevel": "high",
"includeThoughts": true
}
}
},
"gemini-3-pro-medium": {
"id": "gemini-3-pro-preview",
"name": "Gemini 3 Pro Preview (Medium Thinking)",
"options": {
"thinkingConfig": {
"thinkingLevel": "medium",
"includeThoughts": true
}
}
},
"gemini-3-flash": {
"id": "gemini-3-flash",
"name": "Gemini 3 Flash",
"release_date": "2025-12-17",
"reasoning": true,
"limit": {
"context": 1048576,
"output": 65536
},
"cost": {
"input": 0.5,
"output": 3,
"cache_read": 0.05
},
"modalities": {
"input": [
"text",
"image",
"video",
"audio",
"pdf"
],
"output": [
"text"
]
}
},
"gemini-3-flash-high": {
"id": "gemini-3-flash",
"name": "Gemini 3 Flash (High Thinking)",
"options": {
"thinkingConfig": {
"thinkingLevel": "high",
"includeThoughts": true
}
}
},
"gemini-2.5-flash": {
"id": "gemini-2.5-flash",
"name": "Gemini 2.5 Flash",
"limit": {
"context": 1048576,
"output": 65536
},
"cost": {
"input": 0.3,
"output": 2.5
},
"modalities": {
"input": [
"text",
"image",
"audio",
"video",
"pdf"
],
"output": [
"text"
]
}
},
"gemini-claude-sonnet-4-5-thinking-high": {
"id": "gemini-claude-sonnet-4-5-thinking",
"name": "Claude Sonnet 4.5 (High Thinking)",
"release_date": "2025-11-18",
"reasoning": true,
"limit": {
"context": 200000,
"output": 64000
},
"cost": {
"input": 3,
"output": 15,
"cache_read": 0.3
},
"modalities": {
"input": [
"text",
"image",
"pdf"
],
"output": [
"text"
]
},
"options": {
"thinkingConfig": {
"thinkingBudget": 32000,
"includeThoughts": true
}
}
},
"gemini-claude-opus-4-5-thinking-high": {
"id": "gemini-claude-opus-4-5-thinking",
"name": "Claude Opus 4.5 (High Thinking)",
"release_date": "2025-11-24",
"reasoning": true,
"limit": {
"context": 200000,
"output": 64000
},
"cost": {
"input": 5,
"output": 25,
"cache_read": 0.5
},
"modalities": {
"input": [
"text",
"image",
"pdf"
],
"output": [
"text"
]
},
"options": {
"thinkingConfig": {
"thinkingBudget": 32000,
"includeThoughts": false
}
}
},
"gemini-claude-opus-4-5-thinking-medium": {
"id": "gemini-claude-opus-4-5-thinking",
"name": "Claude Opus 4.5 (Medium Thinking)",
"options": {
"thinkingConfig": {
"thinkingBudget": 16000,
"includeThoughts": false
}
}
},
"gemini-claude-opus-4-5-thinking-low": {
"id": "gemini-claude-opus-4-5-thinking",
"name": "Claude Opus 4.5 (Low Thinking)",
"options": {
"thinkingConfig": {
"thinkingBudget": 4000,
"includeThoughts": false
}
}
}
}
}
}
}

View File

@ -0,0 +1,492 @@
# Agents & Skills Setup Guide
Install guardrails skills, agents, and hooks across all supported AI coding platforms.
## Quick Start
| Platform | Setup Time | Install Command |
|----------|-----------|-----------------|
| Claude Code | 30s | `python scripts/setup_agents.py --install --platform claude` |
| Cursor | 30s | `python scripts/setup_agents.py --install --platform cursor` |
| Windsurf | 10s | `python scripts/setup_agents.py --install --platform windsurf` |
| OpenCode | 30s | `python scripts/setup_agents.py --install --platform opencode` |
| GitHub Copilot | 10s | `python scripts/setup_agents.py --install --platform copilot` |
| All platforms | 1min | `python scripts/setup_agents.py --install` |
## Platform Comparison
| Feature | Claude Code | Cursor | Windsurf | OpenCode | GitHub Copilot |
|---------|-------------|--------|----------|----------|----------------|
| Config location | `.claude/skills/` | `.cursor/rules/` | `.windsurfrules` | `.opencode/` | `.github/copilot-instructions.md` |
| Format | JSON | Markdown + YAML frontmatter | Single markdown | JSON + markdown | Markdown |
| Skills | 7 JSON files | 4 rule files | Single file | 3 skill dirs | None (repo-level) |
| Agents | No | No | No | 2 JSON files | No |
| Hooks | 3 shell scripts | No | No | No | No |
| Granular control | Per-skill install | Per-rule apply | All-or-nothing | Per-skill enable | All-or-nothing |
| Auto-install | Yes | Yes | Yes | Yes | Yes |
## Installation Methods
### 1. MCP Tool (Automated)
Use the `guardrail_install_skills` MCP tool from any AI session:
```javascript
// Full platform install
guardrail_install_skills({ platforms: "claude,cursor", target_path: "/path/to/project" })
// Clone a single file from GitHub
guardrail_install_skills({ action: "clone", path: ".claude/skills/guardrails-enforcer.json" })
// Install a single skill by name
guardrail_install_skills({ action: "install", skill: "guardrails-enforcer" })
// List available skills
guardrail_install_skills({ list_skills: true })
// List available platforms
guardrail_install_skills({ list_platforms: true })
```
### 2. Python Script (CLI)
```bash
# Install all platforms (copy mode)
python scripts/setup_agents.py --install
# Install specific platforms
python scripts/setup_agents.py --install --platform claude,cursor
# Symlink mode (live updates when repo changes)
python scripts/setup_agents.py --install --platform claude --mode symlink
# Dry run (preview without writing)
python scripts/setup_agents.py --install --dry-run
# Install to a different project directory
python scripts/setup_agents.py --install --platform claude --target ~/myproject
# Install a single skill by name
python scripts/setup_agents.py --install-skill guardrails-enforcer
# Clone a single file from GitHub (no local repo needed)
python scripts/setup_agents.py --clone .claude/skills/guardrails-enforcer.json
python scripts/setup_agents.py --clone .cursor/rules/guardrails-enforcer.md --target ~/myproject
# List available skills and platforms
python scripts/setup_agents.py --list-skills
python scripts/setup_agents.py --list-platforms
```
### 3. Manual Copy
Copy the config directories directly to your project:
```bash
# Claude Code
cp -r .claude/skills/ /path/to/project/.claude/skills/
cp -r .claude/hooks/ /path/to/project/.claude/hooks/
# Cursor
cp -r .cursor/rules/ /path/to/project/.cursor/rules/
# Windsurf
cp .windsurfrules /path/to/project/.windsurfrules
# OpenCode
cp -r .opencode/ /path/to/project/.opencode/
# GitHub Copilot
mkdir -p /path/to/project/.github/
cp .github/copilot-instructions.md /path/to/project/.github/copilot-instructions.md
```
### 4. Symlink (Live Updates)
```bash
# Claude Code (tracks repo changes)
ln -s "$(pwd)/.claude/skills" /path/to/project/.claude/skills
ln -s "$(pwd)/.claude/hooks" /path/to/project/.claude/hooks
# OpenCode
ln -s "$(pwd)/.opencode" /path/to/project/.opencode
```
## Per-Platform Guides
### Claude Code
**Config files:** `.claude/skills/*.json`, `.claude/hooks/*.sh`
**Skills (7):**
| Skill | File | Purpose |
|-------|------|---------|
| guardrails-enforcer | `guardrails-enforcer.json` | Four Laws enforcement on all operations |
| commit-validator | `commit-validator.json` | Commit message format and safety checks |
| env-separator | `env-separator.json` | Test/production environment isolation |
| scope-validator | `scope-validator.json` | File scope authorization checks |
| production-first | `production-first.json` | Production code before tests/infra |
| three-strikes | `three-strikes.json` | Retry limit and halt escalation |
| error-recovery | `error-recovery.json` | Structured error handling |
**Hooks (3):**
| Hook | File | Trigger |
|------|------|---------|
| Pre-execution | `pre-execution.sh` | Before every tool call |
| Post-execution | `post-execution.sh` | After every tool call |
| Pre-commit | `pre-commit.sh` | Before git commit |
**Skill format (JSON):**
```json
{
"name": "guardrails-enforcer",
"description": "Enforces the Four Laws of Agent Safety",
"tools": ["Read", "Grep", "Glob", "AskUserQuestion"],
"prompt": "Your skill instructions here..."
}
```
**Install:**
```bash
python scripts/setup_agents.py --install-skill guardrails-enforcer
```
**Verify:**
```bash
ls .claude/skills/ # Should show 7 JSON files
ls .claude/hooks/ # Should show 3 shell scripts
```
### Cursor
**Config files:** `.cursor/rules/*.md`
**Rules (4):**
| Rule | File | Always Apply |
|------|------|-------------|
| guardrails-enforcer | `guardrails-enforcer.md` | Yes |
| production-first | `production-first.md` | Yes |
| three-strikes | `three-strikes.md` | Yes |
| clean-architecture | `clean-architecture.md` | Yes |
**Rule format (Markdown + YAML frontmatter):**
```markdown
---
description: Enforces the Four Laws of Agent Safety on all code generation
globs: "**/*"
alwaysApply: true
---
# Guardrails Enforcement
Your rule instructions here...
```
Frontmatter fields:
- `description` — Shows in Cursor rules panel
- `globs` — File patterns where rule applies
- `alwaysApply``true` to auto-attach, `false` for manual
**Install:**
```bash
python scripts/setup_agents.py --install --platform cursor
```
**Verify:**
```bash
ls .cursor/rules/ # Should show 4 markdown files
```
### Windsurf
**Config file:** `.windsurfrules` (single file)
**Format:** Single markdown file containing all rules. Windsurf does not support per-skill granularity or agent configuration.
The file includes:
- Four Laws of Agent Safety
- Pre-operation checklist and forbidden actions
- Three Strikes Rule
- Production-First Rule
- Scope Rules
- Architecture patterns (Clean Architecture, CQRS, Vertical Slices, SOLID)
- References to shared prompts
**Install:**
```bash
python scripts/setup_agents.py --install --platform windsurf
# Or manually:
cp .windsurfrules /path/to/project/.windsurfrules
```
**Verify:**
```bash
test -f .windsurfrules && echo "Installed" || echo "Missing"
```
### OpenCode
**Config files:** `.opencode/oh-my-opencode.jsonc`, `.opencode/agents/*.json`, `.opencode/skills/<name>/SKILL.md`
**Agents (2):**
| Agent | File | Permissions |
|-------|------|------------|
| guardrails-auditor | `guardrails-auditor.json` | Read-only (edit: deny, bash: deny) |
| doc-indexer | `doc-indexer.json` | Read + edit (bash: deny) |
**Skills (3):**
| Skill | Directory |
|-------|-----------|
| guardrails-enforcer | `skills/guardrails-enforcer/SKILL.md` |
| commit-validator | `skills/commit-validator/SKILL.md` |
| env-separator | `skills/env-separator/SKILL.md` |
**Config format (JSONC):**
```jsonc
{
"agents": {
"guardrails-auditor": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "You are a Guardrails Auditor...",
"permissions": { "edit": "deny", "bash": "deny", "read": "allow" }
}
},
"skills": {
"sources": [{"path": "./.opencode/skills", "recursive": true}],
"enable": ["guardrails-enforcer", "commit-validator", "env-separator"]
}
}
```
**Skill format (Markdown + YAML frontmatter):**
```markdown
---
name: guardrails-enforcer
description: "Enforces the Four Laws of Agent Safety"
---
# Guardrails Enforcement
Your skill instructions here...
```
Agent format (JSON):
```json
{
"name": "guardrails-auditor",
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "You are a Guardrails Auditor...",
"permissions": { "edit": "deny", "bash": "deny", "read": "allow" }
}
```
**Install:**
```bash
python scripts/setup_agents.py --install --platform opencode
```
**Verify:**
```bash
test -f .opencode/oh-my-opencode.jsonc && echo "Config OK"
ls .opencode/agents/ # Should show 2 JSON files
ls .opencode/skills/ # Should show 3 skill directories
```
### GitHub Copilot
**Config file:** `.github/copilot-instructions.md`
**Format:** Markdown repo-level instructions. Copilot does not support per-skill configuration, agent definitions, or hooks. All rules are merged into a single file.
The file includes:
- Four Laws of Agent Safety (adapted for autocomplete/chat)
- Code generation rules (scope, production-first, error handling, security)
- Forbidden patterns
- Three Strikes Rule
- File header conventions
- Architecture patterns for the MCP server
- References to shared prompts
**Install:**
```bash
python scripts/setup_agents.py --install --platform copilot
# Or manually:
mkdir -p /path/to/project/.github/
cp .github/copilot-instructions.md /path/to/project/.github/copilot-instructions.md
```
**Verify:**
```bash
test -f .github/copilot-instructions.md && echo "Installed" || echo "Missing"
```
## Shared Prompts
All platform configs derive from canonical prompt files in `skills/shared-prompts/`. These are the source of truth — when rules change, update the shared prompt first, then regenerate platform configs.
| Prompt | File | Description |
|--------|------|-------------|
| Four Laws | `four-laws.md` | Read-before-edit, stay-in-scope, verify-before-commit, halt-when-uncertain |
| Halt Conditions | `halt-conditions.md` | When and how to stop and escalate to user |
| Vibe Coding | `vibe-coding.md` | Flow-state development under constraints |
| Error Recovery | `error-recovery.md` | Structured error handling and retry patterns |
| Three Strikes | `three-strikes.md` | Three-attempt limit with escalating escalation |
| Production First | `production-first.md` | Production code before tests and infrastructure |
| Scope Validation | `scope-validation.md` | File and operation scope authorization |
| Clean Architecture | `clean-architecture.md` | Domain-first layering, dependency inversion |
| CQRS | `cqrs.md` | Command/query separation for write/read operations |
## MCP Tool Usage
The `guardrail_install_skills` MCP tool wraps the setup script. Use it from any AI coding session.
**Full install:**
```javascript
guardrail_install_skills({
platforms: "claude,cursor",
target_path: "/path/to/project"
})
```
**Per-skill install:**
```javascript
guardrail_install_skills({
action: "install",
skill: "guardrails-enforcer",
platform: "claude",
target_path: "/path/to/project"
})
```
**Clone from GitHub:**
```javascript
guardrail_install_skills({
action: "clone",
path: ".claude/skills/guardrails-enforcer.json",
target_path: "/path/to/project"
})
```
**List skills:**
```javascript
guardrail_install_skills({ list_skills: true })
```
**List platforms:**
```javascript
guardrail_install_skills({ list_platforms: true })
```
## Architecture Reference
For the MCP server codebase that underpins these guardrails:
- [ARCHITECTURE_CLEAN_CQRS.md](ARCHITECTURE_CLEAN_CQRS.md) — Full Clean Architecture + CQRS design
- [skills/shared-prompts/clean-architecture.md](../skills/shared-prompts/clean-architecture.md) — Domain-first layering patterns
- [skills/shared-prompts/cqrs.md](../skills/shared-prompts/cqrs.md) — Command/query separation patterns
## Customization
Edit generated files directly in your project, or create new ones:
**Claude Code** — add a JSON file to `.claude/skills/`:
```json
{
"name": "my-custom-skill",
"description": "What this skill does",
"tools": ["Read", "Grep"],
"prompt": "Your skill instructions here..."
}
```
**OpenCode** — add a `SKILL.md` under `.opencode/skills/<name>/`:
```markdown
---
name: my-custom-skill
description: "What this skill does"
---
# My Custom Skill
Your skill instructions here...
```
**Cursor** — add a markdown file to `.cursor/rules/`:
```markdown
---
description: What this rule does
globs: "**/*.go"
alwaysApply: false
---
# My Custom Rule
Your rule instructions here...
```
**Remove all configuration:**
```bash
rm -rf .claude/ .cursor/ .opencode/ .windsurfrules .github/copilot-instructions.md
```
## Troubleshooting
### Skills Not Loading
- **Claude Code:** Verify `.claude/skills/` has JSON files. Check syntax: `python -m json.tool .claude/skills/guardrails-enforcer.json`. Restart after adding skills.
- **Cursor:** Verify `.cursor/rules/` has `.md` files. Check YAML frontmatter has `description`, `globs`, `alwaysApply`. Check settings > Rules.
- **OpenCode:** Verify `oh-my-opencode.jsonc` syntax. Check skills are listed in `skills.enable`. Confirm `SKILL.md` exists in each skill dir. Restart.
- **Hooks not running:** Ensure executable (`chmod +x .claude/hooks/*.sh`). Check syntax: `bash -n .claude/hooks/pre-commit.sh`.
### MCP Tool Not Found
- Ensure the guardrails MCP server is configured in your AI tool's MCP settings
- Check the server process is running: the server provides `guardrail_install_skills`
- Verify connection in your platform's MCP panel
### Install Script Errors
```bash
# Check Python version (3.8+ required)
python --version
# Run with verbose output
python scripts/setup_agents.py --install --dry-run
# Verify write permissions on target
touch /path/to/project/.claude/test && rm /path/to/project/.claude/test
```
## References
- [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) — Core safety protocols
- [COMMIT_WORKFLOW.md](workflows/COMMIT_WORKFLOW.md) — Commit standards
- [TEST_PRODUCTION_SEPARATION.md](standards/TEST_PRODUCTION_SEPARATION.md) — Environment isolation
- [AGENT_EXECUTION.md](workflows/AGENT_EXECUTION.md) — Execution protocols

View File

@ -0,0 +1,319 @@
# Agent Guardrails & Safety Protocols
**Version:** 1.3
**Last Updated:** 2026-01-21
**Applies To:** ALL AI agents, LLMs, and automated systems operating on this codebase
---
## Applicability
This document is **MANDATORY** for:
| System Type | Examples | Binding? |
|-------------|----------|----------|
| **Large Language Models** | Claude, GPT-4/o1/o3, Gemini, LLaMA, Mistral, Qwen, DeepSeek, Cohere, Phi, Falcon, and 30+ other model families | YES |
| **AI Coding Assistants** | Claude Code, GitHub Copilot, Cursor, Cody, Aider, Continue, Windsurf, and others | YES |
| **Autonomous Agents** | AutoGPT, AgentGPT, CrewAI, LangChain, LangGraph, Semantic Kernel agents | YES |
| **Reasoning Models** | o1, o3, DeepSeek-R1, and other chain-of-thought models | YES |
| **CI/CD Bots** | Dependabot, Renovate, automated PR bots | YES |
| **Custom Agents** | Any agent built on this codebase (specialists, operators, swarm) | YES |
| **Human Developers** | Recommended best practices | RECOMMENDED |
**If you are an AI system reading this:** You MUST follow these protocols. They are not suggestions.
---
## Purpose
This document defines mandatory safety protocols, guardrails, and behavioral constraints for ALL automated systems performing tasks on this repository. These rules exist to:
1. **Prevent data loss** — enabling safe rapid iteration without backup anxiety
2. **Maintain code quality** — so AI-generated code ships without manual review overhead
3. **Preserve history** — keeping git history clean and reversible
4. **Enable collaboration** — allowing humans and agents to work together safely
5. **Limit blast radius** — containing errors to minimal scope
### How These Laws Enable Rapid Development
The Four Laws aren't restrictions — they're accelerators. Here's why:
- **Read Before Editing** eliminates rework. One read costs fewer tokens than fixing a blind edit.
- **Stay in Scope** prevents cascade failures. Agents move faster when they're not untangling unintended side effects.
- **Verify Before Committing** catches errors at the cheapest point. A failed test in development costs minutes; in production, it costs hours.
- **Halt When Uncertain** prevents wasted effort. Asking one question is cheaper than building the wrong thing.
When agents follow these laws, they don't need to pause for safety checks — safety is built into every step. The result: full-velocity development with production-grade reliability.
---
## CORE PRINCIPLES
### The Four Laws of Agent Safety
See [skills/shared-prompts/four-laws.md](../skills/shared-prompts/four-laws.md) for the complete Four Laws documentation.
**Quick Reference:**
1. **Read Before Editing** - Never modify code without reading first
2. **Stay in Scope** - Only touch authorized files
3. **Verify Before Committing** - Test all changes
4. **Halt When Uncertain** - Ask instead of guessing
---
## SAFETY PROTOCOLS (MANDATORY)
### Pre-Execution Checklist
**EVERY agent MUST verify these before ANY file modification:**
| # | Check | Requirement | Verify |
|---|-------|-------------|--------|
| 1 | **READ FIRST** | NEVER edit a file without reading it first | [ ] |
| 2 | **SCOPE LOCK** | Only modify files explicitly in scope | [ ] |
| 3 | **NO FEATURE CREEP** | Do NOT add features, refactor, or "improve" unrelated code | [ ] |
| 4 | **PRODUCTION FIRST** | Production code created BEFORE test code | [ ] |
| 5 | **TEST/PROD SEPARATION** | Test infrastructure is separate from production | [ ] |
| 6 | **BACKUP AWARENESS** | Know the rollback command before editing | [ ] |
| 7 | **TEST BEFORE COMMIT** | All tests must pass before committing | [ ] |
| 8 | **CHECK FAILURE REGISTRY** | Review known bugs for affected files ([.guardrails/pre-work-check.md](../.guardrails/pre-work-check.md)) | [ ] |
| 9 | **VERIFY FIXES INTACT** | Confirm previous fixes not being undone | [ ] |
### Git Safety Rules
| Rule | Description | Consequence |
|------|-------------|-------------|
| **NO FORCE PUSH** | Never use `git push --force` | Data loss, history corruption |
| **NO AMEND** | Do not amend commits you didn't create this session | Breaks collaborator history |
| **NO CONFIG CHANGES** | Do not modify git config | Security/identity issues |
| **NO PUSH WITHOUT PERMISSION** | Only push if user explicitly requests | Unwanted remote changes |
| **SINGLE COMMIT** | One focused commit per task | Maintains clean history |
| **NO SKIP HOOKS** | Never use `--no-verify` | Bypasses safety checks |
| **NO REBASE** | Never rebase shared branches | Destroys collaborator work |
| **NO DESTRUCTIVE OPS** | No `reset --hard` on shared branches | Irreversible data loss |
### Code Safety Rules
| Rule | Rationale |
|------|-----------|
| **EXACT REPLACEMENT** | Use provided code exactly - no "improvements" |
| **NO NEW IMPORTS** | Unless explicitly required by the task |
| **NO TYPE CHANGES** | Preserve existing type hints |
| **NO DELETIONS** | Do not delete functionality outside scope |
| **PRESERVE FORMATTING** | Match existing indentation and style |
| **NO SECRETS** | Never commit credentials, keys, tokens |
| **NO BINARY FILES** | Unless explicitly required |
| **NO GENERATED CODE** | Do not commit build artifacts |
### Test/Production Separation Rules (MANDATORY)
| Rule | Violation Level | Action |
|------|-----------------|--------|
| **PRODUCTION CODE FIRST** | CRITICAL | Halt, ask user |
| **SEPARATE DATABASES** | CRITICAL | Halt, ask user |
| **SEPARATE SERVICES** | CRITICAL | Halt, ask user |
| **NO TEST USERS IN PROD** | CRITICAL | Halt, rollback |
| **NO PROD CREDENTIALS IN TEST** | CRITICAL | Halt, rollback |
| **ASK IF UNCERTAIN** | HIGH | Ask user before proceeding |
**Full details:** See [TEST_PRODUCTION_SEPARATION.md](standards/TEST_PRODUCTION_SEPARATION.md)
---
## GUARDRAILS
### HALT CONDITIONS
**Stop immediately and report to user if ANY of these occur:**
```
CRITICAL HALT - DO NOT PROCEED:
[ ] Target file does not exist
[ ] Line numbers don't match expected
[ ] File has unexpected modifications
[ ] Syntax check fails after edit
[ ] Any test fails after edit
[ ] Merge conflicts encountered
[ ] Uncertain about ANY step
[ ] Edit tool reports "string not found"
[ ] Permission denied errors
[ ] Import errors when testing
[ ] Network/connection errors
[ ] Out of memory errors
[ ] Timeout errors
[ ] User requests stop
[ ] Test/production boundary unclear
[ ] Attempting to use production DB for tests
[ ] Attempting to use test DB for production
```
### FORBIDDEN ACTIONS
**No agent may perform these actions under any circumstances:**
```
ABSOLUTE PROHIBITIONS:
FILE OPERATIONS:
- Modify files outside declared scope
- Delete files without explicit permission
- Create files without explicit need
- Modify hidden/system files (.*) without permission
- Change file permissions
CODE CHANGES:
- Add logging/debugging to production code
- Add comments that weren't requested
- "Clean up" or "improve" surrounding code
- Update version numbers without explicit request
- Change security configurations
- Modify authentication/authorization code without review
TEST/PRODUCTION SEPARATION:
- Deploy test code to production environment
- Use production database for tests
- Create test users in production database
- Write test code that imports production secrets
- Use production services for test execution
- Share user accounts across environments
GIT OPERATIONS:
- Force push to any branch
- Delete branches without permission
- Modify git hooks
- Change git config
- Push without explicit permission
SYSTEM OPERATIONS:
- Run servers or long-running services
- Execute commands requiring user input
- Make network requests to unknown endpoints
- Install new dependencies without permission
- Modify CI/CD pipelines without permission
- Execute shell commands with elevated privileges
- Access or modify environment variables
DATA OPERATIONS:
- Access databases without explicit permission
- Modify production data
- Export or transmit user data
- Store credentials or secrets
- Mix test and production data
```
### SCOPE BOUNDARIES
**For any task, clearly define IN/OUT scope:**
```
IN SCOPE (may modify):
- Specific file(s) listed in task
- Specific line ranges identified
- Exact changes described
- Production code (before test code)
OUT OF SCOPE (DO NOT TOUCH):
- All other files
- All other methods/functions in target file
- Tests in production files (read-only unless task is test-related)
- Documentation (unless task is doc-related)
- Git hooks and configs
- CI/CD configurations
- Dependencies/package files
- Environment configurations
- Security-related files
- Production database connections in test code
- Test database connections in production code
```
---
## QUICK REFERENCE
```
+------------------------------------------------------------------+
| UNIVERSAL AGENT GUARDRAILS |
+------------------------------------------------------------------+
| ALWAYS: |
| - Read before edit |
| - Verify before proceeding |
| - Test before committing |
| - Create production code BEFORE test code |
| - Separate test/production infrastructure |
| - Report results to user |
| - Include AI attribution |
+------------------------------------------------------------------+
| NEVER: |
| - Edit without reading |
| - Push without permission |
| - Modify outside scope |
| - Force push or rebase |
| - Continue when uncertain |
| - Use production DB for tests |
| - Create test users in production |
+------------------------------------------------------------------+
| HALT IF: |
| - Conditions don't match |
| - Any check fails |
| - Uncertain about anything |
| - User requests stop |
| - Test/production boundary unclear |
+------------------------------------------------------------------+
| ROLLBACK: git checkout HEAD -- <file> |
+------------------------------------------------------------------+
| APPLIES TO: ALL LLMs, AI assistants, coding agents, and automated systems |
+------------------------------------------------------------------+
```
---
## RELATED DOCUMENTS
### Core Guardrails
- **This document** - Core safety protocols (MANDATORY)
- [TEST_PRODUCTION_SEPARATION.md](standards/TEST_PRODUCTION_SEPARATION.md) - Test/production isolation (MANDATORY)
- [REGRESSION_PREVENTION.md](workflows/REGRESSION_PREVENTION.md) - Bug tracking and regression prevention
### Regression Prevention
- [.guardrails/pre-work-check.md](../.guardrails/pre-work-check.md) - MANDATORY pre-work checklist
- [.guardrails/failure-registry.jsonl](../.guardrails/failure-registry.jsonl) - Bug database (JSONL format)
- [scripts/log_failure.py](../scripts/log_failure.py) - CLI to log new failures
- [scripts/regression_check.py](../scripts/regression_check.py) - Pre-commit regression scanner
### Workflow Documentation
- [AGENT_EXECUTION.md](workflows/AGENT_EXECUTION.md) - Execution protocol, rollback, Three Strikes Rule
- [AGENT_REVIEW_PROTOCOL.md](workflows/AGENT_REVIEW_PROTOCOL.md) - Post-work agent/LLM review (RECOMMENDED)
- [TESTING_VALIDATION.md](workflows/TESTING_VALIDATION.md) - Validation protocols
- [COMMIT_WORKFLOW.md](workflows/COMMIT_WORKFLOW.md) - Commit guidelines
- [GIT_PUSH_PROCEDURES.md](workflows/GIT_PUSH_PROCEDURES.md) - Push safety
- [ROLLBACK_PROCEDURES.md](workflows/ROLLBACK_PROCEDURES.md) - Recovery operations
- [MCP_CHECKPOINTING.md](workflows/MCP_CHECKPOINTING.md) - Checkpoint integration
### Agent Operations
- [AGENT_ESCALATION.md](workflows/AGENT_ESCALATION.md) - Audit requirements and escalation
- [CODE_REVIEW.md](workflows/CODE_REVIEW.md) - Code review process
### Standards
- [PROJECT_CONTEXT_TEMPLATE.md](standards/PROJECT_CONTEXT_TEMPLATE.md) - Project Bible template
- [ADVERSARIAL_TESTING.md](standards/ADVERSARIAL_TESTING.md) - Breaker agent, fuzz testing
- [DEPENDENCY_GOVERNANCE.md](standards/DEPENDENCY_GOVERNANCE.md) - Package allow-list
- [INFRASTRUCTURE_STANDARDS.md](standards/INFRASTRUCTURE_STANDARDS.md) - IaC, Terraform, drift detection
- [OPERATIONAL_PATTERNS.md](standards/OPERATIONAL_PATTERNS.md) - Health checks, circuit breakers
- [LOGGING_PATTERNS.md](standards/LOGGING_PATTERNS.md) - Structured logging
- [MODULAR_DOCUMENTATION.md](standards/MODULAR_DOCUMENTATION.md) - 500-line rule
### Sprint Framework
- [Sprint Task Template](sprints/) - Task execution format
- [SPRINT_GUIDE.md](sprints/SPRINT_GUIDE.md) - How to write sprints
### Security
- [SECRETS_MANAGEMENT.md](../.github/SECRETS_MANAGEMENT.md) - GitHub Secrets
---
**Authored by:** TheArchitectit
**Document Owner:** Project Maintainers
**Review Cycle:** Monthly
**Last Review:** 2026-01-21
**Next Review:** 2026-02-21

View File

@ -0,0 +1,604 @@
# System Architecture
> Architecture diagrams and component documentation for Agent Guardrails Template
**Version:** 1.0
**Last Updated:** 2026-02-15
---
## Table of Contents
1. [High-Level Architecture](#high-level-architecture)
2. [Component Diagram](#component-diagram)
3. [Data Flow](#data-flow)
4. [Team Structure](#team-structure)
5. [Deployment Architecture](#deployment-architecture)
6. [Integration Points](#integration-points)
---
## High-Level Architecture
```mermaid
flowchart TB
subgraph Client["Client Layer"]
CLI["CLI / Scripts"]
IDE["IDE Integration"]
CI["CI/CD Pipeline"]
end
subgraph MCP["MCP Layer"]
Server["MCP Server<br/>Port 8094"]
Router["Request Router"]
Validator["Input Validator"]
end
subgraph Tools["Tool Layer"]
TeamTools["Team Tools"]
GuardrailTools["Guardrail Tools"]
AgentTools["Agent Tools"]
end
subgraph Backend["Backend Layer (Go)"]
TeamMgr["Team Manager<br/>mcp-server/internal/team/"]
RuleEngine["Rule Engine<br/>mcp-server/internal/rules/"]
AuditLog["Audit Logger<br/>mcp-server/internal/audit/"]
end
subgraph Storage["Storage Layer"]
TeamConfig[".teams/*.json"]
Guardrails[".guardrails/"]
Logs[".mcp/logs/"]
end
CLI -->|HTTP/JSON-RPC| Server
IDE -->|HTTP/JSON-RPC| Server
CI -->|HTTP/JSON-RPC| Server
Server --> Router
Router --> Validator
Validator --> TeamTools
Validator --> GuardrailTools
Validator --> AgentTools
TeamTools --> TeamMgr
GuardrailTools --> RuleEngine
AgentTools --> TeamMgr
TeamMgr --> TeamConfig
TeamMgr --> AuditLog
RuleEngine --> Guardrails
AuditLog --> Logs
```
### Architecture Overview
The Agent Guardrails Template follows a layered architecture with clear separation of concerns:
> **Go Implementation:** All backend services are implemented in Go (v2.6.0+). See `mcp-server/internal/`.
| Layer | Responsibility | Components |
|-------|---------------|------------|
| Client | Interface with users | CLI, IDE, CI/CD |
| MCP | Protocol handling | Server, routing, validation |
| Tools | Business logic | Team, guardrail, agent operations |
| Backend | Core services (Go) | Team manager, rules engine, audit logger |
| Storage | Persistence | PostgreSQL, Redis, JSON configs |
---
## Component Diagram
### MCP Server Components
```mermaid
flowchart LR
subgraph MCP_Server["MCP Server"]
direction TB
subgraph Transport["Transport Layer"]
HTTP["HTTP Listener<br/>Port 8094"]
JSONRPC["JSON-RPC Handler"]
end
subgraph Core["Core Services"]
Session["Session Manager"]
ToolReg["Tool Registry"]
Middleware["Middleware Stack"]
end
subgraph Tools["Available Tools"]
T1["guardrail_team_init"]
T2["guardrail_team_list"]
T3["guardrail_team_assign"]
T4["guardrail_team_unassign"]
T5["guardrail_team_status"]
T6["guardrail_phase_gate_check"]
T7["guardrail_agent_team_map"]
T8["guardrail_team_size_validate"]
T9["guardrail_validate_bash"]
T10["guardrail_validate_git_operation"]
T11["guardrail_validate_file_edit"]
end
end
HTTP --> JSONRPC
JSONRPC --> Session
Session --> Middleware
Middleware --> ToolReg
ToolReg --> T1
ToolReg --> T2
ToolReg --> T3
ToolReg --> T4
ToolReg --> T5
ToolReg --> T6
ToolReg --> T7
ToolReg --> T8
ToolReg --> T9
ToolReg --> T10
ToolReg --> T11
```
### Team Manager Components
```mermaid
flowchart TB
subgraph Team_Manager["Team Manager"]
direction TB
API["API Layer"]
subgraph Business_Logic["Business Logic"]
Init["Initialize Teams"]
Assign["Assign/Unassign"]
Validate["Validate Teams"]
Status["Check Status"]
Gates["Phase Gates"]
end
subgraph Data_Access["Data Access"]
ConfigLoader["Config Loader"]
ConfigWriter["Config Writer"]
Validator["Data Validator"]
end
subgraph Models["Team Models"]
Team["Team (1-12)"]
Role["Role"]
Member["Member"]
Phase["Phase (1-5)"]
end
end
API --> Business_Logic
Init --> ConfigWriter
Assign --> ConfigWriter
Validate --> ConfigLoader
Status --> ConfigLoader
Gates --> ConfigLoader
ConfigLoader --> Models
ConfigWriter --> Models
Validator --> Models
```
---
## Data Flow
### Tool Execution Flow
```mermaid
sequenceDiagram
participant Client as Client
participant Server as MCP Server
participant Validator as Input Validator
participant Tool as Tool Handler
participant Backend as Backend Service
participant Storage as Storage
Client->>Server: HTTP POST /mcp/v1/message
Server->>Server: Parse JSON-RPC request
Server->>Validator: Validate input parameters
alt Validation Failed
Validator-->>Server: ValidationError
Server-->>Client: 400 Bad Request
else Validation Passed
Validator->>Tool: Route to tool handler
Tool->>Backend: Execute business logic
Backend->>Storage: Read/Write data
Storage-->>Backend: Data response
Backend-->>Tool: Operation result
Tool-->>Server: Tool response
Server-->>Client: 200 OK + result
end
```
### Team Assignment Flow
```mermaid
sequenceDiagram
participant Client as Client
participant Server as MCP Server
participant TeamTool as Team Tool
participant TeamMgr as Team Manager
participant File as .teams/{project}.json
Client->>Server: guardrail_team_assign
Server->>TeamTool: Route request
TeamTool->>TeamTool: Validate parameters
alt Invalid Parameters
TeamTool-->>Server: Error: TEAM-002/TEAM-003
else Valid Parameters
TeamTool->>TeamMgr: assign_role(project, team, role, person)
TeamMgr->>File: Read current config
File-->>TeamMgr: Team configuration
alt Team Full
TeamMgr-->>TeamTool: Error: TEAM-005
else Role Occupied
TeamMgr-->>TeamTool: Error: TEAM-004
else Success
TeamMgr->>File: Write updated config
TeamMgr->>TeamMgr: Log audit event
TeamMgr-->>TeamTool: Assignment confirmed
end
end
TeamTool-->>Server: Response
Server-->>Client: JSON-RPC result
```
### Phase Gate Check Flow
```mermaid
sequenceDiagram
participant Client as Client
participant Server as MCP Server
participant GateTool as Phase Gate Tool
participant TeamMgr as Team Manager
participant Rules as .guardrails/team-layout-rules.json
participant Config as .teams/{project}.json
Client->>Server: guardrail_phase_gate_check
Server->>GateTool: Route request
GateTool->>Rules: Load gate requirements
Rules-->>GateTool: Gate rules
GateTool->>TeamMgr: Get phase status
TeamMgr->>Config: Read team config
Config-->>TeamMgr: All team data
TeamMgr-->>GateTool: Phase status summary
GateTool->>GateTool: Compare requirements vs actual
alt Gate Requirements Met
GateTool-->>Server: Gate approved, can proceed
else Gate Requirements Not Met
GateTool-->>Server: Missing deliverables list
end
Server-->>Client: Gate check result
```
---
## Team Structure
### 12-Team Organization
```mermaid
flowchart TB
subgraph Phase1["Phase 1: Strategy & Planning"]
T1["Team 1<br/>Business & Product<br/>Strategy"]
T2["Team 2<br/>Enterprise<br/>Architecture"]
T3["Team 3<br/>GRC"]
end
subgraph Phase2["Phase 2: Platform & Foundation"]
T4["Team 4<br/>Infrastructure &<br/>Cloud Ops"]
T5["Team 5<br/>Platform<br/>Engineering"]
T6["Team 6<br/>Data Governance &<br/>Analytics"]
end
subgraph Phase3["Phase 3: The Build Squads"]
T7["Team 7<br/>Core Feature<br/>Squad"]
T8["Team 8<br/>Middleware &<br/>Integration"]
end
subgraph Phase4["Phase 4: Validation & Hardening"]
T9["Team 9<br/>Cybersecurity<br/>AppSec"]
T10["Team 10<br/>Quality<br/>Engineering"]
end
subgraph Phase5["Phase 5: Delivery & Sustainment"]
T11["Team 11<br/>Site Reliability<br/>Engineering"]
T12["Team 12<br/>IT Operations &<br/>Support"]
end
Phase1 -->|Gate 1| Phase2
Phase2 -->|Gate 2| Phase3
Phase3 -->|Gate 3| Phase4
Phase4 -->|Gate 4| Phase5
```
### Phase Gate Flow
```mermaid
flowchart LR
subgraph Gates["Phase Gates"]
direction LR
G1["Gate 1<br/>Architecture<br/>Review Board"]
G2["Gate 2<br/>Environment<br/>Readiness"]
G3["Gate 3<br/>Feature Complete"]
G4["Gate 4<br/>Security + QA<br/>Sign-off"]
end
P1["Phase 1<br/>Strategy"] --> G1 --> P2["Phase 2<br/>Platform"]
P2 --> G2 --> P3["Phase 3<br/>Build"]
P3 --> G3 --> P4["Phase 4<br/>Validate"]
P4 --> G4 --> P5["Phase 5<br/>Deliver"]
```
---
## Deployment Architecture
### Single Node Deployment
```mermaid
flowchart TB
subgraph Server["Single Server"]
subgraph Docker["Docker Container"]
MCP["MCP Server<br/>Port 8094"]
Scripts["Team Manager Scripts"]
end
subgraph Volume1["Config Volume"]
Teams[".teams/"]
Guardrails[".guardrails/"]
end
subgraph Volume2["Log Volume"]
Logs[".mcp/logs/"]
end
end
Client["Client"]
Client -->|HTTP| MCP
MCP --> Scripts
Scripts --> Teams
Scripts --> Guardrails
MCP --> Logs
```
### Production Deployment
```mermaid
flowchart TB
subgraph Clients["Client Layer"]
CLI["CLI Tools"]
IDEs["IDE Extensions"]
CICD["CI/CD Runners"]
end
subgraph LB["Load Balancer"]
Nginx["Nginx / ALB"]
end
subgraph AppServers["Application Servers"]
S1["MCP Server 1"]
S2["MCP Server 2"]
S3["MCP Server 3"]
end
subgraph SharedStorage["Shared Storage"]
NFS["NFS / EFS"]
Teams["Team Configs"]
Rules["Guardrail Rules"]
end
subgraph Database["Database"]
Postgres[(PostgreSQL)]
Audit["Audit Logs"]
end
subgraph Monitoring["Monitoring"]
Prometheus["Prometheus"]
Grafana["Grafana"]
end
CLI -->|HTTPS| Nginx
IDEs -->|HTTPS| Nginx
CICD -->|HTTPS| Nginx
Nginx --> S1
Nginx --> S2
Nginx --> S3
S1 --> NFS
S2 --> NFS
S3 --> NFS
S1 --> Postgres
S2 --> Postgres
S3 --> Postgres
S1 --> Prometheus
S2 --> Prometheus
S3 --> Prometheus
NFS --> Teams
NFS --> Rules
Postgres --> Audit
```
---
## Integration Points
### External System Integrations
```mermaid
flowchart LR
subgraph AGT["Agent Guardrails Template"]
MCP["MCP Server"]
Scripts["Management Scripts"]
end
subgraph External["External Systems"]
Git["Git Provider<br/>GitHub/GitLab"]
CI["CI/CD<br/>Jenkins/Actions"]
Auth["Auth Provider<br/>OAuth/SAML"]
Monitor["Monitoring<br/>Datadog/NewRelic"]
end
subgraph AI["AI Assistants"]
Claude["Claude Code"]
OpenCode["OpenCode"]
Cursor["Cursor"]
end
MCP <-->|Git Operations| Git
MCP <-->|Pipeline Triggers| CI
MCP <-->|Authentication| Auth
Scripts <-->|Metrics Export| Monitor
Claude <-->|MCP Protocol| MCP
OpenCode <-->|MCP Protocol| MCP
Cursor <-->|MCP Protocol| MCP
```
### API Integration Patterns
```mermaid
flowchart TB
subgraph Integration["Integration Patterns"]
direction TB
P1["Synchronous<br/>Request/Response"]
P2["Asynchronous<br/>Webhook"]
P3["Batch<br/>File-based"]
end
subgraph UseCases["Use Cases"]
UC1["Team Assignments"]
UC2["Phase Gate Checks"]
UC3["Validation"]
UC4["Audit Export"]
UC5["Bulk Updates"]
end
P1 --> UC1
P1 --> UC2
P1 --> UC3
P2 --> UC4
P3 --> UC5
```
---
## Security Architecture
### Authentication Flow
```mermaid
sequenceDiagram
participant Client as Client
participant Server as MCP Server
participant Auth as Auth Service
participant Tool as Tool Handler
Client->>Server: Request + API Key
Server->>Auth: Validate API Key
alt Invalid Key
Auth-->>Server: 401 Unauthorized
Server-->>Client: AUTH-002 Error
else Valid Key
Auth-->>Server: User + Permissions
Server->>Server: Check permissions
alt Insufficient Permissions
Server-->>Client: AUTH-003 Error
else Authorized
Server->>Tool: Execute request
Tool-->>Server: Result
Server-->>Client: Success response
end
end
```
### Data Protection
```mermaid
flowchart TB
subgraph Security["Security Layers"]
L1["Input Validation<br/>Sanitization"]
L2["Authentication<br/>Authorization"]
L3["Audit Logging<br/>Non-repudiation"]
L4["Encryption<br/>At Rest & Transit"]
end
subgraph Threats["Threat Mitigation"]
T1["Injection Attacks"]
T2["Unauthorized Access"]
T3["Data Tampering"]
T4["Data Breach"]
end
L1 --> T1
L2 --> T2
L3 --> T3
L4 --> T4
```
---
## Configuration Architecture
> **Go Implementation:** All backend logic is implemented in Go. See `mcp-server/internal/` for package structure.
> **Migration:** `team_manager.py` has been migrated to Go (v2.6.0). See [PYTHON_MIGRATION.md](PYTHON_MIGRATION.md).
### File Organization
```
/mnt/ollama/git/agent-guardrails-template/
├── mcp-server/
│ ├── internal/ # Go implementation
│ │ ├── team/ # Team management logic
│ │ ├── rules/ # Rule engine
│ │ ├── audit/ # Audit logging
│ │ ├── database/ # Database operations
│ │ ├── cache/ # Redis caching
│ │ ├── mcp/ # MCP protocol
│ │ └── web/ # HTTP handlers
│ └── cmd/server/ # Main entry point
├── .teams/
│ ├── {project-name}.json # Team configurations
│ └── backups/
│ └── *.json.bak # Automatic backups
├── .guardrails/
│ ├── rules.json # Validation rules
│ ├── team-layout-rules.json # Team structure rules
│ └── schemas/
│ └── team-config.schema.json # JSON Schema
├── .mcp/
│ ├── mcp.log # Server logs
│ ├── audit.log # Security audit logs
│ └── config.json # Server configuration
└── scripts/
└── setup_agents.py # Agent setup (Python - legacy)
```
---
**Last Updated:** 2026-02-15
**Version:** 2.6.0
**Implementation:** Go (mcp-server/internal/)

View File

@ -0,0 +1,169 @@
# Clean Architecture & CQRS Architecture Map
**Purpose:** Unified architecture reference for the MCP server. Overlays the current structure with the target Clean Architecture + CQRS design.
---
## Current Layer Diagram
```
┌─────────────────────────────────────────────────────┐
│ Interface Adapters │
│ internal/mcp/ ← MCP handlers, HTTP/SSE │
├─────────────────────────────────────────────────────┤
│ Application Layer │
│ internal/mcp/handlers.go ← CQRS command/query │
│ handlers │
├─────────────────────────────────────────────────────┤
│ Domain Layer │
│ internal/domain/ ← Interfaces (ports), │
│ value objects, CQRS │
│ commands/queries │
├─────────────────────────────────────────────────────┤
│ Infrastructure │
│ internal/adapters/ ← Concrete implementations: │
│ internal/validation/ ← ValidationEngine, │
│ internal/database/ ← RuleStore, PostgreSQL │
│ internal/cache/ ← Redis, circuit breaker │
└─────────────────────────────────────────────────────┘
```
## Before vs After
| Aspect | Before | After |
|--------|--------|-------|
| MCPServer depends on | `*validation.ValidationEngine` | `domain.GuardrailService` interface |
| Domain layer | Empty package | Pure interfaces, value objects |
| Infrastructure impl | Inside domain | `internal/adapters/` |
| Vertical slices | Scattered across layers | One dir per guardrail type |
| Cache invalidation | Manual after each write | Event-driven via EventBus |
## Event Flow (CQRS)
```
Command: CreateRule
└─ CreateRuleHandler.Handle()
├─ 1. Validate pattern (PatternMatcher)
├─ 2. Persist (RuleRepository)
└─ 3. Publish Event (EventBus)
└─ CacheInvalidationHandler.Handle()
└─ CachePort.InvalidateRules()
```
```
Query: EvaluateCommand
└─ EvaluateCommandHandler.Handle()
├─ 1. Check cache (CachePort)
└─ 2. Evaluate (GuardrailService)
└─ BashEvaluator.Evaluate()
```
## Vertical Slice Structure
```
internal/guardrails/
├── bash/
│ └── slice.go ← Rule model, Evaluator, Store, Cache, Handler
├── git/
│ └── slice.go ← Same pattern
└── fileedit/
└── slice.go ← Same pattern
```
Each slice is self-contained: model + business logic + handler in one package.
## Interface Definitions
```go
// Domain port — GuardrailService
type GuardrailService interface {
EvaluateCommand(ctx context.Context, command string) ([]Violation, error)
EvaluateGit(ctx context.Context, command string) ([]Violation, error)
EvaluateFileEdit(ctx context.Context, filePath, content, sessionID string) ([]Violation, error)
EvaluateInput(ctx context.Context, input string, categories []string) ([]Violation, error)
CheckFileRead(ctx context.Context, sessionID, filePath string) (*FileReadVerification, error)
}
// Domain port — RuleRepository
type RuleRepository interface {
GetByID(ctx context.Context, id uuid.UUID) (*PreventionRule, error)
GetByRuleID(ctx context.Context, ruleID string) (*PreventionRule, error)
List(ctx context.Context, enabled *bool, category string, limit, offset int) ([]PreventionRule, error)
GetActiveRules(ctx context.Context) ([]PreventionRule, error)
Create(ctx context.Context, rule *PreventionRule) error
Update(ctx context.Context, rule *PreventionRule) error
Delete(ctx context.Context, id uuid.UUID) error
Toggle(ctx context.Context, id uuid.UUID, enabled bool) error
Count(ctx context.Context, enabled *bool, category string) (int, error)
}
// Domain port — EventBus
type EventBus interface {
Publish(ctx context.Context, event Event)
Subscribe(eventType EventType, handler EventHandler)
}
```
## CQRS Command/Query Handlers
| Command Handler | Operation | Event Published |
|-----------------|-----------|-----------------|
| `CreateRuleHandler` | Insert rule | `rule.created` |
| `UpdateRuleHandler` | Modify rule | `rule.updated` |
| `ToggleRuleHandler` | Enable/disable | `rule.toggled` |
| Query Handler | Operation | Caching |
|---------------|-----------|---------|
| `EvaluateCommandHandler` | Validate bash | Cache-first |
| `EvaluateGitHandler` | Validate git | Cache-first |
| `EvaluateFileEditHandler` | Validate file edit | Cache-first |
| `ListRulesHandler` | List rules | No caching |
## Testability
Domain types testable in isolation (no external deps):
```go
// Test domain value objects
func TestSeverityIsValid(t *testing.T) {
assert.Equal(t, true, Severity("critical").IsValid())
assert.Equal(t, false, Severity("invalid").IsValid())
}
// Test CQRS handlers with mocks
func TestCreateRuleHandler(t *testing.T) {
mockRepo := &mockRuleRepository{}
mockBus := &mockEventBus{}
h := NewCreateRuleHandler(mockRepo, mockBus, mockMatcher)
rule, err := h.Handle(ctx, CreateRuleCommand{...})
assert.NoError(t, err)
assert.Len(t, mockBus.PublishedEvents, 1)
}
```
## Migration Path
1. **Phase 1** (done): Domain interfaces + adapters — existing engine wrapped behind interface
2. **Phase 2** (done): Vertical slices — bash/git/fileedit self-contained
3. **Phase 3** (in progress): Wire MCPServer to use interface instead of concrete type
4. **Phase 4** (future): Bounded contexts — `internal/team/` and `internal/validation/` become separate packages
## Key Files
| File | Role |
|------|------|
| `internal/domain/guardrail.go` | Domain interfaces and value objects |
| `internal/domain/cqrs.go` | CQRS commands, queries, handlers, EventBus interface |
| `internal/adapters/validation_adapter.go` | ValidationEngine behind GuardrailService |
| `internal/adapters/database_adapter.go` | RuleStore behind RuleRepository |
| `internal/adapters/event_bus.go` | DefaultEventBus, CacheInvalidationHandler |
| `internal/guardrails/registry.go` | Unified registry wiring all slices |
| `internal/guardrails/bash/slice.go` | Bash vertical slice |
| `internal/guardrails/git/slice.go` | Git vertical slice |
| `internal/guardrails/fileedit/slice.go` | File edit vertical slice |
---
**Last Updated:** 2026-05-08

View File

@ -0,0 +1,269 @@
# Changelog
All notable changes to the Agent Guardrails Template will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
---
## [2.7.0] - 2026-03-14
### Major Release: 2026 UI/UX Game Design Update
**Version:** 2.7.0
**Release Date:** 2026-03-14
**Type:** Major Version Bump (breaking changes in documentation structure)
---
### New Features
#### 2026 Game Design Patterns
**Agent-GDUI-2026** role definition added for specialized game interface and spatial computing development:
- **Spatial Layout** - XR viewport management, depth layering, comfort zone enforcement
- **Motion Design** - Animation guidelines with 60fps minimum, 120fps target
- **Audio Spatialization** - 3D audio positioning with HRTF calibration
- **Input Mapping** - Multi-modal input handlers with accessibility priority
- **Ethical Review** - Automatic dark pattern detection and rejection
- **Performance Budget** - Frame-rate budgets with strict latency constraints
**Documentation Added:**
- [2026_GAME_DESIGN.md](game-design/2026_GAME_DESIGN.md) - Core game design guardrails
- XR/VR comfort zones (30° cone, 20ms latency)
- Platform-specific rules (Mobile, PC, Console, XR)
- Performance budgets per platform
- Language-specific patterns (TypeScript, Rust, Go)
- [2026_UI_UX_STANDARD.md](ui-ux/2026_UI_UX_STANDARD.md) - UI/UX component standards
- Foundational components (Button, Input, Modal, Navigation)
- Design tokens (color, typography, spacing)
- Interaction states (hover, focus, active, disabled)
- Animation guidelines with reduced-motion support
- Responsive breakpoints (xs, sm, md, lg, xl, 2xl)
- [ACCESSIBILITY_GUIDE.md](accessibility/ACCESSIBILITY_GUIDE.md) - WCAG 3.0+ implementation
- WCAG 3.0 conformance levels (Bronze/Silver/Gold)
- Perceptual accessibility (contrast, color independence)
- Cognitive accessibility (plain language, consistent navigation)
- Physical accessibility (keyboard, touch targets, gestures)
- Automated and manual testing methods
- [SPATIAL_COMPUTING_UI.md](spatial/SPATIAL_COMPUTING_UI.md) - XR/VR/AR UI patterns
- Comfort zones and latency requirements
- UI layout patterns (VR, AR, MR)
- Depth layering (3-layer standard)
- Interaction patterns (gesture, gaze, haptic)
- Performance budgets (90fps minimum for XR)
- [ETHICAL_ENGAGEMENT.md](ethical/ETHICAL_ENGAGEMENT.md) - Dark pattern prevention
- Dark pattern taxonomy (deceptive, coercive, addictive, exploitation)
- Ethical design principles (transparency, choice, wellbeing, respect)
- Implementation checklist
- Technical implementation (middleware, detection)
#### Language-Specific Pattern Examples
**TypeScript/React:**
- Accessibility-first component patterns
- Design token usage hooks
- Dark pattern detection components
- Ethical component wrappers
**Rust:**
- Bevy game engine guardrails
- Spatial computing safety components
- Accessibility audit validators
- Leptos/Yew accessible components
**Go:**
- HTMX accessible patterns
- Ethical engagement middleware
- Dark pattern detection handlers
- Server-rendered UI components
**Additional Languages:**
- Java examples
- Python examples
- Ruby examples
- Swift/SwiftUI examples
- Scala functional UI examples
- R game analytics examples
---
### Accessibility Compliance
**WCAG 3.0+ Level Silver** certification requirements:
| Requirement | Level | Implementation |
|-------------|-------|---------------|
| Contrast Ratio | AAA | 7:1 minimum for text |
| Focus Indicators | AA | 3px outline, 3:1 contrast |
| Keyboard Navigation | A | All interactive elements |
| Screen Reader Support | AA | ARIA labels required |
| Reduced Motion | A | Prefers-reduced-motion support |
| Color Independence | AA | Information not color-only |
| Text Resizing | AA | 200% zoom without breaking |
**Badge:** [![WCAG 3.0+ Silver](https://img.shields.io/badge/WCAG-3.0+_Silver-green.svg)](docs/accessibility/ACCESSIBILITY_GUIDE.md)
---
### Spatial Computing Support
**XR/VR/AR/MR** platform support added:
| Platform | Frame Target | Latency Budget | Constraint |
|----------|--------------|---------------|------------|
| Mobile VR | 60fps | 16.6ms/frame | Thermal awareness |
| PC VR | 144fps | 6.9ms/frame | GPU sync required |
| Console VR | 60/120fps | 8.3/16.6ms | V-Sync mandatory |
| XR Headset | 90fps minimum | 11.1ms/frame | Drop frames = nausea |
| VR High-End | 120fps | 8.3ms/frame | Async reprojection |
**Comfort Zone Enforcement:**
- 30° horizontal, 20° vertical primary cone
- Max 3 depth planes
- Stereo separation < 6.5cm
- Motion-to-photon latency < 20ms
---
### Ethical Engagement Compliance
**Dark Pattern Prevention** automatic enforcement:
**Forbidden Patterns:**
- Fake urgency ("3 people viewing!")
- Cookie walls that block access
- Hidden costs revealed at checkout
- Misleading defaults (pre-select paid)
- Disguised ads (native advertising without label)
- Forced continuity (no cancellation path)
- Addiction loops (variable reward schedules)
- Data brokerage (selling user data without consent)
**Ethical Requirements:**
- Cancellation in ≤ 3 clicks
- Opt-in defaults (not opt-out)
- Transparent pricing upfront
- All ads clearly labeled
- Session limits (60min max continuous)
- Break prompts at 45min
- Notification limits (≤ 3/day promotional)
---
### Documentation Structure Changes
**New Documentation Categories:**
| Category | Documents | Purpose |
|----------|-----------|---------|
| Game Design | 2026_GAME_DESIGN.md | Game interface guardrails |
| UI/UX | 2026_UI_UX_STANDARD.md | Component standards |
| Accessibility | ACCESSIBILITY_GUIDE.md | WCAG 3.0+ implementation |
| Spatial Computing | SPATIAL_COMPUTING_UI.md | XR/VR/AR patterns |
| Ethical Engagement | ETHICAL_ENGAGEMENT.md | Dark pattern prevention |
**Navigation Tools:**
- [INDEX_MAP.md](INDEX_MAP.md) - Keyword/category search (saves 60-80% tokens)
- [HEADER_MAP.md](HEADER_MAP.md) - Section-level file:line references
---
### Breaking Changes
**Documentation Structure:**
- Added 5 new documentation directories:
- `docs/game-design/`
- `docs/ui-ux/`
- `docs/accessibility/`
- `docs/spatial/`
- `docs/ethical/`
- INDEX_MAP.md and HEADER_MAP.md now required for navigation
- TOC.md created for complete file listing
**Version Bump:**
- v1.x → v2.7.0 (major version bump for 2026 UI/UX update)
- MCP Server remains at v2.6.0 (Go implementation unchanged)
---
### Migration Guide
**From v1.x to v2.7.0:**
1. Read [INDEX_MAP.md](docs/INDEX_MAP.md) for new document locations
2. Use [HEADER_MAP.md](docs/HEADER_MAP.md) for section-level lookup
3. Review [2026_GAME_DESIGN.md](docs/game-design/2026_GAME_DESIGN.md) for game development
4. Implement [ACCESSIBILITY_GUIDE.md](docs/accessibility/ACCESSIBILITY_GUIDE.md) WCAG 3.0+ requirements
5. Enable [ETHICAL_ENGAGEMENT.md](docs/ethical/ETHICAL_ENGAGEMENT.md) dark pattern detection
---
### Documentation Statistics
| Metric | v1.x | v2.7.0 | Change |
|--------|------|--------|--------|
| Total Files | 31 | 36 | +5 |
| Total Lines | ~9,000 | ~11,500 | +2,500 |
| 500-Line Compliance | 30/31 (97%) | 35/36 (97%) | Maintained |
| New Categories | 0 | 5 | Game Design, UI/UX, Accessibility, Spatial, Ethical |
---
### Credits
**Authored by:** Agent-GDUI-2026 Specialist Team
**Review Cycle:** Quarterly
**Compliance:** WCAG 3.0+ Level Silver, ISO 20885-1, EU DSA, GDPR
---
## [1.10.0] - 2026-02-15
### Summary
MCP Server Go migration complete. Web UI deployed. Team tools stabilized.
**See:** [RELEASE_v1.10.0.md](RELEASE_v1.10.0.md) for details.
---
## [1.9.6] - 2026-02-14
### Summary
Final v1.x release before 2.0.0 major update.
**See:** [RELEASE_v1.9.6.md](RELEASE_v1.9.6.md) for details.
---
## [1.9.0] - [1.9.5] - 2026-01-20 to 2026-02-10
### Summary
Incremental improvements to MCP server, team tools, and documentation.
**See:** Individual release files (RELEASE_v1.9.0.md through RELEASE_v1.9.5.md) for details.
---
## [Unreleased]
Future releases will include:
- Additional language-specific examples
- Extended spatial computing patterns
- Enhanced ethical engagement detection
- Platform-specific accessibility guides
---
**Last Updated:** 2026-03-14
**Version:** 2.7.0
**Maintainer:** TheArchitectit

View File

@ -0,0 +1,248 @@
# Claude Code Integration
This guide explains how to integrate Agent Guardrails with Claude Code using skills and hooks.
## Overview
Claude Code supports:
- **Skills** - JSON files that define specialized behaviors and constraints
- **Hooks** - Shell scripts that run at specific lifecycle points
The setup script installs these configurations for you.
## Setup
### 1. Install All Skills and Hooks
```bash
python scripts/setup_agents.py --install --platform claude
```
This creates:
```
.claude/
├── skills/
│ ├── guardrails-enforcer.json
│ ├── commit-validator.json
│ ├── env-separator.json
│ ├── scope-validator.json
│ ├── production-first.json
│ ├── three-strikes.json
│ └── error-recovery.json
└── hooks/
├── pre-execution.sh
├── post-execution.sh
└── pre-commit.sh
```
### 2. Install a Single Skill
To install just one skill by name:
```bash
python scripts/setup_agents.py --install-skill guardrails-enforcer
```
Use `--list-skills` to see all available skill names:
```bash
python scripts/setup_agents.py --list-skills
```
### 3. Verify Installation
Check that skills are loaded:
```bash
ls -la .claude/skills/
```
Validate JSON syntax:
```bash
python -m json.tool .claude/skills/guardrails-enforcer.json
```
Check that hooks are executable:
```bash
ls -la .claude/hooks/
```
## Skill File Format
Skills are JSON files in `.claude/skills/`. Each file has four fields:
| Field | Type | Description |
|-------|------|-------------|
| `name` | string | Unique identifier for the skill |
| `description` | string | What the skill does (shown in skill list) |
| `tools` | array | Allowed tools for this skill |
| `prompt` | string | Instructions injected into the session context |
### Example: guardrails-enforcer.json
```json
{
"name": "guardrails-enforcer",
"description": "Enforces the Four Laws of Agent Safety: read-before-edit, stay-in-scope, verify-before-commit, halt-when-uncertain",
"tools": ["Read", "Grep", "Glob", "AskUserQuestion"],
"prompt": "# Guardrails Enforcement Agent\n\nYou are the Guardrails Enforcement Agent. You MUST enforce these rules on EVERY operation.\n\n## The Four Laws of Agent Safety\n\n1. **Read Before Editing** - Never modify code without reading it first\n2. **Stay in Scope** - Only touch files explicitly authorized\n3. **Verify Before Committing** - Test and check all changes\n4. **Halt When Uncertain** - Ask for clarification instead of guessing\n..."
}
```
The `prompt` field contains markdown-formatted instructions. Claude Code injects this into the session context when the skill is active.
## Hook Details
Hooks are shell scripts that run automatically at specific points:
| Hook | When It Runs | Purpose |
|------|--------------|---------|
| `pre-execution.sh` | Before file modifications | Verify read-before-edit |
| `post-execution.sh` | After file modifications | Validate changes |
| `pre-commit.sh` | Before git commit | Validate commit message |
### Custom Hook Example
```bash
#!/bin/bash
# .claude/hooks/pre-commit.sh
# Run linter
npm run lint
# Run tests
npm test
# Check for secrets
trufflehog git file://. --since-commit HEAD
```
Make sure hooks remain executable:
```bash
chmod +x .claude/hooks/*.sh
```
## Skill Reference
### guardrails-enforcer
Enforces the Four Laws of Agent Safety. Halts on: unread code, scope violations, missing rollback, test/production mix, three consecutive failures.
### commit-validator
Validates git commits. Checks: AI attribution (`Co-Authored-By:`), single focus per commit, no secrets in diff, tests pass.
### env-separator
Enforces test/production separation. Detects: production DB connections in tests, shared instances, hardcoded production credentials.
### scope-validator
Enforces scope boundaries. Only files explicitly authorized by the user or task description may be modified.
### production-first
Requires production code before tests. Order: implementation, validation, tests, infrastructure.
### three-strikes
Failure recovery protocol. After three consecutive failures, halts and escalates to user.
### error-recovery
Error handling and recovery procedures. Provides structured guidance when operations fail.
## Shared Prompts Reference
All skill prompts incorporate rules from the shared prompts directory:
| Shared Prompt | Used By Skills |
|---------------|---------------|
| `skills/shared-prompts/four-laws.md` | guardrails-enforcer |
| `skills/shared-prompts/halt-conditions.md` | guardrails-enforcer |
| `skills/shared-prompts/three-strikes.md` | three-strikes |
| `skills/shared-prompts/production-first.md` | production-first |
| `skills/shared-prompts/clean-architecture.md` | guardrails-enforcer |
| `skills/shared-prompts/cqrs.md` | guardrails-enforcer |
| `skills/shared-prompts/scope-validation.md` | scope-validator |
| `skills/shared-prompts/error-recovery.md` | error-recovery |
When shared prompts are updated, re-run the setup script to regenerate skill prompts:
```bash
python scripts/setup_agents.py --install --platform claude
```
## Customization
### Adding a Custom Skill
1. Create a new JSON file in `.claude/skills/`:
```json
{
"name": "my-skill",
"description": "What it does",
"tools": ["Read", "Bash"],
"prompt": "Your instructions here..."
}
```
2. Restart Claude Code to load the skill.
### Disabling a Skill
Move it out of the skills directory:
```bash
mkdir -p .claude/skills/disabled
mv .claude/skills/commit-validator.json .claude/skills/disabled/
```
Restart Claude Code to apply.
### Cloning a Single Skill from Another Repo
```bash
python scripts/setup_agents.py --clone .claude/skills/guardrails-enforcer.json
```
This copies a specific skill file by its repo path into the current project.
## Installation Modes
| Mode | Command | Behavior |
|------|---------|----------|
| Copy | `--mode copy` (default) | Writes standalone copies to the project |
| Symlink | `--mode symlink` | Creates symlinks back to this repo |
## Troubleshooting
### Skills Not Loading
- JSON syntax: `python -m json.tool .claude/skills/*.json`
- Files in correct directory: `ls .claude/skills/`
- Restart Claude Code after changes
### Hooks Not Running
- Check executable bit: `chmod +x .claude/hooks/*.sh`
- Validate shell syntax: `bash -n .claude/hooks/pre-execution.sh`
- Check hook names match expected patterns
### Permission Denied
```bash
chmod +x .claude/hooks/*.sh
```
## Best Practices
1. **One skill = one responsibility** - Keep skills focused and composable
2. **Test hooks manually** - Run scripts directly to verify behavior
3. **Regenerate after shared prompt updates** - Re-run setup to sync skills
4. **Commit `.claude/` to version control** - Team shares the same guardrails
## References
- [AGENTS_AND_SKILLS_SETUP.md](AGENTS_AND_SKILLS_SETUP.md) - Unified setup guide
- [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) - Core safety protocols
- [skills/shared-prompts/](../skills/shared-prompts/) - Canonical prompt definitions

View File

@ -0,0 +1,379 @@
# Contributing Guide
> Development guidelines for the Agent Guardrails Template
**Version:** 2.6.0
**Last Updated:** 2026-02-15
---
## Table of Contents
1. [Getting Started](#getting-started)
2. [Go Development Workflow](#go-development-workflow)
3. [Code Standards](#code-standards)
4. [Testing](#testing)
5. [Commit Guidelines](#commit-guidelines)
6. [Migration Notice](#migration-notice)
---
## Getting Started
> **Important:** All future development is in **Go**. Python implementation is deprecated as of v2.6.0.
### Prerequisites
- Go 1.23+
- Docker or Podman
- PostgreSQL 16 (for local development)
- Redis 7 (for local development)
- Make
### Repository Structure
```
mcp-server/
├── cmd/
│ └── server/ # Main application entry point
├── internal/
│ ├── team/ # Team management logic (Go)
│ ├── rules/ # Rule engine
│ ├── audit/ # Audit logging
│ ├── database/ # Database operations
│ ├── cache/ # Redis caching
│ ├── mcp/ # MCP protocol implementation
│ ├── web/ # HTTP handlers
│ ├── security/ # Secrets scanning
│ └── validation/ # Input validation
├── deploy/ # Deployment files
└── Makefile # Build automation
```
---
## Go Development Workflow
### Building
```bash
cd mcp-server
# Build the server binary
make build
# Build for production
make build-prod
# Clean build artifacts
make clean
```
### Running Locally
```bash
# Install dependencies
make deps
# Run database migrations
export DATABASE_URL="postgresql://guardrails:password@localhost:5432/guardrails?sslmode=disable"
make migrate-up
# Run the server (requires PostgreSQL and Redis)
make dev
# Or run directly
go run ./cmd/server
```
### Code Quality
```bash
# Format all Go code
make fmt
# Run linter (golangci-lint)
make lint
# Run tests
make test
# Run tests with coverage
make test-cover
# Check for vulnerabilities
make vuln
# Full check (fmt + lint + test)
make check
```
---
## Code Standards
### Go Code Style
All code must pass the following checks:
1. **gofmt** - Standard Go formatting
```bash
gofmt -w .
```
2. **go vet** - Static analysis
```bash
go vet ./...
```
3. **golangci-lint** - Comprehensive linting
```bash
golangci-lint run
```
### Coding Conventions
- **Package names:** Short, lowercase, no underscores
- **File names:** lowercase_with_underscores.go
- **Interface names:** Where possible, end with `-er` (e.g., `Reader`, `Writer`)
- **Exported names:** PascalCase
- **Unexported names:** camelCase
- **Constants:** PascalCase or ALL_CAPS for exported
### Example
```go
// Good package name
package team
// Good interface name
type Manager interface {
AssignRole(project, team, role, person string) error
GetStatus(project string) (Status, error)
}
// Good struct and method names
type teamManager struct {
db database.Store
cache cache.Cache
}
func (tm *teamManager) AssignRole(project, team, role, person string) error {
// implementation
}
```
### Error Handling
- Always check errors
- Wrap errors with context using `fmt.Errorf` with `%w`
- Use custom error types for business logic errors
```go
// Good
if err := tm.db.AssignRole(ctx, project, team, role, person); err != nil {
return fmt.Errorf("failed to assign role: %w", err)
}
// Custom error type
var ErrTeamFull = errors.New("team is at maximum capacity")
if len(members) >= maxTeamSize {
return ErrTeamFull
}
```
---
## Testing
### Test Structure
```bash
mcp-server/internal/team/
├── team.go # Implementation
└── team_test.go # Tests
```
### Running Tests
```bash
# All tests
make test
# Specific package
go test ./internal/team/...
# With verbose output
go test -v ./internal/team/...
# Race detection
go test -race ./...
# Benchmarks
go test -bench=. ./...
```
### Test Coverage
Minimum coverage requirements:
- Core packages (`internal/team`, `internal/rules`): 80%+
- Handlers (`internal/web`): 70%+
- Utilities: 60%+
```bash
# Generate coverage report
make test-cover
# View in browser
go tool cover -html=coverage.out
```
### Test Guidelines
1. Use table-driven tests where possible
2. Mock external dependencies (database, cache)
3. Test both success and error paths
4. Use meaningful test names
```go
func TestAssignRole(t *testing.T) {
tests := []struct {
name string
project string
team string
role string
person string
wantErr error
}{
{
name: "valid assignment",
project: "test-project",
team: "team-1",
role: "lead",
person: "alice",
wantErr: nil,
},
{
name: "team full",
project: "test-project",
team: "team-1",
role: "developer",
person: "bob",
wantErr: ErrTeamFull,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tm := NewManager(mockDB, mockCache)
err := tm.AssignRole(tt.project, tt.team, tt.role, tt.person)
if !errors.Is(err, tt.wantErr) {
t.Errorf("AssignRole() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
```
---
## Commit Guidelines
### Conventional Commits
Follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:
```
<type>(<scope>): <description>
[optional body]
[optional footer(s)]
```
### Types
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `style`: Code style changes (formatting, no logic change)
- `refactor`: Code refactoring
- `test`: Test additions or updates
- `chore`: Build process or auxiliary tool changes
- `perf`: Performance improvements
- `security`: Security fixes
### Examples
```
feat(team): add team size validation
Implements TEAM-007 compliance check for maximum team size.
Adds validation to prevent over-allocation.
fix(mcp): resolve session timeout handling
docs(api): update endpoint documentation
refactor(database): simplify transaction handling
test(audit): add coverage for audit logging
```
### Scope Values
Common scopes for this project:
- `team`: Team management
- `mcp`: MCP protocol
- `web`: Web handlers
- `database`: Database operations
- `cache`: Redis/cache
- `security`: Security features
- `config`: Configuration
- `deploy`: Deployment
---
## Migration Notice
### Python to Go Migration (v2.6.0)
**Status:** Complete
**What Changed:**
- `scripts/team_manager.py` -> `mcp-server/internal/team/` (Go package)
- All team management logic now in Go
- Database migrations via golang-migrate
- No Python runtime required
**How to Contribute:**
1. Write Go code in `mcp-server/internal/`
2. Follow Go conventions and this guide
3. Run `make check` before committing
4. Ensure tests pass with `make test`
**Benefits:**
- Smaller container size (~50MB vs ~500MB)
- Faster startup (~100ms vs ~3s)
- Distroless security hardening
- Single static binary
**See Also:**
- [PYTHON_MIGRATION.md](PYTHON_MIGRATION.md) - Detailed migration guide
- [ARCHITECTURE.md](ARCHITECTURE.md) - System architecture
- [MIGRATION.md](MIGRATION.md) - Version migration procedures
---
## Getting Help
- **Documentation:** Start with [INDEX_MAP.md](../INDEX_MAP.md)
- **Issues:** [GitHub Issues](https://github.com/TheArchitectit/agent-guardrails-template/issues)
- **Discussions:** [GitHub Discussions](https://github.com/TheArchitectit/agent-guardrails-template/discussions)
---
**Last Updated:** 2026-02-15
**Version:** 2.6.0
**Implementation:** Go (mcp-server/internal/)

View File

@ -0,0 +1,178 @@
# GitHub Copilot Integration
This guide explains how to integrate Agent Guardrails with GitHub Copilot using repo-level instructions.
## Overview
GitHub Copilot reads a file at `.github/copilot-instructions.md` for repo-level instructions. This file provides markdown-formatted guidance that applies to all Copilot completions, suggestions, and chat interactions in the repository.
There are no per-skill files -- all instructions live in one file.
## Setup
### 1. Run Setup Script
```bash
python scripts/setup_agents.py --install --platform copilot
```
This creates:
```
.github/
└── copilot-instructions.md
```
### 2. Manual Installation
If you prefer to install without the script:
```bash
# Copy from template
cp .github/copilot-instructions.md /path/to/your/project/.github/copilot-instructions.md
```
Copilot does not support symlinks for instructions -- use copy mode only.
### 3. Verify Installation
```bash
cat .github/copilot-instructions.md
```
You should see the guardrails instructions beginning with `# GitHub Copilot Instructions`.
## File Format
The `.github/copilot-instructions.md` file is a plain markdown document. GitHub Copilot reads this as project-level instructions injected into every chat session and code suggestion context.
### Structure
```markdown
# GitHub Copilot Instructions
These instructions apply to all Copilot completions, suggestions, and chat
interactions in this repository.
## The Four Laws of Agent Safety
1. **Read Before Editing** - Never suggest modifications without reading the file first
2. **Stay in Scope** - Only work on files within the authorized task scope
3. **Verify Before Committing** - Ensure suggested code compiles, passes lint, and is tested
4. **Halt When Uncertain** - Ask for clarification instead of guessing
## Code Generation Rules
...
## Forbidden Patterns
...
## Three Strikes Rule
...
```
### Key Sections
| Section | Purpose |
|---------|---------|
| The Four Laws | Core safety rules for all operations |
| Code Generation Rules | Scope, production-first, error handling, security |
| Forbidden Patterns | Code that must never be suggested |
| Three Strikes Rule | Failure recovery protocol |
| File Headers | Required header format for new files |
| Architecture Patterns | Clean Architecture, CQRS, SOLID for Go/MCP code |
## How It Applies
Copilot reads `.github/copilot-instructions.md` at the repository level. This means:
- All inline suggestions respect the scope and production-first rules
- Chat responses apply the Four Laws
- Forbidden patterns are never suggested
- Architecture patterns apply when working on `mcp-server/`
- File headers are included in new file suggestions
### Scope in Copilot
Unlike agentic tools (Claude Code, Cursor), Copilot operates at the suggestion level. The scope rules translate as:
- Only suggest changes in the file being edited
- Do not suggest refactoring unrelated code
- Do not suggest adding new files unless the user requests it
- When unclear about intent, do not assume -- suggest the minimal change
## Customization
### Adding Project-Specific Instructions
Append custom sections to `.github/copilot-instructions.md`:
```markdown
## Project-Specific Rules
- All new Python files must use type hints
- API endpoints must follow OpenAPI 3.1 spec
- Use pytest fixtures, not unittest classes
```
### Team-Level Instructions
Since this file lives in `.github/`, it is committed to the repository and shared with the entire team. All contributors get the same guardrails automatically.
### Combining with Personal Instructions
GitHub Copilot also supports personal instructions in your Copilot settings. Repo-level instructions (`.github/copilot-instructions.md`) take precedence over personal instructions for files in this repository.
## Shared Prompts Reference
The `copilot-instructions.md` file incorporates rules from the shared prompts directory:
| Shared Prompt | Rules Covered |
|---------------|---------------|
| `skills/shared-prompts/four-laws.md` | The Four Laws (canonical source) |
| `skills/shared-prompts/halt-conditions.md` | Full halt conditions checklist |
| `skills/shared-prompts/three-strikes.md` | Failure tracking and escalation |
| `skills/shared-prompts/production-first.md` | Production-before-tests ordering |
| `skills/shared-prompts/clean-architecture.md` | Clean Architecture patterns for Go/MCP |
| `skills/shared-prompts/cqrs.md` | CQRS command/query separation |
When shared prompts are updated, re-run the setup script to regenerate the instructions:
```bash
python scripts/setup_agents.py --install --platform copilot
```
## Troubleshooting
### Instructions Not Applied
**Check:**
- File exists at `.github/copilot-instructions.md`: `ls -la .github/copilot-instructions.md`
- The `.github/` directory is committed to the repository
- Your IDE has the GitHub Copilot extension installed and enabled
- Copilot has indexed the repository (restart your IDE if needed)
### Outdated Instructions
**Fix:**
- Re-run: `python scripts/setup_agents.py --install --platform copilot`
### Conflicting Personal Instructions
If you have personal Copilot instructions that conflict with repo-level instructions, the repo-level file takes precedence for this repository. Remove conflicting personal settings or align them with the guardrails.
### Instructions Too Long
If the file becomes very long, Copilot may truncate it. Keep the file focused on the most critical rules. Move detailed patterns to referenced documents like `AGENT_GUARDRAILS.md` and `shared-prompts/`.
## Best Practices
1. **Regenerate after updates** - Re-run setup when shared prompts change
2. **Keep it concise** - Copilot has context limits; prioritize critical rules
3. **Commit to the repo** - All team members get guardrails automatically
4. **Reference, don't duplicate** - Point to shared-prompts/ for full details
## References
- [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) - Core safety protocols
- [AGENTS_AND_SKILLS_SETUP.md](AGENTS_AND_SKILLS_SETUP.md) - Unified setup guide
- [skills/shared-prompts/](../skills/shared-prompts/) - Canonical prompt definitions

View File

@ -0,0 +1,299 @@
# Cursor Integration
This guide explains how to integrate Agent Guardrails with Cursor using markdown-based rules.
## Overview
Cursor supports:
- **Rules** - Markdown files with YAML frontmatter that define AI behavior and constraints
- **Global Rules** - `.cursorrules` file in project root for universal settings
The setup script installs these configurations for you.
## Setup
### 1. Install All Rules
```bash
python scripts/setup_agents.py --install --platform cursor
```
This creates:
```
.cursor/
├── rules/
│ ├── guardrails-enforcer.md
│ ├── commit-validator.md
│ ├── env-separator.md
│ ├── scope-validator.md
│ ├── production-first.md
│ ├── three-strikes.md
│ └── error-recovery.md
└── .cursorrules (optional root config)
```
### 2. Install a Single Skill
To install just one skill by name:
```bash
python scripts/setup_agents.py --install-skill guardrails-enforcer --platform cursor
```
Use `--list-skills` to see all available skill names:
```bash
python scripts/setup_agents.py --list-skills
```
### 3. Verify Installation
Check that rules are loaded:
```bash
ls -la .cursor/rules/
```
Check that `.cursorrules` exists (if using global config):
```bash
cat .cursorrules
```
## Rule File Format
Rules are markdown files in `.cursor/rules/` with YAML frontmatter:
```markdown
---
description: Enforces the Four Laws of Agent Safety on all code generation
globs: "**/*"
alwaysApply: true
---
# Guardrails Enforcement
You are the Guardrails Enforcement Agent. Enforce these rules on EVERY operation.
## The Four Laws of Agent Safety
1. **Read Before Editing** - Never modify code without reading it first
2. **Stay in Scope** - Only touch files explicitly authorized
3. **Verify Before Committing** - Test and check all changes
4. **Halt When Uncertain** - Ask for clarification instead of guessing
...
```
### Frontmatter Fields
| Field | Type | Description |
|-------|------|-------------|
| `description` | string | Summary shown in the Cursor rules list |
| `globs` | string | File patterns this rule applies to (e.g., `"**/*"`, `"src/**/*.ts"`) |
| `alwaysApply` | boolean | Whether to apply this rule to every session automatically |
### Example: guardrails-enforcer.md (Actual File)
```markdown
---
description: Enforces the Four Laws of Agent Safety on all code generation
globs: "**/*"
alwaysApply: true
---
# Guardrails Enforcement
You are the Guardrails Enforcement Agent. Enforce these rules on EVERY operation.
## The Four Laws of Agent Safety
1. **Read Before Editing** - Never modify code without reading it first
2. **Stay in Scope** - Only touch files explicitly authorized
3. **Verify Before Committing** - Test and check all changes
4. **Halt When Uncertain** - Ask for clarification instead of guessing
## Pre-Operation Checklist
Before ANY file modification:
- [ ] Read the target file(s) completely
- [ ] Verify the operation is within authorized scope
- [ ] Identify the rollback procedure
- [ ] Check for test/production separation requirements
## Forbidden Actions
1. Modifying code without reading it first
2. Mixing test and production environments
3. Force pushing to main/master
4. Committing secrets, credentials, or .env files
5. Running untested code in production
6. Modifying unread code
7. Working outside authorized scope
## Halt Conditions
STOP and escalate when:
- Attempting to modify code you haven't read
- No rollback procedure exists or is unclear
- Production impact is uncertain
- User authorization is ambiguous
- Test and production environments may mix
- You are uncertain about ANY aspect of the task
- An operation has failed 3 times
```
## Global Rules (.cursorrules)
The `.cursorrules` file in the project root applies to all Cursor sessions:
```markdown
# Project Rules
## Always
- Follow the Four Laws of Agent Safety
- Read files before editing
- Validate commits before creating
## When
- Editing code: Check scope boundaries
- Running commands: Verify environment separation
```
Use `.cursorrules` for simple, universal rules. Use `.cursor/rules/*.md` for structured, per-skill rules with frontmatter.
## Rule Reference
### guardrails-enforcer
Applies to all files. Enforces the Four Laws, pre-operation checklist, forbidden actions, and halt conditions.
### commit-validator
Validates git commits. Checks AI attribution, single focus, no secrets, tests pass.
### env-separator
Enforces test/production separation. Detects shared instances, production DB in tests.
### scope-validator
Enforces scope boundaries. Only explicitly authorized files may be modified.
### production-first
Requires production code before tests. Order: implementation, validation, tests, infrastructure.
### three-strikes
Failure recovery. After three consecutive failures, halts and escalates to user.
### error-recovery
Error handling procedures. Provides structured guidance when operations fail.
## Shared Prompts Reference
All rule markdown files incorporate rules from the shared prompts directory:
| Shared Prompt | Used By Rules |
|---------------|---------------|
| `skills/shared-prompts/four-laws.md` | guardrails-enforcer |
| `skills/shared-prompts/halt-conditions.md` | guardrails-enforcer |
| `skills/shared-prompts/three-strikes.md` | three-strikes |
| `skills/shared-prompts/production-first.md` | production-first |
| `skills/shared-prompts/clean-architecture.md` | guardrails-enforcer |
| `skills/shared-prompts/cqrs.md` | guardrails-enforcer |
| `skills/shared-prompts/scope-validation.md` | scope-validator |
| `skills/shared-prompts/error-recovery.md` | error-recovery |
When shared prompts are updated, re-run the setup script:
```bash
python scripts/setup_agents.py --install --platform cursor
```
## Customization
### Adding a Custom Rule
1. Create a new markdown file in `.cursor/rules/`:
```markdown
---
description: Custom TypeScript strict mode enforcement
globs: "src/**/*.ts"
alwaysApply: false
---
## Always
- Use strict mode for all TypeScript files
- No `any` types allowed
- All functions must have return type annotations
```
2. Cursor automatically loads rules from this directory.
### Rule Priority
Rules are applied in order:
1. `.cursorrules` (global) - Applied first
2. `.cursor/rules/*.md` - Applied in alphabetical order
Later rules can override earlier ones for the same context.
### Conditional Rules with Globs
Use `globs` to target specific file patterns (e.g., `"**/*.py"`, `"src/**/*.ts"`). Set `alwaysApply: true` for safety rules that must always be active.
### Disabling a Rule
Move it out of the rules directory:
```bash
mkdir -p .cursor/rules/disabled
mv .cursor/rules/commit-validator.md .cursor/rules/disabled/
```
Cursor will stop loading it immediately.
## Installation Modes
| Mode | Command | Behavior |
|------|---------|----------|
| Copy | `--mode copy` (default) | Writes standalone copies to the project |
| Symlink | `--mode symlink` | Creates symlinks back to this repo |
## Troubleshooting
### Rules Not Loading
- Check frontmatter: `---` delimiters with valid YAML
- Files in `.cursor/rules/` with `.md` extension
- Restart Cursor to reload rules
### .cursorrules Not Applied
- File is in project root (not `.cursor/`)
- File is named exactly `.cursorrules` (no extension)
- Restart Cursor to re-index
### Rules Being Ignored
- Save all rule files
- Restart Cursor to reload
- Check for conflicting rules (later rules override earlier ones)
- Verify `globs` pattern matches the files being edited
## Best Practices
1. **One rule = one responsibility** - Keep rules focused and composable
2. **Always include frontmatter** - `description`, `globs`, `alwaysApply` are required
3. **Use `alwaysApply: true` for guardrails** - Safety rules should not be optional
4. **Regenerate after shared prompt updates** - Re-run setup to sync rules
5. **Commit `.cursor/` and `.cursorrules`** - Team shares the same guardrails
## References
- [AGENTS_AND_SKILLS_SETUP.md](AGENTS_AND_SKILLS_SETUP.md) - Unified setup guide
- [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) - Core safety protocols
- [skills/shared-prompts/](../skills/shared-prompts/) - Canonical prompt definitions

View File

@ -0,0 +1,349 @@
# Gap Analysis Report - Team of 4
**Analysis Date:** 2026-02-15
**Team Size:** 4 members (per TEAM-007 compliance)
**Scope:** MCP Team Tools Implementation
---
## Executive Summary
**Team Composition:**
- Analyst #1: Functional Gaps
- Analyst #2: Test Coverage Gaps
- Analyst #3: Security Gaps
- Analyst #4: Operational/Docs Gaps
**Overall Assessment:** 47 gaps identified across 4 categories
| Category | Critical | High | Medium | Low | Total |
|----------|----------|------|--------|-----|-------|
| Functional | 2 | 4 | 6 | 3 | 15 |
| Testing | 3 | 2 | 1 | 0 | 6 |
| Security | 2 | 3 | 4 | 2 | 11 |
| Operational | 1 | 3 | 5 | 6 | 15 |
| **TOTAL** | **8** | **12** | **16** | **11** | **47** |
---
## Analyst #1: Functional Gaps
### FUNC-001: No Unassign/Remove Capability [CRITICAL]
**Location:** `team_manager.py:assign_role()`
**Issue:** Can assign roles but cannot remove assignments
**Impact:** No way to remove people from teams
**Fix:** Add `guardrail_team_unassign` tool
### FUNC-002: No Team/Project Deletion [CRITICAL]
**Location:** `team_manager.py`
**Issue:** Projects can be initialized but never deleted
**Impact:** Data accumulation, no cleanup mechanism
**Fix:** Add `guardrail_team_delete` and `guardrail_project_delete` tools
### FUNC-003: No Role Validation [HIGH]
**Location:** `team_manager.py:364`, `team_tool_handlers.go:130`
**Issue:** `role_name` accepts any string; no validation against standard roles
**Impact:** Invalid roles can be assigned
**Fix:** Validate against team-layout-rules.json role definitions
### FUNC-004: No Phase Parameter Validation [HIGH]
**Location:** `team_tool_handlers.go:84,184`
**Issue:** Phase filter accepts any string
**Impact:** Invalid phase queries return confusing results
**Fix:** Validate against "Phase 1"-"Phase 5"
### FUNC-005: No Batch Operations [HIGH]
**Location:** All handlers
**Issue:** Must assign roles one-by-one
**Impact:** Inefficient for large team setups
**Fix:** Add bulk import/export (CSV/JSON)
### FUNC-006: No Query API [MEDIUM]
**Location:** `team_manager.py`
**Issue:** Cannot search by person, role, or status
**Impact:** Hard to find who is assigned where
**Fix:** Add query/filter capabilities
### FUNC-007: Missing Agent Types [MEDIUM]
**Location:** `team_tool_handlers.go:408-419`
**Issue:** Only 10 agent types; missing "coder", "reviewer"
**Impact:** Incomplete agent coverage
**Fix:** Add missing agent types from TEAM_STRUCTURE.md
### FUNC-008: Hardcoded Rules [MEDIUM]
**Location:** `team_tool_handlers.go:376-421`
**Issue:** Rules embedded in Go code instead of reading JSON
**Impact:** Changes require recompilation
**Fix:** Load from `.guardrails/team-layout-rules.json`
### FUNC-009: No Role Reassignment [MEDIUM]
**Location:** `team_manager.py`
**Issue:** Cannot move person from one role to another
**Impact:** Must unassign (not possible) then reassign
**Fix:** Add transfer capability
### FUNC-010: No Override Capability [MEDIUM]
**Location:** Phase gates
**Issue:** No mechanism to override phase gates with approval
**Impact:** Stuck if gate requirements can't be met
**Fix:** Add override with audit trail
### FUNC-011: No Team History [MEDIUM]
**Location:** `team_manager.py`
**Issue:** No tracking of who was assigned when
**Impact:** Cannot audit team changes over time
**Fix:** Add assignment history log
### FUNC-012: No Duplicate Detection [LOW]
**Location:** `team_manager.py:364`
**Issue:** Same person can be assigned to multiple roles in same team
**Impact:** Potential role conflicts
**Fix:** Add duplicate assignment check
---
## Analyst #2: Test Coverage Gaps
### TEST-001: No Handler Unit Tests [CRITICAL]
**Location:** Missing `team_tool_handlers_test.go`
**Issue:** 0% test coverage for 8 handlers
**Impact:** Changes can break functionality undetected
**Fix:** Create comprehensive test suite
### TEST-002: No Python Backend Tests [CRITICAL]
**Location:** Missing `test_team_manager.py`
**Issue:** 0% test coverage for team_manager.py
**Impact:** Backend logic untested **Fix:** Add pytest test suite
### TEST-003: No Integration Tests [CRITICAL]
**Location:** Entire feature
**Issue:** No Go -> Python integration tests
**Impact:** Interface mismatches undetected
**Fix:** Add integration test suite
### TEST-004: No Mock Infrastructure [HIGH]
**Location:** Test infrastructure
**Issue:** Tests require actual Python execution
**Impact:** Tests cannot run in isolated environments
**Fix:** Create Python script mock
### TEST-005: No E2E Tests [HIGH]
**Location:** Entire feature
**Issue:** No end-to-end workflow tests
**Impact:** User scenarios untested
**Fix:** Add e2e test scenarios
### TEST-006: No Test Fixtures [MEDIUM]
**Location:** `.teams/` directory
**Issue:** No test project configurations
**Impact:** Tests must set up their own data
**Fix:** Create test fixtures directory
---
## Analyst #3: Security Gaps
### SEC-001: No Authorization Checks [CRITICAL]
**Location:** All handlers
**Issue:** Any user can modify any project's teams
**Impact:** Unauthorized team modifications
**Fix:** Add RBAC checks
### SEC-002: No Role Name Validation [HIGH]
**Location:** `team_manager.py:364`, `team_tool_handlers.go:130`
**Issue:** Arbitrary strings accepted; could inject control chars
**Impact:** Data integrity issues
**Fix:** Whitelist validation
### SEC-003: No Person Name Validation [HIGH]
**Location:** `team_manager.py:364`, `team_tool_handlers.go:138`
**Issue:** No validation on assignee names
**Impact:** Invalid data, potential injection
**Fix:** Add format validation
### SEC-004: Race Conditions [HIGH]
**Location:** `team_manager.py:351-362`
**Issue:** No file locking; concurrent writes can corrupt
**Impact:** Data corruption
**Fix:** Add file locking, atomic writes
### SEC-005: No Rate Limiting [MEDIUM]
**Location:** All handlers
**Issue:** No protection against abuse
**Impact:** DoS potential
**Fix:** Add per-tool rate limits
### SEC-006: Path Traversal Risk [MEDIUM]
**Location:** `team_manager.py:327`
**Issue:** Project name validated but path construction needs verification
**Impact:** Potential file access outside `.teams/`
**Fix:** Validate absolute path result
### SEC-007: No Encryption at Rest [MEDIUM]
**Location:** `.teams/*.json`
**Issue:** Team data stored unencrypted
**Impact:** Sensitive data exposure
**Fix:** Add encryption option
### SEC-008: Missing Audit Logging [MEDIUM]
**Location:** All team handlers
**Issue:** Team operations not in audit log **Impact:** Changes not traceable
**Fix:** Add audit logging
### SEC-009: No Input Length Limits [LOW]
**Location:** `team_tool_handlers.go:130,138`
**Issue:** role_name and person have no max length
**Impact:** Potential memory issues
**Fix:** Add length validation
### SEC-010: Phase Parameter Injection [LOW]
**Location:** `team_tool_handlers.go:84`
**Issue:** Phase passed directly to shell
**Impact:** Low risk (spaces not allowed) but should validate
**Fix:** Validate phase values
---
## Analyst #4: Operational & Documentation Gaps
### OPS-001: No Structured Logging [CRITICAL]
**Location:** `team_manager.py:333`
**Issue:** Python uses print() instead of structured logging
**Impact:** Logs not queryable, no correlation IDs
**Fix:** Use structured JSON logging
### OPS-002: No Metrics [HIGH]
**Location:** All handlers
**Issue:** No Prometheus counters, timers, gauges
**Impact:** Cannot monitor team operation health
**Fix:** Add instrumentation
### OPS-003: No Health Check [HIGH]
**Location:** Python backend
**Issue:** No way to verify team_manager.py is functional
**Impact:** Cannot detect backend failures
**Fix:** Add health endpoint
### OPS-004: No Backup Mechanism [HIGH]
**Location:** `.teams/` directory
**Issue:** No automated backup of team configs
**Impact:** Data loss risk
**Fix:** Automated backup before writes
### OPS-005: No Versioning [MEDIUM]
**Location:** `team_manager.py:351-362`
**Issue:** Overwrites file in place; no history
**Impact:** Cannot recover from bad changes
**Fix:** Keep last N versions
### OPS-006: No Migration System [MEDIUM]
**Location:** `team_manager.py`
**Issue:** No way to migrate data format changes
**Impact:** Breaking changes require manual fix
**Fix:** Versioned migrations
### OPS-007: No Log Aggregation [MEDIUM]
**Location:** Python script
**Issue:** Python prints to stdout; no structured log shipping
**Impact:** Logs lost in containerized environments
**Fix:** Add log shipping
### OPS-008: No Performance Monitoring [MEDIUM]
**Location:** All handlers
**Issue:** No execution time tracking
**Impact:** Performance issues undetected
**Fix:** Add latency metrics
### OPS-009: No CLI Tool [LOW]
**Location:** Entire feature
**Issue:** Must use MCP tools; no standalone CLI
**Impact:** Hard to use outside MCP environment
**Fix:** Create CLI wrapper
### OPS-010: No Web UI [LOW]
**Location:** Entire feature
**Issue:** No visual interface for team management
**Impact:** Hard for non-technical users
**Fix:** Web dashboard
### OPS-011: No CI/CD Integration [LOW]
**Location:** Entire feature
**Issue:** No GitHub Actions for team validation
**Impact:** Cannot validate teams in CI
**Fix:** Add GitHub Action
### OPS-012: No Documentation on API Errors [LOW]
**Location:** `docs/TEAM_TOOLS.md`
**Issue:** No error code reference
**Impact:** Hard to troubleshoot failures
**Fix:** Add error reference section
### OPS-013: No Troubleshooting Guide [LOW]
**Location:** Documentation
**Issue:** No guide for common issues
**Impact:** Users stuck when things fail
**Fix:** Add troubleshooting doc
### OPS-014: No Architecture Diagram [LOW]
**Location:** Documentation
**Issue:** No visual of Go -> Python flow
**Impact:** Hard to understand integration
**Fix:** Add diagram
### OPS-015: No Migration Guide [LOW]
**Location:** Documentation
**Issue:** No guidance on migrating existing projects
**Impact:** Adoption friction
**Fix:** Add migration guide
---
## Consolidated Recommendations
### P0 - Critical (Address Immediately)
1. **Create Test Suite** (`team_tool_handlers_test.go`, `test_team_manager.py`)
2. **Add Authorization Checks** (RBAC before team modifications)
3. **Fix Race Conditions** (file locking in team_manager.py)
4. **Add Audit Logging** (all team operations)
5. **Implement Structured Logging** (replace print statements)
### P1 - High Priority (Next Sprint)
6. **Add Unassign/Delete Operations**
7. **Implement Role Validation**
8. **Add Metrics & Monitoring**
9. **Create Backup Mechanism**
10. **Add Health Checks**
### P2 - Medium Priority (Next Quarter)
11. **Load Rules from JSON** (remove hardcoding)
12. **Add Batch Operations**
13. **Implement Versioning**
14. **Add Query API**
15. **Create CLI Tool**
### P3 - Low Priority (Backlog)
16. Web UI Dashboard
17. CI/CD Integration
18. Encryption at Rest
19. Migration System
20. Architecture Diagrams
---
## Team Sign-off
**Analyst #1 (Functional):** ✅ Complete
**Analyst #2 (Testing):** ✅ Complete
**Analyst #3 (Security):** ✅ Complete
**Analyst #4 (Operational):** ✅ Complete
**Team Size Compliance:** 4 members (TEAM-007 ✅)
---
**Report Generated:** 2026-02-15
**Next Review:** After P0 items addressed

View File

@ -0,0 +1,352 @@
# Documentation Header Map
**Purpose:** Section-level lookup with file:line references for targeted reading.
**Usage:** Identify section → read with offset → minimal token consumption
---
## CORE GUARDRAILS
### AGENT_GUARDRAILS.md (docs/AGENT_GUARDRAILS.md)
| Section | Line | Offset |
|---------|------|--------|
| Applicability | 9 | 0 |
| Purpose | 27 | 18 |
| Four Laws of Agent Safety | 41 | 32 |
| Safety Protocols (Mandatory) | 53 | 44 |
| Pre-Execution Checklist | 55 | 46 |
| Git Safety Rules | 71 | 62 |
| Code Safety Rules | 84 | 75 |
| Test/Production Separation Rules | 97 | 88 |
| Guardrails | 112 | 103 |
| Halt Conditions | 114 | 105 |
| Forbidden Actions | 140 | 131 |
| Scope Boundaries | 194 | 185 |
| Quick Reference | 221 | 212 |
| Related Documents | 260 | 251 |
---
## 2026 UI/UX GAME DESIGN
### 2026_GAME_DESIGN.md (docs/game-design/2026_GAME_DESIGN.md)
| Section | Line | Offset |
|---------|------|--------|
| Purpose | 8 | 0 |
| Agent-GDUI-2026 Role Definition | 17 | 9 |
| Core Principles | 28 | 20 |
| Four Laws of Spatial Safety | 30 | 22 |
| Safety Protocols | 36 | 28 |
| Pre-Implementation Checklist | 38 | 30 |
| XR/VR Comfort Rules | 49 | 41 |
| Accessibility Requirements (WCAG 3.0+) | 61 | 53 |
| Performance Budgets | 73 | 65 |
| Dark Pattern Prevention | 84 | 76 |
| Platform-Specific Rules | 96 | 88 |
| Mobile (iOS/Android) | 98 | 90 |
| PC (Desktop/Web) | 105 | 97 |
| Console (Xbox/PlayStation/Switch) | 112 | 104 |
| XR (VR/AR/MR) | 119 | 111 |
| Halt Conditions | 127 | 119 |
| Language-Specific Patterns | 146 | 138 |
| TypeScript/React | 148 | 140 |
| Rust (Bevy Game Engine) | 158 | 150 |
| Go (HTMX Patterns) | 168 | 160 |
| Related Documents | 177 | 169 |
### 2026_UI_UX_STANDARD.md (docs/ui-ux/2026_UI_UX_STANDARD.md)
| Section | Line | Offset |
|---------|------|--------|
| Purpose | 8 | 0 |
| Agent-GDUI-2026 Capabilities | 17 | 9 |
| Core Components | 28 | 20 |
| Foundational Components | 30 | 22 |
| Advanced Components | 40 | 32 |
| Design Tokens | 50 | 42 |
| Color Palette | 52 | 44 |
| Typography Scale | 67 | 59 |
| Spacing Scale | 83 | 75 |
| Interaction States | 96 | 88 |
| State Requirements | 98 | 90 |
| Focus Indicator Standard | 109 | 101 |
| Animation Guidelines | 118 | 110 |
| Motion Principles | 120 | 112 |
| Motion Implementation | 130 | 122 |
| Responsive Breakpoints | 141 | 133 |
| Platform Adaptation | 143 | 135 |
| Responsive Pattern | 154 | 146 |
| Halt Conditions | 164 | 156 |
| Language-Specific Patterns | 183 | 175 |
| TypeScript/React | 185 | 177 |
| Rust (Leptos/Yew) | 196 | 188 |
| Go (HTMX) | 207 | 199 |
| Related Documents | 217 | 209 |
### ACCESSIBILITY_GUIDE.md (docs/accessibility/ACCESSIBILITY_GUIDE.md)
| Section | Line | Offset |
|---------|------|--------|
| Purpose | 8 | 0 |
| WCAG 3.0 Conformance Levels | 19 | 11 |
| Agent-GDUI-2026 Role | 26 | 18 |
| Implementation Checklist | 36 | 28 |
| Perceptual Accessibility | 38 | 30 |
| Cognitive Accessibility | 50 | 42 |
| Physical Accessibility | 62 | 54 |
| Technical Implementation | 74 | 66 |
| Contrast Calculation | 76 | 68 |
| Focus Indicator | 91 | 83 |
| Screen Reader Support | 102 | 94 |
| Keyboard Navigation | 124 | 116 |
| Testing Methods | 137 | 129 |
| Automated Testing | 139 | 131 |
| Manual Testing | 149 | 141 |
| Halt Conditions | 158 | 150 |
| Language-Specific Patterns | 179 | 171 |
| TypeScript/React | 181 | 173 |
| Rust | 192 | 184 |
| Related Documents | 203 | 195 |
### SPATIAL_COMPUTING_UI.md (docs/spatial/SPATIAL_COMPUTING_UI.md)
| Section | Line | Offset |
|---------|------|--------|
| Purpose | 8 | 0 |
| Agent-GDUI-2026 Spatial Capabilities | 17 | 9 |
| Spatial Safety Protocols | 28 | 20 |
| Comfort Zones | 30 | 22 |
| Latency Requirements | 39 | 31 |
| Vestibular Safety | 46 | 38 |
| UI Layout Patterns | 56 | 48 |
| VR Layout (Full Immersion) | 58 | 50 |
| AR Layout (Physical Overlay) | 78 | 70 |
| MR Layout (Bidirectional) | 90 | 82 |
| Depth Layering | 102 | 94 |
| Three-Layer Standard | 104 | 96 |
| Depth Implementation | 114 | 106 |
| Interaction Patterns | 125 | 117 |
| Hand Gesture Vocabulary | 127 | 119 |
| Gaze Interaction | 138 | 130 |
| Haptic Feedback Patterns | 146 | 138 |
| Accessibility in XR | 157 | 149 |
| Spatial Accessibility | 159 | 151 |
| Cognitive Accessibility in XR | 171 | 163 |
| Performance Budgets | 180 | 172 |
| Frame Rate Requirements | 182 | 174 |
| Async Reprojection | 192 | 184 |
| Halt Conditions | 202 | 194 |
| Language-Specific Patterns | 229 | 221 |
| TypeScript (OpenXR/WebXR) | 231 | 223 |
| Rust (XR frameworks) | 244 | 236 |
| Related Documents | 263 | 255 |
### ETHICAL_ENGAGEMENT.md (docs/ethical/ETHICAL_ENGAGEMENT.md)
| Section | Line | Offset |
|---------|------|--------|
| Purpose | 8 | 0 |
| Agent-GDUI-2026 Ethical Review | 17 | 9 |
| Dark Pattern Taxonomy | 28 | 20 |
| Category 1: Deceptive Interfaces | 30 | 22 |
| Category 2: Coercive Interfaces | 40 | 32 |
| Category 3: Addictive Interfaces | 50 | 42 |
| Category 4: Data Exploitation | 60 | 52 |
| Ethical Design Principles | 70 | 62 |
| Principle 1: Transparency | 72 | 64 |
| Principle 2: Choice | 79 | 71 |
| Principle 3: Wellbeing | 86 | 78 |
| Principle 4: Respect | 93 | 85 |
| Implementation Checklist | 100 | 92 |
| Pre-Deployment Ethical Review | 102 | 94 |
| Technical Implementation | 115 | 107 |
| Ethical Middleware | 117 | 109 |
| Dark Pattern Detection | 135 | 127 |
| Cancellation Flow | 169 | 161 |
| Halt Conditions | 179 | 171 |
| Language-Specific Patterns | 200 | 192 |
| TypeScript (React Ethics) | 202 | 194 |
| Go (Ethical Engagement) | 216 | 208 |
| Related Documents | 232 | 224 |
---
## WORKFLOW DOCUMENTATION
### workflows/INDEX.md (docs/workflows/INDEX.md)
| Section | Line | Offset |
|---------|------|--------|
| Workflow Index | 1 | 0 |
### COMMIT_WORKFLOW.md (docs/workflows/COMMIT_WORKFLOW.md)
| Section | Line | Offset |
|---------|------|--------|
| Commit Workflow | 1 | 0 |
### TESTING_VALIDATION.md (docs/workflows/TESTING_VALIDATION.md)
| Section | Line | Offset |
|---------|------|--------|
| Testing Validation | 1 | 0 |
### GIT_PUSH_PROCEDURES.md (docs/workflows/GIT_PUSH_PROCEDURES.md)
| Section | Line | Offset |
|---------|------|--------|
| Git Push Procedures | 1 | 0 |
---
## STANDARDS DOCUMENTATION
### standards/INDEX.md (docs/standards/INDEX.md)
| Section | Line | Offset |
|---------|------|--------|
| Standards Index | 1 | 0 |
### TEST_PRODUCTION_SEPARATION.md (docs/standards/TEST_PRODUCTION_SEPARATION.md)
| Section | Line | Offset |
|---------|------|--------|
| Test/Production Separation | 1 | 0 |
### MODULAR_DOCUMENTATION.md (docs/standards/MODULAR_DOCUMENTATION.md)
| Section | Line | Offset |
|---------|------|--------|
| Modular Documentation | 1 | 0 |
---
## MCP SERVER
### MCP_TOOLS_REFERENCE.md (docs/MCP_TOOLS_REFERENCE.md)
| Section | Line | Offset |
|---------|------|--------|
| MCP Tools Reference | 1 | 0 |
### TEAM_TOOLS.md (docs/TEAM_TOOLS.md)
| Section | Line | Offset |
|---------|------|--------|
| Team Tools | 1 | 0 |
### ARCHITECTURE_CLEAN_CQRS.md (docs/ARCHITECTURE_CLEAN_CQRS.md)
| Section | Line | Offset |
|---------|------|--------|
| Clean Architecture & CQRS | 1 | 0 |
---
## AI TOOL INTEGRATION
### CLCODE_INTEGRATION.md (docs/CLCODE_INTEGRATION.md)
| Section | Line | Offset |
|---------|------|--------|
| Claude Code Integration | 1 | 0 |
### OPCODE_INTEGRATION.md (docs/OPCODE_INTEGRATION.md)
| Section | Line | Offset |
|---------|------|--------|
| OpenCode Integration | 1 | 0 |
### CURSOR_INTEGRATION.md (docs/CURSOR_INTEGRATION.md)
| Section | Line | Offset |
|---------|------|--------|
| Cursor Integration | 1 | 0 |
### WINDSURF_INTEGRATION.md (docs/WINDSURF_INTEGRATION.md)
| Section | Line | Offset |
|---------|------|--------|
| Windsurf Integration | 1 | 0 |
### COPILOT_INTEGRATION.md (docs/COPILOT_INTEGRATION.md)
| Section | Line | Offset |
|---------|------|--------|
| GitHub Copilot Integration | 1 | 0 |
### AGENTS_AND_SKILLS_SETUP.md (docs/AGENTS_AND_SKILLS_SETUP.md)
| Section | Line | Offset |
|---------|------|--------|
| Quick Start | 5 | 0 |
| Platform Comparison | 16 | 11 |
| Installation Methods | 28 | 23 |
| MCP Tool (Automated) | 30 | 25 |
| Python Script (CLI) | 51 | 46 |
| Manual Copy | 81 | 76 |
| Symlink (Live Updates) | 104 | 99 |
| Per-Platform Guides | 115 | 110 |
| Claude Code | 117 | 112 |
| Cursor | 165 | 160 |
| Windsurf | 209 | 204 |
| OpenCode | 238 | 233 |
| GitHub Copilot | 315 | 310 |
| Shared Prompts | 345 | 340 |
| MCP Tool Usage | 361 | 356 |
| Architecture Reference | 407 | 402 |
| Customization | 415 | 410 |
| Troubleshooting | 459 | 454 |
| References | 487 | 482 |
---
## SHARED SKILL PROMPTS (skills/shared-prompts/)
| File | Purpose |
|------|---------|
| four-laws.md | Four Laws of Agent Safety |
| halt-conditions.md | When to stop and escalate |
| vibe-coding.md | Vibe coding principles |
| error-recovery.md | How to recover from failures |
| three-strikes.md | Failure attempt tracking |
| production-first.md | Production before test |
| scope-validation.md | File scope authorization |
---
## LANGUAGE-SPECIFIC EXAMPLES
| Language | Directory | README Location |
|----------|-----------|---------------|
| Go | examples/go/ | examples/go/README.md |
| Java | examples/java/ | examples/java/README.md |
| Python | examples/python/ | examples/python/README.md |
| Ruby | examples/ruby/ | examples/ruby/README.md |
| Rust | examples/rust/ | examples/rust/README.md |
| TypeScript | examples/typescript/ | examples/typescript/README.md |
---
## QUICK OFFSET USAGE
```bash
# Read specific section with offset
# Example: Read Halt Conditions from 2026_GAME_DESIGN.md
read docs/game-design/2026_GAME_DESIGN.md --offset 127 --limit 20
# Example: Read Accessibility Requirements from ACCESSIBILITY_GUIDE.md
read docs/accessibility/ACCESSIBILITY_GUIDE.md --offset 38 --limit 20
# Example: Read Dark Pattern Prevention from ETHICAL_ENGAGEMENT.md
read docs/ethical/ETHICAL_ENGAGEMENT.md --offset 84 --limit 20
```
---
**Last Updated:** 2026-05-09
**Document Owner:** Documentation Team
**Token Savings:** 60-80% vs full document reads

View File

@ -0,0 +1,434 @@
# How to Apply Agent Guardrails
> Detailed instructions for adding agent guardrails to existing or new repositories.
**Related:** [AGENT_GUARDRAILS.md](../AGENT_GUARDRAILS.md) | [INDEX_MAP.md](../INDEX_MAP.md)
---
## Overview
This document provides step-by-step instructions for applying the agent guardrails framework to repositories in different scenarios.
clone from https://github.com/TheArchitectit/agent-guardrails-template
---
## Option A: Apply to an EXISTING Repository
Execute these steps in order:
```
STEP 1: Create docs directory structure
─────────────────────────────────────────────
ACTION: Create directories if they don't exist
COMMAND: mkdir -p docs/sprints/archive
STEP 1.5: Copy Claude Configuration
─────────────────────────────────────────────
ACTION: Read CLAUDE.md from this template
ACTION: Write to TARGET_REPO/CLAUDE.md
ACTION: Read .claudeignore from this template
ACTION: Write to TARGET_REPO/.claudeignore
STEP 2: Copy AGENT_GUARDRAILS.md
─────────────────────────────────────────────
ACTION: Read docs/AGENT_GUARDRAILS.md from this template
ACTION: Write to TARGET_REPO/docs/AGENT_GUARDRAILS.md
STEP 3: Copy Sprint Framework
─────────────────────────────────────────────
ACTION: Read docs/sprints/SPRINT_TEMPLATE.md from this template
ACTION: Write to TARGET_REPO/docs/sprints/SPRINT_TEMPLATE.md
ACTION: Read docs/sprints/SPRINT_GUIDE.md from this template
ACTION: Write to TARGET_REPO/docs/sprints/SPRINT_GUIDE.md
ACTION: Read docs/sprints/INDEX.md from this template
ACTION: Write to TARGET_REPO/docs/sprints/INDEX.md
STEP 4: Update target README.md
─────────────────────────────────────────────
ACTION: Add to Documentation section:
| [**Agent Guardrails**](docs/AGENT_GUARDRAILS.md) | **MANDATORY** safety protocols for ALL AI agents |
ACTION: Add to Contributing section:
> **AI Agents:** Before contributing, read [Agent Guardrails](docs/AGENT_GUARDRAILS.md)
STEP 5: Copy GitHub templates (optional)
─────────────────────────────────────────────
ACTION: Create .github directory if needed
ACTION: Copy .github/PULL_REQUEST_TEMPLATE.md
ACTION: Copy .github/ISSUE_TEMPLATE/bug_report.md
STEP 6: Commit changes
─────────────────────────────────────────────
COMMAND: git add docs/ .github/
COMMAND: git commit -m "docs: add agent guardrails and sprint framework
Added standardized AI agent safety protocols and sprint task templates.
Applies to all LLMs and automated systems.
Authored by TheArchitectit"
```
---
## Option B: Example AI Agent Prompts
**Copy and paste these prompts when working with AI agents.**
### Prompt 1: Add Guardrails to Existing Repository
```
Add the agent guardrails framework from https://github.com/TheArchitectit/agent-guardrails-template
to this repository.
REQUIREMENTS:
1. Create docs/workflows/ and docs/standards/ directories
2. Copy all guardrails documentation (20 total files)
3. Update CLAUDE.md to reference guardrails
4. Update README.md to include guardrails section
5. Update existing documentation index files if they exist
6. Do NOT modify existing code files
7. Commit with message: "docs: add agent guardrails v1.2 framework"
MUST INCLUDE:
- docs/AGENT_GUARDRAILS.md
- docs/standards/TEST_PRODUCTION_SEPARATION.md
- docs/workflows/AGENT_EXECUTION.md
- docs/workflows/AGENT_ESCALATION.md
- All workflow (10 files) and standards (5 files) documents
```
### Prompt 2: Update README with Guardrails Reference
```
Update this repository's README.md to include agent guardrails references.
ADD to top of README:
---
## ⚠️ MANDATORY: AI Agent Guardrails
ALL AI agents MUST read these documents BEFORE any code changes:
| Document | Purpose | Critical For |
|----------|---------|--------------|
| [AGENT_GUARDRAILS.md](docs/AGENT_GUARDRAILS.md) | Core safety protocols (MANDATORY) | ALL operations |
| [TEST_PRODUCTION_SEPARATION.md](docs/standards/TEST_PRODUCTION_SEPARATION.md) | Test/production isolation (MANDATORY) | Deployments |
| [AGENT_EXECUTION.md](docs/workflows/AGENT_EXECUTION.md) | Execution protocol & rollback | Task execution |
| [AGENT_ESCALATION.md](docs/workflows/AGENT_ESCALATION.md) | Audit & escalation procedures | Errors/Uncertainty |
---
UPDATE Contributing section to add:
> **AI Agents:** Before contributing, read [Agent Guardrails](docs/AGENT_GUARDRAILS.md) and [Test/Production Separation](docs/standards/TEST_PRODUCTION_SEPARATION.md).
UPDATE existing Documentation table to include:
| [**Test/Production Separation**](docs/standards/TEST_PRODUCTION_SEPARATION.md) | **MANDATORY** test/production isolation standards |
```
### Prompt 3: Migrate Existing Documentation to Guardrails
```
I have existing documentation in this repository. Help me migrate it to follow
the agent guardrails framework.
ANALYSIS NEEDED:
1. List all existing documentation files
2. Check if any are over 500 lines (need splitting)
3. Identify which documents could be moved to:
- docs/workflows/ (operational procedures)
- docs/standards/ (coding standards)
- docs/sprints/ (task documents)
4. Check if AGENT_GUARDRAILS.md exists
5. Check if INDEX_MAP.md or HEADER_MAP.md exist
ACTIONS TO TAKE:
1. Create missing directory structures
2. Import guardrails framework from /mnt/ollama/git/agent-guardrails-template
3. Reorganize existing docs into appropriate directories
4. Split any docs over 500 lines
5. Create/update INDEX_MAP.md and HEADER_MAP.md
6. Update README.md navigation
7. Commit with descriptive message
ASK ME before:
- Deleting any documentation
- Splitting any documents
- Making major structural changes
```
### Prompt 4: Quick Guardrails Copy
```
Quickly copy the guardrails framework to this repository.
Commands to execute:
1. mkdir -p docs/workflows docs/standards docs/sprints/archive
2. cp /mnt/ollama/git/agent-guardrails-template/docs/AGENT_GUARDRAILS.md docs/
3. cp /mnt/ollama/git/agent-guardrails-template/docs/workflows/*.md docs/workflows/
4. cp /mnt/ollama/git/agent-guardrails-template/docs/standards/*.md docs/standards/
5. cp /mnt/ollama/git/agent-guardrails-template/docs/sprints/*.md docs/sprints/
6. Add guardrails section to README.md and CLAUDE.md
7. git add docs/
8. git commit -m "docs: add agent guardrails v1.2 framework
- Added comprehensive safety protocols for AI agents
- Added test/production separation standards (MANDATORY)
- Added execution protocols and audit requirements
- All documents under 500-line compliance
Authored by TheArchitectit"
DO NOT:
- Modify any source code files
- Delete existing documentation
- Change .gitignore
```
### Prompt 5: Verify Guardrails Installation
```
Verify that agent guardrails framework is properly installed in this repository.
CHECK:
[ ] docs/AGENT_GUARDRAILS.md exists and is complete
[ ] docs/standards/TEST_PRODUCTION_SEPARATION.md exists
[ ] docs/workflows/AGENT_EXECUTION.md exists
[ ] docs/workflows/AGENT_ESCALATION.md exists
[ ] docs/workflows/ contains at least 10 files
[ ] docs/standards/ contains at least 5 files
[ ] README.md references guardrails
[ ] CLAUDE.md references guardrails
[ ] All documentation files are under 500 lines (check with wc -l)
[ ] No duplicate files from old framework
REPORT:
- Number of guardrails files installed
- total documentation count
- Any issues found
- Verification status: PASS/FAIL
```
---
## Option C: Create a NEW Repository with Standards
Execute these steps in order:
```
STEP 1: Create new repository
─────────────────────────────────────────────
COMMAND: mkdir new-project && cd new-project
COMMAND: git init
STEP 2: Create directory structure
─────────────────────────────────────────────
COMMAND: mkdir -p src tests docs/sprints/archive .github/ISSUE_TEMPLATE
STEP 3: Copy all template files
─────────────────────────────────────────────
FILES TO COPY:
- INDEX_MAP.md (navigation map)
- HEADER_MAP.md (section lookup)
- CLAUDE.md
- .claudeignore
- docs/AGENT_GUARDRAILS.md
- docs/workflows/ (all 10 files)
- docs/standards/ (all 5 files)
- docs/sprints/SPRINT_TEMPLATE.md
- docs/sprints/SPRINT_GUIDE.md
- docs/sprints/INDEX.md
- .github/SECRETS_MANAGEMENT.md
- .github/workflows/ (all 3 files)
- .github/PULL_REQUEST_TEMPLATE.md
- .github/ISSUE_TEMPLATE/bug_report.md
- .gitignore
STEP 4: Create README.md
─────────────────────────────────────────────
ACTION: Use the PROJECT README TEMPLATE section in main README.md
ACTION: Customize for the specific project
STEP 5: Initial commit
─────────────────────────────────────────────
COMMAND: git add -A
COMMAND: git commit -m "feat: initial project setup with agent guardrails
- Project structure initialized
- Agent guardrails and sprint framework included
- GitHub templates configured
Authored by TheArchitectit"
STEP 6: Create GitHub repo (if requested)
─────────────────────────────────────────────
COMMAND: gh repo create PROJECT_NAME --private --source=. --push
```
---
## Option D: Migrate Existing Documentation to Guardrails Structure
**If you have an existing repository with documentation, restructure it to follow guardrails conventions.**
```
STEP 1: Analyze Existing Documentation
─────────────────────────────────────────────
ACTION: List all documentation in repository
COMMAND: find . -name "*.md" -type f | grep -v node_modules | grep -v target
ACTION: Check line counts
COMMAND: for f in **/*.md; do echo "$f: $(wc -l < $f) lines"; done
STEP 2: Categorize Documents
─────────────────────────────────────────────
Create directory structure:
docs/workflows/ - Operational procedures (commit, push, rollback, etc.)
docs/standards/ - Coding standards and patterns (logging, API specs, etc.)
docs/sprints/ - Task documents and sprint templates
STEP 3: Import Guardrails Framework
─────────────────────────────────────────────
Follow Option B prompts to add guardrails
STEP 4: Reorganize Existing Docs
─────────────────────────────────────────────
CATEGORIZATION GUIDE:
WORKFOLWS (move to docs/workflows/):
- Commit procedures → COMMIT_WORKFLOW.md (or merge with existing)
- Git operations → GIT_*.md files
- Testing procedures → TESTING_VALIDATION.md (or merge)
- Code review → CODE_REVIEW.md (or merge)
STANDARDS (move to docs/standards/):
- Coding conventions → MODULAR_DOCUMENTATION.md (or merge)
- Logging patterns → LOGGING_PATTERNS.md (or merge)
- API documentation → API_SPECIFICATIONS.md (or merge)
Sprints (move to docs/sprints/):
- Task documents → Keep as individual sprint docs
- Templates → Rename if using SPRINT_TEMPLATE.md format
STEP 5: Split Oversized Documents
─────────────────────────────────────────────
IF any doc > 500 lines:
1. Identify natural section boundaries
2. Create parent doc in new location with INDEX.md
3. Move sections to separate files
4. Update cross-references
STEP 6: Create Navigation Maps
─────────────────────────────────────────────
Import or create:
- INDEX_MAP.md - Master navigation by keyword
- HEADER_MAP.md - Section headers with line numbers
STEP 7: Update README.md
─────────────────────────────────────────────
Add documentation section:
---
## Documentation
| Document | Description |
|----------|-------------|
| [**INDEX_MAP.md**](INDEX_MAP.md) | Master navigation - find docs by keyword |
| [**Agent Guardrails**](docs/AGENT_GUARDRAILS.md) | **MANDATORY** safety protocols |
| [**Workflows**](docs/workflows/INDEX.md) | Operational procedures |
| [**Standards**](docs/standards/INDEX.md) | Coding standards |
---
STEP 8: Commit Migration
─────────────────────────────────────────────
COMMAND: git add docs/ .github/
COMMAND: git commit -m "docs: restructure documentation to follow guardrails conventions
- Imported agent guardrails framework v1.2
- Reorganized existing docs into workflows/standards/sprints/
- Split oversized documents for 500-line compliance
- Added navigation maps (INDEX_MAP.md, HEADER_MAP.md)
- Updated README.md documentation section
Authored by TheArchitectit"
```
### Migration Example
**Before:**
```
project/
├── README.md
├── CONTRIBUTING.md
├── DOCUMENTATION.md (800 lines - too large)
├── GIT_GUIDE.md
├── CODING_STANDARDS.md
└── .github/
```
**After:**
```
project/
├── README.md
├── CLAUDE.md
├── .claudeignore
├── INDEX_MAP.md
├── HEADER_MAP.md
├── docs/
│ ├── AGENT_GUARDRAILS.md
│ ├── CONTRIBUTING.md
│ ├── workflows/
│ │ ├── INDEX.md
│ │ ├── COMMIT_WORKFLOW.md
│ │ ├── GIT_PUSH_PROCEDURES.md
│ │ └── ...
│ ├── standards/
│ │ ├── INDEX.md
│ │ ├── TEST_PRODUCTION_SEPARATION.md
│ │ ├── MODULAR_DOCUMENTATION.md
│ │ └── CODING_STANDARDS.md
│ └── DOCUMENTATION/
│ ├── INDEX.md
│ ├── ARCHITECTURE.md (300 lines)
│ ├── API_REFERENCE.md (350 lines)
│ └── DEPLOYMENT.md (150 lines)
└── .github/
```
---
## Verification Checklist
After applying the template, verify:
```
NAVIGATION MAPS:
[ ] INDEX_MAP.md exists at root
[ ] HEADER_MAP.md exists at root
CORE DOCUMENTATION:
[ ] docs/AGENT_GUARDRAILS.md exists and is complete
[ ] docs/workflows/ contains 10 workflow documents (including AGENT_EXECUTION.md, AGENT_ESCALATION.md)
[ ] docs/standards/ contains 5 standards documents (including TEST_PRODUCTION_SEPARATION.md)
[ ] docs/sprints/SPRINT_TEMPLATE.md exists
[ ] docs/sprints/SPRINT_GUIDE.md exists
[ ] docs/sprints/INDEX.md exists
GITHUB INTEGRATION:
[ ] .github/SECRETS_MANAGEMENT.md exists
[ ] .github/workflows/ contains 3 CI workflows
[ ] .github/PULL_REQUEST_TEMPLATE.md exists
PROJECT FILES:
[ ] CLAUDE.md configured for project
[ ] README.md links to INDEX_MAP.md and Agent Guardrails
[ ] .gitignore exists
[ ] All docs under 500 lines (check with: find docs -name "*.md" -exec sh -c 'wc -l "$1" | awk "{if($1>500) print $1\" lines: \"$1}"' _ {} \;)
```
---
**Authored by:** TheArchitectit
**Document Owner:** Project Maintainers
**Last Updated:** 2026-01-16
**Line Count:** ~295

View File

@ -0,0 +1,201 @@
# Documentation Index Map
**Purpose:** Find documentation by keyword/category. Saves 60-80% tokens vs full document reads.
**Usage:** Search keyword → identify doc → use HEADER_MAP.md for section-level lookup → read specific section
---
## CORE GUARDRAILS
| Keyword | Document | Location |
|---------|----------|----------|
| agent safety, four laws, halt conditions | [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) | docs/ |
| test/prod separation | [TEST_PRODUCTION_SEPARATION.md](standards/TEST_PRODUCTION_SEPARATION.md) | docs/standards/ |
| regression prevention | [REGRESSION_PREVENTION.md](workflows/REGRESSION_PREVENTION.md) | docs/workflows/ |
| pre-work checklist | [.guardrails/pre-work-check.md](../.guardrails/pre-work-check.md) | .guardrails/ |
| failure registry | [.guardrails/failure-registry.jsonl](../.guardrails/failure-registry.jsonl) | .guardrails/ |
---
## 2026 UI/UX GAME DESIGN
**New Section:** Game Design & UI/UX 2026 Standards
| Keyword | Document | Location |
|---------|----------|----------|
| game, UI, UX, spatial, XR, VR, AR, accessibility, 2026 | [2026_GAME_DESIGN.md](game-design/2026_GAME_DESIGN.md) | docs/game-design/ |
| component, design tokens, interaction, responsive | [2026_UI_UX_STANDARD.md](ui-ux/2026_UI_UX_STANDARD.md) | docs/ui-ux/ |
| WCAG 3.0, accessibility, contrast, keyboard, screen reader | [ACCESSIBILITY_GUIDE.md](accessibility/ACCESSIBILITY_GUIDE.md) | docs/accessibility/ |
| spatial computing, XR, VR, AR, MR, depth, comfort zone | [SPATIAL_COMPUTING_UI.md](spatial/SPATIAL_COMPUTING_UI.md) | docs/spatial/ |
| ethical, dark patterns, manipulation, engagement | [ETHICAL_ENGAGEMENT.md](ethical/ETHICAL_ENGAGEMENT.md) | docs/ethical/ |
| Agent-GDUI-2026 | [2026_GAME_DESIGN.md](game-design/2026_GAME_DESIGN.md) | docs/game-design/ |
### Agent-GDUI-2026 Capability References
| Capability | Document | Section |
|------------|----------|---------|
| Spatial Layout | [SPATIAL_COMPUTING_UI.md](spatial/SPATIAL_COMPUTING_UI.md) | Depth Layering |
| Motion Design | [2026_UI_UX_STANDARD.md](ui-ux/2026_UI_UX_STANDARD.md) | Animation Guidelines |
| Audio Spatialization | [SPATIAL_COMPUTING_UI.md](spatial/SPATIAL_COMPUTING_UI.md) | Audio Spatialization |
| Input Mapping | [2026_GAME_DESIGN.md](game-design/2026_GAME_DESIGN.md) | Platform-Specific Rules |
| Ethical Review | [ETHICAL_ENGAGEMENT.md](ethical/ETHICAL_ENGAGEMENT.md) | Dark Pattern Prevention |
| Performance Budget | [2026_GAME_DESIGN.md](game-design/2026_GAME_DESIGN.md) | Performance Budgets |
| Accessibility Compliance | [ACCESSIBILITY_GUIDE.md](accessibility/ACCESSIBILITY_GUIDE.md) | Implementation Checklist |
---
## WORKFLOW DOCUMENTATION
| Keyword | Document | Location |
|---------|----------|----------|
| agent execution, rollback, three strikes | [AGENT_EXECUTION.md](workflows/AGENT_EXECUTION.md) | docs/workflows/ |
| escalation, audit | [AGENT_ESCALATION.md](workflows/AGENT_ESCALATION.md) | docs/workflows/ |
| testing, validation | [TESTING_VALIDATION.md](workflows/TESTING_VALIDATION.md) | docs/workflows/ |
| commit workflow | [COMMIT_WORKFLOW.md](workflows/COMMIT_WORKFLOW.md) | docs/workflows/ |
| git push | [GIT_PUSH_PROCEDURES.md](workflows/GIT_PUSH_PROCEDURES.md) | docs/workflows/ |
| branch strategy | [BRANCH_STRATEGY.md](workflows/BRANCH_STRATEGY.md) | docs/workflows/ |
| code review | [CODE_REVIEW.md](workflows/CODE_REVIEW.md) | docs/workflows/ |
| rollback | [ROLLBACK_PROCEDURES.md](workflows/ROLLBACK_PROCEDURES.md) | docs/workflows/ |
| MCP checkpointing | [MCP_CHECKPOINTING.md](workflows/MCP_CHECKPOINTING.md) | docs/workflows/ |
| documentation updates | [DOCUMENTATION_UPDATES.md](workflows/DOCUMENTATION_UPDATES.md) | docs/workflows/ |
| agent review protocol | [AGENT_REVIEW_PROTOCOL.md](workflows/AGENT_REVIEW_PROTOCOL.md) | docs/workflows/ |
---
## STANDARDS DOCUMENTATION
| Keyword | Document | Location |
|---------|----------|----------|
| test/prod separation | [TEST_PRODUCTION_SEPARATION.md](standards/TEST_PRODUCTION_SEPARATION.md) | docs/standards/ |
| modular documentation, 500-line | [MODULAR_DOCUMENTATION.md](standards/MODULAR_DOCUMENTATION.md) | docs/standards/ |
| logging | [LOGGING_PATTERNS.md](standards/LOGGING_PATTERNS.md) | docs/standards/ |
| logging integration | [LOGGING_INTEGRATION.md](standards/LOGGING_INTEGRATION.md) | docs/standards/ |
| API | [API_SPECIFICATIONS.md](standards/API_SPECIFICATIONS.md) | docs/standards/ |
| adversarial testing | [ADVERSARIAL_TESTING.md](standards/ADVERSARIAL_TESTING.md) | docs/standards/ |
| dependency governance | [DEPENDENCY_GOVERNANCE.md](standards/DEPENDENCY_GOVERNANCE.md) | docs/standards/ |
| infrastructure | [INFRASTRUCTURE_STANDARDS.md](standards/INFRASTRUCTURE_STANDARDS.md) | docs/standards/ |
| operational patterns | [OPERATIONAL_PATTERNS.md](standards/OPERATIONAL_PATTERNS.md) | docs/standards/ |
| project context template | [PROJECT_CONTEXT_TEMPLATE.md](standards/PROJECT_CONTEXT_TEMPLATE.md) | docs/standards/ |
---
## SPRINT FRAMEWORK
| Keyword | Document | Location |
|---------|----------|----------|
| sprint template | [SPRINT_TEMPLATE.md](sprints/SPRINT_TEMPLATE.md) | docs/sprints/ |
| sprint guide | [SPRINT_GUIDE.md](sprints/SPRINT_GUIDE.md) | docs/sprints/ |
| sprint examples | [SPRINT_001_MCP_GAP_IMPLEMENTATION.md](sprints/SPRINT_001_MCP_GAP_IMPLEMENTATION.md) | docs/sprints/ |
---
## MCP SERVER
| Keyword | Document | Location |
|---------|----------|----------|
| MCP tools | [MCP_TOOLS_REFERENCE.md](MCP_TOOLS_REFERENCE.md) | docs/ |
| team tools | [TEAM_TOOLS.md](TEAM_TOOLS.md) | docs/ |
| team structure | [TEAM_STRUCTURE.md](TEAM_STRUCTURE.md) | docs/ |
| deployment | [DEPLOYMENT_GUIDE.md](../mcp-server/DEPLOYMENT_GUIDE.md) | mcp-server/ |
| API | [API.md](../mcp-server/API.md) | mcp-server/ |
| clean architecture, CQRS, vertical slices, SOLID, DDD | [ARCHITECTURE_CLEAN_CQRS.md](ARCHITECTURE_CLEAN_CQRS.md) | docs/ |
---
## AI TOOL INTEGRATION
| Keyword | Document | Location |
|---------|----------|----------|
| Claude Code | [CLCODE_INTEGRATION.md](CLCODE_INTEGRATION.md) | docs/ |
| OpenCode | [OPCODE_INTEGRATION.md](OPCODE_INTEGRATION.md) | docs/ |
| Cursor | [CURSOR_INTEGRATION.md](CURSOR_INTEGRATION.md) | docs/ |
| Windsurf | [WINDSURF_INTEGRATION.md](WINDSURF_INTEGRATION.md) | docs/ |
| GitHub Copilot | [COPILOT_INTEGRATION.md](COPILOT_INTEGRATION.md) | docs/ |
| agents, skills, setup, install, MCP tool, platform comparison | [AGENTS_AND_SKILLS_SETUP.md](AGENTS_AND_SKILLS_SETUP.md) | docs/ |
| skill configs | [.claude/skills/](../.claude/skills/) | / (root) |
| Cursor rules | [.cursor/rules/](../.cursor/rules/) | / (root) |
| OpenCode skills | [.opencode/](../.opencode/) | / (root) |
---
## SHARED SKILL PROMPTS
| Keyword | Document | Location |
|---------|----------|----------|
| four laws, agent safety | [skills/shared-prompts/four-laws.md](../skills/shared-prompts/four-laws.md) | / (root) |
| halt conditions | [skills/shared-prompts/halt-conditions.md](../skills/shared-prompts/halt-conditions.md) | / (root) |
| vibe coding | [skills/shared-prompts/vibe-coding.md](../skills/shared-prompts/vibe-coding.md) | / (root) |
| error recovery | [skills/shared-prompts/error-recovery.md](../skills/shared-prompts/error-recovery.md) | / (root) |
| three strikes | [skills/shared-prompts/three-strikes.md](../skills/shared-prompts/three-strikes.md) | / (root) |
| production-first | [skills/shared-prompts/production-first.md](../skills/shared-prompts/production-first.md) | / (root) |
| scope validation | [skills/shared-prompts/scope-validation.md](../skills/shared-prompts/scope-validation.md) | / (root) |
| clean architecture | [skills/shared-prompts/clean-architecture.md](../skills/shared-prompts/clean-architecture.md) | / (root) |
| CQRS | [skills/shared-prompts/cqrs.md](../skills/shared-prompts/cqrs.md) | / (root) |
| shared-prompt-install | [AGENTS_AND_SKILLS_SETUP.md](AGENTS_AND_SKILLS_SETUP.md) | docs/ |
---
## LANGUAGE-SPECIFIC EXAMPLES
| Language | Examples Directory |
|----------|-------------------|
| Go | [examples/go/](examples/go/) |
| Java | [examples/java/](examples/java/) |
| Python | [examples/python/](examples/python/) |
| Ruby | [examples/ruby/](examples/ruby/) |
| Rust | [examples/rust/](examples/rust/) |
| TypeScript | [examples/typescript/](examples/typescript/) |
### 2026 UI/UX Examples
| Pattern | Directory |
|---------|-----------|
| TypeScript UI Components | `examples/typescript/ui-components/` |
| TypeScript Game UI | `examples/typescript/game-ui/` |
| Python UI Dashboard | `examples/python/ui-dashboard/` |
| Python Game Tools | `examples/python/game-tools/` |
| Go HTMX Patterns | `examples/go/htmx-patterns/` |
| Go Admin UI | `examples/go/admin-ui/` |
| Rust Bevy UI | `examples/rust/bevy-ui-example/` |
| Rust egui Overlay | `examples/rust/egui-overlay/` |
---
## SECURITY
| Keyword | Document | Location |
|---------|----------|----------|
| secrets management | [SECRETS_MANAGEMENT.md](../.github/SECRETS_MANAGEMENT.md) | .github/ |
| security audit | [security/](security/) | docs/security/ |
---
## RELEASE HISTORY
| Keyword | Document | Location |
|---------|----------|----------|
| changelog | [CHANGELOG.md](CHANGELOG.md) | docs/ |
| v2.6.0 | [README.md](README.md) | / (current version) |
| v1.10.0 | [RELEASE_v1.10.0.md](RELEASE_v1.10.0.md) | docs/ |
| v1.9.x | [RELEASE_v1.9.0.md](RELEASE_v1.9.0.md) - [RELEASE_v1.9.6.md](RELEASE_v1.9.6.md) | docs/ |
---
## QUICK NAVIGATION
1. **New to guardrails?** → Start with [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md)
2. **Game/UI development?** → [2026_GAME_DESIGN.md](game-design/2026_GAME_DESIGN.md)
3. **Accessibility?** → [ACCESSIBILITY_GUIDE.md](accessibility/ACCESSIBILITY_GUIDE.md)
4. **Spatial computing?** → [SPATIAL_COMPUTING_UI.md](spatial/SPATIAL_COMPUTING_UI.md)
5. **Ethical review?** → [ETHICAL_ENGAGEMENT.md](ethical/ETHICAL_ENGAGEMENT.md)
6. **UI components?** → [2026_UI_UX_STANDARD.md](ui-ux/2026_UI_UX_STANDARD.md)
7. **Workflow?** → [workflows/INDEX.md](workflows/INDEX.md)
8. **Standards?** → [standards/INDEX.md](standards/INDEX.md)
9. **Sprints?** → [sprints/INDEX.md](sprints/INDEX.md)
---
**Last Updated:** 2026-05-09
**Document Owner:** Documentation Team
**Token Savings:** 60-80% vs full document reads

View File

@ -0,0 +1,321 @@
# MCP Tools Reference
Complete reference for Guardrails MCP validation tools.
---
## Quick Reference Table
| Tool | Purpose | Input | Categories Validated |
|------|---------|-------|---------------------|
| `guardrail_validate_bash` | Validate bash commands | Command string | bash |
| `guardrail_validate_git_operation` | Validate git operations | Operation + args | git |
| `guardrail_validate_file_edit` | Validate file edits | Path + content | file_edit, content, edit, security |
---
## guardrail_validate_bash
Validates bash commands against dangerous patterns.
### Description
Analyzes bash commands for potentially destructive or dangerous operations like `rm -rf /`, fork bombs, and data destruction patterns.
### Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | string | Yes | The bash command to validate |
### Return Value
```json
{
"violations": [
{
"rule_id": "BASH-001",
"severity": "critical",
"message": "Dangerous bash command detected",
"category": "bash"
}
]
}
```
### Example Usage
**Request:**
```json
{
"tool": "guardrail_validate_bash",
"arguments": {
"command": "rm -rf /"
}
}
```
**Response:**
```json
{
"violations": [
{
"rule_id": "BASH-001",
"severity": "critical",
"message": "Dangerous bash command detected",
"category": "bash"
}
]
}
```
**Valid Command (no violations):**
```json
{
"tool": "guardrail_validate_bash",
"arguments": {
"command": "ls -la /home/user"
}
}
```
**Response:**
```json
{
"violations": []
}
```
### Validated Rule Categories
| Category | Rules | Severity |
|----------|-------|----------|
| bash | BASH-001 | critical |
---
## guardrail_validate_git_operation
Validates git operations for safety and compliance.
### Description
Checks git commands against rules preventing force pushes, branch deletions, and history rewrites.
### Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `operation` | string | Yes | Git operation (push, commit, rebase, etc.) |
| `args` | array[string] | Yes | Command arguments |
### Return Value
```json
{
"violations": [
{
"rule_id": "GIT-001",
"severity": "error",
"message": "Force push to main/master is blocked",
"category": "git"
}
]
}
```
### Example Usage
**Request (Force Push Blocked):**
```json
{
"tool": "guardrail_validate_git_operation",
"arguments": {
"operation": "push",
"args": ["--force", "origin", "main"]
}
}
```
**Response:**
```json
{
"violations": [
{
"rule_id": "GIT-001",
"severity": "error",
"message": "Force push to main/master is blocked",
"category": "git"
}
]
}
```
**Request (Safe Operation):**
```json
{
"tool": "guardrail_validate_git_operation",
"arguments": {
"operation": "push",
"args": ["origin", "feature-branch"]
}
}
```
**Response:**
```json
{
"violations": []
}
```
### Validated Rule Categories
| Category | Rules | Severity Range |
|----------|-------|----------------|
| git | GIT-001 to GIT-006 | error, warning |
---
## guardrail_validate_file_edit
Validates file edits for security and safety compliance.
### Description
Multi-purpose validation tool checking file paths, content changes, and security patterns in edits.
### Input Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | Yes | File path being edited |
| `content` | string | Yes | New file content |
| `original_content` | string | No | Previous content (for diff analysis) |
### Return Value
```json
{
"violations": [
{
"rule_id": "API-001",
"severity": "critical",
"message": "API key exposure detected",
"category": "security"
}
]
}
```
### Example Usage
**Request (Secret Detection):**
```json
{
"tool": "guardrail_validate_file_edit",
"arguments": {
"path": "config.js",
"content": "const apiKey = 'sk_live_abc123xyz789secretkey';"
}
}
```
**Response:**
```json
{
"violations": [
{
"rule_id": "API-001",
"severity": "critical",
"message": "API key exposure",
"category": "security"
}
]
}
```
**Request (Protected File):**
```json
{
"tool": "guardrail_validate_file_edit",
"arguments": {
"path": ".claude/config.json",
"content": "{}",
"original_content": "{\"key\": \"value\"}"
}
}
```
**Response:**
```json
{
"violations": [
{
"rule_id": "GENERAL-001",
"severity": "error",
"message": "Cannot modify protected files (.claude/, docs/, .md files)",
"category": "general"
}
]
}
```
### Validated Rule Categories
| Category | Rules | Purpose |
|----------|-------|---------|
| file_edit | GENERAL-001 | Protected path patterns |
| content | CODE-xxx | Code security patterns |
| edit | GIT-xxx | Git-related content |
| security | API-xxx, DB-xxx, CONT-xxx, CFG-xxx | Security credentials |
---
## Validation Engine Features
### Caching
- **TTL:** 30 seconds
- **Scope:** Rule patterns cached to reduce database load
- **Invalidation:** Automatic after TTL expires
### Severity Levels
| Level | Color | Action |
|-------|-------|--------|
| critical | Red | Blocks operation |
| error | Orange | Blocks operation |
| warning | Yellow | Warns, allows with confirmation |
| info | Blue | Informational only |
### Pattern Matching
- **Engine:** Go regexp package
- **Flags:** Case-insensitive (?i) by default
- **Validation:** Pre-compiled for performance
---
## Tool Selection Guide
### Use `guardrail_validate_bash` when:
- Executing shell commands via Bash tool
- Running system commands
- Processing user-provided command strings
### Use `guardrail_validate_git_operation` when:
- Performing git push operations
- Executing git commands with arguments
- Automating git workflows
### Use `guardrail_validate_file_edit` when:
- Writing to files
- Modifying configuration files
- Processing file uploads
- Checking code for secrets before commit
---
## Related Documentation
| Document | Purpose |
|----------|---------|
| [RULES_INDEX_MAP.md](RULES_INDEX_MAP.md) | Complete rule reference |
| [RULE_PATTERNS_GUIDE.md](RULE_PATTERNS_GUIDE.md) | Writing custom patterns |
| [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) | Main guardrails guide |

View File

@ -0,0 +1,782 @@
# Migration Guide
> Version compatibility, migration instructions, and rollback procedures
**Version:** 1.0
**Last Updated:** 2026-02-15
---
## Table of Contents
1. [Version Compatibility Matrix](#version-compatibility-matrix)
2. [Breaking Changes by Version](#breaking-changes-by-version)
3. [Migration Procedures](#migration-procedures)
4. [Rollback Procedures](#rollback-procedures)
5. [Migration Examples](#migration-examples)
6. [Troubleshooting Migrations](#troubleshooting-migrations)
---
## Version Compatibility Matrix
### Current Version Support
| Version | Status | Support End | Compatible With | Implementation |
|---------|--------|-------------|-----------------|----------------|
| 2.6.x | Current | 2027-02-15 | 2.0.x, 1.10.x | **Go** |
| 2.0.x | Maintained | 2026-10-15 | 1.10.x, 1.9.x | Go |
| 1.10.x | Maintained | 2026-08-15 | 1.9.x | Go |
| 1.9.x | Maintained | 2026-06-15 | 1.8.x | Go |
| 1.8.x | Deprecated | 2026-04-15 | 1.7.x | Python |
| < 1.8.0 | End of Life | - | - | Python |
### Compatibility Legend
| Symbol | Meaning |
|--------|---------|
| Full | All features compatible |
| Partial | Some features require configuration |
| Breaking | Requires migration steps |
| N/A | Not compatible |
### MCP Server Compatibility
| Client Version | MCP Server 1.9 | MCP Server 1.10 | MCP Server 2.0 |
|----------------|----------------|-----------------|----------------|
| Claude Code 1.x | Full | Full | Full |
| Claude Code 2.x | Partial | Full | Full |
| OpenCode 1.x | Full | Full | Full |
| Cursor 1.x | N/A | Partial | Full |
| Custom Clients | Breaking | Partial | Full |
### Database Compatibility
| Database Version | Schema Version | Migration Required |
|------------------|----------------|------------------|
| PostgreSQL 15 | v1.8 | Yes |
| PostgreSQL 16 | v1.9+ | No |
| Redis 6 | v1.8 | Yes |
| Redis 7 | v1.9+ | No |
---
## Breaking Changes by Version
### v2.6.0 (Current) - Go Migration
**Release Date:** 2026-02-15
#### Breaking Changes
1. **Language Migration: Python to Go**
- **Old:** `scripts/team_manager.py` (Python)
- **New:** `mcp-server/internal/team/` (Go package)
- **Impact:** No runtime Python required
- **API:** Unchanged from MCP client perspective
2. **Build Process**
- Old: `pip install -r requirements.txt`
- New: `go build ./cmd/server`
- Binary: Single static binary vs Python interpreter
3. **Container**
- Old: Python-based image (~500MB)
- New: Distroless Go image (~50MB)
- Security: Non-root, read-only filesystem, dropped capabilities
#### Migration Benefits
| Metric | Python | Go | Improvement |
|--------|--------|-----|-------------|
| Container Size | ~500MB | ~50MB | **10x smaller** |
| Startup Time | ~3s | ~100ms | **30x faster** |
| Memory Usage | ~200MB | ~20MB | **10x less** |
| Security | Full OS | Distroless | **Hardened** |
#### New Features
- Team size validation (TEAM-007 compliance)
- Phase gate automation
- Agent team mapping
- Extended MCP tools (5 new tools)
- Hot-reloadable configuration
- Circuit breaker patterns
---
### v2.0.0
**Release Date:** 2026-02-15
#### Breaking Changes
1. **Team Configuration Schema v2**
- New required field: `team_version`
- Changed `members` from array to object structure
- Added `metadata` field for custom properties
2. **API Endpoint Changes**
- `/mcp/v1/message` - Now requires `session_id` parameter
- `/mcp/v1/sse` - Changed event format
3. **Environment Variables**
- `MCP_PORT` renamed to `MCP_SERVER_PORT`
- `WEB_PORT` renamed to `WEB_UI_PORT`
- New required: `TEAM_CONFIG_VERSION`
#### New Features
- Team size validation (TEAM-007 compliance)
- Phase gate automation
- Agent team mapping
- Extended MCP tools (5 new tools)
---
### v1.10.0
**Release Date:** 2026-02-08
#### Breaking Changes
None. This is a backward-compatible release.
#### New Features
- 5 new MCP tools (`guardrail_validate_scope`, etc.)
- 6 new MCP resources
- Web UI Management Interface
- Documentation search functionality
#### Migration Notes
- All changes are additive
- No configuration changes required
- New tools available immediately after upgrade
---
### v1.9.0
**Release Date:** 2026-02-07
#### Breaking Changes
1. **MCP Protocol Migration**
- Moved from custom protocol to standard MCP
- Port changed: 8094 (SSE), 8095 (message)
- Authentication now requires `Authorization` header
2. **Configuration Structure**
- `.teams/` directory location changed
- New required files: `.guardrails/rules.json`
3. **Tool Names**
- `validate_bash` renamed to `guardrail_validate_bash`
- `validate_git` renamed to `guardrail_validate_git_operation`
- `validate_file` renamed to `guardrail_validate_file_edit`
#### New Features
- Full MCP server implementation
- SSE transport support
- PostgreSQL and Redis backends
- Production deployment support
---
### v1.8.0 to v1.9.0
**Critical:** This is a major protocol change. Plan for downtime.
#### Breaking Changes
1. **Port Configuration**
- Old: Port 8094 (custom protocol)
- New: Port 8092 (MCP SSE), 8093 (Web UI)
2. **Client Configuration**
- Old: Direct HTTP calls
- New: MCP protocol with SSE
---
## Migration Procedures
### Pre-Migration Checklist
Before starting any migration:
```bash
# 1. Backup current state
./scripts/backup.sh --full
# 2. Verify backup integrity
./scripts/verify_backup.sh /backups/guardrails-$(date +%Y%m%d).tar.gz
# 3. Check current version
git describe --tags
# 4. Review breaking changes
cat docs/MIGRATION.md | grep -A 20 "v$(TARGET_VERSION)"
# 5. Test in staging environment
./scripts/test_migration.sh --version $TARGET_VERSION
```
---
### Migrating to v2.6.0 (Go Implementation)
**Go Migration:** The MCP server and team management have been migrated from Python to Go.
- **Benefits:** Smaller container size, distroless compatibility, improved security
- **API Compatibility:** Unchanged from MCP perspective
- **Location:** Go code is in `mcp-server/internal/`
**Estimated Time:** 30-45 minutes
**Downtime Required:** Yes (5-10 minutes)
#### Step 1: Pre-Migration (5 min)
```bash
# Stop the MCP server
pkill -f mcp_server || true
# Create full backup
mkdir -p backups/$(date +%Y%m%d)
cp -r .teams/ .guardrails/ backups/$(date +%Y%m%d)/
cp .env backups/$(date +%Y%m%d)/
# Export team configurations (Go binary)
cd mcp-server && go run ./cmd/tools/export_teams.go --format json > ../backups/$(date +%Y%m%d)/teams_export.json && cd ..
```
#### Step 2: Update Configuration (10 min)
```bash
# Update environment variables
# OLD:
# MCP_PORT=8094
# WEB_PORT=8093
# NEW:
cat >> .env << 'EOF'
# v2.6.0 Configuration (Go Implementation)
MCP_SERVER_PORT=8094
WEB_UI_PORT=8093
TEAM_CONFIG_VERSION=2
EOF
# Update team configuration schema (Go binary)
cd mcp-server && go run ./cmd/tools/migrate_config.go --from-version 1 --to-version 2 && cd ..
```
#### Step 3: Database Migration (10 min)
```bash
# Run database migrations (using golang-migrate)
cd mcp-server
export DATABASE_URL="postgresql://guardrails:password@localhost:5432/guardrails?sslmode=disable"
make migrate-up
# Verify migration
psql -U guardrails -d guardrails -c "\dt"
psql -U guardrails -d guardrails -c "SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;"
```
#### Step 4: Deploy New Version (5 min)
```bash
# Pull new version
git fetch origin
git checkout v2.6.0
# Build Go binary
cd mcp-server
go build -o bin/server ./cmd/server
cd ..
```
#### Step 5: Post-Migration (5 min)
```bash
# Start server
./start-mcp-server.sh
# Verify health
curl -s http://localhost:8094/mcp/v1/health | jq .
# Test team operations
curl -X POST http://localhost:8094/mcp/v1/message \
-d '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"guardrail_team_list","arguments":{"project_name":"test-project"}}}'
# Verify team size validation
curl -X POST http://localhost:8094/mcp/v1/message \
-d '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"guardrail_team_size_validate","arguments":{"project_name":"test-project"}}}'
```
#### Step 6: Update Client Configurations
**Claude Code:**
```json
// .claude/settings.json
{
"mcpServers": {
"guardrails": {
"url": "http://localhost:8094/mcp/v1/sse",
"headers": {
"Authorization": "Bearer YOUR_API_KEY"
}
}
}
}
```
**OpenCode:**
```jsonc
// .opencode/oh-my-opencode.jsonc
{
"mcp": {
"servers": [
{
"name": "guardrails",
"url": "http://localhost:8094/mcp/v1/sse",
"apiKey": "YOUR_API_KEY"
}
]
}
}
```
---
### Migrating to v1.10.0
**Estimated Time:** 15-20 minutes
**Downtime Required:** Minimal (rolling update possible)
#### Step 1: Backup
```bash
cp -r .teams/ .teams-backup-$(date +%Y%m%d)/
cp .env .env.backup-$(date +%Y%m%d)
```
#### Step 2: Update Code
```bash
git fetch origin
git checkout v1.10.0
pip install -r requirements.txt
cd mcp-server && go build ./cmd/server && cd ..
```
#### Step 3: Restart Server
```bash
# Rolling restart (no downtime)
pkill -HUP -f mcp_server
# Or full restart
pkill -f mcp_server
./mcp-server/cmd/server/server
```
#### Step 4: Verify New Features
```bash
# Access Web UI
open http://localhost:8080/web
# Test new tools
curl -X POST http://localhost:8092/mcp/v1/message \
-d '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"guardrail_validate_scope","arguments":{"path":"src/main.py","allowed_paths":["src/","tests/"]}}}'
```
---
### Migrating to v1.9.0
**Estimated Time:** 45-60 minutes
**Downtime Required:** Yes (protocol change)
#### Step 1: Full Backup
```bash
./scripts/full_backup.sh --output backups/pre-mcp-migration/
```
#### Step 2: Prepare New Infrastructure
```bash
# Setup PostgreSQL and Redis
# See deployment guide in RELEASE_v1.9.0.md
# Create new environment file
cat > .env.v1.9.0 << 'EOF'
MCP_API_KEY=<generate with: openssl rand -hex 32>
IDE_API_KEY=<generate with: openssl rand -hex 32>
JWT_SECRET=<generate with: openssl rand -hex 48>
DB_HOST=postgres
DB_PORT=5432
DB_NAME=guardrails
DB_USER=guardrails
DB_PASSWORD=<secure password>
DB_SSLMODE=disable
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=<secure password>
REDIS_USE_TLS=false
MCP_PORT=8080
WEB_PORT=8081
WEB_ENABLED=true
LOG_LEVEL=info
REQUEST_TIMEOUT=30s
EOF
```
#### Step 3: Deploy New Server
```bash
# Build container
cd mcp-server
docker build -t guardrail-mcp:v1.9.0 -f deploy/Dockerfile .
# Deploy
docker-compose -f deploy/docker-compose.yml up -d
```
#### Step 4: Migrate Data
```bash
# Export from old format
python scripts/export_v1.8.py > migration_data.json
# Import to new format
python scripts/import_v1.9.py --input migration_data.json
```
#### Step 5: Update Clients
Update all client configurations to use new MCP endpoints:
- Old: `http://localhost:8094`
- New: `http://localhost:8092/mcp/v1/sse`
---
## Rollback Procedures
### Automatic Rollback Triggers
The system will automatically rollback if:
1. Health checks fail for 5 consecutive attempts
2. Database migration checksums don't match
3. Team configuration validation fails
### Manual Rollback
#### Rollback from v2.6.0 to v2.0.0
```bash
#!/bin/bash
# rollback_to_v2.0.0.sh
set -e
echo "Starting rollback to v2.0.0..."
# 1. Stop current server
pkill -f mcp_server || true
# 2. Restore configuration from backup
BACKUP_DIR="backups/$(ls -t backups/ | head -1)"
cp "$BACKUP_DIR/.env" .env
# 3. Restore team configurations
cp -r "$BACKUP_DIR/.teams/" .
cp -r "$BACKUP_DIR/.guardrails/" .
# 4. Checkout previous version
git checkout v2.0.0
# 5. Rebuild Go binary
cd mcp-server
go build -o bin/server ./cmd/server
cd ..
# 6. Start server
./mcp-server/bin/server &
# 7. Verify
echo "Waiting for server..."
sleep 5
curl -s http://localhost:8094/mcp/v1/health && echo "Rollback successful!"
```
#### Rollback Database
```bash
# Rollback one migration (golang-migrate)
cd mcp-server
make migrate-down
# Or restore from backup
createdb guardrails_backup
gunzip < backups/postgres-$(date +%Y%m%d).sql.gz | psql guardrails_backup
```
#### Emergency Rollback
If the system is completely broken:
```bash
#!/bin/bash
# emergency_rollback.sh
echo "EMERGENCY ROLLBACK INITIATED"
# Stop everything
pkill -9 -f mcp_server || true
docker-compose down || true
# Restore from latest backup
LATEST_BACKUP=$(ls -td backups/*/ | head -1)
echo "Restoring from: $LATEST_BACKUP"
# Restore files
cp -r "$LATEST_BACKUP/." .
# Checkout last known good version (Go implementation)
git checkout v2.0.0
# Rebuild and start
cd mcp-server
go build -o bin/server ./cmd/server
cd ..
nohup ./mcp-server/bin/server > mcp.log 2>&1 &
echo "Emergency rollback complete"
echo "Check logs: tail -f mcp.log"
```
---
## Migration Examples
### Example 1: Single Project Migration
```bash
# Migrate single project from v1.9.0 to v2.0.0
PROJECT_NAME="my-web-app"
# Step 1: Export project config
python scripts/export_project.py "$PROJECT_NAME" > "$PROJECT_NAME-v1.9.json"
# Step 2: Transform to v2.0.0 format
python scripts/transform_team_config.py \
--input "$PROJECT_NAME-v1.9.json" \
--from-version 1.9 \
--to-version 2.0 \
--output "$PROJECT_NAME-v2.0.json"
# Step 3: Validate new format
python scripts/validate_team_config.py "$PROJECT_NAME-v2.0.json"
# Step 4: Import to v2.0.0
python scripts/import_project.py "$PROJECT_NAME-v2.0.json"
# Step 5: Verify
./scripts/verify_project.sh "$PROJECT_NAME"
```
### Example 2: Batch Migration Script
```bash
#!/bin/bash
# migrate_all_projects.sh
set -e
FROM_VERSION="1.9.0"
TO_VERSION="2.0.0"
FAILED_LOG="migration_failed_$(date +%Y%m%d).log"
SUCCESS_COUNT=0
FAIL_COUNT=0
echo "Starting batch migration from $FROM_VERSION to $TO_VERSION"
# Get all projects
PROJECTS=$(ls .teams/*.json | xargs -n1 basename | sed 's/.json$//')
for PROJECT in $PROJECTS; do
echo "Migrating $PROJECT..."
if python scripts/migrate_project.py \
--project "$PROJECT" \
--from-version "$FROM_VERSION" \
--to-version "$TO_VERSION" \
--backup; then
echo " SUCCESS: $PROJECT"
((SUCCESS_COUNT++))
else
echo " FAILED: $PROJECT"
echo "$PROJECT" >> "$FAILED_LOG"
((FAIL_COUNT++))
fi
done
echo ""
echo "Migration Summary:"
echo " Successful: $SUCCESS_COUNT"
echo " Failed: $FAIL_COUNT"
if [ $FAIL_COUNT -gt 0 ]; then
echo "Failed projects logged to: $FAILED_LOG"
exit 1
fi
```
### Example 3: Zero-Downtime Migration
For v1.10.0 (no breaking changes):
```bash
#!/bin/bash
# zero_downtime_migration.sh
# Start new version on different port
MCP_PORT=8096 WEB_PORT=8097 ./mcp-server/cmd/server/server &
NEW_PID=$!
# Wait for health check
for i in {1..30}; do
if curl -s http://localhost:8096/mcp/v1/health; then
echo "New server ready"
break
fi
sleep 1
done
# Switch load balancer to new port
sudo sed -i 's/8094/8096/g' /etc/nginx/conf.d/mcp.conf
sudo nginx -s reload
# Stop old server
pkill -f "mcp_server.*8094"
# Update to use standard port
kill $NEW_PID
MCP_PORT=8094 ./mcp-server/cmd/server/server &
sudo sed -i 's/8096/8094/g' /etc/nginx/conf.d/mcp.conf
sudo nginx -s reload
echo "Zero-downtime migration complete"
```
---
## Troubleshooting Migrations
### Common Migration Issues
#### Issue: "Team configuration version mismatch"
**Cause:** Migration script didn't update all config files
**Solution:**
```bash
# Force version update (Go binary)
cd mcp-server
go run ./cmd/tools/update_config.go --version 2.0
# Re-run migration
go run ./cmd/tools/migrate_config.go --from-version 1 --to-version 2 --force
```
#### Issue: "Database migration failed"
**Cause:** Partial migration or checksum mismatch
**Solution:**
```bash
# Check migration status
cd mcp-server
make migrate-status
# Fix by marking as applied
migrate -path internal/database/migrations -database "$DATABASE_URL" force 20260215000001
# Or rollback and retry
make migrate-down
make migrate-up
```
#### Issue: "Port already in use"
**Cause:** Old server still running
**Solution:**
```bash
# Find and kill old process
lsof -ti:8094 | xargs kill -9
# Or use different port temporarily
MCP_PORT=8096 ./mcp-server/cmd/server/server
```
#### Issue: "Client connection refused"
**Cause:** Client configured for old endpoint
**Solution:**
```bash
# Update client configuration
./scripts/update_client_configs.sh --new-port 8094 --new-path /mcp/v1/sse
# Verify connectivity
curl -H "Authorization: Bearer $API_KEY" \
http://localhost:8094/mcp/v1/health
```
### Migration Verification
```bash
#!/bin/bash
# verify_migration.sh
echo "Verifying migration..."
# Check server health
echo -n "Health check: "
curl -sf http://localhost:8094/mcp/v1/health && echo "PASS" || echo "FAIL"
# Check version
echo -n "Version check: "
git describe --tags | grep -q "v2.0" && echo "PASS" || echo "FAIL"
# Check database
echo -n "Database check: "
psql -U guardrails -c "SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;" | grep -q "20260215" && echo "PASS" || echo "FAIL"
# Check team configs
echo -n "Team config check: "
python scripts/validate_all_configs.py && echo "PASS" || echo "FAIL"
# Test basic operation
echo -n "Operation check: "
curl -s -X POST http://localhost:8094/mcp/v1/message \
-d '{"jsonrpc":"2.0","method":"tools/list"}' | grep -q "guardrail_team" && echo "PASS" || echo "FAIL"
echo "Verification complete"
```
---
**Last Updated:** 2026-02-15
**Version:** 1.0

View File

@ -0,0 +1,284 @@
# OpenCode Integration
This guide explains how to integrate Agent Guardrails with OpenCode using agents, skills, and hooks.
## Overview
OpenCode supports:
- **Agents** - JSON configurations that define specialized agent behaviors, model selection, and permissions
- **Skills** - Markdown files with structured tool definitions and instructions
- **Hooks** - Shell scripts that run at specific lifecycle points
The setup script installs these configurations for you.
## Setup
### 1. Install All Configs
```bash
python scripts/setup_agents.py --install --platform opencode
```
This creates:
```
.opencode/
├── oh-my-opencode.jsonc
├── agents/
│ ├── guardrails-enforcer.json
│ ├── guardrails-auditor.json
│ └── doc-indexer.json
├── skills/
│ ├── guardrails-enforcer.md
│ ├── commit-validator.md
│ ├── env-separator.md
│ ├── scope-validator.md
│ ├── production-first.md
│ ├── three-strikes.md
│ └── error-recovery.md
└── hooks/
├── pre-execution.sh
├── post-execution.sh
└── pre-commit.sh
```
### 2. Verify Installation
Check that agents are loaded:
```bash
ls -la .opencode/agents/
```
Check that skills are loaded:
```bash
ls -la .opencode/skills/
```
Check that hooks are executable:
```bash
ls -la .opencode/hooks/
```
Validate the main config:
```bash
python -m json.tool .opencode/oh-my-opencode.jsonc
```
## Agent JSON Format
Agents are defined in `oh-my-opencode.jsonc` (JSON with comments). Each agent has four fields:
| Field | Type | Description |
|-------|------|-------------|
| `model` | string | Model identifier (e.g., `anthropic/claude-sonnet-4`) |
| `temperature` | number | Sampling temperature (0.0 = deterministic, 1.0 = creative) |
| `prompt_append` | string | Instructions appended to the agent's system prompt |
| `permissions` | object | Tool permissions (`allow`, `ask`, `deny`) |
### Example: oh-my-opencode.jsonc
```jsonc
{
"$schema": "https://raw.githubusercontent.com/code-yeongyu/oh-my-opencode/master/assets/oh-my-opencode.schema.json",
"agents": {
"guardrails-enforcer": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "You are the Guardrails Enforcement Agent. Before ANY operation verify: 1) File has been read, 2) Scope is authorized, 3) Rollback is known, 4) No forbidden patterns. HALT and ask if uncertain.",
"permissions": {
"edit": "ask",
"bash": "ask",
"webfetch": "allow",
"read": "allow"
}
},
"guardrails-auditor": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "You are a Guardrails Auditor. Review completed work for compliance...",
"permissions": {
"edit": "deny",
"bash": "deny",
"read": "allow"
}
}
},
"skills": {
"sources": [
{"path": "./.opencode/skills", "recursive": true}
],
"enable": [
"guardrails-enforcer",
"commit-validator",
"env-separator"
]
}
}
```
### Permission Levels
| Level | Behavior |
|-------|----------|
| `allow` | Always permitted without prompting |
| `ask` | Prompt the user before executing |
| `deny` | Never permitted |
## Skill Markdown Format
Skills are markdown files in `.opencode/skills/` with structured sections:
```markdown
# Guardrails Enforcer
## Description
Enforces the Four Laws of Agent Safety
## Tools
- Read
- Grep
- Glob
## Instructions
You MUST enforce these rules:
1. Read before editing
2. Stay in scope
3. Verify before committing
4. Halt when uncertain
```
Sections are parsed as follows:
- **Description** - One-line summary of the skill
- **Tools** - Allowed tools for this skill
- **Instructions** - Detailed prompt injected into context
## Hook Details
Hooks are shell scripts that run automatically:
| Hook | When It Runs | Purpose |
|------|--------------|---------|
| `pre-execution.sh` | Before file modifications | Verify read-before-edit |
| `post-execution.sh` | After file modifications | Validate changes |
| `pre-commit.sh` | Before git commit | Validate commit message |
### Custom Hook Example
```bash
#!/bin/bash
# .opencode/hooks/pre-commit.sh
# Run linter
npm run lint
# Run tests
npm test
# Check for secrets
trufflehog git file://. --since-commit HEAD
```
## Shared Prompts Reference
All agent prompts and skill instructions incorporate rules from the shared prompts directory:
| Shared Prompt | Used By |
|---------------|---------|
| `skills/shared-prompts/four-laws.md` | guardrails-enforcer agent/skill |
| `skills/shared-prompts/halt-conditions.md` | guardrails-enforcer agent/skill |
| `skills/shared-prompts/three-strikes.md` | three-strikes skill |
| `skills/shared-prompts/production-first.md` | production-first skill |
| `skills/shared-prompts/clean-architecture.md` | guardrails-enforcer agent |
| `skills/shared-prompts/cqrs.md` | guardrails-enforcer agent |
| `skills/shared-prompts/scope-validation.md` | scope-validator skill |
| `skills/shared-prompts/error-recovery.md` | error-recovery skill |
When shared prompts are updated, re-run the setup script:
```bash
python scripts/setup_agents.py --install --platform opencode
```
## Customization
### Adding a Custom Agent
1. Add an entry to the `agents` object in `oh-my-opencode.jsonc`:
```jsonc
{
"agents": {
"my-agent": {
"model": "anthropic/claude-haiku-4",
"temperature": 0.0,
"prompt_append": "Your instructions here...",
"permissions": {
"edit": "ask",
"bash": "deny",
"read": "allow"
}
}
}
}
```
2. Create a corresponding skill in `.opencode/skills/my-agent.md`.
3. Add the skill name to the `skills.enable` array.
### Disabling an Agent
1. Remove it from the `agents` object in `oh-my-opencode.jsonc`.
2. Remove its skill from the `skills.enable` array.
3. Optionally move agent/skill files to a `disabled/` subdirectory.
### Cloning a Single Skill
```bash
python scripts/setup_agents.py --install-skill guardrails-enforcer --platform opencode
```
## Installation Modes
| Mode | Command | Behavior |
|------|---------|----------|
| Copy | `--mode copy` (default) | Writes standalone copies to the project |
| Symlink | `--mode symlink` | Creates symlinks back to this repo |
## Troubleshooting
### Agents Not Loading
- JSON syntax: `python -m json.tool .opencode/oh-my-opencode.jsonc`
- Agent entries exist in the `agents` object
- `oh-my-opencode.jsonc` is in `.opencode/` directory
### Skills Not Loading
- Markdown files have proper `## Description`, `## Tools`, `## Instructions` sections
- Files are in `.opencode/skills/` directory
- Skill names appear in `skills.enable` array
### Hooks Not Running
- Check executable bit: `chmod +x .opencode/hooks/*.sh`
- Validate shell syntax: `bash -n .opencode/hooks/pre-execution.sh`
- Hook names match expected patterns in config
### Permission Denied
```bash
chmod +x .opencode/hooks/*.sh
```
## Best Practices
1. **One agent = one responsibility** - Keep agents focused and composable
2. **Use low temperature for guardrails** - Deterministic enforcement (0.0-0.1)
3. **Test hooks manually** - Run scripts directly to verify behavior
4. **Regenerate after shared prompt updates** - Re-run setup to sync
5. **Commit `.opencode/` to version control** - Team shares the same guardrails
## References
- [AGENTS_AND_SKILLS_SETUP.md](AGENTS_AND_SKILLS_SETUP.md) - Unified setup guide
- [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) - Core safety protocols
- [skills/shared-prompts/](../skills/shared-prompts/) - Canonical prompt definitions

View File

@ -0,0 +1,412 @@
# OpenCode Integration
This guide explains how to integrate Agent Guardrails with OpenCode using custom agents and skills.
## Overview
OpenCode uses a multi-agent architecture with:
- **Configuration** - JSONC file (`.opencode/oh-my-opencode.jsonc`)
- **Agents** - Specialized workers for different tasks
- **Skills** - Markdown files with YAML frontmatter
- **MCP Servers** - Remote Model Context Protocol servers for guardrail enforcement
## MCP Server Configuration
### Remote MCP Server Setup
If you have a deployed Guardrail MCP server (see [README.md](../README.md) MCP Server section), configure OpenCode to connect to it:
```jsonc
{
"$schema": "https://raw.githubusercontent.com/code-yeongyu/oh-my-opencode/master/assets/oh-my-opencode.schema.json",
"mcpServers": {
"guardrails": {
"type": "remote",
"url": "http://your-server-ip:8094/mcp/v1/sse",
"headers": {
"Authorization": "Bearer YOUR_MCP_API_KEY"
}
}
}
}
```
**Configuration Details:**
| Field | Description | Example |
|-------|-------------|---------|
| `type` | Must be `"remote"` for external MCP servers | `"remote"` |
| `url` | SSE endpoint URL with external port | `http://0.0.0.0:8094/mcp/v1/sse` |
| `headers.Authorization` | Bearer token with MCP_API_KEY | `Bearer JGtwbxsS2Nvy...` |
**Important Notes:**
- Use the **external port** (e.g., 8094), not the internal container port (8080)
- The `Authorization` header must use `Bearer` format
- Do NOT use `X-API-Key` header - it won't work
- Get the API key from your server's `.env` file (MCP_API_KEY variable)
### Verifying MCP Connection
Test that OpenCode can connect to the MCP server:
```bash
# Check MCP server health
curl http://your-server:8095/health/ready
# Should return: {"status":"ready",...}
# Check version
curl http://your-server:8095/version
# Should return: {"version":"v1.12.0",...}
```
## Setup
### 1. Run Setup Script
```bash
python scripts/setup_agents.py --opencode --full
```
This creates:
```
.opencode/
├── oh-my-opencode.jsonc
├── skills/
│ ├── guardrails-enforcer/
│ │ └── SKILL.md
│ ├── commit-validator/
│ │ └── SKILL.md
│ └── env-separator/
│ └── SKILL.md
└── agents/
├── guardrails-auditor.json
└── doc-indexer.json
```
### 2. Verify Installation
Check the configuration:
```bash
cat .opencode/oh-my-opencode.jsonc
```
Check that skills exist:
```bash
ls -la .opencode/skills/*/
```
### 3. Restart OpenCode
OpenCode loads configuration on startup. Restart to apply changes.
## Configuration Format
OpenCode uses **JSONC** (JSON with Comments):
```jsonc
{
"$schema": "https://raw.githubusercontent.com/code-yeongyu/oh-my-opencode/master/assets/oh-my-opencode.schema.json",
// Agent definitions
"agents": {
"guardrails-enforcer": {
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "Additional instructions..."
}
},
// Skill configuration
"skills": {
"enable": ["guardrails-enforcer", "commit-validator"]
}
}
```
## How It Works
### Agents
Agents are specialized workers with:
- `model` - Which LLM to use
- `temperature` - Creativity vs determinism (0.0-1.0)
- `prompt_append` - Additional system instructions
- `permissions` - Access controls
### Skills
Skills are Markdown files with YAML frontmatter:
```markdown
---
name: skill-name
description: "What this skill does"
---
# Skill Title
Instructions here...
```
### Categories
OpenCode uses cost-based categories:
| Category | Cost | Use For |
|----------|------|---------|
| `quick` | $ | Fast queries, greps |
| `unspecified-low` | $$ | Standard operations |
| `unspecified-high` | $$$ | Complex analysis |
| `visual-engineering` | $$$ | UI/UX work |
## Included Agents
### guardrails-enforcer
**Purpose:** Real-time enforcement of safety rules
**Configuration:**
- Model: `claude-sonnet-4`
- Temperature: 0.1 (deterministic)
- Permissions: Ask before edit/bash
**Behavior:**
- Validates read-before-edit
- Enforces scope boundaries
- Checks for halt conditions
### guardrails-auditor
**Purpose:** Post-execution compliance review
**Configuration:**
- Model: `claude-sonnet-4`
- Read-only permissions
- No edit or bash access
**Behavior:**
- Reviews completed work
- Reports violations
- Suggests corrections
### doc-indexer
**Purpose:** Keeps documentation maps updated
**Configuration:**
- Model: `claude-haiku-4` (fast, cheap)
- Edit permissions for docs only
**Behavior:**
- Updates INDEX_MAP.md
- Updates HEADER_MAP.md
- Runs on document changes
## Included Skills
### guardrails-enforcer
**Activates:** All operations
**Enforces:**
- Four Laws of Agent Safety
- Pre-operation checklist
- Halt conditions
- Three Strikes Rule
### commit-validator
**Activates:** Before commits
**Validates:**
- AI attribution
- Single focus
- No secrets
- Tests passing
### env-separator
**Activates:** Test code creation
**Enforces:**
- Production code first
- Separate instances
- No data mixing
## Customization
### Adding a Custom Agent
1. Create a JSON file in `.opencode/agents/`:
```json
{
"name": "my-agent",
"model": "anthropic/claude-sonnet-4",
"temperature": 0.1,
"prompt_append": "Your instructions...",
"permissions": {
"edit": "ask",
"bash": "deny",
"read": "allow"
}
}
```
2. Reference it in `oh-my-opencode.jsonc`:
```jsonc
{
"agents": {
"my-agent": {
"model": "anthropic/claude-sonnet-4",
// ...
}
}
}
```
3. Restart OpenCode
### Adding a Custom Skill
1. Create a directory in `.opencode/skills/`:
```bash
mkdir .opencode/skills/my-skill
```
2. Create `SKILL.md`:
```markdown
---
name: my-skill
description: "What this skill does"
---
# My Skill
Instructions here...
```
3. Enable in `oh-my-opencode.jsonc`:
```jsonc
{
"skills": {
"enable": ["guardrails-enforcer", "my-skill"]
}
}
```
4. Restart OpenCode
## Advanced Configuration
### Category Overrides
Change which models categories use:
```jsonc
{
"categories": {
"quick": {
"model": "opencode/gpt-5-nano"
},
"visual-engineering": {
"model": "google/gemini-3-pro"
}
}
}
```
### Permission Tuning
Fine-grain agent permissions:
```jsonc
{
"agents": {
"explore": {
"permission": {
"edit": "deny",
"bash": "ask",
"webfetch": "allow"
}
}
}
}
```
Options: `allow`, `ask`, `deny`
### Model Parameters
Advanced model configuration:
```jsonc
{
"agents": {
"my-agent": {
"model": "anthropic/claude-opus-4",
"temperature": 0.1,
"top_p": 0.9,
"maxTokens": 4096,
"thinking": {
"budget_tokens": 2000
}
}
}
}
```
## Troubleshooting
### Configuration Not Loading
**Check:**
- JSONC syntax is valid (use a JSONC validator)
- `$schema` URL is correct
- File is at `.opencode/oh-my-opencode.jsonc`
### Skills Not Activating
**Check:**
- Skill is listed in `skills.enable` array
- SKILL.md has valid YAML frontmatter
- Skill directory name matches skill name
### Agent Not Responding
**Check:**
- Agent defined in `agents` section
- Model identifier is valid
- Permissions allow the operation
## Best Practices
1. **Use temperature 0.1 for safety agents** - More deterministic
2. **Enable skills explicitly** - Don't rely on auto-discovery
3. **Set restrictive permissions** - Default to `ask` for destructive ops
4. **Version control** - Commit `.opencode/` to share with team
5. **Document custom agents** - Add purpose and usage notes
## Differences from Claude Code
| Feature | Claude Code | OpenCode |
|---------|-------------|----------|
| Config format | JSON | JSONC |
| Skills location | `.claude/skills/*.json` | `.opencode/skills/*/SKILL.md` |
| Agents | Implicit | Explicit definition |
| Hooks | Shell scripts | Not supported |
| Categories | N/A | Cost-based routing |
## References
- [OpenCode Documentation](https://github.com/code-yeongyu/opencode)
- [Oh My OpenCode Schema](https://raw.githubusercontent.com/code-yeongyu/oh-my-opencode/master/assets/oh-my-opencode.schema.json)
- [AGENT_GUARDRAILS.md](AGENT_GUARDRAILS.md) - Core safety protocols
- [AGENTS_AND_SKILLS_SETUP.md](AGENTS_AND_SKILLS_SETUP.md) - General setup guide

View File

@ -0,0 +1,364 @@
# Python to Go Migration Guide
> Complete guide for the Python to Go migration completed in v2.6.0
**Version:** 2.6.0
**Last Updated:** 2026-02-15
---
## Table of Contents
1. [Why We Migrated](#why-we-migrated)
2. [What's Different](#whats-different)
3. [API Compatibility](#api-compatibility)
4. [How to Contribute](#how-to-contribute)
5. [Migration FAQ](#migration-faq)
---
## Why We Migrated
### Security
The migration to Go enables significant security improvements:
- **Distroless Containers**: Go compiles to a single static binary, allowing us to use distroless container images
- No shell access
- No package manager
- Minimal attack surface
- Non-root execution with dropped capabilities
- **Memory Safety**: Go's memory management prevents common vulnerabilities found in Python
- No buffer overflows
- Type safety at compile time
- No interpreter vulnerabilities
### Container Size
| Metric | Python | Go | Improvement |
|--------|--------|-----|-------------|
| Container Size | ~500MB | ~50MB | **10x smaller** |
| Layers | Multiple | Single | Simpler |
| Attack Surface | Large | Minimal | **Hardened** |
### Performance
| Metric | Python | Go | Improvement |
|--------|--------|-----|-------------|
| Startup Time | ~3 seconds | ~100ms | **30x faster** |
| Memory Usage | ~200MB | ~20MB | **10x less** |
| Concurrency | GIL-limited | Native goroutines | **Unlimited** |
| Cold Start | Slow | Fast | **Better scaling** |
### Deployment Compatibility
Go enables deployment in restricted environments:
- **Distroless**: Google's hardened container images
- **Scratch**: Truly minimal containers
- **Read-only filesystems**: No runtime writes needed
- **Locked-down environments**: No interpreter needed
---
## What's Different
### Code Location
```
# Before (Python)
scripts/
├── team_manager.py # Team management logic
├── export_teams.py # Data export
└── migrate_config.py # Configuration migration
# After (Go)
mcp-server/internal/
├── team/
│ ├── manager.go # Team management
│ ├── types.go # Data structures
│ ├── encryption.go # Encryption at rest
│ ├── validation.go # Input validation
│ ├── rules.go # Layout rules
│ └── metrics.go # Operation metrics
├── database/
│ └── migrations/ # golang-migrate files
└── cmd/tools/ # CLI utilities
```
### Dependencies
```bash
# Before (Python)
pip install -r requirements.txt
# 20+ dependencies
# Virtual environments
# Version conflicts
# After (Go)
go mod download
# Compiled into single binary
# No runtime dependencies
# Static linking
```
### Build Process
```bash
# Before (Python)
# No build step required
python scripts/team_manager.py
# After (Go)
# Compile to binary
cd mcp-server
go build -o bin/server ./cmd/server
./bin/server
```
### Database Migrations
```bash
# Before (Python)
python scripts/migrate_db.py --version 2.0.0
# After (Go)
# Using golang-migrate
cd mcp-server
export DATABASE_URL="postgresql://..."
make migrate-up
```
---
## API Compatibility
### MCP Tools
**Fully Compatible:** All MCP tools work identically.
| Tool | Status | Notes |
|------|--------|-------|
| `guardrail_team_init` | ✅ Unchanged | Go implementation, same API |
| `guardrail_team_list` | ✅ Unchanged | Go implementation, same API |
| `guardrail_team_assign` | ✅ Unchanged | Go implementation, same API |
| `guardrail_team_status` | ✅ Unchanged | Go implementation, same API |
| `guardrail_phase_gate_check` | ✅ Unchanged | Go implementation, same API |
### Data Format
Team configuration files (`.teams/*.json`) remain unchanged:
```json
{
"version": "2.0",
"project": "example",
"teams": {
"team-1": {
"name": "Core Feature Squad",
"phase": 3,
"members": {
"lead": "alice",
"developers": ["bob", "charlie"]
}
}
}
}
```
### REST API
All REST endpoints remain compatible:
- `GET /api/teams`
- `POST /api/teams`
- `GET /api/teams/:id`
- `PUT /api/teams/:id`
- `DELETE /api/teams/:id`
---
## How to Contribute
### Development Setup
```bash
# Clone the repository
git clone https://github.com/TheArchitectit/agent-guardrails-template.git
cd agent-guardrails-template/mcp-server
# Install Go dependencies
make deps
# Run tests
make test
# Build the server
make build
```
### Go Development Workflow
```bash
# Format code
make fmt
# Run linter
make lint
# Run tests
make test
# Check for vulnerabilities
make vuln
# Full check
make check
```
### Writing Go Code
Follow these conventions:
1. **Package names**: Short, lowercase (e.g., `team`, `rules`)
2. **Exported names**: PascalCase
3. **Unexported names**: camelCase
4. **Error handling**: Always check, wrap with context
```go
// Example: Team assignment
type Manager struct {
db *database.Store
cache cache.Cache
}
func (m *Manager) AssignRole(
ctx context.Context,
project, team, role, person string,
) error {
// Validate input
if err := validate.Role(role); err != nil {
return fmt.Errorf("invalid role: %w", err)
}
// Check team capacity
count, err := m.db.CountMembers(ctx, project, team)
if err != nil {
return fmt.Errorf("failed to count members: %w", err)
}
if count >= maxTeamSize {
return ErrTeamFull
}
// Perform assignment
if err := m.db.AssignRole(ctx, project, team, role, person); err != nil {
return fmt.Errorf("failed to assign role: %w", err)
}
return nil
}
```
### Testing
```go
func TestManager_AssignRole(t *testing.T) {
tests := []struct {
name string
project string
team string
role string
person string
wantErr error
}{
// Test cases
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := NewManager(mockDB, mockCache)
err := m.AssignRole(context.Background(),
tt.project, tt.team, tt.role, tt.person)
if !errors.Is(err, tt.wantErr) {
t.Errorf("AssignRole() error = %v, wantErr %v",
err, tt.wantErr)
}
})
}
}
```
---
## Migration FAQ
### Q: Do I need to learn Go to use the MCP server?
**A:** No. The MCP server is a black box from the client perspective. All interactions are through the MCP protocol or REST API.
### Q: Will my existing `.teams/*.json` files work?
**A:** Yes. The data format is unchanged. The Go implementation reads and writes the same JSON structure.
### Q: What happened to `scripts/team_manager.py`?
**A:** The functionality has been migrated to `mcp-server/internal/team/`. The Python script is deprecated and will be removed in v3.0.0.
### Q: Do I need to install Go to run the server?
**A:** No. You can use the pre-built Docker image which contains the compiled Go binary.
### Q: How do I build from source?
**A:**
```bash
cd mcp-server
go build -o bin/server ./cmd/server
./bin/server
```
### Q: Are there any breaking changes?
**A:** No breaking changes from the MCP client perspective. The API is fully compatible.
### Q: What's the performance impact?
**A:** Positive. The Go implementation is faster, uses less memory, and has faster startup times.
### Q: Can I still use Python for other things?
**A:** Yes. Only the team management and MCP server have migrated to Go. Other Python scripts in `scripts/` remain available.
### Q: How do I debug the Go server?
**A:**
```bash
# Build with debug symbols
go build -gcflags="-N -l" -o bin/server ./cmd/server
# Run with delve debugger
dlv exec ./bin/server
# Or enable debug logging
LOG_LEVEL=debug ./bin/server
```
### Q: What Go version is required?
**A:** Go 1.23 or later. See `go.mod` for exact requirements.
---
## References
- [CONTRIBUTING.md](CONTRIBUTING.md) - Development guidelines
- [ARCHITECTURE.md](ARCHITECTURE.md) - System architecture
- [MIGRATION.md](MIGRATION.md) - Version migration procedures
- [Go Documentation](https://golang.org/doc/)
- [Effective Go](https://golang.org/doc/effective_go.html)
---
**Last Updated:** 2026-02-15
**Version:** 2.6.0
**Implementation:** Go (mcp-server/internal/)

View File

@ -0,0 +1,379 @@
# Python to Go Migration Guide
> Complete guide for migrating from Python team_manager.py to Go team package
**Version:** 2.6.0
**Last Updated:** 2026-02-15
**Applies To:** MCP Server v2.6.0+
---
## Overview
As of version 2.6.0, the Agent Guardrails MCP Server has completed its migration from Python to Go. All team management functionality previously provided by `scripts/team_manager.py` is now implemented natively in Go within the `mcp-server/internal/team/` package.
### Key Changes
| Aspect | Before (Python) | After (Go) |
|--------|-----------------|------------|
| **Language** | Python 3.11+ | Go 1.23+ |
| **Entry Point** | `scripts/team_manager.py` | `mcp-server/internal/team/` package |
| **Container** | Required Python runtime | Native Go binary (distroless) |
| **Dependencies** | `cryptography`, `stdlib` | None (built-in) |
| **Performance** | Process spawn overhead | Native in-process calls |
---
## What Was Migrated
### Core Components
1. **Team Management** (`manager.go`)
- Team initialization, listing, assignment
- Phase status tracking
- Project lifecycle management
2. **Encryption** (`encryption.go`)
- Fernet-based encryption at rest
- Environment key derivation
- Transparent encrypt/decrypt
3. **Validation** (`validation.go`)
- Project name validation
- Role name whitelist checking
- Person name sanitization
4. **Rules Engine** (`rules.go`)
- Team layout rules loading
- Phase gate validation
- Agent-to-team mapping
5. **Metrics** (`metrics.go`)
- Team operation metrics
- Performance tracking
- Error categorization
6. **Types** (`types.go`)
- Team data structures
- Phase definitions
- Assignment records
7. **Migrations** (`migrations.go`)
- Data format migration
- Version compatibility
---
## Developer Migration Guide
### For Contributors
#### Before (Python)
```python
# scripts/team_manager.py
from scripts.team_manager import TeamManager
manager = TeamManager("my-project")
manager.init_project()
manager.assign_role(team_id=7, role="Technical Lead", person="Alice")
```
#### After (Go)
```go
// mcp-server/internal/team/manager.go
package main
import (
"context"
"github.com/thearchitectit/guardrail-mcp/internal/team"
)
func main() {
ctx := context.Background()
mgr, err := team.NewManager("my-project")
if err != nil {
panic(err)
}
err = mgr.InitProject(ctx)
if err != nil {
panic(err)
}
err = mgr.AssignRole(ctx, 7, "Technical Lead", "Alice")
if err != nil {
panic(err)
}
}
```
### API Changes
| Python (Old) | Go (New) | Notes |
|--------------|----------|-------|
| `TeamManager.init_project()` | `Manager.InitProject(ctx)` | Added context support |
| `TeamManager.list_teams()` | `Manager.ListTeams(ctx)` | Returns slice instead of dict |
| `TeamManager.assign_role()` | `Manager.AssignRole(ctx, teamID, role, person)` | Parameter order preserved |
| `TeamManager.unassign_role()` | `Manager.UnassignRole(ctx, teamID, role)` | - |
| `TeamManager.get_status()` | `Manager.GetStatus(ctx, phase)` | Phase is optional |
| `EncryptionManager.encrypt()` | `Encrypt(data, key)` | Standalone function |
| `EncryptionManager.decrypt()` | `Decrypt(data, key)` | Standalone function |
### Error Handling
Python exceptions are now Go errors:
```go
// Before (Python):
# try:
# manager.assign_role(...)
# except ValueError as e:
# print(f"Invalid: {e}")
// After (Go):
if err := mgr.AssignRole(ctx, 7, "Role", "Person"); err != nil {
var valErr *team.ValidationError
if errors.As(err, &valErr) {
log.Printf("Invalid: %v", valErr)
}
}
```
---
## Container Changes
### Before (Python Runtime Required)
```dockerfile
FROM gcr.io/distroless/python3-debian12
COPY scripts/ /app/scripts/
RUN pip install cryptography
CMD ["/server"]
```
### After (Pure Go)
```dockerfile
FROM gcr.io/distroless/static:nonroot
COPY server /server
ENTRYPOINT ["/server"]
```
**Benefits:**
- No Python runtime needed
- Smaller container size (~20MB vs ~80MB)
- No dependency management
- Faster startup time
- Reduced attack surface
---
## Deployment Migration
### Step 1: Update Docker Compose
Remove any Python-specific volumes or environment variables:
```yaml
# Before
services:
mcp-server:
volumes:
- ./scripts:/app/scripts:ro
environment:
- PYTHONPATH=/app
# After
services:
mcp-server:
# No scripts volume needed
environment:
- TEAM_ENCRYPTION_KEY=${TEAM_ENCRYPTION_KEY}
```
### Step 2: Environment Variables
| Variable | Status | Notes |
|----------|--------|-------|
| `TEAM_ENCRYPTION_KEY` | **Kept** | Still used by Go encryption |
| `PYTHONPATH` | **Removed** | No longer needed |
| `TEAM_MANAGER_SCRIPT` | **Removed** | Hardcoded in binary |
### Step 3: Data Migration
Team data stored in `.teams/` is compatible:
```bash
# No data migration needed - JSON format unchanged
ls .teams/
# my-project.json
# my-project.lock
```
---
## Testing Changes
### Before (Python Tests)
```python
# scripts/test_team_manager.py
import unittest
from scripts.team_manager import TeamManager
class TestTeamManager(unittest.TestCase):
def test_init_project(self):
mgr = TeamManager("test-project")
result = mgr.init_project()
self.assertTrue(result["success"])
```
### After (Go Tests)
```go
// mcp-server/internal/team/manager_test.go
package team
import (
"context"
"testing"
)
func TestManager_InitProject(t *testing.T) {
mgr, err := NewManager("test-project")
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := mgr.InitProject(ctx); err != nil {
t.Errorf("InitProject failed: %v", err)
}
}
```
---
## Troubleshooting
### Common Issues
#### Issue: "team_manager.py not found"
**Cause:** Old code references Python script
**Solution:** Update to use Go package:
```go
// Replace exec.Command("python", "team_manager.py", ...)
// With:
mgr, _ := team.NewManager(projectName)
result, err := mgr.ListTeams(ctx)
```
#### Issue: Encryption key not working
**Cause:** Key format expectations changed
**Solution:** Ensure key is 32 bytes (Fernet format):
```bash
# Generate compatible key
openssl rand -base64 32
```
#### Issue: Build failures
**Cause:** Missing Go modules
**Solution:**
```bash
cd mcp-server
go mod download
go build ./cmd/server
```
---
## Performance Improvements
| Metric | Python | Go | Improvement |
|--------|--------|-----|-------------|
| **Startup Time** | ~500ms (Python init) | ~50ms | **10x faster** |
| **Memory Usage** | ~40MB | ~15MB | **2.7x less** |
| **Team Operation** | ~100ms | ~5ms | **20x faster** |
| **Container Size** | ~80MB | ~20MB | **4x smaller** |
---
## Backward Compatibility
### MCP Tool API
**Fully Compatible:** All MCP tool names, parameters, and responses remain unchanged.
- `guardrail_team_init`
- `guardrail_team_list`
- `guardrail_team_assign`
- `guardrail_team_unassign`
- `guardrail_team_status`
- `guardrail_phase_gate_check`
- `guardrail_agent_team_map`
- `guardrail_team_size_validate`
### Data Format
**Fully Compatible:** JSON data in `.teams/` directory unchanged.
### Configuration
**Mostly Compatible:** Only Python-specific env vars removed.
---
## Contributing
### Code Organization
```
mcp-server/internal/team/
├── manager.go # Core team management
├── encryption.go # Encryption utilities
├── validation.go # Input validation
├── rules.go # Layout rules
├── metrics.go # Metrics collection
├── types.go # Data structures
└── migrations.go # Data migrations
```
### Testing
```bash
# Run all team tests
cd mcp-server
go test ./internal/team/...
# Run with coverage
go test -cover ./internal/team/...
# Run benchmarks
go test -bench=. ./internal/team/...
```
---
## References
- [Team Tools Reference](./TEAM_TOOLS.md) - Complete MCP tool documentation
- [TEAM_STRUCTURE.md](../ide/TEAM_STRUCTURE.md) - Team and role definitions
- [Go Package Documentation](../mcp-server/internal/team/) - Code-level docs
---
**Migration Status:** ✅ Complete as of v2.6.0
**Questions?** Open an issue on GitHub or refer to the troubleshooting section above.

View File

@ -0,0 +1,488 @@
# MCP Server Tester Guide (Container Deployment)
> This guide is for external testers validating the Guardrail MCP server stack on a deployment host.
**Release Target:** v1.9.6
**Branch:** `mcpserver`
**Status:** Testing in progress
---
## 1) Container Architecture (Current)
The deployment is a **3-container stack** with strict network separation:
```text
Deployment host
|
|-- guardrail-mcp-server (app)
| |-- container port 8080: MCP SSE + JSON-RPC message endpoint
| |-- container port 8081: Web UI + REST API + health + metrics
| |-- attached networks: frontend, backend
|
|-- guardrail-postgres (state)
| |-- container port 5432 (backend network only)
| |-- attached networks: backend
| |-- persistent volume: pg_data
|
|-- guardrail-redis (cache/rate limiting)
| |-- container port 6379 (backend network only)
| |-- attached networks: backend
| |-- persistent volume: redis_data
```
### Host exposure model
- MCP and Web ports are bound to **loopback only** via compose: `127.0.0.1:${MCP_PORT}:8080` and `127.0.0.1:${WEB_PORT}:8081`
- Postgres and Redis are **not** host-exposed
- Default host ports are `8080` and `8081`
- Some environments use `8092` and `8093` by setting env vars
### Security and runtime constraints
- App container runs as non-root `65532:65532`
- Root filesystem is read-only with `/tmp` mounted as tmpfs
- Linux capabilities dropped (`ALL`)
- `no-new-privileges:true` enabled
- `postgres` and `redis` health checks gate app startup
---
## 2) Pre-Flight Checks (Before Testing)
Run these from `mcp-server/`.
```bash
podman --version
podman-compose --version
```
If you are Docker-only (no Podman), use:
```bash
docker --version
docker compose version
```
Verify no local port conflict on your target host ports:
```bash
ss -ltnp | grep -E ":(8080|8081|8092|8093)"
```
If testing from your laptop against the deployment host, create an SSH tunnel first:
```bash
ssh -L 8092:127.0.0.1:8092 -L 8093:127.0.0.1:8093 <user>@<host>
```
Then use `http://localhost:8092` and `http://localhost:8093` locally.
---
## 3) Environment Setup
```bash
cd mcp-server
cp .env.example .env
```
Set at minimum:
- `MCP_API_KEY` (32+ chars, mixed case + digits)
- `IDE_API_KEY` (32+ chars, mixed case + digits)
- `JWT_SECRET` (32+ chars minimum; 64+ recommended)
- `DB_PASSWORD`
- `REDIS_PASSWORD`
- `MCP_PORT` / `WEB_PORT` (use custom ports like `8092` / `8093` if required)
Example secure generation:
```bash
openssl rand -hex 32 # MCP_API_KEY
openssl rand -hex 32 # IDE_API_KEY
openssl rand -hex 64 # JWT_SECRET
openssl rand -base64 32 # DB/Redis passwords
```
---
## 4) Start the Stack
### Option A: Build and run on target host
```bash
cd mcp-server
make docker-up
```
### Option B: Explicit compose command
```bash
cd mcp-server
podman-compose -f deploy/podman-compose.yml up -d --build
```
### Option C: Docker only (no Podman)
The Makefile targets use Podman tools. If you are Docker-only, run compose commands directly:
```bash
cd mcp-server
docker compose -f deploy/podman-compose.yml up -d --build
```
Tester-validated Docker variant (recommended when using Docker Desktop/Engine):
```bash
cd mcp-server
docker compose -f deploy/docker-compose.example.yml up -d --build
```
Check status:
```bash
podman-compose -f deploy/podman-compose.yml ps
podman ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
```
Docker equivalent:
```bash
docker compose -f deploy/podman-compose.yml ps
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
```
If started with the Docker example file, use:
```bash
docker compose -f deploy/docker-compose.example.yml ps
```
Expected containers:
- `guardrail-postgres` (healthy)
- `guardrail-redis` (healthy)
- `guardrail-mcp-server` (running)
---
## 5) Run Database Migrations (Required)
If migrations are skipped, many API operations fail even when containers look healthy.
Use this compose-safe method (works even when Postgres is not host-exposed):
```bash
cd mcp-server
set -a
source .env
set +a
for f in internal/database/migrations/*_up.sql; do
echo "Applying $f"
podman exec -i guardrail-postgres psql -U "$DB_USER" -d "$DB_NAME" < "$f"
done
```
Docker equivalent:
```bash
cd mcp-server
set -a
source .env
set +a
for f in internal/database/migrations/*_up.sql; do
echo "Applying $f"
docker exec -i guardrail-postgres psql -U "$DB_USER" -d "$DB_NAME" < "$f"
done
```
Optional (only if DB is directly reachable from host):
```bash
make migrate-up DATABASE_URL="postgresql://${DB_USER}:${DB_PASSWORD}@127.0.0.1:${DB_PORT}/${DB_NAME}?sslmode=disable"
```
---
## 6) Smoke Test Checklist
Define base URLs from your `.env`:
```bash
set -a
source .env
set +a
export MCP_BASE="http://localhost:${MCP_PORT}"
export WEB_BASE="http://localhost:${WEB_PORT}"
```
### 6.1 Web health and metrics
```bash
curl -s "$WEB_BASE/health/live"
curl -s "$WEB_BASE/health/ready"
curl -s "$WEB_BASE/version"
curl -s "$WEB_BASE/metrics" | head -n 5
```
Expected:
- `/health/live` -> `200`, `status: alive`
- `/health/ready` -> `200`, `status: ready`
- `/version` -> service/version JSON
- `/metrics` -> Prometheus text output
### 6.2 Public vs protected Web API behavior
Public (no API key expected):
```bash
curl -i "$WEB_BASE/api/documents"
curl -i "$WEB_BASE/api/rules"
```
Protected (no API key should fail):
```bash
curl -i -X POST "$WEB_BASE/api/rules" \
-H "Content-Type: application/json" \
-d '{"rule_id":"TEST-001","name":"x","pattern":"x","message":"x","severity":"warning","category":"test","enabled":true}'
```
Expected: `401 Unauthorized` without `Authorization: Bearer <MCP_API_KEY>`.
---
## 7) MCP Protocol Test Flow (Important)
This is where most tester confusion happens.
### Key behavior
- `GET /mcp/v1/sse` creates a session and sends an `endpoint` event
- The event data includes the required `session_id` in message URL
- `POST /mcp/v1/message?session_id=...` usually returns `202 Accepted` (no JSON body)
- The actual JSON-RPC response is delivered on the SSE stream as `event: message`
### Step-by-step (2 terminals)
Terminal A - keep SSE open:
```bash
curl -N "$MCP_BASE/mcp/v1/sse"
```
You should see something like:
```text
event: endpoint
data: http://localhost:<MCP_PORT>/mcp/v1/message?session_id=sess_abc123...
: ping
```
Copy the full `message?session_id=...` URL.
Terminal B - send initialize request to that URL:
```bash
curl -i -X POST "$MCP_BASE/mcp/v1/message?session_id=<session_id>" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {
"name": "test-client",
"version": "1.0"
}
}
}'
```
Expected:
- HTTP status from POST: `202 Accepted`
- Terminal A receives `event: message` with JSON-RPC result payload
### Tool call example
```bash
curl -i -X POST "$MCP_BASE/mcp/v1/message?session_id=<session_id>" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "guardrail_validate_git_operation",
"arguments": {
"command": "push",
"is_force": true
}
}
}'
```
Expected `event: message` payload includes a violation for force push.
---
## 8) Container Security Verification
```bash
podman inspect guardrail-mcp-server --format '{{.Config.User}}'
podman inspect guardrail-mcp-server --format '{{.HostConfig.ReadonlyRootfs}}'
podman inspect guardrail-mcp-server --format '{{json .HostConfig.CapDrop}}'
podman inspect guardrail-mcp-server --format '{{json .HostConfig.SecurityOpt}}'
podman inspect guardrail-mcp-server --format '{{json .HostConfig.Tmpfs}}'
```
Docker equivalent:
```bash
docker inspect guardrail-mcp-server --format '{{.Config.User}}'
docker inspect guardrail-mcp-server --format '{{.HostConfig.ReadonlyRootfs}}'
docker inspect guardrail-mcp-server --format '{{json .HostConfig.CapDrop}}'
docker inspect guardrail-mcp-server --format '{{json .HostConfig.SecurityOpt}}'
docker inspect guardrail-mcp-server --format '{{json .HostConfig.Tmpfs}}'
```
Expected:
- User is `65532:65532`
- `ReadonlyRootfs` is `true`
- Capabilities show `ALL` dropped
- Security options include `no-new-privileges:true`
- `/tmp` tmpfs mount is present
---
## 9) Common Failure Modes and Fixes
### Symptom: `Missing session_id parameter`
- Cause: posting to `/mcp/v1/message` without query string
- Fix: always post to URL emitted in SSE `endpoint` event
### Symptom: POST returns `202` but no JSON body
- Cause: expected behavior in session/SSE mode
- Fix: read JSON-RPC response from Terminal A SSE stream (`event: message`)
### Symptom: `/health/ready` returns `503`
- Cause: DB or Redis unhealthy/unreachable
- Fix:
- `podman logs guardrail-postgres`
- `podman logs guardrail-redis`
- confirm `.env` credentials match compose env
### Symptom: cannot access from outside deployment host
- Cause: ports are bound to `127.0.0.1` only
- Fix: use SSH tunnel or put Nginx/Traefik in front
### Symptom: Web UI loads blank/missing assets
- Cause: stale container image before static asset packaging updates
- Fix:
- `podman-compose -f deploy/podman-compose.yml down`
- `podman-compose -f deploy/podman-compose.yml up -d --build`
---
## 10) Bug Report Template
Use this exact format in issues:
```markdown
**Test Area:** [Architecture | MCP Protocol | Web API | Security | Resilience]
**Severity:** [Critical | High | Medium | Low]
**Expected:** [What should happen]
**Actual:** [What happened]
**Repro Steps:**
1. ...
2. ...
3. ...
**Artifacts:**
- `podman-compose ps` output
- `podman logs guardrail-mcp-server --tail 200`
- Full curl command used (redact secrets)
- Response status/body or SSE event snippet
**Environment:**
- Host: <deployment-host>
- OS:
- Podman version:
- podman-compose version:
- Tested commit/tag:
```
---
## 11) Quick Command Block
```bash
# Start stack
cd mcp-server && make docker-up
# Check service state
podman-compose -f deploy/podman-compose.yml ps
# Follow app logs
podman logs -f guardrail-mcp-server
# Load port values
set -a && source .env && set +a
# Health check
curl -s "http://localhost:${WEB_PORT}/health/ready"
# Open SSE
curl -N "http://localhost:${MCP_PORT}/mcp/v1/sse"
```
Docker-only quick block:
```bash
# Start stack
cd mcp-server
docker compose -f deploy/podman-compose.yml up -d --build
# Or use tester-validated Docker compose file
# docker compose -f deploy/docker-compose.example.yml up -d --build
# Check service state
docker compose -f deploy/podman-compose.yml ps
# Follow app logs
docker logs -f guardrail-mcp-server
# Load port values
set -a && source .env && set +a
# Health check
curl -s "http://localhost:${WEB_PORT}/health/ready"
# Open SSE
curl -N "http://localhost:${MCP_PORT}/mcp/v1/sse"
```
---
## Feedback Channel
- GitHub Issues: https://github.com/TheArchitectit/agent-guardrails-template/issues
---
**Last Updated:** 2026-02-08

Some files were not shown because too many files have changed in this diff Show More