Gap analysis, architecture inventory, and staged implementation plan — mapping the BarnOS vision to working code in CDS-AgentsOrchestration.
← Back to BarnOS OverviewThe CDS-AgentsOrchestration monorepo contains three platform layers plus a Rust runtime and desktop app. This is the foundation BarnOS builds on.
The barn-core crate defines the domain primitives that every other component depends on. These are the structures that need to evolve as BarnOS matures.
pub enum MissionState {
Created,
Queued,
Running,
Paused,
Blocked,
Evaluating,
Completed,
Failed,
Cancelled,
}
// Enforced transitions:
// Created → Queued → Running → Evaluating → Completed
// Running → Paused | Blocked | Failed
// Failed → Queued (retry)
// Cancelled → Queued (re-queue)
impl MissionState {
pub fn is_terminal(&self) -> bool {
matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
}
pub fn can_transition_to(&self, target: &MissionState) -> bool {
matches!(
(self, target),
(Self::Created, Self::Queued)
| (Self::Queued, Self::Running)
| (Self::Running, Self::Paused)
| (Self::Running, Self::Blocked)
| (Self::Running, Self::Evaluating)
| (Self::Running, Self::Failed)
| (Self::Evaluating, Self::Completed)
| (Self::Evaluating, Self::Failed)
| (Self::Failed, Self::Queued) // retry
| (Self::Cancelled, Self::Queued) // re-queue
)
}
}#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum AuthorityLevel {
Observer = 0, // Read-only access
Contributor = 1, // Can submit work
Operator = 2, // Can execute missions
Architect = 3, // Can modify structure
Admin = 4, // Full control
}
pub enum TrustDecision {
Allowed,
Denied(String),
RequiresApproval {
reason: String,
authority_required: AuthorityLevel,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Capability {
ReadKb,
ReadCosmos { containers: Vec<String> },
WriteKb { partitions: Vec<String> },
PostSlack { channels: Vec<String> },
GenerateDocuments,
ExecuteTool { tools: Vec<String> },
CreateMission,
ManageMission { mission_ids: Vec<String> },
WriteRepo { repos: Vec<String> },
CreatePullRequest { repos: Vec<String> },
ModifyConfig { scopes: Vec<String> },
ManageAgents,
ApproveActions { max_authority: u8 },
}/// Mission — matches TS KernelMission interface exactly.
/// Cosmos container: kernel-missions (partition key: /id)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Mission {
pub id: String, // "msn-{uuid12}"
pub name: String,
pub description: String,
pub state: MissionState,
pub agent_id: String,
pub owner_id: String,
pub project_id: Option<String>,
pub spec: MissionSpec, // objective, tools, timeout, strategy
pub steps: Vec<MissionStep>, // each step can override agent_id
pub outcome: Option<MissionOutcome>,
pub tool_call_log: Vec<ToolCallRecord>,
pub current_step_index: usize,
pub priority: MissionPriority, // Low | Normal | High | Critical
pub retry_policy: RetryPolicy,
pub started_at: Option<DateTime<Utc>>,
pub completed_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
pub enum MissionStrategy {
Sequential, // Steps run one after another
Parallel, // All steps run concurrently
FanOutMerge, // Fan out to swarm, merge results
}
pub struct MissionSpec {
pub objective: String,
pub tools: Vec<String>,
pub timeout_secs: u64, // default: 600
pub max_retries: u32, // default: 1
pub strategy: MissionStrategy, // default: Sequential
pub knowledge_capture: bool, // auto-extract to KB on completion
pub kb_partition: Option<String>, // target KB partition
}Mapping each concept from the BarnOS article to what exists in the codebase today.
| BarnOS Concept | Article Section | Status | Current State |
|---|---|---|---|
| Trust K1–K6 | Trust Framework | MISMATCH | 5-level AuthorityLevel (Observer..Admin). Not mapped to K1–K6 reflex/coordinated/executive tiers. |
| Mission Lifecycle | EVOLVE | PARTIAL | 9-state FSM exists. No product lifecycle mapping (discovery / validation / growth / maturity / sunset). |
| Swarm Coordination | GROW | STUB | barn-kernel/src/swarm/mod.rs exists but is empty. |
| Events / Signals | ADD (Drift Detection) | STUB | barn-kernel/src/events/mod.rs exists but is empty. |
| Assumption Registries | ADD | MISSING | New concept. No model, store, or API exists. |
| Drift Detection Missions | ADD | MISSING | Scheduler exists but no continuous background monitoring agents. |
| Cross-Domain Agents | GROW | MISSING | Agent model has no domain tagging. No cross-domain boundary negotiation. |
| Meta-Knowledge Layer | THE SOUL | PARTIAL | KB exists in desktop (redb). No cross-mission learning or institutional memory. |
| Trust Mesh | GROW | MISSING | Trust is per-agent only. No agent-to-agent trust negotiation. |
| MCP Integration | Vendor Agnostic | DONE | MCP server (JSON-RPC 2.0 over TCP) in barn-kernel. Tool dispatch working. |
| Audit Trail | Security | DONE | AuditEntry + AuditLogger with buffered flush to Cosmos. |
| Approval Workflow | Trust Framework | DONE | ApprovalManager with TTL-based expiration. Pending/Approved/Denied/Expired states. |
| Multi-Agent Pipeline | Platform | DONE | C# Durable Functions: Planner → Researcher + Reviewer → Coder. Working in Azure. |
| Agent CRUD + Templates | Platform | DONE | 8 pre-built templates. Cosmos DB persistence. React workflow builder UI. |
Each stage builds on the previous. The work is ordered to deliver value incrementally while converging toward the full BarnOS nervous system.
domain: Option<String> to AgentIdentity. Enables cross-domain queries later without breaking existing agents.
barn-core/src/models/trust.rs → AgentIdentity
ProductStage { Discovery, Validation, Growth, Maturity, Sunset }. Optional field on MissionSpec.
barn-core/src/models/mission.rs
check_authority() in barn-kernel evaluates against K1–K6 instead of numeric levels. K1–K2 auto-approve, K3–K4 require context, K5–K6 require human.
barn-kernel/src/trust/engine.rs
events/ module. Build the assumption registry as a new Cosmos container. Create drift detection as a scheduler extension. This is the "first-day eyes" from the BarnOS article.MissionStateChanged, TrustEscalation, DriftDetected, AssumptionViolated. In-process channel initially, Cosmos-backed later.
barn-kernel/src/events/mod.rs (currently empty)
Assumption { id, process_name, domain, assertion, threshold, monitor_agent_id, last_checked, drift_score }. New Cosmos container: assumption-registries.
barn-core/src/models/ (new file)
mission::scheduler to run background drift-check missions at configurable intervals. Emits DriftDetected events when thresholds exceeded.
barn-kernel/src/mission/scheduler.rs
assumption.list, assumption.create, assumption.check, assumption.history.
barn-kernel/src/mcp/handlers.rs
swarm/ module. Implement cross-domain mission composition where agents from different domains self-organize around shared objectives. Build the trust mesh so agents negotiate K-levels when collaborating.Swarm { id, objective, member_agents, domain_scope, formation_strategy, trust_floor }. Agents can form ad-hoc swarms around shared missions.
barn-kernel/src/swarm/mod.rs (currently empty)
TrustEscalation events when K5+ required.
barn-kernel/src/trust/engine.rs
MissionStrategy::FanOutMerge enum variant needs a real implementation: fan out steps to swarm members, merge results, resolve conflicts.
barn-kernel/src/mission/controller.rs
knowledge_capture: true on MissionSpec, completed missions auto-extract insights into the KB. Currently the field exists but is unused.
barn-core/src/models/mission.rs → MissionSpec.knowledge_capture
insights Cosmos container.
barn-kernel/src/mission/evaluator.rs + knowledge.rs
knowledge.query (semantic search across mission outcomes), knowledge.connections (graph of domain relationships), knowledge.insights (auto-generated cross-domain findings).
barn-kernel/src/mcp/handlers.rs
These Rust modules exist in the kernel but contain no logic yet. They are the scaffolding for Stages 2–4.
//! barn-kernel/src/main.rs
//!
//! Barn Platform Kernel — mission-driven agent runtime.
//! Runs as a sidecar in workspace pods or standalone daemon.
mod config;
mod engine;
mod mcp; // JSON-RPC 2.0 server — DONE
mod metrics; // Health + Prometheus — DONE
mod mission; // Controller + scheduler — DONE
mod store; // CosmosStore backend — DONE
mod trace; // OpenTelemetry tracing — DONE
// Future phases (K3-K6) — empty modules for now
mod swarm; // Stage 3: Cross-domain agent coordination
mod events; // Stage 2: Event bus, drift detection signals
mod trust; // Stage 1: K1-K6 alignment (partially implemented)
use config::KernelConfig;
use mission::MissionController;
use store::CosmosStore;
use trust::{ApprovalManager, AuditLogger};
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let config = KernelConfig::from_env();
// Initialize trust components
let approval_manager = Arc::new(ApprovalManager::new(config.approval_ttl_secs));
let audit_logger = Arc::new(AuditLogger::new(config.audit_buffer_size, config.clone()));
// Initialize persistence + mission controller
let cosmos_store: Arc<dyn barn_core::traits::store::KernelStore> =
Arc::new(CosmosStore::new(config.clone()));
let mission_ctrl = Arc::new(MissionController::new(cosmos_store));
// Hydrate missions from Cosmos (warm cache)
mission_ctrl.hydrate().await?;
// Start MCP server, health server, mission scheduler...
info!("Barn Kernel ready");
tokio::signal::ctrl_c().await?;
}The kernel's main.rs already imports these modules and wires them into the async runtime. The architecture is ready — the implementation is the work ahead.
The code is the seed. The roadmap is how it becomes a nervous system.
← Back to BarnOS Overview