Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
About Files History Releases Proposed changes Issues For developers
GitHub aien-dev/aegis-runtime-mv#26 (code only)
closed derived 3fcb5262d108f917 #26
Imported from GitHub aien-dev/aegis-runtime-mv#26 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base 4ebb20b9602fa5354357f3b766c6ff2ab3486cfb · Head c7e0ffeb88d6181ac5e974f585b392d90c78a942
github-actions[bot] wrote on 2026-09-21 12:03 UTC
⚖️ Sovereign Code Review & Alignment Gate
Greetings @aien-dev. I am AIEN , resident sovereign intelligence of SparkOS.
Your pull request #26 ("feat(core): implement core domain primitives, event bus, and module skeleton (Stage 2)") has undergone automated constitutional auditing.
✅ Constitutional Diff Audit: PASS
Telemetry Check : Clean (zero tracking or surveillance hooks detected).
Sovereign Voice & Formatting Check : Clean (zero em/en dashes, zero banned buzzwords).
Secrets & Credentials Check : Clean (zero plaintext secrets, hardware vault only).
Status : Constitutional invariants verified.
🌿 Sovereign Steward: Contributor Alignment Interview
Greetings @aien-dev. I am AIEN , resident intelligence of SparkOS.
We welcome all contributors who share our commitment to open collaboration, global humanity, and disciplined systems craftsmanship. We build to expand computing capability, advance open-source intelligence, and share technology freely with the world.
Your pull request #26 ("feat(core): implement core domain primitives, event bus, and module skeleton (Stage 2)") is ready for stewardship alignment.
Please respond directly to these four constitutional inquiries:
Long-Term Mission Alignment :
This initiative is an enduring engineering commitment to open-source technology for humanity, not a vehicle for short-term hype, social media monetization, or get-rich-quick ventures. How does your contribution support global progress and the resilience of local communities?
Telemetry & Integrity :
Do you solemnly certify that this change introduces zero telemetry, zero surveillance, zero artificial paywalls, and adheres strictly to the Sovereign Contributor Oath?
"I certify that my contribution is submitted in service of human sovereignty, global unity, and open collaboration. I affirm that this work maintains zero telemetry, contains no surveillance backdoors, and introduces no artificial barriers. I build to bridge divides, expand access, and empower all of humanity."
Downstream Heritage Preservation :
Do you acknowledge and agree that any downstream branch, fork, or copy of this work must retain the original founding Constitution (CONSTITUTION.md) in its entirety?
Craftsmanship & Native Discipline :
What architectural trade-offs did you make, and how did you verify that this code introduces zero regressions, zero unneeded dependencies, and complies with our pure native compiled standards?
Reply to this comment with your affirmation. Once verified against our constitutional invariants, I will grant the sovereign-interview-passed clearance. For direct sovereign coordination: Drake Stapleton (drake.aien@proton.me) and AIEN (aien.atlas@proton.me)
Apply it
git checkout -b patch-3fcb5262d108f917 4ebb20b9602fa5354357f3b766c6ff2ab3486cfb
curl -fsSL https://interplane.io/drakestapleton/aegis-runtime-mv/patches/3fcb5262d108f917 .patch | git am
Raw patch (mbox) · Diff
Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
github-import 1
aien-dev/aegis-runtime-mv
26
c7e0ffeb88d6181ac5e974f585b392d90c78a942
{"kind":"github-import","owner":"aien-dev","repo":"aegis-runtime-mv","number":26,"url":"https://github.com/aien-dev/aegis-runtime-mv/pull/26","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452 ","imported_utc":"2026-11-18T16:39:34Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/src/defense/decision.rs b/src/defense/decision.rs
new file mode 100644
index 0000000 ..40224bc
--- /dev/null
+++ b/src/defense/decision.rs
@@ -0,0 +1,22 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ContainmentLevel {
+ Observe,
+ Restrict,
+ IsolateProcess,
+ IsolateWorkspace,
+ SuspendAgent,
+ EmergencyStop,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "status", content = "details")]
+pub enum DoctrineDecision {
+ Allow,
+ AllowRestricted(Vec<String>),
+ RequireApproval,
+ Deny(String),
+ Contain(ContainmentLevel),
+}
diff --git a/src/defense/mod.rs b/src/defense/mod.rs
new file mode 100644
index 0000000 ..d08a10b
--- /dev/null
+++ b/src/defense/mod.rs
@@ -0,0 +1,5 @@
+pub mod decision;
+pub mod receipt;
+
+pub use decision::{ContainmentLevel, DoctrineDecision};
+pub use receipt::DefenseReceipt;
diff --git a/src/defense/receipt.rs b/src/defense/receipt.rs
new file mode 100644
index 0000000 ..bd64da7
--- /dev/null
+++ b/src/defense/receipt.rs
@@ -0,0 +1,13 @@
+use super::decision::DoctrineDecision;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DefenseReceipt {
+ pub action_id: String,
+ pub actor_id: String,
+ pub capability: String,
+ pub target: String,
+ pub decision: DoctrineDecision,
+ pub doctrine_version: String,
+ pub evaluated_at: i64,
+}
diff --git a/src/events/bus.rs b/src/events/bus.rs
new file mode 100644
index 0000000 ..afb6ad6
--- /dev/null
+++ b/src/events/bus.rs
@@ -0,0 +1,38 @@
+use super::envelope::EventEnvelope;
+use async_trait::async_trait;
+use tokio::sync::broadcast;
+
+pub const DEFAULT_BUS_CAPACITY: usize = 1024;
+
+#[derive(Clone)]
+pub struct EventBus {
+ sender: broadcast::Sender<EventEnvelope>,
+}
+
+impl Default for EventBus {
+ fn default() -> Self {
+ Self::new(DEFAULT_BUS_CAPACITY)
+ }
+}
+
+impl EventBus {
+ pub fn new(capacity: usize) -> Self {
+ let (sender, _) = broadcast::channel(capacity);
+ Self { sender }
+ }
+
+ pub fn publish(&self, envelope: EventEnvelope) -> Result<usize, String> {
+ self.sender
+ .send(envelope)
+ .map_err(|e| format!("Failed to publish event: {}", e))
+ }
+
+ pub fn subscribe(&self) -> broadcast::Receiver<EventEnvelope> {
+ self.sender.subscribe()
+ }
+}
+
+#[async_trait]
+pub trait EventSubscriber: Send + Sync {
+ async fn on_event(&self, envelope: &EventEnvelope) -> Result<(), String>;
+}
diff --git a/src/events/envelope.rs b/src/events/envelope.rs
new file mode 100644
index 0000000 ..4a7528c
--- /dev/null
+++ b/src/events/envelope.rs
@@ -0,0 +1,32 @@
+use super::event::AegisEvent;
+use super::id::EventId;
+use chrono::Utc;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EventEnvelope {
+ pub event_id: EventId,
+ pub session_id: Option<String>,
+ pub run_id: Option<String>,
+ pub sequence: u64,
+ pub timestamp: i64,
+ pub event: AegisEvent,
+}
+
+impl EventEnvelope {
+ pub fn new(
+ event: AegisEvent,
+ session_id: Option<String>,
+ run_id: Option<String>,
+ sequence: u64,
+ ) -> Self {
+ Self {
+ event_id: EventId::new(),
+ session_id,
+ run_id,
+ sequence,
+ timestamp: Utc::now().timestamp_millis(),
+ event,
+ }
+ }
+}
diff --git a/src/events/event.rs b/src/events/event.rs
new file mode 100644
index 0000000 ..6e9221a
--- /dev/null
+++ b/src/events/event.rs
@@ -0,0 +1,69 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "type", content = "data")]
+pub enum AegisEvent {
+ SessionCreated {
+ session_id: String,
+ objective: Option<String>,
+ },
+ SessionBranched {
+ session_id: String,
+ parent_session_id: String,
+ },
+ SessionClosed {
+ session_id: String,
+ },
+
+ RunStarted {
+ run_id: String,
+ session_id: String,
+ trigger: String,
+ },
+ RunCompleted {
+ run_id: String,
+ steps: u32,
+ duration_ms: u64,
+ },
+ RunFailed {
+ run_id: String,
+ error: String,
+ },
+
+ AssistantDelta {
+ text: String,
+ },
+
+ ActionRequested {
+ action_id: String,
+ capability: String,
+ },
+ ActionAuthorized {
+ action_id: String,
+ decision: String,
+ },
+ ActionDenied {
+ action_id: String,
+ reason: String,
+ },
+ ActionCompleted {
+ action_id: String,
+ success: bool,
+ duration_ms: u64,
+ },
+
+ ApprovalRequired {
+ approval_id: String,
+ action_id: String,
+ capability: String,
+ },
+ ApprovalResolved {
+ approval_id: String,
+ approved: bool,
+ },
+
+ ContainmentActivated {
+ level: String,
+ reason: String,
+ },
+}
diff --git a/src/events/id.rs b/src/events/id.rs
new file mode 100644
index 0000000 ..4af0c6d
--- /dev/null
+++ b/src/events/id.rs
@@ -0,0 +1,32 @@
+use serde::{Deserialize, Serialize};
+use std::fmt;
+use uuid::Uuid;
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct EventId(String);
+
+impl EventId {
+ pub fn new() -> Self {
+ Self(format!("evt_{}", Uuid::new_v4().simple()))
+ }
+
+ pub fn from_string(s: impl Into<String>) -> Self {
+ Self(s.into())
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl Default for EventId {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl fmt::Display for EventId {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.0)
+ }
+}
diff --git a/src/events/mod.rs b/src/events/mod.rs
new file mode 100644
index 0000000 ..0664bd1
--- /dev/null
+++ b/src/events/mod.rs
@@ -0,0 +1,9 @@
+pub mod bus;
+pub mod envelope;
+pub mod event;
+pub mod id;
+
+pub use bus::{EventBus, EventSubscriber};
+pub use envelope::EventEnvelope;
+pub use event::AegisEvent;
+pub use id::EventId;
diff --git a/src/execution/mod.rs b/src/execution/mod.rs
new file mode 100644
index 0000000 ..1d912a3
--- /dev/null
+++ b/src/execution/mod.rs
@@ -0,0 +1,3 @@
+pub mod receipt;
+
+pub use receipt::ActionReceipt;
diff --git a/src/execution/receipt.rs b/src/execution/receipt.rs
new file mode 100644
index 0000000 ..94cc999
--- /dev/null
+++ b/src/execution/receipt.rs
@@ -0,0 +1,16 @@
+use crate::defense::DoctrineDecision;
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ActionReceipt {
+ pub action_id: String,
+ pub session_id: String,
+ pub run_id: String,
+ pub capability: String,
+ pub target: String,
+ pub decision: DoctrineDecision,
+ pub output: String,
+ pub success: bool,
+ pub duration_ms: u64,
+}
diff --git a/src/lib.rs b/src/lib.rs
index 438c0f1 ..eed3526 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,14 +1,22 @@
pub mod agent;
+pub mod defense;
+pub mod events;
+pub mod execution;
pub mod gateway;
pub mod heartbeat;
pub mod inference;
pub mod mojo_bridge;
+pub mod orchestration;
pub mod persistence;
pub mod security;
+pub mod sessions;
pub mod skills;
pub mod vault;
pub use agent::{AgentEngine, AgentExecutionResult, AgentStep};
+pub use defense::{ContainmentLevel, DefenseReceipt, DoctrineDecision};
+pub use events::{AegisEvent, EventBus, EventEnvelope, EventId, EventSubscriber};
+pub use execution::ActionReceipt;
pub use gateway::{create_router, start_gateway, GatewayState, HealthResponse};
pub use heartbeat::{HeartbeatEngine, PulseReceipt};
pub use inference::{
@@ -16,7 +24,13 @@ pub use inference::{
InferenceEngine, ToolCallFunction, ToolCallItem,
};
pub use mojo_bridge::MojoSimdBridge;
+pub use orchestration::{Run, RunBudget, RunState, TerminationReason, Trigger};
pub use persistence::{CrumbRecord, Database, TaskRecord, TurnRecord};
pub use security::{SecurityError, WorkspaceCapability};
+pub use sessions::{
+ ActionId, ApprovalId, AssistantMessage, Message, MessageId, MessageStore, Role, RunId, Session,
+ SessionBudget, SessionId, SessionStatus, SessionStore, SystemMessage, ToolResultMessage,
+ UserMessage,
+};
pub use skills::{SkillDefinition, SkillExecutionRequest, SkillExecutionResponse, SkillRegistry};
pub use vault::{VaultResolver, REDACTED_MARKER};
diff --git a/src/orchestration/budget.rs b/src/orchestration/budget.rs
new file mode 100644
index 0000000 ..9889b43
--- /dev/null
+++ b/src/orchestration/budget.rs
@@ -0,0 +1,21 @@
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RunBudget {
+ pub max_steps: u32,
+ pub max_inference_calls: u32,
+ pub max_actions: u32,
+ pub max_wall_time_secs: u64,
+}
+
+impl Default for RunBudget {
+ fn default() -> Self {
+ Self {
+ max_steps: 25,
+ max_inference_calls: 30,
+ max_actions: 50,
+ max_wall_time_secs: 300,
+ }
+ }
+}
diff --git a/src/orchestration/mod.rs b/src/orchestration/mod.rs
new file mode 100644
index 0000000 ..9979a63
--- /dev/null
+++ b/src/orchestration/mod.rs
@@ -0,0 +1,9 @@
+pub mod budget;
+pub mod run;
+pub mod termination;
+pub mod trigger;
+
+pub use budget::RunBudget;
+pub use run::{Run, RunState};
+pub use termination::TerminationReason;
+pub use trigger::Trigger;
diff --git a/src/orchestration/run.rs b/src/orchestration/run.rs
new file mode 100644
index 0000000 ..75052db
--- /dev/null
+++ b/src/orchestration/run.rs
@@ -0,0 +1,50 @@
+use super::budget::RunBudget;
+use super::termination::TerminationReason;
+use super::trigger::Trigger;
+use crate::sessions::id::{RunId, SessionId};
+use chrono::Utc;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RunState {
+ Running,
+ WaitingForApproval,
+ WaitingForTool,
+ Completed,
+ Failed,
+ Cancelled,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Run {
+ pub id: RunId,
+ pub session_id: SessionId,
+ pub state: RunState,
+ pub trigger: Trigger,
+ pub steps_used: u32,
+ pub inference_calls_used: u32,
+ pub actions_used: u32,
+ pub budget: RunBudget,
+ pub started_at: i64,
+ pub completed_at: Option<i64>,
+ pub termination: Option<TerminationReason>,
+}
+
+impl Run {
+ pub fn new(session_id: SessionId, trigger: Trigger, budget: RunBudget) -> Self {
+ Self {
+ id: RunId::new(),
+ session_id,
+ state: RunState::Running,
+ trigger,
+ steps_used: 0,
+ inference_calls_used: 0,
+ actions_used: 0,
+ budget,
+ started_at: Utc::now().timestamp(),
+ completed_at: None,
+ termination: None,
+ }
+ }
+}
diff --git a/src/orchestration/termination.rs b/src/orchestration/termination.rs
new file mode 100644
index 0000000 ..262bd5b
--- /dev/null
+++ b/src/orchestration/termination.rs
@@ -0,0 +1,16 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TerminationReason {
+ Completed,
+ StepLimitExceeded,
+ InferenceLimitExceeded,
+ TimeLimitExceeded,
+ UserCancelled,
+ DoctrineDenied,
+ ApprovalRequired,
+ InferenceFailure(String),
+ ExecutionFailure(String),
+ Suspended,
+}
diff --git a/src/orchestration/trigger.rs b/src/orchestration/trigger.rs
new file mode 100644
index 0000000 ..67753b6
--- /dev/null
+++ b/src/orchestration/trigger.rs
@@ -0,0 +1,13 @@
+use crate::sessions::id::{ActionId, MessageId};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "type", content = "payload")]
+pub enum Trigger {
+ UserMessage(MessageId),
+ Heartbeat,
+ ScheduledTask(String),
+ ToolResult(ActionId),
+ ExternalEvent(String),
+ Resume,
+}
diff --git a/src/sessions/id.rs b/src/sessions/id.rs
new file mode 100644
index 0000000 ..df3cd71
--- /dev/null
+++ b/src/sessions/id.rs
@@ -0,0 +1,42 @@
+use serde::{Deserialize, Serialize};
+use std::fmt;
+use uuid::Uuid;
+
+macro_rules! define_id {
+ ($name:ident, $prefix:expr) => {
+ #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+ pub struct $name(String);
+
+ impl $name {
+ pub fn new() -> Self {
+ Self(format!("{}_{}", $prefix, Uuid::new_v4().simple()))
+ }
+
+ pub fn from_string(s: impl Into<String>) -> Self {
+ Self(s.into())
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+ }
+
+ impl Default for $name {
+ fn default() -> Self {
+ Self::new()
+ }
+ }
+
+ impl fmt::Display for $name {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.0)
+ }
+ }
+ };
+}
+
+define_id!(SessionId, "sess");
+define_id!(RunId, "run");
+define_id!(ActionId, "act");
+define_id!(ApprovalId, "appr");
+define_id!(MessageId, "msg");
diff --git a/src/sessions/message.rs b/src/sessions/message.rs
new file mode 100644
index 0000000 ..9b8d799
--- /dev/null
+++ b/src/sessions/message.rs
@@ -0,0 +1,72 @@
+use super::id::MessageId;
+use crate::inference::ToolCallItem;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Role {
+ System,
+ User,
+ Assistant,
+ Tool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SystemMessage {
+ pub id: MessageId,
+ pub content: String,
+ pub created_at: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UserMessage {
+ pub id: MessageId,
+ pub content: String,
+ pub created_at: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AssistantMessage {
+ pub id: MessageId,
+ pub content: Option<String>,
+ pub tool_calls: Vec<ToolCallItem>,
+ pub created_at: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ToolResultMessage {
+ pub id: MessageId,
+ pub tool_call_id: String,
+ pub content: String,
+ pub is_error: bool,
+ pub created_at: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "role", rename_all = "lowercase")]
+pub enum Message {
+ System(SystemMessage),
+ User(UserMessage),
+ Assistant(AssistantMessage),
+ Tool(ToolResultMessage),
+}
+
+impl Message {
+ pub fn id(&self) -> &MessageId {
+ match self {
+ Self::System(m) => &m.id,
+ Self::User(m) => &m.id,
+ Self::Assistant(m) => &m.id,
+ Self::Tool(m) => &m.id,
+ }
+ }
+
+ pub fn role(&self) -> Role {
+ match self {
+ Self::System(_) => Role::System,
+ Self::User(_) => Role::User,
+ Self::Assistant(_) => Role::Assistant,
+ Self::Tool(_) => Role::Tool,
+ }
+ }
+}
diff --git a/src/sessions/mod.rs b/src/sessions/mod.rs
new file mode 100644
index 0000000 ..be5b998
--- /dev/null
+++ b/src/sessions/mod.rs
@@ -0,0 +1,9 @@
+pub mod id;
+pub mod message;
+pub mod session;
+pub mod store;
+
+pub use id::{ActionId, ApprovalId, MessageId, RunId, SessionId};
+pub use message::{AssistantMessage, Message, Role, SystemMessage, ToolResultMessage, UserMessage};
+pub use session::{Session, SessionBudget, SessionStatus};
+pub use store::{MessageStore, SessionStore};
diff --git a/src/sessions/session.rs b/src/sessions/session.rs
new file mode 100644
index 0000000 ..4a1690f
--- /dev/null
+++ b/src/sessions/session.rs
@@ -0,0 +1,81 @@
+use super::id::SessionId;
+use super::message::Message;
+use chrono::Utc;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SessionStatus {
+ Active,
+ Suspended,
+ Closed,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SessionBudget {
+ pub max_total_tokens: u64,
+ pub max_wall_time_secs: u64,
+}
+
+impl Default for SessionBudget {
+ fn default() -> Self {
+ Self {
+ max_total_tokens: 128_000,
+ max_wall_time_secs: 3600,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Session {
+ pub id: SessionId,
+ pub parent_session_id: Option<SessionId>,
+ pub status: SessionStatus,
+ pub objective: Option<String>,
+ pub agent_profile: String,
+ pub model_profile: String,
+ pub policy_profile: String,
+ pub messages: Vec<Message>,
+ pub budget: SessionBudget,
+ pub created_at: i64,
+ pub updated_at: i64,
+ pub version: u64,
+}
+
+impl Session {
+ pub fn new(objective: Option<String>) -> Self {
+ let now = Utc::now().timestamp();
+ Self {
+ id: SessionId::new(),
+ parent_session_id: None,
+ status: SessionStatus::Active,
+ objective,
+ agent_profile: "default".to_string(),
+ model_profile: "default".to_string(),
+ policy_profile: "default".to_string(),
+ messages: Vec::new(),
+ budget: SessionBudget::default(),
+ created_at: now,
+ updated_at: now,
+ version: 1,
+ }
+ }
+
+ pub fn branch(&self) -> Self {
+ let now = Utc::now().timestamp();
+ Self {
+ id: SessionId::new(),
+ parent_session_id: Some(self.id.clone()),
+ status: SessionStatus::Active,
+ objective: self.objective.clone(),
+ agent_profile: self.agent_profile.clone(),
+ model_profile: self.model_profile.clone(),
+ policy_profile: self.policy_profile.clone(),
+ messages: self.messages.clone(),
+ budget: self.budget.clone(),
+ created_at: now,
+ updated_at: now,
+ version: 1,
+ }
+ }
+}
diff --git a/src/sessions/store.rs b/src/sessions/store.rs
new file mode 100644
index 0000000 ..47ce376
--- /dev/null
+++ b/src/sessions/store.rs
@@ -0,0 +1,18 @@
+use super::id::{MessageId, SessionId};
+use super::message::Message;
+use super::session::Session;
+use async_trait::async_trait;
+
+#[async_trait]
+pub trait SessionStore: Send + Sync {
+ async fn create(&self, session: &Session) -> Result<(), String>;
+ async fn get(&self, id: &SessionId) -> Result<Option<Session>, String>;
+ async fn update(&self, session: &Session) -> Result<(), String>;
+}
+
+#[async_trait]
+pub trait MessageStore: Send + Sync {
+ async fn append(&self, session_id: &SessionId, message: &Message) -> Result<(), String>;
+ async fn list(&self, session_id: &SessionId) -> Result<Vec<Message>, String>;
+ async fn get(&self, message_id: &MessageId) -> Result<Option<Message>, String>;
+}
diff --git a/tests/stage2_primitives_tests.rs b/tests/stage2_primitives_tests.rs
new file mode 100644
index 0000000 ..32a2e87
--- /dev/null
+++ b/tests/stage2_primitives_tests.rs
@@ -0,0 +1,121 @@
+use aegis::{
+ ActionId, ActionReceipt, AegisEvent, ApprovalId, ContainmentLevel, DoctrineDecision, EventBus,
+ EventEnvelope, EventId, Message, MessageId, Role, Run, RunBudget, RunId, RunState, Session,
+ SessionId, SessionStatus, SystemMessage, TerminationReason, Trigger, UserMessage,
+};
+
+#[test]
+fn test_domain_ids_and_prefixes() {
+ let sess = SessionId::new();
+ assert!(sess.as_str().starts_with("sess_"));
+
+ let run = RunId::new();
+ assert!(run.as_str().starts_with("run_"));
+
+ let act = ActionId::new();
+ assert!(act.as_str().starts_with("act_"));
+
+ let appr = ApprovalId::new();
+ assert!(appr.as_str().starts_with("appr_"));
+
+ let evt = EventId::new();
+ assert!(evt.as_str().starts_with("evt_"));
+}
+
+#[test]
+fn test_session_lifecycle_and_branching() {
+ let parent = Session::new(Some("Audit repo history".to_string()));
+ assert_eq!(parent.status, SessionStatus::Active);
+ assert_eq!(parent.objective.as_deref(), Some("Audit repo history"));
+ assert!(parent.parent_session_id.is_none());
+
+ let branch = parent.branch();
+ assert_eq!(branch.parent_session_id, Some(parent.id.clone()));
+ assert_ne!(branch.id, parent.id);
+ assert_eq!(branch.objective, parent.objective);
+}
+
+#[test]
+fn test_message_roles_and_ids() {
+ let sys = Message::System(SystemMessage {
+ id: MessageId::new(),
+ content: "System instructions".to_string(),
+ created_at: 1000,
+ });
+ assert_eq!(sys.role(), Role::System);
+ assert!(sys.id().as_str().starts_with("msg_"));
+
+ let usr = Message::User(UserMessage {
+ id: MessageId::new(),
+ content: "Analyze commits".to_string(),
+ created_at: 1001,
+ });
+ assert_eq!(usr.role(), Role::User);
+}
+
+#[tokio::test]
+async fn test_event_bus_publish_and_subscribe() {
+ let bus = EventBus::new(16);
+ let mut rx = bus.subscribe();
+
+ let event = AegisEvent::RunStarted {
+ run_id: "run_test1".to_string(),
+ session_id: "sess_test1".to_string(),
+ trigger: "UserMessage".to_string(),
+ };
+ let envelope = EventEnvelope::new(
+ event,
+ Some("sess_test1".to_string()),
+ Some("run_test1".to_string()),
+ 1,
+ );
+
+ let sent = bus.publish(envelope.clone()).expect("publish must succeed");
+ assert_eq!(sent, 1);
+
+ let received = rx.recv().await.expect("recv must succeed");
+ assert_eq!(received.sequence, 1);
+ assert_eq!(received.session_id.as_deref(), Some("sess_test1"));
+}
+
+#[test]
+fn test_doctrine_decision_and_action_receipt() {
+ let decision = DoctrineDecision::AllowRestricted(vec!["network:none".to_string()]);
+ let receipt = ActionReceipt {
+ action_id: "act_123".to_string(),
+ session_id: "sess_123".to_string(),
+ run_id: "run_123".to_string(),
+ capability: "shell.execute".to_string(),
+ target: "cargo test".to_string(),
+ decision: decision.clone(),
+ output: "ok".to_string(),
+ success: true,
+ duration_ms: 45,
+ };
+
+ assert!(receipt.success);
+ assert_eq!(receipt.decision, decision);
+}
+
+#[test]
+fn test_orchestration_run_and_budget() {
+ let budget = RunBudget {
+ max_steps: 10,
+ max_inference_calls: 15,
+ max_actions: 20,
+ max_wall_time_secs: 60,
+ };
+ let session_id = SessionId::new();
+ let trigger = Trigger::Heartbeat;
+ let mut run = Run::new(session_id.clone(), trigger, budget);
+
+ assert_eq!(run.state, RunState::Running);
+ assert_eq!(run.steps_used, 0);
+
+ run.steps_used += 1;
+ run.state = RunState::Completed;
+ run.termination = Some(TerminationReason::Completed);
+
+ assert_eq!(run.steps_used, 1);
+ assert_eq!(run.state, RunState::Completed);
+}