Skip to main content

stateknot_core/
tool_invocation.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Durable, integrity-bound state machine for logical tool invocations.
5//!
6//! A logical invocation is anchored to one graph-node activation and keeps the
7//! same [`InvocationId`] across physical attempts. Preparation and every state
8//! transition are committed with an exact run-journal head. The executor must
9//! never perform an external call while holding the store transaction: it first
10//! commits `prepared`, claims an `executing` attempt, performs the call, then
11//! commits its result or public-safe failure under the current run fence.
12
13use std::{fmt, str::FromStr};
14
15use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
16use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
17use thiserror::Error;
18
19use crate::decimal::{UnsignedDecimalError, parse_bounded_u64};
20use crate::{
21    AttemptId, ByteCount, Checkpoint, CheckpointHead, Digest, ExecutionCount, InvocationId,
22    JournalHead, JournalSequence, NodeId, RetryAdvice, RunId, TenantId, Timestamp, ToolDescriptor,
23    ToolError, ToolExecutionLimits, ToolExternalEffect, ToolInput, ToolResult, ToolRisk,
24};
25
26const MAX_DATABASE_ORDINAL: u64 = i64::MAX as u64;
27const INVOCATION_REVISION_PATTERN: &str = "^(0|[1-9][0-9]{0,18})$";
28const GRAPH_NAMESPACE_PATTERN: &str =
29    "^(?:[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(?:/[A-Za-z0-9][A-Za-z0-9_.-]{0,127})*)?$";
30const READY_NODE_INPUT_DIGEST_DOMAIN: &[u8] = b"stateknot-ready-node-input-v1\0";
31const INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-tool-invocation-intent-v1\0";
32const TRANSITION_DIGEST_DOMAIN: &[u8] = b"stateknot-tool-invocation-transition-v1\0";
33const RECORD_DIGEST_DOMAIN: &[u8] = b"stateknot-tool-invocation-record-v1\0";
34
35/// Slash-separated namespace of one node inside a root or nested graph.
36///
37/// The empty string identifies the root graph. Non-root segments use the same
38/// bounded grammar as [`NodeId`], which makes the canonical representation safe
39/// for compound database keys without permitting path traversal components.
40#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
41pub struct GraphNamespace(Box<str>);
42
43impl GraphNamespace {
44    /// Maximum encoded namespace length in bytes.
45    pub const MAX_LEN: usize = 512;
46
47    /// Constructs the root graph namespace.
48    #[must_use]
49    pub fn root() -> Self {
50        Self(Box::from(""))
51    }
52
53    /// Validates and constructs a graph namespace.
54    ///
55    /// # Errors
56    ///
57    /// Returns [`GraphNamespaceError`] for an oversized namespace or an empty,
58    /// path-like, or otherwise invalid non-root segment.
59    pub fn new(value: impl Into<String>) -> Result<Self, GraphNamespaceError> {
60        let value = value.into();
61        if value.len() > Self::MAX_LEN {
62            return Err(GraphNamespaceError::TooLong {
63                maximum: Self::MAX_LEN,
64                actual: value.len(),
65            });
66        }
67        if value.is_empty() {
68            return Ok(Self::root());
69        }
70        for (index, segment) in value.split('/').enumerate() {
71            NodeId::new(segment)
72                .map_err(|source| GraphNamespaceError::InvalidSegment { index, source })?;
73        }
74        Ok(Self(value.into_boxed_str()))
75    }
76
77    /// Returns the canonical namespace text, empty for the root graph.
78    #[must_use]
79    pub fn as_str(&self) -> &str {
80        &self.0
81    }
82
83    /// Returns whether this is the root graph namespace.
84    #[must_use]
85    pub fn is_root(&self) -> bool {
86        self.0.is_empty()
87    }
88}
89
90impl Default for GraphNamespace {
91    fn default() -> Self {
92        Self::root()
93    }
94}
95
96impl AsRef<str> for GraphNamespace {
97    fn as_ref(&self) -> &str {
98        self.as_str()
99    }
100}
101
102impl fmt::Debug for GraphNamespace {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        formatter
105            .debug_tuple("GraphNamespace")
106            .field(&self.as_str())
107            .finish()
108    }
109}
110
111impl fmt::Display for GraphNamespace {
112    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113        formatter.write_str(self.as_str())
114    }
115}
116
117impl FromStr for GraphNamespace {
118    type Err = GraphNamespaceError;
119
120    fn from_str(value: &str) -> Result<Self, Self::Err> {
121        Self::new(value)
122    }
123}
124
125impl TryFrom<String> for GraphNamespace {
126    type Error = GraphNamespaceError;
127
128    fn try_from(value: String) -> Result<Self, Self::Error> {
129        Self::new(value)
130    }
131}
132
133impl TryFrom<&str> for GraphNamespace {
134    type Error = GraphNamespaceError;
135
136    fn try_from(value: &str) -> Result<Self, Self::Error> {
137        Self::new(value)
138    }
139}
140
141impl Serialize for GraphNamespace {
142    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
143    where
144        S: Serializer,
145    {
146        serializer.serialize_str(self.as_str())
147    }
148}
149
150impl<'de> Deserialize<'de> for GraphNamespace {
151    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
152    where
153        D: Deserializer<'de>,
154    {
155        deserializer.deserialize_string(GraphNamespaceVisitor)
156    }
157}
158
159struct GraphNamespaceVisitor;
160
161impl de::Visitor<'_> for GraphNamespaceVisitor {
162    type Value = GraphNamespace;
163
164    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
165        formatter.write_str("a root or slash-separated bounded graph namespace")
166    }
167
168    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
169    where
170        E: de::Error,
171    {
172        GraphNamespace::try_from(value).map_err(E::custom)
173    }
174
175    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
176    where
177        E: de::Error,
178    {
179        GraphNamespace::try_from(value).map_err(E::custom)
180    }
181}
182
183impl JsonSchema for GraphNamespace {
184    fn schema_name() -> std::borrow::Cow<'static, str> {
185        "GraphNamespace".into()
186    }
187
188    fn schema_id() -> std::borrow::Cow<'static, str> {
189        concat!(module_path!(), "::GraphNamespace").into()
190    }
191
192    fn json_schema(_: &mut SchemaGenerator) -> Schema {
193        json_schema!({
194            "type": "string",
195            "maxLength": 512,
196            "pattern": GRAPH_NAMESPACE_PATTERN,
197            "description": "The empty string is the root graph. Runtime additionally rejects '.' and '..' segments."
198        })
199    }
200
201    fn inline_schema() -> bool {
202        true
203    }
204}
205
206/// Invalid graph namespace.
207#[derive(Clone, Debug, Eq, Error, PartialEq)]
208#[non_exhaustive]
209pub enum GraphNamespaceError {
210    /// The encoded namespace exceeded its hard wire and index ceiling.
211    #[error("graph namespace is {actual} bytes; maximum is {maximum}")]
212    TooLong {
213        /// Maximum supported bytes.
214        maximum: usize,
215        /// Observed bytes.
216        actual: usize,
217    },
218    /// One non-root path segment was not a valid node identity.
219    #[error("graph namespace segment {index} is invalid: {source}")]
220    InvalidSegment {
221        /// Zero-based segment position.
222        index: usize,
223        /// Exact node-identity validation failure.
224        #[source]
225        source: crate::NodeIdError,
226    },
227}
228
229/// Monotonic zero-based revision of one logical invocation record.
230///
231/// The decimal-string wire form preserves exact values across languages and
232/// the maximum matches a signed `PostgreSQL BIGINT`.
233#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
234pub struct ToolInvocationRevision(u64);
235
236impl ToolInvocationRevision {
237    /// Preparation record revision.
238    pub const INITIAL: Self = Self(0);
239    /// Largest revision supported by the v1 storage contract.
240    pub const MAX: Self = Self(MAX_DATABASE_ORDINAL);
241
242    /// Constructs a storage-compatible revision.
243    ///
244    /// # Errors
245    ///
246    /// Returns [`ToolInvocationRevisionError::AboveMaximum`] above signed
247    /// `BIGINT`.
248    pub const fn new(value: u64) -> Result<Self, ToolInvocationRevisionError> {
249        if value > MAX_DATABASE_ORDINAL {
250            return Err(ToolInvocationRevisionError::AboveMaximum);
251        }
252        Ok(Self(value))
253    }
254
255    /// Returns the integer revision.
256    #[must_use]
257    pub const fn get(self) -> u64 {
258        self.0
259    }
260
261    /// Returns the exact next revision or `None` at the storage ceiling.
262    #[must_use]
263    pub const fn checked_next(self) -> Option<Self> {
264        if self.0 == MAX_DATABASE_ORDINAL {
265            None
266        } else {
267            Some(Self(self.0 + 1))
268        }
269    }
270}
271
272impl fmt::Display for ToolInvocationRevision {
273    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
274        self.0.fmt(formatter)
275    }
276}
277
278impl FromStr for ToolInvocationRevision {
279    type Err = ToolInvocationRevisionError;
280
281    fn from_str(value: &str) -> Result<Self, Self::Err> {
282        let value = parse_bounded_u64(value, MAX_DATABASE_ORDINAL)
283            .map_err(ToolInvocationRevisionError::from_decimal_error)?;
284        Self::new(value)
285    }
286}
287
288impl Serialize for ToolInvocationRevision {
289    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
290    where
291        S: Serializer,
292    {
293        serializer.collect_str(self)
294    }
295}
296
297impl<'de> Deserialize<'de> for ToolInvocationRevision {
298    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
299    where
300        D: Deserializer<'de>,
301    {
302        deserializer.deserialize_str(ToolInvocationRevisionVisitor)
303    }
304}
305
306struct ToolInvocationRevisionVisitor;
307
308impl de::Visitor<'_> for ToolInvocationRevisionVisitor {
309    type Value = ToolInvocationRevision;
310
311    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
312        formatter.write_str("a canonical non-negative decimal PostgreSQL BIGINT revision")
313    }
314
315    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
316    where
317        E: de::Error,
318    {
319        value.parse().map_err(E::custom)
320    }
321}
322
323impl JsonSchema for ToolInvocationRevision {
324    fn schema_name() -> std::borrow::Cow<'static, str> {
325        "ToolInvocationRevision".into()
326    }
327
328    fn schema_id() -> std::borrow::Cow<'static, str> {
329        concat!(module_path!(), "::ToolInvocationRevision").into()
330    }
331
332    fn json_schema(_: &mut SchemaGenerator) -> Schema {
333        json_schema!({
334            "type": "string",
335            "minLength": 1,
336            "maxLength": 19,
337            "pattern": INVOCATION_REVISION_PATTERN
338        })
339    }
340
341    fn inline_schema() -> bool {
342        true
343    }
344}
345
346/// Invalid canonical invocation revision.
347#[derive(Clone, Debug, Eq, Error, PartialEq)]
348#[non_exhaustive]
349pub enum ToolInvocationRevisionError {
350    /// The wire value was empty or contained a non-decimal byte.
351    #[error("tool invocation revision must contain only unsigned ASCII decimal digits")]
352    InvalidFormat,
353    /// The decimal text contained a leading zero.
354    #[error("tool invocation revision must use canonical decimal text")]
355    NonCanonical,
356    /// The value exceeded signed `PostgreSQL BIGINT`.
357    #[error("tool invocation revision exceeds the PostgreSQL BIGINT maximum")]
358    AboveMaximum,
359}
360
361impl ToolInvocationRevisionError {
362    const fn from_decimal_error(error: UnsignedDecimalError) -> Self {
363        match error {
364            UnsignedDecimalError::Empty | UnsignedDecimalError::InvalidCharacter { .. } => {
365                Self::InvalidFormat
366            }
367            UnsignedDecimalError::LeadingZero => Self::NonCanonical,
368            UnsignedDecimalError::TooLong { .. } | UnsignedDecimalError::Overflow => {
369                Self::AboveMaximum
370            }
371        }
372    }
373}
374
375/// Exact graph-node activation that owns a logical tool invocation.
376///
377/// `input_digest` is the scheduler-computed digest of the node's deterministic
378/// activation input, not merely the tool arguments. The store must additionally
379/// prove from the full base checkpoint that this node belongs to its ready set.
380#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
381#[serde(deny_unknown_fields)]
382pub struct NodeActivation {
383    base_checkpoint: CheckpointHead,
384    graph_namespace: GraphNamespace,
385    node_id: NodeId,
386    input_digest: Digest,
387}
388
389impl NodeActivation {
390    /// Constructs a node activation from already validated identities.
391    #[must_use]
392    pub const fn new(
393        base_checkpoint: CheckpointHead,
394        graph_namespace: GraphNamespace,
395        node_id: NodeId,
396        input_digest: Digest,
397    ) -> Self {
398        Self {
399            base_checkpoint,
400            graph_namespace,
401            node_id,
402            input_digest,
403        }
404    }
405
406    /// Derives the canonical root-graph activation for one ready node.
407    ///
408    /// The logical input digest is domain-separated from every other checksum
409    /// and binds the complete base-checkpoint digest, root namespace, and node
410    /// identity. Replaying the same checkpoint therefore produces byte-for-byte
411    /// identical activations without consulting a process clock, worker ID, or
412    /// completion order.
413    ///
414    /// # Errors
415    ///
416    /// Returns [`NodeActivationError::NodeNotReady`] when `node_id` is absent
417    /// from the checkpoint's exact ready set, or
418    /// [`NodeActivationError::CanonicalSerialization`] if the closed digest
419    /// preimage cannot be encoded canonically.
420    pub fn for_ready_root(
421        checkpoint: &Checkpoint,
422        node_id: NodeId,
423    ) -> Result<Self, NodeActivationError> {
424        if !checkpoint.ready_nodes().contains(&node_id) {
425            return Err(NodeActivationError::NodeNotReady { node_id });
426        }
427        let graph_namespace = GraphNamespace::root();
428        let input_digest =
429            compute_ready_node_input_digest(checkpoint.digest(), &graph_namespace, &node_id)?;
430        Ok(Self::new(
431            checkpoint.head(),
432            graph_namespace,
433            node_id,
434            input_digest,
435        ))
436    }
437
438    /// Returns the exact base checkpoint head.
439    #[must_use]
440    pub const fn base_checkpoint(&self) -> &CheckpointHead {
441        &self.base_checkpoint
442    }
443
444    /// Returns the graph namespace containing the node.
445    #[must_use]
446    pub const fn graph_namespace(&self) -> &GraphNamespace {
447        &self.graph_namespace
448    }
449
450    /// Returns the durable node identity.
451    #[must_use]
452    pub const fn node_id(&self) -> &NodeId {
453        &self.node_id
454    }
455
456    /// Returns the deterministic activation-input digest.
457    #[must_use]
458    pub const fn input_digest(&self) -> Digest {
459        self.input_digest
460    }
461
462    /// Returns the tenant boundary inherited from the checkpoint.
463    #[must_use]
464    pub const fn tenant_id(&self) -> &TenantId {
465        self.base_checkpoint.tenant_id()
466    }
467
468    /// Returns the run identity inherited from the checkpoint.
469    #[must_use]
470    pub const fn run_id(&self) -> RunId {
471        self.base_checkpoint.run_id()
472    }
473}
474
475/// Invalid deterministic construction of a ready-node activation.
476#[derive(Clone, Debug, Eq, Error, PartialEq)]
477#[non_exhaustive]
478pub enum NodeActivationError {
479    /// The requested node is absent from the checkpoint's exact ready set.
480    #[error("node {node_id:?} is not ready in the base checkpoint")]
481    NodeNotReady {
482        /// Rejected node identity.
483        node_id: NodeId,
484    },
485    /// The closed activation-input checksum preimage could not be canonicalized.
486    #[error("ready-node activation input canonical serialization failed")]
487    CanonicalSerialization,
488}
489
490/// One resolved limit field used in narrowed-limit diagnostics.
491#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
492#[non_exhaustive]
493#[serde(rename_all = "snake_case")]
494pub enum ToolInvocationLimit {
495    /// Attempt timeout.
496    Timeout,
497    /// Capability concurrency.
498    MaxConcurrency,
499    /// Encoded argument bytes.
500    MaxInputBytes,
501    /// Inline result bytes.
502    MaxInlineResultBytes,
503    /// Result artifact count.
504    MaxArtifacts,
505    /// Aggregate result artifact bytes.
506    MaxTotalArtifactBytes,
507}
508
509/// Immutable preparation intent for one logical tool invocation.
510#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
511#[serde(deny_unknown_fields)]
512pub struct ToolInvocationIntent {
513    activation: NodeActivation,
514    invocation_id: InvocationId,
515    descriptor: ToolDescriptor,
516    input: ToolInput,
517    effective_limits: ToolExecutionLimits,
518    intent_digest: Digest,
519}
520
521impl ToolInvocationIntent {
522    /// Constructs and checksums a durable invocation intent.
523    ///
524    /// `effective_limits` is the already resolved intersection of system,
525    /// tenant, policy, run-budget, and descriptor ceilings. It may only narrow
526    /// the immutable descriptor.
527    ///
528    /// # Errors
529    ///
530    /// Returns [`ToolInvocationIntentError`] for schema substitution, widened
531    /// limits, oversized arguments, or an integrity serialization failure.
532    pub fn new(
533        activation: NodeActivation,
534        invocation_id: InvocationId,
535        descriptor: ToolDescriptor,
536        input: ToolInput,
537        effective_limits: ToolExecutionLimits,
538    ) -> Result<Self, ToolInvocationIntentError> {
539        validate_intent_shape(&descriptor, &input, &effective_limits)?;
540        let intent_digest = compute_intent_digest(&ToolInvocationIntentDigestWire {
541            activation: &activation,
542            invocation_id,
543            descriptor: &descriptor,
544            input: &input,
545            effective_limits: &effective_limits,
546        })?;
547        Ok(Self {
548            activation,
549            invocation_id,
550            descriptor,
551            input,
552            effective_limits,
553            intent_digest,
554        })
555    }
556
557    /// Restores an intent and verifies its invariant and checksum layers.
558    ///
559    /// # Errors
560    ///
561    /// Returns [`ToolInvocationIntentError`] when validation or integrity fails.
562    pub fn restore(
563        activation: NodeActivation,
564        invocation_id: InvocationId,
565        descriptor: ToolDescriptor,
566        input: ToolInput,
567        effective_limits: ToolExecutionLimits,
568        intent_digest: Digest,
569    ) -> Result<Self, ToolInvocationIntentError> {
570        let restored = Self::new(
571            activation,
572            invocation_id,
573            descriptor,
574            input,
575            effective_limits,
576        )?;
577        if restored.intent_digest != intent_digest {
578            return Err(ToolInvocationIntentError::DigestMismatch);
579        }
580        Ok(restored)
581    }
582
583    /// Returns the owning graph-node activation.
584    #[must_use]
585    pub const fn activation(&self) -> &NodeActivation {
586        &self.activation
587    }
588
589    /// Returns the stable logical invocation identifier.
590    #[must_use]
591    pub const fn invocation_id(&self) -> InvocationId {
592        self.invocation_id
593    }
594
595    /// Returns the exact registered tool-version snapshot.
596    #[must_use]
597    pub const fn descriptor(&self) -> &ToolDescriptor {
598        &self.descriptor
599    }
600
601    /// Returns bounded schema-pinned arguments.
602    #[must_use]
603    pub const fn input(&self) -> &ToolInput {
604        &self.input
605    }
606
607    /// Returns the invocation's resolved effective ceilings.
608    #[must_use]
609    pub const fn effective_limits(&self) -> &ToolExecutionLimits {
610        &self.effective_limits
611    }
612
613    /// Returns the domain-separated preparation fingerprint.
614    #[must_use]
615    pub const fn intent_digest(&self) -> Digest {
616        self.intent_digest
617    }
618
619    /// Returns the tenant boundary inherited from the activation.
620    #[must_use]
621    pub const fn tenant_id(&self) -> &TenantId {
622        self.activation.tenant_id()
623    }
624
625    /// Returns the run identity inherited from the activation.
626    #[must_use]
627    pub const fn run_id(&self) -> RunId {
628        self.activation.run_id()
629    }
630}
631
632impl fmt::Debug for ToolInvocationIntent {
633    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
634        formatter
635            .debug_struct("ToolInvocationIntent")
636            .field("activation", &self.activation)
637            .field("invocation_id", &self.invocation_id)
638            .field("descriptor", &self.descriptor)
639            .field("input", &self.input)
640            .field("effective_limits", &self.effective_limits)
641            .field("intent_digest", &self.intent_digest)
642            .finish_non_exhaustive()
643    }
644}
645
646impl<'de> Deserialize<'de> for ToolInvocationIntent {
647    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
648    where
649        D: Deserializer<'de>,
650    {
651        #[derive(Deserialize)]
652        #[serde(deny_unknown_fields)]
653        struct Wire {
654            activation: NodeActivation,
655            invocation_id: InvocationId,
656            descriptor: ToolDescriptor,
657            input: ToolInput,
658            effective_limits: ToolExecutionLimits,
659            intent_digest: Digest,
660        }
661
662        let wire = Wire::deserialize(deserializer)?;
663        Self::restore(
664            wire.activation,
665            wire.invocation_id,
666            wire.descriptor,
667            wire.input,
668            wire.effective_limits,
669            wire.intent_digest,
670        )
671        .map_err(de::Error::custom)
672    }
673}
674
675/// Invalid durable tool invocation intent.
676#[derive(Clone, Debug, Eq, Error, PartialEq)]
677#[non_exhaustive]
678pub enum ToolInvocationIntentError {
679    /// Arguments named a schema other than the pinned descriptor schema.
680    #[error("tool invocation input schema does not match the descriptor")]
681    InputSchemaMismatch,
682    /// A resolved limit widened rather than narrowed the descriptor ceiling.
683    #[error("effective tool invocation limit {limit:?} exceeds the descriptor ceiling")]
684    EffectiveLimitWidened {
685        /// Widened field.
686        limit: ToolInvocationLimit,
687    },
688    /// Compact arguments exceeded the resolved invocation limit.
689    #[error("tool invocation input is {actual} bytes; effective maximum is {maximum}")]
690    InputLimitExceeded {
691        /// Resolved input-byte ceiling.
692        maximum: ByteCount,
693        /// Exact compact input size.
694        actual: ByteCount,
695    },
696    /// Canonical integrity material could not be serialized.
697    #[error("tool invocation intent integrity calculation failed: {source}")]
698    Integrity {
699        /// Exact integrity failure.
700        #[source]
701        source: ToolInvocationIntegrityError,
702    },
703    /// Persisted intent checksum did not match caller-controlled fields.
704    #[error("tool invocation intent digest does not match its fields")]
705    DigestMismatch,
706}
707
708impl From<ToolInvocationIntegrityError> for ToolInvocationIntentError {
709    fn from(source: ToolInvocationIntegrityError) -> Self {
710        Self::Integrity { source }
711    }
712}
713
714/// Durable lifecycle state of one logical tool invocation.
715#[derive(
716    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
717)]
718#[serde(rename_all = "snake_case")]
719pub enum ToolInvocationStatus {
720    /// Intent is committed but no physical attempt has started.
721    Prepared,
722    /// Exactly one physical attempt has been durably claimed.
723    Executing,
724    /// A validated successful result is durable.
725    Committed,
726    /// A known failed outcome is durable and retry remains policy-gated.
727    Failed,
728    /// An external write outcome is ambiguous and must be reconciled.
729    Unknown,
730}
731
732/// Integrity-bound state payload of one invocation revision.
733#[derive(Clone, Debug, JsonSchema, Serialize)]
734#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
735pub enum ToolInvocationState {
736    /// Prepared intent awaiting an attempt claim.
737    Prepared,
738    /// In-flight physical attempt.
739    Executing {
740        /// Unique physical attempt identifier.
741        attempt_id: AttemptId,
742    },
743    /// Validated successful result.
744    Committed {
745        /// Exact erased result and provenance.
746        result: ToolResult,
747    },
748    /// Known failed outcome.
749    Failed {
750        /// Public-safe failure and effect evidence.
751        error: ToolError,
752    },
753    /// Ambiguous external effect awaiting reconciliation.
754    Unknown {
755        /// Public-safe ambiguous-outcome evidence.
756        error: ToolError,
757    },
758}
759
760impl ToolInvocationState {
761    /// Returns the lifecycle discriminator.
762    #[must_use]
763    pub const fn status(&self) -> ToolInvocationStatus {
764        match self {
765            Self::Prepared => ToolInvocationStatus::Prepared,
766            Self::Executing { .. } => ToolInvocationStatus::Executing,
767            Self::Committed { .. } => ToolInvocationStatus::Committed,
768            Self::Failed { .. } => ToolInvocationStatus::Failed,
769            Self::Unknown { .. } => ToolInvocationStatus::Unknown,
770        }
771    }
772
773    /// Returns the physical attempt represented by this state, if any.
774    #[must_use]
775    pub const fn attempt_id(&self) -> Option<AttemptId> {
776        match self {
777            Self::Prepared => None,
778            Self::Executing { attempt_id } => Some(*attempt_id),
779            Self::Committed { result } => Some(result.provenance().attempt_id()),
780            Self::Failed { error } | Self::Unknown { error } => {
781                Some(error.provenance().attempt_id())
782            }
783        }
784    }
785}
786
787impl<'de> Deserialize<'de> for ToolInvocationState {
788    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
789    where
790        D: Deserializer<'de>,
791    {
792        #[derive(Deserialize)]
793        #[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
794        enum Wire {
795            Prepared,
796            Executing { attempt_id: AttemptId },
797            Committed { result: ToolResult },
798            Failed { error: ToolError },
799            Unknown { error: ToolError },
800        }
801
802        Ok(match Wire::deserialize(deserializer)? {
803            Wire::Prepared => Self::Prepared,
804            Wire::Executing { attempt_id } => Self::Executing { attempt_id },
805            Wire::Committed { result } => Self::Committed { result },
806            Wire::Failed { error } => Self::Failed { error },
807            Wire::Unknown { error } => Self::Unknown { error },
808        })
809    }
810}
811
812/// Kind of one explicit invocation state transition.
813#[derive(
814    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
815)]
816#[serde(rename_all = "snake_case")]
817pub enum ToolInvocationTransitionKind {
818    /// Claim a new physical attempt.
819    StartAttempt,
820    /// Commit the executing attempt's successful result.
821    RecordResult,
822    /// Commit the executing attempt's failure evidence.
823    RecordError,
824    /// Resolve an ambiguous outcome to a successful result.
825    ReconcileResult,
826    /// Record reconciliation evidence without inventing a success.
827    ReconcileError,
828}
829
830/// Explicit transition appended to the run journal and invocation history.
831#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
832#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
833pub enum ToolInvocationTransition {
834    /// Claim a unique physical attempt after durable preparation or safe retry.
835    StartAttempt {
836        /// New physical attempt identity.
837        attempt_id: AttemptId,
838    },
839    /// Commit a successful result from the current executing attempt.
840    RecordResult {
841        /// Validated erased result.
842        result: ToolResult,
843    },
844    /// Commit public-safe failure and external-effect evidence.
845    RecordError {
846        /// Validated attempt failure.
847        error: ToolError,
848    },
849    /// Resolve the current unknown attempt to a successful result.
850    ReconcileResult {
851        /// Authoritatively recovered result of the original attempt.
852        result: ToolResult,
853    },
854    /// Record authoritative or still-ambiguous reconciliation evidence.
855    ReconcileError {
856        /// Failure evidence for the original attempt.
857        error: ToolError,
858    },
859}
860
861impl ToolInvocationTransition {
862    /// Returns the closed transition discriminator.
863    #[must_use]
864    pub const fn kind(&self) -> ToolInvocationTransitionKind {
865        match self {
866            Self::StartAttempt { .. } => ToolInvocationTransitionKind::StartAttempt,
867            Self::RecordResult { .. } => ToolInvocationTransitionKind::RecordResult,
868            Self::RecordError { .. } => ToolInvocationTransitionKind::RecordError,
869            Self::ReconcileResult { .. } => ToolInvocationTransitionKind::ReconcileResult,
870            Self::ReconcileError { .. } => ToolInvocationTransitionKind::ReconcileError,
871        }
872    }
873}
874
875/// Compact exact identity of a validated invocation revision.
876///
877/// A head is an optimistic comparison token. It intentionally omits arguments,
878/// results, and errors; obtain it from [`ToolInvocation::head`] or from storage
879/// that has restored and verified the corresponding full record.
880#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
881#[serde(deny_unknown_fields)]
882pub struct ToolInvocationHead {
883    tenant_id: TenantId,
884    run_id: RunId,
885    invocation_id: InvocationId,
886    revision: ToolInvocationRevision,
887    status: ToolInvocationStatus,
888    #[serde(skip_serializing_if = "Option::is_none")]
889    attempt_id: Option<AttemptId>,
890    journal_head: JournalHead,
891    digest: Digest,
892}
893
894impl ToolInvocationHead {
895    /// Constructs a trusted compact head while enforcing scope and state shape.
896    ///
897    /// # Errors
898    ///
899    /// Returns [`ToolInvocationHeadError`] for crossed journal scope or an
900    /// impossible status/attempt combination.
901    #[allow(clippy::too_many_arguments)]
902    pub fn new(
903        tenant_id: TenantId,
904        run_id: RunId,
905        invocation_id: InvocationId,
906        revision: ToolInvocationRevision,
907        status: ToolInvocationStatus,
908        attempt_id: Option<AttemptId>,
909        journal_head: JournalHead,
910        digest: Digest,
911    ) -> Result<Self, ToolInvocationHeadError> {
912        validate_journal_scope(&tenant_id, run_id, &journal_head)
913            .map_err(ToolInvocationHeadError::from_scope)?;
914        validate_status_attempt(status, attempt_id)?;
915        validate_revision_status(revision, status)?;
916        Ok(Self {
917            tenant_id,
918            run_id,
919            invocation_id,
920            revision,
921            status,
922            attempt_id,
923            journal_head,
924            digest,
925        })
926    }
927
928    /// Returns the tenant boundary.
929    #[must_use]
930    pub const fn tenant_id(&self) -> &TenantId {
931        &self.tenant_id
932    }
933
934    /// Returns the durable run identity.
935    #[must_use]
936    pub const fn run_id(&self) -> RunId {
937        self.run_id
938    }
939
940    /// Returns the stable logical invocation identity.
941    #[must_use]
942    pub const fn invocation_id(&self) -> InvocationId {
943        self.invocation_id
944    }
945
946    /// Returns the exact record revision.
947    #[must_use]
948    pub const fn revision(&self) -> ToolInvocationRevision {
949        self.revision
950    }
951
952    /// Returns the lifecycle state at this revision.
953    #[must_use]
954    pub const fn status(&self) -> ToolInvocationStatus {
955        self.status
956    }
957
958    /// Returns the physical attempt represented by this revision, if any.
959    #[must_use]
960    pub const fn attempt_id(&self) -> Option<AttemptId> {
961        self.attempt_id
962    }
963
964    /// Returns the exact journal prefix anchoring this revision.
965    #[must_use]
966    pub const fn journal_head(&self) -> &JournalHead {
967        &self.journal_head
968    }
969
970    /// Returns the complete invocation-record checksum.
971    #[must_use]
972    pub const fn digest(&self) -> Digest {
973        self.digest
974    }
975}
976
977impl<'de> Deserialize<'de> for ToolInvocationHead {
978    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
979    where
980        D: Deserializer<'de>,
981    {
982        #[derive(Deserialize)]
983        #[serde(deny_unknown_fields)]
984        struct Wire {
985            tenant_id: TenantId,
986            run_id: RunId,
987            invocation_id: InvocationId,
988            revision: ToolInvocationRevision,
989            status: ToolInvocationStatus,
990            attempt_id: Option<AttemptId>,
991            journal_head: JournalHead,
992            digest: Digest,
993        }
994
995        let wire = Wire::deserialize(deserializer)?;
996        Self::new(
997            wire.tenant_id,
998            wire.run_id,
999            wire.invocation_id,
1000            wire.revision,
1001            wire.status,
1002            wire.attempt_id,
1003            wire.journal_head,
1004            wire.digest,
1005        )
1006        .map_err(de::Error::custom)
1007    }
1008}
1009
1010/// Invalid compact invocation head.
1011#[derive(Clone, Debug, Eq, Error, PartialEq)]
1012#[non_exhaustive]
1013pub enum ToolInvocationHeadError {
1014    /// Journal head crossed the invocation tenant boundary.
1015    #[error("tool invocation journal head crosses the tenant boundary")]
1016    JournalTenantMismatch,
1017    /// Journal head named another run.
1018    #[error("tool invocation journal head does not belong to the run")]
1019    JournalRunMismatch,
1020    /// Prepared status unexpectedly named a physical attempt.
1021    #[error("prepared tool invocation head must not contain an attempt")]
1022    PreparedHasAttempt,
1023    /// A non-prepared status omitted its physical attempt.
1024    #[error("non-prepared tool invocation head must contain an attempt")]
1025    AttemptMissing,
1026    /// Revision zero named a state other than preparation.
1027    #[error("tool invocation head revision zero must be prepared")]
1028    InitialStatusMismatch,
1029    /// A later revision tried to return to preparation.
1030    #[error("prepared tool invocation head must use revision zero")]
1031    PreparedRevisionMismatch,
1032}
1033
1034impl ToolInvocationHeadError {
1035    const fn from_scope(error: InvocationScopeError) -> Self {
1036        match error {
1037            InvocationScopeError::Tenant => Self::JournalTenantMismatch,
1038            InvocationScopeError::Run => Self::JournalRunMismatch,
1039        }
1040    }
1041}
1042
1043/// One immutable, journal-anchored revision of a logical tool invocation.
1044///
1045/// Deserialization verifies the record's local checksums, scope, provenance,
1046/// limits, and predecessor-head shape. To prove retry policy and the complete
1047/// state history, stream every revision in ascending order through
1048/// [`ToolInvocationHistoryVerifier`].
1049#[derive(Clone, JsonSchema, Serialize)]
1050#[serde(deny_unknown_fields)]
1051pub struct ToolInvocation {
1052    intent: ToolInvocationIntent,
1053    revision: ToolInvocationRevision,
1054    state: ToolInvocationState,
1055    #[serde(skip_serializing_if = "Option::is_none")]
1056    previous: Option<ToolInvocationHead>,
1057    journal_head: JournalHead,
1058    #[serde(skip_serializing_if = "Option::is_none")]
1059    transition: Option<ToolInvocationTransition>,
1060    #[serde(skip_serializing_if = "Option::is_none")]
1061    transition_digest: Option<Digest>,
1062    digest: Digest,
1063}
1064
1065impl ToolInvocation {
1066    /// Materializes the initial prepared revision after its journal event commits.
1067    ///
1068    /// The supplied journal head must belong to the activation's tenant/run and
1069    /// strictly advance the base checkpoint journal sequence without regressing
1070    /// its durable clock.
1071    ///
1072    /// # Errors
1073    ///
1074    /// Returns [`ToolInvocationError`] for scope, ordering, or integrity failure.
1075    pub fn prepare(
1076        intent: ToolInvocationIntent,
1077        journal_head: JournalHead,
1078    ) -> Result<Self, ToolInvocationError> {
1079        validate_preparation_journal(&intent, &journal_head)?;
1080        let revision = ToolInvocationRevision::INITIAL;
1081        let state = ToolInvocationState::Prepared;
1082        let digest = compute_record_digest(&ToolInvocationRecordDigestWire {
1083            intent_digest: intent.intent_digest,
1084            revision,
1085            state: &state,
1086            previous: None,
1087            journal_head: &journal_head,
1088            transition_digest: None,
1089        })?;
1090        Ok(Self {
1091            intent,
1092            revision,
1093            state,
1094            previous: None,
1095            journal_head,
1096            transition: None,
1097            transition_digest: None,
1098            digest,
1099        })
1100    }
1101
1102    /// Applies one legal transition and constructs its next immutable revision.
1103    ///
1104    /// This method enforces state legality, exact attempt provenance, descriptor
1105    /// and effective limits, external-effect retry safety, minimum retry delay,
1106    /// journal scope/order, and revision overflow. Stores must still compare
1107    /// [`Self::head`] under the run lock and current fencing token.
1108    ///
1109    /// # Errors
1110    ///
1111    /// Returns [`ToolInvocationError`] when the transition cannot safely commit.
1112    pub fn advance(
1113        &self,
1114        transition: ToolInvocationTransition,
1115        journal_head: JournalHead,
1116    ) -> Result<Self, ToolInvocationError> {
1117        validate_successor_journal(self, &journal_head)?;
1118        let revision = self
1119            .revision
1120            .checked_next()
1121            .ok_or(ToolInvocationError::RevisionOverflow)?;
1122        let state = apply_transition(self, &transition, journal_head.recorded_at())?;
1123        let transition_digest = compute_transition_digest(&transition)?;
1124        let previous = self.head();
1125        let digest = compute_record_digest(&ToolInvocationRecordDigestWire {
1126            intent_digest: self.intent.intent_digest,
1127            revision,
1128            state: &state,
1129            previous: Some(&previous),
1130            journal_head: &journal_head,
1131            transition_digest: Some(transition_digest),
1132        })?;
1133        Ok(Self {
1134            intent: self.intent.clone(),
1135            revision,
1136            state,
1137            previous: Some(previous),
1138            journal_head,
1139            transition: Some(transition),
1140            transition_digest: Some(transition_digest),
1141            digest,
1142        })
1143    }
1144
1145    /// Restores a record and verifies all invariants available in that revision.
1146    ///
1147    /// Failed-to-executing retry authorization depends on the predecessor's full
1148    /// failure payload and is therefore verified by
1149    /// [`ToolInvocationHistoryVerifier`], not by a compact predecessor head.
1150    ///
1151    /// # Errors
1152    ///
1153    /// Returns [`ToolInvocationError`] for malformed state, provenance, scope,
1154    /// ordering, transition checksum, or record checksum.
1155    #[allow(clippy::too_many_arguments)]
1156    pub fn restore(
1157        intent: ToolInvocationIntent,
1158        revision: ToolInvocationRevision,
1159        state: ToolInvocationState,
1160        previous: Option<ToolInvocationHead>,
1161        journal_head: JournalHead,
1162        transition: Option<ToolInvocationTransition>,
1163        transition_digest: Option<Digest>,
1164        digest: Digest,
1165    ) -> Result<Self, ToolInvocationError> {
1166        validate_record_shape(
1167            &intent,
1168            revision,
1169            &state,
1170            previous.as_ref(),
1171            &journal_head,
1172            transition.as_ref(),
1173            transition_digest,
1174        )?;
1175        let expected = compute_record_digest(&ToolInvocationRecordDigestWire {
1176            intent_digest: intent.intent_digest,
1177            revision,
1178            state: &state,
1179            previous: previous.as_ref(),
1180            journal_head: &journal_head,
1181            transition_digest,
1182        })?;
1183        if digest != expected {
1184            return Err(ToolInvocationError::DigestMismatch);
1185        }
1186        Ok(Self {
1187            intent,
1188            revision,
1189            state,
1190            previous,
1191            journal_head,
1192            transition,
1193            transition_digest,
1194            digest,
1195        })
1196    }
1197
1198    /// Returns the immutable preparation intent.
1199    #[must_use]
1200    pub const fn intent(&self) -> &ToolInvocationIntent {
1201        &self.intent
1202    }
1203
1204    /// Returns this record's monotonic revision.
1205    #[must_use]
1206    pub const fn revision(&self) -> ToolInvocationRevision {
1207        self.revision
1208    }
1209
1210    /// Returns the integrity-bound lifecycle state.
1211    #[must_use]
1212    pub const fn state(&self) -> &ToolInvocationState {
1213        &self.state
1214    }
1215
1216    /// Returns the lifecycle discriminator.
1217    #[must_use]
1218    pub const fn status(&self) -> ToolInvocationStatus {
1219        self.state.status()
1220    }
1221
1222    /// Returns the physical attempt represented by this revision, if any.
1223    #[must_use]
1224    pub const fn attempt_id(&self) -> Option<AttemptId> {
1225        self.state.attempt_id()
1226    }
1227
1228    /// Validates authoritative success evidence for this invocation's unknown attempt.
1229    ///
1230    /// This performs the same invocation, attempt, tool, schema, inline-size,
1231    /// artifact-limit, and artifact-ownership checks used by [`Self::advance`]
1232    /// before a reconciliation transaction is attempted.
1233    ///
1234    /// # Errors
1235    ///
1236    /// Returns [`ToolInvocationError`] unless this revision is unknown and the
1237    /// result is bound to its exact durable intent and physical attempt.
1238    pub fn validate_reconciliation_result(
1239        &self,
1240        result: &ToolResult,
1241    ) -> Result<(), ToolInvocationError> {
1242        let ToolInvocationState::Unknown { error } = &self.state else {
1243            return Err(ToolInvocationError::InvalidTransition {
1244                status: self.status(),
1245                transition: ToolInvocationTransitionKind::ReconcileResult,
1246            });
1247        };
1248        validate_result_binding(&self.intent, error.provenance().attempt_id(), result)
1249    }
1250
1251    /// Validates authoritative failure/effect evidence for an unknown attempt.
1252    ///
1253    /// The evidence may resolve the invocation to `Failed`, or deliberately
1254    /// retain `Unknown` when the external effect remains uncertain. The same
1255    /// identity, attempt, risk/effect, and retry-safety checks used by
1256    /// [`Self::advance`] are applied here.
1257    ///
1258    /// # Errors
1259    ///
1260    /// Returns [`ToolInvocationError`] unless this revision is unknown and the
1261    /// error is bound to its exact durable intent and physical attempt.
1262    pub fn validate_reconciliation_error(
1263        &self,
1264        error: &ToolError,
1265    ) -> Result<(), ToolInvocationError> {
1266        let ToolInvocationState::Unknown { error: previous } = &self.state else {
1267            return Err(ToolInvocationError::InvalidTransition {
1268                status: self.status(),
1269                transition: ToolInvocationTransitionKind::ReconcileError,
1270            });
1271        };
1272        validate_error_binding(&self.intent, previous.provenance().attempt_id(), error)
1273    }
1274
1275    /// Returns the exact predecessor head, absent only for preparation.
1276    #[must_use]
1277    pub const fn previous(&self) -> Option<&ToolInvocationHead> {
1278        self.previous.as_ref()
1279    }
1280
1281    /// Returns the exact journal prefix anchoring this revision.
1282    #[must_use]
1283    pub const fn journal_head(&self) -> &JournalHead {
1284        &self.journal_head
1285    }
1286
1287    /// Returns the explicit transition, absent only for preparation.
1288    #[must_use]
1289    pub const fn transition(&self) -> Option<&ToolInvocationTransition> {
1290        self.transition.as_ref()
1291    }
1292
1293    /// Returns the transition fingerprint, absent only for preparation.
1294    #[must_use]
1295    pub const fn transition_digest(&self) -> Option<Digest> {
1296        self.transition_digest
1297    }
1298
1299    /// Returns the complete domain-separated record checksum.
1300    #[must_use]
1301    pub const fn digest(&self) -> Digest {
1302        self.digest
1303    }
1304
1305    /// Returns a compact exact optimistic-comparison token.
1306    #[must_use]
1307    pub fn head(&self) -> ToolInvocationHead {
1308        ToolInvocationHead {
1309            tenant_id: self.intent.tenant_id().clone(),
1310            run_id: self.intent.run_id(),
1311            invocation_id: self.intent.invocation_id,
1312            revision: self.revision,
1313            status: self.status(),
1314            attempt_id: self.attempt_id(),
1315            journal_head: self.journal_head.clone(),
1316            digest: self.digest,
1317        }
1318    }
1319}
1320
1321impl fmt::Debug for ToolInvocation {
1322    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1323        formatter
1324            .debug_struct("ToolInvocation")
1325            .field("intent", &self.intent)
1326            .field("revision", &self.revision)
1327            .field("state", &self.state)
1328            .field("previous", &self.previous)
1329            .field("journal_head", &self.journal_head)
1330            .field("transition", &self.transition)
1331            .field("transition_digest", &self.transition_digest)
1332            .field("digest", &self.digest)
1333            .finish_non_exhaustive()
1334    }
1335}
1336
1337impl<'de> Deserialize<'de> for ToolInvocation {
1338    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1339    where
1340        D: Deserializer<'de>,
1341    {
1342        #[derive(Deserialize)]
1343        #[serde(deny_unknown_fields)]
1344        struct Wire {
1345            intent: ToolInvocationIntent,
1346            revision: ToolInvocationRevision,
1347            state: ToolInvocationState,
1348            previous: Option<ToolInvocationHead>,
1349            journal_head: JournalHead,
1350            transition: Option<ToolInvocationTransition>,
1351            transition_digest: Option<Digest>,
1352            digest: Digest,
1353        }
1354
1355        let wire = Wire::deserialize(deserializer)?;
1356        Self::restore(
1357            wire.intent,
1358            wire.revision,
1359            wire.state,
1360            wire.previous,
1361            wire.journal_head,
1362            wire.transition,
1363            wire.transition_digest,
1364            wire.digest,
1365        )
1366        .map_err(de::Error::custom)
1367    }
1368}
1369
1370/// Streaming validator for one complete ascending invocation history.
1371///
1372/// Rejections are transactional: [`Self::verify_next`] never advances the last
1373/// accepted record on failure. A store may therefore page immutable revisions
1374/// without buffering the whole history while still proving every transition.
1375#[derive(Clone, Debug, Default)]
1376pub struct ToolInvocationHistoryVerifier {
1377    last: Option<ToolInvocation>,
1378}
1379
1380impl ToolInvocationHistoryVerifier {
1381    /// Constructs an empty verifier expecting revision zero.
1382    #[must_use]
1383    pub const fn new() -> Self {
1384        Self { last: None }
1385    }
1386
1387    /// Continues after one already trusted, fully restored record.
1388    ///
1389    /// A paged store must first reload the cursor by exact identity and compare
1390    /// its canonical record before using this constructor. This preserves the
1391    /// predecessor failure payload needed to authorize a retry transition.
1392    #[must_use]
1393    pub fn after(record: ToolInvocation) -> Self {
1394        Self { last: Some(record) }
1395    }
1396
1397    /// Returns the last verified head, if any.
1398    #[must_use]
1399    pub fn head(&self) -> Option<ToolInvocationHead> {
1400        self.last.as_ref().map(ToolInvocation::head)
1401    }
1402
1403    /// Returns whether at least one revision has been verified.
1404    #[must_use]
1405    pub const fn has_records(&self) -> bool {
1406        self.last.is_some()
1407    }
1408
1409    /// Verifies and then advances to the next ascending revision.
1410    ///
1411    /// # Errors
1412    ///
1413    /// Returns [`ToolInvocationHistoryError`] for a non-initial first record,
1414    /// intent substitution, head mismatch, unsafe retry, or any other state
1415    /// transition failure.
1416    pub fn verify_next(
1417        &mut self,
1418        record: &ToolInvocation,
1419    ) -> Result<(), ToolInvocationHistoryError> {
1420        let Some(previous) = self.last.as_ref() else {
1421            if record.revision != ToolInvocationRevision::INITIAL {
1422                return Err(ToolInvocationHistoryError::FirstRecordNotInitial {
1423                    actual: record.revision,
1424                });
1425            }
1426            self.last = Some(record.clone());
1427            return Ok(());
1428        };
1429
1430        if record.intent != previous.intent {
1431            return Err(ToolInvocationHistoryError::IntentMismatch);
1432        }
1433        if record.previous.as_ref() != Some(&previous.head()) {
1434            return Err(ToolInvocationHistoryError::PreviousHeadMismatch);
1435        }
1436        let transition = record
1437            .transition
1438            .as_ref()
1439            .ok_or(ToolInvocationHistoryError::TransitionMissing)?;
1440        let expected = previous
1441            .advance(transition.clone(), record.journal_head.clone())
1442            .map_err(|source| ToolInvocationHistoryError::Transition { source })?;
1443        if !canonical_equal(&expected, record)
1444            .map_err(|source| ToolInvocationHistoryError::Integrity { source })?
1445        {
1446            return Err(ToolInvocationHistoryError::RecordMismatch);
1447        }
1448
1449        self.last = Some(record.clone());
1450        Ok(())
1451    }
1452}
1453
1454/// Invalid ascending invocation history.
1455#[derive(Clone, Debug, Eq, Error, PartialEq)]
1456#[non_exhaustive]
1457pub enum ToolInvocationHistoryError {
1458    /// The first supplied record was not preparation revision zero.
1459    #[error("first tool invocation record is revision {actual}; expected 0")]
1460    FirstRecordNotInitial {
1461        /// Rejected first revision.
1462        actual: ToolInvocationRevision,
1463    },
1464    /// A successor substituted immutable preparation fields.
1465    #[error("tool invocation history changed its immutable intent")]
1466    IntentMismatch,
1467    /// A successor did not name the exact previously verified head.
1468    #[error("tool invocation history predecessor head mismatch")]
1469    PreviousHeadMismatch,
1470    /// A non-initial record omitted its transition.
1471    #[error("tool invocation history successor is missing its transition")]
1472    TransitionMissing,
1473    /// Applying the transition to the full predecessor failed.
1474    #[error("tool invocation history transition is invalid: {source}")]
1475    Transition {
1476        /// Exact state-machine failure.
1477        #[source]
1478        source: ToolInvocationError,
1479    },
1480    /// Expected and persisted successor bytes did not match exactly.
1481    #[error("tool invocation history successor does not match the applied transition")]
1482    RecordMismatch,
1483    /// Exact record comparison could not be canonicalized.
1484    #[error("tool invocation history integrity comparison failed: {source}")]
1485    Integrity {
1486        /// Exact canonicalization failure.
1487        #[source]
1488        source: ToolInvocationIntegrityError,
1489    },
1490}
1491
1492/// Artifact binding field rejected while restoring a durable result.
1493#[derive(Clone, Copy, Debug, Eq, Hash, JsonSchema, PartialEq)]
1494#[non_exhaustive]
1495pub enum ToolArtifactBinding {
1496    /// Artifact belongs to another tenant.
1497    Tenant,
1498    /// Artifact provenance names another run.
1499    Run,
1500    /// Artifact provenance names another registry principal.
1501    Principal,
1502    /// Artifact provenance omits or substitutes the producing capability.
1503    Capability,
1504}
1505
1506/// Invalid invocation record, transition, provenance, or integrity layer.
1507#[derive(Clone, Debug, Eq, Error, PartialEq)]
1508#[non_exhaustive]
1509pub enum ToolInvocationError {
1510    /// Canonical typed integrity material could not be serialized.
1511    #[error("tool invocation integrity calculation failed: {source}")]
1512    Integrity {
1513        /// Exact canonical integrity failure.
1514        #[source]
1515        source: ToolInvocationIntegrityError,
1516    },
1517    /// Journal head crossed the invocation tenant boundary.
1518    #[error("tool invocation journal head crosses the tenant boundary")]
1519    JournalTenantMismatch,
1520    /// Journal head named another run.
1521    #[error("tool invocation journal head does not belong to the run")]
1522    JournalRunMismatch,
1523    /// A revision did not strictly advance its required journal predecessor.
1524    #[error("tool invocation journal sequence {actual} does not advance {previous}")]
1525    JournalDidNotAdvance {
1526        /// Required prior sequence.
1527        previous: JournalSequence,
1528        /// Rejected current sequence.
1529        actual: JournalSequence,
1530    },
1531    /// A revision's durable clock preceded its required predecessor.
1532    #[error("tool invocation journal clock regressed from {previous} to {actual}")]
1533    ClockRegression {
1534        /// Required prior durable timestamp.
1535        previous: Timestamp,
1536        /// Rejected current timestamp.
1537        actual: Timestamp,
1538    },
1539    /// No storage-compatible successor revision exists.
1540    #[error("tool invocation revision exceeds the PostgreSQL BIGINT maximum")]
1541    RevisionOverflow,
1542    /// Revision zero did not use the exact preparation shape.
1543    #[error("initial tool invocation revision must be prepared with no predecessor or transition")]
1544    InvalidInitialShape,
1545    /// A successor omitted or unexpectedly added predecessor/transition fields.
1546    #[error(
1547        "tool invocation successor must contain predecessor, transition, and transition digest"
1548    )]
1549    InvalidSuccessorShape,
1550    /// Compact predecessor crossed the immutable tenant boundary.
1551    #[error("tool invocation predecessor crosses the tenant boundary")]
1552    PreviousTenantMismatch,
1553    /// Compact predecessor named another run.
1554    #[error("tool invocation predecessor names another run")]
1555    PreviousRunMismatch,
1556    /// Compact predecessor named another logical invocation.
1557    #[error("tool invocation predecessor names another invocation")]
1558    PreviousInvocationMismatch,
1559    /// Current revision was not the exact successor of its compact predecessor.
1560    #[error("tool invocation revision {actual} does not follow predecessor {previous}")]
1561    PreviousRevisionMismatch {
1562        /// Predecessor revision.
1563        previous: ToolInvocationRevision,
1564        /// Rejected current revision.
1565        actual: ToolInvocationRevision,
1566    },
1567    /// Persisted transition checksum did not match its transition payload.
1568    #[error("tool invocation transition digest does not match its payload")]
1569    TransitionDigestMismatch,
1570    /// Transition is not legal from the predecessor lifecycle state.
1571    #[error("tool invocation transition {transition:?} is invalid from {status:?}")]
1572    InvalidTransition {
1573        /// Predecessor status.
1574        status: ToolInvocationStatus,
1575        /// Rejected transition kind.
1576        transition: ToolInvocationTransitionKind,
1577    },
1578    /// Transition payload and resulting state differed.
1579    #[error("tool invocation transition payload does not match its resulting state")]
1580    TransitionStateMismatch,
1581    /// A retry reused the immediately preceding physical attempt identity.
1582    #[error("tool invocation retry must use a new physical attempt identifier")]
1583    ReusedAttemptId,
1584    /// Failed outcome did not explicitly authorize a safe retry.
1585    #[error("tool invocation failure does not authorize retry")]
1586    RetryNotAuthorized,
1587    /// Retry time could not be represented in the canonical timestamp range.
1588    #[error("tool invocation retry delay exceeds the supported timestamp range")]
1589    RetryDelayOutOfRange,
1590    /// Retry occurred before the failure's explicit minimum delay elapsed.
1591    #[error("tool invocation retry at {actual} precedes not-before time {not_before}")]
1592    RetryDelayNotElapsed {
1593        /// Earliest permitted durable retry timestamp.
1594        not_before: Timestamp,
1595        /// Rejected retry timestamp.
1596        actual: Timestamp,
1597    },
1598    /// Failure evidence and tool semantics do not make repetition safe.
1599    #[error("tool invocation failure evidence does not permit a repeated external call")]
1600    RetryUnsafe,
1601    /// Successful result named another logical invocation.
1602    #[error("tool result names another logical invocation")]
1603    ResultInvocationMismatch,
1604    /// Successful result named another physical attempt.
1605    #[error("tool result names another physical attempt")]
1606    ResultAttemptMismatch,
1607    /// Successful result named another tool version.
1608    #[error("tool result names another tool identity")]
1609    ResultToolMismatch,
1610    /// Successful result named another output schema.
1611    #[error("tool result names another output schema")]
1612    ResultSchemaMismatch,
1613    /// Inline result exceeded the resolved invocation ceiling.
1614    #[error("tool result is {actual} inline bytes; effective maximum is {maximum}")]
1615    ResultInlineLimitExceeded {
1616        /// Resolved inline-result ceiling.
1617        maximum: ByteCount,
1618        /// Exact compact result size.
1619        actual: ByteCount,
1620    },
1621    /// Result artifact count exceeded the resolved invocation ceiling.
1622    #[error("tool result has {actual} artifacts; effective maximum is {maximum}")]
1623    ResultArtifactCountExceeded {
1624        /// Resolved artifact-count ceiling.
1625        maximum: ExecutionCount,
1626        /// Actual artifact count.
1627        actual: ExecutionCount,
1628    },
1629    /// Result artifact bytes exceeded the resolved invocation ceiling.
1630    #[error("tool result artifacts total {actual} bytes; effective maximum is {maximum}")]
1631    ResultArtifactBytesExceeded {
1632        /// Resolved aggregate artifact-byte ceiling.
1633        maximum: ByteCount,
1634        /// Actual aggregate artifact bytes.
1635        actual: ByteCount,
1636    },
1637    /// One artifact crossed an invocation ownership boundary.
1638    #[error("tool result artifact at index {index} has invalid {binding:?} binding")]
1639    ResultArtifactBinding {
1640        /// Zero-based artifact position.
1641        index: usize,
1642        /// Rejected ownership field.
1643        binding: ToolArtifactBinding,
1644    },
1645    /// Failure evidence named another logical invocation.
1646    #[error("tool error names another logical invocation")]
1647    ErrorInvocationMismatch,
1648    /// Failure evidence named another physical attempt.
1649    #[error("tool error names another physical attempt")]
1650    ErrorAttemptMismatch,
1651    /// Failure evidence named another tool version.
1652    #[error("tool error names another tool identity")]
1653    ErrorToolMismatch,
1654    /// Failure effect evidence contradicted the descriptor's reviewed risk.
1655    #[error("tool error effect {effect:?} contradicts descriptor risk {risk:?}")]
1656    ErrorEffectRiskMismatch {
1657        /// Reviewed tool risk.
1658        risk: ToolRisk,
1659        /// Rejected effect evidence.
1660        effect: ToolExternalEffect,
1661    },
1662    /// A non-idempotent applied write claimed automatic retry was safe.
1663    #[error("applied non-idempotent tool write cannot authorize automatic retry")]
1664    UnsafeRetryAfterAppliedNonIdempotentWrite,
1665    /// Failed state incorrectly contained ambiguous outcome evidence.
1666    #[error("failed tool invocation state cannot contain unknown effect evidence")]
1667    FailedStateHasUnknownEffect,
1668    /// Unknown state omitted exact ambiguous outcome evidence.
1669    #[error("unknown tool invocation state requires unknown effect evidence")]
1670    UnknownStateRequiresUnknownEffect,
1671    /// Persisted complete record checksum did not match its fields.
1672    #[error("tool invocation record digest does not match its fields")]
1673    DigestMismatch,
1674}
1675
1676impl From<ToolInvocationIntegrityError> for ToolInvocationError {
1677    fn from(source: ToolInvocationIntegrityError) -> Self {
1678        Self::Integrity { source }
1679    }
1680}
1681
1682/// Failure to canonicalize a closed invocation checksum preimage.
1683#[derive(Clone, Debug, Eq, Error, PartialEq)]
1684#[non_exhaustive]
1685pub enum ToolInvocationIntegrityError {
1686    /// Typed values could not be represented as canonical JSON.
1687    #[error("tool invocation checksum preimage canonical serialization failed")]
1688    CanonicalSerialization,
1689}
1690
1691#[derive(Serialize)]
1692struct ReadyNodeInputDigestWire<'a> {
1693    base_checkpoint_digest: Digest,
1694    graph_namespace: &'a GraphNamespace,
1695    node_id: &'a NodeId,
1696}
1697
1698#[derive(Serialize)]
1699struct ToolInvocationIntentDigestWire<'a> {
1700    activation: &'a NodeActivation,
1701    invocation_id: InvocationId,
1702    descriptor: &'a ToolDescriptor,
1703    input: &'a ToolInput,
1704    effective_limits: &'a ToolExecutionLimits,
1705}
1706
1707#[derive(Serialize)]
1708struct ToolInvocationRecordDigestWire<'a> {
1709    intent_digest: Digest,
1710    revision: ToolInvocationRevision,
1711    state: &'a ToolInvocationState,
1712    #[serde(skip_serializing_if = "Option::is_none")]
1713    previous: Option<&'a ToolInvocationHead>,
1714    journal_head: &'a JournalHead,
1715    #[serde(skip_serializing_if = "Option::is_none")]
1716    transition_digest: Option<Digest>,
1717}
1718
1719fn compute_ready_node_input_digest(
1720    base_checkpoint_digest: Digest,
1721    graph_namespace: &GraphNamespace,
1722    node_id: &NodeId,
1723) -> Result<Digest, NodeActivationError> {
1724    let canonical = serde_json_canonicalizer::to_vec(&ReadyNodeInputDigestWire {
1725        base_checkpoint_digest,
1726        graph_namespace,
1727        node_id,
1728    })
1729    .map_err(|_| NodeActivationError::CanonicalSerialization)?;
1730    let mut preimage = Vec::with_capacity(READY_NODE_INPUT_DIGEST_DOMAIN.len() + canonical.len());
1731    preimage.extend_from_slice(READY_NODE_INPUT_DIGEST_DOMAIN);
1732    preimage.extend_from_slice(&canonical);
1733    Ok(Digest::sha256(preimage))
1734}
1735
1736fn compute_intent_digest(
1737    value: &ToolInvocationIntentDigestWire<'_>,
1738) -> Result<Digest, ToolInvocationIntegrityError> {
1739    domain_separated_digest(INTENT_DIGEST_DOMAIN, value)
1740}
1741
1742fn compute_transition_digest(
1743    value: &ToolInvocationTransition,
1744) -> Result<Digest, ToolInvocationIntegrityError> {
1745    domain_separated_digest(TRANSITION_DIGEST_DOMAIN, value)
1746}
1747
1748fn compute_record_digest(
1749    value: &ToolInvocationRecordDigestWire<'_>,
1750) -> Result<Digest, ToolInvocationIntegrityError> {
1751    domain_separated_digest(RECORD_DIGEST_DOMAIN, value)
1752}
1753
1754fn domain_separated_digest<T: Serialize>(
1755    domain: &[u8],
1756    value: &T,
1757) -> Result<Digest, ToolInvocationIntegrityError> {
1758    let canonical = serde_json_canonicalizer::to_vec(value)
1759        .map_err(|_| ToolInvocationIntegrityError::CanonicalSerialization)?;
1760    let mut preimage = Vec::with_capacity(domain.len() + canonical.len());
1761    preimage.extend_from_slice(domain);
1762    preimage.extend_from_slice(&canonical);
1763    Ok(Digest::sha256(preimage))
1764}
1765
1766fn canonical_equal<T: Serialize>(
1767    left: &T,
1768    right: &T,
1769) -> Result<bool, ToolInvocationIntegrityError> {
1770    let left = serde_json_canonicalizer::to_vec(left)
1771        .map_err(|_| ToolInvocationIntegrityError::CanonicalSerialization)?;
1772    let right = serde_json_canonicalizer::to_vec(right)
1773        .map_err(|_| ToolInvocationIntegrityError::CanonicalSerialization)?;
1774    Ok(left == right)
1775}
1776
1777fn validate_intent_shape(
1778    descriptor: &ToolDescriptor,
1779    input: &ToolInput,
1780    effective: &ToolExecutionLimits,
1781) -> Result<(), ToolInvocationIntentError> {
1782    if input.schema() != descriptor.input_schema() {
1783        return Err(ToolInvocationIntentError::InputSchemaMismatch);
1784    }
1785    let descriptor_limits = descriptor.limits();
1786    for (widened, limit) in [
1787        (
1788            effective.timeout() > descriptor_limits.timeout(),
1789            ToolInvocationLimit::Timeout,
1790        ),
1791        (
1792            effective.max_concurrency() > descriptor_limits.max_concurrency(),
1793            ToolInvocationLimit::MaxConcurrency,
1794        ),
1795        (
1796            effective.max_input_bytes() > descriptor_limits.max_input_bytes(),
1797            ToolInvocationLimit::MaxInputBytes,
1798        ),
1799        (
1800            effective.max_inline_result_bytes() > descriptor_limits.max_inline_result_bytes(),
1801            ToolInvocationLimit::MaxInlineResultBytes,
1802        ),
1803        (
1804            effective.max_artifacts() > descriptor_limits.max_artifacts(),
1805            ToolInvocationLimit::MaxArtifacts,
1806        ),
1807        (
1808            effective.max_total_artifact_bytes() > descriptor_limits.max_total_artifact_bytes(),
1809            ToolInvocationLimit::MaxTotalArtifactBytes,
1810        ),
1811    ] {
1812        if widened {
1813            return Err(ToolInvocationIntentError::EffectiveLimitWidened { limit });
1814        }
1815    }
1816
1817    let actual = byte_count_from_usize(input.value().stats().compact_bytes());
1818    let maximum = effective.max_input_bytes();
1819    if actual > maximum {
1820        return Err(ToolInvocationIntentError::InputLimitExceeded { maximum, actual });
1821    }
1822    Ok(())
1823}
1824
1825fn byte_count_from_usize(value: usize) -> ByteCount {
1826    ByteCount::new(u64::try_from(value).unwrap_or(u64::MAX))
1827}
1828
1829fn execution_count_from_usize(value: usize) -> ExecutionCount {
1830    ExecutionCount::new(u64::try_from(value).unwrap_or(u64::MAX))
1831}
1832
1833#[derive(Clone, Copy)]
1834enum InvocationScopeError {
1835    Tenant,
1836    Run,
1837}
1838
1839fn validate_journal_scope(
1840    tenant_id: &TenantId,
1841    run_id: RunId,
1842    head: &JournalHead,
1843) -> Result<(), InvocationScopeError> {
1844    if head.tenant_id() != tenant_id {
1845        return Err(InvocationScopeError::Tenant);
1846    }
1847    if head.run_id() != run_id {
1848        return Err(InvocationScopeError::Run);
1849    }
1850    Ok(())
1851}
1852
1853fn validate_status_attempt(
1854    status: ToolInvocationStatus,
1855    attempt_id: Option<AttemptId>,
1856) -> Result<(), ToolInvocationHeadError> {
1857    match (status, attempt_id) {
1858        (ToolInvocationStatus::Prepared, None)
1859        | (
1860            ToolInvocationStatus::Executing
1861            | ToolInvocationStatus::Committed
1862            | ToolInvocationStatus::Failed
1863            | ToolInvocationStatus::Unknown,
1864            Some(_),
1865        ) => Ok(()),
1866        (ToolInvocationStatus::Prepared, Some(_)) => {
1867            Err(ToolInvocationHeadError::PreparedHasAttempt)
1868        }
1869        (
1870            ToolInvocationStatus::Executing
1871            | ToolInvocationStatus::Committed
1872            | ToolInvocationStatus::Failed
1873            | ToolInvocationStatus::Unknown,
1874            None,
1875        ) => Err(ToolInvocationHeadError::AttemptMissing),
1876    }
1877}
1878
1879fn validate_revision_status(
1880    revision: ToolInvocationRevision,
1881    status: ToolInvocationStatus,
1882) -> Result<(), ToolInvocationHeadError> {
1883    match (revision == ToolInvocationRevision::INITIAL, status) {
1884        (true, ToolInvocationStatus::Prepared)
1885        | (
1886            false,
1887            ToolInvocationStatus::Executing
1888            | ToolInvocationStatus::Committed
1889            | ToolInvocationStatus::Failed
1890            | ToolInvocationStatus::Unknown,
1891        ) => Ok(()),
1892        (true, _) => Err(ToolInvocationHeadError::InitialStatusMismatch),
1893        (false, ToolInvocationStatus::Prepared) => {
1894            Err(ToolInvocationHeadError::PreparedRevisionMismatch)
1895        }
1896    }
1897}
1898
1899fn map_scope_error(error: InvocationScopeError) -> ToolInvocationError {
1900    match error {
1901        InvocationScopeError::Tenant => ToolInvocationError::JournalTenantMismatch,
1902        InvocationScopeError::Run => ToolInvocationError::JournalRunMismatch,
1903    }
1904}
1905
1906fn validate_journal_advances(
1907    previous: &JournalHead,
1908    actual: &JournalHead,
1909) -> Result<(), ToolInvocationError> {
1910    if actual.sequence() <= previous.sequence() {
1911        return Err(ToolInvocationError::JournalDidNotAdvance {
1912            previous: previous.sequence(),
1913            actual: actual.sequence(),
1914        });
1915    }
1916    if actual.recorded_at() < previous.recorded_at() {
1917        return Err(ToolInvocationError::ClockRegression {
1918            previous: previous.recorded_at(),
1919            actual: actual.recorded_at(),
1920        });
1921    }
1922    Ok(())
1923}
1924
1925fn validate_preparation_journal(
1926    intent: &ToolInvocationIntent,
1927    journal_head: &JournalHead,
1928) -> Result<(), ToolInvocationError> {
1929    validate_journal_scope(intent.tenant_id(), intent.run_id(), journal_head)
1930        .map_err(map_scope_error)?;
1931    validate_journal_advances(
1932        intent.activation.base_checkpoint().journal_head(),
1933        journal_head,
1934    )
1935}
1936
1937fn validate_successor_journal(
1938    invocation: &ToolInvocation,
1939    journal_head: &JournalHead,
1940) -> Result<(), ToolInvocationError> {
1941    validate_journal_scope(
1942        invocation.intent.tenant_id(),
1943        invocation.intent.run_id(),
1944        journal_head,
1945    )
1946    .map_err(map_scope_error)?;
1947    validate_journal_advances(&invocation.journal_head, journal_head)
1948}
1949
1950#[allow(clippy::too_many_arguments)]
1951fn validate_record_shape(
1952    intent: &ToolInvocationIntent,
1953    revision: ToolInvocationRevision,
1954    state: &ToolInvocationState,
1955    previous: Option<&ToolInvocationHead>,
1956    journal_head: &JournalHead,
1957    transition: Option<&ToolInvocationTransition>,
1958    transition_digest: Option<Digest>,
1959) -> Result<(), ToolInvocationError> {
1960    validate_journal_scope(intent.tenant_id(), intent.run_id(), journal_head)
1961        .map_err(map_scope_error)?;
1962    validate_state_binding(intent, state)?;
1963
1964    if revision == ToolInvocationRevision::INITIAL {
1965        if !matches!(state, ToolInvocationState::Prepared)
1966            || previous.is_some()
1967            || transition.is_some()
1968            || transition_digest.is_some()
1969        {
1970            return Err(ToolInvocationError::InvalidInitialShape);
1971        }
1972        return validate_preparation_journal(intent, journal_head);
1973    }
1974
1975    let (Some(previous), Some(transition), Some(transition_digest)) =
1976        (previous, transition, transition_digest)
1977    else {
1978        return Err(ToolInvocationError::InvalidSuccessorShape);
1979    };
1980    if previous.tenant_id() != intent.tenant_id() {
1981        return Err(ToolInvocationError::PreviousTenantMismatch);
1982    }
1983    if previous.run_id() != intent.run_id() {
1984        return Err(ToolInvocationError::PreviousRunMismatch);
1985    }
1986    if previous.invocation_id() != intent.invocation_id() {
1987        return Err(ToolInvocationError::PreviousInvocationMismatch);
1988    }
1989    if previous.revision().checked_next() != Some(revision) {
1990        return Err(ToolInvocationError::PreviousRevisionMismatch {
1991            previous: previous.revision(),
1992            actual: revision,
1993        });
1994    }
1995    validate_journal_advances(previous.journal_head(), journal_head)?;
1996
1997    if compute_transition_digest(transition)? != transition_digest {
1998        return Err(ToolInvocationError::TransitionDigestMismatch);
1999    }
2000    validate_transition_shape(intent, previous, transition, state)
2001}
2002
2003fn validate_state_binding(
2004    intent: &ToolInvocationIntent,
2005    state: &ToolInvocationState,
2006) -> Result<(), ToolInvocationError> {
2007    match state {
2008        ToolInvocationState::Prepared | ToolInvocationState::Executing { .. } => Ok(()),
2009        ToolInvocationState::Committed { result } => {
2010            validate_result_binding(intent, result.provenance().attempt_id(), result)
2011        }
2012        ToolInvocationState::Failed { error } => {
2013            validate_error_binding(intent, error.provenance().attempt_id(), error)?;
2014            if error.external_effect() == ToolExternalEffect::Unknown {
2015                return Err(ToolInvocationError::FailedStateHasUnknownEffect);
2016            }
2017            Ok(())
2018        }
2019        ToolInvocationState::Unknown { error } => {
2020            validate_error_binding(intent, error.provenance().attempt_id(), error)?;
2021            if error.external_effect() != ToolExternalEffect::Unknown {
2022                return Err(ToolInvocationError::UnknownStateRequiresUnknownEffect);
2023            }
2024            Ok(())
2025        }
2026    }
2027}
2028
2029fn validate_result_binding(
2030    intent: &ToolInvocationIntent,
2031    expected_attempt: AttemptId,
2032    result: &ToolResult,
2033) -> Result<(), ToolInvocationError> {
2034    let provenance = result.provenance();
2035    if provenance.invocation_id() != intent.invocation_id() {
2036        return Err(ToolInvocationError::ResultInvocationMismatch);
2037    }
2038    if provenance.attempt_id() != expected_attempt {
2039        return Err(ToolInvocationError::ResultAttemptMismatch);
2040    }
2041    if provenance.tool() != intent.descriptor.metadata().identity() {
2042        return Err(ToolInvocationError::ResultToolMismatch);
2043    }
2044    if result.output_schema() != intent.descriptor.output_schema() {
2045        return Err(ToolInvocationError::ResultSchemaMismatch);
2046    }
2047
2048    let actual = byte_count_from_usize(result.output().stats().compact_bytes());
2049    let maximum = intent.effective_limits.max_inline_result_bytes();
2050    if actual > maximum {
2051        return Err(ToolInvocationError::ResultInlineLimitExceeded { maximum, actual });
2052    }
2053    let actual = execution_count_from_usize(result.artifacts().len());
2054    let maximum = intent.effective_limits.max_artifacts();
2055    if actual > maximum {
2056        return Err(ToolInvocationError::ResultArtifactCountExceeded { maximum, actual });
2057    }
2058    let actual = result.artifacts().total_bytes();
2059    let maximum = intent.effective_limits.max_total_artifact_bytes();
2060    if actual > maximum {
2061        return Err(ToolInvocationError::ResultArtifactBytesExceeded { maximum, actual });
2062    }
2063
2064    let expected_principal = intent.descriptor.metadata().identity().owner();
2065    let expected_capability = intent.descriptor.metadata().identity().capability();
2066    for (index, artifact) in result.artifacts().iter().enumerate() {
2067        let binding = if artifact.identity().tenant_id() != intent.tenant_id() {
2068            Some(ToolArtifactBinding::Tenant)
2069        } else if artifact.provenance().run_id() != intent.run_id() {
2070            Some(ToolArtifactBinding::Run)
2071        } else if artifact.provenance().principal() != expected_principal {
2072            Some(ToolArtifactBinding::Principal)
2073        } else if artifact.provenance().capability() != Some(expected_capability) {
2074            Some(ToolArtifactBinding::Capability)
2075        } else {
2076            None
2077        };
2078        if let Some(binding) = binding {
2079            return Err(ToolInvocationError::ResultArtifactBinding { index, binding });
2080        }
2081    }
2082    Ok(())
2083}
2084
2085fn validate_error_binding(
2086    intent: &ToolInvocationIntent,
2087    expected_attempt: AttemptId,
2088    error: &ToolError,
2089) -> Result<(), ToolInvocationError> {
2090    let provenance = error.provenance();
2091    if provenance.invocation_id() != intent.invocation_id() {
2092        return Err(ToolInvocationError::ErrorInvocationMismatch);
2093    }
2094    if provenance.attempt_id() != expected_attempt {
2095        return Err(ToolInvocationError::ErrorAttemptMismatch);
2096    }
2097    if provenance.tool() != intent.descriptor.metadata().identity() {
2098        return Err(ToolInvocationError::ErrorToolMismatch);
2099    }
2100
2101    let risk = intent.descriptor.semantics().risk();
2102    let effect = error.external_effect();
2103    let valid = match risk {
2104        ToolRisk::ReadOnly => effect == ToolExternalEffect::NotApplicable,
2105        ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite => matches!(
2106            effect,
2107            ToolExternalEffect::NotStarted
2108                | ToolExternalEffect::NotApplied
2109                | ToolExternalEffect::Applied
2110                | ToolExternalEffect::Unknown
2111        ),
2112    };
2113    if !valid {
2114        return Err(ToolInvocationError::ErrorEffectRiskMismatch { risk, effect });
2115    }
2116    if risk == ToolRisk::NonIdempotentWrite
2117        && effect == ToolExternalEffect::Applied
2118        && matches!(
2119            error.failure().retry_advice(),
2120            RetryAdvice::SafeAfter { .. }
2121        )
2122    {
2123        return Err(ToolInvocationError::UnsafeRetryAfterAppliedNonIdempotentWrite);
2124    }
2125    Ok(())
2126}
2127
2128fn validate_transition_shape(
2129    intent: &ToolInvocationIntent,
2130    previous: &ToolInvocationHead,
2131    transition: &ToolInvocationTransition,
2132    state: &ToolInvocationState,
2133) -> Result<(), ToolInvocationError> {
2134    let valid = match (previous.status(), transition, state) {
2135        (
2136            ToolInvocationStatus::Prepared | ToolInvocationStatus::Failed,
2137            ToolInvocationTransition::StartAttempt { attempt_id },
2138            ToolInvocationState::Executing {
2139                attempt_id: state_attempt,
2140            },
2141        ) => {
2142            if previous.attempt_id() == Some(*attempt_id) {
2143                return Err(ToolInvocationError::ReusedAttemptId);
2144            }
2145            attempt_id == state_attempt
2146        }
2147        (
2148            ToolInvocationStatus::Executing,
2149            ToolInvocationTransition::RecordResult { result },
2150            ToolInvocationState::Committed {
2151                result: state_result,
2152            },
2153        )
2154        | (
2155            ToolInvocationStatus::Unknown,
2156            ToolInvocationTransition::ReconcileResult { result },
2157            ToolInvocationState::Committed {
2158                result: state_result,
2159            },
2160        ) => result == state_result,
2161        (
2162            ToolInvocationStatus::Executing,
2163            ToolInvocationTransition::RecordError { error },
2164            ToolInvocationState::Failed { error: state_error },
2165        ) if error.external_effect() != ToolExternalEffect::Unknown => {
2166            canonical_equal(error, state_error)?
2167        }
2168        (
2169            ToolInvocationStatus::Executing,
2170            ToolInvocationTransition::RecordError { error },
2171            ToolInvocationState::Unknown { error: state_error },
2172        ) if error.external_effect() == ToolExternalEffect::Unknown => {
2173            canonical_equal(error, state_error)?
2174        }
2175        (
2176            ToolInvocationStatus::Unknown,
2177            ToolInvocationTransition::ReconcileError { error },
2178            ToolInvocationState::Unknown { error: state_error },
2179        ) if error.external_effect() == ToolExternalEffect::Unknown => {
2180            canonical_equal(error, state_error)?
2181        }
2182        (
2183            ToolInvocationStatus::Unknown,
2184            ToolInvocationTransition::ReconcileError { error },
2185            ToolInvocationState::Failed { error: state_error },
2186        ) if error.external_effect() != ToolExternalEffect::Unknown => {
2187            canonical_equal(error, state_error)?
2188        }
2189        _ => {
2190            return Err(ToolInvocationError::InvalidTransition {
2191                status: previous.status(),
2192                transition: transition.kind(),
2193            });
2194        }
2195    };
2196    if !valid {
2197        return Err(ToolInvocationError::TransitionStateMismatch);
2198    }
2199
2200    let expected_attempt = previous.attempt_id();
2201    match transition {
2202        ToolInvocationTransition::StartAttempt { .. } => {}
2203        ToolInvocationTransition::RecordResult { result }
2204        | ToolInvocationTransition::ReconcileResult { result } => {
2205            validate_result_binding(
2206                intent,
2207                expected_attempt.ok_or(ToolInvocationError::TransitionStateMismatch)?,
2208                result,
2209            )?;
2210        }
2211        ToolInvocationTransition::RecordError { error }
2212        | ToolInvocationTransition::ReconcileError { error } => {
2213            validate_error_binding(
2214                intent,
2215                expected_attempt.ok_or(ToolInvocationError::TransitionStateMismatch)?,
2216                error,
2217            )?;
2218        }
2219    }
2220    Ok(())
2221}
2222
2223fn apply_transition(
2224    invocation: &ToolInvocation,
2225    transition: &ToolInvocationTransition,
2226    recorded_at: Timestamp,
2227) -> Result<ToolInvocationState, ToolInvocationError> {
2228    match (&invocation.state, transition) {
2229        (ToolInvocationState::Prepared, ToolInvocationTransition::StartAttempt { attempt_id }) => {
2230            Ok(ToolInvocationState::Executing {
2231                attempt_id: *attempt_id,
2232            })
2233        }
2234        (
2235            ToolInvocationState::Failed { error },
2236            ToolInvocationTransition::StartAttempt { attempt_id },
2237        ) => {
2238            let previous_attempt = error.provenance().attempt_id();
2239            if previous_attempt == *attempt_id {
2240                return Err(ToolInvocationError::ReusedAttemptId);
2241            }
2242            validate_retry(invocation, error, recorded_at)?;
2243            Ok(ToolInvocationState::Executing {
2244                attempt_id: *attempt_id,
2245            })
2246        }
2247        (
2248            ToolInvocationState::Executing { attempt_id },
2249            ToolInvocationTransition::RecordResult { result },
2250        ) => {
2251            validate_result_binding(&invocation.intent, *attempt_id, result)?;
2252            Ok(ToolInvocationState::Committed {
2253                result: result.clone(),
2254            })
2255        }
2256        (
2257            ToolInvocationState::Executing { attempt_id },
2258            ToolInvocationTransition::RecordError { error },
2259        ) => {
2260            validate_error_binding(&invocation.intent, *attempt_id, error)?;
2261            Ok(state_from_error(error.clone()))
2262        }
2263        (
2264            ToolInvocationState::Unknown { error: previous },
2265            ToolInvocationTransition::ReconcileResult { result },
2266        ) => {
2267            validate_result_binding(
2268                &invocation.intent,
2269                previous.provenance().attempt_id(),
2270                result,
2271            )?;
2272            Ok(ToolInvocationState::Committed {
2273                result: result.clone(),
2274            })
2275        }
2276        (
2277            ToolInvocationState::Unknown { error: previous },
2278            ToolInvocationTransition::ReconcileError { error },
2279        ) => {
2280            validate_error_binding(
2281                &invocation.intent,
2282                previous.provenance().attempt_id(),
2283                error,
2284            )?;
2285            Ok(state_from_error(error.clone()))
2286        }
2287        _ => Err(ToolInvocationError::InvalidTransition {
2288            status: invocation.status(),
2289            transition: transition.kind(),
2290        }),
2291    }
2292}
2293
2294fn state_from_error(error: ToolError) -> ToolInvocationState {
2295    if error.external_effect() == ToolExternalEffect::Unknown {
2296        ToolInvocationState::Unknown { error }
2297    } else {
2298        ToolInvocationState::Failed { error }
2299    }
2300}
2301
2302fn validate_retry(
2303    invocation: &ToolInvocation,
2304    error: &ToolError,
2305    recorded_at: Timestamp,
2306) -> Result<(), ToolInvocationError> {
2307    let Some(delay) = error.failure().retry_advice().safe_after_delay() else {
2308        return Err(ToolInvocationError::RetryNotAuthorized);
2309    };
2310    let risk = invocation.intent.descriptor.semantics().risk();
2311    let safe = matches!(
2312        (risk, error.external_effect()),
2313        (ToolRisk::ReadOnly, ToolExternalEffect::NotApplicable)
2314            | (
2315                ToolRisk::IdempotentWrite,
2316                ToolExternalEffect::NotStarted
2317                    | ToolExternalEffect::NotApplied
2318                    | ToolExternalEffect::Applied
2319            )
2320            | (
2321                ToolRisk::NonIdempotentWrite,
2322                ToolExternalEffect::NotStarted | ToolExternalEffect::NotApplied
2323            )
2324    );
2325    if !safe {
2326        return Err(ToolInvocationError::RetryUnsafe);
2327    }
2328
2329    let not_before_micros = i128::from(invocation.journal_head.recorded_at().unix_micros())
2330        + i128::from(delay.as_i64()) * 1_000;
2331    if not_before_micros > i128::from(Timestamp::MAX.unix_micros()) {
2332        return Err(ToolInvocationError::RetryDelayOutOfRange);
2333    }
2334    let not_before = Timestamp::from_unix_micros(
2335        i64::try_from(not_before_micros).map_err(|_| ToolInvocationError::RetryDelayOutOfRange)?,
2336    )
2337    .map_err(|_| ToolInvocationError::RetryDelayOutOfRange)?;
2338    if recorded_at < not_before {
2339        return Err(ToolInvocationError::RetryDelayNotElapsed {
2340            not_before,
2341            actual: recorded_at,
2342        });
2343    }
2344    Ok(())
2345}
2346
2347#[cfg(test)]
2348mod tests {
2349    use schemars::schema_for;
2350    use serde_json::{Value, from_value, json, to_value};
2351
2352    use super::*;
2353    use crate::{
2354        Checkpoint, DurationMillis, EventId, Failure, FailureCategory, FailureCode, FailureId,
2355        FailureMessage, FailureOrigin, ToolErrorPhase, ToolErrorProvenance,
2356    };
2357
2358    fn fixture(path: &[&str], source: &str) -> Value {
2359        let mut value: Value = serde_json::from_str(source).unwrap();
2360        for component in path {
2361            value = match component.parse::<usize>() {
2362                Ok(index) => value[index].clone(),
2363                Err(_) => value[*component].clone(),
2364            };
2365        }
2366        value
2367    }
2368
2369    fn checkpoint() -> Checkpoint {
2370        from_value(fixture(
2371            &["checkpoints", "0"],
2372            include_str!("../tests/fixtures/core-checkpoint-v1.json"),
2373        ))
2374        .unwrap()
2375    }
2376
2377    fn descriptor() -> ToolDescriptor {
2378        from_value(fixture(
2379            &["descriptors", "valid", "0"],
2380            include_str!("../tests/fixtures/core-tool-v1.json"),
2381        ))
2382        .unwrap()
2383    }
2384
2385    fn input() -> ToolInput {
2386        from_value(fixture(
2387            &["inputs", "valid", "0"],
2388            include_str!("../tests/fixtures/core-tool-runtime-v1.json"),
2389        ))
2390        .unwrap()
2391    }
2392
2393    fn result() -> ToolResult {
2394        from_value(fixture(
2395            &["results", "valid", "0"],
2396            include_str!("../tests/fixtures/core-tool-runtime-v1.json"),
2397        ))
2398        .unwrap()
2399    }
2400
2401    fn fixture_error(index: &str) -> ToolError {
2402        from_value(fixture(
2403            &["errors", "valid", index],
2404            include_str!("../tests/fixtures/core-tool-runtime-v1.json"),
2405        ))
2406        .unwrap()
2407    }
2408
2409    fn invocation_id() -> InvocationId {
2410        "01912345-6789-7abc-8def-0123456789ad".parse().unwrap()
2411    }
2412
2413    fn attempt(suffix: &str) -> AttemptId {
2414        format!("01912345-6789-7abc-8def-0123456789{suffix}")
2415            .parse()
2416            .unwrap()
2417    }
2418
2419    fn intent() -> ToolInvocationIntent {
2420        let checkpoint = checkpoint();
2421        let descriptor = descriptor();
2422        ToolInvocationIntent::new(
2423            NodeActivation::new(
2424                checkpoint.head(),
2425                GraphNamespace::root(),
2426                NodeId::new("authorize").unwrap(),
2427                Digest::sha256(b"node-input"),
2428            ),
2429            invocation_id(),
2430            descriptor.clone(),
2431            input(),
2432            descriptor.limits().clone(),
2433        )
2434        .unwrap()
2435    }
2436
2437    fn journal(intent: &ToolInvocationIntent, sequence: u64) -> JournalHead {
2438        let base = intent
2439            .activation()
2440            .base_checkpoint()
2441            .journal_head()
2442            .recorded_at();
2443        let offset = i64::try_from(sequence - 1).unwrap() * 1_000_000;
2444        let event_id: EventId =
2445            format!("01912345-6789-7abc-8def-0123456789{:02x}", 0xc0 + sequence)
2446                .parse()
2447                .unwrap();
2448        JournalHead::new(
2449            intent.tenant_id().clone(),
2450            intent.run_id(),
2451            JournalSequence::new(sequence).unwrap(),
2452            event_id,
2453            Timestamp::from_unix_micros(base.unix_micros() + offset).unwrap(),
2454            Digest::sha256(sequence.to_be_bytes()),
2455        )
2456    }
2457
2458    fn prepared() -> ToolInvocation {
2459        let intent = intent();
2460        let head = journal(&intent, 2);
2461        ToolInvocation::prepare(intent, head).unwrap()
2462    }
2463
2464    fn safe_error(delay_millis: i64) -> ToolError {
2465        let failure = Failure::new(
2466            "01912345-6789-7abc-8def-0123456789b8"
2467                .parse::<FailureId>()
2468                .unwrap(),
2469            FailureCategory::DependencyUnavailable,
2470            FailureCode::new("tool.dependency_unavailable").unwrap(),
2471            FailureOrigin::new("tool.payments").unwrap(),
2472            FailureMessage::new("The payment dependency is temporarily unavailable.").unwrap(),
2473            RetryAdvice::SafeAfter {
2474                delay: DurationMillis::new(delay_millis).unwrap(),
2475            },
2476        )
2477        .unwrap();
2478        ToolError::new(
2479            failure,
2480            ToolErrorPhase::Execution,
2481            ToolExternalEffect::NotApplied,
2482            ToolErrorProvenance::new(
2483                invocation_id(),
2484                attempt("ab"),
2485                descriptor().metadata().identity().clone(),
2486            ),
2487        )
2488        .unwrap()
2489    }
2490
2491    #[test]
2492    fn namespace_and_revision_wires_are_canonical_and_bounded() {
2493        for valid in ["", "parent", "parent/child-v2", "a.b/c_d"] {
2494            let namespace = GraphNamespace::new(valid).unwrap();
2495            assert_eq!(to_value(&namespace).unwrap(), json!(valid));
2496            assert_eq!(
2497                from_value::<GraphNamespace>(json!(valid)).unwrap(),
2498                namespace
2499            );
2500        }
2501        for invalid in ["/node", "node/", "node//child", ".", "parent/.."] {
2502            assert!(GraphNamespace::new(invalid).is_err());
2503        }
2504        assert!(GraphNamespace::new("a".repeat(GraphNamespace::MAX_LEN + 1)).is_err());
2505
2506        for value in [0, 1, MAX_DATABASE_ORDINAL] {
2507            let revision = ToolInvocationRevision::new(value).unwrap();
2508            assert_eq!(
2509                revision
2510                    .to_string()
2511                    .parse::<ToolInvocationRevision>()
2512                    .unwrap(),
2513                revision
2514            );
2515            assert_eq!(
2516                from_value::<ToolInvocationRevision>(json!(value.to_string())).unwrap(),
2517                revision
2518            );
2519        }
2520        for invalid in [
2521            json!(0),
2522            json!("00"),
2523            json!("-1"),
2524            json!("9223372036854775808"),
2525        ] {
2526            assert!(from_value::<ToolInvocationRevision>(invalid).is_err());
2527        }
2528    }
2529
2530    #[test]
2531    fn ready_root_activation_is_deterministic_and_checkpoint_bound() {
2532        let checkpoint = checkpoint();
2533        let node_id = NodeId::new("authorize").unwrap();
2534        let first = NodeActivation::for_ready_root(&checkpoint, node_id.clone()).unwrap();
2535        let replayed = NodeActivation::for_ready_root(&checkpoint, node_id).unwrap();
2536
2537        assert_eq!(first, replayed);
2538        assert_eq!(first.base_checkpoint(), &checkpoint.head());
2539        assert!(first.graph_namespace().is_root());
2540        assert_eq!(first.node_id().as_str(), "authorize");
2541        assert_eq!(
2542            first.input_digest(),
2543            "sha256:fe68cf4a42614bfc0bf4b41ab0fd3e552840e2a389bb61354af2dbdff086bb2c"
2544                .parse()
2545                .unwrap()
2546        );
2547
2548        let sibling =
2549            NodeActivation::for_ready_root(&checkpoint, NodeId::new("reserve-stock").unwrap())
2550                .unwrap();
2551        assert_ne!(first.input_digest(), sibling.input_digest());
2552
2553        assert_eq!(
2554            NodeActivation::for_ready_root(&checkpoint, NodeId::new("not-ready").unwrap(),),
2555            Err(NodeActivationError::NodeNotReady {
2556                node_id: NodeId::new("not-ready").unwrap(),
2557            })
2558        );
2559    }
2560
2561    #[test]
2562    fn intent_is_narrowed_integrity_bound_and_secret_safe_in_debug() {
2563        let intent = intent();
2564        let restored = from_value::<ToolInvocationIntent>(to_value(&intent).unwrap()).unwrap();
2565        assert_eq!(restored, intent);
2566
2567        let mut tampered = to_value(&intent).unwrap();
2568        tampered["input"]["value"]["amount"] = json!(43);
2569        assert!(from_value::<ToolInvocationIntent>(tampered).is_err());
2570
2571        let descriptor = descriptor();
2572        let widened = ToolExecutionLimits::new(
2573            DurationMillis::new(descriptor.limits().timeout().as_i64() + 1).unwrap(),
2574            descriptor.limits().max_concurrency(),
2575            descriptor.limits().max_input_bytes(),
2576            descriptor.limits().max_inline_result_bytes(),
2577            descriptor.limits().max_artifacts(),
2578            descriptor.limits().max_total_artifact_bytes(),
2579        )
2580        .unwrap();
2581        assert_eq!(
2582            ToolInvocationIntent::new(
2583                intent.activation().clone(),
2584                invocation_id(),
2585                descriptor,
2586                input(),
2587                widened,
2588            ),
2589            Err(ToolInvocationIntentError::EffectiveLimitWidened {
2590                limit: ToolInvocationLimit::Timeout,
2591            })
2592        );
2593
2594        let debug = format!("{intent:?}");
2595        assert!(!debug.contains("CNY"));
2596        assert!(!debug.contains("amount"));
2597        assert!(debug.contains("ToolInput"));
2598    }
2599
2600    #[test]
2601    fn success_path_round_trips_and_history_verifies_transactionally() {
2602        let prepared = prepared();
2603        let executing = prepared
2604            .advance(
2605                ToolInvocationTransition::StartAttempt {
2606                    attempt_id: attempt("ab"),
2607                },
2608                journal(prepared.intent(), 3),
2609            )
2610            .unwrap();
2611        let committed = executing
2612            .advance(
2613                ToolInvocationTransition::RecordResult { result: result() },
2614                journal(executing.intent(), 4),
2615            )
2616            .unwrap();
2617
2618        assert_eq!(prepared.status(), ToolInvocationStatus::Prepared);
2619        assert_eq!(executing.status(), ToolInvocationStatus::Executing);
2620        assert_eq!(committed.status(), ToolInvocationStatus::Committed);
2621        assert_eq!(committed.revision().get(), 2);
2622        let decoded = from_value::<ToolInvocation>(to_value(&committed).unwrap()).unwrap();
2623        assert_eq!(decoded.head(), committed.head());
2624
2625        let mut verifier = ToolInvocationHistoryVerifier::new();
2626        for record in [&prepared, &executing, &committed] {
2627            verifier.verify_next(record).unwrap();
2628        }
2629        assert_eq!(verifier.head(), Some(committed.head()));
2630
2631        assert!(matches!(
2632            committed.advance(
2633                ToolInvocationTransition::StartAttempt {
2634                    attempt_id: attempt("ac"),
2635                },
2636                journal(committed.intent(), 5),
2637            ),
2638            Err(ToolInvocationError::InvalidTransition {
2639                status: ToolInvocationStatus::Committed,
2640                transition: ToolInvocationTransitionKind::StartAttempt,
2641            })
2642        ));
2643    }
2644
2645    #[test]
2646    fn unknown_outcome_cannot_retry_and_only_reconciliation_resolves_it() {
2647        let prepared = prepared();
2648        let executing = prepared
2649            .advance(
2650                ToolInvocationTransition::StartAttempt {
2651                    attempt_id: attempt("ab"),
2652                },
2653                journal(prepared.intent(), 3),
2654            )
2655            .unwrap();
2656        let unknown = executing
2657            .advance(
2658                ToolInvocationTransition::RecordError {
2659                    error: fixture_error("1"),
2660                },
2661                journal(executing.intent(), 4),
2662            )
2663            .unwrap();
2664        assert_eq!(unknown.status(), ToolInvocationStatus::Unknown);
2665        unknown.validate_reconciliation_result(&result()).unwrap();
2666        unknown
2667            .validate_reconciliation_error(&fixture_error("1"))
2668            .unwrap();
2669        assert!(matches!(
2670            prepared.validate_reconciliation_result(&result()),
2671            Err(ToolInvocationError::InvalidTransition {
2672                status: ToolInvocationStatus::Prepared,
2673                transition: ToolInvocationTransitionKind::ReconcileResult,
2674            })
2675        ));
2676        assert!(matches!(
2677            unknown.advance(
2678                ToolInvocationTransition::StartAttempt {
2679                    attempt_id: attempt("ac"),
2680                },
2681                journal(unknown.intent(), 5),
2682            ),
2683            Err(ToolInvocationError::InvalidTransition {
2684                status: ToolInvocationStatus::Unknown,
2685                transition: ToolInvocationTransitionKind::StartAttempt,
2686            })
2687        ));
2688
2689        let reconciled = unknown
2690            .advance(
2691                ToolInvocationTransition::ReconcileResult { result: result() },
2692                journal(unknown.intent(), 5),
2693            )
2694            .unwrap();
2695        assert_eq!(reconciled.status(), ToolInvocationStatus::Committed);
2696        assert!(matches!(
2697            reconciled.validate_reconciliation_error(&fixture_error("1")),
2698            Err(ToolInvocationError::InvalidTransition {
2699                status: ToolInvocationStatus::Committed,
2700                transition: ToolInvocationTransitionKind::ReconcileError,
2701            })
2702        ));
2703    }
2704
2705    #[test]
2706    fn retry_requires_explicit_safety_and_elapsed_delay() {
2707        let prepared = prepared();
2708        let executing = prepared
2709            .advance(
2710                ToolInvocationTransition::StartAttempt {
2711                    attempt_id: attempt("ab"),
2712                },
2713                journal(prepared.intent(), 3),
2714            )
2715            .unwrap();
2716        let failed = executing
2717            .advance(
2718                ToolInvocationTransition::RecordError {
2719                    error: safe_error(2_000),
2720                },
2721                journal(executing.intent(), 4),
2722            )
2723            .unwrap();
2724
2725        let early_head = JournalHead::new(
2726            failed.intent().tenant_id().clone(),
2727            failed.intent().run_id(),
2728            JournalSequence::new(5).unwrap(),
2729            "01912345-6789-7abc-8def-0123456789c5".parse().unwrap(),
2730            Timestamp::from_unix_micros(
2731                failed.journal_head().recorded_at().unix_micros() + 1_000_000,
2732            )
2733            .unwrap(),
2734            Digest::sha256(b"early"),
2735        );
2736        assert!(matches!(
2737            failed.advance(
2738                ToolInvocationTransition::StartAttempt {
2739                    attempt_id: attempt("ac"),
2740                },
2741                early_head,
2742            ),
2743            Err(ToolInvocationError::RetryDelayNotElapsed { .. })
2744        ));
2745
2746        let retried = failed
2747            .advance(
2748                ToolInvocationTransition::StartAttempt {
2749                    attempt_id: attempt("ac"),
2750                },
2751                journal(failed.intent(), 6),
2752            )
2753            .unwrap();
2754        assert_eq!(retried.attempt_id(), Some(attempt("ac")));
2755
2756        let never_failed = executing
2757            .advance(
2758                ToolInvocationTransition::RecordError {
2759                    error: fixture_error("0"),
2760                },
2761                journal(executing.intent(), 4),
2762            )
2763            .unwrap();
2764        assert!(matches!(
2765            never_failed.advance(
2766                ToolInvocationTransition::StartAttempt {
2767                    attempt_id: attempt("ac"),
2768                },
2769                journal(never_failed.intent(), 5),
2770            ),
2771            Err(ToolInvocationError::RetryNotAuthorized)
2772        ));
2773    }
2774
2775    #[test]
2776    fn tampering_and_branch_substitution_fail_closed() {
2777        let prepared = prepared();
2778        let executing = prepared
2779            .advance(
2780                ToolInvocationTransition::StartAttempt {
2781                    attempt_id: attempt("ab"),
2782                },
2783                journal(prepared.intent(), 3),
2784            )
2785            .unwrap();
2786        let mut wire = to_value(&executing).unwrap();
2787        wire["state"]["attempt_id"] = json!(attempt("ac"));
2788        assert!(from_value::<ToolInvocation>(wire).is_err());
2789
2790        let mut wire = to_value(&executing).unwrap();
2791        wire["transition_digest"] = json!(Digest::sha256(b"wrong-transition"));
2792        assert!(from_value::<ToolInvocation>(wire).is_err());
2793
2794        let branch = prepared
2795            .advance(
2796                ToolInvocationTransition::StartAttempt {
2797                    attempt_id: attempt("ac"),
2798                },
2799                journal(prepared.intent(), 4),
2800            )
2801            .unwrap();
2802        let mut verifier = ToolInvocationHistoryVerifier::new();
2803        verifier.verify_next(&prepared).unwrap();
2804        verifier.verify_next(&executing).unwrap();
2805        let accepted = verifier.head();
2806        assert_eq!(
2807            verifier.verify_next(&branch),
2808            Err(ToolInvocationHistoryError::PreviousHeadMismatch)
2809        );
2810        assert_eq!(verifier.head(), accepted);
2811    }
2812
2813    #[test]
2814    fn public_object_schemas_are_closed() {
2815        for schema in [
2816            to_value(schema_for!(NodeActivation)).unwrap(),
2817            to_value(schema_for!(ToolInvocationIntent)).unwrap(),
2818            to_value(schema_for!(ToolInvocationHead)).unwrap(),
2819            to_value(schema_for!(ToolInvocation)).unwrap(),
2820        ] {
2821            assert_eq!(schema["additionalProperties"], false);
2822        }
2823    }
2824}