1use 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
18pub 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 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 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
53fn 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
86pub 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 pub fn build(
111 &self,
112 node: &Node,
113 family: WorkerFamily,
114 critique: Option<String>,
115 ) -> Result<ContextPacket> {
116 let mentioned = &self.plan.mentioned;
120 let input_artifacts: Vec<String> = node
121 .inputs
122 .iter()
123 .filter(|i| i.as_str() != "diff") .cloned()
125 .collect();
126
127 let mut packet = ContextPacket {
128 critique,
129 ..Default::default()
130 };
131
132 match family {
133 WorkerFamily::Harness => {
134 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 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 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
180fn artifact_rel_path(name: &str) -> PathBuf {
183 Path::new(BLACKBOARD_DIR).join("artifacts").join(name)
184}
185
186const MAX_INLINE_BYTES: usize = 256 * 1024;
190
191fn 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 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 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 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 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 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 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}