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/// Defensive parser for harnesses that emit a single JSON result object: probe
65/// common result fields, falling back to raw stdout on any surprise
66/// (`CONTEXT.md` §21). Suitable for not-yet-pinned beta CLIs.
67pub fn parse_generic_json(out: &SubprocessOutput) -> ParsedHarness {
68    let pick = |v: &serde_json::Value| {
69        v.get("result")
70            .or_else(|| v.get("text"))
71            .or_else(|| v.get("message"))
72            .or_else(|| v.get("content"))
73            .or_else(|| v.get("response"))
74            .and_then(|x| x.as_str())
75            .map(String::from)
76    };
77    for line in out.stdout.lines().rev() {
78        let line = line.trim();
79        if !line.starts_with('{') {
80            continue;
81        }
82        if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
83            if let Some(result) = pick(&v) {
84                let session_id = v
85                    .get("session_id")
86                    .or_else(|| v.get("sessionId"))
87                    .and_then(|x| x.as_str())
88                    .map(String::from);
89                let is_error = v.get("is_error").and_then(|b| b.as_bool()).unwrap_or(false);
90                return ParsedHarness {
91                    result,
92                    session_id,
93                    usage: Usage::default(),
94                    is_error,
95                };
96            }
97        }
98    }
99    ParsedHarness::raw(&out.stdout)
100}
101
102/// The trivial parser: the captured stdout is the result (for CLIs that print
103/// plain text, e.g. Aider).
104pub fn parse_raw(out: &SubprocessOutput) -> ParsedHarness {
105    ParsedHarness::raw(&out.stdout)
106}
107/// Parse a harness CLI's captured output into normalized fields.
108pub type OutputParser = fn(out: &SubprocessOutput) -> ParsedHarness;
109
110/// A generic harness worker driven over the `subprocess-json` transport. Each
111/// concrete CLI supplies its program name, argv builder, output parser, and an
112/// optional line mapper for richer streaming.
113pub struct HarnessAdapter {
114    pub descriptor: WorkerDescriptor,
115    pub program: String,
116    pub build_args: ArgsBuilder,
117    /// Lean argv used when the harness runs as the **planner** (`Role::Planner`):
118    /// a plain-text completion, not the agentic/streaming work invocation. When
119    /// set, planning reads the full stdout as the answer (more robust across CLI
120    /// versions than parsing a streaming format). `None` → planning reuses
121    /// `build_args` and the normal parser unchanged.
122    pub plan_args: Option<ArgsBuilder>,
123    pub parse: OutputParser,
124    pub line_mapper: LineMapper,
125    /// Whether the prompt is piped via stdin (vs. passed as an argument).
126    pub prompt_via_stdin: bool,
127    pub default_timeout: Duration,
128    /// How this harness is told to use a node's MCP servers (`MCP_SKILLS.md` §6).
129    /// `None` means the harness has no MCP provisioning wired: a node's tools are
130    /// simply unavailable to it (the node still runs), so the conductor should
131    /// prefer an API worker for tool-heavy nodes on such a harness.
132    pub provisioner: Option<McpProvisioner>,
133}
134
135impl HarnessAdapter {
136    /// Replace the static model ladder with a live (or config-merged) list.
137    pub fn with_models(mut self, models: Vec<String>) -> Self {
138        self.descriptor.models = models;
139        self
140    }
141
142    /// Ensure `model` is on the ladder (appended as frontier if missing). Used
143    /// so a user pin / `[models].by_worker` entry is never dropped as "unknown".
144    pub fn ensure_model(mut self, model: &str) -> Self {
145        let model = model.trim();
146        if model.is_empty() {
147            return self;
148        }
149        if !self.descriptor.models.iter().any(|m| m == model) {
150            self.descriptor.models.push(model.to_string());
151        }
152        self
153    }
154}
155
156#[async_trait]
157impl Worker for HarnessAdapter {
158    fn descriptor(&self) -> &WorkerDescriptor {
159        &self.descriptor
160    }
161
162    /// A harness serves MCP tools when it has a provisioner wired (the provision
163    /// path, `MCP_SKILLS.md` §6).
164    fn serves_mcp_tools(&self) -> bool {
165        self.provisioner.is_some()
166    }
167
168    async fn execute(
169        &self,
170        request: ExecuteRequest,
171        events: EventSink,
172        cancel: CancellationToken,
173    ) -> Result<ExecuteResult> {
174        let prompt = compose_prompt(&request);
175        let timeout = request
176            .constraints
177            .timeout_secs
178            .map(Duration::from_secs)
179            .unwrap_or(self.default_timeout);
180
181        let model = request.constraints.model.as_deref();
182        let has_lean = self.plan_args.is_some();
183        // The lean plain-text invocation: used for the planner role, and as an
184        // automatic fallback when the rich/streaming invocation fails with no
185        // output (e.g. a CLI version that rejects the streaming flags). Planning
186        // starts lean so a work flag can't make the planner exit non-zero.
187        let mut lean = matches!(request.role, Role::Planner) && has_lean;
188
189        // Provision the node's MCP servers into this harness once, up front
190        // (`MCP_SKILLS.md` §6). A provisioner failure is non-fatal: narrate it and
191        // run without the tools rather than failing the node.
192        let provision = self.provision(&request, &events);
193
194        // Retry transient failures (spawn errors, timeouts) once before giving
195        // up — beta CLIs are flaky (`CONTEXT.md` §21). A cancelled run is not
196        // retried.
197        const MAX_ATTEMPTS: u32 = 2;
198        let mut attempt = 0;
199        let out = loop {
200            attempt += 1;
201            let builder = if lean { self.plan_args.unwrap() } else { self.build_args };
202            let mapper = if lean { subprocess::raw_lines } else { self.line_mapper };
203            let (mut args, stdin) = if self.prompt_via_stdin {
204                (builder("", model), Some(prompt.clone()))
205            } else {
206                (builder(&prompt, model), None)
207            };
208            // Append the MCP flags on the rich work invocation (not the lean
209            // planner path, which neither needs tools nor accepts the flags).
210            if !lean {
211                args.extend(provision.args.iter().cloned());
212            }
213            let spec = SubprocessSpec {
214                program: self.program.clone(),
215                args,
216                workspace: request.workspace.clone(),
217                stdin,
218                timeout: Some(timeout),
219                env: provision.env.clone(),
220            };
221            match subprocess::run(spec, &events, &cancel, mapper).await {
222                Ok(out) => {
223                    let timed_out = matches!(out.status, ExecStatus::TimedOut);
224                    if timed_out && attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
225                        emit(&events, WorkerEvent::Message(format!(
226                            "{} timed out — retrying ({attempt}/{MAX_ATTEMPTS})",
227                            self.program
228                        )));
229                        continue;
230                    }
231                    // Rich invocation failed with nothing usable on stdout, and a
232                    // lean plain invocation is available → fall back to it once.
233                    let empty_fail = !matches!(out.status, ExecStatus::Success)
234                        && out.stdout.trim().is_empty();
235                    if empty_fail && !lean && has_lean && !cancel.is_cancelled() {
236                        lean = true;
237                        emit(&events, WorkerEvent::Message(format!(
238                            "{} failed in streaming mode — retrying in plain mode",
239                            self.program
240                        )));
241                        continue;
242                    }
243                    break out;
244                }
245                Err(e) => {
246                    if attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
247                        emit(&events, WorkerEvent::Message(format!(
248                            "{} failed to start ({e}) — retrying ({attempt}/{MAX_ATTEMPTS})",
249                            self.program
250                        )));
251                        tokio::time::sleep(Duration::from_millis(500)).await;
252                        continue;
253                    }
254                    return Err(e);
255                }
256            }
257        };
258        // Best-effort cleanup of the provisioned config file (it holds no secret,
259        // but leaving scratch around is untidy).
260        if let Some(path) = &provision.cleanup {
261            let _ = std::fs::remove_file(path);
262        }
263        // The lean invocation yields plain text (the answer / JSON DAG, possibly
264        // fenced); take full stdout and let the caller's tolerant parser read it.
265        let parsed = if lean {
266            ParsedHarness::raw(&out.stdout)
267        } else {
268            (self.parse)(&out)
269        };
270
271        // Reconcile the transport-level status with the parsed error flag.
272        let status = match out.status {
273            ExecStatus::Success if parsed.is_error => {
274                ExecStatus::Failed("worker reported an error".into())
275            }
276            other => other,
277        };
278
279        let mut usage = parsed.usage;
280        if usage.wall_ms == 0 {
281            usage.wall_ms = out.wall_ms;
282        }
283        // Many harness CLIs (Grok streaming-json, Aider, …) never report token
284        // counts. Fill zeros from the prompt + result so status / ledger / UI
285        // show consumption instead of a permanent `0 tok`.
286        usage.fill_estimates(&prompt, &parsed.result);
287
288        Ok(ExecuteResult {
289            result: parsed.result,
290            // Diff capture from the workspace is handled by the dispatcher in
291            // Phase 3 (git-aware); adapters leave it None unless the CLI emits
292            // one directly.
293            file_diff: None,
294            transcript: if out.stderr.is_empty() {
295                out.stdout
296            } else {
297                format!("{}\n--- stderr ---\n{}", out.stdout, out.stderr)
298            },
299            status,
300            usage,
301            session_id: parsed.session_id,
302        })
303    }
304}
305
306impl HarnessAdapter {
307    /// Run this harness's provisioner over a node's MCP servers, narrating the
308    /// outcome. Returns an empty provision (no args/env) when the node attaches
309    /// no servers, the harness has no provisioner, or provisioning fails.
310    fn provision(&self, request: &ExecuteRequest, events: &EventSink) -> Provision {
311        let empty = Provision {
312            args: Vec::new(),
313            env: Vec::new(),
314            cleanup: None,
315        };
316        if request.mcp_servers.is_empty() {
317            return empty;
318        }
319        let Some(provisioner) = self.provisioner else {
320            emit(
321                events,
322                WorkerEvent::Message(format!(
323                    "{} has no MCP provisioning — running without {} tool server(s)",
324                    self.program,
325                    request.mcp_servers.len()
326                )),
327            );
328            return empty;
329        };
330        let scratch = request
331            .workspace
332            .join(rinne_core::BLACKBOARD_DIR)
333            .join("mcp");
334        match provisioner(&request.mcp_servers, &scratch) {
335            Ok(p) => {
336                let names: Vec<&str> = request.mcp_servers.iter().map(|s| s.name.as_str()).collect();
337                emit(
338                    events,
339                    WorkerEvent::Message(format!("provisioned MCP: {}", names.join(", "))),
340                );
341                p
342            }
343            Err(e) => {
344                emit(
345                    events,
346                    WorkerEvent::Message(format!("MCP provisioning failed ({e}) — running without tools")),
347                );
348                empty
349            }
350        }
351    }
352}
353
354/// Render the symbol map neighborhoods into a `## Relevant code structure` section.
355/// Returns an empty string when the slice is empty so callers can push it unconditionally.
356pub(crate) fn render_symbol_map(neighborhoods: &[rinne_types::graph::Neighborhood]) -> String {
357    if neighborhoods.is_empty() {
358        return String::new();
359    }
360    let mut s = String::from("\n\n## Relevant code structure\n");
361    for nb in neighborhoods {
362        let def = &nb.definition;
363        s.push_str(&format!("{} ({}:{})\n", def.name, def.file, def.line));
364        if !nb.callers.is_empty() {
365            let names: Vec<&str> = nb.callers.iter().map(|r| r.name.as_str()).collect();
366            s.push_str(&format!("  called by: {}\n", names.join(", ")));
367        }
368        if !nb.callees.is_empty() {
369            let names: Vec<&str> = nb.callees.iter().map(|r| r.name.as_str()).collect();
370            s.push_str(&format!("  calls: {}\n", names.join(", ")));
371        }
372    }
373    s
374}
375
376/// Compose a harness prompt from the request: the instruction, any critique fed
377/// back on loop-back, ambient steering, and the pinned file paths the worker
378/// should read itself.
379pub fn compose_prompt(request: &ExecuteRequest) -> String {
380    let mut out = String::new();
381    out.push_str(&request.instruction);
382
383    if !request.context.skill_text.is_empty() {
384        out.push_str("\n\n");
385        out.push_str(&request.context.skill_text);
386    }
387
388    if !request.context.prior_context.is_empty() {
389        out.push_str("\n\n## Context\n");
390        out.push_str(&request.context.prior_context);
391    }
392
393    if let Some(critique) = &request.context.critique {
394        out.push_str("\n\n## Address this feedback from the previous attempt\n");
395        out.push_str(critique);
396    }
397
398    if let Some(steer) = &request.constraints.steer {
399        out.push_str("\n\n## Steering\n");
400        out.push_str(steer);
401    }
402
403    if !request.context.pinned_paths.is_empty() {
404        out.push_str("\n\n## Relevant files (read these)\n");
405        for p in &request.context.pinned_paths {
406            out.push_str("- ");
407            out.push_str(&p.display().to_string());
408            out.push('\n');
409        }
410    }
411
412    out.push_str(&render_symbol_map(&request.context.symbol_map));
413
414    out
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420    use rinne_core::worker::{ContextPacket, Constraints};
421    use std::path::PathBuf;
422
423    fn req(skill_text: &str) -> ExecuteRequest {
424        ExecuteRequest {
425            role: Role::Generator,
426            instruction: "do the task".into(),
427            context: ContextPacket {
428                skill_text: skill_text.into(),
429                ..Default::default()
430            },
431            workspace: PathBuf::from("/tmp"),
432            constraints: Constraints::default(),
433            tools: Vec::new(),
434            mcp_servers: Vec::new(),
435        }
436    }
437
438    #[test]
439    fn symbol_map_is_rendered_into_harness_prompt() {
440        use rinne_types::graph::{Neighborhood, SymbolRef};
441        let nb = Neighborhood {
442            definition: SymbolRef { name: "helper".into(), file: "m.rs".into(), line: 1 },
443            callers: vec![SymbolRef { name: "main".into(), file: "main.rs".into(), line: 5 }],
444            callees: vec![],
445            imports: vec![],
446            stale: false,
447        };
448        let mut r = req("");
449        r.context.symbol_map = vec![nb];
450        let prompt = compose_prompt(&r);
451        assert!(prompt.contains("## Relevant code structure"), "section header missing");
452        assert!(prompt.contains("helper"), "definition name missing");
453        assert!(prompt.contains("m.rs:1"), "definition file:line missing");
454        assert!(prompt.contains("main"), "caller name missing");
455    }
456
457    #[test]
458    fn skill_text_is_injected_after_instruction() {
459        let prompt = compose_prompt(&req("## Skill: pdf-forms\nFlatten the form"));
460        assert!(prompt.starts_with("do the task"));
461        assert!(prompt.contains("## Skill: pdf-forms"));
462        assert!(prompt.contains("Flatten the form"));
463    }
464
465    #[test]
466    fn absent_skill_text_adds_nothing() {
467        assert_eq!(compose_prompt(&req("")), "do the task");
468    }
469
470    fn harness(provisioner: Option<McpProvisioner>) -> HarnessAdapter {
471        use rinne_core::worker::{
472            AuthMode, Capability, LatencyProfile, QuotaModel, Transport, WorkerFamily,
473        };
474        HarnessAdapter {
475            descriptor: WorkerDescriptor {
476                name: "test".into(),
477                family: WorkerFamily::Harness,
478                capabilities: vec![Capability::CodeEdit],
479                auth_mode: AuthMode::Subscription,
480                quota: QuotaModel::unlimited(),
481                latency: LatencyProfile::Medium,
482                transport: Transport::SubprocessJson,
483                models: vec![],
484            },
485            program: "test".into(),
486            build_args: |_, _| vec![],
487            plan_args: None,
488            parse: parse_raw,
489            line_mapper: crate::transport::subprocess::raw_lines,
490            prompt_via_stdin: false,
491            default_timeout: std::time::Duration::from_secs(1),
492            provisioner,
493        }
494    }
495
496    fn tool_request() -> ExecuteRequest {
497        use rinne_core::worker::{McpServerSpec, McpTransportKind};
498        let mut r = req("");
499        r.mcp_servers = vec![McpServerSpec {
500            name: "srv".into(),
501            transport: McpTransportKind::Stdio,
502            command: Some("cmd".into()),
503            args: vec![],
504            env: vec![],
505            url: None,
506            headers: vec![],
507            token_env: None,
508            token: None,
509            auth: None,
510            auth_header: None,
511        }];
512        r
513    }
514
515    #[test]
516    fn provisioner_supplies_args_and_env_for_a_tool_node() {
517        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
518            Ok(Provision {
519                args: vec!["--mcp-config".into(), "x.json".into()],
520                env: vec![("TOKEN".into(), "secret".into())],
521                cleanup: None,
522            })
523        }
524        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
525        let p = harness(Some(prov)).provision(&tool_request(), &tx);
526        assert_eq!(p.args, vec!["--mcp-config", "x.json"]);
527        assert_eq!(p.env, vec![("TOKEN".to_string(), "secret".to_string())]);
528    }
529
530    #[test]
531    fn no_provisioner_yields_empty_provision_and_narrates() {
532        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
533        let p = harness(None).provision(&tool_request(), &tx);
534        assert!(p.args.is_empty(), "no flags when the harness can't provision");
535        assert!(p.env.is_empty());
536        // The gap is surfaced, not silent.
537        let mut narrated = false;
538        while let Ok(ev) = rx.try_recv() {
539            if let WorkerEvent::Message(m) = ev {
540                if m.contains("no MCP provisioning") {
541                    narrated = true;
542                }
543            }
544        }
545        assert!(narrated, "a missing provisioner should be narrated");
546    }
547
548    #[test]
549    fn no_servers_means_no_provision_work() {
550        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
551            panic!("must not be called when the node attaches no servers");
552        }
553        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
554        let p = harness(Some(prov)).provision(&req(""), &tx); // req() has no mcp_servers
555        assert!(p.args.is_empty());
556    }
557}