Skip to main content

rinne_loop/
engine.rs

1//! The loop engine: the run lifecycle with verification (`CONTEXT.md` §12).
2//!
3//! Phase 3 built the serial spine; Phase 5 adds the loop control that makes
4//! Rinne a verifying loop rather than a dispatcher: the evaluator gate (tool /
5//! AI / human), the test ratchet, `on_fail` loop-back with critique artifacts,
6//! the stuck-detector, human parking, and the replanner hook.
7
8use std::collections::{HashMap, HashSet};
9use std::hash::{Hash, Hasher};
10use std::path::Path;
11use std::sync::Arc;
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use async_trait::async_trait;
15use tokio_util::sync::CancellationToken;
16
17use crate::assembler::ContextAssembler;
18use crate::dag::{Checkpoint, EvaluatorKind, Node, OnFail, Plan};
19use crate::evaluator::{self, AiEvaluator, HumanEvaluator, ToolEvaluator};
20use crate::ratchet;
21use crate::registry::WorkerRegistry;
22use crate::worker::{
23    Constraints, EventSink, ExecStatus, ExecuteRequest, McpServerSpec, ToolSpec, Usage,
24    WorkerDescriptor, WorkerEvent, WorkerFamily,
25};
26use crate::Result;
27use rinne_types::{Blackboard, EvalContext, Evaluator, Gate, NodeStatus, Replanner, RinneError};
28
29/// Tunable limits for a run, merged from config and the plan's own budget.
30#[derive(Debug, Clone)]
31pub struct EngineOptions {
32    pub max_iterations_per_node: u32,
33    pub global_budget_minutes: Option<u64>,
34    pub max_total_iterations: Option<u32>,
35    /// Identical-failure loops before escalating to a human (`CONTEXT.md` §11).
36    pub stuck_loop_threshold: u32,
37    /// Apply the test ratchet at evaluator gates by default.
38    pub test_ratchet: bool,
39    /// Per-role model defaults (role name → model), from config.
40    pub role_models: HashMap<String, String>,
41    /// Per-worker model defaults (worker name → model), from config.
42    pub worker_models: HashMap<String, String>,
43    /// Per-worker cascade ladders (worker name → models cheap→strong), used to
44    /// escalate a node's model on evaluator failure (`CONTEXT.md` §7).
45    pub model_ladders: HashMap<String, Vec<String>>,
46    /// Whether the pool is single-family; if so, AI evaluators are same-family
47    /// and the engine narrates that independence is limited.
48    pub single_family_pool: bool,
49    /// Installed skill bodies (name → instruction body), resolved at run start.
50    /// A node's `skills` are looked up here and injected into its prompt
51    /// (`MCP_SKILLS.md` §11).
52    pub skill_bodies: HashMap<String, String>,
53    /// MCP tool specs (id → spec) the host path offers to an API worker whose
54    /// node attaches that tool (`MCP_SKILLS.md` §6). A node's `tools` are looked
55    /// up here to populate its `ExecuteRequest`.
56    pub tool_specs: HashMap<String, ToolSpec>,
57    /// MCP server connection specs (server name → spec) the provision path
58    /// provisions into a harness whose node attaches a tool from that server
59    /// (`MCP_SKILLS.md` §6).
60    pub mcp_servers: HashMap<String, McpServerSpec>,
61}
62
63impl Default for EngineOptions {
64    fn default() -> Self {
65        Self {
66            max_iterations_per_node: 8,
67            global_budget_minutes: Some(120),
68            max_total_iterations: None,
69            stuck_loop_threshold: 3,
70            test_ratchet: true,
71            role_models: HashMap::new(),
72            worker_models: HashMap::new(),
73            model_ladders: HashMap::new(),
74            single_family_pool: false,
75            skill_bodies: HashMap::new(),
76            tool_specs: HashMap::new(),
77            mcp_servers: HashMap::new(),
78        }
79    }
80}
81
82/// Why a run stopped.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum StopReason {
85    Completed,
86    Blocked,
87    BudgetMinutes,
88    BudgetIterations,
89    NoCapableWorker(String),
90    Cancelled,
91    /// A node is parked awaiting the user (checkpoint, human evaluator, or a
92    /// stuck escalation). Resume with [`ResumeInput`] (`CONTEXT.md` §11).
93    NeedsHuman { node: String, question: String },
94}
95
96/// A user's response when resuming a parked run (`CONTEXT.md` §11).
97#[derive(Debug, Clone)]
98pub struct ResumeInput {
99    /// The parked node this addresses; defaults to the sole parked node.
100    pub node: Option<String>,
101    pub decision: HumanDecision,
102}
103
104/// A human's decision at a checkpoint / evaluator (`CONTEXT.md` §11).
105#[derive(Debug, Clone)]
106pub enum HumanDecision {
107    /// Accept the current state and move on.
108    Approve,
109    /// Throw out this approach; replan from scratch.
110    Reject,
111    /// Give the missing guidance; it becomes the critique fed back to the loop.
112    Steer(String),
113}
114
115/// The outcome of a run.
116#[derive(Debug, Clone)]
117pub struct RunReport {
118    pub completed: bool,
119    pub stop_reason: StopReason,
120    pub node_statuses: Vec<(String, NodeStatus)>,
121    pub total_usage: Usage,
122    pub total_iterations: u32,
123}
124
125/// Engine events for the interface / `status` to render.
126#[derive(Debug, Clone)]
127pub enum EngineEvent {
128    NodeStarted { id: String, worker: String },
129    NodeStream { id: String, event: WorkerEvent },
130    NodeFinished { id: String, status: NodeStatus },
131    Narration(String),
132    /// A node parked awaiting the user, with the sharp question to answer.
133    Parked { id: String, question: String },
134}
135
136pub type EngineSink = tokio::sync::mpsc::UnboundedSender<EngineEvent>;
137
138/// In-memory loop bookkeeping for a single `run` call.
139#[derive(Default)]
140struct LoopTracker {
141    /// Pending critique to inject into a node's next assembly (loop-back).
142    critiques: HashMap<String, String>,
143    /// Per-evaluator history of failure signatures, for stuck detection.
144    failures: HashMap<String, Vec<String>>,
145    /// Per-node escalated model: on evaluator failure the loop-back runs the
146    /// generator on the next-stronger model rather than re-running the same one
147    /// (the start-cheap-escalate cascade, `CONTEXT.md` §7).
148    escalated_models: HashMap<String, String>,
149}
150
151/// An absolute ceiling on total node iterations per run, applied even when no
152/// minutes/iteration budget is configured, so the loop can never run unbounded.
153/// Set far above any real run; it is a runaway backstop, not a working budget.
154const HARD_ITERATION_CEILING: u32 = 2000;
155
156/// Maximum times the replanner may amend the DAG in one run. Each replan can
157/// introduce fresh node ids that reset per-node iteration caps, so without this
158/// a perpetually-failing plan could churn indefinitely.
159const MAX_REPLANS: u32 = 10;
160
161/// The loop engine over a blackboard, owned plan, and worker registry.
162pub struct Engine<'a> {
163    blackboard: &'a dyn Blackboard,
164    plan: Plan,
165    registry: &'a WorkerRegistry,
166    options: EngineOptions,
167    replanner: Option<Arc<dyn Replanner>>,
168    /// Replans applied so far this run (capped by [`MAX_REPLANS`]).
169    replan_count: u32,
170}
171
172impl<'a> Engine<'a> {
173    pub fn new(
174        blackboard: &'a dyn Blackboard,
175        plan: Plan,
176        registry: &'a WorkerRegistry,
177        options: EngineOptions,
178    ) -> Self {
179        Self {
180            blackboard,
181            plan,
182            registry,
183            options,
184            replanner: None,
185            replan_count: 0,
186        }
187    }
188
189    /// Attach a replanner (the conductor) so the engine can amend the DAG.
190    pub fn with_replanner(mut self, replanner: Arc<dyn Replanner>) -> Self {
191        self.replanner = Some(replanner);
192        self
193    }
194
195    /// Run (or resume) the plan to completion, a stop condition, or a park.
196    pub async fn run(
197        &mut self,
198        cancel: CancellationToken,
199        sink: Option<EngineSink>,
200        resume: Option<ResumeInput>,
201    ) -> Result<RunReport> {
202        // The engine reaches persistence only through the blackboard seam (it
203        // never names the concrete `State`), so it can live behind the trait.
204        let state = self.blackboard;
205        for node in &self.plan.nodes {
206            state.ensure_node(&node.id)?;
207            // Reconcile persisted status with artifacts on disk: a node marked
208            // Succeeded whose declared named output is gone (partial write, manual
209            // deletion, interrupted run) must not be consumed as empty context —
210            // reset it to re-run rather than silently feed downstream nothing.
211            if matches!(state.status(&node.id), Ok(NodeStatus::Succeeded)) {
212                let missing = node
213                    .outputs
214                    .iter()
215                    .filter(|o| o.as_str() != "diff") // `diff` is a pseudo-output, not a file
216                    .any(|name| !state.artifact_exists(name));
217                if missing {
218                    state.set_status(&node.id, NodeStatus::Pending)?;
219                    self.blackboard.append_progress(&format!(
220                        "node {} was Succeeded but an output artifact is missing — re-running",
221                        node.id
222                    ))?;
223                }
224            }
225        }
226        if state.meta("started_at")?.is_none() {
227            state.set_meta("started_at", &now_secs().to_string())?;
228        }
229        let started_at: u64 = state
230            .meta("started_at")?
231            .and_then(|s| s.parse().ok())
232            .unwrap_or_else(now_secs);
233
234        let mut tracker = LoopTracker::default();
235
236        // Apply any resume input to a parked node before scheduling.
237        if let Some(input) = resume {
238            if let Some(stop) = self.apply_resume(state, &mut tracker, input).await? {
239                return self.finish(state, stop);
240            }
241        }
242
243        let effective_minutes = self.plan.budget.minutes.or(self.options.global_budget_minutes);
244        let effective_max_iters = self
245            .plan
246            .budget
247            .max_total_iterations
248            .or(self.options.max_total_iterations);
249
250        let stop_reason = loop {
251            if cancel.is_cancelled() {
252                break StopReason::Cancelled;
253            }
254            if let Some(mins) = effective_minutes {
255                if now_secs().saturating_sub(started_at) >= mins.saturating_mul(60) {
256                    break StopReason::BudgetMinutes;
257                }
258            }
259            // The configured cap (if any), plus an always-on absolute backstop so
260            // a run with no budget configured still cannot loop forever.
261            let total_iters = state.total_iterations()?;
262            if effective_max_iters.map(|max| total_iters >= max).unwrap_or(false)
263                || total_iters >= HARD_ITERATION_CEILING
264            {
265                break StopReason::BudgetIterations;
266            }
267
268            let ready = self.ready_nodes(state)?;
269            if ready.is_empty() {
270                let all_ok = self
271                    .plan
272                    .nodes
273                    .iter()
274                    .all(|n| matches!(state.status(&n.id), Ok(NodeStatus::Succeeded)));
275                break if all_ok {
276                    StopReason::Completed
277                } else {
278                    StopReason::Blocked
279                };
280            }
281
282            // Parallelize independent read-only evaluators; everything that
283            // writes the workspace stays serial (`CONTEXT.md` §14, §19).
284            let batch: Vec<Node> = ready
285                .iter()
286                .filter(|n| self.is_parallel_evaluator(n))
287                .cloned()
288                .collect();
289            if batch.len() >= 2 {
290                if let Some(stop) = self
291                    .run_parallel_evaluators(&batch, state, &mut tracker, &sink, &cancel)
292                    .await?
293                {
294                    break stop;
295                }
296                continue;
297            }
298
299            // Otherwise, handle one node serially (the first ready).
300            let node = ready.into_iter().next().unwrap();
301
302            // Checkpoint-before gate: pause for approval unless already granted.
303            if node.checkpoint == Some(Checkpoint::Before)
304                && state.meta(&ckpt_key(&node.id))?.is_none()
305            {
306                self.park(state, &sink, &node.id, "checkpoint", &node.id, &format!(
307                    "approve before running {}?",
308                    node.id
309                ))?;
310                break StopReason::NeedsHuman {
311                    node: node.id.clone(),
312                    question: format!("approve before running {}?", node.id),
313                };
314            }
315
316            let is_evaluator =
317                node.evaluator.is_some() || matches!(node.role, crate::worker::Role::Evaluator);
318
319            if is_evaluator {
320                let gate = self.grade(&node, state, &sink, &cancel).await?;
321                if let Some(stop) = self.apply_gate(&node, gate, state, &mut tracker, &sink).await? {
322                    break stop;
323                }
324            } else {
325                // A normal worker node.
326                if let Some(stop) = self.run_worker_node(&node, state, &mut tracker, &sink, &cancel).await? {
327                    break stop;
328                }
329            }
330        };
331
332        self.finish(state, stop_reason)
333    }
334
335    /// Execute a non-evaluator node by dispatching to a worker.
336    async fn run_worker_node(
337        &self,
338        node: &Node,
339        state: &dyn Blackboard,
340        tracker: &mut LoopTracker,
341        sink: &Option<EngineSink>,
342        cancel: &CancellationToken,
343    ) -> Result<Option<StopReason>> {
344        // Tool-aware routing (`MCP_SKILLS.md` §6): a node that attaches tools
345        // prefers a worker that can actually serve them.
346        let needs_tools = !node.tools.is_empty();
347        let Some((worker, tools_servable)) =
348            self.registry
349                .resolve_for(&node.needs, node.prefer.as_deref(), needs_tools)
350        else {
351            // Unsatisfiable node: never silently assign an incapable worker —
352            // park for the human instead (`CONTEXT.md` §7).
353            let question = format!(
354                "no available worker satisfies {:?} for node {} — add a capable worker (e.g. an \
355                 API key) or tell me how to proceed",
356                node.needs, node.id
357            );
358            self.park(state, sink, &node.id, "human", &node.id, &question)?;
359            return Ok(Some(StopReason::NeedsHuman {
360                node: node.id.clone(),
361                question,
362            }));
363        };
364        let worker_name = worker.descriptor().name.clone();
365        let family = worker.descriptor().family;
366
367        // A tool node landed on a worker that can't run its tools (no
368        // tool-capable worker satisfied its needs). Surface it rather than
369        // dropping the tools silently.
370        if needs_tools && !tools_servable {
371            narrate(
372                sink,
373                format!(
374                    "{} attaches tools but {} can't run them — proceeding without tools \
375                     (add an API worker or claude-code to serve them)",
376                    node.id, worker_name
377                ),
378            );
379        }
380
381        narrate(sink, format!(
382            "routed {} ({:?}) to {} [{}]",
383            node.id, node.role, worker_name, family_label(family)
384        ));
385        emit_engine(sink, EngineEvent::NodeStarted {
386            id: node.id.clone(),
387            worker: worker_name.clone(),
388        });
389
390        state.set_status(&node.id, NodeStatus::Running)?;
391        state.set_worker(&node.id, &worker_name)?;
392        let iteration = state.incr_iteration(&node.id)?;
393
394        // Inject any pending critique from a loop-back into this node's context.
395        let critique = tracker.critiques.remove(&node.id);
396        self.blackboard.append_progress(&format!(
397            "node {} → {} (iteration {iteration}){}",
398            node.id,
399            worker_name,
400            if critique.is_some() { " [with critique]" } else { "" }
401        ))?;
402
403        let assembler = ContextAssembler::new(self.blackboard, &self.plan);
404        let mut packet = assembler.build(node, family, critique)?;
405        packet.skill_text = self.skill_text(node);
406        if let Ok(json) = serde_json::to_string_pretty(&packet) {
407            let _ = self.blackboard.write_context(&node.id, &json);
408        }
409
410        // A cascade escalation (from a prior evaluator failure) overrides the
411        // node's assigned model. Validate against the worker that actually runs
412        // the node: a model belongs to one worker, so if the scheduler resolved
413        // a different worker than the conductor intended, drop the stale model
414        // rather than passing e.g. an NVIDIA model id to Claude.
415        let candidate = tracker
416            .escalated_models
417            .get(&node.id)
418            .cloned()
419            .or_else(|| self.resolve_model(node, &worker_name));
420        let model = self.valid_model_for(candidate, worker.descriptor(), &worker_name, sink);
421        if let Some(m) = &model {
422            narrate(sink, format!("{} on {worker_name}:{m}", node.id));
423        }
424        let request = ExecuteRequest {
425            role: node.role,
426            instruction: node.instruction.clone(),
427            context: packet,
428            workspace: self.blackboard.workspace().to_path_buf(),
429            constraints: Constraints {
430                model,
431                ..Default::default()
432            },
433            tools: self.tool_specs_for(node),
434            mcp_servers: self.mcp_servers_for(node),
435        };
436
437        let result = self.dispatch(worker.as_ref(), &node.id, request, sink, cancel).await?;
438        self.blackboard.write_transcript(&node.id, &result.transcript)?;
439        self.persist_outputs(node, &result)?;
440        state.record_usage(&node.id, &worker_name, &result.usage)?;
441
442        let status = match &result.status {
443            ExecStatus::Success => NodeStatus::Succeeded,
444            ExecStatus::Cancelled => NodeStatus::Pending,
445            ExecStatus::Failed(_) | ExecStatus::TimedOut => NodeStatus::Failed,
446        };
447        state.set_status(&node.id, status)?;
448        self.blackboard.append_progress(&format!(
449            "node {} {} ({} tok, {} ms)",
450            node.id, status.label(), result.usage.total_tokens(), result.usage.wall_ms
451        ))?;
452        emit_engine(sink, EngineEvent::NodeFinished { id: node.id.clone(), status });
453
454        if result.status == ExecStatus::Cancelled {
455            return Ok(Some(StopReason::Cancelled));
456        }
457        Ok(None)
458    }
459
460    /// Grade an evaluator node by dispatching to the matching `Evaluator` impl
461    /// through the seam. The engine keeps the cross-cutting bits (status,
462    /// iteration count, the test ratchet); the kind-specific grading lives in
463    /// the evaluator strategies (`MCP_SKILLS.md` §15).
464    async fn grade(
465        &self,
466        node: &Node,
467        state: &dyn Blackboard,
468        sink: &Option<EngineSink>,
469        cancel: &CancellationToken,
470    ) -> Result<Gate> {
471        state.set_status(&node.id, NodeStatus::Running)?;
472        state.incr_iteration(&node.id)?;
473        let kind = node.evaluator.unwrap_or(EvaluatorKind::Tool);
474
475        // The test ratchet runs first: a diff that deletes tests fails the gate
476        // regardless of what the tests say (`CONTEXT.md` §12).
477        if node.test_ratchet || (self.options.test_ratchet && node.evaluator == Some(EvaluatorKind::Tool)) {
478            if let Some(verdict) = self.ratchet_block(node) {
479                self.blackboard
480                    .append_progress(&format!("eval {} BLOCKED by test ratchet", node.id))?;
481                return Ok(Gate::Fail {
482                    critique: verdict,
483                    policy: node.parsed_on_fail().unwrap_or(OnFail::Replan),
484                });
485            }
486        }
487
488        let ctx = GradeCtx { engine: self, sink, cancel };
489        let evaluator: Box<dyn Evaluator> = match kind {
490            EvaluatorKind::Tool => Box::new(ToolEvaluator),
491            EvaluatorKind::Ai => Box::new(AiEvaluator),
492            EvaluatorKind::Human => Box::new(HumanEvaluator),
493        };
494        evaluator.grade(node, &ctx).await
495    }
496
497    /// Apply an evaluator failure: write the critique, check the stuck-detector
498    /// and the iteration budget, then loop back, fix, or replan.
499    async fn on_fail(
500        &mut self,
501        node: &Node,
502        state: &dyn Blackboard,
503        tracker: &mut LoopTracker,
504        sink: &Option<EngineSink>,
505        critique: String,
506        policy: OnFail,
507    ) -> Result<Option<StopReason>> {
508        // Persist the critique artifact for visibility / resume.
509        let critique_name = match &policy {
510            OnFail::LoopBack { critique: Some(p), .. } => p.clone(),
511            _ => format!("eval-{}.md", node.id),
512        };
513        self.blackboard.write_artifact(&critique_name, &critique)?;
514        self.blackboard
515            .append_progress(&format!("eval {} FAIL → {:?}", node.id, policy))?;
516
517        match policy {
518            OnFail::Replan => self.do_replan(state, sink).await,
519            OnFail::Fixer => {
520                // Route the fix to the evaluated generator (first dependency).
521                let target = node.depends_on.first().cloned();
522                self.loop_back(node, state, tracker, sink, target, critique).await
523            }
524            OnFail::LoopBack { node: target, .. } | OnFail::LoopWith { node: target } => {
525                self.loop_back(node, state, tracker, sink, Some(target), critique).await
526            }
527        }
528    }
529
530    /// Loop back to `target`, with stuck-detection and budget guards. Escalates
531    /// to a human (parks) rather than burning budget (`CONTEXT.md` §11).
532    async fn loop_back(
533        &self,
534        node: &Node,
535        state: &dyn Blackboard,
536        tracker: &mut LoopTracker,
537        sink: &Option<EngineSink>,
538        target: Option<String>,
539        critique: String,
540    ) -> Result<Option<StopReason>> {
541        let Some(target) = target else {
542            state.set_status(&node.id, NodeStatus::Failed)?;
543            return Ok(Some(StopReason::Blocked));
544        };
545
546        // Record the failure signature and detect the wall-ramming signature:
547        // the same failure repeating `stuck_loop_threshold` times.
548        let sig = signature(&critique);
549        let history = tracker.failures.entry(node.id.clone()).or_default();
550        history.push(sig.clone());
551        let n = self.options.stuck_loop_threshold.max(1) as usize;
552        let stuck = history.len() >= n && history.iter().rev().take(n).all(|s| s == &sig);
553
554        // Iteration budget for the target generator.
555        let cap = self
556            .plan
557            .node(&target)
558            .and_then(|t| t.budget.iterations)
559            .unwrap_or(self.options.max_iterations_per_node);
560        let over_budget = state.iterations(&target)? >= cap;
561
562        if stuck || over_budget {
563            let why = if stuck {
564                format!("{}↔{} looped {n}× with the same failure", target, node.id)
565            } else {
566                format!("{} hit its iteration budget ({cap})", target)
567            };
568            let question = format!(
569                "stuck: {why}. Give the missing constraint (/steer), accept (/approve), or restart (/reject).",
570            );
571            // Park the evaluator and remember the loop target for resume.
572            self.park(state, sink, &node.id, "stuck", &target, &question)?;
573            return Ok(Some(StopReason::NeedsHuman {
574                node: node.id.clone(),
575                question,
576            }));
577        }
578
579        // Start-cheap-escalate cascade: on failure, climb the target's model
580        // ladder rather than re-running the same model (`CONTEXT.md` §7).
581        self.escalate_model(&target, tracker, sink);
582        // Feed the critique to the target and re-run the affected subtree.
583        tracker.critiques.insert(target.clone(), critique);
584        self.reset_subtree(state, &target)?;
585        narrate(sink, format!("loop-back to {target} with critique"));
586        Ok(None)
587    }
588
589    /// Climb the target node's cascade ladder by one tier (or jump to the top if
590    /// its starting model is unknown). No-op when there's no ladder or it's
591    /// already at the frontier.
592    fn escalate_model(&self, target_id: &str, tracker: &mut LoopTracker, sink: &Option<EngineSink>) {
593        let Some(node) = self.plan.node(target_id) else {
594            return;
595        };
596        let Some(worker) = self.registry.resolve(&node.needs, node.prefer.as_deref()) else {
597            return;
598        };
599        let name = worker.descriptor().name.clone();
600        let Some(ladder) = self.options.model_ladders.get(&name) else {
601            return;
602        };
603        if ladder.len() < 2 {
604            return;
605        }
606        let current = tracker
607            .escalated_models
608            .get(target_id)
609            .cloned()
610            .or_else(|| self.resolve_model(node, &name));
611        let next = match current.as_deref().and_then(|c| ladder.iter().position(|m| m == c)) {
612            Some(idx) if idx + 1 < ladder.len() => ladder[idx + 1].clone(),
613            Some(_) => return,                              // already at the top tier
614            None => ladder.last().cloned().unwrap_or_default(), // unknown start → frontier
615        };
616        if next.is_empty() || Some(&next) == current.as_ref() {
617            return;
618        }
619        narrate(sink, format!("escalating {target_id} → {name}:{next} after evaluator failure"));
620        tracker.escalated_models.insert(target_id.to_string(), next);
621    }
622
623    /// Ask the replanner (the conductor) to amend the DAG (`CONTEXT.md` §12).
624    async fn do_replan(
625        &mut self,
626        state: &dyn Blackboard,
627        sink: &Option<EngineSink>,
628    ) -> Result<Option<StopReason>> {
629        let Some(replanner) = self.replanner.clone() else {
630            narrate(sink, "replan requested but no replanner is attached".into());
631            return Ok(Some(StopReason::Blocked));
632        };
633        if self.replan_count >= MAX_REPLANS {
634            narrate(
635                sink,
636                format!("replan limit reached ({MAX_REPLANS}) — stopping instead of churning"),
637            );
638            return Ok(Some(StopReason::Blocked));
639        }
640        self.replan_count += 1;
641        let digest = self.digest(state)?;
642        narrate(sink, "replanning the DAG".into());
643        let new_plan = replanner
644            .replan(&self.plan.goal, &digest, &self.plan)
645            .await?;
646        new_plan.validate()?;
647        self.blackboard.save_plan(&new_plan)?;
648        self.plan = new_plan;
649        for n in &self.plan.nodes {
650            state.ensure_node(&n.id)?;
651        }
652        self.blackboard.append_progress("DAG amended by replanner")?;
653        Ok(None)
654    }
655
656    /// Apply a resume decision to a parked node before scheduling resumes.
657    async fn apply_resume(
658        &mut self,
659        state: &dyn Blackboard,
660        tracker: &mut LoopTracker,
661        input: ResumeInput,
662    ) -> Result<Option<StopReason>> {
663        // Find the parked node this addresses.
664        let parked = match input.node {
665            Some(id) => Some(id),
666            None => self
667                .plan
668                .nodes
669                .iter()
670                .find(|n| matches!(state.status(&n.id), Ok(NodeStatus::Parked)))
671                .map(|n| n.id.clone()),
672        };
673        let Some(parked) = parked else {
674            return Ok(None);
675        };
676        let kind = state.meta(&park_kind_key(&parked))?.unwrap_or_default();
677        let target = state.meta(&park_target_key(&parked))?.unwrap_or_else(|| parked.clone());
678
679        match input.decision {
680            HumanDecision::Approve => {
681                if kind == "checkpoint" {
682                    // Grant the checkpoint and let the node run.
683                    state.set_meta(&ckpt_key(&parked), "ok")?;
684                    state.set_status(&parked, NodeStatus::Pending)?;
685                } else {
686                    // Accept current state: the parked evaluator passes.
687                    state.set_status(&parked, NodeStatus::Succeeded)?;
688                }
689                self.blackboard
690                    .append_progress(&format!("resume: approved {parked}"))?;
691                Ok(None)
692            }
693            HumanDecision::Reject => {
694                self.blackboard
695                    .append_progress(&format!("resume: rejected {parked} → replan"))?;
696                self.do_replan(state, &None).await
697            }
698            HumanDecision::Steer(text) => {
699                // The user's words become the critique that flows into the loop.
700                self.blackboard.write_artifact("eval-human.md", &text)?;
701                tracker.critiques.insert(target.clone(), text);
702                state.set_status(&parked, NodeStatus::Pending)?;
703                self.reset_subtree(state, &target)?;
704                // Fresh slate for the stuck-detector after human guidance.
705                tracker.failures.remove(&parked);
706                self.blackboard
707                    .append_progress(&format!("resume: steered {parked} → loop-back {target}"))?;
708                Ok(None)
709            }
710        }
711    }
712
713    /// Park a node for the user, recording how to resume it.
714    fn park(
715        &self,
716        state: &dyn Blackboard,
717        sink: &Option<EngineSink>,
718        node_id: &str,
719        kind: &str,
720        target: &str,
721        question: &str,
722    ) -> Result<()> {
723        state.set_status(node_id, NodeStatus::Parked)?;
724        state.set_meta(&park_kind_key(node_id), kind)?;
725        state.set_meta(&park_target_key(node_id), target)?;
726        self.blackboard
727            .append_progress(&format!("⏸ parked {node_id}: {question}"))?;
728        emit_engine(sink, EngineEvent::Parked {
729            id: node_id.to_string(),
730            question: question.to_string(),
731        });
732        Ok(())
733    }
734
735    /// Check the test ratchet against the diff produced by the node(s) this
736    /// evaluator depends on. Returns a critique if the ratchet blocks.
737    fn ratchet_block(&self, node: &Node) -> Option<String> {
738        for dep in &node.depends_on {
739            let diff_artifact = format!("{dep}.diff");
740            if let Ok(diff) = self.blackboard.read_artifact(&diff_artifact) {
741                let verdict = ratchet::check_diff(&diff);
742                if !verdict.ok {
743                    return Some(format!(
744                        "TEST RATCHET: {} (in {dep}'s diff). Do not weaken or delete tests.",
745                        verdict.reason
746                    ));
747                }
748            }
749        }
750        None
751    }
752
753    /// Reset `target` and all its transitive dependents to Pending so the
754    /// affected subtree re-runs after a loop-back.
755    fn reset_subtree(&self, state: &dyn Blackboard, target: &str) -> Result<()> {
756        let mut to_reset: HashSet<String> = HashSet::new();
757        to_reset.insert(target.to_string());
758        // Iteratively pull in anything that depends on something already marked.
759        loop {
760            let mut grew = false;
761            for n in &self.plan.nodes {
762                if to_reset.contains(&n.id) {
763                    continue;
764                }
765                if n.depends_on.iter().any(|d| to_reset.contains(d)) {
766                    to_reset.insert(n.id.clone());
767                    grew = true;
768                }
769            }
770            if !grew {
771                break;
772            }
773        }
774        for id in to_reset {
775            state.set_status(&id, NodeStatus::Pending)?;
776        }
777        Ok(())
778    }
779
780    /// Resolve the model to run for a node, in precedence order: the node's own
781    /// model (conductor's choice), then the per-role config default, then the
782    /// per-worker config default. `None` means the harness default
783    /// (`CONTEXT.md` §7 cost/latency optimization).
784    fn resolve_model(&self, node: &Node, worker_name: &str) -> Option<String> {
785        let role = format!("{:?}", node.role).to_lowercase();
786        node.model
787            .clone()
788            .or_else(|| self.options.role_models.get(&role).cloned())
789            .or_else(|| self.options.worker_models.get(worker_name).cloned())
790    }
791
792    /// The combined instruction text of a node's attached skills (`MCP_SKILLS.md`
793    /// §11), each under a `## Skill: <name>` header. Empty when the node attaches
794    /// none, or none are installed. Unknown skill names are skipped silently —
795    /// the catalog only ever offers installed ones.
796    fn skill_text(&self, node: &Node) -> String {
797        let mut out = String::new();
798        for name in &node.skills {
799            if let Some(body) = self.options.skill_bodies.get(name) {
800                if !out.is_empty() {
801                    out.push_str("\n\n");
802                }
803                out.push_str(&format!("## Skill: {name}\n{body}"));
804            }
805        }
806        out
807    }
808
809    /// Resolve a node's attached `tools` to their full specs from the run's tool
810    /// catalog (`MCP_SKILLS.md` §6). Unknown ids are skipped — the catalog only
811    /// offers tools that were reachable at plan time.
812    fn tool_specs_for(&self, node: &Node) -> Vec<ToolSpec> {
813        node.tools
814            .iter()
815            .filter_map(|id| self.options.tool_specs.get(id).cloned())
816            .collect()
817    }
818
819    /// The distinct MCP servers backing a node's attached `tools`, as connection
820    /// specs for the provision path (`MCP_SKILLS.md` §6). A tool id is
821    /// `server.tool`; each server is provisioned once even if the node attaches
822    /// several of its tools. Unknown servers are skipped.
823    fn mcp_servers_for(&self, node: &Node) -> Vec<McpServerSpec> {
824        let mut seen = std::collections::HashSet::new();
825        let mut out = Vec::new();
826        for id in &node.tools {
827            let server = id.split_once('.').map(|(s, _)| s).unwrap_or(id.as_str());
828            if !seen.insert(server.to_string()) {
829                continue;
830            }
831            if let Some(spec) = self.options.mcp_servers.get(server) {
832                out.push(spec.clone());
833            }
834        }
835        out
836    }
837
838    /// Validate a candidate model against the worker that will run the node.
839    /// A model belongs to a specific worker (Claude's are opus/sonnet/haiku;
840    /// an NVIDIA worker's is `deepseek-ai/…`), so a model the worker doesn't
841    /// advertise is dropped — the worker uses its default — rather than passed
842    /// through and rejected. A worker with no advertised models accepts any.
843    fn valid_model_for(
844        &self,
845        candidate: Option<String>,
846        descriptor: &WorkerDescriptor,
847        worker_name: &str,
848        sink: &Option<EngineSink>,
849    ) -> Option<String> {
850        match candidate {
851            Some(m) if descriptor.models.is_empty() || descriptor.models.iter().any(|wm| *wm == m) => {
852                Some(m)
853            }
854            Some(m) => {
855                narrate(
856                    sink,
857                    format!("model `{m}` isn't available on {worker_name} — using its default model"),
858                );
859                None
860            }
861            None => None,
862        }
863    }
864
865    /// The node a failure on `node` loops back to (its generator).
866    fn loop_target(&self, node: &Node) -> Option<String> {
867        match node.parsed_on_fail() {
868            Some(OnFail::LoopBack { node, .. }) | Some(OnFail::LoopWith { node }) => Some(node),
869            _ => node.depends_on.first().cloned(),
870        }
871    }
872
873    /// A digest of current state for the replanner.
874    fn digest(&self, state: &dyn Blackboard) -> Result<String> {
875        let mut s = String::new();
876        s.push_str("Node statuses:\n");
877        for n in &self.plan.nodes {
878            s.push_str(&format!(
879                "- {} ({:?}): {}\n",
880                n.id,
881                n.role,
882                state.status(&n.id)?.label()
883            ));
884        }
885        if let Ok(progress) = std::fs::read_to_string(self.blackboard.progress_path()) {
886            let tail: Vec<&str> = progress.lines().rev().take(12).collect();
887            s.push_str("\nRecent progress:\n");
888            for line in tail.into_iter().rev() {
889                s.push_str(line);
890                s.push('\n');
891            }
892        }
893        Ok(s)
894    }
895
896    /// All ready nodes, in plan order. Ready = not yet succeeded/failed/parked
897    /// and all dependencies have succeeded. A node left `Running` by an
898    /// interrupted run is re-runnable.
899    fn ready_nodes(&self, state: &dyn Blackboard) -> Result<Vec<Node>> {
900        let mut out = Vec::new();
901        for node in &self.plan.nodes {
902            let status = state.status(&node.id)?;
903            if !matches!(status, NodeStatus::Pending | NodeStatus::Running) {
904                continue;
905            }
906            let deps_ok = node
907                .depends_on
908                .iter()
909                .all(|d| matches!(state.status(d), Ok(NodeStatus::Succeeded)));
910            if deps_ok {
911                out.push(node.clone());
912            }
913        }
914        Ok(out)
915    }
916
917    /// Whether a node is a read-only evaluator safe to run concurrently with
918    /// other ready evaluators (`CONTEXT.md` §19): an AI or tool evaluator that
919    /// doesn't write the workspace, isn't gated by a checkpoint, and isn't a
920    /// human node (which parks).
921    fn is_parallel_evaluator(&self, node: &Node) -> bool {
922        let is_eval =
923            node.evaluator.is_some() || matches!(node.role, crate::worker::Role::Evaluator);
924        is_eval
925            && node.checkpoint != Some(Checkpoint::Before)
926            && node.evaluator != Some(EvaluatorKind::Human)
927            && !node.needs.contains(&crate::worker::Capability::CodeEdit)
928    }
929
930    /// Grade a batch of independent read-only evaluators concurrently, then
931    /// apply their gates sequentially. The grade phase (worker calls, tool
932    /// commands) runs in parallel — the slow part — while result handling, which
933    /// mutates state and the plan, stays serial and deterministic.
934    async fn run_parallel_evaluators(
935        &mut self,
936        batch: &[Node],
937        state: &dyn Blackboard,
938        tracker: &mut LoopTracker,
939        sink: &Option<EngineSink>,
940        cancel: &CancellationToken,
941    ) -> Result<Option<StopReason>> {
942        narrate(sink, format!("running {} evaluators concurrently", batch.len()));
943
944        // Concurrent grade (read-only borrows of &self). Scoped so the borrows
945        // end before the sequential, mutating apply phase.
946        let gates: Vec<Result<Gate>> = {
947            let futures: Vec<_> = batch
948                .iter()
949                .map(|n| self.grade(n, state, sink, cancel))
950                .collect();
951            futures_util::future::join_all(futures).await
952        };
953
954        // Apply every gate that graded successfully so we don't discard work the
955        // other evaluators already did (tokens spent, transcripts written) just
956        // because one sibling errored; surface the first error only after.
957        let mut first_err: Option<RinneError> = None;
958        for (node, gate) in batch.iter().zip(gates) {
959            match gate {
960                Ok(gate) => {
961                    if let Some(stop) = self.apply_gate(node, gate, state, tracker, sink).await? {
962                        return Ok(Some(stop));
963                    }
964                }
965                Err(e) => {
966                    narrate(sink, format!("evaluator {} errored: {e}", node.id));
967                    if first_err.is_none() {
968                        first_err = Some(e);
969                    }
970                }
971            }
972        }
973        if let Some(e) = first_err {
974            return Err(e);
975        }
976        Ok(None)
977    }
978
979    /// Apply an evaluator's gate: pass closes the node, park surfaces a human
980    /// question, fail runs the `on_fail` policy.
981    async fn apply_gate(
982        &mut self,
983        node: &Node,
984        gate: Gate,
985        state: &dyn Blackboard,
986        tracker: &mut LoopTracker,
987        sink: &Option<EngineSink>,
988    ) -> Result<Option<StopReason>> {
989        match gate {
990            Gate::Pass => {
991                state.set_status(&node.id, NodeStatus::Succeeded)?;
992                self.blackboard
993                    .append_progress(&format!("eval {} PASS", node.id))?;
994                emit_engine(sink, EngineEvent::NodeFinished {
995                    id: node.id.clone(),
996                    status: NodeStatus::Succeeded,
997                });
998                Ok(None)
999            }
1000            Gate::Park { question } => {
1001                let target = self.loop_target(node).unwrap_or_else(|| node.id.clone());
1002                self.park(state, sink, &node.id, "human", &target, &question)?;
1003                Ok(Some(StopReason::NeedsHuman {
1004                    node: node.id.clone(),
1005                    question,
1006                }))
1007            }
1008            Gate::Fail { critique, policy } => {
1009                self.on_fail(node, state, tracker, sink, critique, policy).await
1010            }
1011        }
1012    }
1013
1014    async fn dispatch(
1015        &self,
1016        worker: &dyn crate::worker::Worker,
1017        node_id: &str,
1018        request: ExecuteRequest,
1019        sink: &Option<EngineSink>,
1020        cancel: &CancellationToken,
1021    ) -> Result<crate::worker::ExecuteResult> {
1022        let (tx, mut rx): (EventSink, _) = tokio::sync::mpsc::unbounded_channel();
1023        let forward_sink = sink.clone();
1024        let id = node_id.to_string();
1025        let forwarder = tokio::spawn(async move {
1026            while let Some(event) = rx.recv().await {
1027                emit_engine(&forward_sink, EngineEvent::NodeStream { id: id.clone(), event });
1028            }
1029        });
1030        let result = worker.execute(request, tx, cancel.clone()).await;
1031        let _ = forwarder.await;
1032        result
1033    }
1034
1035    fn persist_outputs(&self, node: &Node, result: &crate::worker::ExecuteResult) -> Result<()> {
1036        let mut wrote_named = false;
1037        for name in &node.outputs {
1038            if name == "diff" {
1039                if let Some(diff) = &result.file_diff {
1040                    self.blackboard.write_artifact(&format!("{}.diff", node.id), diff)?;
1041                }
1042            } else {
1043                self.blackboard.write_artifact(name, &result.result)?;
1044                wrote_named = true;
1045            }
1046        }
1047        if !wrote_named {
1048            self.blackboard
1049                .write_artifact(&format!("{}.out.md", node.id), &result.result)?;
1050        }
1051        Ok(())
1052    }
1053
1054    fn finish(&self, state: &dyn Blackboard, stop_reason: StopReason) -> Result<RunReport> {
1055        let node_statuses = self
1056            .plan
1057            .nodes
1058            .iter()
1059            .map(|n| (n.id.clone(), state.status(&n.id).unwrap_or(NodeStatus::Pending)))
1060            .collect();
1061        Ok(RunReport {
1062            completed: stop_reason == StopReason::Completed,
1063            stop_reason,
1064            node_statuses,
1065            total_usage: state.total_usage()?,
1066            total_iterations: state.total_iterations()?,
1067        })
1068    }
1069}
1070
1071/// The engine's [`EvalContext`]: the services the evaluator strategies call,
1072/// implemented over the running engine plus this grade's sink and cancel token.
1073struct GradeCtx<'a, 'e> {
1074    engine: &'a Engine<'e>,
1075    sink: &'a Option<EngineSink>,
1076    cancel: &'a CancellationToken,
1077}
1078
1079#[async_trait(?Send)]
1080impl EvalContext for GradeCtx<'_, '_> {
1081    fn workspace(&self) -> &Path {
1082        self.engine.blackboard.workspace()
1083    }
1084
1085    async fn run_tool(&self, node: &Node, command: &str, must_exit: i32) -> Result<(bool, String)> {
1086        emit_engine(self.sink, EngineEvent::NodeStarted {
1087            id: node.id.clone(),
1088            worker: format!("tool:{command}"),
1089        });
1090        let verdict = evaluator::run_tool(
1091            self.engine.blackboard.workspace(),
1092            command,
1093            must_exit,
1094            Duration::from_secs(300),
1095        )
1096        .await?;
1097        emit_engine(self.sink, EngineEvent::NodeStream {
1098            id: node.id.clone(),
1099            event: WorkerEvent::Message(format!(
1100                "{} → {}",
1101                command,
1102                if verdict.passed { "pass" } else { "fail" }
1103            )),
1104        });
1105        Ok((verdict.passed, verdict.output))
1106    }
1107
1108    async fn run_ai(&self, node: &Node, extra_instruction: &str) -> Result<Option<String>> {
1109        let e = self.engine;
1110        let sink = self.sink;
1111        let Some(worker) = e.registry.resolve(&node.needs, node.prefer.as_deref()) else {
1112            return Ok(None);
1113        };
1114        let worker_name = worker.descriptor().name.clone();
1115        let family = worker.descriptor().family;
1116        e.blackboard.set_worker(&node.id, &worker_name)?;
1117        // Evaluator-independence ladder: a single-family pool can only do
1118        // same-family review, which shares blind spots. Be honest about it
1119        // (`CONTEXT.md` §7, §11).
1120        if e.options.single_family_pool {
1121            narrate(
1122                sink,
1123                "same-family review — independence is limited; a tool check, a human checkpoint, \
1124                 or a cheap second-family key would strengthen verification"
1125                    .to_string(),
1126            );
1127        }
1128        emit_engine(sink, EngineEvent::NodeStarted {
1129            id: node.id.clone(),
1130            worker: worker_name.clone(),
1131        });
1132
1133        let assembler = ContextAssembler::new(e.blackboard, &e.plan);
1134        let mut packet = assembler.build(node, family, None)?;
1135        packet.skill_text = e.skill_text(node);
1136        let candidate = e.resolve_model(node, &worker_name);
1137        let model = e.valid_model_for(candidate, worker.descriptor(), &worker_name, sink);
1138        if let Some(m) = &model {
1139            narrate(sink, format!("{} on {worker_name}:{m}", node.id));
1140        }
1141        let request = ExecuteRequest {
1142            role: node.role,
1143            instruction: format!("{}{}", node.instruction, extra_instruction),
1144            context: packet,
1145            workspace: e.blackboard.workspace().to_path_buf(),
1146            constraints: Constraints {
1147                model,
1148                ..Default::default()
1149            },
1150            // Evaluators grade; they do not call tools.
1151            tools: Vec::new(),
1152            mcp_servers: Vec::new(),
1153        };
1154        let result = e.dispatch(worker.as_ref(), &node.id, request, sink, self.cancel).await?;
1155        e.blackboard.write_transcript(&node.id, &result.transcript)?;
1156        e.blackboard.record_usage(&node.id, &worker_name, &result.usage)?;
1157        Ok(Some(result.result))
1158    }
1159}
1160
1161fn ckpt_key(id: &str) -> String {
1162    format!("ckpt_ok:{id}")
1163}
1164fn park_kind_key(id: &str) -> String {
1165    format!("park_kind:{id}")
1166}
1167fn park_target_key(id: &str) -> String {
1168    format!("park_target:{id}")
1169}
1170
1171fn signature(s: &str) -> String {
1172    let mut h = std::collections::hash_map::DefaultHasher::new();
1173    s.trim().hash(&mut h);
1174    format!("{:016x}", h.finish())
1175}
1176
1177fn family_label(f: WorkerFamily) -> &'static str {
1178    match f {
1179        WorkerFamily::Harness => "harness",
1180        WorkerFamily::Api => "api",
1181    }
1182}
1183
1184fn narrate(sink: &Option<EngineSink>, line: String) {
1185    emit_engine(sink, EngineEvent::Narration(line));
1186}
1187
1188fn emit_engine(sink: &Option<EngineSink>, event: EngineEvent) {
1189    if let Some(s) = sink {
1190        let _ = s.send(event);
1191    }
1192}
1193
1194fn now_secs() -> u64 {
1195    SystemTime::now()
1196        .duration_since(UNIX_EPOCH)
1197        .map(|d| d.as_secs())
1198        .unwrap_or(0)
1199}