hird 0.2.2

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! The herald: the queue announcing work that is waiting for hands.
//!
//! Everything else in hird is pull. An agent calls `task_next` when it wants
//! work, and a task that becomes claimable while nobody is asking sits there —
//! correct, visible on the board, and silent. That silence is a design
//! decision (§2: no daemon), but it leaves one seam the human still has to
//! work by hand: noticing that the queue has something ready and going to
//! find an agent to point at it.
//!
//! The herald closes that seam without opening the one the design forbids.
//! It is not a scheduler and not a daemon: it is one configured command
//! (`dispatch_hook` in `config.toml`), run at the moment a task becomes
//! claimable, told which task, why, and whom the queue would refuse it to
//! (`HIRD_RECUSED` — so a summons never wakes the one agent a filed review
//! is barred from — and `HIRD_REQUIRES`, so a router can choose equipped
//! hands), and then left entirely alone. What the
//! command does — prompt an idle agent through a terminal multiplexer such as
//! herdr, post a notification, append to a log, nothing — is the human's
//! business. hird neither waits for it nor reads its answer, so the queue's
//! own operations cannot be slowed down or failed by whatever the hook gets
//! up to.
//!
//! Because hird only runs when somebody calls it, announcements happen when
//! the becoming-claimable is *observed*, which for everything except lease
//! expiry is the same write that causes it: completing a task announces the
//! dependents it released, filing work announces it if nothing blocks it, a
//! `sent_back` verdict announces the reopened work. Lease expiry alone has no
//! write of its own — it is enforced lazily by sweeps — so it is announced by
//! whichever sweep first notices it, with the same latency the expiry itself
//! already has.
//!
//! Questions have the same seam on the other side of the table. A task
//! released with a question steps out of dispatch — deliberately unannounced,
//! because it is waiting for a human, not another agent — and a human who is
//! not watching the board waits in the same silence an idle agent did. The
//! `question_hook` key closes that seam the same way: one command, run
//! detached at the moment a question gate opens, with the question in its
//! environment. Same contract, different audience.

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use crate::config::Config;
use crate::db::Db;
use crate::identity;

/// Why a task is being announced. Every cause means the same thing at the
/// moment it fires — this task is claimable now — and names how it got there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cause {
    /// Created with nothing blocking it.
    Filed,
    /// Its last unmet dependency finished.
    Unblocked,
    /// Finished work put itself in front of another harness.
    ReviewFiled,
    /// A review's verdict reopened it, findings appended to its brief.
    SentBack,
    /// A human put it back in the pool.
    Reopened,
    /// Its holder handed it back unfinished.
    Released,
    /// A human answered the question that had kept it out of dispatch.
    Answered,
    /// Its holder went quiet and the lease ran out.
    LeaseExpired,
    /// The human lifted a recess, and this task was waiting behind it.
    Resumed,
}

impl Cause {
    /// The word the hook receives in `HIRD_EVENT`.
    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",
        }
    }
}

/// One announcement: task `seq` is claimable, why — and whom it is not for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Announcement {
    pub cause: Cause,
    pub seq: i64,
    pub title: String,
    pub project: String,
    /// Harnesses the queue will refuse this task to. The claim would tell
    /// them so anyway; telling the hook first means a summons that can pick
    /// between agents never wakes one the queue is about to turn away —
    /// which is every `review_filed` announcement under a hook that always
    /// prompts the same worker.
    pub recused: Vec<String>,
    /// Capabilities a suitable worker must advertise. The hook remains the
    /// router; hird only supplies the fact it could not otherwise infer.
    pub requirements: Vec<String>,
}

/// The configured messenger, or nothing.
///
/// Built once per process from the `dispatch_hook` key; an empty or unset key
/// builds `None` and costs every call site one `is_some` check.
#[derive(Debug, Clone)]
pub struct Herald {
    command: String,
    db: PathBuf,
}

impl Herald {
    /// A herald for `command`, announcing a queue that lives at `db`.
    ///
    /// `None` when the command is empty: no hook configured, nothing to run.
    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(),
        })
    }

    /// Announce one claimable task: run the hook with the facts in its
    /// environment and walk away.
    ///
    /// The command runs through `sh -c` with `HIRD_EVENT`, `HIRD_TASK`,
    /// `HIRD_TITLE`, `HIRD_PROJECT`, `HIRD_RECUSED`, `HIRD_REQUIRES` and
    /// `HIRD_DB` set.
    /// `HIRD_RECUSED` is comma-separated harness names — commas cannot appear
    /// in a harness name, so `case ",$HIRD_RECUSED," in *,codex,*)` is a safe
    /// membership test — and empty for the tasks anybody may take. All three
    /// stdio streams are closed: an MCP server's stdout is a JSON-RPC wire,
    /// and a hook that inherited it could corrupt the session that fired it.
    /// Failure to spawn is swallowed — the queue's work is already committed,
    /// and a broken hook must not turn a finished task into an error.
    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(",")),
            ],
        );
    }

    /// Announce a batch, one hook run per task.
    pub fn announce_all(&self, list: &[Announcement]) {
        for a in list {
            self.announce(a);
        }
    }
}

/// Run `command` through `sh -c` with `vars` and `HIRD_DB` set, and walk away.
///
/// All three stdio streams are closed: an MCP server's stdout is a JSON-RPC
/// wire, and a hook that inherited it could corrupt the session that fired it.
/// Failure to spawn is swallowed — the queue's work is already committed, and
/// a broken hook must not turn a finished write into an error.
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 {
        // Reap from a thread so the hook neither blocks this call nor
        // lingers as a zombie under a long-lived MCP server.
        std::thread::spawn(move || {
            let _ = child.wait();
        });
    }
}

/// One raised question: task `seq` has stepped out of dispatch to wait on a
/// human answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RaisedQuestion {
    pub seq: i64,
    pub title: String,
    pub project: String,
    pub question: String,
    /// Who asked, exactly as the board records it — `harness:session` for an
    /// agent, so a notification can say which model hit the human edge.
    pub asked_by: String,
}

/// The configured messenger for question gates, or nothing.
///
/// The herald's twin with the opposite audience: it speaks when a task leaves
/// dispatch rather than when one enters it, and the one it summons is the
/// human. Built once per process from the `question_hook` key; an empty or
/// unset key builds `None`.
#[derive(Debug, Clone)]
pub struct QuestionHerald {
    command: String,
    db: PathBuf,
}

impl QuestionHerald {
    /// A question herald for `command`, announcing a queue that lives at `db`.
    ///
    /// `None` when the command is empty: no hook configured, nothing to run.
    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(),
        })
    }

    /// Announce one open question gate: run the hook with the question in its
    /// environment and walk away.
    ///
    /// The command runs through `sh -c` with `HIRD_EVENT` (always `asked`),
    /// `HIRD_TASK`, `HIRD_TITLE`, `HIRD_PROJECT`, `HIRD_QUESTION`,
    /// `HIRD_ASKED_BY` and `HIRD_DB` set. `HIRD_EVENT` matches the word the
    /// event trail records, so one script can serve both hooks and branch on
    /// the same vocabulary.
    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()),
            ],
        );
    }
}

/// Announce `list` through `herald`, if there is one.
///
/// The call sites all hold an `Option<Herald>`; this keeps each of them to a
/// single line that reads as what it does.
pub fn announce(herald: Option<&Herald>, list: &[Announcement]) {
    if let Some(herald) = herald {
        herald.announce_all(list);
    }
}

/// Tell the herald task `seq` is claimable, if it is and there is one.
///
/// Read back from the database rather than trusted from the caller: by the
/// time this runs, an agent may already have taken the task, and announcing
/// work that is no longer waiting would send a summoned agent to an empty
/// queue.
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,
    });
}

/// Heal expired leases and tell the herald what came back to the pool.
///
/// Expiry is the one cause with no write behind it, so it belongs to whoever
/// reads next — and a sweep reports each lapsed lease to exactly one sweeper.
/// Any process that polls the board therefore has to do both halves: sweeping
/// without announcing does not leave the announcement for somebody else, it
/// consumes it. Every reader that runs on a timer calls this — the CLI before
/// its verb, `hird events --follow` on each poll, the TUI on each refresh — so
/// whichever of them collects an expiry is the one that summons a replacement.
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"
        );
    }

    /// A hook that can address more than one agent routes on `HIRD_RECUSED`:
    /// the names arrive comma-joined, and empty when anybody may claim.
    #[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]");
    }

    /// The hook is fire-and-forget: a command that cannot run does not turn
    /// into an error at the call site.
    #[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(),
        });
    }

    /// The question herald carries the question itself and who asked it, so a
    /// notification can say what decision is waiting without a board lookup.
    #[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]");
    }
}