🍃 🌿 🌱
🌿 Barnyard Engineering

🌱 BarnOS Development Roadmap

Gap analysis, architecture inventory, and staged implementation plan — mapping the BarnOS vision to working code in CDS-AgentsOrchestration.

← Back to BarnOS Overview
🍃 INVENTORY

What's Already Built

The CDS-AgentsOrchestration monorepo contains three platform layers plus a Rust runtime and desktop app. This is the foundation BarnOS builds on.

CDS-AgentsOrchestration/ ├── barn/ Rust workspace (5 crates) │ ├── barn-core Shared models, traits, engine │ ├── barn-kernel Cloud sidecar: MCP, missions, trust │ ├── barn-desktop-core Local-first: RedbStore, LLM, ingestion │ ├── barn-sdk Rust API client + streaming │ └── barn-cli CLI tool ├── barnos-desktop/ Tauri 2 desktop app (React + Rust) ├── cds-azure-openai-func/ C# Azure Durable Functions backend ├── cds-llm-wasm-client/ TS orchestration API + React UI + WASM ├── pipelines/ Azure DevOps CI/CD └── docs/ Architecture docs, A2A-MCP, auth guides
barn-core
Mission FSM (9 states), AgentIdentity, AuthorityLevel, Capability enums, TrustDecision, AuditEntry
RUST
barn-kernel
MCP server (JSON-RPC 2.0), mission scheduler, CosmosStore, approval manager, audit logger
RUST
barnos-desktop
Chat, Agents, Missions, Knowledge Base, Settings. Offline-capable with embedded redb
TAURI 2
Orchestration API
Agent CRUD, workflow DAG execution, Cosmos DB persistence, 16 Azure Functions endpoints
TYPESCRIPT
Durable Functions
Multi-agent pipeline: Planner → Researcher + Reviewer (parallel) → Coder
C# .NET 8
Workflow Builder
Visual DAG editor with ReactFlow, Zustand state, TanStack Query, Tailwind CSS
REACT
🌿 MODELS

Key Data Models in Rust

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.

Mission State Machine (9 states)

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
        )
    }
}

Authority & Trust

#[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 Spec & Steps

/// 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
}
🍂 GAP ANALYSIS

BarnOS Vision vs. Current Implementation

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.
🌳 ROADMAP

Development Stages

Each stage builds on the previous. The work is ordered to deliver value incrementally while converging toward the full BarnOS nervous system.

1
🌱 Seed — Trust Alignment & Domain Model
Now — Foundation work
Align the existing authority model to the K1–K6 trust tiers from the BarnOS article. Add domain tagging to agents. Extend mission lifecycle with product stages. This is purely model-layer work — no new infrastructure.
Map AuthorityLevel to K1–K6 trust tiers
Remap the 5-level enum (Observer..Admin) to 6 tiers: K1 Reflex, K2 Autonomous, K3 Coordinated, K4 Predictive, K5 Strategic, K6 Executive. barn-core/src/models/trust.rs
Add domain field to Agent model
Add domain: Option<String> to AgentIdentity. Enables cross-domain queries later without breaking existing agents. barn-core/src/models/trust.rs → AgentIdentity
Add product lifecycle to MissionSpec
New enum: ProductStage { Discovery, Validation, Growth, Maturity, Sunset }. Optional field on MissionSpec. barn-core/src/models/mission.rs
Update trust engine to use K-levels
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
2
🌿 Root — Events, Signals & Assumption Registries
After Stage 1 — The sensory layer
Fill the empty 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.
Implement events module
Event bus with typed events: MissionStateChanged, TrustEscalation, DriftDetected, AssumptionViolated. In-process channel initially, Cosmos-backed later. barn-kernel/src/events/mod.rs (currently empty)
Assumption Registry model + store
New model: 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)
Drift detection scheduler job
Extend existing mission::scheduler to run background drift-check missions at configurable intervals. Emits DriftDetected events when thresholds exceeded. barn-kernel/src/mission/scheduler.rs
MCP handlers for assumption CRUD
Add JSON-RPC methods: assumption.list, assumption.create, assumption.check, assumption.history. barn-kernel/src/mcp/handlers.rs
3
🍃 Branch — Swarm Coordination & Trust Mesh
After Stage 2 — Multi-agent intelligence
Fill the empty 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 model + coordination engine
New model: 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)
Cross-domain mission composition
A mission step can target an agent in a different domain. The kernel negotiates trust boundaries: both agents' K-levels must satisfy the operation's requirements. barn-kernel/src/mission/controller.rs
Trust mesh: agent-to-agent negotiation
When Agent A (domain: supply-chain, K3) needs data from Agent B (domain: finance, K4), the trust engine evaluates both identities and the operation's sensitivity. Emit TrustEscalation events when K5+ required. barn-kernel/src/trust/engine.rs
FanOutMerge strategy for parallel swarm execution
The existing MissionStrategy::FanOutMerge enum variant needs a real implementation: fan out steps to swarm members, merge results, resolve conflicts. barn-kernel/src/mission/controller.rs
4
🌳 Canopy — Meta-Knowledge & Institutional Memory
After Stage 3 — The nervous system learns
Every mission outcome enriches the system. Build the meta-knowledge layer that captures cross-mission patterns, surfaces connections between domains, and makes the organism smarter with every cycle. This is the "soul" of BarnOS.
Mission outcome knowledge capture
When 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
Cross-mission pattern detection
Background agent that analyzes completed missions across domains. Surfaces: recurring failures, successful patterns, cross-domain correlations. Writes to a new insights Cosmos container. barn-kernel/src/mission/evaluator.rs + knowledge.rs
Institutional memory API
New MCP methods: 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
First-Day Audit missions
Periodic agent-driven reviews that approach a business domain as if seeing it for the first time. Uses assumption registries + mission history to generate "what would a newcomer question?" reports. New mission template + scheduler config
🌳 STUBS

Empty Modules Waiting for Implementation

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