Skip to main content

dsl_kit_core/
lib.rs

1//! Engine primitives for `dsl-kit` (v3 engine shape).
2//!
3//! This crate defines the observable primitives every DSL built with the
4//! kit carries: stable node identifiers, call frame identifiers with
5//! depth, iteration counters, root-to-node paths, an event stream, the
6//! `Stepper` trait modelling evaluation as an externally-driven state
7//! machine, an AST traversal contract, and structured errors that always
8//! carry the location at which the error happened.
9//!
10//! ## v3 shape (Round 13)
11//!
12//! - `Stepper` is a sync trait; async is a host concern. Interpretation is
13//!   observable, steppable, and supports first-class fan-out with structured
14//!   join through `Par` frames.
15//! - Suspensions are identified by `SuspensionId` and can be N-in-flight;
16//!   the host resolves each with `Ok(Value)` or `Err(EffectError)`.
17//! - Fan-out is expressed by a `Par` frame with a `JoinPolicy` (shape +
18//!   fail); reducers fold the collected slots into the parent value.
19//! - Cancellation is cooperative; the host drains cancelled ids via
20//!   `take_cancellations()` and looks them up in its own runtime-handle
21//!   map.
22//!
23//! The full behavioural specification lives in the rustdoc of
24//! [`Engine`], [`Stepper`], and the item-level contracts they link.
25
26#![warn(missing_docs)]
27
28// Re-exported for `#[derive(DslExec)]`-generated code (`Call` payload
29// construction); not part of the public API surface.
30#[doc(hidden)]
31pub use serde_json;
32
33use std::borrow::Cow;
34use std::collections::HashMap;
35use std::fmt;
36use std::sync::Arc;
37use std::sync::atomic::{AtomicU64, Ordering};
38
39mod drive;
40mod engine;
41pub use drive::{AsyncEffectResolver, DriveOutcome, EffectResolver, drive, drive_async};
42pub use engine::{Ast, Engine, ExecError, LoopDecision, NodeKind};
43
44// ---------- Observation primitives --------------------------------------
45
46/// Stable identifier assigned to every AST node when the tree is built.
47///
48/// A `NodeId` is orthogonal to source location: two nodes at the same
49/// source span but in different expansions carry different IDs, and the
50/// same node retains its ID across evaluation runs.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub struct NodeId(pub u64);
53
54impl fmt::Display for NodeId {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        write!(f, "n{}", self.0)
57    }
58}
59
60/// Identifier for a single activation of a function-like node.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub struct CallFrameId(pub u64);
63
64impl fmt::Display for CallFrameId {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        write!(f, "f{}", self.0)
67    }
68}
69
70/// Position within the current iteration of a loop-shaped node.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub struct Iteration(pub u64);
73
74/// Root-to-node identifier chain, usable for path-shaped breakpoint
75/// conditions.
76#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
77pub struct Path(pub Vec<NodeId>);
78
79impl Path {
80    /// Returns an empty path (i.e. the root).
81    #[inline]
82    pub fn root() -> Self {
83        Path(Vec::new())
84    }
85
86    /// Returns a new path with `node` pushed onto the end.
87    pub fn push(&self, node: NodeId) -> Self {
88        let mut next = self.0.clone();
89        next.push(node);
90        Path(next)
91    }
92
93    /// Depth of the path (number of node IDs).
94    #[inline]
95    pub fn depth(&self) -> usize {
96        self.0.len()
97    }
98
99    /// Returns the node ID at the tip of the path, if any.
100    pub fn tip(&self) -> Option<NodeId> {
101        self.0.last().copied()
102    }
103}
104
105impl fmt::Display for Path {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        if self.0.is_empty() {
108            return write!(f, "/");
109        }
110        for id in &self.0 {
111            write!(f, "/{id}")?;
112        }
113        Ok(())
114    }
115}
116
117/// Monotonic ID generator for nodes and call frames.
118#[derive(Debug, Default)]
119pub struct IdGen {
120    next: AtomicU64,
121}
122
123impl IdGen {
124    /// Creates a fresh generator initialised at zero.
125    pub const fn new() -> Self {
126        Self {
127            next: AtomicU64::new(0),
128        }
129    }
130
131    /// Allocates a fresh `NodeId`.
132    pub fn node(&self) -> NodeId {
133        NodeId(self.next.fetch_add(1, Ordering::Relaxed))
134    }
135
136    /// Allocates a fresh `CallFrameId`.
137    pub fn frame(&self) -> CallFrameId {
138        CallFrameId(self.next.fetch_add(1, Ordering::Relaxed))
139    }
140}
141
142/// Location context attached to every emitted event and to every error.
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct NodeContext {
145    /// The node currently being evaluated.
146    pub node: NodeId,
147    /// The root-to-node path leading to `node`.
148    pub path: Path,
149    /// The active call frame, if any.
150    pub frame: Option<CallFrameId>,
151    /// Depth of the current call / evaluation stack.
152    pub depth: u32,
153    /// Iteration counter when the surrounding node is loop-shaped.
154    pub iteration: Option<Iteration>,
155}
156
157impl NodeContext {
158    /// Builds a context for a node visited without any active frame.
159    pub fn at(node: NodeId, path: Path) -> Self {
160        Self {
161            node,
162            path,
163            frame: None,
164            depth: 0,
165            iteration: None,
166        }
167    }
168}
169
170impl fmt::Display for NodeContext {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        write!(f, "{}", self.node)?;
173        if let Some(frame) = self.frame {
174            write!(f, " (frame {}, depth {})", frame, self.depth)?;
175        }
176        if let Some(it) = self.iteration {
177            write!(f, " iter {}", it.0)?;
178        }
179        write!(f, " at {}", self.path)
180    }
181}
182
183// ---------- Suspension identity ----------------------------------------
184
185/// Stable identifier for one in-flight suspension.
186///
187/// Allocated by the engine when a `Frame::PendingEffect` leaf is created.
188/// The host uses it as the key on [`Stepper::resolve`] and as the map key
189/// for its own `SuspensionId -> runtime handle` bookkeeping when
190/// cooperative cancellation is required. Monotonic within one `Stepper`
191/// instance; never reused, even after cancellation.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
193pub struct SuspensionId(pub u64);
194
195impl fmt::Display for SuspensionId {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        write!(f, "s{}", self.0)
198    }
199}
200
201/// One live suspension.
202#[derive(Debug, Clone)]
203pub struct Pending {
204    /// Stable identifier.
205    pub id: SuspensionId,
206    /// Why the engine yielded.
207    pub reason: SuspendReason,
208    /// Where the suspension happened.
209    pub at: NodeContext,
210}
211
212// ---------- Suspend reason ---------------------------------------------
213
214/// Why the engine yielded control.
215///
216/// Cancellation runtime handles are NOT stored here — the host maintains
217/// its own `SuspensionId -> handle` map.
218#[derive(Debug, Clone)]
219#[non_exhaustive]
220pub enum SuspendReason {
221    /// A first-class external effect (LLM call, tool invocation, …).
222    Call {
223        /// Host-defined effect descriptor.
224        spec: CallSpec,
225    },
226    /// A registered breakpoint fired.
227    Breakpoint,
228    /// The scheduler chose to yield cooperatively.
229    Cooperative,
230    /// Host-defined effect the DSL wants to model beyond `Call`.
231    User {
232        /// Short tag identifying the effect kind.
233        tag: Cow<'static, str>,
234    },
235}
236
237impl fmt::Display for SuspendReason {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        match self {
240            SuspendReason::Call { spec } => write!(f, "call({})", spec.label),
241            SuspendReason::Breakpoint => write!(f, "breakpoint"),
242            SuspendReason::Cooperative => write!(f, "cooperative"),
243            SuspendReason::User { tag } => write!(f, "user({tag})"),
244        }
245    }
246}
247
248/// Host-defined effect descriptor. Opaque to the engine.
249#[derive(Debug, Clone)]
250pub struct CallSpec {
251    /// Short human-readable label (also fed into the DSL's canned
252    /// responses when applicable).
253    pub label: String,
254    /// Effect payload; the engine stores it verbatim and the host
255    /// interprets it per the DSL's semantics.
256    pub payload: serde_json::Value,
257}
258
259// ---------- Event stream -----------------------------------------------
260
261/// One observation from the evaluator.
262#[derive(Debug, Clone)]
263#[non_exhaustive]
264pub enum Event {
265    /// Emitted before a node's semantics run.
266    VisitPre {
267        /// Where the observation happened.
268        at: NodeContext,
269    },
270    /// Emitted after a node's semantics complete.
271    VisitPost {
272        /// Where the observation happened.
273        at: NodeContext,
274    },
275    /// A function-like node started a new call frame.
276    FrameEnter {
277        /// Where the observation happened.
278        at: NodeContext,
279    },
280    /// A function-like node's frame ended.
281    FrameLeave {
282        /// Where the observation happened.
283        at: NodeContext,
284    },
285    /// A loop node advanced to a new iteration.
286    IterationTick {
287        /// Where the observation happened.
288        at: NodeContext,
289    },
290    /// The stepper is about to yield to the outside world.
291    Suspend {
292        /// Where the observation happened.
293        at: NodeContext,
294        /// Why the stepper is yielding.
295        reason: SuspendReason,
296    },
297    /// The stepper resumed after a yield.
298    Resume {
299        /// Where the observation happened.
300        at: NodeContext,
301    },
302    /// A suspension was cancelled (tracer convenience; the authoritative
303    /// channel is [`Stepper::take_cancellations`]).
304    Cancel {
305        /// The cancelled suspension.
306        id: SuspensionId,
307    },
308}
309
310/// Sink for the event stream.
311pub trait EventSink {
312    /// Consumes one event.
313    fn emit(&mut self, event: &Event);
314}
315
316/// A no-op sink useful for tests and for evaluators that do not need
317/// observation.
318#[derive(Debug, Default)]
319pub struct NullSink;
320
321impl EventSink for NullSink {
322    #[inline]
323    fn emit(&mut self, _event: &Event) {}
324}
325
326/// Silent event sink that counts each event kind.
327///
328/// Used by the engine as its default observation channel so hosts
329/// can inspect basic activity without wiring a custom sink.
330#[derive(Debug, Default, Clone, Copy)]
331pub struct CountingSink {
332    /// Number of `VisitPre` events observed.
333    pub visit_pre: u32,
334    /// Number of `VisitPost` events observed.
335    pub visit_post: u32,
336    /// Number of `FrameEnter` events observed.
337    pub frame_enter: u32,
338    /// Number of `FrameLeave` events observed.
339    pub frame_leave: u32,
340    /// Number of `IterationTick` events observed.
341    pub iteration_tick: u32,
342    /// Number of `Suspend` events observed.
343    pub suspend: u32,
344    /// Number of `Resume` events observed.
345    pub resume: u32,
346}
347
348impl EventSink for CountingSink {
349    fn emit(&mut self, event: &Event) {
350        match event {
351            Event::VisitPre { .. } => self.visit_pre += 1,
352            Event::VisitPost { .. } => self.visit_post += 1,
353            Event::FrameEnter { .. } => self.frame_enter += 1,
354            Event::FrameLeave { .. } => self.frame_leave += 1,
355            Event::IterationTick { .. } => self.iteration_tick += 1,
356            Event::Suspend { .. } => self.suspend += 1,
357            Event::Resume { .. } => self.resume += 1,
358            _ => {}
359        }
360    }
361}
362
363impl CountingSink {
364    /// Returns a single-line human-readable event histogram.
365    pub fn summarise(&self) -> String {
366        format!(
367            "pre={} post={} frame_enter={} frame_leave={} iter={} suspend={} resume={}",
368            self.visit_pre,
369            self.visit_post,
370            self.frame_enter,
371            self.frame_leave,
372            self.iteration_tick,
373            self.suspend,
374            self.resume,
375        )
376    }
377}
378
379/// Recording event sink that keeps every observed [`Event`] in order.
380///
381/// Complements [`CountingSink`] (built-in on `Engine`) by preserving the
382/// full event history for downstream inspection — debuggers, tracers,
383/// test assertions, etc. Attach one to an engine via
384/// `Engine::attach_sink` and drain / snapshot it between mutations.
385#[derive(Debug, Default, Clone)]
386pub struct BufferingSink {
387    events: Vec<Event>,
388}
389
390impl BufferingSink {
391    /// Creates an empty, unbounded buffer.
392    pub fn new() -> Self {
393        Self { events: Vec::new() }
394    }
395
396    /// Creates an empty buffer with pre-allocated capacity `cap`.
397    ///
398    /// The buffer is still logically unbounded; `cap` is only a
399    /// hint to avoid early re-allocations.
400    pub fn with_capacity(cap: usize) -> Self {
401        Self {
402            events: Vec::with_capacity(cap),
403        }
404    }
405
406    /// Returns a slice view of the recorded events without draining.
407    pub fn snapshot(&self) -> &[Event] {
408        &self.events
409    }
410
411    /// Takes every recorded event and clears the buffer.
412    pub fn drain(&mut self) -> Vec<Event> {
413        std::mem::take(&mut self.events)
414    }
415
416    /// Discards every recorded event without returning them.
417    pub fn clear(&mut self) {
418        self.events.clear();
419    }
420
421    /// Number of recorded events currently held.
422    pub fn len(&self) -> usize {
423        self.events.len()
424    }
425
426    /// True when no events are held.
427    pub fn is_empty(&self) -> bool {
428        self.events.is_empty()
429    }
430}
431
432impl EventSink for BufferingSink {
433    fn emit(&mut self, event: &Event) {
434        self.events.push(event.clone());
435    }
436}
437
438// ---------- Errors ------------------------------------------------------
439
440/// Structured error type for engine and evaluator failures.
441///
442/// Every applicable variant carries a [`NodeContext`] or a
443/// [`SuspensionId`] / [`ReducerId`] so that error messages, MCP tool
444/// responses, and log lines can always answer "at which node / for
445/// which id did this happen?". Diagnostic codes are stable,
446/// machine-readable identifiers under the `dsl_kit::` namespace.
447#[derive(Debug, thiserror::Error, miette::Diagnostic)]
448#[non_exhaustive]
449pub enum EngineError {
450    /// The evaluator explicitly aborted the current step.
451    #[error("evaluation aborted at {at}: {reason}")]
452    #[diagnostic(
453        code(dsl_kit::eval::aborted),
454        help(
455            "The interpreter returned an `Aborted` outcome. Inspect the reason and the node context to locate the abort site."
456        )
457    )]
458    Aborted {
459        /// Where the abort happened.
460        at: NodeContext,
461        /// Why the evaluator aborted.
462        reason: String,
463    },
464
465    /// A node's semantics returned an error.
466    #[error("evaluator failed at {at}")]
467    #[diagnostic(
468        code(dsl_kit::eval::failed),
469        help(
470            "The interpreter returned an error while evaluating this node. The `#[source]` chain points at the underlying failure."
471        )
472    )]
473    EvalFailed {
474        /// Where the failure happened.
475        at: NodeContext,
476        /// The underlying error returned by the interpreter.
477        #[source]
478        source: Box<dyn std::error::Error + Send + Sync>,
479    },
480
481    /// A traversal or stepper reached a node that was expected to have a
482    /// specific shape but did not.
483    #[error("malformed AST at {at}: {detail}")]
484    #[diagnostic(
485        code(dsl_kit::ast::malformed),
486        help(
487            "An AST invariant was violated. This usually means a hand-constructed tree omitted a required child."
488        )
489    )]
490    Malformed {
491        /// Where the invariant violation was detected.
492        at: NodeContext,
493        /// Human-readable description of the invariant that failed.
494        detail: String,
495    },
496
497    /// The host tried to resume a suspended stepper before it had suspended,
498    /// or resumed twice for a single suspension.
499    #[error("stepper protocol violation at {at}: {detail}")]
500    #[diagnostic(
501        code(dsl_kit::stepper::protocol),
502        help(
503            "The stepper's suspend/resume contract was broken. Each `PendingEffect` leaf must be resolved exactly once before further steps observe its value."
504        )
505    )]
506    StepperProtocol {
507        /// Where the protocol violation was detected.
508        at: NodeContext,
509        /// Human-readable description of the misuse.
510        detail: String,
511    },
512
513    /// The host called `resolve` with a `SuspensionId` the engine does
514    /// not know about (never created, already resolved, or belonging to
515    /// a cancelled leg). Hosts treat this as a benign no-op — it
516    /// happens routinely for cancelled effects whose external work
517    /// completes after abort.
518    #[error("unknown suspension {id}")]
519    #[diagnostic(
520        code(dsl_kit::stepper::unknown_suspension),
521        help(
522            "The host called resolve() with a SuspensionId the engine does not know. This is the expected outcome for a late response arriving after the effect's branch was cancelled."
523        )
524    )]
525    UnknownSuspension {
526        /// The unknown suspension id.
527        id: SuspensionId,
528    },
529
530    /// A `ParFrame` referenced a `ReducerId` that is not registered in
531    /// the active [`ReducerRegistry`].
532    #[error("unknown reducer {id:?}")]
533    #[diagnostic(
534        code(dsl_kit::reducer::unknown),
535        help(
536            "The ParFrame's reducer_id was not found in the ReducerRegistry. Register the reducer at Stepper build time or fix the AST to reference a known id."
537        )
538    )]
539    UnknownReducer {
540        /// The unknown reducer id.
541        id: ReducerId,
542    },
543
544    /// An `Apply` node referenced an [`OpId`] that is not registered in
545    /// the active [`OpRegistry`].
546    #[error("unknown op {id:?}")]
547    #[diagnostic(
548        code(dsl_kit::op::unknown),
549        help(
550            "The Apply node's op_id was not found in the OpRegistry. Register the op at Stepper build time (Engine::new_with_ops) or fix the AST to reference a known id."
551        )
552    )]
553    UnknownOp {
554        /// The unknown op id.
555        id: OpId,
556    },
557}
558
559/// Result alias for engine and evaluator operations.
560pub type EngineResult<T> = Result<T, EngineError>;
561
562/// One entry in an error catalogue: a stable machine-readable code paired
563/// with the human-readable help text explaining how to react to it.
564#[derive(Debug, Clone, PartialEq, Eq)]
565pub struct ErrorCatalogEntry {
566    /// Stable diagnostic code, e.g. `"dsl_kit::eval::aborted"`.
567    pub code: String,
568    /// Help text mirroring the miette `help(..)` attribute on the variant.
569    pub help: String,
570}
571
572/// Returns the built-in [`EngineError`] catalogue.
573pub fn engine_error_catalog() -> Vec<ErrorCatalogEntry> {
574    use miette::Diagnostic;
575
576    fn ctx() -> NodeContext {
577        NodeContext::at(NodeId(0), Path::root())
578    }
579
580    let samples: Vec<EngineError> = vec![
581        EngineError::Aborted {
582            at: ctx(),
583            reason: String::new(),
584        },
585        EngineError::EvalFailed {
586            at: ctx(),
587            source: Box::new(std::io::Error::other("")),
588        },
589        EngineError::Malformed {
590            at: ctx(),
591            detail: String::new(),
592        },
593        EngineError::StepperProtocol {
594            at: ctx(),
595            detail: String::new(),
596        },
597        EngineError::UnknownSuspension {
598            id: SuspensionId(0),
599        },
600        EngineError::UnknownReducer {
601            id: ReducerId(String::new()),
602        },
603        EngineError::UnknownOp {
604            id: OpId(String::new()),
605        },
606    ];
607
608    samples
609        .into_iter()
610        .filter_map(|e| {
611            let code = e.code()?.to_string();
612            let help = e.help()?.to_string();
613            Some(ErrorCatalogEntry { code, help })
614        })
615        .collect()
616}
617
618// ---------- Step outcome & Stepper -------------------------------------
619
620/// Result of one [`Stepper::step`] call.
621///
622/// The three states name the driver's next action verbatim:
623///
624/// - `Ready` — the engine made progress and can make more without host
625///   input. Call `step()` again immediately.
626/// - `Blocked { newly_pending }` — the engine did everything it can
627///   without host input. Do NOT call `step()` again until at least one
628///   `resolve` has been fed back, or a cancellation observed via
629///   `take_cancellations()`.
630/// - `Done(v)` — the root frame produced a value; interpretation is
631///   complete.
632///
633/// Terminal failure is returned as `Err(Stepper::Error)` from `step()`;
634/// there is no `Failed` variant. Cancellations queued during the failing
635/// step are still drainable via `take_cancellations()` after the `Err`.
636#[derive(Debug, Clone)]
637pub enum StepOutcome<V> {
638    /// Engine advanced; keep looping.
639    Ready,
640    /// Engine is blocked awaiting host input. `newly_pending` names
641    /// suspensions created this call (may be empty when the block is
642    /// on already-live pending).
643    Blocked {
644        /// Suspensions newly created during this `step` call.
645        newly_pending: smallvec::SmallVec<[Pending; 1]>,
646    },
647    /// Interpretation completed with a value.
648    Done(V),
649}
650
651/// Something that can be driven one step at a time from the outside.
652///
653/// v3 shape: sync trait, generic in `V` / `C` / `D` / `EffectError` /
654/// `Error`. Async is a host concern — a host wrapping the stepper in
655/// `FuturesUnordered<ResolverFuture>` is the canonical async story.
656pub trait Stepper {
657    /// Value the stepper produces on completion.
658    type Value;
659    /// DSL-specific node cursor state stored inside `Frame::Node`.
660    type Cursor;
661    /// DSL-specific state delta / write log stored inside `Env` and
662    /// merged by reducers at join.
663    type Delta;
664    /// DSL-specific effect-side failure surfaced via `resolve`.
665    type EffectError: std::error::Error + Send + Sync + 'static;
666    /// DSL / engine-level error surfaced from `step` and `resolve`.
667    type Error: From<Self::EffectError> + std::error::Error + Send + Sync + 'static;
668
669    /// Advance the interpretation as far as possible without host input.
670    fn step(&mut self) -> Result<StepOutcome<Self::Value>, Self::Error>;
671
672    /// Feed a response back for one pending suspension.
673    ///
674    /// Order-independent; the host may resolve pending IDs in any
675    /// order. Unknown IDs return an error the host may treat as a
676    /// benign no-op (see [`EngineError::UnknownSuspension`]).
677    fn resolve(
678        &mut self,
679        id: SuspensionId,
680        result: Result<Self::Value, Self::EffectError>,
681    ) -> Result<(), Self::Error>;
682
683    /// Snapshot of every suspension currently blocking the tree.
684    /// Excludes ids under `Frame::Cancelled` sub-trees. Order matches
685    /// DFS pre-order over the frame tree.
686    fn pending(&self) -> &[Pending];
687
688    /// Drain the set of suspensions the engine has just cancelled.
689    /// Must be called after every `Ok(Ready)` AND every `Err(_)`
690    /// return from `step()`.
691    fn take_cancellations(&mut self) -> Vec<SuspensionId>;
692
693    /// Root of the live frame tree. Debugger read.
694    fn frame_tree(&self) -> &FrameTree<Self::Value, Self::Cursor, Self::Delta, Self::EffectError>;
695
696    /// True when the root has produced a value.
697    fn is_done(&self) -> bool;
698}
699
700// ---------- Frame tree --------------------------------------------------
701
702/// Which child slot in a `ParFrame` a value corresponds to.
703pub type ChildIndex = usize;
704
705/// Why a sub-tree was cancelled.
706#[derive(Debug, Clone)]
707pub enum CancelReason {
708    /// Cancelled because the enclosing `Par` policy fired
709    /// (`Any` / `FirstK` winner selected).
710    ParPolicyFired,
711    /// Cancelled because a sibling failed (FailFast).
712    SiblingFailed,
713}
714
715/// One node in the live frame tree.
716#[derive(Debug)]
717pub enum Frame<V, C, D, EE> {
718    /// An interior interpretation node currently executing.
719    Node {
720        /// AST node this frame is interpreting.
721        node: NodeId,
722        /// Shared environment snapshot.
723        env: EnvRef<D>,
724        /// DSL-specific cursor (opaque to the engine).
725        cursor: C,
726    },
727    /// A fan-out root. Children live on the enclosing `FrameTree.kids`.
728    Par(ParFrame<V, D, EE>),
729    /// A labelled section wrapper (no fan-out semantics).
730    Scope {
731        /// Section label.
732        label: String,
733        /// Shared environment snapshot.
734        env: EnvRef<D>,
735    },
736    /// A leaf blocked on an external effect.
737    PendingEffect {
738        /// Stable id (also present in `Stepper::pending`).
739        id: SuspensionId,
740    },
741    /// A leaf whose value is ready and waiting to be consumed by its
742    /// parent frame's continuation.
743    Value(V),
744    /// A sub-tree the engine has cancelled. Never selected for `step()`
745    /// progress; kept so the debugger can render it.
746    Cancelled {
747        /// Why the sub-tree was cancelled.
748        reason: CancelReason,
749    },
750}
751
752/// Tree of frames. `kids[i]` under a `Par` root is the `i`-th sibling
753/// child, matched positionally with `ParFrame.slots[i]` and
754/// `ParFrame.deltas[i]`.
755#[derive(Debug)]
756pub struct FrameTree<V, C, D, EE> {
757    /// The frame at this node.
758    pub root: Frame<V, C, D, EE>,
759    /// Child sub-trees.
760    pub kids: Vec<FrameTree<V, C, D, EE>>,
761}
762
763/// Fan-out metadata.
764///
765/// `children` are stored on the enclosing `FrameTree.kids`; `slots`,
766/// `deltas`, and `completion_order` are indexed against that same
767/// positional list.
768#[derive(Debug)]
769pub struct ParFrame<V, D, EE> {
770    /// Policy (shape + fail).
771    pub policy: JoinPolicy,
772    /// `slots[i]` is `Some(v)` once child i completed successfully;
773    /// `None` while still running, pending, or cancelled without a
774    /// value. FailFast: reroutes failure to `Err` before reducer.
775    /// CollectAll: per-child failures live in `failures[i]`; combine
776    /// slot + failure at reducer-invocation time.
777    pub slots: Vec<Option<V>>,
778    /// Per-child effect-side failures (CollectAll only). `Some(e)`
779    /// once the child resolved with `Err(e)`; always `None` under
780    /// FailFast (failures reroute to `Err` before the reducer runs).
781    pub failures: Vec<Option<EE>>,
782    /// Per-child accumulated delta.
783    pub deltas: Vec<Option<D>>,
784    /// Order in which children completed successfully.
785    pub completion_order: Vec<ChildIndex>,
786    /// Registry key for the reducer.
787    pub reducer_id: ReducerId,
788    /// Resolved reducer handle (FailFast or CollectAll, matching
789    /// `policy.fail`).
790    pub reducer: ReducerHandle<V, D, EE>,
791    /// True once the shape has fired.
792    pub joined: bool,
793}
794
795// ---------- Join policy -------------------------------------------------
796
797/// Full policy for a `ParFrame`: success-side `shape` + failure-side
798/// `fail`.
799#[derive(Debug, Clone, Copy)]
800pub struct JoinPolicy {
801    /// Success completion condition.
802    pub shape: JoinShape,
803    /// Failure handling.
804    pub fail: FailPolicy,
805}
806
807/// Success-side completion condition.
808#[derive(Debug, Clone, Copy)]
809pub enum JoinShape {
810    /// Every child must complete successfully.
811    All,
812    /// The first successful child wins; remaining children are cancelled.
813    Any,
814    /// The first `k` successful children win; remaining children are
815    /// cancelled.
816    FirstK(usize),
817}
818
819/// Failure-side policy.
820#[derive(Debug, Clone, Copy)]
821pub enum FailPolicy {
822    /// A single child failure aborts the `Par` immediately.
823    FailFast,
824    /// Failures are collected into slots; shape completion still decides
825    /// based on the count of successes.
826    CollectAll,
827}
828
829// ---------- Reducer trait + registry -----------------------------------
830
831/// Serialisable name for a registered reducer.
832#[derive(Debug, Clone, PartialEq, Eq, Hash)]
833pub struct ReducerId(pub String);
834
835impl fmt::Display for ReducerId {
836    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837        write!(f, "{}", self.0)
838    }
839}
840
841impl From<&str> for ReducerId {
842    fn from(s: &str) -> Self {
843        ReducerId(s.to_string())
844    }
845}
846
847impl From<String> for ReducerId {
848    fn from(s: String) -> Self {
849        ReducerId(s)
850    }
851}
852
853/// FailFast reducer. Sees successful joins only.
854pub trait Reducer<V, D>: Send + Sync {
855    /// Fold slots + deltas + completion order into a joined `(V, D)`.
856    fn reduce(
857        &self,
858        slots: &[Option<V>],
859        deltas: &[Option<D>],
860        winners: &[ChildIndex],
861    ) -> Result<(V, D), EngineError>;
862}
863
864/// CollectAll reducer. Sees the full success/failure slot vector.
865pub trait ReducerCollectAll<V, D, EffectError>: Send + Sync {
866    /// Fold slots (each `Some(Ok)` / `Some(Err)` / `None`) + deltas +
867    /// completion order into a joined `(V, D)`.
868    fn reduce(
869        &self,
870        slots: &[Option<Result<V, EffectError>>],
871        deltas: &[Option<D>],
872        winners: &[ChildIndex],
873    ) -> Result<(V, D), EngineError>;
874}
875
876/// Runtime handle for the resolved reducer of a `ParFrame`.
877///
878/// Which variant is present is dictated by `JoinPolicy.fail`. The
879/// `CollectAll` variant is typed directly in the effect-error `EE`
880/// so the engine can invoke `reduce` on a `&[Option<Result<V, EE>>]`
881/// slot vector at fold time without any downcast.
882pub enum ReducerHandle<V, D, EE> {
883    /// FailFast-typed reducer.
884    FailFast(Arc<dyn Reducer<V, D>>),
885    /// CollectAll-typed reducer, typed in the effect-error `EE`.
886    CollectAll(Arc<dyn ReducerCollectAll<V, D, EE>>),
887}
888
889impl<V, D, EE> fmt::Debug for ReducerHandle<V, D, EE> {
890    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891        match self {
892            ReducerHandle::FailFast(_) => f.write_str("ReducerHandle::FailFast(..)"),
893            ReducerHandle::CollectAll(_) => f.write_str("ReducerHandle::CollectAll(..)"),
894        }
895    }
896}
897
898impl<V, D, EE> Clone for ReducerHandle<V, D, EE> {
899    fn clone(&self) -> Self {
900        match self {
901            ReducerHandle::FailFast(a) => ReducerHandle::FailFast(a.clone()),
902            ReducerHandle::CollectAll(a) => ReducerHandle::CollectAll(a.clone()),
903        }
904    }
905}
906
907/// Runtime lookup table.
908///
909/// Constructed by the host at Stepper build time; a DSL typically ships
910/// a helper `default_registry()` that registers its standard reducers
911/// under the canonical ids (`"reduce_all_ordered"` etc.).
912pub struct ReducerRegistry<V, D, EffectError> {
913    fail_fast: HashMap<ReducerId, Arc<dyn Reducer<V, D>>>,
914    collect_all: HashMap<ReducerId, Arc<dyn ReducerCollectAll<V, D, EffectError>>>,
915}
916
917impl<V, D, EE> Default for ReducerRegistry<V, D, EE> {
918    fn default() -> Self {
919        Self::new()
920    }
921}
922
923impl<V, D, EE> ReducerRegistry<V, D, EE> {
924    /// Creates an empty registry.
925    pub fn new() -> Self {
926        Self {
927            fail_fast: HashMap::new(),
928            collect_all: HashMap::new(),
929        }
930    }
931
932    /// Registers a FailFast-typed reducer under `id`.
933    pub fn register_fail_fast(
934        &mut self,
935        id: impl Into<ReducerId>,
936        reducer: Arc<dyn Reducer<V, D>>,
937    ) {
938        self.fail_fast.insert(id.into(), reducer);
939    }
940
941    /// Registers a CollectAll-typed reducer under `id`.
942    pub fn register_collect_all(
943        &mut self,
944        id: impl Into<ReducerId>,
945        reducer: Arc<dyn ReducerCollectAll<V, D, EE>>,
946    ) {
947        self.collect_all.insert(id.into(), reducer);
948    }
949
950    /// Resolves the reducer for a `ParFrame` at construction time.
951    ///
952    /// The `fail` argument disambiguates when the same id has been
953    /// registered under both traits. Returns
954    /// `EngineError::UnknownReducer` on miss.
955    pub fn resolve(
956        &self,
957        id: &ReducerId,
958        fail: FailPolicy,
959    ) -> Result<ReducerHandle<V, D, EE>, EngineError> {
960        match fail {
961            FailPolicy::FailFast => self
962                .fail_fast
963                .get(id)
964                .cloned()
965                .map(ReducerHandle::FailFast)
966                .ok_or_else(|| EngineError::UnknownReducer { id: id.clone() }),
967            FailPolicy::CollectAll => self
968                .collect_all
969                .get(id)
970                .cloned()
971                .map(ReducerHandle::CollectAll)
972                .ok_or_else(|| EngineError::UnknownReducer { id: id.clone() }),
973        }
974    }
975}
976
977// ---------- Op trait + registry -----------------------------------------
978
979/// Serialisable name for a registered op.
980#[derive(Debug, Clone, PartialEq, Eq, Hash)]
981pub struct OpId(pub String);
982
983impl fmt::Display for OpId {
984    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
985        write!(f, "{}", self.0)
986    }
987}
988
989impl From<&str> for OpId {
990    fn from(s: &str) -> Self {
991        OpId(s.to_string())
992    }
993}
994
995impl From<String> for OpId {
996    fn from(s: String) -> Self {
997        OpId(s)
998    }
999}
1000
1001/// A pure value fold applied by an `Apply` node once every child
1002/// argument has produced a value.
1003///
1004/// Ops never suspend: effects belong in `Call` children, whose values
1005/// arrive here as ordinary `args` entries. Domain failures (division by
1006/// zero, type mismatch on a dynamic value) are reported as
1007/// [`EngineError::EvalFailed`] with the node context supplied by the
1008/// engine at the call site.
1009pub trait Op<V>: Send + Sync {
1010    /// Fold the evaluated child values into the node's value.
1011    ///
1012    /// `args` holds one entry per `Apply` child, in declaration order.
1013    /// Zero-child `Apply` nodes invoke the op with an empty slice.
1014    fn apply(&self, node: NodeId, args: &[V]) -> Result<V, EngineError>;
1015}
1016
1017/// Runtime handle for the resolved op of an `Apply` frame.
1018pub type OpHandle<V> = Arc<dyn Op<V>>;
1019
1020/// Runtime lookup table for [`Op`]s, the `Apply` counterpart of
1021/// [`ReducerRegistry`].
1022///
1023/// Constructed by the host at Stepper build time; a DSL typically ships
1024/// a helper that registers its standard ops under canonical ids
1025/// (`"add"`, `"mul"`, ...). Passed to [`Engine::new_with_ops`]; DSLs
1026/// with no `Apply` nodes can stay on [`Engine::new`], which uses an
1027/// empty registry.
1028///
1029/// [`Engine::new`]: crate::Engine::new
1030/// [`Engine::new_with_ops`]: crate::Engine::new_with_ops
1031pub struct OpRegistry<V> {
1032    ops: HashMap<OpId, OpHandle<V>>,
1033}
1034
1035impl<V> Default for OpRegistry<V> {
1036    fn default() -> Self {
1037        Self::new()
1038    }
1039}
1040
1041impl<V> OpRegistry<V> {
1042    /// Creates an empty registry.
1043    pub fn new() -> Self {
1044        Self {
1045            ops: HashMap::new(),
1046        }
1047    }
1048
1049    /// Registers an op under `id`.
1050    pub fn register(&mut self, id: impl Into<OpId>, op: OpHandle<V>) {
1051        self.ops.insert(id.into(), op);
1052    }
1053
1054    /// Resolves the op for an `Apply` frame at spawn / validation time.
1055    /// Returns [`EngineError::UnknownOp`] on miss.
1056    pub fn resolve(&self, id: &OpId) -> Result<OpHandle<V>, EngineError> {
1057        self.ops
1058            .get(id)
1059            .cloned()
1060            .ok_or_else(|| EngineError::UnknownOp { id: id.clone() })
1061    }
1062}
1063
1064// ---------- Derived execution (DslExec / DslSemantics / DerivedAst) ----
1065
1066/// Mechanical node classification, normally supplied by
1067/// `#[derive(DslExec)]` from `dsl-kit-macros`.
1068///
1069/// This is the derivable half of an [`Ast`]: which engine [`NodeKind`]
1070/// each variant maps to, and the payload of `value`-marked literal
1071/// variants. The semantic half (value type, truthiness, bindings)
1072/// lives in [`DslSemantics`]; [`DerivedAst`] zips the two into an
1073/// engine-ready [`Ast`].
1074pub trait DslExec: Walk {
1075    /// Payload type of `#[dsl_exec(value)]` variants. `()` when the
1076    /// enum has no value variants.
1077    type LitValue: Clone + fmt::Debug;
1078
1079    /// Engine classification of this node.
1080    fn exec_kind(&self) -> NodeKind;
1081
1082    /// Payload of a value variant; `None` for every other variant.
1083    fn exec_literal(&self) -> Option<Self::LitValue>;
1084}
1085
1086/// The semantic half an author writes next to `#[derive(DslExec)]`:
1087/// the runtime value type and the hooks whose meaning the kit cannot
1088/// derive. Every hook mirrors its [`Ast`] counterpart and keeps the
1089/// same default, so a DSL only implements what its node kinds use.
1090pub trait DslSemantics {
1091    /// Runtime value type produced by the DSL.
1092    type Value: Clone + fmt::Debug;
1093    /// Per-child state delta accumulated across a `Par` and extended
1094    /// by `Bind`.
1095    type Delta: Clone + Default + fmt::Debug;
1096    /// Effect-side failure the host reports through `resolve`.
1097    type EffectError: std::error::Error + Clone + Send + Sync + 'static;
1098    /// Per-frame cursor surfaced through the projected frame tree.
1099    type Cursor: Clone + fmt::Debug + Default;
1100
1101    /// See [`Ast::unit_value`].
1102    fn unit_value(&self) -> Self::Value;
1103
1104    /// See [`Ast::truthy`].
1105    fn truthy(&self, _value: &Self::Value) -> Option<bool> {
1106        None
1107    }
1108
1109    /// See [`Ast::continue_loop`].
1110    fn continue_loop(&self, _node: NodeId, _last: &Self::Value, _iteration: usize) -> LoopDecision {
1111        LoopDecision::Break
1112    }
1113
1114    /// See [`Ast::bind_delta`].
1115    fn bind_delta(&self, _name: &str, _value: &Self::Value) -> Option<Self::Delta> {
1116        None
1117    }
1118
1119    /// See [`Ast::lookup`].
1120    fn lookup(&self, _delta: &Self::Delta, _name: &str) -> Option<Self::Value> {
1121        None
1122    }
1123}
1124
1125/// Engine-ready [`Ast`] assembled from a `#[derive(DslExec)]` node
1126/// type plus a [`DslSemantics`] implementation.
1127///
1128/// Construction walks the tree once to build the `NodeId -> node`
1129/// lookup; `node_kind` / `literal` then delegate to the derived
1130/// classification and every semantic hook to `S`.
1131pub struct DerivedAst<'a, N, S> {
1132    root: &'a N,
1133    by_id: HashMap<NodeId, &'a N>,
1134    sem: S,
1135}
1136
1137impl<'a, N: DslExec, S> DerivedAst<'a, N, S> {
1138    /// Builds the lookup for `root` and attaches the semantics.
1139    pub fn new(root: &'a N, sem: S) -> Self {
1140        fn collect<'a, N: Walk>(node: &'a N, map: &mut HashMap<NodeId, &'a N>) {
1141            map.insert(node.node_id(), node);
1142            for child in node.children() {
1143                collect(child, map);
1144            }
1145        }
1146        let mut by_id = HashMap::new();
1147        collect(root, &mut by_id);
1148        Self { root, by_id, sem }
1149    }
1150
1151    fn node(&self, id: NodeId) -> &'a N {
1152        self.by_id.get(&id).copied().expect("unknown NodeId")
1153    }
1154}
1155
1156impl<N, S> Ast for DerivedAst<'_, N, S>
1157where
1158    N: DslExec,
1159    S: DslSemantics,
1160    S::Value: From<N::LitValue>,
1161{
1162    type Value = S::Value;
1163    type Delta = S::Delta;
1164    type EffectError = S::EffectError;
1165    type Cursor = S::Cursor;
1166
1167    fn root(&self) -> NodeId {
1168        self.root.node_id()
1169    }
1170
1171    fn node_kind(&self, id: NodeId) -> NodeKind {
1172        self.node(id).exec_kind()
1173    }
1174
1175    fn unit_value(&self) -> Self::Value {
1176        self.sem.unit_value()
1177    }
1178
1179    fn truthy(&self, value: &Self::Value) -> Option<bool> {
1180        self.sem.truthy(value)
1181    }
1182
1183    fn continue_loop(&self, node: NodeId, last: &Self::Value, iteration: usize) -> LoopDecision {
1184        self.sem.continue_loop(node, last, iteration)
1185    }
1186
1187    fn bind_delta(&self, name: &str, value: &Self::Value) -> Option<Self::Delta> {
1188        self.sem.bind_delta(name, value)
1189    }
1190
1191    fn lookup(&self, delta: &Self::Delta, name: &str) -> Option<Self::Value> {
1192        self.sem.lookup(delta, name)
1193    }
1194
1195    fn literal(&self, node: NodeId) -> Option<Self::Value> {
1196        self.node(node).exec_literal().map(S::Value::from)
1197    }
1198}
1199
1200// ---------- Environment sharing ----------------------------------------
1201
1202/// Shared environment handle.
1203///
1204/// Reads are cheap `Arc` clones. Writes accumulate in a per-child `D`
1205/// (state delta) inside a `Par` and are merged by the reducer at join.
1206#[derive(Debug)]
1207pub struct EnvRef<D>(pub Arc<Env<D>>);
1208
1209impl<D> Clone for EnvRef<D> {
1210    fn clone(&self) -> Self {
1211        EnvRef(self.0.clone())
1212    }
1213}
1214
1215/// The `Env` a `Frame::Node` or `Frame::Scope` holds. Generic over the
1216/// DSL-owned `D` (state delta); the engine does not interpret `D`.
1217#[derive(Debug)]
1218pub struct Env<D> {
1219    /// The DSL's own state delta / bindings snapshot.
1220    pub delta: D,
1221    /// Optional parent for lexical lookup.
1222    pub parent: Option<Arc<Env<D>>>,
1223}
1224
1225// ---------- Marker traits + traversal ----------------------------------
1226
1227/// Marker trait for AST enums recognised by the kit.
1228pub trait DslNode {
1229    /// Returns the stable ID assigned to this node.
1230    fn node_id(&self) -> NodeId;
1231
1232    /// Returns the enum variant name of this node as a static string
1233    /// (e.g. `"Seq"`, `"Par"`, `"Call"`).
1234    ///
1235    /// The name matches the variant's Rust source ident and lines up
1236    /// with `dsl_kit_schema::VariantSchema::name` when the type also
1237    /// derives `DslSchema`. Consumers use this to correlate a runtime
1238    /// node with its type-level schema entry — schema-aware lint
1239    /// rules, editor tooling, and any other component that needs to
1240    /// go from an AST value to "which variant is this" without
1241    /// downcasting.
1242    fn variant_name(&self) -> &'static str;
1243}
1244
1245// ---------- Breakpoints -------------------------------------------------
1246
1247/// Identifier assigned by a [`BreakpointSet`] to each added condition.
1248#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1249pub struct BreakpointId(pub u64);
1250
1251impl fmt::Display for BreakpointId {
1252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1253        write!(f, "bp{}", self.0)
1254    }
1255}
1256
1257/// A boolean predicate over [`NodeContext`] used to describe conditional
1258/// breakpoints.
1259#[derive(Debug, Clone, PartialEq, Eq)]
1260pub enum BreakCondition {
1261    /// Matches when the node ID is exactly `id`.
1262    Node(NodeId),
1263    /// Matches when the current path has the given prefix.
1264    PathPrefix(Path),
1265    /// Matches when the current path equals the given path exactly.
1266    PathExact(Path),
1267    /// Matches when the current call-frame depth is at least `n`.
1268    DepthAtLeast(u32),
1269    /// Matches when the current call-frame depth is at most `n`.
1270    DepthAtMost(u32),
1271    /// Matches when the current call-frame depth equals `n` exactly.
1272    DepthEquals(u32),
1273    /// Matches when the iteration counter equals `n`.
1274    Iteration(u64),
1275    /// Matches when the current call frame equals `frame`.
1276    CallFrame(CallFrameId),
1277    /// Matches when any child matches.
1278    Any(Vec<BreakCondition>),
1279    /// Matches when every child matches.
1280    All(Vec<BreakCondition>),
1281    /// Matches when the inner does not match.
1282    Not(Box<BreakCondition>),
1283    /// Always matches (useful as a debugger's "break on every node" mode).
1284    Always,
1285    /// Never matches (useful as a disabled placeholder).
1286    Never,
1287}
1288
1289impl BreakCondition {
1290    /// Convenience constructor.
1291    pub fn at_node(id: NodeId) -> Self {
1292        Self::Node(id)
1293    }
1294
1295    /// Convenience constructor.
1296    pub fn under_path(path: Path) -> Self {
1297        Self::PathPrefix(path)
1298    }
1299
1300    /// Convenience constructor.
1301    pub fn at_path(path: Path) -> Self {
1302        Self::PathExact(path)
1303    }
1304
1305    /// Convenience constructor.
1306    pub fn at_depth_at_least(n: u32) -> Self {
1307        Self::DepthAtLeast(n)
1308    }
1309
1310    /// Convenience constructor.
1311    pub fn at_depth_at_most(n: u32) -> Self {
1312        Self::DepthAtMost(n)
1313    }
1314
1315    /// Convenience constructor.
1316    pub fn at_depth(n: u32) -> Self {
1317        Self::DepthEquals(n)
1318    }
1319
1320    /// Convenience constructor.
1321    pub fn at_iteration(n: u64) -> Self {
1322        Self::Iteration(n)
1323    }
1324
1325    /// Convenience constructor.
1326    pub fn in_call_frame(frame: CallFrameId) -> Self {
1327        Self::CallFrame(frame)
1328    }
1329
1330    /// Logical AND.
1331    pub fn and(self, other: Self) -> Self {
1332        match (self, other) {
1333            (Self::All(mut xs), Self::All(ys)) => {
1334                xs.extend(ys);
1335                Self::All(xs)
1336            }
1337            (Self::All(mut xs), other) => {
1338                xs.push(other);
1339                Self::All(xs)
1340            }
1341            (this, Self::All(mut ys)) => {
1342                ys.insert(0, this);
1343                Self::All(ys)
1344            }
1345            (this, other) => Self::All(vec![this, other]),
1346        }
1347    }
1348
1349    /// Logical OR.
1350    pub fn or(self, other: Self) -> Self {
1351        match (self, other) {
1352            (Self::Any(mut xs), Self::Any(ys)) => {
1353                xs.extend(ys);
1354                Self::Any(xs)
1355            }
1356            (Self::Any(mut xs), other) => {
1357                xs.push(other);
1358                Self::Any(xs)
1359            }
1360            (this, Self::Any(mut ys)) => {
1361                ys.insert(0, this);
1362                Self::Any(ys)
1363            }
1364            (this, other) => Self::Any(vec![this, other]),
1365        }
1366    }
1367
1368    /// Evaluates the condition against a context.
1369    pub fn matches(&self, ctx: &NodeContext) -> bool {
1370        match self {
1371            Self::Node(id) => ctx.node == *id,
1372            Self::PathPrefix(prefix) => {
1373                ctx.path.0.len() >= prefix.0.len() && ctx.path.0[..prefix.0.len()] == prefix.0[..]
1374            }
1375            Self::PathExact(path) => ctx.path == *path,
1376            Self::DepthAtLeast(n) => ctx.depth >= *n,
1377            Self::DepthAtMost(n) => ctx.depth <= *n,
1378            Self::DepthEquals(n) => ctx.depth == *n,
1379            Self::Iteration(n) => ctx.iteration.map(|i| i.0 == *n).unwrap_or(false),
1380            Self::CallFrame(frame) => ctx.frame == Some(*frame),
1381            Self::Any(children) => children.iter().any(|c| c.matches(ctx)),
1382            Self::All(children) => children.iter().all(|c| c.matches(ctx)),
1383            Self::Not(inner) => !inner.matches(ctx),
1384            Self::Always => true,
1385            Self::Never => false,
1386        }
1387    }
1388}
1389
1390impl std::ops::Not for BreakCondition {
1391    type Output = Self;
1392
1393    /// Logical NOT: `!cond` matches exactly when `cond` does not.
1394    fn not(self) -> Self {
1395        Self::Not(Box::new(self))
1396    }
1397}
1398
1399/// A registry of breakpoint conditions and their assigned IDs.
1400#[derive(Debug, Default)]
1401pub struct BreakpointSet {
1402    next: u64,
1403    entries: Vec<(BreakpointId, BreakCondition)>,
1404}
1405
1406impl BreakpointSet {
1407    /// Creates an empty set.
1408    pub fn new() -> Self {
1409        Self {
1410            next: 1,
1411            entries: Vec::new(),
1412        }
1413    }
1414
1415    /// Adds a condition and returns its assigned id.
1416    pub fn add(&mut self, condition: BreakCondition) -> BreakpointId {
1417        let id = BreakpointId(self.next);
1418        self.next += 1;
1419        self.entries.push((id, condition));
1420        id
1421    }
1422
1423    /// Removes an entry by id. Returns whether an entry was found.
1424    pub fn remove(&mut self, id: BreakpointId) -> bool {
1425        let before = self.entries.len();
1426        self.entries.retain(|(entry_id, _)| *entry_id != id);
1427        self.entries.len() != before
1428    }
1429
1430    /// Returns the ids of all entries whose condition matches `ctx`.
1431    pub fn matches(&self, ctx: &NodeContext) -> Vec<BreakpointId> {
1432        self.entries
1433            .iter()
1434            .filter(|(_, cond)| cond.matches(ctx))
1435            .map(|(id, _)| *id)
1436            .collect()
1437    }
1438
1439    /// Returns whether the set has no entries.
1440    pub fn is_empty(&self) -> bool {
1441        self.entries.is_empty()
1442    }
1443
1444    /// Number of entries currently registered.
1445    pub fn len(&self) -> usize {
1446        self.entries.len()
1447    }
1448
1449    /// Iterates over the registered `(id, condition)` pairs.
1450    pub fn iter(&self) -> impl Iterator<Item = (BreakpointId, &BreakCondition)> {
1451        self.entries.iter().map(|(id, c)| (*id, c))
1452    }
1453}
1454
1455// ---------- Traversal ---------------------------------------------------
1456
1457/// Which side of a node's traversal the visitor is currently on.
1458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1459pub enum Phase {
1460    /// Before descending into the node's children.
1461    Pre,
1462    /// After all children have been visited.
1463    Post,
1464}
1465
1466/// AST traversal contract.
1467pub trait Walk: DslNode + Sized {
1468    /// Direct children of this node, in traversal order.
1469    fn children(&self) -> Vec<&Self>;
1470
1471    /// Depth-first pre / post traversal.
1472    fn walk<F>(&self, visitor: &mut F)
1473    where
1474        F: FnMut(&Self, Phase),
1475    {
1476        visitor(self, Phase::Pre);
1477        for child in self.children() {
1478            child.walk(visitor);
1479        }
1480        visitor(self, Phase::Post);
1481    }
1482
1483    /// Depth-first traversal with early exit.
1484    fn walk_until<F, T>(&self, visitor: &mut F) -> Option<T>
1485    where
1486        F: FnMut(&Self, Phase) -> Option<T>,
1487    {
1488        if let Some(t) = visitor(self, Phase::Pre) {
1489            return Some(t);
1490        }
1491        for child in self.children() {
1492            if let Some(t) = child.walk_until(visitor) {
1493                return Some(t);
1494            }
1495        }
1496        visitor(self, Phase::Post)
1497    }
1498
1499    /// Locates a node by its stable ID.
1500    fn find_by_id(&self, target: NodeId) -> Option<&Self> {
1501        self.walk_until(&mut |node, phase| {
1502            if phase == Phase::Pre && node.node_id() == target {
1503                Some(node as *const Self)
1504            } else {
1505                None
1506            }
1507        })
1508        .map(|ptr| unsafe { &*ptr })
1509    }
1510}
1511
1512/// Mutable counterpart of [`Walk`].
1513pub trait WalkMut: DslNode + Sized {
1514    /// Direct children of this node, mutably, in traversal order.
1515    fn children_mut(&mut self) -> Vec<&mut Self>;
1516
1517    /// Depth-first pre / post traversal with mutable access.
1518    fn walk_mut<F>(&mut self, visitor: &mut F)
1519    where
1520        F: FnMut(&mut Self, Phase),
1521    {
1522        visitor(self, Phase::Pre);
1523        for child in self.children_mut() {
1524            child.walk_mut(visitor);
1525        }
1526        visitor(self, Phase::Post);
1527    }
1528}
1529
1530#[cfg(test)]
1531mod tests {
1532    use super::*;
1533
1534    #[test]
1535    fn path_push_extends_depth() {
1536        let ids = IdGen::new();
1537        let a = ids.node();
1538        let b = ids.node();
1539
1540        let root = Path::root();
1541        assert_eq!(root.depth(), 0);
1542
1543        let one = root.push(a);
1544        assert_eq!(one.depth(), 1);
1545
1546        let two = one.push(b);
1547        assert_eq!(two.depth(), 2);
1548        assert_eq!(two.tip(), Some(b));
1549    }
1550
1551    #[test]
1552    fn id_generator_yields_distinct_ids() {
1553        let ids = IdGen::new();
1554        let a = ids.node();
1555        let b = ids.node();
1556        assert_ne!(a, b);
1557    }
1558
1559    #[test]
1560    fn null_sink_accepts_events() {
1561        let mut sink = NullSink;
1562        let event = Event::VisitPre {
1563            at: NodeContext::at(NodeId(0), Path::root()),
1564        };
1565        sink.emit(&event);
1566    }
1567
1568    fn ctx_at(node: NodeId, path: Path, depth: u32) -> NodeContext {
1569        NodeContext {
1570            node,
1571            path,
1572            frame: None,
1573            depth,
1574            iteration: None,
1575        }
1576    }
1577
1578    #[test]
1579    fn breakpoint_node_matches_exact_id() {
1580        let cond = BreakCondition::at_node(NodeId(7));
1581        assert!(cond.matches(&ctx_at(NodeId(7), Path::root().push(NodeId(7)), 1)));
1582        assert!(!cond.matches(&ctx_at(NodeId(8), Path::root().push(NodeId(8)), 1)));
1583    }
1584
1585    #[test]
1586    fn breakpoint_set_add_matches_remove() {
1587        let mut set = BreakpointSet::new();
1588        let hit = set.add(BreakCondition::at_node(NodeId(4)));
1589        let miss = set.add(BreakCondition::at_node(NodeId(99)));
1590
1591        let ctx = ctx_at(NodeId(4), Path::root().push(NodeId(4)), 1);
1592        assert_eq!(set.matches(&ctx), vec![hit]);
1593
1594        assert!(set.remove(hit));
1595        assert!(set.matches(&ctx).is_empty());
1596        assert_eq!(set.len(), 1);
1597        assert!(set.iter().any(|(id, _)| id == miss));
1598    }
1599
1600    #[test]
1601    fn engine_error_carries_stable_code() {
1602        let err = EngineError::Aborted {
1603            at: NodeContext::at(NodeId(1), Path::root().push(NodeId(1))),
1604            reason: "user requested".into(),
1605        };
1606        use miette::Diagnostic;
1607        assert_eq!(
1608            err.code().map(|c| c.to_string()).as_deref(),
1609            Some("dsl_kit::eval::aborted")
1610        );
1611    }
1612
1613    #[test]
1614    fn engine_error_catalog_covers_every_variant() {
1615        let entries = engine_error_catalog();
1616        let codes: Vec<&str> = entries.iter().map(|e| e.code.as_str()).collect();
1617        assert!(codes.contains(&"dsl_kit::eval::aborted"));
1618        assert!(codes.contains(&"dsl_kit::eval::failed"));
1619        assert!(codes.contains(&"dsl_kit::ast::malformed"));
1620        assert!(codes.contains(&"dsl_kit::stepper::protocol"));
1621        assert!(codes.contains(&"dsl_kit::stepper::unknown_suspension"));
1622        assert!(codes.contains(&"dsl_kit::reducer::unknown"));
1623        for entry in &entries {
1624            assert!(!entry.help.is_empty(), "help empty for {}", entry.code);
1625        }
1626    }
1627
1628    #[test]
1629    fn reducer_id_from_str_and_string() {
1630        let a: ReducerId = "foo".into();
1631        let b: ReducerId = String::from("foo").into();
1632        assert_eq!(a, b);
1633    }
1634
1635    #[test]
1636    fn reducer_registry_resolves_fail_fast_and_collect_all_independently() {
1637        // A trivial FailFast reducer that returns the first non-None
1638        // slot verbatim.
1639        struct FirstNonNone;
1640        impl Reducer<i64, ()> for FirstNonNone {
1641            fn reduce(
1642                &self,
1643                slots: &[Option<i64>],
1644                _deltas: &[Option<()>],
1645                _winners: &[ChildIndex],
1646            ) -> Result<(i64, ()), EngineError> {
1647                let v = slots.iter().find_map(|s| *s).unwrap_or(0);
1648                Ok((v, ()))
1649            }
1650        }
1651
1652        // A trivial CollectAll reducer.
1653        struct CountOk;
1654        impl ReducerCollectAll<i64, (), std::io::Error> for CountOk {
1655            fn reduce(
1656                &self,
1657                slots: &[Option<Result<i64, std::io::Error>>],
1658                _deltas: &[Option<()>],
1659                _winners: &[ChildIndex],
1660            ) -> Result<(i64, ()), EngineError> {
1661                let count = slots.iter().filter(|s| matches!(s, Some(Ok(_)))).count();
1662                Ok((count as i64, ()))
1663            }
1664        }
1665
1666        let mut reg: ReducerRegistry<i64, (), std::io::Error> = ReducerRegistry::new();
1667        reg.register_fail_fast("first", Arc::new(FirstNonNone));
1668        reg.register_collect_all("count_ok", Arc::new(CountOk));
1669
1670        let ff = reg.resolve(&"first".into(), FailPolicy::FailFast).unwrap();
1671        assert!(matches!(ff, ReducerHandle::FailFast(_)));
1672        let ca = reg
1673            .resolve(&"count_ok".into(), FailPolicy::CollectAll)
1674            .unwrap();
1675        assert!(matches!(ca, ReducerHandle::CollectAll(_)));
1676
1677        let miss = reg.resolve(&"nope".into(), FailPolicy::FailFast);
1678        assert!(matches!(miss, Err(EngineError::UnknownReducer { .. })));
1679    }
1680}