Skip to main content

cortex_domain/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::collections::{HashMap, HashSet, VecDeque};
4use std::fmt::{Display, Formatter};
5
6use serde::{Deserialize, Serialize};
7
8mod default_graph;
9
10pub use default_graph::default_control_plane;
11
12/// The wire format this crate reads and writes.
13///
14/// [`GraphDocument::validate`] accepts only this value, so a document that
15/// declares a different schema is rejected rather than silently
16/// misinterpreted.
17pub const GRAPH_SCHEMA_VERSION: &str = "cortex-loom.graph.v1";
18/// Upper bound on nodes in one document.
19pub const MAX_GRAPH_NODES: usize = 4_096;
20/// Upper bound on edges in one document.
21pub const MAX_GRAPH_EDGES: usize = 16_384;
22
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
24#[serde(rename_all = "camelCase")]
25pub struct GraphDocument {
26    pub schema_version: String,
27    pub id: String,
28    pub name: String,
29    pub revision: u64,
30    pub nodes: Vec<GraphNode>,
31    pub edges: Vec<GraphEdge>,
32    #[serde(default)]
33    pub metadata: HashMap<String, String>,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37#[serde(rename_all = "camelCase")]
38pub struct GraphNode {
39    pub id: String,
40    pub kind: NodeKind,
41    pub label: String,
42    #[serde(default)]
43    pub description: String,
44    pub position: Position,
45    #[serde(default)]
46    pub execution: Option<ExecutionPolicy>,
47    #[serde(default)]
48    pub provenance: Vec<Provenance>,
49    #[serde(default)]
50    /// Free-form typed configuration for the node kind, for example a retry
51    /// controller's `targetNodeId` and `maxAttempts`.
52    pub config: HashMap<String, blazingly_json::Value>,
53}
54
55/// What a node represents. The kind carries the semantics: gates block,
56/// controllers branch or retry, and the rest do work.
57#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
58#[serde(rename_all = "snake_case")]
59pub enum NodeKind {
60    /// Entry point that receives the request or task.
61    Input,
62    /// Work done by deterministic tooling, with no model involved.
63    Deterministic,
64    /// Repository graph and impact analysis.
65    Weavatrix,
66    /// A reusable methodology workflow, typically compiled from `SKILL.md`.
67    Skill,
68    /// A unit of work handed to an agent.
69    AgentTask,
70    /// A bounded local-model step; advisory output only.
71    LocalModel,
72    /// Gate on structure, provenance, risk, and budgets.
73    QualityGate,
74    /// Gate requiring an explicit human decision.
75    HumanGate,
76    /// Gate on a test run.
77    TestGate,
78    /// Gate requiring an explicit review decision.
79    ReviewGate,
80    /// Gate requiring cited evidence before proceeding.
81    EvidenceGate,
82    /// Controller that selects exactly one outgoing conditional edge.
83    Branch,
84    /// Controller that reopens a failed target for a bounded number of
85    /// attempts; configured through `config` with `targetNodeId` and
86    /// `maxAttempts`.
87    Retry,
88    /// Transfer of responsibility to another executor.
89    Handoff,
90    /// A terminal state that ends its path.
91    Terminal,
92    /// Work reserved for the strong upstream agent.
93    UpstreamAgent,
94    /// Exit point carrying the verified result.
95    Output,
96}
97
98impl NodeKind {
99    /// The wire name, identical to the serialised form.
100    #[must_use]
101    pub const fn as_str(self) -> &'static str {
102        match self {
103            Self::Input => "input",
104            Self::Deterministic => "deterministic",
105            Self::Weavatrix => "weavatrix",
106            Self::Skill => "skill",
107            Self::AgentTask => "agent_task",
108            Self::LocalModel => "local_model",
109            Self::QualityGate => "quality_gate",
110            Self::HumanGate => "human_gate",
111            Self::TestGate => "test_gate",
112            Self::ReviewGate => "review_gate",
113            Self::EvidenceGate => "evidence_gate",
114            Self::Branch => "branch",
115            Self::Retry => "retry",
116            Self::Handoff => "handoff",
117            Self::Terminal => "terminal",
118            Self::UpstreamAgent => "upstream_agent",
119            Self::Output => "output",
120        }
121    }
122
123    /// Parse a wire name. Hyphens and spaces are accepted so a human writing
124    /// `review-gate` in Markdown is not punished for it.
125    #[must_use]
126    pub fn parse(value: &str) -> Option<Self> {
127        let normalized = value.trim().to_ascii_lowercase().replace([' ', '-'], "_");
128        Self::ALL
129            .iter()
130            .copied()
131            .find(|kind| kind.as_str() == normalized)
132    }
133
134    /// Every kind, in declaration order.
135    pub const ALL: [Self; 17] = [
136        Self::Input,
137        Self::Deterministic,
138        Self::Weavatrix,
139        Self::Skill,
140        Self::AgentTask,
141        Self::LocalModel,
142        Self::QualityGate,
143        Self::HumanGate,
144        Self::TestGate,
145        Self::ReviewGate,
146        Self::EvidenceGate,
147        Self::Branch,
148        Self::Retry,
149        Self::Handoff,
150        Self::Terminal,
151        Self::UpstreamAgent,
152        Self::Output,
153    ];
154}
155
156#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
157pub struct Position {
158    pub x: f64,
159    pub y: f64,
160}
161
162/// How a node may be executed.
163///
164/// [`GraphDocument::validate`] enforces two authority rules on every policy,
165/// not just structure: mutation authority is reserved for
166/// [`ExecutionTarget::Upstream`] or [`ExecutionTarget::Human`], and so is any
167/// target whose `risk` is [`RiskLevel::High`] or above. A graph that grants
168/// mutation to a local model or an automated tool is rejected. This is a
169/// deliberate safety default of this schema; if you need different rules,
170/// leave `execution` as `None` and enforce your own policy above the graph.
171#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
172#[serde(rename_all = "camelCase")]
173pub struct ExecutionPolicy {
174    pub target: ExecutionTarget,
175    pub risk: RiskLevel,
176    pub max_input_tokens: u32,
177    pub max_output_tokens: u32,
178    pub require_evidence: bool,
179    pub require_upstream_review: bool,
180    pub allow_mutation: bool,
181    #[serde(default)]
182    pub model_profile: Option<String>,
183}
184
185#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
186#[serde(rename_all = "snake_case")]
187pub enum ExecutionTarget {
188    Deterministic,
189    Weavatrix,
190    Ollama,
191    Upstream,
192    Human,
193}
194
195#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
196#[serde(rename_all = "snake_case")]
197pub enum RiskLevel {
198    Low,
199    Medium,
200    High,
201    Critical,
202}
203
204#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
205#[serde(rename_all = "camelCase")]
206pub struct Provenance {
207    pub source: String,
208    pub locator: String,
209    #[serde(default)]
210    pub digest: Option<String>,
211}
212
213#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
214#[serde(rename_all = "camelCase")]
215pub struct GraphEdge {
216    pub id: String,
217    pub from: String,
218    pub to: String,
219    pub kind: EdgeKind,
220    #[serde(default)]
221    pub label: String,
222    #[serde(default)]
223    pub condition: Option<String>,
224}
225
226/// What an edge means. Executable kinds move a run forward; the rest express
227/// relationships between nodes.
228#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
229#[serde(rename_all = "snake_case")]
230pub enum EdgeKind {
231    /// Plain ordering: the target follows the source.
232    Sequence,
233    /// The source supplies context to the target.
234    Context,
235    /// The source invokes the target as a tool.
236    Tool,
237    /// Taken when the source succeeds.
238    Success,
239    /// Taken when the source fails.
240    Failure,
241    /// Taken only when explicitly selected by id; never inferred.
242    Conditional,
243    /// Recovery path taken when the source fails.
244    Fallback,
245    /// Taken when a gate approves.
246    Approval,
247    /// The target requires the source to have completed.
248    Requires,
249    /// Taken when a gate rejects.
250    Reject,
251    /// The source prevents the target from proceeding.
252    Blocks,
253    /// The source escalates to the target.
254    Escalates,
255    /// The source invalidates the target's result.
256    Invalidates,
257    /// The source replaces the target.
258    Supersedes,
259}
260
261/// A structural validation failure.
262///
263/// Marked `#[non_exhaustive]` so new invariants can be reported without a
264/// breaking release; match with a wildcard arm.
265#[derive(Debug, Clone, PartialEq, Eq)]
266#[non_exhaustive]
267pub enum GraphError {
268    UnsupportedSchema(String),
269    EmptyField(&'static str),
270    EmptyNodeField { node: String, field: &'static str },
271    EmptyEdgeField { edge: String, field: &'static str },
272    TooManyNodes(usize),
273    TooManyEdges(usize),
274    DuplicateNode(String),
275    DuplicateEdge(String),
276    MissingEndpoint { edge: String, node: String },
277    SelfEdge(String),
278    InvalidPosition(String),
279    InvalidExecution { node: String, message: &'static str },
280}
281
282impl Display for GraphError {
283    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
284        match self {
285            Self::UnsupportedSchema(value) => {
286                write!(formatter, "unsupported graph schema: {value}")
287            }
288            Self::EmptyField(field) => write!(formatter, "graph field must not be empty: {field}"),
289            Self::EmptyNodeField { node, field } => {
290                write!(formatter, "node {node} has an empty {field}")
291            }
292            Self::EmptyEdgeField { edge, field } => {
293                write!(formatter, "edge {edge} has an empty {field}")
294            }
295            Self::TooManyNodes(count) => {
296                write!(
297                    formatter,
298                    "graph has {count} nodes; limit is {MAX_GRAPH_NODES}"
299                )
300            }
301            Self::TooManyEdges(count) => {
302                write!(
303                    formatter,
304                    "graph has {count} edges; limit is {MAX_GRAPH_EDGES}"
305                )
306            }
307            Self::DuplicateNode(id) => write!(formatter, "duplicate node id: {id}"),
308            Self::DuplicateEdge(id) => write!(formatter, "duplicate edge id: {id}"),
309            Self::MissingEndpoint { edge, node } => {
310                write!(formatter, "edge {edge} references missing node {node}")
311            }
312            Self::SelfEdge(id) => write!(formatter, "self edge is not allowed: {id}"),
313            Self::InvalidPosition(id) => write!(formatter, "node has a non-finite position: {id}"),
314            Self::InvalidExecution { node, message } => {
315                write!(
316                    formatter,
317                    "node {node} has an invalid execution policy: {message}"
318                )
319            }
320        }
321    }
322}
323
324impl std::error::Error for GraphError {}
325
326impl GraphDocument {
327    pub fn validate(&self) -> Result<(), GraphError> {
328        if self.schema_version != GRAPH_SCHEMA_VERSION {
329            return Err(GraphError::UnsupportedSchema(self.schema_version.clone()));
330        }
331        if self.id.trim().is_empty() {
332            return Err(GraphError::EmptyField("id"));
333        }
334        if self.name.trim().is_empty() {
335            return Err(GraphError::EmptyField("name"));
336        }
337        if self.nodes.len() > MAX_GRAPH_NODES {
338            return Err(GraphError::TooManyNodes(self.nodes.len()));
339        }
340        if self.edges.len() > MAX_GRAPH_EDGES {
341            return Err(GraphError::TooManyEdges(self.edges.len()));
342        }
343
344        let mut node_ids = HashSet::with_capacity(self.nodes.len());
345        for node in &self.nodes {
346            for (field, value) in [("id", node.id.as_str()), ("label", node.label.as_str())] {
347                if value.trim().is_empty() {
348                    return Err(GraphError::EmptyNodeField {
349                        node: node.id.clone(),
350                        field,
351                    });
352                }
353            }
354            if !node_ids.insert(node.id.as_str()) {
355                return Err(GraphError::DuplicateNode(node.id.clone()));
356            }
357            if !node.position.x.is_finite() || !node.position.y.is_finite() {
358                return Err(GraphError::InvalidPosition(node.id.clone()));
359            }
360            if let Some(policy) = &node.execution {
361                validate_execution(&node.id, policy)?;
362            }
363        }
364
365        let mut edge_ids = HashSet::with_capacity(self.edges.len());
366        for edge in &self.edges {
367            for (field, value) in [
368                ("id", edge.id.as_str()),
369                ("from", edge.from.as_str()),
370                ("to", edge.to.as_str()),
371            ] {
372                if value.trim().is_empty() {
373                    return Err(GraphError::EmptyEdgeField {
374                        edge: edge.id.clone(),
375                        field,
376                    });
377                }
378            }
379            if !edge_ids.insert(edge.id.as_str()) {
380                return Err(GraphError::DuplicateEdge(edge.id.clone()));
381            }
382
383            if edge.from == edge.to {
384                return Err(GraphError::SelfEdge(edge.id.clone()));
385            }
386            for endpoint in [&edge.from, &edge.to] {
387                if !node_ids.contains(endpoint.as_str()) {
388                    return Err(GraphError::MissingEndpoint {
389                        edge: edge.id.clone(),
390                        node: endpoint.clone(),
391                    });
392                }
393            }
394        }
395        Ok(())
396    }
397
398    #[must_use]
399    pub fn reachable_from(&self, start: &str) -> HashSet<String> {
400        let mut outgoing: HashMap<&str, Vec<&str>> = HashMap::new();
401        for edge in &self.edges {
402            outgoing.entry(&edge.from).or_default().push(&edge.to);
403        }
404        let mut seen = HashSet::new();
405        let mut queue = VecDeque::from([start]);
406        while let Some(current) = queue.pop_front() {
407            if !seen.insert(current.to_owned()) {
408                continue;
409            }
410            if let Some(targets) = outgoing.get(current) {
411                queue.extend(targets.iter().copied());
412            }
413        }
414        seen
415    }
416}
417
418fn validate_execution(node: &str, policy: &ExecutionPolicy) -> Result<(), GraphError> {
419    let invalid = |message| GraphError::InvalidExecution {
420        node: node.to_owned(),
421        message,
422    };
423    if policy.max_input_tokens == 0 || policy.max_output_tokens == 0 {
424        return Err(invalid("token budgets must be greater than zero"));
425    }
426    if policy
427        .model_profile
428        .as_ref()
429        .is_some_and(|value| value.trim().is_empty())
430    {
431        return Err(invalid("model profile must not be empty"));
432    }
433    if policy.allow_mutation
434        && !matches!(
435            policy.target,
436            ExecutionTarget::Upstream | ExecutionTarget::Human
437        )
438    {
439        return Err(invalid(
440            "only upstream or human targets may receive mutation authority",
441        ));
442    }
443    if policy.risk >= RiskLevel::High
444        && !matches!(
445            policy.target,
446            ExecutionTarget::Upstream | ExecutionTarget::Human
447        )
448    {
449        return Err(invalid(
450            "high-risk work must target an upstream agent or human",
451        ));
452    }
453    if policy.target == ExecutionTarget::Ollama
454        && (!policy.require_upstream_review || policy.allow_mutation)
455    {
456        return Err(invalid(
457            "Ollama work must be advisory and require upstream review",
458        ));
459    }
460    Ok(())
461}
462
463#[cfg(test)]
464mod tests;