brainwires-agents
Agent orchestration, coordination, and lifecycle management for the Brainwires Agent Framework.
Overview
brainwires-agents provides the multi-agent infrastructure for autonomous task execution. Agents run in a shared pool, communicate through a central hub, coordinate file and resource access via RAII lock guards, and pass through a validation gate before reporting success.
Design principles:
- Async-native — built on
tokio, every lock and message operation is non-blocking - RAII guards — file and resource locks are released automatically when guards drop
- Message-driven — agents coordinate through a broadcast
CommunicationHubwith 50+ typed message variants - Heartbeat liveness — resource locks are validated against operation heartbeats, not fixed timeouts
┌───────────────────────────────────────────────────┐
│ AgentPool │
│ │
spawn ──────► │ TaskAgent ◄──────► CommunicationHub │
│ │ ▲ │
│ ▼ │ │
│ ┌─────────┐ ┌────────────┴──────────┐ │
│ │Execution│ │ AgentMessage (50+) │ │
│ │ Graph │ │ StatusUpdate, Saga, │ │
│ └─────────┘ │ ContractNet, Git ... │ │
│ └───────────────────────┘ │
│ │
│ ┌──────────────┐ ┌───────────────────┐ │
│ │FileLockMgr │ │ResourceLockMgr │ │
│ │(read/write) │ │(build/test/git) │ │
│ └──────────────┘ └───────────────────┘ │
│ │
│ ┌──────────────┐ ┌───────────────────┐ │
│ │Validation │ │OperationTracker │ │
│ │Loop │ │(heartbeat liveness)│ │
│ └──────────────┘ └───────────────────┘ │
└───────────────────────────────────────────────────┘
Quick Start
Add to your Cargo.toml:
[]
= "0.1"
Spawn a task agent via the pool:
use Arc;
use *;
use Task;
let hub = new;
let locks = new;
let pool = new;
let agent_id = pool.spawn_agent.await?;
let result = pool.await_completion.await?;
println!;
Features
| Feature | Default | Description |
|---|---|---|
native |
Yes | Git worktree management (git2) and process liveness checking (libc) |
wasm |
No | WebAssembly-compatible build (disables native-only functionality) |
tools |
No | Kept for backward compatibility; brainwires-tool-system is always available |
reasoning |
No | Named reasoning strategies (ReAct, Reflexion, CoT, ToT) and local inference |
eval |
No | Evaluation framework (trials, adversarial, regression, stability) |
otel |
No | OpenTelemetry span export for agent execution traces |
Enable features in Cargo.toml:
# Default (native)
= "0.1"
# WebAssembly target
= { = "0.1", = false, = ["wasm"] }
Architecture
Agent Lifecycle
A TaskAgent runs an AI provider in a loop — calling tools, tracking progress, and validating work before completion.
Key types:
TaskAgent— the autonomous execution unit; owns its conversation history and working setTaskAgentConfig— controls iteration limits, budgets, validation, and loop detectionTaskAgentResult— outcome including iterations used, token counts, cost, and failure categoryFailureCategory— why an agent stopped (when unsuccessful)ExecutionGraph— full DAG trace of provider calls and tool invocationsRunTelemetry— aggregate summary derived from the execution graph
FailureCategory variants:
| Variant | Description |
|---|---|
IterationLimitExceeded |
Exhausted max_iterations |
TokenBudgetExceeded |
Cumulative tokens exceeded ceiling |
CostBudgetExceeded |
Cumulative cost (USD) exceeded ceiling |
WallClockTimeout |
timeout_secs elapsed |
LoopDetected |
Same tool called repeatedly |
MaxReplanAttemptsExceeded |
Too many replan cycles |
FileScopeViolation |
File operation outside allowed paths |
ValidationFailed |
Validation could not be resolved within budget |
ToolExecutionError |
Unexpected tool error caused abort |
Communication
Agents coordinate through a CommunicationHub with typed AgentMessage variants grouped by protocol.
Core messages:
| Group | Variants |
|---|---|
| Task lifecycle | TaskRequest, TaskResult, StatusUpdate, AgentSpawned, AgentProgress, AgentCompleted |
| Help & approval | HelpRequest, HelpResponse, ApprovalRequest, ApprovalResponse, Broadcast, Custom |
| Operations | OperationStarted, OperationCompleted, LockAvailable, WaitQueuePosition, LockContention |
| Git | GitOperationStarted, GitOperationCompleted, BuildBlocked, FileWriteBlocked, ConflictResolved |
| Saga | SagaStarted, SagaStepCompleted, SagaCompleted, SagaCompensating |
| Contract-Net | TaskAnnounced, BidSubmitted, TaskAwarded, TaskAccepted, TaskDeclined |
| Market | ResourceAvailable, ResourceBidSubmitted, ResourceAllocated, ResourceReleased |
| Worktree | WorktreeCreated, WorktreeRemoved, WorktreeSwitched |
| Validation | ValidationFailed, ValidationWarning |
| Optimistic | VersionConflict, ConflictResolutionApplied |
MessageEnvelope wraps every message with from, to, and timestamp metadata.
File & Resource Locks
Two lock managers handle different coordination layers.
FileLockManager — path-level read/write locking with deadlock detection:
| Feature | Description |
|---|---|
| Shared reads | Multiple agents can hold LockType::Read on the same file |
| Exclusive writes | LockType::Write blocks all other access |
RAII LockGuard |
Lock released automatically when guard drops |
| Deadlock detection | DFS cycle detection in the wait-for graph |
| Configurable timeout | Per-lock or global default (5 min default) |
| Wait-and-retry | acquire_with_wait polls with deadlock checks until timeout |
ResourceLockManager — operation-level locking for builds, tests, and git:
ResourceType |
Conflicts with |
|---|---|
Build |
Build, BuildTest, GitRemoteMerge, GitDestructive |
Test |
Test, BuildTest, GitRemoteMerge, GitDestructive |
BuildTest |
Build, Test, BuildTest |
GitIndex |
GitIndex, GitCommit, GitRemoteMerge, GitDestructive |
GitCommit |
GitIndex, GitCommit, GitDestructive |
GitRemoteWrite |
GitRemoteWrite |
GitRemoteMerge |
GitRemoteMerge, GitIndex, Build, Test |
GitBranch |
GitBranch |
GitDestructive |
GitDestructive, GitIndex, GitCommit, Build, Test |
Resource locks support ResourceScope::Global or ResourceScope::Project(path) for isolation.
AccessControlManager — bundles file and resource locks together with contention strategies (Fail, Wait, Preempt).
Validation
Agents pass through a validation gate before reporting success.
ValidationCheck variants:
| Check | Description |
|---|---|
NoDuplicates |
Detect duplicate exports, functions, types |
BuildSuccess { build_type } |
Run cargo build, npm build, etc. |
SyntaxValid |
Basic syntax error detection |
CustomCommand { command, args } |
Run an arbitrary validation command |
ValidationConfig controls which checks run, the working directory, max retries (default 3), and the file working set. ValidationResult reports passed status and a list of ValidationIssue items with severity (Error or Warning).
Coordination Patterns
Six coordination patterns are available for multi-agent workflows:
| Pattern | Module | Description |
|---|---|---|
| Contract-Net | contract_net |
Bidding protocol — manager announces tasks, agents bid, best bidder wins |
| Saga | saga |
Compensating transactions — execute steps in sequence, roll back on failure |
| Optimistic Concurrency | optimistic |
Version-based conflict detection with retry and merge strategies |
| Wait Queue | wait_queue |
FIFO coordination primitive with notification on resource release |
| Market Allocation | market_allocation |
Market-based resource allocation with priority and urgency bidding |
| Three-State Model | state_model |
State snapshots (proposed/committed/rolled-back) for safe rollback |
Task Management
TaskManager— hierarchical task decomposition with dependency trackingTaskQueue— priority-based scheduling with dependency awarenessPlanExecutorAgent— executes multi-step plans with configurable approval modes (Auto,StepByStep,PlanLevel)
Git Coordination
GitCoordinator maps git tool operations to their required resource locks:
| Git Tool | Required Locks | Notes |
|---|---|---|
git_status, git_diff, git_log, git_search, git_fetch |
None | Read-only |
git_stage, git_unstage |
GitIndex |
Modifies staging area |
git_commit |
GitIndex, GitCommit |
Creates commit |
git_push |
GitRemoteWrite |
Writes to remote |
git_pull |
GitRemoteMerge, GitIndex |
Reads remote, modifies working tree |
git_branch |
GitBranch |
Branch operations |
git_discard |
GitDestructive, GitIndex |
Dangerous: loses changes |
Confidence Scoring
ResponseConfidence scores AI responses on a 0.0–1.0 scale based on four factors:
| Factor | Signal |
|---|---|
completion_confidence |
finish_reason — "stop" = high, truncated = low |
pattern_confidence |
Hedging language ("I think", "possibly") = low |
length_confidence |
Response length (normalized) |
structure_confidence |
Presence of tool use = higher confidence |
Levels: very_high (>= 0.9), high (>= 0.8), medium (>= 0.6), low (>= 0.4), very_low (< 0.4).
Usage Examples
Spawn Agent via AgentPool
use Arc;
use *;
use Task;
let pool = new;
let id = pool.spawn_agent.await?;
let result = pool.await_completion.await?;
TaskAgentConfig with Validation and Budget
use ;
let config = TaskAgentConfig ;
File Lock Acquire / Release
use Arc;
use ;
let manager = new;
// Shared read — multiple agents can hold simultaneously
let _read_guard = manager.acquire_lock.await?;
// Exclusive write — blocks all other access
let _write_guard = manager.acquire_lock.await?;
// Guards release automatically when dropped
CommunicationHub Broadcast
use Arc;
use ;
let hub = new;
hub.register_agent.await?;
hub.register_agent.await?;
hub.broadcast.await?;
let msg = hub.try_receive_message.await;
Saga Compensating Transaction
use SagaExecutor;
let mut saga = new;
// Execute steps in sequence
saga.execute_step.await?;
saga.execute_step.await?;
saga.execute_step.await?;
// If any step fails, compensate all completed operations in reverse
if failed
Git Coordination
use Arc;
use PathBuf;
use ;
// Check lock requirements for a git operation
let reqs = get_lock_requirements;
assert!;
assert!;
assert!;
Confidence Scoring
use ;
let confidence: ResponseConfidence = extract_confidence;
if confidence.is_high_confidence else
Configuration
TaskAgentConfig Fields
| Field | Type | Default | Description |
|---|---|---|---|
max_iterations |
u32 |
100 | Provider call iteration limit |
system_prompt |
Option<String> |
None |
Override the default reasoning prompt |
temperature |
f32 |
0.0 | AI temperature (0.0–1.0) |
max_tokens |
u32 |
4096 | Max tokens per AI response |
validation_config |
Option<ValidationConfig> |
Some(default) | Quality checks before completion |
loop_detection |
Option<LoopDetectionConfig> |
Some(5-call) | Detect repeated tool calls |
goal_revalidation_interval |
Option<u32> |
Some(10) | Inject goal reminder every N iterations |
max_replan_attempts |
u32 |
3 | Abort after N replan cycles |
max_total_tokens |
Option<u64> |
None |
Cumulative token ceiling |
max_cost_usd |
Option<f64> |
None |
Cumulative cost ceiling (USD) |
timeout_secs |
Option<u64> |
None |
Wall-clock timeout |
allowed_files |
Option<Vec<PathBuf>> |
None |
File scope whitelist |
ValidationConfig Builder
use ;
let config = ValidationConfig ;
Workflow Graph Builder
Build declarative DAG workflows with parallel execution, conditional routing, and shared state:
use ;
let workflow = new
.node
.node
.node
.node
.edge
.edge // lint and review run in parallel
.edge
.edge // summarize waits for both
.build?;
let result = workflow.run.await?;
assert!;
Features:
- Topological validation via
petgraph(cycle detection) - Parallel fan-out / fan-in execution
- Conditional routing based on node output
- Shared state via
WorkflowContext(Arc<RwLock<HashMap<String, Value>>>) - Failure propagation — downstream nodes are skipped when predecessors fail
Reasoning Strategies
Named reasoning patterns behind the reasoning feature flag:
= { = "0.1", = ["reasoning"] }
use *;
// Factory creation via preset
let strategy = ReAct.create;
println!;
// Get the system prompt for an agent
let prompt = strategy.system_prompt;
// Check completion based on step history
let steps = vec!;
assert!;
Available strategies:
| Strategy | Pattern | Max Steps |
|---|---|---|
ReActStrategy |
Think → Act → Observe loop | 25 |
ReflexionStrategy |
Act → Reflect → Revise loop | 15 |
ChainOfThoughtStrategy |
Step-by-step reasoning chain | 10 |
TreeOfThoughtsStrategy |
Parallel branch exploration with scoring | 20 |
OpenTelemetry Export
Export agent execution traces to Jaeger, Datadog, Grafana, or any OpenTelemetry-compatible backend. Requires the otel feature:
= { = "0.1", = ["otel"] }
use ;
use global;
let tracer = tracer;
// Export full span hierarchy: agent.run → agent.iteration.N → agent.tool.name
export_to_otel;
// Or attach telemetry to an existing span
let attrs = telemetry_attributes;
Span hierarchy:
agent.run (root)
├── agent.iteration.0
│ ├── agent.tool.read_file
│ └── agent.tool.edit_file
├── agent.iteration.1
│ └── agent.tool.bash
└── agent.iteration.2
Span attributes: prompt_hash, total_iterations, total_tool_calls, tool_error_count, total_prompt_tokens, total_completion_tokens, total_cost_usd, duration_ms, success, tools_used
Integration with Brainwires
Use via the brainwires facade crate:
[]
= { = "0.1", = ["agents"] }
Or use standalone — brainwires-agents depends only on brainwires-core and brainwires-tool-system.
License
Licensed under either of Apache License, Version 2.0 or MIT License at your option.