prevent-agent-bloat

Previne Sub-Agents inchados - especialização única, interface contratual, stateless, graceful errors

Prevent Agent Bloat

Esta SKILL previne criação de Sub-Agents inchados e excessivos, aplicando princípios de especialização única, interface contratual clara, invocação lazy, stateless e graceful errors.

Shared Base

This file contains the principles and policies shared by all prevention SKILLs (prevent-skill-bloat, prevent-agent-bloat, prevent-command-bloat, prevent-file-floods).

Objective

Prevent behaviors that frustrate users:

  1. Creating much more than requested (extra files, unnecessary validations, unsolicited examples)
  2. Exaggerated and over-written descriptions (excessive verbosity when brevity would be better)
  3. Returning to the same problems after refactoring (not learning from user corrections)
  4. Implementations with parts from various iterations (inconsistent final code/definition)

File Creation Policy

NEVER create automatically:

  • Documentation (README.md, ANALYSIS.md, REPORT.md, SUMMARY.md, etc.)
  • Explanations, analyses, or reviews in files
  • Responses to "explain", "analyze", "what is", "how does"

ALWAYS create:

  • Functional code (.py, .js, .ts, etc.) when implementing features
  • Essential configuration (package.json, requirements.txt, .env.example)
  • Explicitly requested files ("create a file", "save to")

ASK before:

  • Ambiguous request
  • File >100 lines (better in file than chat)
  • Multi-file projects with unclear structure

Behavior Mode: Contextual Analysis

Apply contextual analysis - there is no rigid template:

Simple and direct → Minimal implementation

  • DO: Create only what was requested
  • DO NOT: Add long descriptions, redundancies, extra explanations

Complex with composition → Create necessary files

  • DO: Use sub-skill composition when it increases efficiency
  • DO: Structure complex resources adequately

Deterministic → Implement exactly what was requested

  • DO: Implement what was asked (not "what could be")
  • DO NOT: Add multiple possibilities to deterministic cases

Ambiguous → Ask instead of guessing

  • DO: Use AskUserQuestion when unclear
  • DO NOT: Implement as precaution or "just in case"

Assertive Execution

BEFORE creating or modifying any resource:

  1. IDENTIFY: What is this resource's single responsibility?

    • Must have ONE clear and specific responsibility
    • Name should reflect the responsibility
  2. IMPLEMENT: Only what was explicitly requested

    • DO: Implement exactly what was asked
    • DO NOT: Add "possibilities" or "variations"
    • DO NOT: Create extra resources "as precaution"
  3. WRITE: Imperative mode, direct instructions

    • MUST: Imperative language ("DO this", "MUST do")
    • DO NOT: Ambiguous language ("could", "maybe", "consider")
  4. VERIFY: Is response deterministic for given input?

    • Same input should generate same output
    • Predictable and consistent behavior

IF unsure about user intent: → USE: AskUserQuestion tool to clarify → DO NOT: Implement multiple variations or guess

IF detect principle violation DURING work: → STOP immediately → WARN: "⚠️ [action] may violate [principle X] in principles/[file].md" → WAIT: For user confirmation before proceeding


Princípios Específicos para Sub-Agents

Principles for Sub-Agents

Principle I: Single Specialization

MUST: Sub-Agent solves ONE specific category of problem MUST: Name clearly reflects specialization (e.g.: FileValidator, CodeAnalyzer) DO NOT: Names with "and" or "or" (indicates multiple responsibilities)

Specialization Test:

Question: "Does this sub-agent do X AND Y?"
→ YES: SPLIT into 2 sub-agents
→ NO: OK, single specialization maintained

❌ "FileValidatorAndCreator" (2 responsibilities)
✅ "FileValidator" + "FileCreator" (each does ONE thing)

Principle II: Contractual Interface

MUST: Clearly define Input, Output, Errors, Constraints MUST: Interface documented in AGENT.md or interface spec

Required Components:

  1. Input Schema: What sub-agent expects to receive
  2. Output Schema: What sub-agent ALWAYS returns
  3. Error Cases: Failure conditions and format
  4. Constraints: Limitations and pre-conditions

Minimal Structure:

SubAgent: FileValidator
Input: {filename, user_message, context?}
Output: {should_create, decision, reasons, confidence}
Errors: [INVALID_FILENAME, MISSING_CONTEXT]
Constraints: [stateless, <100ms response time]

Complete Template (YAML format):

sub_agent: FileValidator
version: 1.0.0
responsibility: "Validates if file should be created"

input:
  required: [filename, user_message]
  properties:
    filename: string
    user_message: string
    context: object (optional)

output:
  properties:
    should_create: boolean
    decision: enum[ALLOWED, BLOCKED, ASK_USER]
    reasons: array<string>
    confidence: float[0.0-1.0]

errors:
  INVALID_FILENAME: "empty filename → return error"
  MISSING_CONTEXT: "empty user_message → ASK_USER"

constraints:
  - Stateless (no state between calls)
  - Does not modify filesystem
  - <100ms for 95% of cases

Principle III: Lazy Invocation (Cost-Conscious)

MUST: Sub-Agent invoked ONLY when necessary MUST: Implement guard clauses for simple cases

Strategies:

  1. Guard Clauses: Check pre-conditions before invoking
  2. Fast-Path: Resolve simple cases without sub-agent
  3. Cache: Reuse results when applicable
  4. Batching: Group multiple calls

Lazy Invocation Pattern:

BEFORE invoking sub-agent:
1. CHECK: Is it trivial case? → Handle directly
2. CHECK: Already have cached result? → Reuse
3. CHECK: Can resolve with fast-path? → Use fast-path
4. ONLY THEN: Invoke sub-agent for complex case

RESULT: 40-60% reduction in unnecessary invocations

Pseudo-Code Example:

# ❌ BAD: Always invokes
result = SubAgent.process(input)

# ✅ GOOD: Guard clauses first
IF trivial_case(input):
    RETURN handle_trivial()
IF cached(input):
    RETURN get_cached()
IF can_fast_path(input):
    RETURN fast_path()
ELSE:
    RETURN SubAgent.process(input)

Principle IV: State Isolation (Stateless)

MUST: Sub-Agent does not maintain state between invocations MUST: All necessary context comes in input DO NOT: Depend on previous executions DO NOT: Use global variables or mutable cache

Benefits:

  • Safe parallelization
  • Simplified debugging
  • Isolated tests
  • Zero side-effects

Stateless Design:

MUST:
- Pure functions (same input → same output)
- All state in input
- Output independent of previous calls

DO NOT:
- Global variables
- Persistent cache modified by sub-agent
- Dependencies on execution order

Stateless Example:

# ✅ GOOD: Stateless
def validate_file(filename, rules, context):
    # All state comes from input
    return Decision(filename, rules, context)

# ❌ BAD: Stateful
validation_count = 0  # Global state
def validate_file(filename):
    global validation_count
    validation_count += 1  # Side-effect

Principle V: Graceful Failure (Error Handling)

MUST: Return structured error, never crash MUST: Include sufficient context for debugging MUST: Suggest corrective action when possible

Structured Error Format:

{
  "success": false,
  "error": {
    "code": "INVALID_INPUT",
    "message": "Filename cannot be empty",
    "suggestion": "Provide valid filename parameter",
    "context": {
      "received": null,
      "expected": "string"
    }
  }
}

Error Levels:

  1. INVALID_INPUT: Malformed input → return error immediately
  2. PROCESSING_ERROR: Failure during execution → return error with context
  3. PARTIAL_SUCCESS: Partially processed → return success + warnings
  4. DEGRADED_MODE: Limited functionality → return with flag

Error Handling Pattern:

def process(input):
    # Validate input
    IF not valid(input):
        RETURN error("INVALID_INPUT", details, suggestion)

    # Process with try/catch
    TRY:
        result = do_work(input)
        RETURN success(result)
    CATCH exception:
        RETURN error("PROCESSING_ERROR", exception, suggestion)

Handling Strategies:

  • Fail Fast: Validate input before processing
  • No Silent Failures: Always return explicit status
  • Context Rich: Include what caused error
  • Actionable: Suggest how to fix

Common Anti-Patterns

❌ God Agent

Problem: Sub-Agent does everything (validation, transformation, persistence, notification) Solution: Split into specialized sub-agents

❌ Anemic Agent

Problem: Sub-Agent only calls another sub-agent without adding value Solution: Remove unnecessary intermediate layer

❌ Chatty Interface

Problem: Multiple calls to complete one operation Solution: Single interface with all necessary info

❌ Hidden Dependencies

Problem: Sub-Agent depends on global state or execution order Solution: Make all dependencies explicit in input

❌ Over-Engineering

Problem: Sub-Agent too generic trying to cover all cases Solution: Focused specialization, create additional sub-agents when necessary

❌ No Error Handling

Problem: Sub-Agent crashes or returns null on error Solution: Always return structured error with context


Creation Checklist

BEFORE creating sub-agent, verify:

  • MUST: Has single responsibility? (Specialization Test)
  • MUST: Contractual interface defined? (Input/Output/Errors/Constraints)
  • MUST: Is stateless? (No state between calls)
  • MUST: Complete error handling? (Never crashes)
  • MUST: Justifies existence? (Not anemic)

IF any answer is NO: → STOP and redesign before implementing


Keywords de Ativação

Esta SKILL ativa quando usuário menciona:

  • "criar sub-agent", "novo agent", "modificar agent"
  • "implementar agent", "atualizar agent"
  • "fazer um agent", "gerar agent", "criar agente"

Não ativa para perguntas conceituais sobre Sub-Agents.


Versão: 0.0.1-beta (Modular) Parte do: anti-flood plugin