Skip to main content

stateknot_core/
child_run_policy.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Immutable delegation declarations. Live ownership still needs a transaction.
5
6use std::collections::BTreeMap;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, de};
10use thiserror::Error;
11
12use crate::{
13    AgentDescriptor, CapabilityIdentity, ChildRunAdmissionIntent, ChildRunSlot, CompiledGraph,
14    Digest, GraphReference, NodeId, SchemaReference,
15};
16
17/// Exact Agent definition pin, including instructions, tools, model and limits.
18///
19/// Identity alone cannot detect different definitions published under the same
20/// owner/name/version. This domain-separated digest includes the complete
21/// canonical descriptor, without copying its private content into the parent.
22#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
23#[serde(deny_unknown_fields)]
24pub struct ChildAgentReference {
25    identity: CapabilityIdentity,
26    definition_digest: Digest,
27}
28
29impl ChildAgentReference {
30    /// Pins a complete trusted descriptor using strict interoperable JSON.
31    pub fn from_descriptor(descriptor: &AgentDescriptor) -> Result<Self, ChildRunPolicyError> {
32        let canonical = crate::agent_admission::canonical_bytes(descriptor)
33            .map_err(|_| ChildRunPolicyError::AgentEncoding)?;
34        let mut bytes = b"stateknot.child-agent-definition.v1\0".to_vec();
35        bytes.extend_from_slice(&canonical);
36        Ok(Self {
37            identity: descriptor.metadata().identity().clone(),
38            definition_digest: Digest::sha256(bytes),
39        })
40    }
41
42    /// Returns the exact owner-qualified Agent version.
43    #[must_use]
44    pub const fn identity(&self) -> &CapabilityIdentity {
45        &self.identity
46    }
47
48    /// Returns the complete descriptor fingerprint, not an authorization grant.
49    #[must_use]
50    pub const fn definition_digest(&self) -> Digest {
51        self.definition_digest
52    }
53}
54
55/// One node-owned, named delegation slot with pinned Agent and graph contracts.
56#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
57#[serde(deny_unknown_fields)]
58pub struct ChildRunDeclaration {
59    node_id: NodeId,
60    slot: ChildRunSlot,
61    agent: ChildAgentReference,
62    graph: GraphReference,
63    input_schema: SchemaReference,
64    output_schema: SchemaReference,
65}
66
67impl ChildRunDeclaration {
68    /// Declares exactly one target. Schema pins must match its compiled graph.
69    pub fn new(
70        node_id: NodeId,
71        slot: ChildRunSlot,
72        agent: &AgentDescriptor,
73        graph: &CompiledGraph,
74    ) -> Result<Self, ChildRunPolicyError> {
75        if agent.input_schema() != graph.input_schema()
76            || agent.output_schema() != graph.output_schema()
77        {
78            return Err(ChildRunPolicyError::TargetSchemaMismatch);
79        }
80        Ok(Self {
81            node_id,
82            slot,
83            agent: ChildAgentReference::from_descriptor(agent)?,
84            graph: graph.reference(),
85            input_schema: agent.input_schema().clone(),
86            output_schema: agent.output_schema().clone(),
87        })
88    }
89
90    /// Returns the owning node in the parent graph.
91    #[must_use]
92    pub const fn node_id(&self) -> &NodeId {
93        &self.node_id
94    }
95
96    /// Returns the stable, case-sensitive slot identity.
97    #[must_use]
98    pub const fn slot(&self) -> &ChildRunSlot {
99        &self.slot
100    }
101
102    /// Returns the complete Agent definition pin.
103    #[must_use]
104    pub const fn agent(&self) -> &ChildAgentReference {
105        &self.agent
106    }
107
108    /// Returns the exact independently executable child graph.
109    #[must_use]
110    pub const fn graph(&self) -> &GraphReference {
111        &self.graph
112    }
113
114    /// Returns the pinned child input schema.
115    #[must_use]
116    pub const fn input_schema(&self) -> &SchemaReference {
117        &self.input_schema
118    }
119
120    /// Returns the pinned child terminal output schema.
121    #[must_use]
122    pub const fn output_schema(&self) -> &SchemaReference {
123        &self.output_schema
124    }
125
126    /// Validates a locally resolved graph and strictly decreasing depth.
127    ///
128    /// Depth counts edges below this Run (a leaf has depth zero). Every target
129    /// must fit the parent's declared remaining depth. This excludes recursive
130    /// deployment cycles; it does not count live descendants or reserve budget.
131    pub fn validate_target(
132        &self,
133        target: &CompiledGraph,
134        limits: ChildRunTopologyLimits,
135    ) -> Result<(), ChildRunPolicyError> {
136        if &target.reference() != self.graph() {
137            return Err(ChildRunPolicyError::TargetGraphMismatch);
138        }
139        if target.input_schema() != self.input_schema()
140            || target.output_schema() != self.output_schema()
141        {
142            return Err(ChildRunPolicyError::TargetSchemaMismatch);
143        }
144        let child_depth = target
145            .child_runs()
146            .map_or(0, |policy| policy.limits().maximum_descendant_depth());
147        if child_depth >= limits.maximum_descendant_depth() {
148            return Err(ChildRunPolicyError::DepthNotNarrowed);
149        }
150        Ok(())
151    }
152}
153
154/// Finite topology limits pinned by a parent graph, never unlimited defaults.
155///
156/// Children-per-activation is bounded separately by the declared slot set.
157/// `maximum_children_per_run` counts lifetime immediate children, including
158/// terminated children; `maximum_active_descendants` counts nonterminal Runs
159/// anywhere below this Run. A store must enforce all ancestor limits atomically.
160#[derive(Clone, Copy, Debug, Eq, JsonSchema, PartialEq, Serialize)]
161#[serde(deny_unknown_fields)]
162// Wire names distinguish ceilings from future observed topology counts.
163#[allow(clippy::struct_field_names)]
164pub struct ChildRunTopologyLimits {
165    #[schemars(range(min = 1, max = 32))]
166    maximum_descendant_depth: u16,
167    #[schemars(range(min = 1, max = 256))]
168    maximum_children_per_run: u16,
169    #[schemars(range(min = 1, max = 256))]
170    maximum_active_descendants: u16,
171}
172
173impl ChildRunTopologyLimits {
174    /// Hard limit for bounded ancestor traversal.
175    pub const MAX_DEPTH: u16 = 32;
176    /// Hard lifetime direct-child and live-descendant count bound.
177    pub const MAX_CHILDREN: u16 = 256;
178
179    /// Constructs positive ceilings within the framework limits.
180    pub fn new(depth: u16, children: u16, active: u16) -> Result<Self, ChildRunPolicyError> {
181        if !(1..=Self::MAX_DEPTH).contains(&depth)
182            || !(1..=Self::MAX_CHILDREN).contains(&children)
183            || !(1..=Self::MAX_CHILDREN).contains(&active)
184        {
185            return Err(ChildRunPolicyError::InvalidLimits);
186        }
187        Ok(Self {
188            maximum_descendant_depth: depth,
189            maximum_children_per_run: children,
190            maximum_active_descendants: active,
191        })
192    }
193
194    /// Returns maximum remaining descendant edges from this Run.
195    #[must_use]
196    pub const fn maximum_descendant_depth(self) -> u16 {
197        self.maximum_descendant_depth
198    }
199
200    /// Returns the lifetime immediate-child ceiling, not active child count.
201    #[must_use]
202    pub const fn maximum_children_per_run(self) -> u16 {
203        self.maximum_children_per_run
204    }
205
206    /// Returns the simultaneous nonterminal-descendant ceiling.
207    #[must_use]
208    pub const fn maximum_active_descendants(self) -> u16 {
209        self.maximum_active_descendants
210    }
211}
212
213impl<'de> Deserialize<'de> for ChildRunTopologyLimits {
214    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
215        #[derive(Deserialize)]
216        #[serde(deny_unknown_fields)]
217        #[allow(clippy::struct_field_names)]
218        struct Wire {
219            maximum_descendant_depth: u16,
220            maximum_children_per_run: u16,
221            maximum_active_descendants: u16,
222        }
223        let wire = Wire::deserialize(deserializer)?;
224        Self::new(
225            wire.maximum_descendant_depth,
226            wire.maximum_children_per_run,
227            wire.maximum_active_descendants,
228        )
229        .map_err(de::Error::custom)
230    }
231}
232
233/// Closed version-one delegation profile embedded in the parent graph digest.
234///
235/// Declarations are sorted by `(node_id, slot)`, which also defines future join
236/// reduction order. Only cancel-and-join is supported; no detached option exists.
237/// A graph without this policy delegates nothing. This profile authorizes only
238/// declared target selection, not live admission or external side effects.
239#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
240#[serde(deny_unknown_fields)]
241pub struct GraphChildRunPolicy {
242    #[schemars(range(min = 1, max = 1))]
243    version: u8,
244    limits: ChildRunTopologyLimits,
245    #[schemars(length(min = 1, max = 256))]
246    declarations: Box<[ChildRunDeclaration]>,
247}
248
249impl GraphChildRunPolicy {
250    /// Maximum declarations in one graph definition.
251    pub const MAX_DECLARATIONS: usize = 256;
252    /// Maximum distinct child slots for one node activation.
253    pub const MAX_SLOTS_PER_NODE: usize = 64;
254
255    /// Validates and orders bounded, duplicate-free declarations.
256    pub fn new<I>(
257        limits: ChildRunTopologyLimits,
258        declarations: I,
259    ) -> Result<Self, ChildRunPolicyError>
260    where
261        I: IntoIterator<Item = ChildRunDeclaration>,
262    {
263        let mut ordered = BTreeMap::new();
264        let mut per_node = BTreeMap::new();
265        for declaration in declarations {
266            if ordered.len() == Self::MAX_DECLARATIONS {
267                return Err(ChildRunPolicyError::TooManyDeclarations);
268            }
269            let count = per_node.entry(declaration.node_id.clone()).or_insert(0);
270            *count += 1;
271            if *count > Self::MAX_SLOTS_PER_NODE {
272                return Err(ChildRunPolicyError::TooManyNodeSlots);
273            }
274            let key = (declaration.node_id.clone(), declaration.slot.clone());
275            if ordered.insert(key, declaration).is_some() {
276                return Err(ChildRunPolicyError::DuplicateSlot);
277            }
278        }
279        if ordered.is_empty() {
280            return Err(ChildRunPolicyError::EmptyDeclarations);
281        }
282        Ok(Self {
283            version: 1,
284            limits,
285            declarations: ordered.into_values().collect(),
286        })
287    }
288
289    /// Returns the exact finite topology contract.
290    #[must_use]
291    pub const fn limits(&self) -> ChildRunTopologyLimits {
292        self.limits
293    }
294
295    /// Returns declarations in canonical node/slot order.
296    #[must_use]
297    pub const fn declarations(&self) -> &[ChildRunDeclaration] {
298        &self.declarations
299    }
300
301    /// Resolves one node-owned slot. Another node's equal slot name is distinct.
302    #[must_use]
303    pub fn declaration(&self, node: &NodeId, slot: &ChildRunSlot) -> Option<&ChildRunDeclaration> {
304        self.declarations
305            .binary_search_by(|value| (&value.node_id, &value.slot).cmp(&(node, slot)))
306            .ok()
307            .map(|index| &self.declarations[index])
308    }
309
310    pub(crate) fn validate_nodes(&self, graph: &CompiledGraph) -> Result<(), ChildRunPolicyError> {
311        if self
312            .declarations
313            .iter()
314            .any(|item| graph.node(item.node_id()).is_none())
315        {
316            return Err(ChildRunPolicyError::UndeclaredParentNode);
317        }
318        Ok(())
319    }
320}
321
322impl<'de> Deserialize<'de> for GraphChildRunPolicy {
323    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
324        #[derive(Deserialize)]
325        #[serde(deny_unknown_fields)]
326        struct Wire {
327            version: u8,
328            limits: ChildRunTopologyLimits,
329            #[serde(deserialize_with = "bounded_declarations")]
330            declarations: Vec<ChildRunDeclaration>,
331        }
332        let wire = Wire::deserialize(deserializer)?;
333        if wire.version != 1 {
334            return Err(de::Error::custom(ChildRunPolicyError::UnsupportedVersion));
335        }
336        Self::new(wire.limits, wire.declarations).map_err(de::Error::custom)
337    }
338}
339
340fn bounded_declarations<'de, D: Deserializer<'de>>(
341    deserializer: D,
342) -> Result<Vec<ChildRunDeclaration>, D::Error> {
343    struct Visitor;
344    impl<'de> de::Visitor<'de> for Visitor {
345        type Value = Vec<ChildRunDeclaration>;
346
347        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
348            formatter.write_str("at most 256 child declarations")
349        }
350
351        fn visit_seq<A: de::SeqAccess<'de>>(
352            self,
353            mut sequence: A,
354        ) -> Result<Self::Value, A::Error> {
355            let maximum = GraphChildRunPolicy::MAX_DECLARATIONS;
356            if sequence.size_hint().is_some_and(|size| size > maximum) {
357                return Err(de::Error::custom(ChildRunPolicyError::TooManyDeclarations));
358            }
359            let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(maximum));
360            while let Some(value) = sequence.next_element()? {
361                if values.len() == maximum {
362                    return Err(de::Error::custom(ChildRunPolicyError::TooManyDeclarations));
363                }
364                values.push(value);
365            }
366            Ok(values)
367        }
368    }
369    deserializer.deserialize_seq(Visitor)
370}
371
372impl ChildRunAdmissionIntent {
373    /// Checks target selection against the exact trusted parent graph policy.
374    ///
375    /// This is independent of `validate_for`: callers must perform both checks
376    /// using authoritative graph/admission/checkpoint snapshots. Neither is an
377    /// atomic budget reservation, a fence check, or an external authority grant.
378    pub fn validate_declaration(&self, parent: &CompiledGraph) -> Result<(), ChildRunPolicyError> {
379        if self.key().parent().base_checkpoint().graph() != &parent.reference() {
380            return Err(ChildRunPolicyError::ParentGraphMismatch);
381        }
382        let policy = parent
383            .child_runs()
384            .ok_or(ChildRunPolicyError::DelegationNotDeclared)?;
385        let declaration = policy
386            .declaration(self.key().parent().node_id(), self.key().slot())
387            .ok_or(ChildRunPolicyError::DelegationNotDeclared)?;
388        declaration.validate_target(self.child_graph(), policy.limits())?;
389        if declaration.agent() != &ChildAgentReference::from_descriptor(self.child().descriptor())?
390        {
391            return Err(ChildRunPolicyError::TargetAgentMismatch);
392        }
393        Ok(())
394    }
395}
396
397/// Public-safe declaration/profile validation failure; no request data is exposed.
398#[derive(Clone, Debug, Eq, Error, PartialEq)]
399#[non_exhaustive]
400pub enum ChildRunPolicyError {
401    /// Complete descriptor could not be encoded as interoperable canonical JSON.
402    #[error("child Agent definition encoding failed")]
403    AgentEncoding,
404    /// A limit is zero or exceeds its fixed resource ceiling.
405    #[error("invalid child topology limits")]
406    InvalidLimits,
407    /// An empty policy is not a delegation declaration.
408    #[error("child policy must declare at least one slot")]
409    EmptyDeclarations,
410    /// Aggregate graph declarations exceeded their fixed bound.
411    #[error("too many graph child declarations")]
412    TooManyDeclarations,
413    /// One activation could select too many distinct slots.
414    #[error("too many child slots on one node")]
415    TooManyNodeSlots,
416    /// A node/slot identity was repeated.
417    #[error("duplicate child slot on one node")]
418    DuplicateSlot,
419    /// Version is not supported and must not be treated as the current profile.
420    #[error("unsupported child policy version")]
421    UnsupportedVersion,
422    /// A declaration refers to a node missing from its parent graph.
423    #[error("child declaration references an unknown parent node")]
424    UndeclaredParentNode,
425    /// The trusted graph is not the graph pinned by the parent activation.
426    #[error("child declaration parent graph mismatch")]
427    ParentGraphMismatch,
428    /// There is no delegation policy or no slot owned by this parent node.
429    #[error("child delegation is not declared by the parent node")]
430    DelegationNotDeclared,
431    /// Target identity, version, graph bytes, or state schema changed.
432    #[error("declared child graph mismatch")]
433    TargetGraphMismatch,
434    /// Target input/output schema pins differ.
435    #[error("declared child input or output schema mismatch")]
436    TargetSchemaMismatch,
437    /// The full target Agent descriptor differs, even under an equal identity.
438    #[error("declared child Agent definition mismatch")]
439    TargetAgentMismatch,
440    /// A nested target could exceed the parent's remaining descendant depth.
441    #[error("declared child depth does not narrow the parent depth")]
442    DepthNotNarrowed,
443}
444
445#[cfg(test)]
446#[path = "child_run_policy_tests.rs"]
447mod tests;