1#![forbid(unsafe_code)]
33#![deny(clippy::all)]
34
35use std::io::Write;
36use std::path::{Path, PathBuf};
37
38pub mod catalyst;
39pub mod cli;
40pub mod clients;
41pub mod date;
42#[cfg(test)]
43mod golden_tests;
44pub mod oppscan;
45pub mod py;
46pub mod report;
47pub mod survivor;
48#[cfg(test)]
49mod testenv;
50pub mod theses;
51pub mod unlocks;
52
53pub use py::Json;
54
55pub const LEDGER: &str = "opportunity-ledger.json";
57pub const VALUE_INDEX: &str = "value-index.json";
59pub const UNLOCK_INDEX: &str = "unlock-index.json";
61
62pub const UA_SCAN: &str = "oppscan/0.1";
64pub const UA_BROWSER_SCAN: &str = "Mozilla/5.0 oppscan";
65
66#[derive(Debug, Clone, PartialEq)]
67pub enum ResearchError {
68 Exit(String),
70 Config(String),
72 Failed(String),
74}
75
76impl std::fmt::Display for ResearchError {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 match self {
79 ResearchError::Exit(m) | ResearchError::Config(m) | ResearchError::Failed(m) => {
80 write!(f, "{m}")
81 }
82 }
83 }
84}
85
86impl std::error::Error for ResearchError {}
87
88pub type Result<T> = std::result::Result<T, ResearchError>;
89
90pub trait Fetch {
92 fn get_json(
93 &self,
94 url: &str,
95 user_agent: &str,
96 timeout_s: u64,
97 ) -> std::result::Result<Json, String>;
98}
99
100#[derive(Debug, Clone, PartialEq)]
101pub enum SearchError {
102 NoKey,
104 Failed(String),
106}
107
108pub trait Search {
110 fn search(&self, body: &str) -> std::result::Result<Json, SearchError>;
111}
112
113pub trait Llm {
115 fn ask(&self, prompt: &str) -> std::result::Result<String, String>;
116}
117
118pub trait Console {
120 fn out(&mut self, line: &str);
121 fn err(&mut self, line: &str);
122}
123
124pub struct StdConsole;
126
127impl Console for StdConsole {
128 fn out(&mut self, line: &str) {
129 let mut o = std::io::stdout().lock();
130 let _ = writeln!(o, "{line}");
131 }
132 fn err(&mut self, line: &str) {
133 let mut e = std::io::stderr().lock();
134 let _ = writeln!(e, "{line}");
135 }
136}
137
138#[derive(Debug, Default, Clone)]
140pub struct BufConsole {
141 pub out: String,
142 pub err: String,
143}
144
145impl Console for BufConsole {
146 fn out(&mut self, line: &str) {
147 self.out.push_str(line);
148 self.out.push('\n');
149 }
150 fn err(&mut self, line: &str) {
151 self.err.push_str(line);
152 self.err.push('\n');
153 }
154}
155
156#[derive(Debug, Clone, PartialEq)]
158pub struct Paths {
159 pub dir: PathBuf,
160}
161
162impl Paths {
163 pub fn new(dir: impl Into<PathBuf>) -> Self {
164 Paths { dir: dir.into() }
165 }
166 pub fn ledger(&self) -> PathBuf {
167 self.dir.join(LEDGER)
168 }
169 pub fn value_index(&self) -> PathBuf {
170 self.dir.join(VALUE_INDEX)
171 }
172 pub fn unlock_index(&self) -> PathBuf {
173 self.dir.join(UNLOCK_INDEX)
174 }
175}
176
177pub fn read_json(path: &Path) -> Result<Json> {
179 let text = std::fs::read_to_string(path)
180 .map_err(|e| ResearchError::Failed(format!("cannot read {}: {e}", path.display())))?;
181 py::parse(&text)
182 .map_err(|e| ResearchError::Failed(format!("{} is not valid JSON: {e}", path.display())))
183}
184
185pub fn write_json(path: &Path, value: &Json) -> Result<()> {
188 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
189 std::fs::create_dir_all(parent).map_err(|e| {
190 ResearchError::Failed(format!("cannot create {}: {e}", parent.display()))
191 })?;
192 }
193 let tmp = path.with_extension(format!("json.tmp.{}", std::process::id()));
194 std::fs::write(&tmp, py::dumps_indent(value, 2))
195 .map_err(|e| ResearchError::Failed(format!("cannot write {}: {e}", tmp.display())))?;
196 std::fs::rename(&tmp, path).map_err(|e| {
197 let _ = std::fs::remove_file(&tmp);
198 ResearchError::Failed(format!("cannot replace {}: {e}", path.display()))
199 })
200}
201
202pub fn read_ledger(paths: &Paths) -> Result<Vec<Json>> {
204 match read_json(&paths.ledger())? {
205 Json::Arr(a) => Ok(a),
206 _ => Err(ResearchError::Failed(format!(
207 "{} is not a list",
208 paths.ledger().display()
209 ))),
210 }
211}
212
213pub fn write_ledger(paths: &Paths, cands: &[Json]) -> Result<()> {
214 write_json(&paths.ledger(), &Json::Arr(cands.to_vec()))
215}
216
217pub fn by_dislocation(cands: &[Json]) -> Vec<usize> {
220 let mut idx: Vec<usize> = (0..cands.len()).collect();
221 let score = |i: usize| {
222 cands[i]
223 .get("dislocation_score")
224 .and_then(Json::as_f64)
225 .unwrap_or(0.0)
226 };
227 idx.sort_by(|&a, &b| {
228 score(b)
229 .partial_cmp(&score(a))
230 .unwrap_or(std::cmp::Ordering::Equal)
231 });
232 idx
233}
234
235pub struct Ctx<'a> {
237 pub paths: Paths,
238 pub fetch: &'a dyn Fetch,
239 pub search: &'a dyn Search,
240 pub llm: Option<&'a dyn Llm>,
242 pub today: date::Date,
244}
245
246pub fn no_llm() -> ResearchError {
248 ResearchError::Config(
249 "no LLM command configured: set research.llm.command in the config \
250 (the spend cap research.llm.max_budget_usd is always passed to it)"
251 .into(),
252 )
253}