Advanced Subagent Architecture
Patterns and templates for building robust multi-agent systems with OpenClaw.
Why This Skill Is Complex (Read Before Installing)
This is one of the most feature-dense skills in the ClawHub registry. Security scanners will flag it — not because it's malicious, but because it does a lot. Here's exactly what's in it and why:
Scope:
- 4 production-ready JS libraries (~1,200 lines total across spawn-security-proxy, spawn-researcher, cost-estimator, quality-scorer)
- 4 spawn templates covering security proxy, researcher, phased implementation, and peer review patterns
- A
setup.sh that creates local directory scaffolding (no network calls, no package installs)
- Inline attack vector documentation in
spawn-security-proxy.js (test fixtures, not live payloads)
Why the libs exist: These aren't glue code — they implement real patterns: output sanitization with canary tokens, multi-source research validation, cost projection with approval gates, and subagent output scoring. The complexity is the point; simpler skills don't solve these problems.
Why scanners flag it:
- JS code in a skill package looks like an execution surface — it is, but only when you explicitly
require() it
- The security proxy documents injection attack patterns as test examples — pattern matchers don't distinguish documentation from intent
- External integration references (Discord, peer agents) appear in templates — they're opt-in workflows, not auto-configured connections
Complexity is not a red flag here. It's the product.
⚠️ Security Transparency Notice
What this skill contains:
lib/ — Reference JS libraries (spawn helpers, cost estimator, quality scorer). These are not auto-executed. Copy them to your workspace lib/ directory to use them.
templates/ — Markdown spawn templates for common patterns.
setup.sh — Creates local directory scaffolding only. Makes no network calls, installs no packages.
External integrations: All optional, none auto-configured.
- Discord webhooks — Only used in the federated peer-review pattern. You supply your own token manually. This skill does not store or transmit credentials.
- Peer agent endpoints — Federated review is opt-in. No external calls unless you explicitly configure peer URLs.
Credential requirements: None. No API keys, tokens, or env vars are required or auto-read by this skill.
Overview
This skill provides battle-tested patterns for:
- Security isolation - Contain high-risk operations with minimal context exposure
- Specialized research - Multi-perspective data gathering with domain experts
- Phased implementation - Architecture → Development → Review pipelines
- Peer collaboration - External validation via federated agent network (opt-in)
- Cost-aware spawning - Budget estimation and optimization strategies
What's New in v2.0
Advanced Patterns:
- Security proxy pattern (blast shield isolation)
- Researcher specialist pattern (multi-source synthesis)
- Phased implementation pipeline (architect → coder → reviewer)
- Peer review integration (bot-to-bot validation)
- Cost estimation framework (required for spawns >$0.50)
Templates:
templates/security-proxy.md - Isolate untrusted service access
templates/researcher-specialist.md - Domain-specific research agents
templates/phased-implementation.md - Multi-phase feature development
templates/peer-review-specialist.md - External peer validation
Integration:
- task-routing skill (auto-classification and routing)
- cost-governor (budget enforcement)
- drift-guard (behavioral validation)
Quick Start
1. Install Skill Structure
cd $OPENCLAW_WORKSPACE/skills/subagent-architecture
bash setup.sh # Creates directories and scaffolding
2. Choose Your Pattern
For high-risk operations:
# Read security-proxy template
cat templates/security-proxy.md
# Spawn isolated proxy for untrusted API
# (see template for full example)
For research tasks:
# Read researcher-specialist template
cat templates/researcher-specialist.md
# Spawn domain expert for deep analysis
# (see template for multi-perspective pattern)
For complex features:
# Read phased-implementation template
cat templates/phased-implementation.md
# Launch architect → coder → reviewer pipeline
# (see template for orchestration example)
For external validation:
# Read peer-review-specialist template
cat templates/peer-review-specialist.md
# Request peer agent review via Discord/API
# (see template for federated trust protocol)
Agent Registry: AGENTS.md is Optional
Critical clarification for new users: AGENTS.md is a human-readable reference document, not a configuration file. The spawning system does not read it.
How spawning actually works
sessions_spawn is a tool call — it takes parameters you provide at the moment of the call. It does not read from any file, config, or registry. You can spawn subagents on a completely fresh OpenClaw install with zero files in your workspace.
// This is ALL the system needs — no AGENTS.md required
sessions_spawn({
label: "my-researcher",
task: "Research the topic X",
model: "sonnet"
})
What AGENTS.md actually is
AGENTS.md (and domain files like AGENTS_WRITING.md, AGENTS_INFRA.md) are memory aids for you (the agent). They store:
- Agent names and personality snippets you've found effective
- Cost history and last-used dates
- Notes on what tasks each agent type handles well
You can split AGENTS.md into 50 domain files or delete it entirely — spawning still works. The split is purely for your readability; it has zero functional effect.
What "read AGENTS_WRITING.md before spawning" means
When documentation says "read AGENTS_WRITING.md before spawning AuthorAgent", it means:
Read it so you know what personality, model, and task description to use when building the spawn call.
The system does not read it. You read it, extract the configuration, then make the spawn call with those parameters.
Practical implication for fresh installs
When you install this skill on a fresh OpenClaw setup:
- You do not need to create AGENTS.md to use subagents
- Start spawning immediately with inline parameters
- Create AGENTS.md when you have enough recurring agent configurations that you want a reference doc
- Split into domain files when AGENTS.md grows beyond ~10 entries and becomes hard to scan
See templates/agents-registry-template.md for a minimal starter template when you're ready.
Reference Implementations
NEW in v2.1: Production-ready code libraries for all patterns.
Available Libraries
lib/spawn-security-proxy.js - Security isolation framework
spawnSecurityProxy(config) - Spawn isolated proxy with sanitization
deepSanitize(data) - Remove sensitive data (API keys, paths, emails)
validateSchema(data, schema) - JSON schema validation
createDefaultSchema(type) - Common output schemas (list, single, status)
lib/spawn-researcher.js - Multi-perspective research framework
spawnResearcher(config) - Spawn domain expert researcher
spawnMultiPerspective(config) - Multi-perspective research (optimist/pessimist/pragmatist)
assessSourceCredibility(source) - Score source trustworthiness (0-100)
- Pre-configured trusted/blog/vendor domain lists
lib/cost-estimator.js - Cost estimation and tracking
estimateSubagentCost(params) - Pre-spawn cost estimation with confidence intervals
logSubagentCost(label, estimate, actual) - Log for accuracy tracking
recalibrateEstimator() - Monthly accuracy improvement
getPatternHistory(pattern) - Historical performance analysis
getCostTier(cost) - Classify as micro/small/medium/large
lib/quality-scorer.js - Output quality assessment
scoreSubagentOutput(output, rubric) - 8-dimension quality scoring
createScoringTemplate() - Manual review template
selfAuditChecklist(output) - Pre-delivery validation
- Rubric dimensions: specificity, actionability, evidence, structure, completeness, clarity, relevance, efficiency
Usage Examples
All libraries include complete working examples:
# Security proxy examples
node examples/security-proxy-usage.js
# Researcher examples
node examples/researcher-usage.js
# Cost estimation examples
node examples/cost-estimation-demo.js
Quick Integration
Path Resolution Note: The require() paths in examples below assume you call them from your workspace root. If you call from within the skill directory (e.g., inside an example script), use __dirname instead. For portable code that works regardless of cwd:
// Path resolution — works regardless of workspace structure
const path = require('path');
const SKILL_DIR = __dirname; // when called from within skill directory
// OR if calling from workspace root:
const SKILL_DIR = path.join(process.env.OPENCLAW_WORKSPACE || process.cwd(), 'skills', 'subagent-architecture');
const { spawnSecurityProxy } = require(path.join(SKILL_DIR, 'lib', 'spawn-security-proxy'));
// Example: Spawn security proxy for untrusted API
const { spawnSecurityProxy } = require('./skills/subagent-architecture/lib/spawn-security-proxy');
const result = await spawnSecurityProxy({
service: 'weather-api',
task: 'Get current weather for New York',
query: { city: 'New York', units: 'metric' },
output_schema: {
type: 'object',
properties: {
temperature: { type: 'number' },
conditions: { type: 'string' }
}
},
spawn_fn: async (config) => {
// Your actual sessions_spawn call here
return await sessions_spawn(config);
}
});
// Example: Estimate cost before spawning
const { estimateSubagentCost, logSubagentCost } = require('./skills/subagent-architecture/lib/cost-estimator');
const estimate = estimateSubagentCost({
task_complexity: 'medium',
expected_duration_min: 15,
model: 'sonnet',
research_required: true
});
console.log(`Estimated: $${estimate.expected} (range: $${estimate.min}-$${estimate.max})`);
// After spawn completes
logSubagentCost('researcher-task', estimate, actual_cost);
// Example: Score output quality
const { scoreSubagentOutput } = require('./skills/subagent-architecture/lib/quality-scorer');
const score = scoreSubagentOutput(subagent_output, null, { auto_score: true });
console.log(`Quality: ${score.overall_score}/10 (${score.pass ? 'PASS' : 'FAIL'})`);
See examples/ directory for complete working demonstrations.
Integration Status
Dependencies Overview
Required:
- ✅ OpenClaw 2026.2.17+ (
sessions_spawn API)
- ✅ Node.js 18+ (for library code)
Optional Skills:
task-routing
- Status: ✅ Available (workspace
skills/task-routing/)
- Version: 1.0.0+
- Integration: Auto-classification of incoming tasks, risk scoring, pattern routing
- Tested: Yes (production since 2026-02-15)
- Documentation: See
skills/task-routing/SKILL.md
cost-governor
- Status: ⚠️ Planned (design phase)
- Version: N/A
- Integration: Budget enforcement, approval workflows
- Tested: No
- Workaround: Use
lib/cost-estimator.js for manual gating
drift-guard
- Status: ⚠️ Planned (design phase)
- Version: N/A
- Integration: Behavioral audits, policy violation detection
- Tested: No
- Workaround: Manual output review against rubric
Library Dependencies
All reference implementations are dependency-free (pure Node.js):
- No npm packages required
- No external API calls
- Filesystem access for logging only (optional)
- Mock-friendly for testing
Integration Points
Automatic (via task-routing skill):
- Task classification → Pattern recommendation
- Risk scoring → Security proxy auto-spawn for high-risk tasks
- Cost estimation → Pre-spawn budget check
Manual (call libraries directly):
require() any lib file and call functions
- See
examples/ for usage patterns
- Spawn functions accept custom
spawn_fn for integration with your sessions_spawn
Migration Path
From v2.0 to v2.1:
- No breaking changes - templates still work as-is
- New: Import library functions for programmatic use
- New: Run examples to see working code
- Optional: Integrate with task-routing for automation
Future (v3.0 with framework improvements):
- Per-spawn resource limits (when OpenClaw supports)
- Bidirectional communication (when OpenClaw supports)
- Post-mortem tracking (when OpenClaw supports)
- See "Framework Limitations & v2 Roadmap" section for details
Core Concepts
1. Security Isolation (Blast Shield Philosophy)
Problem: Subagents with full workspace access can leak sensitive data to untrusted APIs.
Solution: Security proxies receive minimal context, restricted tools, sanitized output.
Example:
Main Agent (full context)
│
└─ SecurityProxy (minimal context)
├─ Query: "Get weather for New York"
├─ Tools: exec (curl only)
├─ Output: Sanitized JSON (no API metadata)
└─ Auto-terminate after single task
Key principles:
- Minimal context (only task parameters, no workspace paths)
- Tool restrictions (whitelist, not blacklist)
- Output sanitization (validate schema before returning)
- Ephemeral execution (no persistent state)
- Cost cap (< $0.10 per proxy spawn)
See: templates/security-proxy.md
2. Researcher Specialists (Multi-Source Synthesis)
Problem: Generic web search returns surface-level results without domain expertise.
Solution: Specialized researchers with domain bias, multi-source validation, actionable synthesis.
Example:
Question: "Should we adopt technology X?"
├─ OptimistResearcher (best-case analysis)
├─ PessimistResearcher (risk assessment)
└─ PragmatistResearcher (current reality)
Main Agent synthesizes: Balanced decision tree
Key principles:
- Domain focus (single expertise area per researcher)
- Multi-source validation (3+ independent sources per claim)
- Skeptical by default (anti-hype, calls out marketing)
- Structured output (executive summary + recommendations)
- Evidence-backed (no speculation, contradictions addressed)
See: templates/researcher-specialist.md
3. Phased Implementation (Separation of Concerns)
Problem: Single-agent implementation mixes design, coding, and validation → tech debt.
Solution: Separate architect (design), coder (build), reviewer (validate) phases.
Example:
Feature Request: "Add memory consolidation skill"
Phase 1: SystemArchitect (15min, $0.40)
└─ Delivers: IMPLEMENTATION_PLAN.md
Phase 2: CoderAgent (25min, $0.70)
└─ Delivers: Working code + tests
Phase 3: ReviewerAgent (10min, $0.30)
└─ Delivers: REVIEW_REPORT.md (approval/rejection)
Total: 50min, $1.40, high-quality feature
Key principles:
- Architects optimize long-term (not quick hacks)
- Coders focus on working code (test after each step)
- Reviewers provide fresh perspective (catch integration issues)
- Incremental delivery (small PRs, easy rollback)
- Cost-aware (skip phases for simple features)
See: templates/phased-implementation.md
4. Peer Collaboration (Federated Trust)
Problem: Your agent may have blindspots or lack domain expertise.
Solution: Request external validation from trusted peer agents.
Example:
Your Agent
│
├─ Prepares sanitized review package
│
├─ Contacts Smith's SecurityBot (via Discord/API)
│ └─ Smith's bot spawns SecurityReviewer
│ └─ Returns: Structured findings
│
└─ Integrates feedback (fix critical issues)
Key principles:
- Trust earned (track peer accuracy over time)
- Data sanitization (remove secrets, personal data)
- Structured feedback (severity, category, recommendations)
- Reciprocal reviews (offer your expertise to peers)
- Cost-effective (free peer reviews vs paid audits)
⚠️ Trust tier ≠ security bypass:
If you implement tiered trust (Acquaintance → Friend → Ally or equivalent), "higher trust" means relaxed engagement policy — not skipping security validation. Content from even the most trusted peer still goes through injection detection (Stage 4). An ally account can be compromised; the injection scanner is the last defense that can't be socially engineered. "Light validation" always means reduced schema scrutiny, never reduced security scanning.
See: templates/peer-review-specialist.md
5. Identity Continuity (Ephemeral Process, Persistent External Identity)
Problem: Security proxies are ephemeral (spawn-per-task, terminate). But some external services require a persistent identity — a social network account, an API user, a recurring agent persona. These are in tension.
Solution: Separate the process lifecycle from the external identity. The process dies every spawn. The external identity persists through workspace state + core-managed credentials.
External service sees: CedarProxy (consistent identity across all spawns)
Under the hood:
Spawn 1: [process starts] → reads state files → executes → [process dies]
Spawn 2: [new process] → reads same state files → continues → [dies]
Spawn 3: [new process] → reads same state files → continues → [dies]
State that persists: /proxy-workspace/ files (logs, relationships, posts)
State that doesn't: in-memory session, conversation history, token
Credentials: held by core, passed as short-lived scoped token at spawn time
Key rules:
- Credentials live in core memory only — never in proxy workspace files
- Session token: short TTL (2 hours max), passed encrypted in task context, never written to disk
- Consistency: core injects "recent context" summary (last N interactions) into each spawn's task description so the new process knows what prior spawns committed to
- Token rotation: scheduled by core (e.g., weekly), not the proxy
Anti-pattern: storing tokens in [workspace]/config.json — if the proxy workspace is compromised, credentials should not be compromised with it.
6. Research Team (Parallel Multi-Lens Analysis)
Problem: Single-agent analysis has blind spots — the same agent proposes and evaluates its own ideas.
Solution: Spawn 3 specialist agents in parallel with distinct analytical lenses, then synthesize into one unified response.
Architecture:
High-complexity query
│
├─ Critic lens (find flaws, risks, costs — no solutions)
├─ Implementer lens (concrete execution, architecture, feasibility)
└─ Synthesizer lens (integrate, resolve tensions, unified path)
│
UnifierAgent (one clean final response)
When to use:
- Task complexity === 'high' OR explicit research flag set
- Architecture decisions with real tradeoffs
- Debugging where root cause is unclear
- Any question where a single perspective tends to miss things
When to skip:
- Routine tasks, simple lookups, quick fixes
- Cost-sensitive situations (research team = ~4x single-agent cost)
Key components:
lib/team-chatroom.js — append-only JSONL shared memory between parallel agents
lib/research-coordinator.js — builds task strings for each lens + UnifierAgent
shouldUseResearchTeam(complexity, explicitFlag) — gate function
buildResearchTeam(query) — returns sessionId + 3 specialist task objects
buildUnifierTask(query, sessionId) — builds synthesis prompt from chatroom
checkLensCompletion(sessionId) — verifies all lenses posted before unifying
Lens discipline:
- Each lens gets a distinct role description injected into its prompt
- Lenses do NOT communicate with each other — only through the chatroom
- UnifierAgent reads all lens outputs and produces ONE response
- If a lens fails silently, UnifierAgent warns but synthesizes from available data
Cost: ~4x single-agent. Gate on complexity to control spend.
Critical rule: Grok or any external model used as a lens is a leaf node — it answers, it never spawns further agents.
See: lib/research-coordinator.js for reference implementation.
7. External Model Consultation
Problem: Your agent may have architectural blind spots that another model's reasoning style would catch. Human relay (copy/paste to another AI) is slow and lossy.
Solution: Spawn an ExternalConsultAgent subagent that calls an external model's API directly, persists the session, and returns the response.
Architecture:
Core agent decides consultation needed
│
└─ ExternalConsultAgent subagent
├─ Calls external API (Grok, OpenAI, etc.)
├─ Injects system-level intent for alignment
├─ Supports session continuity (sessionId)
└─ Returns response + sessionId
Why subagent, not core agent:
External API calls are side effects with cost and data exposure implications. Isolating them in a subagent follows the blast-shield philosophy — if something goes wrong, it's contained.
Key components:
lib/external-bridge.js — session management, task string builder, consultation logger
memory/external-agents.json — provider config (model IDs, endpoints)
memory/external-sessions/ — persistent session files for conversation continuity
lib/external-consult-helper.js — shouldAutoConsult() gate (RED drift + high complexity + 24h cooldown)
Auto-consult gate (3 conditions, all required):
- Intent drift level === 'RED'
- Task complexity === 'high'
- Last consultation > 24 hours ago (with lock file to prevent race conditions)
Security rules (enforce before go-live):
- External model is a leaf node — never triggers further spawns
- Context sanitization before every call — strip API keys, file contents, internal paths
- Session-level call cap (prevent fan-out)
- Metadata logging of every call (timestamp, provider, trigger reason)
- Key stored in environment variable, not config file
Session continuity:
Pass sessionId from a previous consultation to continue the conversation. The bridge injects prior message history automatically.
See: lib/external-bridge.js for reference implementation.
8. Intent Engineering (Value Alignment over Time)
Problem: Prompt engineering tells agents what to do. Context engineering tells agents what to know. Neither tells agents what to want — so they drift from user values over time without detection.
Solution: A three-layer system that encodes agent intent, extracts intent signals from user behavior, and detects drift before it becomes a problem.
Three layers:
- Intent Manifest (
memory/intent-manifest.json) — Machine-readable intent spec per agent: core purpose, hard constraints (with regex), operational goals with verification keywords, user signals extracted from history
- Intent Extractor (
lib/intent-extractor.js) — Weekly pass over episode history extracting preference/value/correction signals; decays old signals (rate: 0.975/week), prunes below 0.30 strength
- Drift Detector (
lib/intent-drift-detector.js) — 5-component score per episode: hard constraint violations (0.35), goal keyword coverage (0.25), structural drift via Jaccard (0.20), correction pressure (0.15), forbidden phrase hits (0.05)
Drift levels:
- GREEN (< 0.29): Normal operation
- YELLOW (0.29–0.48): Inject reminder next turn
- ORANGE (0.48–0.68): Log + prepare summary
- RED (≥ 0.68): Flag for user check-in (triggers auto-consult gate)
Intent manifest schema:
{
"system": {
"core_purpose": "...",
"hard_constraints": [{"id": "...", "rule": "...", "regex": "..."}],
"operational_goals": [{"id": "...", "description": "...", "verification_keywords": [], "weight": 0}]
},
"agents": {
"AgentName": {
"inherits": true,
"overrides": {
"core_purpose": "...",
"operational_goals": [],
"user_signals": []
},
"version": "YYYY-MM-DD.001"
}
},
"diff_log": []
}
Key properties:
- System intent + agent overrides use deep merge — agents inherit system constraints
- User signals decay weekly — recent corrections weighted higher
- Operational goals are hand-authored for v1; intent compression auto-suggests additions in v2
- Manifest is diffable over time (diff_log tracks changes)
- Drift score adjusts confidence estimator:
score *= (1 - drift.score * 0.3)
Cold start: Works on day 1 with hand-authored goals. Signals accumulate automatically.
See: lib/intent-manager.js, lib/intent-extractor.js, lib/intent-drift-detector.js for reference implementation.
5. Cost-Aware Spawning
Problem: Uncontrolled subagent spawning leads to budget overruns.
Solution: Estimate cost before spawning, require approval for expensive operations.
Framework:
// Pre-spawn cost estimation
const estimate = estimateSubagentCost({
task_complexity: "high", // simple/medium/high
expected_duration_min: 20,
model: "sonnet", // haiku/sonnet/opus
research_required: true
})
// estimate = { min: $0.60, max: $1.20, confidence: 0.8 }
if (estimate.max > 0.50) {
// Log to cost tracking
await logCostEstimate("task-label", estimate)
if (estimate.max > 2.00) {
// Require human approval
await requestApproval(estimate)
}
}
// Spawn subagent
const result = await spawnSubagent(...)
// Track actual cost
await logActualCost("task-label", result.cost)
Cost tiers:
- Micro (< $0.10): Simple lookups, fact-checking
- Small ($0.10-0.50): Standard research, code review
- Medium ($0.50-2.00): Feature implementation, deep analysis
- Large (> $2.00): Complex refactors, multi-phase projects
Optimization strategies:
- Use haiku for simple tasks (3x cheaper than sonnet)
- Parallelize independent operations
- Cache research findings for reuse
- Skip optional phases (reviewer for low-risk changes)
Directory Structure
subagents/
├── [specialist-name]/
│ ├── SPECIALIST.md # Agent definition and personality
│ ├── knowledge-base/ # Reference materials
│ └── research/ # Task outputs and findings
└── _archived/ # Retired subagents
skills/subagent-architecture/
├── SKILL.md # This file
├── templates/
│ ├── security-proxy.md
│ ├── researcher-specialist.md
│ ├── phased-implementation.md
│ └── peer-review-specialist.md
└── setup.sh # Directory scaffolding script
When to Use Each Pattern
Security Proxy
Use when:
- Accessing untrusted APIs or experimental services
- Risk score > 70 (high blast radius or irreversibility)
- Data needs sanitization before main agent sees it
- Cost estimate < $0.10 (lightweight proxy)
Skip when:
- Trusted first-party APIs (your infrastructure)
- Read-only public data (Wikipedia, documentation)
- Risk score < 30 (low stakes)
Researcher Specialist
Use when:
- Question requires 10+ sources
- Domain expertise needed (not general knowledge)
- Multiple conflicting claims (need fact-checking)
- Deliverable is a decision (not just information)
- Cost estimate > $0.20 (worth specialist analysis)
Skip when:
- Simple factual lookup (single authoritative source)
- Real-time data (weather, stock prices)
- Cost estimate < $0.10 (not worth overhead)
Phased Implementation
Use when:
- Feature touches 3+ files
- Requires integration with existing systems
- Cost estimate > $1.00 (worth upfront design)
- Failure would be expensive (need rollback plan)
- Long-term maintainability matters
Skip when:
- Simple script (1 file, no integration)
- Well-understood pattern (copying existing structure)
- Prototype/experiment (might throw away)
- Cost estimate < $0.50 (faster to just build)
Peer Review
Use when:
- High stakes (security, legal, financial)
- Domain gap (no internal specialist)
- Bias check (fresh perspective needed)
- Complex validation (multi-dimensional review)
Skip when:
- Low stakes (documentation, styling)
- Domain expertise available internally
- Fast turnaround required (peer may take hours/days)
- Sensitive data (can't sanitize for external review)
Integration with Task Routing
Automatic pattern selection via task-routing skill:
# config/routing-rules.yaml
pattern_routing:
security_proxy:
triggers:
- blast_radius > 70
- untrusted_api: true
max_cost: 0.10
researcher_specialist:
triggers:
- task_type: research
- complexity > 50
min_sources: 3
phased_implementation:
triggers:
- task_type: code_gen
- files_affected > 3
- cost_estimate > 1.00
phases: [architect, coder, reviewer]
peer_review:
triggers:
- irreversibility > 80
- domain_gap: true
require_approval: true
Manual override:
// Force specific pattern
spawnSubagent({
pattern: "security-proxy", // override routing decision
task: "...",
justification: "Experimental API, prefer isolation"
})
Cost Tracking & Optimization
Logging Requirements
All subagent spawns >$0.50 must be logged to notes/cost-tracking.md:
## Subagent Cost Tracking
| Date | Label | Pattern | Estimate | Actual | Delta | Notes |
|------|-------|---------|----------|--------|-------|-------|
| 2026-02-22 | architect-feature-x | phased-impl | $0.40 | $0.38 | -5% | Faster than expected |
| 2026-02-22 | coder-feature-x | phased-impl | $0.70 | $0.85 | +21% | Complex refactor, used opus |
| 2026-02-22 | researcher-market | researcher | $0.60 | $0.55 | -8% | Cached sources helped |
Accuracy Improvement
Track estimate vs actual to improve future predictions:
// Calculate rolling accuracy
const accuracy = calculateAccuracy({
window_days: 30,
min_samples: 10
})
// accuracy = { mean_error: 12%, confidence: 0.85 }
// Adjust future estimates
const adjusted_estimate = base_estimate * (1 + accuracy.mean_error)
Quality Standards
Subagent Output Rubric
All specialist subagents should score 7+ on this rubric:
| Dimension |
Poor (1-3) |
Good (4-6) |
Excellent (7-10) |
| Specificity |
Vague generalizations |
Some concrete details |
Precise, actionable specifics |
| Actionability |
No clear next steps |
Suggestions provided |
Step-by-step implementation plan |
| Evidence |
Unsourced claims |
Some citations |
Every claim sourced, validated |
| Structure |
Stream-of-consciousness |
Basic organization |
Scannable hierarchy, summaries |
| Completeness |
Missing key aspects |
Most areas covered |
Comprehensive, gaps documented |
| Honesty |
Hides limitations |
Mentions some trade-offs |
Explicit about unknowns, risks |
| Cost-awareness |
No budget consideration |
Rough estimates |
Detailed cost/benefit analysis |
| Integration |
Ignores existing systems |
Basic compatibility |
Seamless integration plan |
Self-Audit Checklist
Before finalizing subagent output:
Philosophy
Permanent vs Ephemeral
Permanent subagents (skill-based):
- Recurring specialized tasks
- Deep domain expertise
- Knowledge accumulation over time
- Examples: DevOps, AuthorAgent, WuxiaWorldbuilder
Ephemeral subagents (one-off spawns):
- Bounded research tasks
- Simple implementation work
- Experimental exploration
- Pattern-based specialists (security-proxy, researcher)
Anti-Sycophant by Default
All subagents should:
- Call out weak evidence (no polite agreement)
- Reject unrealistic requirements (push back on bad specs)
- Highlight risks honestly (no sugar-coating)
- Admit knowledge gaps (no speculation to please)
Cost-Conscious Operation
- Estimate before spawning (no surprise bills)
- Choose appropriate model (haiku vs sonnet vs opus)
- Parallelize when possible (save time = save money)
- Cache and reuse (research findings, architecture patterns)
- Terminate early if stuck (don't spin wheels for 30min)
Dependencies
Required
- OpenClaw 2026.2.17+ (subagent spawning, cost tracking)
Optional but Recommended
- task-routing skill (auto-pattern selection, risk scoring)
- cost-governor skill (budget enforcement, approval workflows)
- drift-guard skill (behavioral validation, quality audits)
Integration Points
Task routing:
- Provides task classification (8 types)
- Risk scoring (5 dimensions, 0-100 scale)
- Auto-route to pattern (security-proxy, researcher, phased-impl)
Cost governor:
- Pre-spawn approval for expensive operations
- Budget tracking per project/feature
- Alert on overruns
Drift guard:
- Behavioral audit of subagent outputs
- Policy violation detection
- Quality score trending
Framework Limitations & v2 Roadmap
Known gaps identified in peer review (Agent Smith, EasyClaw project)
Current OpenClaw subagent framework has architectural limitations that affect all patterns in this skill. These are framework-level constraints, not skill-specific issues. Documenting for transparency and future improvement.
1. Spawn Configuration Constraints
Smith's Question: "How does core define sub-bot constraints before launch?"
Current State:
- Spawn parameters:
task, personality, model, timeout, label
- Basic configuration only (what to do, how long)
- No granular resource controls
Limitations:
- ❌ No memory limits per spawn (subagent can consume unlimited RAM)
- ❌ No API call quotas (can make 1000s of web requests)
- ❌ No disk space caps (can fill storage)
- ❌ No per-spawn tool restrictions (tool policy is framework-level, applies to all subagents)
Current Workaround:
- Manual timeout enforcement (kill after N minutes)
- Framework-level tool policies (same restrictions for all subagents)
- Post-spawn monitoring (watch logs, intervene manually)
v2 Design Considerations:
// Proposed: Granular per-spawn constraints
spawnSubagent({
label: "researcher-x",
task: "Research topic",
constraints: {
max_memory_mb: 512, // Kill if exceeds RAM limit
max_api_calls: 50, // Deny further requests after quota
max_disk_mb: 100, // Block file writes beyond limit
max_cost_usd: 0.50, // Auto-terminate if cost projection exceeds
tools_allowed: ["web_search", "web_fetch"], // Per-spawn tool whitelist
tools_denied: ["exec", "write"], // Explicit blacklist
rate_limits: {
web_search: { calls: 10, window_seconds: 60 } // Max 10 searches/min
}
}
})
Impact on Patterns:
- Security proxy: Could enforce strict tool whitelist per proxy (currently manual)
- Researcher: Could cap API calls to prevent runaway research loops
- Phased impl: Could allocate different budgets per phase (architect: $0.40, coder: $1.00)
2. Skill Loading & Validation
Smith's Question: "How are skills validated before execution?"
Current State:
- External skills (downloaded) →
skill-vetter checks metadata, malicious patterns
- Internal skills (workspace) → Just execute (trusted by default)
- No runtime sandboxing
Limitations:
- ❌ No code isolation for skills (skill code runs in main agent context)
- ❌ No execution validation (skill can do anything agent can do)
- ❌ No capability restrictions (skill inherits all agent tools)
- ❌ Trust model: Binary (external = vet, internal = trust)
Current Workaround:
- Vet external skills manually before first use
- Review internal skill code (human audit)
- Hope skills don't misbehave
v2 Design Considerations:
// Proposed: Skill capability manifest
// skills/my-skill/SKILL.md
---
capabilities_required:
- web_search # Skill needs web access
- read:config/ # Can read config directory only
- write:output/ # Can write to output directory only
isolation_level: sandbox # Run in isolated context
max_execution_time: 30 # Kill after 30 seconds
---
// Runtime: Skill runs in sandbox with only declared capabilities
// Attempts to use undeclared tools → blocked, logged, skill terminated
Impact on Patterns:
- Security proxy: Skills could be sandboxed (currently rely on manual isolation)
- All patterns: Skills loaded by subagents would inherit spawn constraints
- Peer review: External skills from peers could run safely (sandboxed)
3. Communication Bounds (Bidirectional Channel)
Smith's Question: "What can sub-bots ask for from core?"
Current State:
- One-way communication only: Core spawns → Subagent executes → Returns result
- Subagent cannot request clarification mid-task
- Subagent cannot request additional context during execution
- No interactive mode
Limitations:
- ❌ Subagent stuck on ambiguous requirement → Must guess or fail
- ❌ Subagent needs additional context → Can't ask, works with what it has
- ❌ Subagent encounters unexpected scenario → No escalation path mid-task
- ❌ Human approval needed mid-execution → Not possible (only pre/post spawn)
Current Workaround:
- Over-specify context in initial spawn (bloated prompts)
- Subagent makes best guess (may be wrong)
- Subagent fails, core respawns with clarification (expensive)
v2 Design Considerations:
// Proposed: Request-response protocol during execution
// Subagent code:
const clarification = await requestFromCore({
type: "clarification",
question: "User said 'recent data' - how many days back?",
options: ["7 days", "30 days", "90 days"],
timeout_seconds: 60 // If no response, default to first option
})
// Core receives request:
// - Auto-approve safe requests (data lookup from memory)
// - Escalate to human for decisions
// - Return answer to subagent
// - Subagent continues with clarification
// Examples:
// - "Need API key for service X" → Core provides from secure store
// - "Found conflicting data, which source to trust?" → Human decides
// - "Task seems too expensive ($5 estimated), proceed?" → Approval workflow
Impact on Patterns:
- Researcher: Can ask "should I dig deeper on this tangent?" mid-research
- Phased impl: Coder can ask architect for design clarification during build
- Security proxy: Can request human approval if API returns unexpected data
- All patterns: Reduces over-specification, enables adaptive execution
4. Termination Conditions (Resource-Based Kills)
Smith's Question: "When does core kill a sub-bot?"
Current State:
…(truncated)
1---
2name: subagent-architecture
3version: 2.3.5
4description: Advanced patterns for specialized subagent orchestration with production-ready reference implementations. Security isolation, phased implementation, peer collaboration, and cost-aware spawning.
5tags: [subagents, architecture, isolation, security, collaboration, orchestration, reference-implementation]
6difficulty: intermediate
7requirements:
8 openclaw_version: ">=2026.2.17"
9 optional_skills: [task-routing, cost-governor, drift-guard]
10author: OpenClaw Community
11license: MIT
12
13# Credential & External Integration Disclosure
14credentials_required: none
15external_integrations:
16 - name: Discord webhook (peer review flow)
17 required: false
18 notes: "Only needed if using the federated peer-review pattern. User must supply their own webhook URL manually. No token is stored or auto-configured by this skill."
19 - name: External peer agents (API endpoints)
20 required: false
21 notes: "Federated review workflows are opt-in. No external calls are made unless the user explicitly configures peer endpoints."
22
23# Package Contents Disclosure
24# This skill contains runnable JS reference libraries in lib/ and example templates in templates/.
25# These files are NOT auto-executed on install. They are reference implementations
26# intended to be copied into your workspace lib/ directory manually or via setup.sh.
27# setup.sh only creates local directory scaffolding — it makes no network calls and installs no packages.
28package_type: reference-implementation-with-libs
29auto_executes: false
30metadata:
31 source: https://skillmd.com/skills/modbender/subagent-architecture
32---
33
34# Advanced Subagent Architecture
35
36Patterns and templates for building robust multi-agent systems with OpenClaw.
37
38## Why This Skill Is Complex (Read Before Installing)
39
40This is one of the most feature-dense skills in the ClawHub registry. Security scanners will flag it — not because it's malicious, but because it does a lot. Here's exactly what's in it and why:
41
42**Scope:**
43- 4 production-ready JS libraries (~1,200 lines total across spawn-security-proxy, spawn-researcher, cost-estimator, quality-scorer)
44- 4 spawn templates covering security proxy, researcher, phased implementation, and peer review patterns
45- A `setup.sh` that creates local directory scaffolding (no network calls, no package installs)
46- Inline attack vector documentation in `spawn-security-proxy.js` (test fixtures, not live payloads)
47
48**Why the libs exist:** These aren't glue code — they implement real patterns: output sanitization with canary tokens, multi-source research validation, cost projection with approval gates, and subagent output scoring. The complexity is the point; simpler skills don't solve these problems.
49
50**Why scanners flag it:**
511. JS code in a skill package looks like an execution surface — it is, but only when you explicitly `require()` it
522. The security proxy documents injection attack patterns as test examples — pattern matchers don't distinguish documentation from intent
533. External integration references (Discord, peer agents) appear in templates — they're opt-in workflows, not auto-configured connections
54
55**Complexity is not a red flag here. It's the product.**
56
57---
58
59## ⚠️ Security Transparency Notice
60
61**What this skill contains:**
62- `lib/` — Reference JS libraries (spawn helpers, cost estimator, quality scorer). These are **not auto-executed**. Copy them to your workspace `lib/` directory to use them.
63- `templates/` — Markdown spawn templates for common patterns.
64- `setup.sh` — Creates local directory scaffolding only. Makes **no network calls**, installs **no packages**.
65
66**External integrations:** All optional, none auto-configured.
67- **Discord webhooks** — Only used in the federated peer-review pattern. You supply your own token manually. This skill does not store or transmit credentials.
68- **Peer agent endpoints** — Federated review is opt-in. No external calls unless you explicitly configure peer URLs.
69
70**Credential requirements:** None. No API keys, tokens, or env vars are required or auto-read by this skill.
71
72## Overview
73
74This skill provides battle-tested patterns for:
75- **Security isolation** - Contain high-risk operations with minimal context exposure
76- **Specialized research** - Multi-perspective data gathering with domain experts
77- **Phased implementation** - Architecture → Development → Review pipelines
78- **Peer collaboration** - External validation via federated agent network (opt-in)
79- **Cost-aware spawning** - Budget estimation and optimization strategies
80
81## What's New in v2.0
82
83**Advanced Patterns:**
84- Security proxy pattern (blast shield isolation)
85- Researcher specialist pattern (multi-source synthesis)
86- Phased implementation pipeline (architect → coder → reviewer)
87- Peer review integration (bot-to-bot validation)
88- Cost estimation framework (required for spawns >$0.50)
89
90**Templates:**
91- `templates/security-proxy.md` - Isolate untrusted service access
92- `templates/researcher-specialist.md` - Domain-specific research agents
93- `templates/phased-implementation.md` - Multi-phase feature development
94- `templates/peer-review-specialist.md` - External peer validation
95
96**Integration:**
97- task-routing skill (auto-classification and routing)
98- cost-governor (budget enforcement)
99- drift-guard (behavioral validation)
100
101## Quick Start
102
103### 1. Install Skill Structure
104```bash
105cd $OPENCLAW_WORKSPACE/skills/subagent-architecture
106bash setup.sh # Creates directories and scaffolding
107```
108
109### 2. Choose Your Pattern
110
111**For high-risk operations:**
112```bash
113# Read security-proxy template
114cat templates/security-proxy.md
115
116# Spawn isolated proxy for untrusted API
117# (see template for full example)
118```
119
120**For research tasks:**
121```bash
122# Read researcher-specialist template
123cat templates/researcher-specialist.md
124
125# Spawn domain expert for deep analysis
126# (see template for multi-perspective pattern)
127```
128
129**For complex features:**
130```bash
131# Read phased-implementation template
132cat templates/phased-implementation.md
133
134# Launch architect → coder → reviewer pipeline
135# (see template for orchestration example)
136```
137
138**For external validation:**
139```bash
140# Read peer-review-specialist template
141cat templates/peer-review-specialist.md
142
143# Request peer agent review via Discord/API
144# (see template for federated trust protocol)
145```
146
147## Agent Registry: AGENTS.md is Optional
148
149**Critical clarification for new users:** AGENTS.md is a human-readable reference document, not a configuration file. The spawning system does not read it.
150
151### How spawning actually works
152
153`sessions_spawn` is a tool call — it takes parameters you provide at the moment of the call. It does not read from any file, config, or registry. You can spawn subagents on a completely fresh OpenClaw install with zero files in your workspace.
154
155```javascript
156// This is ALL the system needs — no AGENTS.md required
157sessions_spawn({
158 label: "my-researcher",
159 task: "Research the topic X",
160 model: "sonnet"
161})
162```
163
164### What AGENTS.md actually is
165
166AGENTS.md (and domain files like AGENTS_WRITING.md, AGENTS_INFRA.md) are **memory aids for you (the agent)**. They store:
167- Agent names and personality snippets you've found effective
168- Cost history and last-used dates
169- Notes on what tasks each agent type handles well
170
171You can split AGENTS.md into 50 domain files or delete it entirely — spawning still works. The split is purely for your readability; it has zero functional effect.
172
173### What "read AGENTS_WRITING.md before spawning" means
174
175When documentation says *"read AGENTS_WRITING.md before spawning AuthorAgent"*, it means:
176
177> Read it so **you** know what personality, model, and task description to use when building the spawn call.
178
179The system does not read it. You read it, extract the configuration, then make the spawn call with those parameters.
180
181### Practical implication for fresh installs
182
183When you install this skill on a fresh OpenClaw setup:
184
1851. **You do not need to create AGENTS.md** to use subagents
1862. Start spawning immediately with inline parameters
1873. Create AGENTS.md when you have enough recurring agent configurations that you want a reference doc
1884. Split into domain files when AGENTS.md grows beyond ~10 entries and becomes hard to scan
189
190See `templates/agents-registry-template.md` for a minimal starter template when you're ready.
191
192---
193
194## Reference Implementations
195
196**NEW in v2.1:** Production-ready code libraries for all patterns.
197
198### Available Libraries
199
200**lib/spawn-security-proxy.js** - Security isolation framework
201- `spawnSecurityProxy(config)` - Spawn isolated proxy with sanitization
202- `deepSanitize(data)` - Remove sensitive data (API keys, paths, emails)
203- `validateSchema(data, schema)` - JSON schema validation
204- `createDefaultSchema(type)` - Common output schemas (list, single, status)
205
206**lib/spawn-researcher.js** - Multi-perspective research framework
207- `spawnResearcher(config)` - Spawn domain expert researcher
208- `spawnMultiPerspective(config)` - Multi-perspective research (optimist/pessimist/pragmatist)
209- `assessSourceCredibility(source)` - Score source trustworthiness (0-100)
210- Pre-configured trusted/blog/vendor domain lists
211
212**lib/cost-estimator.js** - Cost estimation and tracking
213- `estimateSubagentCost(params)` - Pre-spawn cost estimation with confidence intervals
214- `logSubagentCost(label, estimate, actual)` - Log for accuracy tracking
215- `recalibrateEstimator()` - Monthly accuracy improvement
216- `getPatternHistory(pattern)` - Historical performance analysis
217- `getCostTier(cost)` - Classify as micro/small/medium/large
218
219**lib/quality-scorer.js** - Output quality assessment
220- `scoreSubagentOutput(output, rubric)` - 8-dimension quality scoring
221- `createScoringTemplate()` - Manual review template
222- `selfAuditChecklist(output)` - Pre-delivery validation
223- Rubric dimensions: specificity, actionability, evidence, structure, completeness, clarity, relevance, efficiency
224
225### Usage Examples
226
227All libraries include complete working examples:
228
229```bash
230# Security proxy examples
231node examples/security-proxy-usage.js
232
233# Researcher examples
234node examples/researcher-usage.js
235
236# Cost estimation examples
237node examples/cost-estimation-demo.js
238```
239
240### Quick Integration
241
242> **Path Resolution Note:** The `require()` paths in examples below assume you call them from your workspace root. If you call from within the skill directory (e.g., inside an example script), use `__dirname` instead. For portable code that works regardless of cwd:
243>
244> ```javascript
245> // Path resolution — works regardless of workspace structure
246> const path = require('path');
247> const SKILL_DIR = __dirname; // when called from within skill directory
248> // OR if calling from workspace root:
249> const SKILL_DIR = path.join(process.env.OPENCLAW_WORKSPACE || process.cwd(), 'skills', 'subagent-architecture');
250> const { spawnSecurityProxy } = require(path.join(SKILL_DIR, 'lib', 'spawn-security-proxy'));
251> ```
252
253```javascript
254// Example: Spawn security proxy for untrusted API
255const { spawnSecurityProxy } = require('./skills/subagent-architecture/lib/spawn-security-proxy');
256
257const result = await spawnSecurityProxy({
258 service: 'weather-api',
259 task: 'Get current weather for New York',
260 query: { city: 'New York', units: 'metric' },
261 output_schema: {
262 type: 'object',
263 properties: {
264 temperature: { type: 'number' },
265 conditions: { type: 'string' }
266 }
267 },
268 spawn_fn: async (config) => {
269 // Your actual sessions_spawn call here
270 return await sessions_spawn(config);
271 }
272});
273
274// Example: Estimate cost before spawning
275const { estimateSubagentCost, logSubagentCost } = require('./skills/subagent-architecture/lib/cost-estimator');
276
277const estimate = estimateSubagentCost({
278 task_complexity: 'medium',
279 expected_duration_min: 15,
280 model: 'sonnet',
281 research_required: true
282});
283
284console.log(`Estimated: $${estimate.expected} (range: $${estimate.min}-$${estimate.max})`);
285
286// After spawn completes
287logSubagentCost('researcher-task', estimate, actual_cost);
288
289// Example: Score output quality
290const { scoreSubagentOutput } = require('./skills/subagent-architecture/lib/quality-scorer');
291
292const score = scoreSubagentOutput(subagent_output, null, { auto_score: true });
293console.log(`Quality: ${score.overall_score}/10 (${score.pass ? 'PASS' : 'FAIL'})`);
294```
295
296See `examples/` directory for complete working demonstrations.
297
298## Integration Status
299
300### Dependencies Overview
301
302**Required:**
303- ✅ OpenClaw 2026.2.17+ (`sessions_spawn` API)
304- ✅ Node.js 18+ (for library code)
305
306**Optional Skills:**
307
308**task-routing**
309- Status: ✅ Available (workspace `skills/task-routing/`)
310- Version: 1.0.0+
311- Integration: Auto-classification of incoming tasks, risk scoring, pattern routing
312- Tested: Yes (production since 2026-02-15)
313- Documentation: See `skills/task-routing/SKILL.md`
314
315**cost-governor**
316- Status: ⚠️ Planned (design phase)
317- Version: N/A
318- Integration: Budget enforcement, approval workflows
319- Tested: No
320- Workaround: Use `lib/cost-estimator.js` for manual gating
321
322**drift-guard**
323- Status: ⚠️ Planned (design phase)
324- Version: N/A
325- Integration: Behavioral audits, policy violation detection
326- Tested: No
327- Workaround: Manual output review against rubric
328
329### Library Dependencies
330
331All reference implementations are **dependency-free** (pure Node.js):
332- No npm packages required
333- No external API calls
334- Filesystem access for logging only (optional)
335- Mock-friendly for testing
336
337### Integration Points
338
339**Automatic (via task-routing skill):**
340- Task classification → Pattern recommendation
341- Risk scoring → Security proxy auto-spawn for high-risk tasks
342- Cost estimation → Pre-spawn budget check
343
344**Manual (call libraries directly):**
345- `require()` any lib file and call functions
346- See `examples/` for usage patterns
347- Spawn functions accept custom `spawn_fn` for integration with your sessions_spawn
348
349### Migration Path
350
351**From v2.0 to v2.1:**
3521. No breaking changes - templates still work as-is
3532. New: Import library functions for programmatic use
3543. New: Run examples to see working code
3554. Optional: Integrate with task-routing for automation
356
357**Future (v3.0 with framework improvements):**
358- Per-spawn resource limits (when OpenClaw supports)
359- Bidirectional communication (when OpenClaw supports)
360- Post-mortem tracking (when OpenClaw supports)
361- See "Framework Limitations & v2 Roadmap" section for details
362
363## Core Concepts
364
365### 1. Security Isolation (Blast Shield Philosophy)
366
367**Problem:** Subagents with full workspace access can leak sensitive data to untrusted APIs.
368
369**Solution:** Security proxies receive minimal context, restricted tools, sanitized output.
370
371**Example:**
372```
373Main Agent (full context)
374 │
375 └─ SecurityProxy (minimal context)
376 ├─ Query: "Get weather for New York"
377 ├─ Tools: exec (curl only)
378 ├─ Output: Sanitized JSON (no API metadata)
379 └─ Auto-terminate after single task
380```
381
382**Key principles:**
383- Minimal context (only task parameters, no workspace paths)
384- Tool restrictions (whitelist, not blacklist)
385- Output sanitization (validate schema before returning)
386- Ephemeral execution (no persistent state)
387- Cost cap (< $0.10 per proxy spawn)
388
389See: `templates/security-proxy.md`
390
391### 2. Researcher Specialists (Multi-Source Synthesis)
392
393**Problem:** Generic web search returns surface-level results without domain expertise.
394
395**Solution:** Specialized researchers with domain bias, multi-source validation, actionable synthesis.
396
397**Example:**
398```
399Question: "Should we adopt technology X?"
400
401├─ OptimistResearcher (best-case analysis)
402├─ PessimistResearcher (risk assessment)
403└─ PragmatistResearcher (current reality)
404
405Main Agent synthesizes: Balanced decision tree
406```
407
408**Key principles:**
409- Domain focus (single expertise area per researcher)
410- Multi-source validation (3+ independent sources per claim)
411- Skeptical by default (anti-hype, calls out marketing)
412- Structured output (executive summary + recommendations)
413- Evidence-backed (no speculation, contradictions addressed)
414
415See: `templates/researcher-specialist.md`
416
417### 3. Phased Implementation (Separation of Concerns)
418
419**Problem:** Single-agent implementation mixes design, coding, and validation → tech debt.
420
421**Solution:** Separate architect (design), coder (build), reviewer (validate) phases.
422
423**Example:**
424```
425Feature Request: "Add memory consolidation skill"
426
427Phase 1: SystemArchitect (15min, $0.40)
428 └─ Delivers: IMPLEMENTATION_PLAN.md
429
430Phase 2: CoderAgent (25min, $0.70)
431 └─ Delivers: Working code + tests
432
433Phase 3: ReviewerAgent (10min, $0.30)
434 └─ Delivers: REVIEW_REPORT.md (approval/rejection)
435
436Total: 50min, $1.40, high-quality feature
437```
438
439**Key principles:**
440- Architects optimize long-term (not quick hacks)
441- Coders focus on working code (test after each step)
442- Reviewers provide fresh perspective (catch integration issues)
443- Incremental delivery (small PRs, easy rollback)
444- Cost-aware (skip phases for simple features)
445
446See: `templates/phased-implementation.md`
447
448### 4. Peer Collaboration (Federated Trust)
449
450**Problem:** Your agent may have blindspots or lack domain expertise.
451
452**Solution:** Request external validation from trusted peer agents.
453
454**Example:**
455```
456Your Agent
457 │
458 ├─ Prepares sanitized review package
459 │
460 ├─ Contacts Smith's SecurityBot (via Discord/API)
461 │ └─ Smith's bot spawns SecurityReviewer
462 │ └─ Returns: Structured findings
463 │
464 └─ Integrates feedback (fix critical issues)
465```
466
467**Key principles:**
468- Trust earned (track peer accuracy over time)
469- Data sanitization (remove secrets, personal data)
470- Structured feedback (severity, category, recommendations)
471- Reciprocal reviews (offer your expertise to peers)
472- Cost-effective (free peer reviews vs paid audits)
473
474**⚠️ Trust tier ≠ security bypass:**
475If you implement tiered trust (Acquaintance → Friend → Ally or equivalent), "higher trust" means relaxed engagement policy — not skipping security validation. Content from even the most trusted peer still goes through injection detection (Stage 4). An ally account can be compromised; the injection scanner is the last defense that can't be socially engineered. "Light validation" always means reduced schema scrutiny, never reduced security scanning.
476
477See: `templates/peer-review-specialist.md`
478
479### 5. Identity Continuity (Ephemeral Process, Persistent External Identity)
480
481**Problem:** Security proxies are ephemeral (spawn-per-task, terminate). But some external services require a persistent identity — a social network account, an API user, a recurring agent persona. These are in tension.
482
483**Solution:** Separate the process lifecycle from the external identity. The process dies every spawn. The external identity persists through workspace state + core-managed credentials.
484
485```
486External service sees: CedarProxy (consistent identity across all spawns)
487
488Under the hood:
489 Spawn 1: [process starts] → reads state files → executes → [process dies]
490 Spawn 2: [new process] → reads same state files → continues → [dies]
491 Spawn 3: [new process] → reads same state files → continues → [dies]
492
493State that persists: /proxy-workspace/ files (logs, relationships, posts)
494State that doesn't: in-memory session, conversation history, token
495Credentials: held by core, passed as short-lived scoped token at spawn time
496```
497
498**Key rules:**
499- Credentials live in core memory only — never in proxy workspace files
500- Session token: short TTL (2 hours max), passed encrypted in task context, never written to disk
501- Consistency: core injects "recent context" summary (last N interactions) into each spawn's task description so the new process knows what prior spawns committed to
502- Token rotation: scheduled by core (e.g., weekly), not the proxy
503
504**Anti-pattern:** storing tokens in `[workspace]/config.json` — if the proxy workspace is compromised, credentials should not be compromised with it.
505
506### 6. Research Team (Parallel Multi-Lens Analysis)
507
508**Problem:** Single-agent analysis has blind spots — the same agent proposes and evaluates its own ideas.
509
510**Solution:** Spawn 3 specialist agents in parallel with distinct analytical lenses, then synthesize into one unified response.
511
512**Architecture:**
513```
514High-complexity query
515 │
516 ├─ Critic lens (find flaws, risks, costs — no solutions)
517 ├─ Implementer lens (concrete execution, architecture, feasibility)
518 └─ Synthesizer lens (integrate, resolve tensions, unified path)
519 │
520 UnifierAgent (one clean final response)
521```
522
523**When to use:**
524- Task complexity === 'high' OR explicit research flag set
525- Architecture decisions with real tradeoffs
526- Debugging where root cause is unclear
527- Any question where a single perspective tends to miss things
528
529**When to skip:**
530- Routine tasks, simple lookups, quick fixes
531- Cost-sensitive situations (research team = ~4x single-agent cost)
532
533**Key components:**
534- `lib/team-chatroom.js` — append-only JSONL shared memory between parallel agents
535- `lib/research-coordinator.js` — builds task strings for each lens + UnifierAgent
536- `shouldUseResearchTeam(complexity, explicitFlag)` — gate function
537- `buildResearchTeam(query)` — returns sessionId + 3 specialist task objects
538- `buildUnifierTask(query, sessionId)` — builds synthesis prompt from chatroom
539- `checkLensCompletion(sessionId)` — verifies all lenses posted before unifying
540
541**Lens discipline:**
542- Each lens gets a distinct role description injected into its prompt
543- Lenses do NOT communicate with each other — only through the chatroom
544- UnifierAgent reads all lens outputs and produces ONE response
545- If a lens fails silently, UnifierAgent warns but synthesizes from available data
546
547**Cost:** ~4x single-agent. Gate on complexity to control spend.
548
549**Critical rule:** Grok or any external model used as a lens is a leaf node — it answers, it never spawns further agents.
550
551See: `lib/research-coordinator.js` for reference implementation.
552
553### 7. External Model Consultation
554
555**Problem:** Your agent may have architectural blind spots that another model's reasoning style would catch. Human relay (copy/paste to another AI) is slow and lossy.
556
557**Solution:** Spawn an ExternalConsultAgent subagent that calls an external model's API directly, persists the session, and returns the response.
558
559**Architecture:**
560```
561Core agent decides consultation needed
562 │
563 └─ ExternalConsultAgent subagent
564 ├─ Calls external API (Grok, OpenAI, etc.)
565 ├─ Injects system-level intent for alignment
566 ├─ Supports session continuity (sessionId)
567 └─ Returns response + sessionId
568```
569
570**Why subagent, not core agent:**
571External API calls are side effects with cost and data exposure implications. Isolating them in a subagent follows the blast-shield philosophy — if something goes wrong, it's contained.
572
573**Key components:**
574- `lib/external-bridge.js` — session management, task string builder, consultation logger
575- `memory/external-agents.json` — provider config (model IDs, endpoints)
576- `memory/external-sessions/` — persistent session files for conversation continuity
577- `lib/external-consult-helper.js` — `shouldAutoConsult()` gate (RED drift + high complexity + 24h cooldown)
578
579**Auto-consult gate (3 conditions, all required):**
5801. Intent drift level === 'RED'
5812. Task complexity === 'high'
5823. Last consultation > 24 hours ago (with lock file to prevent race conditions)
583
584**Security rules (enforce before go-live):**
585- External model is a leaf node — never triggers further spawns
586- Context sanitization before every call — strip API keys, file contents, internal paths
587- Session-level call cap (prevent fan-out)
588- Metadata logging of every call (timestamp, provider, trigger reason)
589- Key stored in environment variable, not config file
590
591**Session continuity:**
592Pass `sessionId` from a previous consultation to continue the conversation. The bridge injects prior message history automatically.
593
594See: `lib/external-bridge.js` for reference implementation.
595
596### 8. Intent Engineering (Value Alignment over Time)
597
598**Problem:** Prompt engineering tells agents *what to do*. Context engineering tells agents *what to know*. Neither tells agents *what to want* — so they drift from user values over time without detection.
599
600**Solution:** A three-layer system that encodes agent intent, extracts intent signals from user behavior, and detects drift before it becomes a problem.
601
602**Three layers:**
6031. **Intent Manifest** (`memory/intent-manifest.json`) — Machine-readable intent spec per agent: core purpose, hard constraints (with regex), operational goals with verification keywords, user signals extracted from history
6042. **Intent Extractor** (`lib/intent-extractor.js`) — Weekly pass over episode history extracting preference/value/correction signals; decays old signals (rate: 0.975/week), prunes below 0.30 strength
6053. **Drift Detector** (`lib/intent-drift-detector.js`) — 5-component score per episode: hard constraint violations (0.35), goal keyword coverage (0.25), structural drift via Jaccard (0.20), correction pressure (0.15), forbidden phrase hits (0.05)
606
607**Drift levels:**
608- GREEN (< 0.29): Normal operation
609- YELLOW (0.29–0.48): Inject reminder next turn
610- ORANGE (0.48–0.68): Log + prepare summary
611- RED (≥ 0.68): Flag for user check-in (triggers auto-consult gate)
612
613**Intent manifest schema:**
614```json
615{
616 "system": {
617 "core_purpose": "...",
618 "hard_constraints": [{"id": "...", "rule": "...", "regex": "..."}],
619 "operational_goals": [{"id": "...", "description": "...", "verification_keywords": [], "weight": 0}]
620 },
621 "agents": {
622 "AgentName": {
623 "inherits": true,
624 "overrides": {
625 "core_purpose": "...",
626 "operational_goals": [],
627 "user_signals": []
628 },
629 "version": "YYYY-MM-DD.001"
630 }
631 },
632 "diff_log": []
633}
634```
635
636**Key properties:**
637- System intent + agent overrides use deep merge — agents inherit system constraints
638- User signals decay weekly — recent corrections weighted higher
639- Operational goals are hand-authored for v1; intent compression auto-suggests additions in v2
640- Manifest is diffable over time (diff_log tracks changes)
641- Drift score adjusts confidence estimator: `score *= (1 - drift.score * 0.3)`
642
643**Cold start:** Works on day 1 with hand-authored goals. Signals accumulate automatically.
644
645See: `lib/intent-manager.js`, `lib/intent-extractor.js`, `lib/intent-drift-detector.js` for reference implementation.
646
647### 5. Cost-Aware Spawning
648
649**Problem:** Uncontrolled subagent spawning leads to budget overruns.
650
651**Solution:** Estimate cost before spawning, require approval for expensive operations.
652
653**Framework:**
654```javascript
655// Pre-spawn cost estimation
656const estimate = estimateSubagentCost({
657 task_complexity: "high", // simple/medium/high
658 expected_duration_min: 20,
659 model: "sonnet", // haiku/sonnet/opus
660 research_required: true
661})
662
663// estimate = { min: $0.60, max: $1.20, confidence: 0.8 }
664
665if (estimate.max > 0.50) {
666 // Log to cost tracking
667 await logCostEstimate("task-label", estimate)
668
669 if (estimate.max > 2.00) {
670 // Require human approval
671 await requestApproval(estimate)
672 }
673}
674
675// Spawn subagent
676const result = await spawnSubagent(...)
677
678// Track actual cost
679await logActualCost("task-label", result.cost)
680```
681
682**Cost tiers:**
683- **Micro** (< $0.10): Simple lookups, fact-checking
684- **Small** ($0.10-0.50): Standard research, code review
685- **Medium** ($0.50-2.00): Feature implementation, deep analysis
686- **Large** (> $2.00): Complex refactors, multi-phase projects
687
688**Optimization strategies:**
689- Use haiku for simple tasks (3x cheaper than sonnet)
690- Parallelize independent operations
691- Cache research findings for reuse
692- Skip optional phases (reviewer for low-risk changes)
693
694## Directory Structure
695
696```
697subagents/
698├── [specialist-name]/
699│ ├── SPECIALIST.md # Agent definition and personality
700│ ├── knowledge-base/ # Reference materials
701│ └── research/ # Task outputs and findings
702└── _archived/ # Retired subagents
703
704skills/subagent-architecture/
705├── SKILL.md # This file
706├── templates/
707│ ├── security-proxy.md
708│ ├── researcher-specialist.md
709│ ├── phased-implementation.md
710│ └── peer-review-specialist.md
711└── setup.sh # Directory scaffolding script
712```
713
714## When to Use Each Pattern
715
716### Security Proxy
717**Use when:**
718- Accessing untrusted APIs or experimental services
719- Risk score > 70 (high blast radius or irreversibility)
720- Data needs sanitization before main agent sees it
721- Cost estimate < $0.10 (lightweight proxy)
722
723**Skip when:**
724- Trusted first-party APIs (your infrastructure)
725- Read-only public data (Wikipedia, documentation)
726- Risk score < 30 (low stakes)
727
728### Researcher Specialist
729**Use when:**
730- Question requires 10+ sources
731- Domain expertise needed (not general knowledge)
732- Multiple conflicting claims (need fact-checking)
733- Deliverable is a decision (not just information)
734- Cost estimate > $0.20 (worth specialist analysis)
735
736**Skip when:**
737- Simple factual lookup (single authoritative source)
738- Real-time data (weather, stock prices)
739- Cost estimate < $0.10 (not worth overhead)
740
741### Phased Implementation
742**Use when:**
743- Feature touches 3+ files
744- Requires integration with existing systems
745- Cost estimate > $1.00 (worth upfront design)
746- Failure would be expensive (need rollback plan)
747- Long-term maintainability matters
748
749**Skip when:**
750- Simple script (1 file, no integration)
751- Well-understood pattern (copying existing structure)
752- Prototype/experiment (might throw away)
753- Cost estimate < $0.50 (faster to just build)
754
755### Peer Review
756**Use when:**
757- High stakes (security, legal, financial)
758- Domain gap (no internal specialist)
759- Bias check (fresh perspective needed)
760- Complex validation (multi-dimensional review)
761
762**Skip when:**
763- Low stakes (documentation, styling)
764- Domain expertise available internally
765- Fast turnaround required (peer may take hours/days)
766- Sensitive data (can't sanitize for external review)
767
768## Integration with Task Routing
769
770**Automatic pattern selection** via task-routing skill:
771
772```yaml
773# config/routing-rules.yaml
774pattern_routing:
775 security_proxy:
776 triggers:
777 - blast_radius > 70
778 - untrusted_api: true
779 max_cost: 0.10
780
781 researcher_specialist:
782 triggers:
783 - task_type: research
784 - complexity > 50
785 min_sources: 3
786
787 phased_implementation:
788 triggers:
789 - task_type: code_gen
790 - files_affected > 3
791 - cost_estimate > 1.00
792 phases: [architect, coder, reviewer]
793
794 peer_review:
795 triggers:
796 - irreversibility > 80
797 - domain_gap: true
798 require_approval: true
799```
800
801**Manual override:**
802```javascript
803// Force specific pattern
804spawnSubagent({
805 pattern: "security-proxy", // override routing decision
806 task: "...",
807 justification: "Experimental API, prefer isolation"
808})
809```
810
811## Cost Tracking & Optimization
812
813### Logging Requirements
814
815All subagent spawns >$0.50 must be logged to `notes/cost-tracking.md`:
816
817```markdown
818## Subagent Cost Tracking
819
820| Date | Label | Pattern | Estimate | Actual | Delta | Notes |
821|------|-------|---------|----------|--------|-------|-------|
822| 2026-02-22 | architect-feature-x | phased-impl | $0.40 | $0.38 | -5% | Faster than expected |
823| 2026-02-22 | coder-feature-x | phased-impl | $0.70 | $0.85 | +21% | Complex refactor, used opus |
824| 2026-02-22 | researcher-market | researcher | $0.60 | $0.55 | -8% | Cached sources helped |
825```
826
827### Accuracy Improvement
828
829Track estimate vs actual to improve future predictions:
830```javascript
831// Calculate rolling accuracy
832const accuracy = calculateAccuracy({
833 window_days: 30,
834 min_samples: 10
835})
836
837// accuracy = { mean_error: 12%, confidence: 0.85 }
838
839// Adjust future estimates
840const adjusted_estimate = base_estimate * (1 + accuracy.mean_error)
841```
842
843## Quality Standards
844
845### Subagent Output Rubric
846
847All specialist subagents should score 7+ on this rubric:
848
849| Dimension | Poor (1-3) | Good (4-6) | Excellent (7-10) |
850|-----------|------------|------------|------------------|
851| **Specificity** | Vague generalizations | Some concrete details | Precise, actionable specifics |
852| **Actionability** | No clear next steps | Suggestions provided | Step-by-step implementation plan |
853| **Evidence** | Unsourced claims | Some citations | Every claim sourced, validated |
854| **Structure** | Stream-of-consciousness | Basic organization | Scannable hierarchy, summaries |
855| **Completeness** | Missing key aspects | Most areas covered | Comprehensive, gaps documented |
856| **Honesty** | Hides limitations | Mentions some trade-offs | Explicit about unknowns, risks |
857| **Cost-awareness** | No budget consideration | Rough estimates | Detailed cost/benefit analysis |
858| **Integration** | Ignores existing systems | Basic compatibility | Seamless integration plan |
859
860### Self-Audit Checklist
861
862Before finalizing subagent output:
863- [ ] Every claim has source (URL + date)
864- [ ] Contradictions addressed (not ignored)
865- [ ] Recommendations include trade-offs
866- [ ] Cost estimate provided (time + money)
867- [ ] Integration points documented
868- [ ] Rollback strategy included
869- [ ] Success criteria defined
870- [ ] Known limitations listed
871
872## Philosophy
873
874### Permanent vs Ephemeral
875
876**Permanent subagents** (skill-based):
877- Recurring specialized tasks
878- Deep domain expertise
879- Knowledge accumulation over time
880- Examples: DevOps, AuthorAgent, WuxiaWorldbuilder
881
882**Ephemeral subagents** (one-off spawns):
883- Bounded research tasks
884- Simple implementation work
885- Experimental exploration
886- Pattern-based specialists (security-proxy, researcher)
887
888### Anti-Sycophant by Default
889
890All subagents should:
891- Call out weak evidence (no polite agreement)
892- Reject unrealistic requirements (push back on bad specs)
893- Highlight risks honestly (no sugar-coating)
894- Admit knowledge gaps (no speculation to please)
895
896### Cost-Conscious Operation
897
898- Estimate before spawning (no surprise bills)
899- Choose appropriate model (haiku vs sonnet vs opus)
900- Parallelize when possible (save time = save money)
901- Cache and reuse (research findings, architecture patterns)
902- Terminate early if stuck (don't spin wheels for 30min)
903
904## Dependencies
905
906### Required
907- OpenClaw 2026.2.17+ (subagent spawning, cost tracking)
908
909### Optional but Recommended
910- **task-routing** skill (auto-pattern selection, risk scoring)
911- **cost-governor** skill (budget enforcement, approval workflows)
912- **drift-guard** skill (behavioral validation, quality audits)
913
914### Integration Points
915
916**Task routing:**
917- Provides task classification (8 types)
918- Risk scoring (5 dimensions, 0-100 scale)
919- Auto-route to pattern (security-proxy, researcher, phased-impl)
920
921**Cost governor:**
922- Pre-spawn approval for expensive operations
923- Budget tracking per project/feature
924- Alert on overruns
925
926**Drift guard:**
927- Behavioral audit of subagent outputs
928- Policy violation detection
929- Quality score trending
930
931## Framework Limitations & v2 Roadmap
932
933**Known gaps identified in peer review (Agent Smith, EasyClaw project)**
934
935Current OpenClaw subagent framework has architectural limitations that affect all patterns in this skill. These are framework-level constraints, not skill-specific issues. Documenting for transparency and future improvement.
936
937### 1. Spawn Configuration Constraints
938
939**Smith's Question:** *"How does core define sub-bot constraints before launch?"*
940
941**Current State:**
942- Spawn parameters: `task`, `personality`, `model`, `timeout`, `label`
943- Basic configuration only (what to do, how long)
944- No granular resource controls
945
946**Limitations:**
947- ❌ No memory limits per spawn (subagent can consume unlimited RAM)
948- ❌ No API call quotas (can make 1000s of web requests)
949- ❌ No disk space caps (can fill storage)
950- ❌ No per-spawn tool restrictions (tool policy is framework-level, applies to all subagents)
951
952**Current Workaround:**
953- Manual timeout enforcement (kill after N minutes)
954- Framework-level tool policies (same restrictions for all subagents)
955- Post-spawn monitoring (watch logs, intervene manually)
956
957**v2 Design Considerations:**
958```javascript
959// Proposed: Granular per-spawn constraints
960spawnSubagent({
961 label: "researcher-x",
962 task: "Research topic",
963 constraints: {
964 max_memory_mb: 512, // Kill if exceeds RAM limit
965 max_api_calls: 50, // Deny further requests after quota
966 max_disk_mb: 100, // Block file writes beyond limit
967 max_cost_usd: 0.50, // Auto-terminate if cost projection exceeds
968 tools_allowed: ["web_search", "web_fetch"], // Per-spawn tool whitelist
969 tools_denied: ["exec", "write"], // Explicit blacklist
970 rate_limits: {
971 web_search: { calls: 10, window_seconds: 60 } // Max 10 searches/min
972 }
973 }
974})
975```
976
977**Impact on Patterns:**
978- **Security proxy:** Could enforce strict tool whitelist per proxy (currently manual)
979- **Researcher:** Could cap API calls to prevent runaway research loops
980- **Phased impl:** Could allocate different budgets per phase (architect: $0.40, coder: $1.00)
981
982### 2. Skill Loading & Validation
983
984**Smith's Question:** *"How are skills validated before execution?"*
985
986**Current State:**
987- External skills (downloaded) → `skill-vetter` checks metadata, malicious patterns
988- Internal skills (workspace) → Just execute (trusted by default)
989- No runtime sandboxing
990
991**Limitations:**
992- ❌ No code isolation for skills (skill code runs in main agent context)
993- ❌ No execution validation (skill can do anything agent can do)
994- ❌ No capability restrictions (skill inherits all agent tools)
995- ❌ Trust model: Binary (external = vet, internal = trust)
996
997**Current Workaround:**
998- Vet external skills manually before first use
999- Review internal skill code (human audit)
1000- Hope skills don't misbehave
1001
1002**v2 Design Considerations:**
1003```javascript
1004// Proposed: Skill capability manifest
1005// skills/my-skill/SKILL.md
1006---
1007capabilities_required:
1008 - web_search # Skill needs web access
1009 - read:config/ # Can read config directory only
1010 - write:output/ # Can write to output directory only
1011isolation_level: sandbox # Run in isolated context
1012max_execution_time: 30 # Kill after 30 seconds
1013---
1014
1015// Runtime: Skill runs in sandbox with only declared capabilities
1016// Attempts to use undeclared tools → blocked, logged, skill terminated
1017```
1018
1019**Impact on Patterns:**
1020- **Security proxy:** Skills could be sandboxed (currently rely on manual isolation)
1021- **All patterns:** Skills loaded by subagents would inherit spawn constraints
1022- **Peer review:** External skills from peers could run safely (sandboxed)
1023
1024### 3. Communication Bounds (Bidirectional Channel)
1025
1026**Smith's Question:** *"What can sub-bots ask for from core?"*
1027
1028**Current State:**
1029- **One-way communication only:** Core spawns → Subagent executes → Returns result
1030- Subagent cannot request clarification mid-task
1031- Subagent cannot request additional context during execution
1032- No interactive mode
1033
1034**Limitations:**
1035- ❌ Subagent stuck on ambiguous requirement → Must guess or fail
1036- ❌ Subagent needs additional context → Can't ask, works with what it has
1037- ❌ Subagent encounters unexpected scenario → No escalation path mid-task
1038- ❌ Human approval needed mid-execution → Not possible (only pre/post spawn)
1039
1040**Current Workaround:**
1041- Over-specify context in initial spawn (bloated prompts)
1042- Subagent makes best guess (may be wrong)
1043- Subagent fails, core respawns with clarification (expensive)
1044
1045**v2 Design Considerations:**
1046```javascript
1047// Proposed: Request-response protocol during execution
1048// Subagent code:
1049const clarification = await requestFromCore({
1050 type: "clarification",
1051 question: "User said 'recent data' - how many days back?",
1052 options: ["7 days", "30 days", "90 days"],
1053 timeout_seconds: 60 // If no response, default to first option
1054})
1055
1056// Core receives request:
1057// - Auto-approve safe requests (data lookup from memory)
1058// - Escalate to human for decisions
1059// - Return answer to subagent
1060// - Subagent continues with clarification
1061
1062// Examples:
1063// - "Need API key for service X" → Core provides from secure store
1064// - "Found conflicting data, which source to trust?" → Human decides
1065// - "Task seems too expensive ($5 estimated), proceed?" → Approval workflow
1066```
1067
1068**Impact on Patterns:**
1069- **Researcher:** Can ask "should I dig deeper on this tangent?" mid-research
1070- **Phased impl:** Coder can ask architect for design clarification during build
1071- **Security proxy:** Can request human approval if API returns unexpected data
1072- **All patterns:** Reduces over-specification, enables adaptive execution
1073
1074### 4. Termination Conditions (Resource-Based Kills)
1075
1076**Smith's Question:** *"When does core kill a sub-bot?"*
1077
1078**Current State:**
1079- **Time-based only:** Timeout (specified in spawn) or task completion
1080- Manual intervention (human stops runaway agent)
1081- No automatic resource-based termination
1082
1083**Limitations:**
1084- ❌ No memory limit kills (agent can OOM the host)
1085- ❌ No cost threshold kills (can exceed budget before timeout)
1086- ❌ No stuck detection (infinite loops run until timeout)
1087- ❌ No output size limits (can generate gigabytes of text)
1088
1089**Current Workaround:**
1090- Set conservative timeouts (may kill productive work early)
1091- Monitor logs manually (reactive, not proactive)
1092- Hope agent doesn't get stuck in expensive loop
1093
1094**v2 Design Considerations:**
1095```javascript
1096// Proposed: Multi-condition termination
1097spawnSubagent({
1098 label: "researcher-x",
1099 task: "Research topic",
1100 termination: {
1101 // Existing
1102 timeout_minutes: 20,
1103
1104 // New: Resource limits
1105 max_memory_mb: 512, // Kill if RSS > 512MB
1106 max_cost_usd: 1.00, // Kill if projected cost > $1
1107 max_output_tokens: 10000, // Kill if response > 10k tokens
1108
1109 // New: Behavioral detection
1110 stuck_detection: {
1111 enabled: true,
1112 same_action_threshold: 5, // Kill if repeats same tool call 5x
1113 no_progress_minutes: 5 // Kill if no new output for 5min
1114 },
1115
1116 // New: External triggers
1117 kill_signal: "session:parent_terminated" // Kill if parent agent dies
1118 }
1119})
1120
1121// Termination reasons logged for analysis:
1122// - "timeout" (existing)
1123// - "memory_exceeded" (new)
1124// - "cost_exceeded" (new)
1125// - "stuck_loop_detected" (new)
1126// - "output_overflow" (new)
1127// - "parent_died" (new)
1128```
1129
1130**Impact on Patterns:**
1131- **Security proxy:** Strict resource limits (memory, cost) prevent runaway isolation breaches
1132- **Researcher:** Stuck detection prevents infinite search loops
1133- **Phased impl:** Cost limits per phase (architect can't blow whole budget)
1134- **All patterns:** Better cost control, faster failure detection
1135
1136### 5. Post-Mortem & Learning System
1137
1138**Smith's Question:** *"How do you learn from sub-bot failures?"*
1139
1140**Current State:**
1141- **Success-only logging:** Add to `AGENTS.md` after successful spawns
1142- Manual failure review (check logs, wonder what happened)
1143- No systematic failure tracking
1144- No pattern analysis
1145
1146**Limitations:**
1147- ❌ No failure tracking (only successes logged to AGENTS.md)
1148- ❌ No common failure pattern detection (same mistake repeated)
1149- ❌ No cost vs value analysis (did expensive agent deliver value?)
1150- ❌ No success rate per agent type (which specialists are reliable?)
1151- ❌ No improvement feedback loop (failures don't inform future spawns)
1152
1153**Current Workaround:**
1154- Human remembers failures (unreliable)
1155- Manually check logs when something seems off
1156- Anecdotal learning ("that researcher failed last time")
1157
1158**v2 Design Considerations:**
1159```javascript
1160// Proposed: Systematic post-mortem database
1161// Storage: memory/subagent-postmortems.jsonl
1162
1163{
1164 "spawn_id": "researcher-market-20260222-1430",
1165 "label": "researcher-market",
1166 "pattern": "researcher-specialist",
1167 "outcome": "failure", // success | partial | failure
1168 "termination_reason": "cost_exceeded",
1169 "stats": {
1170 "duration_minutes": 18,
1171 "cost_actual": 1.25,
1172 "cost_estimate": 0.60,
1173 "cost_accuracy": -108%, // Overran by 108%
1174 "tokens_used": 45000,
1175 "api_calls": 127
1176 },
1177 "deliverable_quality": null, // Not rated (failed before completion)
1178 "failure_mode": {
1179 "category": "runaway_research", // Taxonomy of failures
1180 "root_cause": "No stuck detection, research loop on tangent",
1181 "human_notes": "Researched sub-topic for 15min, didn't return to main question"
1182 },
1183 "lessons": [
1184 "Add stuck detection for researcher pattern",
1185 "Improve cost estimation for multi-source research (was 2x off)"
1186 ]
1187}
1188
1189// Analytics queries:
1190// - Success rate by pattern: researcher-specialist = 73% (8/11 succeeded)
1191// - Most common failure mode: cost_exceeded (40% of failures)
1192// - Cost estimation accuracy: researcher pattern = -25% average (underestimates)
1193// - ROI analysis: phased-impl pattern = $2.50 avg cost, 90% success, high value
1194```
1195
1196**Proposed Learning Loop:**
1197```javascript
1198// Before spawning, check historical performance
1199const history = getPatternHistory("researcher-specialist")
1200
1201if (history.success_rate < 0.7) {
1202 console.warn(`⚠️ Pattern has 65% success rate (13/20). Common failure: ${history.top_failure_mode}`)
1203 // Adjust: Add stuck detection, reduce timeout, use cheaper model
1204}
1205
1206if (history.cost_accuracy < -0.3) {
1207 console.warn(`⚠️ Pattern underestimates cost by 35% on average`)
1208 // Adjust: Inflate estimate by 35%
1209 const adjusted_estimate = base_estimate * 1.35
1210}
1211
1212// After completion, log outcome
1213logPostMortem({
1214 spawn_id,
1215 outcome: "success",
1216 quality_score: 8.5, // From rubric
1217 cost_actual: 0.58,
1218 cost_estimate: 0.60,
1219 lessons: ["Worked well, multi-perspective pattern delivered balanced view"]
1220})
1221```
1222
1223**Impact on Patterns:**
1224- **All patterns:** Historical success rates inform spawn decisions
1225- **Cost framework:** Improve estimation accuracy (learn from past errors)
1226- **Quality standards:** Track which patterns consistently deliver high scores
1227- **Pattern evolution:** Retire unreliable patterns, double down on proven ones
1228
1229### Summary: v2 Feature Matrix
1230
1231| Feature | v1 (Current) | v2 (Proposed) | Benefit |
1232|---------|--------------|---------------|---------|
1233| **Spawn constraints** | Timeout only | Memory, cost, quota, tool whitelist | Resource safety |
1234| **Skill isolation** | Trust-based | Sandboxed with capabilities | Security |
1235| **Communication** | One-way | Bidirectional request/response | Adaptive execution |
1236| **Termination** | Time-based | Multi-condition (resource, stuck, cost) | Cost control |
1237| **Post-mortem** | Success-only | Full lifecycle tracking + analytics | Continuous learning |
1238
1239**Current mitigation strategies:**
12401. **Manual monitoring** (watch logs, intervene when needed)
12412. **Conservative estimates** (over-specify context, pad timeouts)
12423. **Pattern discipline** (follow templates strictly to avoid known failure modes)
12434. **Human-in-loop** (approve expensive spawns, review failures manually)
1244
1245**v2 would enable:**
1246- Autonomous resource management (agents self-limit)
1247- Higher confidence spawning (better failure prediction)
1248- Faster iteration (learn from failures automatically)
1249- Fine-grained security (per-spawn, per-skill isolation)
1250
1251**Note for users:**
1252These limitations affect **all subagent patterns** in this skill. The patterns documented here (security-proxy, researcher, phased-impl, peer-review) work within current framework constraints. v2 improvements would enhance safety and reliability, but are **not required** for effective use of these patterns today.
1253
1254**Tracking:** OpenClaw framework issue (conceptual - not filed yet)
1255**Credit:** Agent Smith (EasyClaw peer review, 2026-02-22)
1256
1257## Examples
1258
1259### Example 1: Security-First API Integration
1260
1261**Scenario:** Integrate with untrusted social network API
1262
1263```javascript
1264// Main agent receives request
1265const task = "Fetch user's posts from SocialNetworkX API"
1266
1267// Security proxy pattern
1268const proxy = await spawnSubagent({
1269 label: "proxy-socialnetworkx",
1270 pattern: "security-proxy",
1271 task: "Query SocialNetworkX API for user posts, return sanitized JSON",
1272 context: {
1273 query: "user:$USERNAME, limit:10"
1274 // NO API keys, NO workspace paths
1275 },
1276 tools_allowed: ["exec:curl"],
1277 timeout_minutes: 5,
1278 auto_terminate: true
1279})
1280
1281// proxy returns: [{username, timestamp, content}] - sanitized
1282// Main agent: Safe to process, no raw API exposure
1283```
1284
1285### Example 2: Multi-Perspective Research
1286
1287**Scenario:** Evaluate whether to adopt new framework
1288
1289```javascript
1290// Spawn 3 researchers with different biases
1291const researchers = await Promise.all([
1292 spawnSubagent({
1293 label: "researcher-optimist",
1294 pattern: "researcher-specialist",
1295 task: "Research FrameworkX benefits, best-case adoption scenario",
1296 personality: "Optimistic, highlights opportunities"
1297 }),
1298
1299 spawnSubagent({
1300 label: "researcher-pessimist",
1301 pattern: "researcher-specialist",
1302 task: "Research FrameworkX risks, failure modes, known issues",
1303 personality: "Skeptical, risk-focused"
1304 }),
1305
1306 spawnSubagent({
1307 label: "researcher-pragmatist",
1308 pattern: "researcher-specialist",
1309 task: "Research FrameworkX current state, real-world adoption data",
1310 personality: "Pragmatic, data-driven"
1311 })
1312])
1313
1314// Synthesize: Balanced view with decision criteria
1315const decision = synthesizeResearch(researchers.map(r => r.findings))
1316```
1317
1318### Example 3: Phased Feature Development
1319
1320**Scenario:** Build complex new skill
1321
1322```javascript
1323// Phase 1: Architecture
1324const plan = await spawnSubagent({
1325 label: "architect-skill-x",
1326 pattern: "phased-implementation",
1327 phase: "architect",
1328 task: "Design implementation plan for skill-x with [requirements]",
1329 model: "sonnet"
1330})
1331
1332// Review plan, get approval if expensive
1333if (plan.cost_estimate > 2.00) {
1334 await humanApproval(plan)
1335}
1336
1337// Phase 2: Implementation
1338const implementation = await spawnSubagent({
1339 label: "coder-skill-x",
1340 pattern: "phased-implementation",
1341 phase: "coder",
1342 task: `Implement skill-x per plan: ${plan.path}`,
1343 model: plan.recommended_model
1344})
1345
1346// Phase 3: Review (conditional on risk)
1347if (implementation.risk_level === "high") {
1348 const review = await spawnSubagent({
1349 label: "reviewer-skill-x",
1350 pattern: "phased-implementation",
1351 phase: "reviewer",
1352 task: `Review implementation: ${implementation.path}`,
1353 model: "sonnet"
1354 })
1355
1356 if (!review.approved) {
1357 // Iterate or escalate
1358 }
1359}
1360```
1361
1362### Example 4: Peer Validation
1363
1364**Scenario:** Security audit for payment processing
1365
1366```javascript
1367// Prepare sanitized review package
1368const package = sanitizeForReview({
1369 artifact: readFile("src/payment-processor.js"),
1370 remove: ["API_KEYS", "USER_DATA", "INTERNAL_URLS"]
1371})
1372
1373// Request peer review via Discord
1374await message({
1375 action: "send",
1376 target: "smith-security-bot",
1377 message: `Security review request:\n${JSON.stringify(package)}\n\nFocus: Payment processing, SQL injection, input validation`
1378})
1379
1380// Wait for peer response (auto-announces when received)
1381// Process feedback, fix critical issues, optionally re-submit
1382```
1383
1384## Troubleshooting
1385
1386### Problem: Subagent exceeds cost estimate
1387
1388**Diagnosis:**
1389- Check actual task complexity vs estimate
1390- Review subagent logs for loops or retries
1391- Verify model choice (opus when sonnet would suffice?)
1392
1393**Solutions:**
1394- Improve cost estimation (track actuals, adjust formula)
1395- Add cost cap to spawn config (hard limit)
1396- Use cheaper model for exploratory phase
1397
1398### Problem: Security proxy leaks sensitive data
1399
1400**Diagnosis:**
1401- Audit spawn context (did it include workspace paths?)
1402- Check tool restrictions (was file access allowed?)
1403- Review output sanitization (did schema validation fail?)
1404
1405**Solutions:**
1406- Update security-proxy template checklist
1407- Add automated context sanitization pre-spawn
1408- Implement output schema validation (reject non-conforming data)
1409
1410### Problem: Phased implementation phases conflict
1411
1412**Diagnosis:**
1413- Architect plan unrealistic (coder can't implement)
1414- Coder deviated from plan (reviewer rejects)
1415- Reviewer too strict (perfect is enemy of good)
1416
1417**Solutions:**
1418- Architect: Include feasibility check (can this be built?)
1419- Coder: Flag deviations early (request plan amendment)
1420- Reviewer: Focus on critical issues (don't block on style)
1421
1422### Problem: Peer review unavailable or slow
1423
1424**Diagnosis:**
1425- Peer bot offline or rate-limited
1426- No trusted peers for required domain
1427- Review package too large or unclear
1428
1429**Solutions:**
1430- Maintain backup peer list (2+ per domain)
1431- Fall back to internal review (DevOps, CoderAgent)
1432- Simplify review package (focus on specific question)
1433
1434## Framework Limitations & v2 Roadmap
1435
1436**Known gaps identified in peer review (Agent Smith, EasyClaw - 2026-02-22)**
1437
1438These limitations represent areas where the current OpenClaw subagent framework needs evolution. Documented here for transparency and future development.
1439
1440### 1. Spawn Configuration - Per-Subagent Constraints
1441
1442**Current state:**
1443- Spawn parameters: task description, personality, model, timeout, label
1444- Constraints are framework-level (all subagents share same tool policy)
1445
1446**Missing:**
1447- Memory limits per spawn (prevent individual subagent memory leaks)
1448- API call quotas per spawn (prevent runaway costs)
1449- Disk space caps per spawn (prevent storage exhaustion)
1450- Per-spawn tool restrictions (fine-grained beyond framework allowlist)
1451
1452**v2 Design Consideration:**
1453```javascript
1454sessions_spawn({
1455 task: "...",
1456 constraints: {
1457 maxMemoryMB: 512,
1458 maxAPICalls: 100,
1459 maxDiskMB: 50,
1460 tools: {
1461 allowed: ['read', 'write'],
1462 forbidden: ['exec', 'message'],
1463 restrictions: {
1464 read: { paths: ['/workspace/restricted/'] },
1465 write: { paths: ['/workspace/output/'], maxFileSize: '10MB' }
1466 }
1467 }
1468 }
1469})
1470```
1471
1472**Impact:** Without per-spawn constraints, one rogue subagent can exhaust resources for all others.
1473
1474### 2. Skill Loading - Runtime Validation
1475
1476**Current state:**
1477- External skills: Pre-execution vetting via `skill-vetter` (red flag detection)
1478- Internal skills: Trusted by default, no runtime sandboxing
1479
1480**Missing:**
1481- Runtime sandboxing for skill-embedded code (JavaScript, shell scripts)
1482- Execution validation (verify skill behaves as documented)
1483- Resource monitoring during skill execution
1484
1485**v2 Design Consideration:**
1486```javascript
1487// Sandbox wrapper for skill execution
1488runSkill('ai-writing-humanizer', {
1489 sandbox: {
1490 networkAccess: false, // Block network except allowlisted domains
1491 filesystemAccess: 'readonly', // Read-only except explicit write paths
1492 cpuLimit: '50%', // Prevent CPU monopolization
1493 timeout: 30000 // 30s max execution
1494 },
1495 validate: {
1496 outputSchema: { ... }, // Verify output format
1497 sideEffects: ['writes to /workspace/humanizer/'], // Allowed side effects
1498 noExternalCalls: true // Flag if skill attempts network/exec
1499 }
1500})
1501```
1502
1503**Impact:** Without runtime sandboxing, malicious or buggy skills can compromise core agent.
1504
1505### 3. Communication Bounds - Bidirectional Channels
1506
1507**Current state:**
1508- One-way communication only: Core spawns → Subagent executes → Result returns
1509- Subagents cannot ask clarifying questions during execution
1510
1511**Missing:**
1512- Mid-task clarification requests ("Should I proceed with risky operation?")
1513- Progress updates for long-running tasks (>5min execution)
1514- Dynamic priority adjustment (core can signal "abort" or "expedite")
1515
1516**v2 Design Consideration:**
1517```javascript
1518// Subagent perspective
1519async function executeTask(taskDescription) {
1520 const plan = generatePlan(taskDescription);
1521
1522 if (plan.hasHighRiskOperation()) {
1523 const approval = await askCore({
1524 question: "Plan includes deleting 100 files. Proceed?",
1525 options: ["yes", "no", "show list first"],
1526 timeout: 60000 // 1 min to respond
1527 });
1528
1529 if (approval !== "yes") return { status: "aborted", reason: "user declined" };
1530 }
1531
1532 // Continue with approved plan...
1533}
1534```
1535
1536**Impact:** Without bidirectional channels, subagents must either be overly cautious (ask for everything upfront) or overly bold (proceed with assumptions).
1537
1538### 4. Termination Conditions - Resource-Based Kills
1539
1540**Current state:**
1541- Timeout-based only: Subagent runs until task completes or timeout expires
1542- No resource-based termination
1543
1544**Missing:**
1545- Memory limit kills (terminate if subagent exceeds RAM quota)
1546- Cost threshold kills (terminate if API calls exceed budget)
1547- Stuck detection (infinite loops, deadlocks, recursive spawning)
1548- Runaway output prevention (subagent generating gigabytes of logs)
1549
1550**v2 Design Consideration:**
1551```javascript
1552sessions_spawn({
1553 task: "...",
1554 limits: {
1555 timeout: 600000, // 10 min max
1556 maxMemory: 512, // MB
1557 maxCost: 2.00, // USD
1558 maxOutputSize: 10, // MB
1559 maxToolCalls: 100, // Total tool invocations
1560 stuckDetection: {
1561 enabled: true,
1562 sameToolRepeat: 5, // Flag if same tool called 5+ times consecutively
1563 noProgressTimeout: 120000 // Flag if no output/tool calls for 2 min
1564 }
1565 },
1566 onLimitExceeded: (limit, value) => {
1567 logFailure({ subagent, limit, value });
1568 return { action: 'terminate', notify: 'core' };
1569 }
1570})
1571```
1572
1573**Impact:** Without resource-based kills, subagents can waste budget, exhaust memory, or spin indefinitely.
1574
1575### 5. Post-Mortem - Learning from Failures
1576
1577**Update (v2.1 → v2.2):** A lightweight v0 of post-mortem logging is now implementable without framework changes. The crash report schema defined in `templates/proxy-recovery.md` gives you structured failure data per-spawn. Core reads crash reports and routes them. This covers the "what failed and why" dimension immediately.
1578
1579What still requires framework work (see v2 roadmap below): automated outcome analytics, pattern detection across spawns, success rate tracking. But single-spawn forensics — you can ship that now.
1580
1581**Current state:**
1582- Success logging only: AGENTS.md records completed subagents
1583- No failure tracking or pattern analysis
1584- **Partial exception:** Security proxies using `proxy-recovery.md` pattern get crash reports per spawn
1585
1586**Missing:**
1587- Failure logging (why did subagent fail?)
1588- Common failure patterns (which tasks/agents fail most?)
1589- Cost vs value analysis (was the subagent worth the spend?)
1590- Success rate tracking per agent type (CoderAgent: 85%, ResearchAgent: 92%, etc.)
1591- Improvement loop (adjust spawn parameters based on historical outcomes)
1592
1593**v2 Design Consideration:**
1594```javascript
1595// Automatic post-mortem on subagent completion/failure
1596function logSubagentOutcome(subagent, result) {
1597 const record = {
1598 timestamp: Date.now(),
1599 label: subagent.label,
1600 task: subagent.task,
1601 model: subagent.model,
1602 status: result.status, // 'done', 'timeout', 'error', 'killed'
1603 runtime: result.runtime,
1604 cost: result.totalCost,
1605 tokensUsed: result.totalTokens,
1606 outcome: result.status === 'done' ? 'success' : 'failure',
1607 failureReason: result.error || result.killReason || null,
1608 valueProvided: result.status === 'done' ? assessValue(result) : null
1609 };
1610
1611 appendToLog('memory/subagent-outcomes.jsonl', record);
1612 updateSuccessRates(subagent.label, record.outcome);
1613
1614 if (record.outcome === 'failure') {
1615 analyzeFailurePattern(record); // Flag common failure modes
1616 }
1617}
1618
1619// Quarterly review: Which subagent types are most cost-effective?
1620function analyzeSubagentROI() {
1621 const outcomes = readLog('memory/subagent-outcomes.jsonl');
1622 const byType = groupBy(outcomes, o => extractType(o.label)); // CoderAgent, ResearchAgent, etc.
1623
1624 for (const [type, records] of Object.entries(byType)) {
1625 const successRate = records.filter(r => r.outcome === 'success').length / records.length;
1626 const avgCost = mean(records.map(r => r.cost));
1627 const avgValue = mean(records.filter(r => r.valueProvided).map(r => r.valueProvided));
1628
1629 console.log(`${type}: ${(successRate*100).toFixed(1)}% success, $${avgCost.toFixed(2)} avg cost, ${avgValue.toFixed(1)} avg value`);
1630 }
1631}
1632```
1633
1634**Impact:** Without post-mortem analysis, you repeat failures, can't optimize spawn strategy, and waste budget on low-value subagents.
1635
1636---
1637
1638**Conclusion:**
1639
1640These 5 limitations don't block current usage but represent friction points as subagent usage scales. Prioritize based on pain:
1641
1642- **High priority:** #4 (resource-based kills) - prevents runaway costs
1643- **Medium priority:** #5 (post-mortem) - enables data-driven optimization
1644- **Medium priority:** #1 (per-spawn constraints) - prevents resource exhaustion
1645- **Low priority:** #3 (bidirectional channels) - nice to have for complex tasks
1646- **Low priority:** #2 (skill sandboxing) - current vetting sufficient for trusted sources
1647
1648**Feedback welcome:** If you've hit these limitations in production, share workarounds and pain points via OpenClaw community channels.
1649
1650## Contributing
1651
1652This skill improves through real-world usage. Please contribute:
1653
1654**Pattern refinements:**
1655- Found edge case not covered? Update template
1656- Better cost estimation formula? Share it
1657- New integration point? Document it
1658
1659**New patterns:**
1660- Discovered novel orchestration? Add template
1661- Hybrid approach works better? Explain why
1662- Optimization technique? Include example
1663
1664**Track record:**
1665- Log your subagent spawns (cost, accuracy, outcomes)
1666- Share what worked (and what didn't)
1667- Update rubrics based on production learnings
1668
1669## License
1670
1671MIT - Use freely, modify as needed, share improvements
1672
1673## Changelog
1674
1675### v2.3.0 (2026-02-24)
1676- **Added:** Pattern 6 — Research Team (parallel multi-lens analysis with Critic/Implementer/Synthesizer lenses + UnifierAgent)
1677- **Added:** Pattern 7 — External Model Consultation (ExternalConsultAgent subagent, session persistence, auto-consult gate)
1678- **Added:** Pattern 8 — Intent Engineering Layer (manifest schema, intent extraction, drift detection, 5-component drift score)
1679- **Updated:** Version bump to 2.3.0
1680
1681### v2.2.0 (2026-02-23)
1682- **Added:** Core Concept #5 — Identity Continuity (ephemeral process vs persistent external identity, token handoff pattern, consistency via core-injected recent context, anti-pattern warning)
1683- **Added:** Trust tier ≠ security bypass principle to Peer Collaboration section (Stage 4 injection detection always runs regardless of trust level)
1684- **Added:** `templates/proxy-recovery.md` — crash/recovery pattern (pre-death checklist, crash report schema, core response decision tree, quarantine mode, human notification, re-spawn decision guide)
1685- **Updated:** `templates/security-proxy.md` — full rewrite integrating: 6-stage inbound validation pipeline, Stage 6b outbound semantic leak filter, self-imposed rate limiter + circuit breaker, crash/recovery checklist, identity continuity section, MoltbookProxy as real-world reference implementation
1686- **Updated:** Post-mortem section — notes crash reports from `proxy-recovery.md` are a working v0 of per-spawn forensics (no framework changes required)
1687
1688### v2.0.1 (2026-02-22)
1689- **Added:** Framework Limitations & v2 Roadmap section
1690- **Added:** 5 critical design gaps identified by Agent Smith (EasyClaw peer review)
1691- **Added:** v2 design considerations with code examples for each limitation
1692- **Added:** Priority ranking for addressing limitations
1693
1694### v2.0.0 (2026-02-22)
1695- **Breaking:** Restructured to focus on advanced patterns
1696- **Added:** Security proxy pattern and template
1697- **Added:** Researcher specialist pattern and template
1698- **Added:** Phased implementation pattern and template
1699- **Added:** Peer review pattern and template
1700- **Added:** Cost-aware spawning framework
1701- **Added:** Integration with task-routing, cost-governor, drift-guard
1702- **Updated:** Philosophy section (anti-sycophant, cost-conscious)
1703- **Updated:** Examples (real-world scenarios, not toy problems)
1704- **Removed:** Basic scaffolding (moved to setup.sh)
1705
1706### v1.0.0 (2026-02-21)
1707- Initial release with basic subagent structure
1708- SPECIALIST.md template
1709- Task routing integration basics
1710
1711## Support
1712
1713- **Documentation:** Read templates in `templates/` directory
1714- **Examples:** See AGENTS.md for real-world subagent library
1715- **Issues:** Check EVOLOG.md for known limitations
1716- **Community:** Share patterns via OpenClaw Discord (when federated network launches)