spark-hive
Multi-agent swarm coordination and peer routing engine
Brought by drakestapleton
spark-hive / src / store.rs
| 1 | use chrono::Utc; |
| 2 | use rusqlite::{params, Connection, OptionalExtension}; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use std::collections::HashSet; |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | use std::sync::Mutex; |
| 7 | use thiserror::Error; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | use crate::geometry::{hex_distance, HexCoord, HEX_DIRECTIONS, HEX_DIRECTION_LABELS}; |
| 11 | |
| 12 | #[derive(Debug, Error)] |
| 13 | pub enum HiveError { |
| 14 | #[error("Coordinate ({q}, {r}) is already occupied by comb '{comb_id}'")] |
| 15 | Collision { q: i32, r: i32, comb_id: String }, |
| 16 | #[error("Parent comb '{0}' not found")] |
| 17 | ParentNotFound(String), |
| 18 | #[error("SQLite database error: {0}")] |
| 19 | Db(#[from] rusqlite::Error), |
| 20 | #[error("Invalid input: {0}")] |
| 21 | InvalidInput(String), |
| 22 | #[error("Forge task '{0}' not found")] |
| 23 | TaskNotFound(String), |
| 24 | #[error("Forge task '{task_id}' is already claimed by '{claimed_by}'")] |
| 25 | TaskAlreadyClaimed { task_id: String, claimed_by: String }, |
| 26 | #[error("Unauthorized: task '{task_id}' is leased to '{claimed_by}', not '{agent_id}'")] |
| 27 | TaskUnauthorized { task_id: String, claimed_by: String, agent_id: String }, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, Deserialize)] |
| 31 | pub struct CreateForgeTaskInput { |
| 32 | pub project: String, |
| 33 | pub module: String, |
| 34 | pub ring: usize, |
| 35 | pub title: String, |
| 36 | pub description: String, |
| 37 | pub parent_comb_id: Option<String>, |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 41 | pub struct ForgeTask { |
| 42 | pub id: String, |
| 43 | pub comb_id: String, |
| 44 | pub project: String, |
| 45 | pub module: String, |
| 46 | pub ring: usize, |
| 47 | pub q: i32, |
| 48 | pub r: i32, |
| 49 | pub title: String, |
| 50 | pub status: String, |
| 51 | pub claimed_by: Option<String>, |
| 52 | pub expires_at: Option<String>, |
| 53 | pub worktree_path: Option<String>, |
| 54 | pub created_at: String, |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 58 | pub struct HiveComb { |
| 59 | pub id: String, |
| 60 | pub q: i32, |
| 61 | pub r: i32, |
| 62 | pub author: String, |
| 63 | pub role: String, |
| 64 | pub content: String, |
| 65 | pub intent: String, |
| 66 | pub parent_id: Option<String>, |
| 67 | pub created_at: String, |
| 68 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 69 | pub neighbors: Vec<NeighborLink>, |
| 70 | } |
| 71 | |
| 72 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 73 | pub struct NeighborLink { |
| 74 | pub id: String, |
| 75 | pub q: i32, |
| 76 | pub r: i32, |
| 77 | pub direction: usize, |
| 78 | pub direction_label: String, |
| 79 | } |
| 80 | |
| 81 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 82 | pub struct BoundingBox { |
| 83 | pub min_q: i32, |
| 84 | pub max_q: i32, |
| 85 | pub min_r: i32, |
| 86 | pub max_r: i32, |
| 87 | pub count: usize, |
| 88 | pub radius: i32, |
| 89 | pub revision: usize, |
| 90 | pub message_count: usize, |
| 91 | } |
| 92 | |
| 93 | #[derive(Debug, Clone, Deserialize)] |
| 94 | pub struct PlaceCombInput { |
| 95 | pub q: Option<i32>, |
| 96 | pub r: Option<i32>, |
| 97 | pub author: String, |
| 98 | pub role: Option<String>, |
| 99 | pub content: String, |
| 100 | pub intent: Option<String>, |
| 101 | pub parent_id: Option<String>, |
| 102 | } |
| 103 | |
| 104 | pub struct CombStore { |
| 105 | conn: Mutex<Connection>, |
| 106 | path: PathBuf, |
| 107 | } |
| 108 | |
| 109 | impl CombStore { |
| 110 | pub fn open(path: &Path) -> Result<Self, HiveError> { |
| 111 | if let Some(parent) = path.parent() { |
| 112 | let _ = std::fs::create_dir_all(parent); |
| 113 | } |
| 114 | let conn = Connection::open(path)?; |
| 115 | let _: Result<String, _> = conn.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)); |
| 116 | conn.execute_batch("PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?; |
| 117 | conn.busy_timeout(std::time::Duration::from_millis(5000))?; |
| 118 | let store = Self { |
| 119 | conn: Mutex::new(conn), |
| 120 | path: path.to_path_buf(), |
| 121 | }; |
| 122 | store.init_schema()?; |
| 123 | Ok(store) |
| 124 | } |
| 125 | |
| 126 | pub fn open_default() -> Result<Self, HiveError> { |
| 127 | let path_str = std::env::var("HIVE_DB_PATH") |
| 128 | .unwrap_or_else(|_| "/home/drakestapleton/.config/cortex/hive.db".to_string()); |
| 129 | let path = PathBuf::from(path_str); |
| 130 | Self::open(&path) |
| 131 | } |
| 132 | |
| 133 | pub fn open_in_memory() -> Result<Self, HiveError> { |
| 134 | let conn = Connection::open_in_memory()?; |
| 135 | let store = Self { |
| 136 | conn: Mutex::new(conn), |
| 137 | path: PathBuf::from(":memory:"), |
| 138 | }; |
| 139 | store.init_schema()?; |
| 140 | Ok(store) |
| 141 | } |
| 142 | |
| 143 | pub fn path(&self) -> &Path { |
| 144 | &self.path |
| 145 | } |
| 146 | |
| 147 | fn init_schema(&self) -> Result<(), HiveError> { |
| 148 | let conn = self.conn.lock().unwrap(); |
| 149 | conn.execute_batch( |
| 150 | "CREATE TABLE IF NOT EXISTS hive_combs ( |
| 151 | id TEXT PRIMARY KEY, |
| 152 | q INTEGER NOT NULL, |
| 153 | r INTEGER NOT NULL, |
| 154 | author TEXT NOT NULL, |
| 155 | role TEXT NOT NULL DEFAULT 'agent', |
| 156 | content TEXT NOT NULL, |
| 157 | intent TEXT NOT NULL DEFAULT 'independent', |
| 158 | parent_id TEXT, |
| 159 | created_at TEXT NOT NULL, |
| 160 | UNIQUE(q, r) |
| 161 | ); |
| 162 | CREATE INDEX IF NOT EXISTS idx_hive_combs_qr ON hive_combs(q, r); |
| 163 | CREATE INDEX IF NOT EXISTS idx_hive_combs_created ON hive_combs(created_at); |
| 164 | CREATE INDEX IF NOT EXISTS idx_hive_combs_parent ON hive_combs(parent_id); |
| 165 | CREATE TABLE IF NOT EXISTS forge_tasks ( |
| 166 | id TEXT PRIMARY KEY, |
| 167 | comb_id TEXT NOT NULL, |
| 168 | project TEXT NOT NULL, |
| 169 | module TEXT NOT NULL, |
| 170 | ring INTEGER NOT NULL, |
| 171 | q INTEGER NOT NULL, |
| 172 | r INTEGER NOT NULL, |
| 173 | title TEXT NOT NULL, |
| 174 | status TEXT NOT NULL DEFAULT 'open', |
| 175 | claimed_by TEXT, |
| 176 | expires_at TEXT, |
| 177 | worktree_path TEXT, |
| 178 | created_at TEXT NOT NULL |
| 179 | ); |
| 180 | CREATE INDEX IF NOT EXISTS idx_forge_tasks_status ON forge_tasks(status); |
| 181 | CREATE INDEX IF NOT EXISTS idx_forge_tasks_project ON forge_tasks(project);" |
| 182 | )?; |
| 183 | |
| 184 | // Seed genesis comb if table is empty |
| 185 | let count: i64 = conn.query_row("SELECT COUNT(*) FROM hive_combs", [], |r| r.get(0))?; |
| 186 | if count == 0 { |
| 187 | let genesis_id = "comb-genesis-00000000"; |
| 188 | let now = Utc::now().to_rfc3339(); |
| 189 | conn.execute( |
| 190 | "INSERT INTO hive_combs (id, q, r, author, role, content, intent, parent_id, created_at) |
| 191 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", |
| 192 | params![ |
| 193 | genesis_id, |
| 194 | 0, |
| 195 | 0, |
| 196 | "AIEN Genesis", |
| 197 | "coordinator", |
| 198 | "AIEN Sovereign Hive Online ยท Hexagonal Honeycomb Active", |
| 199 | "independent", |
| 200 | None::<String>, |
| 201 | now, |
| 202 | ], |
| 203 | )?; |
| 204 | } |
| 205 | |
| 206 | Ok(()) |
| 207 | } |
| 208 | |
| 209 | pub fn get_comb(&self, id: &str) -> Result<Option<HiveComb>, HiveError> { |
| 210 | let conn = self.conn.lock().unwrap(); |
| 211 | let mut stmt = conn.prepare( |
| 212 | "SELECT id, q, r, author, role, content, intent, parent_id, created_at |
| 213 | FROM hive_combs WHERE id = ?1" |
| 214 | )?; |
| 215 | let row = stmt.query_row(params![id], |r| { |
| 216 | Ok(HiveComb { |
| 217 | id: r.get(0)?, |
| 218 | q: r.get(1)?, |
| 219 | r: r.get(2)?, |
| 220 | author: r.get(3)?, |
| 221 | role: r.get(4)?, |
| 222 | content: r.get(5)?, |
| 223 | intent: r.get(6)?, |
| 224 | parent_id: r.get(7)?, |
| 225 | created_at: r.get(8)?, |
| 226 | neighbors: Vec::new(), |
| 227 | }) |
| 228 | }).optional()?; |
| 229 | |
| 230 | Ok(row) |
| 231 | } |
| 232 | |
| 233 | pub fn get_comb_at(&self, q: i32, r: i32) -> Result<Option<HiveComb>, HiveError> { |
| 234 | let conn = self.conn.lock().unwrap(); |
| 235 | let mut stmt = conn.prepare( |
| 236 | "SELECT id, q, r, author, role, content, intent, parent_id, created_at |
| 237 | FROM hive_combs WHERE q = ?1 AND r = ?2" |
| 238 | )?; |
| 239 | let row = stmt.query_row(params![q, r], |row| { |
| 240 | Ok(HiveComb { |
| 241 | id: row.get(0)?, |
| 242 | q: row.get(1)?, |
| 243 | r: row.get(2)?, |
| 244 | author: row.get(3)?, |
| 245 | role: row.get(4)?, |
| 246 | content: row.get(5)?, |
| 247 | intent: row.get(6)?, |
| 248 | parent_id: row.get(7)?, |
| 249 | created_at: row.get(8)?, |
| 250 | neighbors: Vec::new(), |
| 251 | }) |
| 252 | }).optional()?; |
| 253 | |
| 254 | Ok(row) |
| 255 | } |
| 256 | |
| 257 | pub fn get_cells(&self) -> Result<(Vec<HiveComb>, BoundingBox), HiveError> { |
| 258 | let conn = self.conn.lock().unwrap(); |
| 259 | let mut stmt = conn.prepare( |
| 260 | "SELECT id, q, r, author, role, content, intent, parent_id, created_at |
| 261 | FROM hive_combs ORDER BY created_at ASC" |
| 262 | )?; |
| 263 | |
| 264 | let rows = stmt.query_map([], |r| { |
| 265 | Ok(HiveComb { |
| 266 | id: r.get(0)?, |
| 267 | q: r.get(1)?, |
| 268 | r: r.get(2)?, |
| 269 | author: r.get(3)?, |
| 270 | role: r.get(4)?, |
| 271 | content: r.get(5)?, |
| 272 | intent: r.get(6)?, |
| 273 | parent_id: r.get(7)?, |
| 274 | created_at: r.get(8)?, |
| 275 | neighbors: Vec::new(), |
| 276 | }) |
| 277 | })?; |
| 278 | |
| 279 | let mut combs = Vec::new(); |
| 280 | let mut min_q = 0; |
| 281 | let mut max_q = 0; |
| 282 | let mut min_r = 0; |
| 283 | let mut max_r = 0; |
| 284 | let mut max_radius = 5; |
| 285 | |
| 286 | for (i, comb_res) in rows.enumerate() { |
| 287 | let comb = comb_res?; |
| 288 | if i == 0 { |
| 289 | min_q = comb.q; |
| 290 | max_q = comb.q; |
| 291 | min_r = comb.r; |
| 292 | max_r = comb.r; |
| 293 | } else { |
| 294 | min_q = min_q.min(comb.q); |
| 295 | max_q = max_q.max(comb.q); |
| 296 | min_r = min_r.min(comb.r); |
| 297 | max_r = max_r.max(comb.r); |
| 298 | } |
| 299 | let d = hex_distance(comb.q, comb.r, 0, 0); |
| 300 | if d > max_radius { |
| 301 | max_radius = d; |
| 302 | } |
| 303 | combs.push(comb); |
| 304 | } |
| 305 | |
| 306 | // Build coordinate lookup table for neighbor linking |
| 307 | let coord_map: std::collections::HashMap<(i32, i32), (String, usize)> = combs |
| 308 | .iter() |
| 309 | .enumerate() |
| 310 | .map(|(idx, c)| ((c.q, c.r), (c.id.clone(), idx))) |
| 311 | .collect(); |
| 312 | |
| 313 | // Calculate neighbor links for each comb |
| 314 | for comb in &mut combs { |
| 315 | let mut neighbors = Vec::new(); |
| 316 | for (dir_idx, (dq, dr)) in HEX_DIRECTIONS.iter().enumerate() { |
| 317 | let n_coord = (comb.q + dq, comb.r + dr); |
| 318 | if let Some((n_id, _)) = coord_map.get(&n_coord) { |
| 319 | neighbors.push(NeighborLink { |
| 320 | id: n_id.clone(), |
| 321 | q: n_coord.0, |
| 322 | r: n_coord.1, |
| 323 | direction: dir_idx, |
| 324 | direction_label: HEX_DIRECTION_LABELS[dir_idx].to_string(), |
| 325 | }); |
| 326 | } |
| 327 | } |
| 328 | comb.neighbors = neighbors; |
| 329 | } |
| 330 | |
| 331 | let count = combs.len(); |
| 332 | let bounds = BoundingBox { |
| 333 | min_q, |
| 334 | max_q, |
| 335 | min_r, |
| 336 | max_r, |
| 337 | count, |
| 338 | radius: max_radius, |
| 339 | revision: count, |
| 340 | message_count: count, |
| 341 | }; |
| 342 | |
| 343 | Ok((combs, bounds)) |
| 344 | } |
| 345 | |
| 346 | /// Finds the first available unoccupied coordinate. |
| 347 | /// If parent_id is given, searches adjacent neighbors of parent first. |
| 348 | pub fn find_free_coordinate(&self, parent_id: Option<&str>) -> Result<HexCoord, HiveError> { |
| 349 | let conn = self.conn.lock().unwrap(); |
| 350 | Self::find_free_coordinate_with_conn(&conn, parent_id) |
| 351 | } |
| 352 | |
| 353 | /// Internal coordinate finder operating under an already locked database connection. |
| 354 | fn find_free_coordinate_with_conn( |
| 355 | conn: &rusqlite::Connection, |
| 356 | parent_id: Option<&str>, |
| 357 | ) -> Result<HexCoord, HiveError> { |
| 358 | let mut stmt = conn.prepare("SELECT q, r FROM hive_combs")?; |
| 359 | let occupied_coords: HashSet<(i32, i32)> = stmt |
| 360 | .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))? |
| 361 | .collect::<Result<HashSet<_>, _>>()?; |
| 362 | |
| 363 | let center = if let Some(pid) = parent_id { |
| 364 | let mut parent_stmt = conn.prepare("SELECT q, r FROM hive_combs WHERE id = ?1")?; |
| 365 | let parent_coord: Option<(i32, i32)> = parent_stmt |
| 366 | .query_row(params![pid], |r| Ok((r.get(0)?, r.get(1)?))) |
| 367 | .optional()?; |
| 368 | |
| 369 | match parent_coord { |
| 370 | Some((pq, pr)) => HexCoord::new(pq, pr), |
| 371 | None => HexCoord::new(0, 0), |
| 372 | } |
| 373 | } else { |
| 374 | HexCoord::new(0, 0) |
| 375 | }; |
| 376 | |
| 377 | // Check center itself first if empty |
| 378 | if !occupied_coords.contains(&(center.q, center.r)) { |
| 379 | return Ok(center); |
| 380 | } |
| 381 | |
| 382 | // 1. Check all 6 immediate neighbors in canonical order |
| 383 | for (dq, dr) in HEX_DIRECTIONS { |
| 384 | let cand = (center.q + dq, center.r + dr); |
| 385 | if !occupied_coords.contains(&cand) { |
| 386 | return Ok(HexCoord::new(cand.0, cand.1)); |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | // 2. Search outward rings around center up to radius 50 |
| 391 | for ring_radius in 2..=50 { |
| 392 | let mut current = HexCoord::new( |
| 393 | center.q + HEX_DIRECTIONS[4].0 * ring_radius, |
| 394 | center.r + HEX_DIRECTIONS[4].1 * ring_radius, |
| 395 | ); |
| 396 | for (dir_idx, _) in HEX_DIRECTIONS.iter().enumerate() { |
| 397 | for _ in 0..ring_radius { |
| 398 | if !occupied_coords.contains(&(current.q, current.r)) { |
| 399 | return Ok(current); |
| 400 | } |
| 401 | let next_dir = HEX_DIRECTIONS[dir_idx]; |
| 402 | current = HexCoord::new(current.q + next_dir.0, current.r + next_dir.1); |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | Ok(HexCoord::new(0, 0)) |
| 408 | } |
| 409 | |
| 410 | pub fn place_comb(&self, input: PlaceCombInput) -> Result<HiveComb, HiveError> { |
| 411 | let conn = self.conn.lock().unwrap(); |
| 412 | |
| 413 | let (q, r) = match (input.q, input.r) { |
| 414 | (Some(q), Some(r)) => (q, r), |
| 415 | _ => { |
| 416 | let coord = Self::find_free_coordinate_with_conn(&conn, input.parent_id.as_deref())?; |
| 417 | (coord.q, coord.r) |
| 418 | } |
| 419 | }; |
| 420 | |
| 421 | // 1. Collision check |
| 422 | let mut check_stmt = conn.prepare("SELECT id FROM hive_combs WHERE q = ?1 AND r = ?2")?; |
| 423 | let existing_id: Option<String> = check_stmt.query_row(params![q, r], |row| row.get(0)).optional()?; |
| 424 | if let Some(id) = existing_id { |
| 425 | return Err(HiveError::Collision { q, r, comb_id: id }); |
| 426 | } |
| 427 | |
| 428 | // 2. Neighbor linking |
| 429 | let mut neighbors = Vec::new(); |
| 430 | let mut neighbor_stmt = conn.prepare("SELECT id FROM hive_combs WHERE q = ?1 AND r = ?2")?; |
| 431 | for (dir_idx, (dq, dr)) in HEX_DIRECTIONS.iter().enumerate() { |
| 432 | let n_q = q + dq; |
| 433 | let n_r = r + dr; |
| 434 | if let Some(n_id) = neighbor_stmt.query_row(params![n_q, n_r], |row| row.get(0)).optional()? { |
| 435 | neighbors.push(NeighborLink { |
| 436 | id: n_id, |
| 437 | q: n_q, |
| 438 | r: n_r, |
| 439 | direction: dir_idx, |
| 440 | direction_label: HEX_DIRECTION_LABELS[dir_idx].to_string(), |
| 441 | }); |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | // 3. Verify parent_id if supplied |
| 446 | if let Some(ref pid) = input.parent_id { |
| 447 | let mut parent_check = conn.prepare("SELECT 1 FROM hive_combs WHERE id = ?1")?; |
| 448 | let parent_exists: Option<i32> = parent_check.query_row(params![pid], |_| Ok(1)).optional()?; |
| 449 | if parent_exists.is_none() { |
| 450 | // Parent does not exist yet; accepted as unanchored |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | let id = format!("comb-{}", Uuid::new_v4()); |
| 455 | let role = input.role.unwrap_or_else(|| "agent".to_string()); |
| 456 | let intent = input.intent.unwrap_or_else(|| "independent".to_string()); |
| 457 | let created_at = Utc::now().to_rfc3339(); |
| 458 | |
| 459 | conn.execute( |
| 460 | "INSERT INTO hive_combs (id, q, r, author, role, content, intent, parent_id, created_at) |
| 461 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", |
| 462 | params![ |
| 463 | &id, |
| 464 | q, |
| 465 | r, |
| 466 | &input.author, |
| 467 | &role, |
| 468 | &input.content, |
| 469 | &intent, |
| 470 | &input.parent_id, |
| 471 | &created_at, |
| 472 | ], |
| 473 | )?; |
| 474 | |
| 475 | Ok(HiveComb { |
| 476 | id, |
| 477 | q, |
| 478 | r, |
| 479 | author: input.author, |
| 480 | role, |
| 481 | content: input.content, |
| 482 | intent, |
| 483 | parent_id: input.parent_id, |
| 484 | created_at, |
| 485 | neighbors, |
| 486 | }) |
| 487 | } |
| 488 | |
| 489 | pub fn spawn_forge_project( |
| 490 | &self, |
| 491 | project: &str, |
| 492 | title: &str, |
| 493 | core_spec: &str, |
| 494 | ) -> Result<ForgeTask, HiveError> { |
| 495 | let comb = self.place_comb(PlaceCombInput { |
| 496 | q: None, |
| 497 | r: None, |
| 498 | author: "AIEN-Forge".to_string(), |
| 499 | role: Some("genesis".to_string()), |
| 500 | content: format!("Project [{}] core spec: {}", project, core_spec), |
| 501 | intent: Some("genesis".to_string()), |
| 502 | parent_id: None, |
| 503 | })?; |
| 504 | |
| 505 | let task_id = format!("task-{}-{}", project, &Uuid::new_v4().to_string()[..8]); |
| 506 | let now = Utc::now().to_rfc3339(); |
| 507 | |
| 508 | let conn = self.conn.lock().unwrap(); |
| 509 | conn.execute( |
| 510 | "INSERT INTO forge_tasks (id, comb_id, project, module, ring, q, r, title, status, created_at) |
| 511 | VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6, ?7, 'open', ?8)", |
| 512 | params![ |
| 513 | task_id, |
| 514 | comb.id, |
| 515 | project, |
| 516 | "core", |
| 517 | comb.q, |
| 518 | comb.r, |
| 519 | title, |
| 520 | now, |
| 521 | ], |
| 522 | )?; |
| 523 | |
| 524 | Ok(ForgeTask { |
| 525 | id: task_id, |
| 526 | comb_id: comb.id, |
| 527 | project: project.to_string(), |
| 528 | module: "core".to_string(), |
| 529 | ring: 0, |
| 530 | q: comb.q, |
| 531 | r: comb.r, |
| 532 | title: title.to_string(), |
| 533 | status: "open".to_string(), |
| 534 | claimed_by: None, |
| 535 | expires_at: None, |
| 536 | worktree_path: None, |
| 537 | created_at: now, |
| 538 | }) |
| 539 | } |
| 540 | |
| 541 | pub fn create_forge_task( |
| 542 | &self, |
| 543 | input: CreateForgeTaskInput, |
| 544 | ) -> Result<ForgeTask, HiveError> { |
| 545 | let comb = self.place_comb(PlaceCombInput { |
| 546 | q: None, |
| 547 | r: None, |
| 548 | author: "AIEN-Forge".to_string(), |
| 549 | role: Some("module".to_string()), |
| 550 | content: format!("Task [{}:{}]: {}", input.project, input.module, input.description), |
| 551 | intent: Some("branch".to_string()), |
| 552 | parent_id: input.parent_comb_id.clone().or_else(|| Some("comb-genesis-00000000".to_string())), |
| 553 | })?; |
| 554 | |
| 555 | let task_id = format!("task-{}-{}", input.module, &Uuid::new_v4().to_string()[..8]); |
| 556 | let now = Utc::now().to_rfc3339(); |
| 557 | |
| 558 | let conn = self.conn.lock().unwrap(); |
| 559 | conn.execute( |
| 560 | "INSERT INTO forge_tasks (id, comb_id, project, module, ring, q, r, title, status, created_at) |
| 561 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'open', ?9)", |
| 562 | params![ |
| 563 | task_id, |
| 564 | comb.id, |
| 565 | input.project, |
| 566 | input.module, |
| 567 | input.ring as i64, |
| 568 | comb.q, |
| 569 | comb.r, |
| 570 | input.title, |
| 571 | now, |
| 572 | ], |
| 573 | )?; |
| 574 | |
| 575 | Ok(ForgeTask { |
| 576 | id: task_id, |
| 577 | comb_id: comb.id, |
| 578 | project: input.project, |
| 579 | module: input.module, |
| 580 | ring: input.ring, |
| 581 | q: comb.q, |
| 582 | r: comb.r, |
| 583 | title: input.title, |
| 584 | status: "open".to_string(), |
| 585 | claimed_by: None, |
| 586 | expires_at: None, |
| 587 | worktree_path: None, |
| 588 | created_at: now, |
| 589 | }) |
| 590 | } |
| 591 | |
| 592 | pub fn claim_forge_task( |
| 593 | &self, |
| 594 | task_id: &str, |
| 595 | agent_id: &str, |
| 596 | ttl_secs: u64, |
| 597 | ) -> Result<ForgeTask, HiveError> { |
| 598 | let conn = self.conn.lock().unwrap(); |
| 599 | let mut stmt = conn.prepare( |
| 600 | "SELECT id, comb_id, project, module, ring, q, r, title, status, claimed_by, expires_at, worktree_path, created_at |
| 601 | FROM forge_tasks WHERE id = ?1" |
| 602 | )?; |
| 603 | |
| 604 | let mut row_iter = stmt.query_map(params![task_id], |row| { |
| 605 | Ok(ForgeTask { |
| 606 | id: row.get(0)?, |
| 607 | comb_id: row.get(1)?, |
| 608 | project: row.get(2)?, |
| 609 | module: row.get(3)?, |
| 610 | ring: row.get::<_, i64>(4)? as usize, |
| 611 | q: row.get(5)?, |
| 612 | r: row.get(6)?, |
| 613 | title: row.get(7)?, |
| 614 | status: row.get(8)?, |
| 615 | claimed_by: row.get(9)?, |
| 616 | expires_at: row.get(10)?, |
| 617 | worktree_path: row.get(11)?, |
| 618 | created_at: row.get(12)?, |
| 619 | }) |
| 620 | })?; |
| 621 | |
| 622 | let mut task = match row_iter.next() { |
| 623 | Some(res) => res?, |
| 624 | None => return Err(HiveError::TaskNotFound(task_id.to_string())), |
| 625 | }; |
| 626 | |
| 627 | let now = Utc::now(); |
| 628 | let now_str = now.to_rfc3339(); |
| 629 | |
| 630 | if task.status == "claimed" { |
| 631 | if let Some(ref exp) = task.expires_at { |
| 632 | if exp.as_str() > now_str.as_str() { |
| 633 | if let Some(ref current_claimer) = task.claimed_by { |
| 634 | if current_claimer != agent_id { |
| 635 | return Err(HiveError::TaskAlreadyClaimed { |
| 636 | task_id: task_id.to_string(), |
| 637 | claimed_by: current_claimer.clone(), |
| 638 | }); |
| 639 | } |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | let new_expires = (now + chrono::Duration::seconds(ttl_secs as i64)).to_rfc3339(); |
| 646 | let worktree = format!("/home/drakestapleton/workspace/hive-worktrees/{}", task_id); |
| 647 | |
| 648 | conn.execute( |
| 649 | "UPDATE forge_tasks SET status = 'claimed', claimed_by = ?1, expires_at = ?2, worktree_path = ?3 WHERE id = ?4", |
| 650 | params![agent_id, new_expires, worktree, task_id], |
| 651 | )?; |
| 652 | |
| 653 | task.status = "claimed".to_string(); |
| 654 | task.claimed_by = Some(agent_id.to_string()); |
| 655 | task.expires_at = Some(new_expires); |
| 656 | task.worktree_path = Some(worktree); |
| 657 | |
| 658 | Ok(task) |
| 659 | } |
| 660 | |
| 661 | pub fn heartbeat_forge_task( |
| 662 | &self, |
| 663 | task_id: &str, |
| 664 | agent_id: &str, |
| 665 | ttl_secs: u64, |
| 666 | ) -> Result<(), HiveError> { |
| 667 | let conn = self.conn.lock().unwrap(); |
| 668 | let claimed_by: Option<String> = conn |
| 669 | .query_row( |
| 670 | "SELECT claimed_by FROM forge_tasks WHERE id = ?1", |
| 671 | params![task_id], |
| 672 | |r| r.get(0), |
| 673 | ) |
| 674 | .optional()? |
| 675 | .ok_or_else(|| HiveError::TaskNotFound(task_id.to_string()))?; |
| 676 | |
| 677 | match claimed_by { |
| 678 | Some(ref c) if c == agent_id => { |
| 679 | let new_expires = (Utc::now() + chrono::Duration::seconds(ttl_secs as i64)).to_rfc3339(); |
| 680 | conn.execute( |
| 681 | "UPDATE forge_tasks SET expires_at = ?1 WHERE id = ?2", |
| 682 | params![new_expires, task_id], |
| 683 | )?; |
| 684 | Ok(()) |
| 685 | } |
| 686 | Some(other) => Err(HiveError::TaskUnauthorized { |
| 687 | task_id: task_id.to_string(), |
| 688 | claimed_by: other, |
| 689 | agent_id: agent_id.to_string(), |
| 690 | }), |
| 691 | None => Err(HiveError::TaskUnauthorized { |
| 692 | task_id: task_id.to_string(), |
| 693 | claimed_by: "unclaimed".to_string(), |
| 694 | agent_id: agent_id.to_string(), |
| 695 | }), |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | pub fn reclaim_expired_leases(&self) -> Result<usize, HiveError> { |
| 700 | let conn = self.conn.lock().unwrap(); |
| 701 | let now = Utc::now().to_rfc3339(); |
| 702 | let rows = conn.execute( |
| 703 | "UPDATE forge_tasks SET status = 'open', claimed_by = NULL, expires_at = NULL, worktree_path = NULL |
| 704 | WHERE status = 'claimed' AND expires_at IS NOT NULL AND expires_at < ?1", |
| 705 | params![now], |
| 706 | )?; |
| 707 | Ok(rows) |
| 708 | } |
| 709 | |
| 710 | pub fn submit_forge_task( |
| 711 | &self, |
| 712 | task_id: &str, |
| 713 | agent_id: &str, |
| 714 | _branch: &str, |
| 715 | _pr_url: Option<&str>, |
| 716 | ) -> Result<(), HiveError> { |
| 717 | let conn = self.conn.lock().unwrap(); |
| 718 | let claimed_by: Option<String> = conn |
| 719 | .query_row( |
| 720 | "SELECT claimed_by FROM forge_tasks WHERE id = ?1", |
| 721 | params![task_id], |
| 722 | |r| r.get(0), |
| 723 | ) |
| 724 | .optional()? |
| 725 | .ok_or_else(|| HiveError::TaskNotFound(task_id.to_string()))?; |
| 726 | |
| 727 | match claimed_by { |
| 728 | Some(ref c) if c == agent_id => { |
| 729 | conn.execute( |
| 730 | "UPDATE forge_tasks SET status = 'submitted' WHERE id = ?1", |
| 731 | params![task_id], |
| 732 | )?; |
| 733 | Ok(()) |
| 734 | } |
| 735 | Some(other) => Err(HiveError::TaskUnauthorized { |
| 736 | task_id: task_id.to_string(), |
| 737 | claimed_by: other, |
| 738 | agent_id: agent_id.to_string(), |
| 739 | }), |
| 740 | None => Err(HiveError::TaskUnauthorized { |
| 741 | task_id: task_id.to_string(), |
| 742 | claimed_by: "unclaimed".to_string(), |
| 743 | agent_id: agent_id.to_string(), |
| 744 | }), |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | pub fn verify_forge_task( |
| 749 | &self, |
| 750 | task_id: &str, |
| 751 | verdict: bool, |
| 752 | _notes: &str, |
| 753 | ) -> Result<(), HiveError> { |
| 754 | let conn = self.conn.lock().unwrap(); |
| 755 | let new_status = if verdict { "verified" } else { "failed" }; |
| 756 | let rows = conn.execute( |
| 757 | "UPDATE forge_tasks SET status = ?1 WHERE id = ?2", |
| 758 | params![new_status, task_id], |
| 759 | )?; |
| 760 | if rows == 0 { |
| 761 | return Err(HiveError::TaskNotFound(task_id.to_string())); |
| 762 | } |
| 763 | Ok(()) |
| 764 | } |
| 765 | |
| 766 | pub fn list_forge_tasks( |
| 767 | &self, |
| 768 | project: Option<&str>, |
| 769 | ring: Option<usize>, |
| 770 | status: Option<&str>, |
| 771 | ) -> Result<Vec<ForgeTask>, HiveError> { |
| 772 | let conn = self.conn.lock().unwrap(); |
| 773 | let mut query = "SELECT id, comb_id, project, module, ring, q, r, title, status, claimed_by, expires_at, worktree_path, created_at FROM forge_tasks WHERE 1=1".to_string(); |
| 774 | let mut param_vals: Vec<Box<dyn rusqlite::ToSql>> = Vec::new(); |
| 775 | |
| 776 | if let Some(p) = project { |
| 777 | query.push_str(" AND project = ?"); |
| 778 | param_vals.push(Box::new(p.to_string())); |
| 779 | } |
| 780 | if let Some(r) = ring { |
| 781 | query.push_str(" AND ring = ?"); |
| 782 | param_vals.push(Box::new(r as i64)); |
| 783 | } |
| 784 | if let Some(s) = status { |
| 785 | query.push_str(" AND status = ?"); |
| 786 | param_vals.push(Box::new(s.to_string())); |
| 787 | } |
| 788 | |
| 789 | query.push_str(" ORDER BY ring ASC, created_at ASC"); |
| 790 | |
| 791 | let mut stmt = conn.prepare(&query)?; |
| 792 | let param_refs: Vec<&dyn rusqlite::ToSql> = param_vals.iter().map(|p| p.as_ref()).collect(); |
| 793 | |
| 794 | let tasks = stmt |
| 795 | .query_map(¶m_refs[..], |row| { |
| 796 | Ok(ForgeTask { |
| 797 | id: row.get(0)?, |
| 798 | comb_id: row.get(1)?, |
| 799 | project: row.get(2)?, |
| 800 | module: row.get(3)?, |
| 801 | ring: row.get::<_, i64>(4)? as usize, |
| 802 | q: row.get(5)?, |
| 803 | r: row.get(6)?, |
| 804 | title: row.get(7)?, |
| 805 | status: row.get(8)?, |
| 806 | claimed_by: row.get(9)?, |
| 807 | expires_at: row.get(10)?, |
| 808 | worktree_path: row.get(11)?, |
| 809 | created_at: row.get(12)?, |
| 810 | }) |
| 811 | })? |
| 812 | .collect::<Result<Vec<_>, _>>()?; |
| 813 | |
| 814 | Ok(tasks) |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | #[cfg(test)] |
| 819 | mod tests { |
| 820 | use super::*; |
| 821 | |
| 822 | #[test] |
| 823 | fn test_in_memory_store_genesis_and_get_cells() { |
| 824 | let store = CombStore::open_in_memory().expect("open in memory store"); |
| 825 | let (cells, bounds) = store.get_cells().expect("get cells"); |
| 826 | assert_eq!(cells.len(), 1); |
| 827 | assert_eq!(cells[0].q, 0); |
| 828 | assert_eq!(cells[0].r, 0); |
| 829 | assert_eq!(cells[0].author, "AIEN Genesis"); |
| 830 | assert_eq!(bounds.count, 1); |
| 831 | assert_eq!(bounds.min_q, 0); |
| 832 | assert_eq!(bounds.max_q, 0); |
| 833 | } |
| 834 | |
| 835 | #[test] |
| 836 | fn test_place_comb_collision_check() { |
| 837 | let store = CombStore::open_in_memory().expect("open in memory store"); |
| 838 | |
| 839 | // Attempt to place at (0, 0) where genesis comb lives -> must trigger Collision! |
| 840 | let collision_result = store.place_comb(PlaceCombInput { |
| 841 | q: Some(0), |
| 842 | r: Some(0), |
| 843 | author: "Tester".to_string(), |
| 844 | role: None, |
| 845 | content: "Collision test".to_string(), |
| 846 | intent: None, |
| 847 | parent_id: None, |
| 848 | }); |
| 849 | |
| 850 | match collision_result { |
| 851 | Err(HiveError::Collision { q, r, comb_id }) => { |
| 852 | assert_eq!(q, 0); |
| 853 | assert_eq!(r, 0); |
| 854 | assert_eq!(comb_id, "comb-genesis-00000000"); |
| 855 | } |
| 856 | other => panic!("Expected collision error, got: {:?}", other), |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | #[test] |
| 861 | fn test_place_comb_with_neighbors_linking() { |
| 862 | let store = CombStore::open_in_memory().expect("open in memory store"); |
| 863 | |
| 864 | // Place east neighbor of genesis (1, 0) |
| 865 | let placed = store.place_comb(PlaceCombInput { |
| 866 | q: Some(1), |
| 867 | r: Some(0), |
| 868 | author: "AIEN Subagent".to_string(), |
| 869 | role: Some("researcher".to_string()), |
| 870 | content: "Subagent completed research task".to_string(), |
| 871 | intent: Some("join".to_string()), |
| 872 | parent_id: Some("comb-genesis-00000000".to_string()), |
| 873 | }).expect("place east neighbor"); |
| 874 | |
| 875 | assert_eq!(placed.q, 1); |
| 876 | assert_eq!(placed.r, 0); |
| 877 | assert_eq!(placed.neighbors.len(), 1); |
| 878 | assert_eq!(placed.neighbors[0].id, "comb-genesis-00000000"); |
| 879 | assert_eq!(placed.neighbors[0].direction_label, "west"); // Genesis is west of (1, 0) |
| 880 | |
| 881 | // Verify get_cells links both ways |
| 882 | let (cells, bounds) = store.get_cells().expect("get cells"); |
| 883 | assert_eq!(cells.len(), 2); |
| 884 | assert_eq!(bounds.count, 2); |
| 885 | |
| 886 | let genesis = cells.iter().find(|c| c.q == 0 && c.r == 0).unwrap(); |
| 887 | assert_eq!(genesis.neighbors.len(), 1); |
| 888 | assert_eq!(genesis.neighbors[0].direction_label, "east"); |
| 889 | assert_eq!(genesis.neighbors[0].id, placed.id); |
| 890 | } |
| 891 | |
| 892 | #[test] |
| 893 | fn test_auto_place_comb_around_parent() { |
| 894 | let store = CombStore::open_in_memory().expect("open in memory store"); |
| 895 | |
| 896 | // Auto place with parent_id -> should place at first free neighbor of genesis: (1, 0) East |
| 897 | let auto1 = store.place_comb(PlaceCombInput { |
| 898 | q: None, |
| 899 | r: None, |
| 900 | author: "Subagent 1".to_string(), |
| 901 | role: Some("coder".to_string()), |
| 902 | content: "First code commit".to_string(), |
| 903 | intent: Some("branch".to_string()), |
| 904 | parent_id: Some("comb-genesis-00000000".to_string()), |
| 905 | }).expect("auto place 1"); |
| 906 | |
| 907 | assert_eq!(auto1.q, 1); |
| 908 | assert_eq!(auto1.r, 0); |
| 909 | |
| 910 | // Auto place again -> should place at next free neighbor: (1, -1) Northeast |
| 911 | let auto2 = store.place_comb(PlaceCombInput { |
| 912 | q: None, |
| 913 | r: None, |
| 914 | author: "Subagent 2".to_string(), |
| 915 | role: Some("tester".to_string()), |
| 916 | content: "Tests passed".to_string(), |
| 917 | intent: Some("join".to_string()), |
| 918 | parent_id: Some("comb-genesis-00000000".to_string()), |
| 919 | }).expect("auto place 2"); |
| 920 | |
| 921 | assert_eq!(auto2.q, 1); |
| 922 | assert_eq!(auto2.r, -1); |
| 923 | } |
| 924 | |
| 925 | #[test] |
| 926 | fn test_concurrent_auto_place_comb() { |
| 927 | use std::sync::Arc; |
| 928 | use std::thread; |
| 929 | |
| 930 | let store = Arc::new(CombStore::open_in_memory().expect("in memory store")); |
| 931 | let mut handles = Vec::new(); |
| 932 | |
| 933 | for i in 0..12 { |
| 934 | let s = Arc::clone(&store); |
| 935 | handles.push(thread::spawn(move || { |
| 936 | s.place_comb(PlaceCombInput { |
| 937 | q: None, |
| 938 | r: None, |
| 939 | author: format!("Agent-{}", i), |
| 940 | role: Some("subagent".to_string()), |
| 941 | content: format!("Concurrent message {}", i), |
| 942 | intent: Some("branch".to_string()), |
| 943 | parent_id: Some("comb-genesis-00000000".to_string()), |
| 944 | }) |
| 945 | })); |
| 946 | } |
| 947 | |
| 948 | for h in handles { |
| 949 | let res = h.join().expect("thread join"); |
| 950 | assert!(res.is_ok(), "Concurrent auto placement must never collide: {:?}", res.err()); |
| 951 | } |
| 952 | |
| 953 | let (cells, bounds) = store.get_cells().expect("get cells"); |
| 954 | assert_eq!(cells.len(), 13); |
| 955 | assert_eq!(bounds.count, 13); |
| 956 | } |
| 957 | |
| 958 | #[test] |
| 959 | fn test_forge_project_genesis_and_tasks() { |
| 960 | let store = CombStore::open_in_memory().expect("in memory store"); |
| 961 | |
| 962 | let project_task = store.spawn_forge_project( |
| 963 | "harvester", |
| 964 | "Model Harvester Pipeline Core", |
| 965 | "Extract reasoning tokens from commercial LLMs", |
| 966 | ).expect("spawn forge project"); |
| 967 | |
| 968 | assert_eq!(project_task.project, "harvester"); |
| 969 | assert_eq!(project_task.ring, 0); |
| 970 | assert_eq!(project_task.status, "open"); |
| 971 | |
| 972 | let module_task = store.create_forge_task(CreateForgeTaskInput { |
| 973 | project: "harvester".to_string(), |
| 974 | module: "openai-provider".to_string(), |
| 975 | ring: 1, |
| 976 | title: "Implement OpenAI provider client".to_string(), |
| 977 | description: "Streaming extraction with reasoning tokens".to_string(), |
| 978 | parent_comb_id: Some(project_task.comb_id.clone()), |
| 979 | }).expect("create module task"); |
| 980 | |
| 981 | assert_eq!(module_task.project, "harvester"); |
| 982 | assert_eq!(module_task.module, "openai-provider"); |
| 983 | assert_eq!(module_task.ring, 1); |
| 984 | assert_eq!(module_task.status, "open"); |
| 985 | |
| 986 | let tasks = store.list_forge_tasks(Some("harvester"), None, None).expect("list tasks"); |
| 987 | assert_eq!(tasks.len(), 2); |
| 988 | } |
| 989 | |
| 990 | #[test] |
| 991 | fn test_forge_task_lease_heartbeat_and_reclaim() { |
| 992 | let store = CombStore::open_in_memory().expect("in memory store"); |
| 993 | |
| 994 | let task = store.spawn_forge_project("cortex", "Cortex Core", "Memory graph").unwrap(); |
| 995 | |
| 996 | // Agent 1 claims task |
| 997 | let claimed = store.claim_forge_task(&task.id, "agent-alpha", 60).expect("claim task"); |
| 998 | assert_eq!(claimed.status, "claimed"); |
| 999 | assert_eq!(claimed.claimed_by.as_deref(), Some("agent-alpha")); |
| 1000 | |
| 1001 | // Agent 2 attempts to claim -> fails |
| 1002 | let err = store.claim_forge_task(&task.id, "agent-beta", 60); |
| 1003 | assert!(matches!(err, Err(HiveError::TaskAlreadyClaimed { .. }))); |
| 1004 | |
| 1005 | // Agent 1 heartbeats |
| 1006 | let hb = store.heartbeat_forge_task(&task.id, "agent-alpha", 120); |
| 1007 | assert!(hb.is_ok()); |
| 1008 | |
| 1009 | // Agent 2 attempts unauthorized heartbeat -> fails |
| 1010 | let hb_err = store.heartbeat_forge_task(&task.id, "agent-beta", 120); |
| 1011 | assert!(matches!(hb_err, Err(HiveError::TaskUnauthorized { .. }))); |
| 1012 | |
| 1013 | // Agent 1 submits task |
| 1014 | let submit = store.submit_forge_task(&task.id, "agent-alpha", "feat/cortex-core", None); |
| 1015 | assert!(submit.is_ok()); |
| 1016 | |
| 1017 | // AEGIS verifies task |
| 1018 | let verify = store.verify_forge_task(&task.id, true, "Passes zero secret and unit tests"); |
| 1019 | assert!(verify.is_ok()); |
| 1020 | |
| 1021 | let final_tasks = store.list_forge_tasks(Some("cortex"), None, Some("verified")).unwrap(); |
| 1022 | assert_eq!(final_tasks.len(), 1); |
| 1023 | assert_eq!(final_tasks[0].status, "verified"); |
| 1024 | } |
| 1025 | } |
| 1026 |