use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use crate::config::Config;
use crate::db::Db;
use crate::identity;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cause {
Filed,
Unblocked,
ReviewFiled,
SentBack,
Reopened,
Released,
Answered,
LeaseExpired,
Resumed,
}
impl Cause {
pub fn as_str(self) -> &'static str {
match self {
Cause::Filed => "filed",
Cause::Unblocked => "unblocked",
Cause::ReviewFiled => "review_filed",
Cause::SentBack => "sent_back",
Cause::Reopened => "reopened",
Cause::Released => "released",
Cause::Answered => "answered",
Cause::LeaseExpired => "lease_expired",
Cause::Resumed => "resumed",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Announcement {
pub cause: Cause,
pub seq: i64,
pub title: String,
pub project: String,
pub recused: Vec<String>,
pub requirements: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct Herald {
command: String,
db: PathBuf,
}
impl Herald {
pub fn new(command: &str, db: &Path) -> Option<Herald> {
let command = command.trim();
if command.is_empty() {
return None;
}
Some(Herald {
command: command.to_string(),
db: db.to_path_buf(),
})
}
pub fn announce(&self, a: &Announcement) {
run_detached(
&self.command,
&self.db,
&[
("HIRD_EVENT", a.cause.as_str().to_string()),
("HIRD_TASK", a.seq.to_string()),
("HIRD_TITLE", a.title.clone()),
("HIRD_PROJECT", a.project.clone()),
("HIRD_RECUSED", a.recused.join(",")),
("HIRD_REQUIRES", a.requirements.join(",")),
],
);
}
pub fn announce_all(&self, list: &[Announcement]) {
for a in list {
self.announce(a);
}
}
}
fn run_detached(command: &str, db: &Path, vars: &[(&str, String)]) {
let mut cmd = Command::new("sh");
cmd.arg("-c").arg(command);
for (name, value) in vars {
cmd.env(name, value);
}
let child = cmd
.env(identity::DB_ENV, db)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
if let Ok(mut child) = child {
std::thread::spawn(move || {
let _ = child.wait();
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RaisedQuestion {
pub seq: i64,
pub title: String,
pub project: String,
pub question: String,
pub asked_by: String,
}
#[derive(Debug, Clone)]
pub struct QuestionHerald {
command: String,
db: PathBuf,
}
impl QuestionHerald {
pub fn new(command: &str, db: &Path) -> Option<QuestionHerald> {
let command = command.trim();
if command.is_empty() {
return None;
}
Some(QuestionHerald {
command: command.to_string(),
db: db.to_path_buf(),
})
}
pub fn announce(&self, q: &RaisedQuestion) {
run_detached(
&self.command,
&self.db,
&[
("HIRD_EVENT", "asked".to_string()),
("HIRD_TASK", q.seq.to_string()),
("HIRD_TITLE", q.title.clone()),
("HIRD_PROJECT", q.project.clone()),
("HIRD_QUESTION", q.question.clone()),
("HIRD_ASKED_BY", q.asked_by.clone()),
],
);
}
}
pub fn announce(herald: Option<&Herald>, list: &[Announcement]) {
if let Some(herald) = herald {
herald.announce_all(list);
}
}
pub fn announce_claimable(
herald: Option<&Herald>,
db: &Db,
config: &Config,
cause: Cause,
seq: i64,
) {
let Some(herald) = herald else {
return;
};
let Ok(Some(claimable)) = db.deps().claimable(seq, config.clearance()) else {
return;
};
herald.announce(&Announcement {
cause,
seq: claimable.seq,
title: claimable.title,
project: claimable.project,
recused: claimable.recused,
requirements: claimable.requirements,
});
}
pub fn sweep_announcing(db: &Db, config: &Config, herald: Option<&Herald>) {
if herald.is_none() {
return;
}
let Ok(outcome) = db.tasks().sweep_leases() else {
return;
};
for seq in outcome.expired {
announce_claimable(herald, db, config, Cause::LeaseExpired, seq);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
fn wait_for(path: &Path) -> String {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
if let Ok(contents) = std::fs::read_to_string(path) {
if !contents.is_empty() {
return contents;
}
}
assert!(
Instant::now() < deadline,
"hook never wrote {}",
path.display()
);
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn an_empty_command_builds_no_herald() {
assert!(Herald::new("", Path::new("/tmp/x.db")).is_none());
assert!(Herald::new(" ", Path::new("/tmp/x.db")).is_none());
assert!(Herald::new("true", Path::new("/tmp/x.db")).is_some());
}
#[test]
fn the_hook_receives_the_announcement_in_its_environment() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let herald = Herald::new(
&format!(
"printf '%s %s %s %s %s' \"$HIRD_EVENT\" \"$HIRD_TASK\" \"$HIRD_TITLE\" \
\"$HIRD_PROJECT\" \"$HIRD_DB\" > {}",
log.display()
),
Path::new("/tmp/board.db"),
)
.unwrap();
herald.announce(&Announcement {
cause: Cause::Unblocked,
seq: 7,
title: "port the loader".to_string(),
project: "/repo".to_string(),
recused: Vec::new(),
requirements: Vec::new(),
});
assert_eq!(
wait_for(&log),
"unblocked 7 port the loader /repo /tmp/board.db"
);
}
#[test]
fn the_hook_is_told_whom_the_task_is_not_for() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let herald = Herald::new(
&format!("printf '[%s]' \"$HIRD_RECUSED\" > {}", log.display()),
Path::new("/tmp/board.db"),
)
.unwrap();
herald.announce(&Announcement {
cause: Cause::ReviewFiled,
seq: 8,
title: "Review: port the loader".to_string(),
project: "/repo".to_string(),
recused: vec!["claude-code".to_string(), "codex".to_string()],
requirements: Vec::new(),
});
assert_eq!(wait_for(&log), "[claude-code,codex]");
}
#[test]
fn a_broken_hook_is_swallowed() {
let herald = Herald::new("/nonexistent/hook", Path::new("/tmp/x.db")).unwrap();
herald.announce(&Announcement {
cause: Cause::Filed,
seq: 1,
title: "t".to_string(),
project: "p".to_string(),
recused: Vec::new(),
requirements: Vec::new(),
});
}
#[test]
fn the_question_hook_receives_the_question_in_its_environment() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let herald = QuestionHerald::new(
&format!(
"printf '%s %s %s %s' \"$HIRD_EVENT\" \"$HIRD_TASK\" \"$HIRD_QUESTION\" \
\"$HIRD_ASKED_BY\" > {}",
log.display()
),
Path::new("/tmp/board.db"),
)
.unwrap();
herald.announce(&RaisedQuestion {
seq: 4,
title: "migrate the config".to_string(),
project: "/repo".to_string(),
question: "Keep the old format readable?".to_string(),
asked_by: "codex:1".to_string(),
});
assert_eq!(
wait_for(&log),
"asked 4 Keep the old format readable? codex:1"
);
}
#[test]
fn an_empty_command_builds_no_question_herald() {
assert!(QuestionHerald::new("", Path::new("/tmp/x.db")).is_none());
assert!(QuestionHerald::new(" ", Path::new("/tmp/x.db")).is_none());
assert!(QuestionHerald::new("true", Path::new("/tmp/x.db")).is_some());
}
#[test]
fn the_hook_is_told_what_the_worker_must_have() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let herald = Herald::new(
&format!("printf '[%s]' \"$HIRD_REQUIRES\" > {}", log.display()),
Path::new("/tmp/board.db"),
)
.unwrap();
herald.announce(&Announcement {
cause: Cause::Filed,
seq: 9,
title: "visual QA".to_string(),
project: "/repo".to_string(),
recused: Vec::new(),
requirements: vec!["browser".to_string(), "network".to_string()],
});
assert_eq!(wait_for(&log), "[browser,network]");
}
}