Skip to main content

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