Skip to main content

rinne_workers/adapters/
common.rs

1//! Shared machinery for harness adapters (`CONTEXT.md` §8).
2//!
3//! A harness worker is an autonomous agent: it gets a chunky self-contained
4//! prompt and reads/edits the repo itself, so context is passed as a prompt plus
5//! *pinned file paths*, never inlined contents (`CONTEXT.md` §8 behavioral
6//! split, §12 context assembler).
7
8use std::path::{Path, PathBuf};
9use std::time::Duration;
10
11use async_trait::async_trait;
12use tokio_util::sync::CancellationToken;
13
14use rinne_core::worker::{
15    emit, EventSink, ExecStatus, ExecuteRequest, ExecuteResult, McpServerSpec, Role, Usage, Worker,
16    WorkerDescriptor, WorkerEvent,
17};
18use rinne_core::Result;
19
20use crate::transport::subprocess::{self, LineMapper, SubprocessOutput, SubprocessSpec};
21
22/// How a harness invocation is augmented to use a set of MCP servers — the
23/// provision path (`MCP_SKILLS.md` §6). A provisioner writes whatever config the
24/// CLI needs and returns the extra argv, the subprocess environment (carrying
25/// secret tokens, kept out of the file via `${VAR}` expansion), and a file to
26/// clean up afterward.
27pub struct Provision {
28    pub args: Vec<String>,
29    pub env: Vec<(String, String)>,
30    pub cleanup: Option<PathBuf>,
31}
32
33/// Builds the MCP provisioning for a harness given the node's servers and a
34/// scratch directory to write any config file into.
35pub type McpProvisioner = fn(servers: &[McpServerSpec], scratch: &Path) -> Result<Provision>;
36
37/// What an adapter extracts from a harness CLI's raw output. Parsers should be
38/// defensive: on any doubt, fall back to the raw stdout as the result text so a
39/// schema change in a beta CLI degrades gracefully (`CONTEXT.md` §21).
40pub struct ParsedHarness {
41    pub result: String,
42    pub session_id: Option<String>,
43    pub usage: Usage,
44    /// The CLI signalled an error in its structured output, even if it exited 0.
45    pub is_error: bool,
46}
47
48impl ParsedHarness {
49    /// The trivial parse: use raw stdout, no session, no usage.
50    pub fn raw(stdout: &str) -> Self {
51        Self {
52            result: stdout.trim().to_string(),
53            session_id: None,
54            usage: Usage::default(),
55            is_error: false,
56        }
57    }
58}
59
60/// Build the argv for a harness invocation given the composed prompt and an
61/// optional model selection.
62pub type ArgsBuilder = fn(prompt: &str, model: Option<&str>) -> Vec<String>;
63
64/// Serializes tests that mutate process-global harness env vars. Shared across
65/// adapter modules — `cargo test` runs them on one thread pool, so a per-module
66/// lock would not actually exclude them from each other.
67#[cfg(test)]
68pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
69
70/// Whether harness sessions should pass their non-interactive approval flags.
71///
72/// Set from `[harness_stage].approvals` via `RINNE_HARNESS_APPROVALS`
73/// (`crates/rinne-cli/src/runner.rs::apply_harness_stage_env`). Defaults to
74/// auto, matching the config default: a Stage session nobody is watching
75/// blocks forever on a permission prompt otherwise.
76///
77/// Unset means auto, but any recognised *negative* spelling means human — this
78/// is a permission switch, so `RINNE_HARNESS_APPROVALS=off` must not fail open
79/// into auto-approving every tool call. The vocabulary matches the sibling
80/// `RINNE_HARNESS_INTERACTIVE_TUI` parse below.
81pub fn approvals_are_auto() -> bool {
82    match std::env::var("RINNE_HARNESS_APPROVALS") {
83        Ok(v) => !matches!(
84            v.trim().to_ascii_lowercase().as_str(),
85            "human"
86                | "manual"
87                | "ask"
88                | "prompt"
89                | "never"
90                | "none"
91                | "no"
92                | "off"
93                | "false"
94                | "0"
95                | ""
96        ),
97        Err(_) => true,
98    }
99}
100
101/// Default interactive argv: model flag (if any) + prompt as a positional arg.
102/// Used when an adapter has no custom `interactive_args` (opens product TUI).
103pub fn default_interactive_args(prompt: &str, model: Option<&str>) -> Vec<String> {
104    let mut args = Vec::new();
105    if let Some(m) = model {
106        args.push("--model".into());
107        args.push(m.into());
108    }
109    args.push(prompt.into());
110    args
111}
112
113/// Write a large prompt under the workspace blackboard so we can pass
114/// `--prompt-file` instead of blowing ARG_MAX / shell quoting.
115fn prompt_file_for(workspace: &Path, prompt: &str) -> std::io::Result<PathBuf> {
116    let dir = workspace
117        .join(rinne_core::BLACKBOARD_DIR)
118        .join("stage-prompts");
119    std::fs::create_dir_all(&dir)?;
120    let path = dir.join(format!(
121        "prompt-{}.txt",
122        std::time::SystemTime::now()
123            .duration_since(std::time::UNIX_EPOCH)
124            .map(|d| d.as_nanos())
125            .unwrap_or(0)
126    ));
127    std::fs::write(&path, prompt)?;
128    Ok(path)
129}
130
131/// Grok single-turn via `--prompt-file` (avoids embedding multi-KB plans in argv).
132fn grok_prompt_file_args(path: &Path, model: Option<&str>, lean: bool) -> Vec<String> {
133    let mut args = vec![
134        "--prompt-file".into(),
135        path.display().to_string(),
136        "--output-format".into(),
137        if lean {
138            "plain".into()
139        } else {
140            // Visible Stage plain is human-readable in Terminal; streaming-json
141            // is for pure headless parse paths.
142            "plain".into()
143        },
144        "--no-plan".into(),
145        "--always-approve".into(),
146    ];
147    if let Some(m) = model {
148        args.push("-m".into());
149        args.push(m.into());
150    }
151    args
152}
153
154/// Stage interactive bundle: full task on disk + result path + short kickoff
155/// so the product TUI opens cleanly (no multi-KB argv) and Rinne can still
156/// recover the deliverable without tee'ing the TTY.
157fn stage_task_bundle(
158    workspace: &Path,
159    full_prompt: &str,
160    is_planner: bool,
161) -> std::io::Result<(String, PathBuf)> {
162    let dir = workspace
163        .join(rinne_core::BLACKBOARD_DIR)
164        .join("stage-prompts");
165    std::fs::create_dir_all(&dir)?;
166    let stamp = std::time::SystemTime::now()
167        .duration_since(std::time::UNIX_EPOCH)
168        .map(|d| d.as_nanos())
169        .unwrap_or(0);
170    let task_path = dir.join(format!("task-{stamp}.md"));
171    let result_path = dir.join(format!("result-{stamp}.txt"));
172    // Ensure result does not exist yet (poll for create + stable size).
173    let _ = std::fs::remove_file(&result_path);
174    std::fs::write(&task_path, full_prompt)?;
175
176    let deliverable = if is_planner {
177        "the final planning deliverable: a single JSON object (the DAG plan) with no markdown fence unless required"
178    } else {
179        "your complete final answer / report for this task"
180    };
181
182    // Keep kickoff short — long multi-line kicks fight TUI layout on first paint.
183    let kickoff = format!(
184        "Rinne Stage: complete the task in {task}. \
185         Use tools freely. When done, write {deliverable} to {result} (UTF-8, overwrite OK), then exit. \
186         No clarifying questions — work autonomously.",
187        task = task_path.display(),
188        result = result_path.display(),
189        deliverable = deliverable,
190    );
191
192    Ok((kickoff, result_path))
193}
194
195/// Defensive parser for harnesses that emit a single JSON result object: probe
196/// common result fields, falling back to raw stdout on any surprise
197/// (`CONTEXT.md` §21). Suitable for not-yet-pinned beta CLIs.
198pub fn parse_generic_json(out: &SubprocessOutput) -> ParsedHarness {
199    let pick = |v: &serde_json::Value| {
200        v.get("result")
201            .or_else(|| v.get("text"))
202            .or_else(|| v.get("message"))
203            .or_else(|| v.get("content"))
204            .or_else(|| v.get("response"))
205            .and_then(|x| x.as_str())
206            .map(String::from)
207    };
208    for line in out.stdout.lines().rev() {
209        let line = line.trim();
210        if !line.starts_with('{') {
211            continue;
212        }
213        if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
214            if let Some(result) = pick(&v) {
215                let session_id = v
216                    .get("session_id")
217                    .or_else(|| v.get("sessionId"))
218                    .and_then(|x| x.as_str())
219                    .map(String::from);
220                let is_error = v.get("is_error").and_then(|b| b.as_bool()).unwrap_or(false);
221                return ParsedHarness {
222                    result,
223                    session_id,
224                    usage: Usage::default(),
225                    is_error,
226                };
227            }
228        }
229    }
230    ParsedHarness::raw(&out.stdout)
231}
232
233/// The trivial parser: the captured stdout is the result (for CLIs that print
234/// plain text, e.g. Aider).
235pub fn parse_raw(out: &SubprocessOutput) -> ParsedHarness {
236    ParsedHarness::raw(&out.stdout)
237}
238/// Parse a harness CLI's captured output into normalized fields.
239pub type OutputParser = fn(out: &SubprocessOutput) -> ParsedHarness;
240
241/// A generic harness worker driven over the `subprocess-json` transport. Each
242/// concrete CLI supplies its program name, argv builder, output parser, and an
243/// optional line mapper for richer streaming.
244pub struct HarnessAdapter {
245    pub descriptor: WorkerDescriptor,
246    pub program: String,
247    pub build_args: ArgsBuilder,
248    /// Lean argv used when the harness runs as the **planner** (`Role::Planner`):
249    /// a plain-text completion, not the agentic/streaming work invocation. When
250    /// set, planning reads the full stdout as the answer (more robust across CLI
251    /// versions than parsing a streaming format). `None` → planning reuses
252    /// `build_args` and the normal parser unchanged.
253    pub plan_args: Option<ArgsBuilder>,
254    /// Args for a **real interactive harness TUI** in an external Terminal window.
255    /// Must NOT use headless flags (`-p`, `--output-format json`, `exec --json`, …)
256    /// so the full product UI is visible. `None` → default: `[prompt]` (+ model if any).
257    pub interactive_args: Option<ArgsBuilder>,
258    pub parse: OutputParser,
259    pub line_mapper: LineMapper,
260    /// Whether the prompt is piped via stdin (vs. passed as an argument).
261    pub prompt_via_stdin: bool,
262    pub default_timeout: Duration,
263    /// How this harness is told to use a node's MCP servers (`MCP_SKILLS.md` §6).
264    /// `None` means the harness has no MCP provisioning wired: a node's tools are
265    /// simply unavailable to it (the node still runs), so the conductor should
266    /// prefer an API worker for tool-heavy nodes on such a harness.
267    pub provisioner: Option<McpProvisioner>,
268}
269
270impl HarnessAdapter {
271    /// Replace the static model ladder with a live (or config-merged) list.
272    pub fn with_models(mut self, models: Vec<String>) -> Self {
273        self.descriptor.models = models;
274        self
275    }
276
277    /// Ensure `model` is on the ladder (appended as frontier if missing). Used
278    /// so a user pin / `[models].by_worker` entry is never dropped as "unknown".
279    pub fn ensure_model(mut self, model: &str) -> Self {
280        let model = model.trim();
281        if model.is_empty() {
282            return self;
283        }
284        if !self.descriptor.models.iter().any(|m| m == model) {
285            self.descriptor.models.push(model.to_string());
286        }
287        self
288    }
289}
290
291#[async_trait]
292impl Worker for HarnessAdapter {
293    fn descriptor(&self) -> &WorkerDescriptor {
294        &self.descriptor
295    }
296
297    /// A harness serves MCP tools when it has a provisioner wired (the provision
298    /// path, `MCP_SKILLS.md` §6).
299    fn serves_mcp_tools(&self) -> bool {
300        self.provisioner.is_some()
301    }
302
303    async fn execute(
304        &self,
305        request: ExecuteRequest,
306        events: EventSink,
307        cancel: CancellationToken,
308    ) -> Result<ExecuteResult> {
309        let prompt = compose_prompt(&request);
310        let timeout = request
311            .constraints
312            .timeout_secs
313            .map(Duration::from_secs)
314            .unwrap_or(self.default_timeout);
315
316        let model = request.constraints.model.as_deref();
317        let has_lean = self.plan_args.is_some();
318        // The lean plain-text invocation: used for the planner role, and as an
319        // automatic fallback when the rich/streaming invocation fails with no
320        // output (e.g. a CLI version that rejects the streaming flags). Planning
321        // starts lean so a work flag can't make the planner exit non-zero.
322        let mut lean = matches!(request.role, Role::Planner) && has_lean;
323        let is_planner = matches!(request.role, Role::Planner);
324
325        // Provision the node's MCP servers into this harness once, up front
326        // (`MCP_SKILLS.md` §6). A provisioner failure is non-fatal: narrate it and
327        // run without the tools rather than failing the node.
328        let provision = self.provision(&request, &events);
329
330        // Retry transient failures (spawn errors, timeouts) once before giving
331        // up — beta CLIs are flaky (`CONTEXT.md` §21). A cancelled run is not
332        // retried. Visible sessions are NOT retried on timeout (that just opens
333        // a second broken Terminal window).
334        const MAX_ATTEMPTS: u32 = 2;
335        let mut attempt = 0;
336        let out = loop {
337            attempt += 1;
338            // Visible Stage = real Terminal.app with the **product harness UI**
339            // (Grok Build, Claude Code, …). Capture goes through a result file
340            // so we never tee/script the TTY (that caused mouse-protocol garbage).
341            // Opt out of the TUI with RINNE_HARNESS_INTERACTIVE_TUI=0 (single-turn
342            // plain text in Terminal instead).
343            let mut visible = request.constraints.visible_stage;
344            let interactive_env = std::env::var("RINNE_HARNESS_INTERACTIVE_TUI")
345                .map(|v| v.to_ascii_lowercase())
346                .unwrap_or_default();
347            let force_plain = matches!(interactive_env.as_str(), "0" | "false" | "no" | "off");
348            let want_interactive_tui = visible && !force_plain && self.interactive_args.is_some();
349
350            let builder = if want_interactive_tui {
351                self.interactive_args.unwrap_or(default_interactive_args)
352            } else if lean {
353                self.plan_args.unwrap()
354            } else {
355                self.build_args
356            };
357            let mapper = if want_interactive_tui {
358                // TUI has no useful line stream; Stage events come from SessionOpened.
359                subprocess::raw_lines
360            } else if lean || visible {
361                subprocess::raw_lines
362            } else {
363                self.line_mapper
364            };
365
366            // Interactive Stage: short kickoff prompt + full task on disk +
367            // result file for the deliverable (plan JSON, report, etc.).
368            let mut result_file: Option<PathBuf> = None;
369            let (mut args, stdin) = if want_interactive_tui {
370                match stage_task_bundle(&request.workspace, &prompt, is_planner) {
371                    Ok((kickoff, result_path)) => {
372                        result_file = Some(result_path);
373                        (builder(&kickoff, model), None)
374                    }
375                    Err(e) => {
376                        emit(
377                            &events,
378                            WorkerEvent::Message(format!(
379                                "could not write Stage task files ({e}) — falling back to plain single-turn"
380                            )),
381                        );
382                        // Fall through to plain builders below.
383                        if lean {
384                            if self.program == "grok" && prompt.len() > 1500 {
385                                match prompt_file_for(&request.workspace, &prompt) {
386                                    Ok(path) => (grok_prompt_file_args(&path, model, true), None),
387                                    Err(_) => (builder(&prompt, model), None),
388                                }
389                            } else {
390                                (self.plan_args.unwrap()(&prompt, model), None)
391                            }
392                        } else if self.prompt_via_stdin {
393                            ((self.build_args)("", model), Some(prompt.clone()))
394                        } else {
395                            ((self.build_args)(&prompt, model), None)
396                        }
397                    }
398                }
399            } else if self.program == "grok" && prompt.len() > 1500 {
400                let pf = prompt_file_for(&request.workspace, &prompt);
401                match pf {
402                    Ok(path) => (grok_prompt_file_args(&path, model, lean), None),
403                    Err(_) if self.prompt_via_stdin => (builder("", model), Some(prompt.clone())),
404                    Err(_) => (builder(&prompt, model), None),
405                }
406            } else if self.prompt_via_stdin {
407                (builder("", model), Some(prompt.clone()))
408            } else {
409                (builder(&prompt, model), None)
410            };
411            // If interactive setup failed we may have cleared want visually but
412            // still set result_file only on success — OK.
413            let interactive_active = want_interactive_tui && result_file.is_some();
414
415            // Append the MCP flags on the rich work invocation (not the lean
416            // planner path, which neither needs tools nor accepts the flags).
417            // Skip for interactive visible sessions — MCP provision flags are
418            // often headless-oriented; interactive harnesses use their own MCP.
419            if !lean && !visible {
420                args.extend(provision.args.iter().cloned());
421            }
422            let spec = SubprocessSpec {
423                program: self.program.clone(),
424                args,
425                workspace: request.workspace.clone(),
426                stdin,
427                timeout: Some(timeout),
428                env: provision.env.clone(),
429                result_file: result_file.clone(),
430            };
431            // Cap concurrent Terminal windows; overflow → headless.
432            let visible_slot = if visible {
433                match crate::session_gate::try_acquire_visible() {
434                    Some(slot) => Some(slot),
435                    None => {
436                        emit(
437                            &events,
438                            WorkerEvent::Message(format!(
439                                "Harness Stage: max concurrent terminal windows reached — \
440                                 running {} headless",
441                                self.descriptor.name
442                            )),
443                        );
444                        visible = false;
445                        None
446                    }
447                }
448            } else {
449                None
450            };
451            let role_tag = match request.role {
452                Role::Planner => "planner",
453                Role::Generator => "generator",
454                Role::Evaluator => "evaluator",
455                _ => "worker",
456            };
457            if attempt == 1 {
458                let model = model.map(|m| m.to_string());
459                emit(
460                    &events,
461                    WorkerEvent::SessionOpened {
462                        worker: self.descriptor.name.clone(),
463                        model,
464                        backend: if visible {
465                            if interactive_active {
466                                format!("external-terminal/interactive/{role_tag}")
467                            } else {
468                                format!("external-terminal/single-turn/{role_tag}")
469                            }
470                        } else {
471                            format!("headless/{role_tag}")
472                        },
473                    },
474                );
475                if visible {
476                    emit(
477                        &events,
478                        WorkerEvent::Message(format!(
479                            "▶ {} · {} · {}",
480                            role_tag,
481                            self.descriptor.name,
482                            if interactive_active {
483                                "product UI"
484                            } else {
485                                "single-turn"
486                            }
487                        )),
488                    );
489                }
490            }
491            let run_result = if visible {
492                use crate::transport::external_terminal::{self, TerminalMode};
493                let mode = if interactive_active {
494                    TerminalMode::Interactive
495                } else {
496                    TerminalMode::Capture
497                };
498                // Real Terminal window. Prefer system Terminal; on failure try
499                // embedded PTY, then in-process headless as last resort.
500                match external_terminal::run_with_mode(spec.clone(), &events, &cancel, mapper, mode)
501                    .await
502                {
503                    Ok(out) => Ok(out),
504                    Err(e) => {
505                        emit(
506                            &events,
507                            WorkerEvent::Message(format!(
508                                "could not open system Terminal ({e}) — trying embedded PTY"
509                            )),
510                        );
511                        match crate::transport::pty::run(spec.clone(), &events, &cancel, mapper)
512                            .await
513                        {
514                            Ok(out) => Ok(out),
515                            Err(e2) => {
516                                emit(
517                                    &events,
518                                    WorkerEvent::Message(format!(
519                                        "PTY session failed ({e2}) — headless fallback"
520                                    )),
521                                );
522                                let hb = if lean {
523                                    self.plan_args.unwrap_or(self.build_args)
524                                } else {
525                                    self.build_args
526                                };
527                                let (mut hargs, hstdin) = if self.prompt_via_stdin {
528                                    (hb("", model), Some(prompt.clone()))
529                                } else {
530                                    (hb(&prompt, model), None)
531                                };
532                                if !lean {
533                                    hargs.extend(provision.args.iter().cloned());
534                                }
535                                let hspec = SubprocessSpec {
536                                    program: self.program.clone(),
537                                    args: hargs,
538                                    workspace: request.workspace.clone(),
539                                    stdin: hstdin,
540                                    timeout: Some(timeout),
541                                    env: provision.env.clone(),
542                                    result_file: None,
543                                };
544                                subprocess::run(hspec, &events, &cancel, mapper).await
545                            }
546                        }
547                    }
548                }
549            } else {
550                subprocess::run(spec, &events, &cancel, mapper).await
551            };
552            drop(visible_slot);
553            match run_result {
554                Ok(out) => {
555                    let timed_out = matches!(out.status, ExecStatus::TimedOut);
556                    // Never re-open another Terminal window on timeout — that is
557                    // what produced the double grok/claude Stage spam.
558                    if timed_out && !visible && attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
559                        emit(
560                            &events,
561                            WorkerEvent::Message(format!(
562                                "{} timed out — retrying ({attempt}/{MAX_ATTEMPTS})",
563                                self.program
564                            )),
565                        );
566                        continue;
567                    }
568                    // Rich invocation failed with nothing usable on stdout, and a
569                    // lean plain invocation is available → fall back to it once.
570                    let empty_fail =
571                        !matches!(out.status, ExecStatus::Success) && out.stdout.trim().is_empty();
572                    if empty_fail && !lean && has_lean && !cancel.is_cancelled() {
573                        lean = true;
574                        emit(
575                            &events,
576                            WorkerEvent::Message(format!(
577                                "{} failed in streaming mode — retrying in plain mode",
578                                self.program
579                            )),
580                        );
581                        continue;
582                    }
583                    break out;
584                }
585                Err(e) => {
586                    if attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
587                        emit(
588                            &events,
589                            WorkerEvent::Message(format!(
590                                "{} failed to start ({e}) — retrying ({attempt}/{MAX_ATTEMPTS})",
591                                self.program
592                            )),
593                        );
594                        tokio::time::sleep(Duration::from_millis(500)).await;
595                        continue;
596                    }
597                    return Err(e);
598                }
599            }
600        };
601        // Best-effort cleanup of the provisioned config file (it holds no secret,
602        // but leaving scratch around is untidy).
603        if let Some(path) = &provision.cleanup {
604            let _ = std::fs::remove_file(path);
605        }
606        // Lean planner + interactive Stage deliverables are plain text / JSON
607        // written to a result file (not NDJSON streams). Take stdout as-is.
608        let parsed = if lean || request.constraints.visible_stage {
609            ParsedHarness::raw(&out.stdout)
610        } else {
611            (self.parse)(&out)
612        };
613
614        // Reconcile the transport-level status with the parsed error flag.
615        let status = match out.status {
616            ExecStatus::Success if parsed.is_error => {
617                ExecStatus::Failed("worker reported an error".into())
618            }
619            other => other,
620        };
621
622        let mut usage = parsed.usage;
623        if usage.wall_ms == 0 {
624            usage.wall_ms = out.wall_ms;
625        }
626        // Many harness CLIs (Grok streaming-json, Aider, …) never report token
627        // counts. Fill zeros from the prompt + result so status / ledger / UI
628        // show consumption instead of a permanent `0 tok`.
629        usage.fill_estimates(&prompt, &parsed.result);
630
631        Ok(ExecuteResult {
632            result: parsed.result,
633            // Diff capture from the workspace is handled by the dispatcher in
634            // Phase 3 (git-aware); adapters leave it None unless the CLI emits
635            // one directly.
636            file_diff: None,
637            transcript: if out.stderr.is_empty() {
638                out.stdout
639            } else {
640                format!("{}\n--- stderr ---\n{}", out.stdout, out.stderr)
641            },
642            status,
643            usage,
644            session_id: parsed.session_id,
645        })
646    }
647}
648
649impl HarnessAdapter {
650    /// Run this harness's provisioner over a node's MCP servers, narrating the
651    /// outcome. Returns an empty provision (no args/env) when the node attaches
652    /// no servers, the harness has no provisioner, or provisioning fails.
653    fn provision(&self, request: &ExecuteRequest, events: &EventSink) -> Provision {
654        let empty = Provision {
655            args: Vec::new(),
656            env: Vec::new(),
657            cleanup: None,
658        };
659        if request.mcp_servers.is_empty() {
660            return empty;
661        }
662        let Some(provisioner) = self.provisioner else {
663            emit(
664                events,
665                WorkerEvent::Message(format!(
666                    "{} has no MCP provisioning — running without {} tool server(s)",
667                    self.program,
668                    request.mcp_servers.len()
669                )),
670            );
671            return empty;
672        };
673        let scratch = request
674            .workspace
675            .join(rinne_core::BLACKBOARD_DIR)
676            .join("mcp");
677        match provisioner(&request.mcp_servers, &scratch) {
678            Ok(p) => {
679                let names: Vec<&str> = request
680                    .mcp_servers
681                    .iter()
682                    .map(|s| s.name.as_str())
683                    .collect();
684                emit(
685                    events,
686                    WorkerEvent::Message(format!("provisioned MCP: {}", names.join(", "))),
687                );
688                p
689            }
690            Err(e) => {
691                emit(
692                    events,
693                    WorkerEvent::Message(format!(
694                        "MCP provisioning failed ({e}) — running without tools"
695                    )),
696                );
697                empty
698            }
699        }
700    }
701}
702
703/// Render the symbol map neighborhoods into a `## Relevant code structure` section.
704/// Returns an empty string when the slice is empty so callers can push it unconditionally.
705pub(crate) fn render_symbol_map(neighborhoods: &[rinne_types::graph::Neighborhood]) -> String {
706    if neighborhoods.is_empty() {
707        return String::new();
708    }
709    let mut s = String::from("\n\n## Relevant code structure\n");
710    for nb in neighborhoods {
711        let def = &nb.definition;
712        s.push_str(&format!("{} ({}:{})\n", def.name, def.file, def.line));
713        if !nb.callers.is_empty() {
714            let names: Vec<&str> = nb.callers.iter().map(|r| r.name.as_str()).collect();
715            s.push_str(&format!("  called by: {}\n", names.join(", ")));
716        }
717        if !nb.callees.is_empty() {
718            let names: Vec<&str> = nb.callees.iter().map(|r| r.name.as_str()).collect();
719            s.push_str(&format!("  calls: {}\n", names.join(", ")));
720        }
721    }
722    s
723}
724
725/// Compose a harness prompt from the request: the instruction, any critique fed
726/// back on loop-back, ambient steering, and the pinned file paths the worker
727/// should read itself.
728pub fn compose_prompt(request: &ExecuteRequest) -> String {
729    let mut out = String::new();
730    out.push_str(&request.instruction);
731
732    if !request.context.skill_text.is_empty() {
733        out.push_str("\n\n");
734        out.push_str(&request.context.skill_text);
735    }
736
737    if !request.context.prior_context.is_empty() {
738        out.push_str("\n\n## Context\n");
739        out.push_str(&request.context.prior_context);
740    }
741
742    if let Some(critique) = &request.context.critique {
743        out.push_str("\n\n## Address this feedback from the previous attempt\n");
744        out.push_str(critique);
745    }
746
747    if let Some(steer) = &request.constraints.steer {
748        out.push_str("\n\n## Steering\n");
749        out.push_str(steer);
750    }
751
752    if !request.context.pinned_paths.is_empty() {
753        out.push_str("\n\n## Relevant files (read these)\n");
754        for p in &request.context.pinned_paths {
755            out.push_str("- ");
756            out.push_str(&p.display().to_string());
757            out.push('\n');
758        }
759    }
760
761    out.push_str(&render_symbol_map(&request.context.symbol_map));
762
763    out
764}
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769    use rinne_core::worker::{Constraints, ContextPacket};
770    use std::path::PathBuf;
771
772    #[test]
773    fn approvals_default_to_auto_and_human_opts_out() {
774        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
775        std::env::remove_var("RINNE_HARNESS_APPROVALS");
776        assert!(
777            approvals_are_auto(),
778            "[harness_stage].approvals defaults to auto, so an unset env must match"
779        );
780        std::env::set_var("RINNE_HARNESS_APPROVALS", "human");
781        assert!(!approvals_are_auto());
782        std::env::set_var("RINNE_HARNESS_APPROVALS", "auto");
783        assert!(approvals_are_auto());
784        std::env::remove_var("RINNE_HARNESS_APPROVALS");
785    }
786
787    #[test]
788    fn approvals_do_not_fail_open_on_negative_spellings() {
789        // A permission switch must not auto-approve because the user wrote
790        // `off` instead of the one blessed spelling.
791        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
792        for v in [
793            "off", "0", "false", "no", "never", "none", "manual", "ASK", " human ",
794        ] {
795            std::env::set_var("RINNE_HARNESS_APPROVALS", v);
796            assert!(!approvals_are_auto(), "`{v}` must not mean auto-approve");
797        }
798        for v in ["auto", "AUTO", "yes", "1"] {
799            std::env::set_var("RINNE_HARNESS_APPROVALS", v);
800            assert!(approvals_are_auto(), "`{v}` must mean auto-approve");
801        }
802        std::env::remove_var("RINNE_HARNESS_APPROVALS");
803    }
804
805    fn req(skill_text: &str) -> ExecuteRequest {
806        ExecuteRequest {
807            role: Role::Generator,
808            instruction: "do the task".into(),
809            context: ContextPacket {
810                skill_text: skill_text.into(),
811                ..Default::default()
812            },
813            workspace: PathBuf::from("/tmp"),
814            constraints: Constraints::default(),
815            tools: Vec::new(),
816            mcp_servers: Vec::new(),
817        }
818    }
819
820    #[test]
821    fn symbol_map_is_rendered_into_harness_prompt() {
822        use rinne_types::graph::{Neighborhood, SymbolRef};
823        let nb = Neighborhood {
824            definition: SymbolRef {
825                name: "helper".into(),
826                file: "m.rs".into(),
827                line: 1,
828                end_line: 1,
829            },
830            callers: vec![SymbolRef {
831                name: "main".into(),
832                file: "main.rs".into(),
833                line: 5,
834                end_line: 5,
835            }],
836            callees: vec![],
837            imports: vec![],
838            stale: false,
839        };
840        let mut r = req("");
841        r.context.symbol_map = vec![nb];
842        let prompt = compose_prompt(&r);
843        assert!(
844            prompt.contains("## Relevant code structure"),
845            "section header missing"
846        );
847        assert!(prompt.contains("helper"), "definition name missing");
848        assert!(prompt.contains("m.rs:1"), "definition file:line missing");
849        assert!(prompt.contains("main"), "caller name missing");
850    }
851
852    #[test]
853    fn skill_text_is_injected_after_instruction() {
854        let prompt = compose_prompt(&req("## Skill: pdf-forms\nFlatten the form"));
855        assert!(prompt.starts_with("do the task"));
856        assert!(prompt.contains("## Skill: pdf-forms"));
857        assert!(prompt.contains("Flatten the form"));
858    }
859
860    #[test]
861    fn absent_skill_text_adds_nothing() {
862        assert_eq!(compose_prompt(&req("")), "do the task");
863    }
864
865    fn harness(provisioner: Option<McpProvisioner>) -> HarnessAdapter {
866        use rinne_core::worker::{
867            AuthMode, Capability, LatencyProfile, QuotaModel, Transport, WorkerFamily,
868        };
869        HarnessAdapter {
870            descriptor: WorkerDescriptor {
871                name: "test".into(),
872                family: WorkerFamily::Harness,
873                capabilities: vec![Capability::CodeEdit],
874                auth_mode: AuthMode::Subscription,
875                quota: QuotaModel::unlimited(),
876                latency: LatencyProfile::Medium,
877                transport: Transport::SubprocessJson,
878                models: vec![],
879            },
880            program: "test".into(),
881            build_args: |_, _| vec![],
882            plan_args: None,
883            interactive_args: None,
884            parse: parse_raw,
885            line_mapper: crate::transport::subprocess::raw_lines,
886            prompt_via_stdin: false,
887            default_timeout: std::time::Duration::from_secs(1),
888            provisioner,
889        }
890    }
891
892    fn tool_request() -> ExecuteRequest {
893        use rinne_core::worker::{McpServerSpec, McpTransportKind};
894        let mut r = req("");
895        r.mcp_servers = vec![McpServerSpec {
896            name: "srv".into(),
897            transport: McpTransportKind::Stdio,
898            command: Some("cmd".into()),
899            args: vec![],
900            env: vec![],
901            url: None,
902            headers: vec![],
903            token_env: None,
904            token: None,
905            auth: None,
906            auth_header: None,
907        }];
908        r
909    }
910
911    #[test]
912    fn provisioner_supplies_args_and_env_for_a_tool_node() {
913        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
914            Ok(Provision {
915                args: vec!["--mcp-config".into(), "x.json".into()],
916                env: vec![("TOKEN".into(), "secret".into())],
917                cleanup: None,
918            })
919        }
920        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
921        let p = harness(Some(prov)).provision(&tool_request(), &tx);
922        assert_eq!(p.args, vec!["--mcp-config", "x.json"]);
923        assert_eq!(p.env, vec![("TOKEN".to_string(), "secret".to_string())]);
924    }
925
926    #[test]
927    fn no_provisioner_yields_empty_provision_and_narrates() {
928        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
929        let p = harness(None).provision(&tool_request(), &tx);
930        assert!(
931            p.args.is_empty(),
932            "no flags when the harness can't provision"
933        );
934        assert!(p.env.is_empty());
935        // The gap is surfaced, not silent.
936        let mut narrated = false;
937        while let Ok(ev) = rx.try_recv() {
938            if let WorkerEvent::Message(m) = ev {
939                if m.contains("no MCP provisioning") {
940                    narrated = true;
941                }
942            }
943        }
944        assert!(narrated, "a missing provisioner should be narrated");
945    }
946
947    #[test]
948    fn no_servers_means_no_provision_work() {
949        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
950            panic!("must not be called when the node attaches no servers");
951        }
952        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
953        let p = harness(Some(prov)).provision(&req(""), &tx); // req() has no mcp_servers
954        assert!(p.args.is_empty());
955    }
956}