use std::path::{Path, PathBuf};
use std::sync::Arc;
use rinne_graph::{indexer::Indexer, Graph};
use crate::dag::Plan;
use crate::state::{NodeStatus, State, UsageRow};
use crate::worker::Usage;
use crate::{Result, RinneError, BLACKBOARD_DIR};
pub struct Blackboard {
root: PathBuf,
workspace: PathBuf,
state: State,
graph: Option<Arc<Graph>>,
indexer: Option<Indexer>,
}
impl Blackboard {
pub fn open(workspace: &Path) -> Result<Self> {
Self::open_with(workspace, true)
}
pub fn open_with(workspace: &Path, enable_graph: bool) -> Result<Self> {
let root = workspace.join(BLACKBOARD_DIR);
for sub in ["", "context", "artifacts", "transcripts"] {
std::fs::create_dir_all(root.join(sub))?;
}
let db_path = root.join("state.db");
let state = State::open(&db_path)?;
let (graph, indexer) = if enable_graph {
match Graph::open(&db_path, workspace) {
Ok(g) => {
let g = Arc::new(g);
let idx = Indexer::spawn(Arc::clone(&g), workspace.to_path_buf());
(Some(g), Some(idx))
}
Err(e) => {
tracing::warn!("blackboard: failed to open code graph: {e}");
(None, None)
}
}
} else {
(None, None)
};
Ok(Self {
root,
workspace: workspace.to_path_buf(),
state,
graph,
indexer,
})
}
pub fn graph_enabled(&self) -> bool {
self.graph.is_some()
}
pub fn concrete_graph(&self) -> Option<Arc<Graph>> {
self.graph.clone()
}
pub fn reindex_file(&self, abs: &Path) {
if let Some(idx) = &self.indexer {
idx.ensure_now(abs);
}
}
pub fn index_repo(&self) -> usize {
self.indexer
.as_ref()
.map(|idx| idx.index_all())
.unwrap_or(0)
}
pub fn exists(workspace: &Path) -> bool {
workspace.join(BLACKBOARD_DIR).join("plan.json").is_file()
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn workspace(&self) -> &Path {
&self.workspace
}
pub fn plan_path(&self) -> PathBuf {
self.root.join("plan.json")
}
pub fn state_db_path(&self) -> PathBuf {
self.root.join("state.db")
}
pub fn progress_path(&self) -> PathBuf {
self.root.join("progress.md")
}
pub fn load_plan(&self) -> Result<Plan> {
let path = self.plan_path();
let bytes = std::fs::read(&path).map_err(|_| RinneError::NotFound(path.clone()))?;
let plan: Plan = serde_json::from_slice(&bytes)?;
plan.validate()?;
Ok(plan)
}
pub fn save_plan(&self, plan: &Plan) -> Result<()> {
let bytes = serde_json::to_vec_pretty(plan)?;
atomic_write(&self.plan_path(), &bytes)
}
pub fn reset_run(&self) -> Result<()> {
self.state.reset()?;
let _ = std::fs::remove_file(self.progress_path());
Ok(())
}
pub fn ensure_node(&self, node_id: &str) -> Result<()> {
self.state.ensure_node(node_id)
}
pub fn set_status(&self, node_id: &str, status: NodeStatus) -> Result<()> {
self.state.set_status(node_id, status)
}
pub fn set_worker(&self, node_id: &str, worker: &str) -> Result<()> {
self.state.set_worker(node_id, worker)
}
pub fn status(&self, node_id: &str) -> Result<NodeStatus> {
self.state.status(node_id)
}
pub fn worker(&self, node_id: &str) -> Result<Option<String>> {
self.state.worker(node_id)
}
pub fn incr_iteration(&self, node_id: &str) -> Result<u32> {
self.state.incr_iteration(node_id)
}
pub fn iterations(&self, node_id: &str) -> Result<u32> {
self.state.iterations(node_id)
}
pub fn record_usage(&self, node_id: &str, worker: &str, usage: &Usage) -> Result<()> {
self.state.record_usage(node_id, worker, usage)
}
pub fn total_iterations(&self) -> Result<u32> {
self.state.total_iterations()
}
pub fn total_usage(&self) -> Result<Usage> {
self.state.total_usage()
}
pub fn usage_rows(&self) -> Result<Vec<UsageRow>> {
self.state.usage_rows()
}
pub fn set_meta(&self, key: &str, value: &str) -> Result<()> {
self.state.set_meta(key, value)
}
pub fn meta(&self, key: &str) -> Result<Option<String>> {
self.state.meta(key)
}
pub fn artifact_path(&self, name: &str) -> PathBuf {
let name = name.strip_prefix("artifacts/").unwrap_or(name);
self.root.join("artifacts").join(name)
}
pub fn write_artifact(&self, name: &str, contents: &str) -> Result<()> {
let path = self.artifact_path(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
atomic_write(&path, contents.as_bytes())
}
pub fn read_artifact(&self, name: &str) -> Result<String> {
let path = self.artifact_path(name);
std::fs::read_to_string(&path).map_err(|_| RinneError::NotFound(path))
}
pub fn artifact_exists(&self, name: &str) -> bool {
self.artifact_path(name).is_file()
}
pub fn write_transcript(&self, node_id: &str, contents: &str) -> Result<()> {
let path = self.root.join("transcripts").join(format!("{node_id}.txt"));
atomic_write(&path, contents.as_bytes())
}
pub fn write_context(&self, node_id: &str, contents: &str) -> Result<()> {
let path = self.root.join("context").join(format!("{node_id}.json"));
atomic_write(&path, contents.as_bytes())
}
pub fn append_progress(&self, line: &str) -> Result<()> {
use std::io::Write;
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(self.progress_path())?;
writeln!(f, "{line}")?;
Ok(())
}
}
impl rinne_types::Blackboard for Blackboard {
fn workspace(&self) -> &Path {
Blackboard::workspace(self)
}
fn progress_path(&self) -> PathBuf {
Blackboard::progress_path(self)
}
fn save_plan(&self, plan: &Plan) -> Result<()> {
Blackboard::save_plan(self, plan)
}
fn write_artifact(&self, name: &str, contents: &str) -> Result<()> {
Blackboard::write_artifact(self, name, contents)
}
fn read_artifact(&self, name: &str) -> Result<String> {
Blackboard::read_artifact(self, name)
}
fn artifact_exists(&self, name: &str) -> bool {
Blackboard::artifact_exists(self, name)
}
fn write_transcript(&self, node_id: &str, contents: &str) -> Result<()> {
Blackboard::write_transcript(self, node_id, contents)
}
fn write_context(&self, node_id: &str, contents: &str) -> Result<()> {
Blackboard::write_context(self, node_id, contents)
}
fn append_progress(&self, line: &str) -> Result<()> {
Blackboard::append_progress(self, line)
}
fn ensure_node(&self, node_id: &str) -> Result<()> {
Blackboard::ensure_node(self, node_id)
}
fn set_status(&self, node_id: &str, status: NodeStatus) -> Result<()> {
Blackboard::set_status(self, node_id, status)
}
fn set_worker(&self, node_id: &str, worker: &str) -> Result<()> {
Blackboard::set_worker(self, node_id, worker)
}
fn status(&self, node_id: &str) -> Result<NodeStatus> {
Blackboard::status(self, node_id)
}
fn incr_iteration(&self, node_id: &str) -> Result<u32> {
Blackboard::incr_iteration(self, node_id)
}
fn iterations(&self, node_id: &str) -> Result<u32> {
Blackboard::iterations(self, node_id)
}
fn record_usage(&self, node_id: &str, worker: &str, usage: &Usage) -> Result<()> {
Blackboard::record_usage(self, node_id, worker, usage)
}
fn total_iterations(&self) -> Result<u32> {
Blackboard::total_iterations(self)
}
fn total_usage(&self) -> Result<Usage> {
Blackboard::total_usage(self)
}
fn set_meta(&self, key: &str, value: &str) -> Result<()> {
Blackboard::set_meta(self, key, value)
}
fn meta(&self, key: &str) -> Result<Option<String>> {
Blackboard::meta(self, key)
}
fn code_graph(&self) -> Option<&dyn rinne_types::graph::CodeGraph> {
self.graph
.as_deref()
.map(|g| g as &dyn rinne_types::graph::CodeGraph)
}
fn reindex_file(&self, abs: &Path) {
Blackboard::reindex_file(self, abs)
}
}
pub fn require_plan(blackboard: &Blackboard) -> Result<Plan> {
if !Blackboard::exists(blackboard.workspace()) {
return Err(RinneError::Plan(
"no plan.json in .rinne/ — nothing to run or resume".into(),
));
}
blackboard.load_plan()
}
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes)?;
std::fs::rename(&tmp, path)?;
Ok(())
}
#[cfg(test)]
mod graph_wiring {
use super::*;
#[test]
fn blackboard_exposes_code_graph() {
let dir = std::env::temp_dir().join(format!("rinne-bb-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let bb = Blackboard::open(&dir).unwrap();
let via_trait = (&bb as &dyn rinne_types::Blackboard).code_graph();
assert_eq!(bb.graph_enabled(), via_trait.is_some());
let bb_no_graph = Blackboard::open_with(&dir, false).unwrap();
assert!(!bb_no_graph.graph_enabled());
assert!((&bb_no_graph as &dyn rinne_types::Blackboard)
.code_graph()
.is_none());
let _ = std::fs::remove_dir_all(&dir);
}
}