Skip to main content

rinne_loop/
assembler.rs

1//! The context assembler (`CONTEXT.md` §12).
2//!
3//! Builds each node's context packet from the blackboard. This is the hardest
4//! component because no two workers share a context window. For a **harness**
5//! worker it writes a thin packet and *pins file paths* — the worker reads the
6//! repo itself. For an **API** worker it *inlines file contents* — the model
7//! sees only what is sent. Get this right or workers talk past each other.
8
9use std::path::{Path, PathBuf};
10
11use crate::dag::{Node, Plan};
12use crate::worker::{ContextPacket, InlinedFile, WorkerFamily};
13use crate::{Result, BLACKBOARD_DIR};
14use rinne_types::Blackboard;
15
16const COMMON_NAMES: &[&str] = &["new", "run", "get", "set", "build", "main", "init", "from", "into"];
17const MIN_IDENT_LEN: usize = 4;
18
19/// Picks symbol names to attach from the graph for a given node instruction.
20///
21/// Returns exact identifier tokens in `instruction` that match a known symbol
22/// name, plus symbols named like a mentioned file's stem. Deduplicates output.
23/// Skips tokens shorter than `MIN_IDENT_LEN` and tokens in `COMMON_NAMES`.
24pub fn resolve_symbols(
25    graph: &dyn rinne_types::graph::CodeGraph,
26    instruction: &str,
27    mentioned: &[std::path::PathBuf],
28    known: &[String],
29) -> Vec<String> {
30    let known_set: std::collections::HashSet<&str> = known.iter().map(|s| s.as_str()).collect();
31    let mut out: Vec<String> = Vec::new();
32    // Exact identifier tokens from the instruction that name a known symbol.
33    for tok in instruction.split(|c: char| !c.is_alphanumeric() && c != '_') {
34        if tok.len() >= MIN_IDENT_LEN
35            && !COMMON_NAMES.contains(&tok)
36            && known_set.contains(tok)
37            && !out.iter().any(|o| o == tok)
38        {
39            out.push(tok.to_string());
40        }
41    }
42    // Symbols named like a mentioned file's stem (best-effort).
43    for m in mentioned {
44        if let Some(stem) = m.file_stem().and_then(|s| s.to_str()) {
45            if known_set.contains(stem) && !out.iter().any(|o| o == stem) {
46                out.push(stem.to_string());
47            }
48        }
49    }
50    let _ = graph;
51    out
52}
53
54/// Builds context packets against a plan and its blackboard.
55pub struct ContextAssembler<'a> {
56    blackboard: &'a dyn Blackboard,
57    plan: &'a Plan,
58    graph: Option<&'a dyn rinne_types::graph::CodeGraph>,
59}
60
61impl<'a> ContextAssembler<'a> {
62    pub fn new(
63        blackboard: &'a dyn Blackboard,
64        plan: &'a Plan,
65        graph: Option<&'a dyn rinne_types::graph::CodeGraph>,
66    ) -> Self {
67        Self { blackboard, plan, graph }
68    }
69
70    /// Assemble the packet for `node`, shaped for the target worker `family`.
71    ///
72    /// `critique` carries an evaluator's feedback on loop-back (P5); pass `None`
73    /// on the first attempt.
74    pub fn build(
75        &self,
76        node: &Node,
77        family: WorkerFamily,
78        critique: Option<String>,
79    ) -> Result<ContextPacket> {
80        // The context sources are the same regardless of family: the plan's
81        // pinned `@`-mentions plus this node's named input artifacts. Only the
82        // *shaping* (paths vs. contents) differs.
83        let mentioned = &self.plan.mentioned;
84        let input_artifacts: Vec<String> = node
85            .inputs
86            .iter()
87            .filter(|i| i.as_str() != "diff") // `diff` is a special pseudo-input
88            .cloned()
89            .collect();
90
91        let mut packet = ContextPacket {
92            critique,
93            ..Default::default()
94        };
95
96        match family {
97            WorkerFamily::Harness => {
98                // Pin repo-relative mention paths, and the on-disk paths of input
99                // artifacts (under .rinne/artifacts/) for the worker to read.
100                for m in mentioned {
101                    packet.pinned_paths.push(m.clone());
102                }
103                for name in &input_artifacts {
104                    if self.blackboard.artifact_exists(name) {
105                        packet
106                            .pinned_paths
107                            .push(artifact_rel_path(name));
108                    }
109                }
110            }
111            WorkerFamily::Api => {
112                // Inline contents: the model sees only what we send.
113                let workspace = self.blackboard.workspace();
114                for m in mentioned {
115                    if let Some(file) = read_inlined(workspace, m) {
116                        packet.inlined_files.push(file);
117                    }
118                }
119                for name in &input_artifacts {
120                    if let Ok(contents) = self.blackboard.read_artifact(name) {
121                        packet.inlined_files.push(InlinedFile {
122                            path: artifact_rel_path(name),
123                            contents,
124                        });
125                    }
126                }
127            }
128        }
129
130        // Attach graph neighborhoods for resolved symbols (additive; never
131        // replaces pinned_paths / inlined_files set above).
132        if let Some(graph) = self.graph {
133            let known = graph.symbol_names();
134            let picked = resolve_symbols(graph, &node.instruction, mentioned, &known);
135            for name in &picked {
136                if let Some(neighborhood) = graph.neighborhood(name) {
137                    packet.symbol_map.push(neighborhood);
138                }
139            }
140        }
141
142        Ok(packet)
143    }
144}
145
146/// The workspace-relative path of a named artifact (e.g.
147/// `.rinne/artifacts/design.md`), usable by a harness worker from the repo root.
148fn artifact_rel_path(name: &str) -> PathBuf {
149    Path::new(BLACKBOARD_DIR).join("artifacts").join(name)
150}
151
152/// Cap on a single inlined file's size, so `@`-mentioning a huge (or binary)
153/// file can't blow up the API request's tokens/cost/memory. Content past the cap
154/// is truncated with a visible marker rather than sent whole.
155const MAX_INLINE_BYTES: usize = 256 * 1024;
156
157/// Read a mentioned file's contents for inlining, resolving it against the
158/// workspace. Returns `None` if it cannot be read (e.g. a directory or missing);
159/// oversized files are truncated with a marker rather than dropped.
160fn read_inlined(workspace: &Path, rel: &Path) -> Option<InlinedFile> {
161    let abs = if rel.is_absolute() {
162        rel.to_path_buf()
163    } else {
164        workspace.join(rel)
165    };
166    let mut contents = std::fs::read_to_string(&abs).ok()?;
167    if contents.len() > MAX_INLINE_BYTES {
168        // Truncate on a char boundary at or below the cap.
169        let mut cut = MAX_INLINE_BYTES;
170        while cut > 0 && !contents.is_char_boundary(cut) {
171            cut -= 1;
172        }
173        contents.truncate(cut);
174        contents.push_str("\n…[file truncated: exceeded inline size limit]\n");
175    }
176    Some(InlinedFile {
177        path: rel.to_path_buf(),
178        contents,
179    })
180}
181
182#[cfg(test)]
183mod graph_tests {
184    use super::*;
185    use rinne_types::graph::{CodeGraph, Neighborhood, SymbolRef};
186
187    struct FakeGraph;
188    impl CodeGraph for FakeGraph {
189        fn neighborhood(&self, symbol: &str) -> Option<Neighborhood> {
190            (symbol == "HttpTransport").then(|| Neighborhood {
191                definition: SymbolRef { name: "HttpTransport".into(), file: "t.rs".into(), line: 10 },
192                callers: vec![SymbolRef { name: "send".into(), file: "s.rs".into(), line: 3 }],
193                callees: vec![],
194                imports: vec![],
195                stale: false,
196            })
197        }
198        fn resolve_in_file(&self, _f: &str, _n: &str) -> Option<SymbolRef> { None }
199        fn symbol_names(&self) -> Vec<String> { vec!["HttpTransport".into()] }
200    }
201
202    #[test]
203    fn attaches_neighborhood_for_exact_identifier_in_instruction() {
204        let names = FakeGraph.symbol_names();
205        let picked = resolve_symbols(&FakeGraph, "add retry to HttpTransport", &[], &names);
206        assert_eq!(picked, vec!["HttpTransport".to_string()]);
207    }
208
209    #[test]
210    fn skips_common_short_names() {
211        let names = vec!["new".to_string(), "run".to_string()];
212        let picked = resolve_symbols(&FakeGraph, "run the new thing", &[], &names);
213        assert!(picked.is_empty());
214    }
215}