Skip to main content

rinne_loop/
engine.rs

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