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 MIN_IDENT_LEN: usize = 4;
17
18/// Picks symbol names to attach from the graph for a given node instruction.
19///
20/// Returns exact identifier tokens in `instruction` that match a known symbol
21/// name, plus symbols named like a mentioned file's stem. Deduplicates output.
22/// Skips tokens shorter than `MIN_IDENT_LEN`.
23///
24/// Note: there is no hardcoded common-name denylist. Ambiguous names (`build`,
25/// `run`, `new`) are disambiguated downstream by the mentioned-file hint in
26/// [`ContextAssembler::build`], so they no longer need blanket suppression.
27pub fn resolve_symbols(
28    graph: &dyn rinne_types::graph::CodeGraph,
29    instruction: &str,
30    mentioned: &[std::path::PathBuf],
31    known: &[String],
32) -> Vec<String> {
33    let known_set: std::collections::HashSet<&str> = known.iter().map(|s| s.as_str()).collect();
34    let mut out: Vec<String> = Vec::new();
35    // Exact identifier tokens from the instruction that name a known symbol.
36    for tok in instruction.split(|c: char| !c.is_alphanumeric() && c != '_') {
37        if tok.len() >= MIN_IDENT_LEN && known_set.contains(tok) && !out.iter().any(|o| o == tok) {
38            out.push(tok.to_string());
39        }
40    }
41    // Symbols named like a mentioned file's stem (best-effort).
42    for m in mentioned {
43        if let Some(stem) = m.file_stem().and_then(|s| s.to_str()) {
44            if known_set.contains(stem) && !out.iter().any(|o| o == stem) {
45                out.push(stem.to_string());
46            }
47        }
48    }
49    let _ = graph;
50    out
51}
52
53/// Picks the neighborhoods to attach for a resolved symbol name, using the
54/// node's mentioned files as a disambiguation hint.
55///
56/// A name may resolve to several definitions across files (e.g. `build` on
57/// `ContextAssembler` vs `Blackboard`). When any definition lives in a mentioned
58/// file, only those are attached — the mention is a strong signal of intent.
59/// Otherwise every definition is attached, so a worker sees the full set rather
60/// than one silently-chosen (possibly wrong) anchor.
61fn neighborhoods_for(
62    graph: &dyn rinne_types::graph::CodeGraph,
63    name: &str,
64    mentioned: &[std::path::PathBuf],
65) -> Vec<rinne_types::graph::Neighborhood> {
66    let all = graph.neighborhood_all(name);
67    if all.len() <= 1 {
68        return all;
69    }
70    let in_mentioned: Vec<_> = all
71        .iter()
72        .filter(|nb| {
73            mentioned
74                .iter()
75                .any(|m| m.to_str().is_some_and(|p| p == nb.definition.file))
76        })
77        .cloned()
78        .collect();
79    if in_mentioned.is_empty() {
80        all
81    } else {
82        in_mentioned
83    }
84}
85
86/// Builds context packets against a plan and its blackboard.
87pub struct ContextAssembler<'a> {
88    blackboard: &'a dyn Blackboard,
89    plan: &'a Plan,
90    graph: Option<&'a dyn rinne_types::graph::CodeGraph>,
91}
92
93impl<'a> ContextAssembler<'a> {
94    pub fn new(
95        blackboard: &'a dyn Blackboard,
96        plan: &'a Plan,
97        graph: Option<&'a dyn rinne_types::graph::CodeGraph>,
98    ) -> Self {
99        Self {
100            blackboard,
101            plan,
102            graph,
103        }
104    }
105
106    /// Assemble the packet for `node`, shaped for the target worker `family`.
107    ///
108    /// `critique` carries an evaluator's feedback on loop-back (P5); pass `None`
109    /// on the first attempt.
110    pub fn build(
111        &self,
112        node: &Node,
113        family: WorkerFamily,
114        critique: Option<String>,
115    ) -> Result<ContextPacket> {
116        // The context sources are the same regardless of family: the plan's
117        // pinned `@`-mentions plus this node's named input artifacts. Only the
118        // *shaping* (paths vs. contents) differs.
119        let mentioned = &self.plan.mentioned;
120        let input_artifacts: Vec<String> = node
121            .inputs
122            .iter()
123            .filter(|i| i.as_str() != "diff") // `diff` is a special pseudo-input
124            .cloned()
125            .collect();
126
127        let mut packet = ContextPacket {
128            critique,
129            ..Default::default()
130        };
131
132        match family {
133            WorkerFamily::Harness => {
134                // Pin repo-relative mention paths, and the on-disk paths of input
135                // artifacts (under .rinne/artifacts/) for the worker to read.
136                for m in mentioned {
137                    packet.pinned_paths.push(m.clone());
138                }
139                for name in &input_artifacts {
140                    if self.blackboard.artifact_exists(name) {
141                        packet.pinned_paths.push(artifact_rel_path(name));
142                    }
143                }
144            }
145            WorkerFamily::Api => {
146                // Inline contents: the model sees only what we send.
147                let workspace = self.blackboard.workspace();
148                for m in mentioned {
149                    if let Some(file) = read_inlined(workspace, m) {
150                        packet.inlined_files.push(file);
151                    }
152                }
153                for name in &input_artifacts {
154                    if let Ok(contents) = self.blackboard.read_artifact(name) {
155                        packet.inlined_files.push(InlinedFile {
156                            path: artifact_rel_path(name),
157                            contents,
158                        });
159                    }
160                }
161            }
162        }
163
164        // Attach graph neighborhoods for resolved symbols (additive; never
165        // replaces pinned_paths / inlined_files set above).
166        if let Some(graph) = self.graph {
167            let known = graph.symbol_names();
168            let picked = resolve_symbols(graph, &node.instruction, mentioned, &known);
169            for name in &picked {
170                for neighborhood in neighborhoods_for(graph, name, mentioned) {
171                    packet.symbol_map.push(neighborhood);
172                }
173            }
174        }
175
176        Ok(packet)
177    }
178}
179
180/// The workspace-relative path of a named artifact (e.g.
181/// `.rinne/artifacts/design.md`), usable by a harness worker from the repo root.
182fn artifact_rel_path(name: &str) -> PathBuf {
183    Path::new(BLACKBOARD_DIR).join("artifacts").join(name)
184}
185
186/// Cap on a single inlined file's size, so `@`-mentioning a huge (or binary)
187/// file can't blow up the API request's tokens/cost/memory. Content past the cap
188/// is truncated with a visible marker rather than sent whole.
189const MAX_INLINE_BYTES: usize = 256 * 1024;
190
191/// Read a mentioned file's contents for inlining, resolving it against the
192/// workspace. Returns `None` if it cannot be read (e.g. a directory or missing);
193/// oversized files are truncated with a marker rather than dropped.
194fn read_inlined(workspace: &Path, rel: &Path) -> Option<InlinedFile> {
195    let abs = if rel.is_absolute() {
196        rel.to_path_buf()
197    } else {
198        workspace.join(rel)
199    };
200    let mut contents = std::fs::read_to_string(&abs).ok()?;
201    if contents.len() > MAX_INLINE_BYTES {
202        // Truncate on a char boundary at or below the cap.
203        let mut cut = MAX_INLINE_BYTES;
204        while cut > 0 && !contents.is_char_boundary(cut) {
205            cut -= 1;
206        }
207        contents.truncate(cut);
208        contents.push_str("\n…[file truncated: exceeded inline size limit]\n");
209    }
210    Some(InlinedFile {
211        path: rel.to_path_buf(),
212        contents,
213    })
214}
215
216#[cfg(test)]
217mod graph_tests {
218    use super::*;
219    use rinne_types::graph::{CodeGraph, Neighborhood, SymbolRef};
220
221    struct FakeGraph;
222    impl CodeGraph for FakeGraph {
223        fn neighborhood(&self, symbol: &str) -> Option<Neighborhood> {
224            (symbol == "HttpTransport").then(|| Neighborhood {
225                definition: SymbolRef {
226                    name: "HttpTransport".into(),
227                    file: "t.rs".into(),
228                    line: 10,
229                    end_line: 10,
230                },
231                callers: vec![SymbolRef {
232                    name: "send".into(),
233                    file: "s.rs".into(),
234                    line: 3,
235                    end_line: 3,
236                }],
237                callees: vec![],
238                imports: vec![],
239                stale: false,
240            })
241        }
242        fn resolve_in_file(&self, _f: &str, _n: &str) -> Option<SymbolRef> {
243            None
244        }
245        fn symbol_names(&self) -> Vec<String> {
246            vec!["HttpTransport".into()]
247        }
248    }
249
250    #[test]
251    fn attaches_neighborhood_for_exact_identifier_in_instruction() {
252        let names = FakeGraph.symbol_names();
253        let picked = resolve_symbols(&FakeGraph, "add retry to HttpTransport", &[], &names);
254        assert_eq!(picked, vec!["HttpTransport".to_string()]);
255    }
256
257    #[test]
258    fn skips_short_names_below_min_ident_len() {
259        // `new`/`run` are shorter than MIN_IDENT_LEN (4) and are skipped by the
260        // length filter — NOT by any common-name denylist (which Stage 1 removed).
261        let names = vec!["new".to_string(), "run".to_string()];
262        let picked = resolve_symbols(&FakeGraph, "run the new thing", &[], &names);
263        assert!(picked.is_empty());
264    }
265
266    #[test]
267    fn keeps_formerly_denylisted_long_names() {
268        // Stage 1 removed the COMMON_NAMES denylist: a 4+ char name like `build`
269        // is now KEPT (to be disambiguated downstream by the mentioned-file hint),
270        // whereas the old denylist suppressed it wholesale.
271        let names = vec!["build".to_string()];
272        let picked = resolve_symbols(&FakeGraph, "call build to assemble", &[], &names);
273        assert_eq!(picked, vec!["build".to_string()]);
274    }
275
276    /// A graph where `build` is defined in two files, for testing the
277    /// mentioned-file disambiguation in `neighborhoods_for`.
278    struct AmbiguousGraph;
279    impl AmbiguousGraph {
280        fn nb(file: &str) -> Neighborhood {
281            Neighborhood {
282                definition: SymbolRef {
283                    name: "build".into(),
284                    file: file.into(),
285                    line: 1,
286                    end_line: 1,
287                },
288                callers: vec![],
289                callees: vec![],
290                imports: vec![],
291                stale: false,
292            }
293        }
294    }
295    impl CodeGraph for AmbiguousGraph {
296        fn neighborhood(&self, symbol: &str) -> Option<Neighborhood> {
297            self.neighborhood_all(symbol).into_iter().next()
298        }
299        fn neighborhood_all(&self, symbol: &str) -> Vec<Neighborhood> {
300            if symbol == "build" {
301                vec![Self::nb("assembler.rs"), Self::nb("blackboard.rs")]
302            } else {
303                vec![]
304            }
305        }
306        fn resolve_in_file(&self, _f: &str, _n: &str) -> Option<SymbolRef> {
307            None
308        }
309        fn symbol_names(&self) -> Vec<String> {
310            vec!["build".into()]
311        }
312    }
313
314    #[test]
315    fn mentioned_file_disambiguates_among_same_name_defs() {
316        // Mention assembler.rs → only that file's `build` is attached, not blackboard's.
317        let mentioned = vec![std::path::PathBuf::from("assembler.rs")];
318        let got = neighborhoods_for(&AmbiguousGraph, "build", &mentioned);
319        assert_eq!(got.len(), 1, "hint must narrow to the mentioned file");
320        assert_eq!(got[0].definition.file, "assembler.rs");
321    }
322
323    #[test]
324    fn without_hint_attaches_all_same_name_defs() {
325        // No mention → attach BOTH, so the worker sees the full set rather than
326        // one silently-chosen (possibly wrong) anchor. This is the core Stage 1 fix.
327        let got = neighborhoods_for(&AmbiguousGraph, "build", &[]);
328        let mut files: Vec<&str> = got.iter().map(|n| n.definition.file.as_str()).collect();
329        files.sort_unstable();
330        assert_eq!(files, vec!["assembler.rs", "blackboard.rs"]);
331    }
332}