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