harness-rs-loop 0.0.61

ReAct agent loop for harness-rs with measured guards: stuck detection, acceptance checks, a tool-result ceiling that spills oversized payloads to disk instead of truncating, per-call tool deadlines, subagent isolation, and session record/replay (JSONL).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Blueprint — deterministic + agent hybrid state machine (Stripe Minions pattern).
//!
//! Each node is either:
//! - **Deterministic** — runs an `async FnMut(&mut World) -> Result<NodeOutput>`
//! - **Agent** — placeholder; in v0.1 we accept an opaque async closure so users
//!   can plug in `AgentLoop` themselves (see `examples/`). A first-class
//!   `Node::Agent { AgentLoop }` is sketched in DESIGN.md §8 and lands once
//!   we resolve the variance/lifetime story for `&mut AgentLoop` in a `Box`.
//!
//! Control flow:
//! - Edges are followed by `NodeOutput.transition`.
//! - Failure of a node can branch to a retry/fallback node when `branch_on_failure`
//!   is set; up to `retry_cap` retries.

use futures::future::BoxFuture;
use harness_core::{HarnessError, World};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

pub type NodeId = String;

/// What a node returns. `transition` decides what edge to follow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeOutput {
    pub transition: Transition,
    #[serde(default)]
    pub data: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Transition {
    /// Follow the named edge.
    Edge(String),
    /// Use the default ("next") edge if any.
    Next,
    /// Mark the run complete; ignore any downstream edges.
    Done,
    /// Abort the blueprint with this reason.
    Abort(String),
}

/// One executable node.
pub enum Node {
    /// Deterministic Rust closure. Receives `&mut World`. Cheap; no tokens.
    Deterministic(BoxedDetermFn),
    /// User-supplied async closure that knows how to run an agent loop.
    /// Receives `&mut World`. This is the v0.1 escape hatch.
    Agent(BoxedAgentFn),
}

type BoxedDetermFn = Box<
    dyn for<'a> Fn(&'a mut World) -> BoxFuture<'a, Result<NodeOutput, HarnessError>> + Send + Sync,
>;

type BoxedAgentFn = Box<
    dyn for<'a> Fn(&'a mut World) -> BoxFuture<'a, Result<NodeOutput, HarnessError>> + Send + Sync,
>;

impl Node {
    /// Wrap a closure that returns a boxed future. The closure body can borrow
    /// `&mut World` for the future's lifetime.
    ///
    /// ```ignore
    /// Node::deterministic(|w| Box::pin(async move {
    ///     let out = w.runner.exec("git", &["status"], None).await?;
    ///     Ok(NodeOutput { transition: Transition::Next, data: ... })
    /// }))
    /// ```
    pub fn deterministic<F>(f: F) -> Self
    where
        F: for<'a> Fn(&'a mut World) -> BoxFuture<'a, Result<NodeOutput, HarnessError>>
            + Send
            + Sync
            + 'static,
    {
        Node::Deterministic(Box::new(f))
    }

    pub fn agent<F>(f: F) -> Self
    where
        F: for<'a> Fn(&'a mut World) -> BoxFuture<'a, Result<NodeOutput, HarnessError>>
            + Send
            + Sync
            + 'static,
    {
        Node::Agent(Box::new(f))
    }
}

/// Convenience: avoid the `Box::pin` boilerplate when the closure doesn't
/// borrow `w`.
#[macro_export]
macro_rules! node_async {
    (|$w:ident| $body:block) => {
        $crate::blueprint::Node::deterministic(|$w| Box::pin(async move $body))
    };
}

/// An edge — either named or default.
#[derive(Debug, Clone)]
struct EdgeDef {
    /// `None` means the default "next" edge.
    name: Option<String>,
    target: NodeId,
}

/// Per-node failure policy.
#[derive(Debug, Clone, Default)]
struct FailurePolicy {
    fallback: Option<NodeId>,
    retry_cap: u32,
}

pub struct Blueprint {
    nodes: HashMap<NodeId, Node>,
    edges: HashMap<NodeId, Vec<EdgeDef>>,
    failure: HashMap<NodeId, FailurePolicy>,
    start: Option<NodeId>,
}

impl Default for Blueprint {
    fn default() -> Self {
        Self::new()
    }
}

impl Blueprint {
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            edges: HashMap::new(),
            failure: HashMap::new(),
            start: None,
        }
    }

    /// Add a node. The first node added becomes the start (overridable via `start()`).
    pub fn add(mut self, id: impl Into<NodeId>, node: Node) -> Self {
        let id = id.into();
        if self.start.is_none() {
            self.start = Some(id.clone());
        }
        self.nodes.insert(id, node);
        self
    }

    pub fn start(mut self, id: impl Into<NodeId>) -> Self {
        self.start = Some(id.into());
        self
    }

    /// Default ("next") edge from `from` → `to`.
    pub fn edge(mut self, from: impl Into<NodeId>, to: impl Into<NodeId>) -> Self {
        self.edges.entry(from.into()).or_default().push(EdgeDef {
            name: None,
            target: to.into(),
        });
        self
    }

    /// Named edge from `from` →(name)→ `to`. Matches `Transition::Edge("name")`.
    pub fn edge_named(
        mut self,
        from: impl Into<NodeId>,
        name: impl Into<String>,
        to: impl Into<NodeId>,
    ) -> Self {
        self.edges.entry(from.into()).or_default().push(EdgeDef {
            name: Some(name.into()),
            target: to.into(),
        });
        self
    }

    /// Fallback node + retry cap when `from` fails.
    pub fn branch_on_failure(
        mut self,
        from: impl Into<NodeId>,
        fallback: impl Into<NodeId>,
        retry_cap: u32,
    ) -> Self {
        self.failure.insert(
            from.into(),
            FailurePolicy {
                fallback: Some(fallback.into()),
                retry_cap,
            },
        );
        self
    }

    /// Execute the blueprint.
    pub async fn run(&self, world: &mut World) -> Result<BlueprintOutcome, HarnessError> {
        let mut current = self
            .start
            .clone()
            .ok_or_else(|| HarnessError::Other("blueprint has no start node".into()))?;
        let mut visited: Vec<NodeId> = Vec::new();
        let mut retries: HashMap<NodeId, u32> = HashMap::new();

        loop {
            tracing::debug!(node = %current, "blueprint enter");
            let node = self.nodes.get(&current).ok_or_else(|| {
                HarnessError::Other(format!("blueprint: node `{current}` not found"))
            })?;
            let result = match node {
                Node::Deterministic(f) => f(world).await,
                Node::Agent(f) => f(world).await,
            };
            visited.push(current.clone());
            let out = match result {
                Ok(o) => o,
                Err(e) => {
                    if let Some(pol) = self.failure.get(&current).cloned()
                        && let Some(fallback) = pol.fallback.clone()
                    {
                        let count = retries.entry(current.clone()).or_insert(0);
                        if *count < pol.retry_cap {
                            *count += 1;
                            tracing::warn!(node = %current, retry = *count, "node failed; rerunning");
                            continue;
                        }
                        tracing::warn!(node = %current, fallback = %fallback, "retries exhausted, branching");
                        current = fallback;
                        continue;
                    }
                    return Err(e);
                }
            };
            match out.transition {
                Transition::Done => {
                    return Ok(BlueprintOutcome {
                        visited,
                        last: out.data,
                    });
                }
                Transition::Abort(reason) => return Err(HarnessError::Policy(reason)),
                Transition::Edge(name) => {
                    let next = self
                        .edges
                        .get(&current)
                        .and_then(|es| es.iter().find(|e| e.name.as_deref() == Some(&name)))
                        .map(|e| e.target.clone())
                        .ok_or_else(|| {
                            HarnessError::Other(format!(
                                "blueprint: node `{current}` has no edge named `{name}`"
                            ))
                        })?;
                    current = next;
                }
                Transition::Next => {
                    let next = self
                        .edges
                        .get(&current)
                        .and_then(|es| es.first())
                        .map(|e| e.target.clone());
                    match next {
                        Some(t) => current = t,
                        None => {
                            return Ok(BlueprintOutcome {
                                visited,
                                last: out.data,
                            });
                        }
                    }
                }
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct BlueprintOutcome {
    pub visited: Vec<NodeId>,
    pub last: serde_json::Value,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn mk_world() -> World {
        harness_context::default_world(".")
    }

    #[tokio::test]
    async fn linear_chain_runs_in_order() {
        let bp = Blueprint::new()
            .add(
                "a",
                Node::deterministic(|_w| {
                    Box::pin(async move {
                        Ok(NodeOutput {
                            transition: Transition::Next,
                            data: json!({"step":"a"}),
                        })
                    })
                }),
            )
            .add(
                "b",
                Node::deterministic(|_w| {
                    Box::pin(async move {
                        Ok(NodeOutput {
                            transition: Transition::Next,
                            data: json!({"step":"b"}),
                        })
                    })
                }),
            )
            .add(
                "c",
                Node::deterministic(|_w| {
                    Box::pin(async move {
                        Ok(NodeOutput {
                            transition: Transition::Done,
                            data: json!({"step":"c"}),
                        })
                    })
                }),
            )
            .edge("a", "b")
            .edge("b", "c");
        let mut w = mk_world();
        let out = bp.run(&mut w).await.unwrap();
        assert_eq!(out.visited, vec!["a", "b", "c"]);
        assert_eq!(out.last["step"], "c");
    }

    #[tokio::test]
    async fn branch_on_failure_recovers() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU32, Ordering};
        let attempts = Arc::new(AtomicU32::new(0));
        let attempts2 = attempts.clone();
        let bp = Blueprint::new()
            .add(
                "flaky",
                Node::deterministic(move |_w| {
                    let attempts = attempts2.clone();
                    Box::pin(async move {
                        let n = attempts.fetch_add(1, Ordering::SeqCst);
                        if n < 1 {
                            Err(HarnessError::Other("transient".into()))
                        } else {
                            Ok(NodeOutput {
                                transition: Transition::Done,
                                data: json!({}),
                            })
                        }
                    })
                }),
            )
            .add(
                "fallback",
                Node::deterministic(|_w| {
                    Box::pin(async move {
                        Ok(NodeOutput {
                            transition: Transition::Done,
                            data: json!({"recovered": true}),
                        })
                    })
                }),
            )
            .branch_on_failure("flaky", "fallback", 2);
        let mut w = mk_world();
        let out = bp.run(&mut w).await.unwrap();
        // First attempt failed, second succeeded — we should have visited "flaky" twice.
        assert_eq!(
            out.visited.iter().filter(|n| n.as_str() == "flaky").count(),
            2
        );
        assert_eq!(attempts.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn named_edges_route_via_transition() {
        let bp = Blueprint::new()
            .add(
                "router",
                Node::deterministic(|_w| {
                    Box::pin(async move {
                        Ok(NodeOutput {
                            transition: Transition::Edge("left".into()),
                            data: json!({}),
                        })
                    })
                }),
            )
            .add(
                "left",
                Node::deterministic(|_w| {
                    Box::pin(async move {
                        Ok(NodeOutput {
                            transition: Transition::Done,
                            data: json!({"branch":"left"}),
                        })
                    })
                }),
            )
            .add(
                "right",
                Node::deterministic(|_w| {
                    Box::pin(async move {
                        Ok(NodeOutput {
                            transition: Transition::Done,
                            data: json!({"branch":"right"}),
                        })
                    })
                }),
            )
            .edge_named("router", "left", "left")
            .edge_named("router", "right", "right");
        let mut w = mk_world();
        let out = bp.run(&mut w).await.unwrap();
        assert_eq!(out.visited, vec!["router", "left"]);
    }
}