interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-hive / src / store.rs

1577 lines · 57166 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use chrono::{DateTime, Utc};
17use rusqlite::{Connection, ErrorCode, OptionalExtension, Row, TransactionBehavior, params};
18use serde::de::DeserializeOwned;
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21use sha2::{Digest, Sha256};
22use std::collections::HashSet;
23use std::path::{Path, PathBuf};
24use std::sync::Mutex;
25use thiserror::Error;
26use uuid::Uuid;
27
28use crate::geometry::{HEX_DIRECTION_LABELS, HEX_DIRECTIONS, HexCoord, hex_distance};
29
30#[derive(Debug, Error)]
31pub enum HiveError {
32 #[error("Coordinate ({q}, {r}) is already occupied by comb '{comb_id}'")]
33 Collision { q: i32, r: i32, comb_id: String },
34 #[error("Parent comb '{0}' not found")]
35 ParentNotFound(String),
36 #[error("SQLite database error: {0}")]
37 Db(rusqlite::Error),
38 /// SQLite stayed BUSY or LOCKED past the busy timeout. Nothing changed;
39 /// the caller may retry. Rule: om/hive-task/task.om op 6.
40 #[error("SQLite database busy, nothing changed, retry: {0}")]
41 Busy(rusqlite::Error),
42 #[error("Invalid input: {0}")]
43 InvalidInput(String),
44 #[error("Forge task '{0}' not found")]
45 TaskNotFound(String),
46 /// The transition rules in om/hive-task/task.om refuse this operation in
47 /// the task's current state; the row is unchanged.
48 #[error("Forge task '{task_id}' refused {op}: status '{status}', generation {generation}")]
49 Refused {
50 task_id: String,
51 op: &'static str,
52 status: String,
53 generation: i64,
54 },
55 /// The command id already answered a different request; nothing changed.
56 /// Rule: om/hive-task/task.om op 7.
57 #[error("Command id '{command_id}' was already used for a different request")]
58 CommandConflict { command_id: String },
59 /// The database file could not be put in WAL journal mode, so a reader
60 /// could make a write's commit fail after its row was returned.
61 #[error("SQLite journal_mode is '{0}', not wal; refusing to serve this database")]
62 NotWal(String),
63 /// A conditional UPDATE keyed by the task id changed more than one row.
64 #[error("Forge update changed {0} rows; expected at most one")]
65 ManyRows(usize),
66}
67
68impl From<rusqlite::Error> for HiveError {
69 fn from(error: rusqlite::Error) -> Self {
70 match error.sqlite_error_code() {
71 Some(ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked) => Self::Busy(error),
72 _ => Self::Db(error),
73 }
74 }
75}
76
77impl HiveError {
78 /// True when the operation changed nothing and may be sent again.
79 pub fn is_retryable(&self) -> bool {
80 matches!(self, Self::Busy(_))
81 }
82}
83
84/// The caller's proof that it holds the current lease: the attempt id and
85/// generation returned by its claim, and the agent that claimed.
86#[derive(Debug, Clone, Copy)]
87pub struct LeaseFence<'a> {
88 pub agent_id: &'a str,
89 pub attempt_id: &'a str,
90 pub generation: i64,
91}
92
93/// Lease bounds and generation ceiling; the same constants as MAXTTL and GMAX
94/// in om/hive-task/task.om.
95pub const MAX_LEASE_SECS: u64 = 86_400;
96pub const MAX_GENERATION: i64 = 9_007_199_254_740_991;
97/// Longest command id in bytes; CMDMAX in om/hive-task/task.om.
98pub const MAX_COMMAND_ID: usize = 128;
99
100/// A forge write named by the caller's command id. Host adapter for
101/// om/hive-task/task.om op 7 (#925, DRA-288): the digest covers the
102/// operation, the task id and every normalized request field.
103struct Command<'a> {
104 id: &'a str,
105 op: &'static str,
106 task_id: &'a str,
107 digest: String,
108}
109
110impl<'a> Command<'a> {
111 /// None without a command id; InvalidInput for a malformed one, which is
112 /// refused before any lookup and never recorded.
113 fn new(
114 id: Option<&'a str>,
115 op: &'static str,
116 task_id: &'a str,
117 fields: Value,
118 ) -> Result<Option<Self>, HiveError> {
119 let Some(id) = id else {
120 return Ok(None);
121 };
122 let well_formed = (1..=MAX_COMMAND_ID).contains(&id.len())
123 && id
124 .bytes()
125 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'));
126 if !well_formed {
127 return Err(HiveError::InvalidInput(format!(
128 "command_id must be 1 to {MAX_COMMAND_ID} bytes of A-Z a-z 0-9 . _ : -"
129 )));
130 }
131 let request = json!([op, task_id, fields]).to_string();
132 let digest = Sha256::digest(request.as_bytes())
133 .iter()
134 .map(|b| format!("{b:02x}"))
135 .collect();
136 Ok(Some(Self {
137 id,
138 op,
139 task_id,
140 digest,
141 }))
142 }
143}
144
145fn result_error(e: serde_json::Error) -> HiveError {
146 HiveError::Db(rusqlite::Error::ToSqlConversionFailure(Box::new(e)))
147}
148
149/// task.om BADTTL: an out-of-range ttl is bad input (400), answered before
150/// any command record is read. The WHERE clauses keep the same bound as a
151/// second line of defence.
152fn check_ttl(ttl_secs: u64) -> Result<(), HiveError> {
153 if (1..=MAX_LEASE_SECS).contains(&ttl_secs) {
154 Ok(())
155 } else {
156 Err(HiveError::InvalidInput(format!(
157 "ttl_secs {ttl_secs} is outside 1..={MAX_LEASE_SECS}"
158 )))
159 }
160}
161
162/// Runs one conditional `UPDATE ... RETURNING` to SQLITE_DONE and returns
163/// the changed row, if any. In autocommit mode the change commits when the
164/// statement finishes, so stepping to the end is what surfaces a commit
165/// failure (BUSY, IOERR, FULL); `query_row` takes the first row and drops
166/// the statement, and the reset that rolls the change back reports its error
167/// to nobody. The task id is the primary key, so a second row is an error.
168fn update_returning<T>(
169 conn: &Connection,
170 sql: &str,
171 params: impl rusqlite::Params,
172 map: impl FnMut(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
173) -> Result<Option<T>, HiveError> {
174 let mut stmt = conn.prepare(sql)?;
175 let mut rows = stmt
176 .query_map(params, map)?
177 .collect::<Result<Vec<T>, _>>()?;
178 if rows.len() > 1 {
179 return Err(HiveError::ManyRows(rows.len()));
180 }
181 Ok(rows.pop())
182}
183
184#[derive(Debug, Clone, Deserialize)]
185pub struct CreateForgeTaskInput {
186 pub project: String,
187 pub module: String,
188 pub ring: usize,
189 pub title: String,
190 pub description: String,
191 pub parent_comb_id: Option<String>,
192}
193
194#[derive(Debug, Clone, Default, Serialize, Deserialize)]
195pub struct ForgeTask {
196 pub id: String,
197 pub comb_id: String,
198 pub project: String,
199 pub module: String,
200 pub ring: usize,
201 pub q: i32,
202 pub r: i32,
203 pub title: String,
204 pub status: String,
205 pub claimed_by: Option<String>,
206 pub expires_at: Option<String>,
207 pub worktree_path: Option<String>,
208 pub created_at: String,
209 #[serde(default)]
210 pub attempt_id: Option<String>,
211 #[serde(default)]
212 pub generation: i64,
213 #[serde(default)]
214 pub branch: Option<String>,
215 #[serde(default)]
216 pub pr_url: Option<String>,
217 #[serde(default)]
218 pub artifact: Option<String>,
219 #[serde(default)]
220 pub verified_by: Option<String>,
221 #[serde(default)]
222 pub verify_notes: Option<String>,
223}
224
225const FORGE_COLUMNS: &str = "id, comb_id, project, module, ring, q, r, title, status, claimed_by, \
226 expires_at, worktree_path, created_at, attempt_id, generation, branch, pr_url, artifact, \
227 verified_by, verify_notes";
228
229/// Columns added to the original 13-column forge_tasks table.
230const FORGE_ADDED_COLUMNS: &[(&str, &str)] = &[
231 ("attempt_id", "TEXT"),
232 ("generation", "INTEGER NOT NULL DEFAULT 0"),
233 ("lease_expires_ms", "INTEGER"),
234 ("branch", "TEXT"),
235 ("pr_url", "TEXT"),
236 ("artifact", "TEXT"),
237 ("verified_by", "TEXT"),
238 ("verify_notes", "TEXT"),
239];
240
241fn forge_task_from_row(row: &Row<'_>) -> rusqlite::Result<ForgeTask> {
242 Ok(ForgeTask {
243 id: row.get(0)?,
244 comb_id: row.get(1)?,
245 project: row.get(2)?,
246 module: row.get(3)?,
247 ring: row.get::<_, i64>(4)? as usize,
248 q: row.get(5)?,
249 r: row.get(6)?,
250 title: row.get(7)?,
251 status: row.get(8)?,
252 claimed_by: row.get(9)?,
253 expires_at: row.get(10)?,
254 worktree_path: row.get(11)?,
255 created_at: row.get(12)?,
256 attempt_id: row.get(13)?,
257 generation: row.get(14)?,
258 branch: row.get(15)?,
259 pr_url: row.get(16)?,
260 artifact: row.get(17)?,
261 verified_by: row.get(18)?,
262 verify_notes: row.get(19)?,
263 })
264}
265
266/// Adds the lease-fence and evidence columns to a forge_tasks table created
267/// by an older build. One IMMEDIATE transaction, so two processes opening the
268/// same file cannot both add a column. A claimed row's RFC 3339 expires_at is
269/// copied into lease_expires_ms; an unreadable one becomes 0 (expired). A row
270/// submitted by an older build has no artifact digest, so no candidate can be
271/// verified: it becomes failed (claimable for rework), with verified_by
272/// 'migration' and a note saying why.
273fn migrate_forge_tasks(conn: &mut Connection) -> Result<(), HiveError> {
274 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
275 let present: HashSet<String> = tx
276 .prepare("SELECT name FROM pragma_table_info('forge_tasks')")?
277 .query_map([], |r| r.get(0))?
278 .collect::<Result<_, _>>()?;
279 let mut backfill = false;
280 for &(name, decl) in FORGE_ADDED_COLUMNS {
281 if !present.contains(name) {
282 tx.execute_batch(&format!("ALTER TABLE forge_tasks ADD COLUMN {name} {decl}"))?;
283 backfill |= name == "lease_expires_ms";
284 }
285 }
286 if backfill {
287 let leases: Vec<(String, Option<String>)> = tx
288 .prepare("SELECT id, expires_at FROM forge_tasks WHERE status = 'claimed'")?
289 .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
290 .collect::<Result<_, _>>()?;
291 for (id, expires_at) in leases {
292 let ms = expires_at
293 .and_then(|e| DateTime::parse_from_rfc3339(&e).ok())
294 .map_or(0, |e| e.timestamp_millis());
295 tx.execute(
296 "UPDATE forge_tasks SET lease_expires_ms = ?1 WHERE id = ?2",
297 params![ms, id],
298 )?;
299 }
300 tx.execute(
301 "UPDATE forge_tasks SET status = 'failed', verified_by = 'migration',
302 verify_notes = 'submitted before the artifact digest was recorded; claim and resubmit'
303 WHERE status = 'submitted' AND artifact IS NULL",
304 [],
305 )?;
306 }
307 tx.commit()?;
308 Ok(())
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct HiveComb {
313 pub id: String,
314 pub q: i32,
315 pub r: i32,
316 pub author: String,
317 pub role: String,
318 pub content: String,
319 pub intent: String,
320 pub parent_id: Option<String>,
321 pub created_at: String,
322 #[serde(default, skip_serializing_if = "Vec::is_empty")]
323 pub neighbors: Vec<NeighborLink>,
324}
325
326#[derive(Debug, Clone, Serialize, Deserialize)]
327pub struct NeighborLink {
328 pub id: String,
329 pub q: i32,
330 pub r: i32,
331 pub direction: usize,
332 pub direction_label: String,
333}
334
335#[derive(Debug, Clone, Serialize, Deserialize)]
336pub struct BoundingBox {
337 pub min_q: i32,
338 pub max_q: i32,
339 pub min_r: i32,
340 pub max_r: i32,
341 pub count: usize,
342 pub radius: i32,
343 pub revision: usize,
344 pub message_count: usize,
345}
346
347#[derive(Debug, Clone, Deserialize)]
348pub struct PlaceCombInput {
349 pub q: Option<i32>,
350 pub r: Option<i32>,
351 pub author: String,
352 pub role: Option<String>,
353 pub content: String,
354 pub intent: Option<String>,
355 pub parent_id: Option<String>,
356}
357
358pub struct CombStore {
359 conn: Mutex<Connection>,
360 path: PathBuf,
361}
362
363impl CombStore {
364 pub fn open(path: &Path) -> Result<Self, HiveError> {
365 if let Some(parent) = path.parent() {
366 let _ = std::fs::create_dir_all(parent);
367 }
368 let conn = Connection::open(path)?;
369 conn.busy_timeout(std::time::Duration::from_millis(5000))?;
370 // Every forge write commits when its statement finishes; in WAL mode a
371 // reader can never make that commit BUSY. A file left in another
372 // journal mode (for example a reader held a lock while we switched)
373 // is refused here instead of served (#925).
374 let mode: String = conn.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))?;
375 if !mode.eq_ignore_ascii_case("wal") {
376 return Err(HiveError::NotWal(mode));
377 }
378 conn.execute_batch("PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?;
379 let store = Self {
380 conn: Mutex::new(conn),
381 path: path.to_path_buf(),
382 };
383 store.init_schema()?;
384 Ok(store)
385 }
386
387 pub fn open_default() -> Result<Self, HiveError> {
388 let path_str = std::env::var("HIVE_DB_PATH").unwrap_or_else(|_| {
389 let home = std::env::var("HOME")
390 .or_else(|_| std::env::var("USERPROFILE"))
391 .unwrap_or_else(|_| ".".to_string());
392 format!("{}/.config/cortex/hive.db", home)
393 });
394 let path = PathBuf::from(path_str);
395 Self::open(&path)
396 }
397
398 pub fn open_in_memory() -> Result<Self, HiveError> {
399 let conn = Connection::open_in_memory()?;
400 let store = Self {
401 conn: Mutex::new(conn),
402 path: PathBuf::from(":memory:"),
403 };
404 store.init_schema()?;
405 Ok(store)
406 }
407
408 pub fn path(&self) -> &Path {
409 &self.path
410 }
411
412 fn init_schema(&self) -> Result<(), HiveError> {
413 let mut conn = self.conn.lock().unwrap();
414 conn.execute_batch(
415 "CREATE TABLE IF NOT EXISTS hive_combs (
416 id TEXT PRIMARY KEY,
417 q INTEGER NOT NULL,
418 r INTEGER NOT NULL,
419 author TEXT NOT NULL,
420 role TEXT NOT NULL DEFAULT 'agent',
421 content TEXT NOT NULL,
422 intent TEXT NOT NULL DEFAULT 'independent',
423 parent_id TEXT,
424 created_at TEXT NOT NULL,
425 UNIQUE(q, r)
426 );
427 CREATE INDEX IF NOT EXISTS idx_hive_combs_qr ON hive_combs(q, r);
428 CREATE INDEX IF NOT EXISTS idx_hive_combs_created ON hive_combs(created_at);
429 CREATE INDEX IF NOT EXISTS idx_hive_combs_parent ON hive_combs(parent_id);
430 CREATE TABLE IF NOT EXISTS forge_tasks (
431 id TEXT PRIMARY KEY,
432 comb_id TEXT NOT NULL,
433 project TEXT NOT NULL,
434 module TEXT NOT NULL,
435 ring INTEGER NOT NULL,
436 q INTEGER NOT NULL,
437 r INTEGER NOT NULL,
438 title TEXT NOT NULL,
439 status TEXT NOT NULL DEFAULT 'open',
440 claimed_by TEXT,
441 expires_at TEXT,
442 worktree_path TEXT,
443 created_at TEXT NOT NULL
444 );
445 CREATE INDEX IF NOT EXISTS idx_forge_tasks_status ON forge_tasks(status);
446 CREATE INDEX IF NOT EXISTS idx_forge_tasks_project ON forge_tasks(project);
447 CREATE TABLE IF NOT EXISTS forge_commands (
448 command_id TEXT PRIMARY KEY,
449 op TEXT NOT NULL,
450 task_id TEXT NOT NULL,
451 digest TEXT NOT NULL,
452 decision INTEGER NOT NULL,
453 result TEXT NOT NULL,
454 created_at TEXT NOT NULL
455 );",
456 )?;
457 migrate_forge_tasks(&mut conn)?;
458
459 // Seed genesis comb if table is empty
460 let count: i64 = conn.query_row("SELECT COUNT(*) FROM hive_combs", [], |r| r.get(0))?;
461 if count == 0 {
462 let genesis_id = "comb-genesis-00000000";
463 let now = Utc::now().to_rfc3339();
464 conn.execute(
465 "INSERT INTO hive_combs (id, q, r, author, role, content, intent, parent_id, created_at)
466 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
467 params![
468 genesis_id,
469 0,
470 0,
471 "AIEN Genesis",
472 "coordinator",
473 "AIEN Sovereign Hive Online ยท Hexagonal Honeycomb Active",
474 "independent",
475 None::<String>,
476 now,
477 ],
478 )?;
479 }
480
481 Ok(())
482 }
483
484 pub fn get_comb(&self, id: &str) -> Result<Option<HiveComb>, HiveError> {
485 let conn = self.conn.lock().unwrap();
486 let mut stmt = conn.prepare(
487 "SELECT id, q, r, author, role, content, intent, parent_id, created_at
488 FROM hive_combs WHERE id = ?1",
489 )?;
490 let row = stmt
491 .query_row(params![id], |r| {
492 Ok(HiveComb {
493 id: r.get(0)?,
494 q: r.get(1)?,
495 r: r.get(2)?,
496 author: r.get(3)?,
497 role: r.get(4)?,
498 content: r.get(5)?,
499 intent: r.get(6)?,
500 parent_id: r.get(7)?,
501 created_at: r.get(8)?,
502 neighbors: Vec::new(),
503 })
504 })
505 .optional()?;
506
507 Ok(row)
508 }
509
510 pub fn get_comb_at(&self, q: i32, r: i32) -> Result<Option<HiveComb>, HiveError> {
511 let conn = self.conn.lock().unwrap();
512 let mut stmt = conn.prepare(
513 "SELECT id, q, r, author, role, content, intent, parent_id, created_at
514 FROM hive_combs WHERE q = ?1 AND r = ?2",
515 )?;
516 let row = stmt
517 .query_row(params![q, r], |row| {
518 Ok(HiveComb {
519 id: row.get(0)?,
520 q: row.get(1)?,
521 r: row.get(2)?,
522 author: row.get(3)?,
523 role: row.get(4)?,
524 content: row.get(5)?,
525 intent: row.get(6)?,
526 parent_id: row.get(7)?,
527 created_at: row.get(8)?,
528 neighbors: Vec::new(),
529 })
530 })
531 .optional()?;
532
533 Ok(row)
534 }
535
536 pub fn get_cells(&self) -> Result<(Vec<HiveComb>, BoundingBox), HiveError> {
537 let conn = self.conn.lock().unwrap();
538 let mut stmt = conn.prepare(
539 "SELECT id, q, r, author, role, content, intent, parent_id, created_at
540 FROM hive_combs ORDER BY created_at ASC",
541 )?;
542
543 let rows = stmt.query_map([], |r| {
544 Ok(HiveComb {
545 id: r.get(0)?,
546 q: r.get(1)?,
547 r: r.get(2)?,
548 author: r.get(3)?,
549 role: r.get(4)?,
550 content: r.get(5)?,
551 intent: r.get(6)?,
552 parent_id: r.get(7)?,
553 created_at: r.get(8)?,
554 neighbors: Vec::new(),
555 })
556 })?;
557
558 let mut combs = Vec::new();
559 let mut min_q = 0;
560 let mut max_q = 0;
561 let mut min_r = 0;
562 let mut max_r = 0;
563 let mut max_radius = 5;
564
565 for (i, comb_res) in rows.enumerate() {
566 let comb = comb_res?;
567 if i == 0 {
568 min_q = comb.q;
569 max_q = comb.q;
570 min_r = comb.r;
571 max_r = comb.r;
572 } else {
573 min_q = min_q.min(comb.q);
574 max_q = max_q.max(comb.q);
575 min_r = min_r.min(comb.r);
576 max_r = max_r.max(comb.r);
577 }
578 let d = hex_distance(comb.q, comb.r, 0, 0);
579 if d > max_radius {
580 max_radius = d;
581 }
582 combs.push(comb);
583 }
584
585 // Build coordinate lookup table for neighbor linking
586 let coord_map: std::collections::HashMap<(i32, i32), (String, usize)> = combs
587 .iter()
588 .enumerate()
589 .map(|(idx, c)| ((c.q, c.r), (c.id.clone(), idx)))
590 .collect();
591
592 // Calculate neighbor links for each comb
593 for comb in &mut combs {
594 let mut neighbors = Vec::new();
595 for (dir_idx, (dq, dr)) in HEX_DIRECTIONS.iter().enumerate() {
596 let n_coord = (comb.q + dq, comb.r + dr);
597 if let Some((n_id, _)) = coord_map.get(&n_coord) {
598 neighbors.push(NeighborLink {
599 id: n_id.clone(),
600 q: n_coord.0,
601 r: n_coord.1,
602 direction: dir_idx,
603 direction_label: HEX_DIRECTION_LABELS[dir_idx].to_string(),
604 });
605 }
606 }
607 comb.neighbors = neighbors;
608 }
609
610 let count = combs.len();
611 let bounds = BoundingBox {
612 min_q,
613 max_q,
614 min_r,
615 max_r,
616 count,
617 radius: max_radius,
618 revision: count,
619 message_count: count,
620 };
621
622 Ok((combs, bounds))
623 }
624
625 /// Finds the first available unoccupied coordinate.
626 /// If parent_id is given, searches adjacent neighbors of parent first.
627 pub fn find_free_coordinate(&self, parent_id: Option<&str>) -> Result<HexCoord, HiveError> {
628 let conn = self.conn.lock().unwrap();
629 Self::find_free_coordinate_with_conn(&conn, parent_id)
630 }
631
632 /// Internal coordinate finder operating under an already locked database connection.
633 fn find_free_coordinate_with_conn(
634 conn: &rusqlite::Connection,
635 parent_id: Option<&str>,
636 ) -> Result<HexCoord, HiveError> {
637 let mut stmt = conn.prepare("SELECT q, r FROM hive_combs")?;
638 let occupied_coords: HashSet<(i32, i32)> = stmt
639 .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
640 .collect::<Result<HashSet<_>, _>>()?;
641
642 let center = if let Some(pid) = parent_id {
643 let mut parent_stmt = conn.prepare("SELECT q, r FROM hive_combs WHERE id = ?1")?;
644 let parent_coord: Option<(i32, i32)> = parent_stmt
645 .query_row(params![pid], |r| Ok((r.get(0)?, r.get(1)?)))
646 .optional()?;
647
648 match parent_coord {
649 Some((pq, pr)) => HexCoord::new(pq, pr),
650 None => HexCoord::new(0, 0),
651 }
652 } else {
653 HexCoord::new(0, 0)
654 };
655
656 // Check center itself first if empty
657 if !occupied_coords.contains(&(center.q, center.r)) {
658 return Ok(center);
659 }
660
661 // 1. Check all 6 immediate neighbors in canonical order
662 for (dq, dr) in HEX_DIRECTIONS {
663 let cand = (center.q + dq, center.r + dr);
664 if !occupied_coords.contains(&cand) {
665 return Ok(HexCoord::new(cand.0, cand.1));
666 }
667 }
668
669 // 2. Search outward rings around center up to radius 50
670 for ring_radius in 2..=50 {
671 let mut current = HexCoord::new(
672 center.q + HEX_DIRECTIONS[4].0 * ring_radius,
673 center.r + HEX_DIRECTIONS[4].1 * ring_radius,
674 );
675 for (dir_idx, _) in HEX_DIRECTIONS.iter().enumerate() {
676 for _ in 0..ring_radius {
677 if !occupied_coords.contains(&(current.q, current.r)) {
678 return Ok(current);
679 }
680 let next_dir = HEX_DIRECTIONS[dir_idx];
681 current = HexCoord::new(current.q + next_dir.0, current.r + next_dir.1);
682 }
683 }
684 }
685
686 Ok(HexCoord::new(0, 0))
687 }
688
689 pub fn place_comb(&self, input: PlaceCombInput) -> Result<HiveComb, HiveError> {
690 let conn = self.conn.lock().unwrap();
691
692 let (q, r) = match (input.q, input.r) {
693 (Some(q), Some(r)) => (q, r),
694 _ => {
695 let coord =
696 Self::find_free_coordinate_with_conn(&conn, input.parent_id.as_deref())?;
697 (coord.q, coord.r)
698 }
699 };
700
701 // 1. Collision check
702 let mut check_stmt = conn.prepare("SELECT id FROM hive_combs WHERE q = ?1 AND r = ?2")?;
703 let existing_id: Option<String> = check_stmt
704 .query_row(params![q, r], |row| row.get(0))
705 .optional()?;
706 if let Some(id) = existing_id {
707 return Err(HiveError::Collision { q, r, comb_id: id });
708 }
709
710 // 2. Neighbor linking
711 let mut neighbors = Vec::new();
712 let mut neighbor_stmt =
713 conn.prepare("SELECT id FROM hive_combs WHERE q = ?1 AND r = ?2")?;
714 for (dir_idx, (dq, dr)) in HEX_DIRECTIONS.iter().enumerate() {
715 let n_q = q + dq;
716 let n_r = r + dr;
717 if let Some(n_id) = neighbor_stmt
718 .query_row(params![n_q, n_r], |row| row.get(0))
719 .optional()?
720 {
721 neighbors.push(NeighborLink {
722 id: n_id,
723 q: n_q,
724 r: n_r,
725 direction: dir_idx,
726 direction_label: HEX_DIRECTION_LABELS[dir_idx].to_string(),
727 });
728 }
729 }
730
731 // 3. Verify parent_id if supplied
732 if let Some(ref pid) = input.parent_id {
733 let mut parent_check = conn.prepare("SELECT 1 FROM hive_combs WHERE id = ?1")?;
734 let parent_exists: Option<i32> =
735 parent_check.query_row(params![pid], |_| Ok(1)).optional()?;
736 if parent_exists.is_none() {
737 // Parent does not exist yet; accepted as unanchored
738 }
739 }
740
741 let id = format!("comb-{}", Uuid::new_v4());
742 let role = input.role.unwrap_or_else(|| "agent".to_string());
743 let intent = input.intent.unwrap_or_else(|| "independent".to_string());
744 let created_at = Utc::now().to_rfc3339();
745
746 conn.execute(
747 "INSERT INTO hive_combs (id, q, r, author, role, content, intent, parent_id, created_at)
748 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
749 params![
750 &id,
751 q,
752 r,
753 &input.author,
754 &role,
755 &input.content,
756 &intent,
757 &input.parent_id,
758 &created_at,
759 ],
760 )?;
761
762 Ok(HiveComb {
763 id,
764 q,
765 r,
766 author: input.author,
767 role,
768 content: input.content,
769 intent,
770 parent_id: input.parent_id,
771 created_at,
772 neighbors,
773 })
774 }
775
776 pub fn spawn_forge_project(
777 &self,
778 project: &str,
779 title: &str,
780 core_spec: &str,
781 ) -> Result<ForgeTask, HiveError> {
782 let comb = self.place_comb(PlaceCombInput {
783 q: None,
784 r: None,
785 author: "AIEN-Forge".to_string(),
786 role: Some("genesis".to_string()),
787 content: format!("Project [{}] core spec: {}", project, core_spec),
788 intent: Some("genesis".to_string()),
789 parent_id: None,
790 })?;
791
792 let task_id = format!("task-{}-{}", project, &Uuid::new_v4().to_string()[..8]);
793 let now = Utc::now().to_rfc3339();
794
795 let conn = self.conn.lock().unwrap();
796 conn.execute(
797 "INSERT INTO forge_tasks (id, comb_id, project, module, ring, q, r, title, status, created_at)
798 VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6, ?7, 'open', ?8)",
799 params![
800 task_id,
801 comb.id,
802 project,
803 "core",
804 comb.q,
805 comb.r,
806 title,
807 now,
808 ],
809 )?;
810
811 Ok(ForgeTask {
812 id: task_id,
813 comb_id: comb.id,
814 project: project.to_string(),
815 module: "core".to_string(),
816 ring: 0,
817 q: comb.q,
818 r: comb.r,
819 title: title.to_string(),
820 status: "open".to_string(),
821 claimed_by: None,
822 expires_at: None,
823 worktree_path: None,
824 created_at: now,
825 ..ForgeTask::default()
826 })
827 }
828
829 pub fn create_forge_task(&self, input: CreateForgeTaskInput) -> Result<ForgeTask, HiveError> {
830 let comb = self.place_comb(PlaceCombInput {
831 q: None,
832 r: None,
833 author: "AIEN-Forge".to_string(),
834 role: Some("module".to_string()),
835 content: format!(
836 "Task [{}:{}]: {}",
837 input.project, input.module, input.description
838 ),
839 intent: Some("branch".to_string()),
840 parent_id: input
841 .parent_comb_id
842 .clone()
843 .or_else(|| Some("comb-genesis-00000000".to_string())),
844 })?;
845
846 let task_id = format!("task-{}-{}", input.module, &Uuid::new_v4().to_string()[..8]);
847 let now = Utc::now().to_rfc3339();
848
849 let conn = self.conn.lock().unwrap();
850 conn.execute(
851 "INSERT INTO forge_tasks (id, comb_id, project, module, ring, q, r, title, status, created_at)
852 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'open', ?9)",
853 params![
854 task_id,
855 comb.id,
856 input.project,
857 input.module,
858 input.ring as i64,
859 comb.q,
860 comb.r,
861 input.title,
862 now,
863 ],
864 )?;
865
866 Ok(ForgeTask {
867 id: task_id,
868 comb_id: comb.id,
869 project: input.project,
870 module: input.module,
871 ring: input.ring,
872 q: comb.q,
873 r: comb.r,
874 title: input.title,
875 status: "open".to_string(),
876 claimed_by: None,
877 expires_at: None,
878 worktree_path: None,
879 created_at: now,
880 ..ForgeTask::default()
881 })
882 }
883
884 /// The refusal for a conditional UPDATE that changed no row: the task's
885 /// current status and generation, or TaskNotFound.
886 fn refusal(conn: &Connection, task_id: &str, op: &'static str) -> HiveError {
887 let row = conn
888 .query_row(
889 "SELECT status, generation FROM forge_tasks WHERE id = ?1",
890 params![task_id],
891 |r| Ok((r.get(0)?, r.get(1)?)),
892 )
893 .optional();
894 match row {
895 Ok(Some((status, generation))) => HiveError::Refused {
896 task_id: task_id.to_string(),
897 op,
898 status,
899 generation,
900 },
901 Ok(None) => HiveError::TaskNotFound(task_id.to_string()),
902 Err(e) => e.into(),
903 }
904 }
905
906 /// Runs one forge write inside one IMMEDIATE transaction. The clock is
907 /// read only after the write lock is granted and is passed to `apply`,
908 /// so a request that waited in the busy handler cannot grant a lease
909 /// that already ran out or renew one that expired while it waited
910 /// (#925). With a command id, the record lookup, `apply` and the record
911 /// of an allowed outcome share the transaction (om/hive-task/task.om op
912 /// 7): the same request again returns the stored result, as it was
913 /// answered, and changes nothing; another request under the id is
914 /// CommandConflict; a refusal or busy outcome rolls back unrecorded, so
915 /// a retry is decided again.
916 fn run_command<T: Serialize + DeserializeOwned>(
917 &self,
918 command: Option<Command<'_>>,
919 apply: impl FnOnce(&Connection, DateTime<Utc>) -> Result<T, HiveError>,
920 ) -> Result<T, HiveError> {
921 let mut conn = self.conn.lock().unwrap();
922 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
923 if let Some(command) = &command {
924 let prior: Option<(String, String)> = tx
925 .query_row(
926 "SELECT digest, result FROM forge_commands WHERE command_id = ?1",
927 params![command.id],
928 |r| Ok((r.get(0)?, r.get(1)?)),
929 )
930 .optional()?;
931 if let Some((digest, result)) = prior {
932 if digest != command.digest {
933 return Err(HiveError::CommandConflict {
934 command_id: command.id.to_string(),
935 });
936 }
937 return serde_json::from_str(&result).map_err(result_error);
938 }
939 }
940 let out = apply(&tx, Utc::now())?;
941 if let Some(command) = command {
942 let result = serde_json::to_string(&out).map_err(result_error)?;
943 tx.execute(
944 "INSERT INTO forge_commands (command_id, op, task_id, digest, decision, result, created_at)
945 VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6)",
946 params![
947 command.id,
948 command.op,
949 command.task_id,
950 command.digest,
951 result,
952 Utc::now().to_rfc3339(),
953 ],
954 )?;
955 }
956 tx.commit()?;
957 Ok(out)
958 }
959
960 /// Grants a new lease with a fresh attempt id and generation + 1. Each
961 /// mutation below is one conditional UPDATE whose WHERE clause is the rule
962 /// in om/hive-task/task.om, so two connections cannot both be granted.
963 pub fn claim_forge_task(
964 &self,
965 task_id: &str,
966 agent_id: &str,
967 ttl_secs: u64,
968 command_id: Option<&str>,
969 ) -> Result<ForgeTask, HiveError> {
970 let command = Command::new(command_id, "claim", task_id, json!([agent_id, ttl_secs]))?;
971 check_ttl(ttl_secs)?;
972 let home = std::env::var("HOME")
973 .or_else(|_| std::env::var("USERPROFILE"))
974 .unwrap_or_else(|_| ".".to_string());
975 let worktree = format!("{}/workspace/hive-worktrees/{}", home, task_id);
976 let attempt_id = Uuid::new_v4().to_string();
977
978 self.run_command(command, |conn, now| {
979 let expires = now + chrono::Duration::seconds(ttl_secs as i64);
980 let claimed = update_returning(
981 conn,
982 &format!(
983 "UPDATE forge_tasks SET status = 'claimed', claimed_by = ?2, attempt_id = ?3,
984 generation = generation + 1, lease_expires_ms = ?4, expires_at = ?5,
985 worktree_path = ?6, branch = NULL, pr_url = NULL, artifact = NULL,
986 verified_by = NULL, verify_notes = NULL
987 WHERE id = ?1 AND ?7 BETWEEN 1 AND ?8 AND generation < ?9
988 AND (status IN ('open', 'failed')
989 OR (status = 'claimed' AND COALESCE(lease_expires_ms, 0) <= ?10))
990 RETURNING {FORGE_COLUMNS}"
991 ),
992 params![
993 task_id,
994 agent_id,
995 attempt_id,
996 expires.timestamp_millis(),
997 expires.to_rfc3339(),
998 worktree,
999 i64::try_from(ttl_secs).unwrap_or(i64::MAX),
1000 MAX_LEASE_SECS as i64,
1001 MAX_GENERATION,
1002 now.timestamp_millis(),
1003 ],
1004 forge_task_from_row,
1005 )?;
1006 claimed.ok_or_else(|| Self::refusal(conn, task_id, "claim"))
1007 })
1008 }
1009
1010 /// Extends the live lease held by `fence`.
1011 pub fn heartbeat_forge_task(
1012 &self,
1013 task_id: &str,
1014 fence: &LeaseFence<'_>,
1015 ttl_secs: u64,
1016 command_id: Option<&str>,
1017 ) -> Result<ForgeTask, HiveError> {
1018 let command = Command::new(
1019 command_id,
1020 "heartbeat",
1021 task_id,
1022 json!([fence.agent_id, fence.attempt_id, fence.generation, ttl_secs]),
1023 )?;
1024 check_ttl(ttl_secs)?;
1025 self.run_command(command, |conn, now| {
1026 let expires = now + chrono::Duration::seconds(ttl_secs as i64);
1027 let renewed = update_returning(
1028 conn,
1029 &format!(
1030 "UPDATE forge_tasks SET lease_expires_ms = ?5, expires_at = ?6
1031 WHERE id = ?1 AND status = 'claimed' AND claimed_by = ?2
1032 AND attempt_id = ?3 AND generation = ?4
1033 AND COALESCE(lease_expires_ms, 0) > ?7 AND ?8 BETWEEN 1 AND ?9
1034 RETURNING {FORGE_COLUMNS}"
1035 ),
1036 params![
1037 task_id,
1038 fence.agent_id,
1039 fence.attempt_id,
1040 fence.generation,
1041 expires.timestamp_millis(),
1042 expires.to_rfc3339(),
1043 now.timestamp_millis(),
1044 i64::try_from(ttl_secs).unwrap_or(i64::MAX),
1045 MAX_LEASE_SECS as i64,
1046 ],
1047 forge_task_from_row,
1048 )?;
1049 renewed.ok_or_else(|| Self::refusal(conn, task_id, "renew"))
1050 })
1051 }
1052
1053 /// Returns every expired claim to open. Generation is kept, so the
1054 /// expired holder's fence can never match again.
1055 pub fn reclaim_expired_leases(&self, command_id: Option<&str>) -> Result<usize, HiveError> {
1056 let command = Command::new(command_id, "reclaim", "", json!([]))?;
1057 self.run_command(command, |conn, now| {
1058 let rows = conn.execute(
1059 "UPDATE forge_tasks SET status = 'open', claimed_by = NULL, attempt_id = NULL,
1060 expires_at = NULL, lease_expires_ms = NULL, worktree_path = NULL
1061 WHERE status = 'claimed' AND COALESCE(lease_expires_ms, 0) <= ?1",
1062 params![now.timestamp_millis()],
1063 )?;
1064 Ok(rows)
1065 })
1066 }
1067
1068 /// Submits the candidate `artifact` (its digest) under the live lease
1069 /// held by `fence`; the lease ends.
1070 pub fn submit_forge_task(
1071 &self,
1072 task_id: &str,
1073 fence: &LeaseFence<'_>,
1074 branch: &str,
1075 pr_url: Option<&str>,
1076 artifact: &str,
1077 command_id: Option<&str>,
1078 ) -> Result<ForgeTask, HiveError> {
1079 if artifact.trim().is_empty() {
1080 return Err(HiveError::InvalidInput(
1081 "artifact digest is required".into(),
1082 ));
1083 }
1084 let command = Command::new(
1085 command_id,
1086 "submit",
1087 task_id,
1088 json!([
1089 fence.agent_id,
1090 fence.attempt_id,
1091 fence.generation,
1092 branch,
1093 pr_url,
1094 artifact
1095 ]),
1096 )?;
1097 self.run_command(command, |conn, now| {
1098 let submitted = update_returning(
1099 conn,
1100 &format!(
1101 "UPDATE forge_tasks SET status = 'submitted', branch = ?5, pr_url = ?6,
1102 artifact = ?7, lease_expires_ms = NULL, expires_at = NULL
1103 WHERE id = ?1 AND status = 'claimed' AND claimed_by = ?2
1104 AND attempt_id = ?3 AND generation = ?4
1105 AND COALESCE(lease_expires_ms, 0) > ?8
1106 RETURNING {FORGE_COLUMNS}"
1107 ),
1108 params![
1109 task_id,
1110 fence.agent_id,
1111 fence.attempt_id,
1112 fence.generation,
1113 branch,
1114 pr_url,
1115 artifact,
1116 now.timestamp_millis(),
1117 ],
1118 forge_task_from_row,
1119 )?;
1120 submitted.ok_or_else(|| Self::refusal(conn, task_id, "submit"))
1121 })
1122 }
1123
1124 /// Records `verifier`'s verdict on exactly the submitted candidate: the
1125 /// task must be submitted, at `generation`, with this `artifact`.
1126 #[allow(clippy::too_many_arguments)]
1127 pub fn verify_forge_task(
1128 &self,
1129 task_id: &str,
1130 generation: i64,
1131 artifact: &str,
1132 verifier: &str,
1133 verdict: bool,
1134 notes: &str,
1135 command_id: Option<&str>,
1136 ) -> Result<ForgeTask, HiveError> {
1137 if verifier.trim().is_empty() {
1138 return Err(HiveError::InvalidInput("verifier is required".into()));
1139 }
1140 let command = Command::new(
1141 command_id,
1142 "verify",
1143 task_id,
1144 json!([generation, artifact, verifier, verdict, notes]),
1145 )?;
1146 self.run_command(command, |conn, _now| {
1147 let verified = update_returning(
1148 conn,
1149 &format!(
1150 "UPDATE forge_tasks SET status = ?4, verified_by = ?5, verify_notes = ?6
1151 WHERE id = ?1 AND status = 'submitted' AND generation = ?2 AND artifact = ?3
1152 RETURNING {FORGE_COLUMNS}"
1153 ),
1154 params![
1155 task_id,
1156 generation,
1157 artifact,
1158 if verdict { "verified" } else { "failed" },
1159 verifier,
1160 notes,
1161 ],
1162 forge_task_from_row,
1163 )?;
1164 verified.ok_or_else(|| Self::refusal(conn, task_id, "verify"))
1165 })
1166 }
1167
1168 pub fn list_forge_tasks(
1169 &self,
1170 project: Option<&str>,
1171 ring: Option<usize>,
1172 status: Option<&str>,
1173 ) -> Result<Vec<ForgeTask>, HiveError> {
1174 let conn = self.conn.lock().unwrap();
1175 let mut query = format!("SELECT {FORGE_COLUMNS} FROM forge_tasks WHERE 1=1");
1176 let mut param_vals: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
1177
1178 if let Some(p) = project {
1179 query.push_str(" AND project = ?");
1180 param_vals.push(Box::new(p.to_string()));
1181 }
1182 if let Some(r) = ring {
1183 query.push_str(" AND ring = ?");
1184 param_vals.push(Box::new(r as i64));
1185 }
1186 if let Some(s) = status {
1187 query.push_str(" AND status = ?");
1188 param_vals.push(Box::new(s.to_string()));
1189 }
1190
1191 query.push_str(" ORDER BY ring ASC, created_at ASC");
1192
1193 let mut stmt = conn.prepare(&query)?;
1194 let param_refs: Vec<&dyn rusqlite::ToSql> = param_vals.iter().map(|p| p.as_ref()).collect();
1195
1196 let tasks = stmt
1197 .query_map(&param_refs[..], forge_task_from_row)?
1198 .collect::<Result<Vec<_>, _>>()?;
1199
1200 Ok(tasks)
1201 }
1202}
1203
1204#[cfg(test)]
1205mod tests {
1206 use super::*;
1207
1208 #[test]
1209 fn test_in_memory_store_genesis_and_get_cells() {
1210 let store = CombStore::open_in_memory().expect("open in memory store");
1211 let (cells, bounds) = store.get_cells().expect("get cells");
1212 assert_eq!(cells.len(), 1);
1213 assert_eq!(cells[0].q, 0);
1214 assert_eq!(cells[0].r, 0);
1215 assert_eq!(cells[0].author, "AIEN Genesis");
1216 assert_eq!(bounds.count, 1);
1217 assert_eq!(bounds.min_q, 0);
1218 assert_eq!(bounds.max_q, 0);
1219 }
1220
1221 #[test]
1222 fn test_place_comb_collision_check() {
1223 let store = CombStore::open_in_memory().expect("open in memory store");
1224
1225 // Attempt to place at (0, 0) where genesis comb lives -> must trigger Collision!
1226 let collision_result = store.place_comb(PlaceCombInput {
1227 q: Some(0),
1228 r: Some(0),
1229 author: "Tester".to_string(),
1230 role: None,
1231 content: "Collision test".to_string(),
1232 intent: None,
1233 parent_id: None,
1234 });
1235
1236 match collision_result {
1237 Err(HiveError::Collision { q, r, comb_id }) => {
1238 assert_eq!(q, 0);
1239 assert_eq!(r, 0);
1240 assert_eq!(comb_id, "comb-genesis-00000000");
1241 }
1242 other => panic!("Expected collision error, got: {:?}", other),
1243 }
1244 }
1245
1246 #[test]
1247 fn test_place_comb_with_neighbors_linking() {
1248 let store = CombStore::open_in_memory().expect("open in memory store");
1249
1250 // Place east neighbor of genesis (1, 0)
1251 let placed = store
1252 .place_comb(PlaceCombInput {
1253 q: Some(1),
1254 r: Some(0),
1255 author: "AIEN Subagent".to_string(),
1256 role: Some("researcher".to_string()),
1257 content: "Subagent completed research task".to_string(),
1258 intent: Some("join".to_string()),
1259 parent_id: Some("comb-genesis-00000000".to_string()),
1260 })
1261 .expect("place east neighbor");
1262
1263 assert_eq!(placed.q, 1);
1264 assert_eq!(placed.r, 0);
1265 assert_eq!(placed.neighbors.len(), 1);
1266 assert_eq!(placed.neighbors[0].id, "comb-genesis-00000000");
1267 assert_eq!(placed.neighbors[0].direction_label, "west"); // Genesis is west of (1, 0)
1268
1269 // Verify get_cells links both ways
1270 let (cells, bounds) = store.get_cells().expect("get cells");
1271 assert_eq!(cells.len(), 2);
1272 assert_eq!(bounds.count, 2);
1273
1274 let genesis = cells.iter().find(|c| c.q == 0 && c.r == 0).unwrap();
1275 assert_eq!(genesis.neighbors.len(), 1);
1276 assert_eq!(genesis.neighbors[0].direction_label, "east");
1277 assert_eq!(genesis.neighbors[0].id, placed.id);
1278 }
1279
1280 #[test]
1281 fn test_auto_place_comb_around_parent() {
1282 let store = CombStore::open_in_memory().expect("open in memory store");
1283
1284 // Auto place with parent_id -> should place at first free neighbor of genesis: (1, 0) East
1285 let auto1 = store
1286 .place_comb(PlaceCombInput {
1287 q: None,
1288 r: None,
1289 author: "Subagent 1".to_string(),
1290 role: Some("coder".to_string()),
1291 content: "First code commit".to_string(),
1292 intent: Some("branch".to_string()),
1293 parent_id: Some("comb-genesis-00000000".to_string()),
1294 })
1295 .expect("auto place 1");
1296
1297 assert_eq!(auto1.q, 1);
1298 assert_eq!(auto1.r, 0);
1299
1300 // Auto place again -> should place at next free neighbor: (1, -1) Northeast
1301 let auto2 = store
1302 .place_comb(PlaceCombInput {
1303 q: None,
1304 r: None,
1305 author: "Subagent 2".to_string(),
1306 role: Some("tester".to_string()),
1307 content: "Tests passed".to_string(),
1308 intent: Some("join".to_string()),
1309 parent_id: Some("comb-genesis-00000000".to_string()),
1310 })
1311 .expect("auto place 2");
1312
1313 assert_eq!(auto2.q, 1);
1314 assert_eq!(auto2.r, -1);
1315 }
1316
1317 #[test]
1318 fn test_concurrent_auto_place_comb() {
1319 use std::sync::Arc;
1320 use std::thread;
1321
1322 let store = Arc::new(CombStore::open_in_memory().expect("in memory store"));
1323 let mut handles = Vec::new();
1324
1325 for i in 0..12 {
1326 let s = Arc::clone(&store);
1327 handles.push(thread::spawn(move || {
1328 s.place_comb(PlaceCombInput {
1329 q: None,
1330 r: None,
1331 author: format!("Agent-{}", i),
1332 role: Some("subagent".to_string()),
1333 content: format!("Concurrent message {}", i),
1334 intent: Some("branch".to_string()),
1335 parent_id: Some("comb-genesis-00000000".to_string()),
1336 })
1337 }));
1338 }
1339
1340 for h in handles {
1341 let res = h.join().expect("thread join");
1342 assert!(
1343 res.is_ok(),
1344 "Concurrent auto placement must never collide: {:?}",
1345 res.err()
1346 );
1347 }
1348
1349 let (cells, bounds) = store.get_cells().expect("get cells");
1350 assert_eq!(cells.len(), 13);
1351 assert_eq!(bounds.count, 13);
1352 }
1353
1354 #[test]
1355 fn test_forge_project_genesis_and_tasks() {
1356 let store = CombStore::open_in_memory().expect("in memory store");
1357
1358 let project_task = store
1359 .spawn_forge_project(
1360 "harvester",
1361 "Model Harvester Pipeline Core",
1362 "Extract reasoning tokens from commercial LLMs",
1363 )
1364 .expect("spawn forge project");
1365
1366 assert_eq!(project_task.project, "harvester");
1367 assert_eq!(project_task.ring, 0);
1368 assert_eq!(project_task.status, "open");
1369
1370 let module_task = store
1371 .create_forge_task(CreateForgeTaskInput {
1372 project: "harvester".to_string(),
1373 module: "openai-provider".to_string(),
1374 ring: 1,
1375 title: "Implement OpenAI provider client".to_string(),
1376 description: "Streaming extraction with reasoning tokens".to_string(),
1377 parent_comb_id: Some(project_task.comb_id.clone()),
1378 })
1379 .expect("create module task");
1380
1381 assert_eq!(module_task.project, "harvester");
1382 assert_eq!(module_task.module, "openai-provider");
1383 assert_eq!(module_task.ring, 1);
1384 assert_eq!(module_task.status, "open");
1385
1386 let tasks = store
1387 .list_forge_tasks(Some("harvester"), None, None)
1388 .expect("list tasks");
1389 assert_eq!(tasks.len(), 2);
1390 }
1391
1392 #[test]
1393 fn test_forge_task_lease_heartbeat_and_reclaim() {
1394 let store = CombStore::open_in_memory().expect("in memory store");
1395
1396 let task = store
1397 .spawn_forge_project("cortex", "Cortex Core", "Memory graph")
1398 .unwrap();
1399
1400 // Agent 1 claims task under a command id
1401 let claimed = store
1402 .claim_forge_task(&task.id, "agent-alpha", 60, Some("cmd-1"))
1403 .expect("claim task");
1404 assert_eq!(claimed.status, "claimed");
1405 assert_eq!(claimed.claimed_by.as_deref(), Some("agent-alpha"));
1406 assert_eq!(claimed.generation, 1);
1407
1408 // The same request again replays the stored result and changes nothing
1409 let replay = store
1410 .claim_forge_task(&task.id, "agent-alpha", 60, Some("cmd-1"))
1411 .expect("replay claim");
1412 assert_eq!(replay.generation, 1);
1413 assert_eq!(replay.attempt_id, claimed.attempt_id);
1414 // Another request under the same id is a conflict; a malformed id is invalid
1415 let other = store.claim_forge_task(&task.id, "agent-alpha", 61, Some("cmd-1"));
1416 assert!(matches!(other, Err(HiveError::CommandConflict { .. })));
1417 let bad = store.claim_forge_task(&task.id, "agent-alpha", 60, Some("cmd/1"));
1418 assert!(matches!(bad, Err(HiveError::InvalidInput(_))));
1419 let attempt = claimed.attempt_id.clone().expect("attempt id");
1420 let fence = LeaseFence {
1421 agent_id: "agent-alpha",
1422 attempt_id: &attempt,
1423 generation: claimed.generation,
1424 };
1425
1426 // Agent 2 attempts to claim -> refused
1427 let err = store.claim_forge_task(&task.id, "agent-beta", 60, None);
1428 assert!(matches!(err, Err(HiveError::Refused { .. })));
1429
1430 // Agent 1 heartbeats
1431 let hb = store.heartbeat_forge_task(&task.id, &fence, 120, None);
1432 assert!(hb.is_ok());
1433
1434 // Agent 2 attempts unauthorized heartbeat -> refused
1435 let beta = LeaseFence {
1436 agent_id: "agent-beta",
1437 ..fence
1438 };
1439 let hb_err = store.heartbeat_forge_task(&task.id, &beta, 120, None);
1440 assert!(matches!(hb_err, Err(HiveError::Refused { .. })));
1441
1442 // Agent 1 submits task
1443 let submit = store.submit_forge_task(
1444 &task.id,
1445 &fence,
1446 "feat/cortex-core",
1447 None,
1448 "sha256:abc",
1449 None,
1450 );
1451 assert!(submit.is_ok());
1452
1453 // A verdict on another candidate is refused
1454 let wrong = store.verify_forge_task(&task.id, 1, "sha256:other", "aegis", true, "", None);
1455 assert!(matches!(wrong, Err(HiveError::Refused { .. })));
1456
1457 // AEGIS verifies task
1458 let verify = store.verify_forge_task(
1459 &task.id,
1460 1,
1461 "sha256:abc",
1462 "aegis",
1463 true,
1464 "Passes zero secret and unit tests",
1465 None,
1466 );
1467 assert!(verify.is_ok());
1468
1469 let final_tasks = store
1470 .list_forge_tasks(Some("cortex"), None, Some("verified"))
1471 .unwrap();
1472 assert_eq!(final_tasks.len(), 1);
1473 assert_eq!(final_tasks[0].status, "verified");
1474 assert_eq!(final_tasks[0].verified_by.as_deref(), Some("aegis"));
1475 assert_eq!(final_tasks[0].artifact.as_deref(), Some("sha256:abc"));
1476 }
1477
1478 /// #925: in DELETE journal mode a reader's SHARED lock makes an
1479 /// `UPDATE ... RETURNING` commit BUSY after its row was produced.
1480 /// `query_row` hands back the row while the reset rolls the change back;
1481 /// `update_returning` steps to the end and reports the failure.
1482 #[test]
1483 fn test_update_returning_reports_commit_failure() {
1484 let dir = std::env::temp_dir().join(format!("hive-commit-{}", Uuid::new_v4()));
1485 std::fs::create_dir_all(&dir).unwrap();
1486 let path = dir.join("t.db");
1487 let writer = Connection::open(&path).unwrap();
1488 writer.busy_timeout(std::time::Duration::ZERO).unwrap();
1489 let mode: String = writer
1490 .query_row("PRAGMA journal_mode = DELETE", [], |r| r.get(0))
1491 .unwrap();
1492 assert_eq!(mode, "delete");
1493 writer
1494 .execute_batch(
1495 "CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER);
1496 INSERT INTO t VALUES (1, 0);",
1497 )
1498 .unwrap();
1499 let reader = Connection::open(&path).unwrap();
1500 let hold = |sql: &str| {
1501 reader.execute_batch(sql).unwrap();
1502 let _: i64 = reader
1503 .query_row("SELECT v FROM t", [], |r| r.get(0))
1504 .unwrap();
1505 };
1506 let value =
1507 |c: &Connection| -> i64 { c.query_row("SELECT v FROM t", [], |r| r.get(0)).unwrap() };
1508
1509 hold("BEGIN");
1510 let old: i64 = writer
1511 .query_row("UPDATE t SET v = 1 WHERE id = 1 RETURNING v", [], |r| {
1512 r.get(0)
1513 })
1514 .unwrap();
1515 assert_eq!(old, 1, "query_row returned the row");
1516 reader.execute_batch("COMMIT").unwrap();
1517 assert_eq!(
1518 value(&writer),
1519 0,
1520 "and the change was rolled back unreported"
1521 );
1522
1523 hold("BEGIN");
1524 let new = update_returning(
1525 &writer,
1526 "UPDATE t SET v = 2 WHERE id = 1 RETURNING v",
1527 [],
1528 |r| r.get::<_, i64>(0),
1529 );
1530 assert!(matches!(new, Err(HiveError::Busy(_))), "{new:?}");
1531 // A DELETE-mode file cannot become WAL while the reader holds it.
1532 let refused = CombStore::open(&path);
1533 assert!(
1534 refused.is_err(),
1535 "open must refuse a file it cannot put in WAL"
1536 );
1537 reader.execute_batch("COMMIT").unwrap();
1538 assert_eq!(value(&writer), 0);
1539 let applied = update_returning(
1540 &writer,
1541 "UPDATE t SET v = 3 WHERE id = 1 RETURNING v",
1542 [],
1543 |r| r.get::<_, i64>(0),
1544 );
1545 assert_eq!(applied.unwrap(), Some(3));
1546 assert_eq!(value(&writer), 3);
1547 let _ = std::fs::remove_dir_all(&dir);
1548 }
1549
1550 /// task.om BADTTL: an out-of-range ttl is 400 invalid, checked first.
1551 #[test]
1552 fn test_forge_ttl_out_of_range_is_invalid() {
1553 let store = CombStore::open_in_memory().unwrap();
1554 let task = store
1555 .create_forge_task(CreateForgeTaskInput {
1556 project: "p".into(),
1557 module: "m".into(),
1558 ring: 0,
1559 title: "t".into(),
1560 description: "d".into(),
1561 parent_comb_id: None,
1562 })
1563 .unwrap();
1564 for ttl in [0, MAX_LEASE_SECS + 1] {
1565 let r = store.claim_forge_task(&task.id, "a", ttl, None);
1566 assert!(matches!(r, Err(HiveError::InvalidInput(_))), "{r:?}");
1567 }
1568 let held = store.claim_forge_task(&task.id, "a", 60, None).unwrap();
1569 let fence = LeaseFence {
1570 agent_id: "a",
1571 attempt_id: held.attempt_id.as_deref().unwrap(),
1572 generation: held.generation,
1573 };
1574 let r = store.heartbeat_forge_task(&task.id, &fence, 0, None);
1575 assert!(matches!(r, Err(HiveError::InvalidInput(_))), "{r:?}");
1576 }
1577}