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 COMMON_NAMES: &[&str] = &["new", "run", "get", "set", "build", "main", "init", "from", "into"];
17const MIN_IDENT_LEN: usize = 4;
18
19pub 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 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 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
54pub 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 pub fn build(
75 &self,
76 node: &Node,
77 family: WorkerFamily,
78 critique: Option<String>,
79 ) -> Result<ContextPacket> {
80 let mentioned = &self.plan.mentioned;
84 let input_artifacts: Vec<String> = node
85 .inputs
86 .iter()
87 .filter(|i| i.as_str() != "diff") .cloned()
89 .collect();
90
91 let mut packet = ContextPacket {
92 critique,
93 ..Default::default()
94 };
95
96 match family {
97 WorkerFamily::Harness => {
98 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 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 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
146fn artifact_rel_path(name: &str) -> PathBuf {
149 Path::new(BLACKBOARD_DIR).join("artifacts").join(name)
150}
151
152const MAX_INLINE_BYTES: usize = 256 * 1024;
156
157fn 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 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}