hird 0.1.0

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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Filing a whole plan: many tasks, their dependencies and their scopes, at once.
//!
//! A plan is filed in one transaction. Either the entire graph lands or none of
//! it does, which is the property a shell script full of `hird add` calls
//! cannot have: one that dies halfway leaves a handful of real tasks behind,
//! missing exactly the dependencies that were going to keep them in order.
//!
//! Applying is idempotent. Each task a plan files is remembered by the name it
//! had in the file, so applying the same plan again recognizes its own work and
//! adds only what is new. That is what makes a plan file something you can edit
//! and re-run rather than something you get one shot at.
//!
//! What it will not do is rewrite tasks that already exist. A plan is how work
//! is filed, not a description the queue is kept in sync with: by the time you
//! edit the file an agent may have claimed a task, worked it, and recorded what
//! it learned. So a task whose title has drifted from the plan keeps the
//! queue's version, and [`Applied::drifted`] says so rather than letting the
//! difference pass unmentioned.

use rusqlite::{params, Connection, OptionalExtension, Transaction};

use super::deps::{dependency_path, id_for_seq};
use super::scope::{declare_in_tx, normalize_all, patterns_for_id, OnConflict};
use super::tasks::{create_in_tx, insert_dep, insert_event};
use crate::error::{Error, Result};
use crate::model::{now_ts, Conflict, EventKind};
use crate::plan::{Plan, PlanTask};

/// Repository over `task_plan_nodes`, and the one place a plan becomes rows.
pub struct Plans<'a> {
    conn: &'a Connection,
}

/// A task in the queue, under the name the plan gave it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Placed {
    pub name: String,
    pub seq: i64,
    pub title: String,
}

/// A task the plan describes differently from how the queue holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Drift {
    pub name: String,
    pub seq: i64,
    /// Which part differs: `"title"`, `"body"`, `"priority"` or
    /// `"requirements"`.
    pub field: &'static str,
}

impl Drift {
    /// One sentence, as `hird plan apply` prints it.
    pub fn describe(&self) -> String {
        format!(
            "#{} ({}) — the plan's {} differs from the queue's, and the queue's \
             was kept; edit it with the task, not the file",
            self.seq, self.name, self.field
        )
    }
}

/// What applying a plan did.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Applied {
    /// Tasks this apply filed, in plan order.
    pub created: Vec<Placed>,
    /// Tasks an earlier apply of the same plan had already filed.
    pub reused: Vec<Placed>,
    /// Reused tasks the plan now describes differently.
    pub drifted: Vec<Drift>,
    /// Dependency edges this apply added.
    pub edges_added: usize,
    /// Overlaps between what the plan declares and what agents hold right now.
    pub conflicts: Vec<Conflict>,
}

impl Applied {
    /// Did this apply change anything at all?
    pub fn is_empty(&self) -> bool {
        self.created.is_empty() && self.edges_added == 0
    }
}

impl<'a> Plans<'a> {
    pub(crate) fn new(conn: &'a Connection) -> Plans<'a> {
        Plans { conn }
    }

    /// File every task in `plan` that is not filed already, with its
    /// dependencies and declared scopes, in one transaction.
    ///
    /// The plan has already been validated by [`crate::plan::parse`], so the
    /// only refusals left are ones the database knows about: a dependency that
    /// would close a cycle through an edge somebody added by hand.
    pub fn apply(&self, project: &str, plan: &Plan, actor: &str) -> Result<Applied> {
        let tx = super::immediate_tx(self.conn)?;
        let now = now_ts();
        let mut applied = Applied::default();
        // Name → (task id, seq), for the dependency pass below. Built as tasks
        // are created or found, so both passes see the same resolution.
        let mut placed: Vec<(&PlanTask, String, i64)> = Vec::new();

        for task in &plan.tasks {
            match find_node(&tx, project, &plan.plan, &task.name)? {
                Some(existing) => {
                    let planned_requirements = crate::capability::normalize_all(&task.requires)?;
                    let existing_requirements = super::requirements::for_id(&tx, &existing.id)?;
                    let field = drifted_field(&existing, task).or_else(|| {
                        (existing_requirements != planned_requirements).then_some("requirements")
                    });
                    if let Some(field) = field {
                        applied.drifted.push(Drift {
                            name: task.name.clone(),
                            seq: existing.seq,
                            field,
                        });
                    }
                    applied.reused.push(Placed {
                        name: task.name.clone(),
                        seq: existing.seq,
                        title: existing.title.clone(),
                    });
                    placed.push((task, existing.id, existing.seq));
                }
                None => {
                    let created =
                        create_in_tx(&tx, project, &task.title, &task.body, task.priority, actor)?;
                    let required = crate::capability::normalize_all(&task.requires)?;
                    super::requirements::set_in_tx(&tx, &created.id, &required, actor, &now_ts())?;
                    tx.execute(
                        "INSERT INTO task_plan_nodes (task_id, project, plan, node, at)
                         VALUES (?1, ?2, ?3, ?4, ?5)",
                        params![created.id, project, plan.plan, task.name, now],
                    )?;
                    insert_event(
                        &tx,
                        &created.id,
                        &now,
                        actor,
                        EventKind::Note,
                        &format!("filed from plan {:?} as {:?}", plan.plan, task.name),
                    )?;
                    applied.created.push(Placed {
                        name: task.name.clone(),
                        seq: created.seq,
                        title: created.title.clone(),
                    });
                    placed.push((task, created.id, created.seq));
                }
            }
        }

        // Scopes and dependencies go on after every task exists, so a plan may
        // name its tasks in any order — `needs` points backwards or forwards.
        //
        // Only patterns the task has not already declared are put through the
        // collision check. Re-declaring what is already on record changes
        // nothing, and warning about it would mean every re-apply reported the
        // overlaps of tasks it did not touch.
        for (task, id, seq) in &placed {
            if task.paths.is_empty() {
                continue;
            }
            let known = patterns_for_id(&tx, id)?;
            let fresh: Vec<String> = normalize_all(&task.paths)?
                .into_iter()
                .filter(|pattern| !known.contains(pattern))
                .collect();
            if fresh.is_empty() {
                continue;
            }
            applied
                .conflicts
                .extend(declare_in_tx(&tx, *seq, &fresh, actor, OnConflict::Report)?);
        }
        for (task, _, seq) in &placed {
            if task.review {
                super::tasks::set_review_in_tx(&tx, *seq, true, actor)?;
            }
        }
        for (task, id, seq) in &placed {
            for need in &task.needs {
                let Some((_, needed_id, needed_seq)) =
                    placed.iter().find(|(t, _, _)| &t.name == need)
                else {
                    // Unreachable: validation resolved every name in the plan.
                    continue;
                };
                applied.edges_added += usize::from(add_edge(
                    &tx,
                    id,
                    needed_id,
                    *seq,
                    *needed_seq,
                    actor,
                    &now,
                )?);
            }
        }

        tx.commit()?;
        Ok(applied)
    }

    /// Every task filed by `plan_name` in this project, in queue order.
    pub fn nodes(&self, project: &str, plan_name: &str) -> Result<Vec<(String, i64)>> {
        let mut stmt = self.conn.prepare(
            "SELECT n.node, t.seq FROM task_plan_nodes n
             JOIN tasks t ON t.id = n.task_id
             WHERE n.project = ?1 AND n.plan = ?2
             ORDER BY t.seq",
        )?;
        let rows = stmt.query_map(params![project, plan_name], |row| {
            Ok((row.get(0)?, row.get(1)?))
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    /// The plans that have filed work in this project, with how many tasks each.
    pub fn list(&self, project: &str) -> Result<Vec<(String, usize)>> {
        let mut stmt = self.conn.prepare(
            "SELECT plan, COUNT(*) FROM task_plan_nodes
             WHERE project = ?1 GROUP BY plan ORDER BY plan",
        )?;
        let rows = stmt.query_map([project], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as usize))
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    /// The plan and node name a task was filed under, if it came from a plan.
    pub fn origin_of(&self, seq: i64) -> Result<Option<(String, String)>> {
        let task_id = id_for_seq(self.conn, seq)?;
        Ok(self
            .conn
            .query_row(
                "SELECT plan, node FROM task_plan_nodes WHERE task_id = ?1",
                [&task_id],
                |row| Ok((row.get(0)?, row.get(1)?)),
            )
            .optional()?)
    }
}

// ------------------------------------------------------------------ helpers

/// A task an earlier apply of this plan filed.
struct Existing {
    id: String,
    seq: i64,
    title: String,
    body: String,
    priority: i64,
}

fn find_node(
    tx: &Transaction<'_>,
    project: &str,
    plan: &str,
    node: &str,
) -> Result<Option<Existing>> {
    Ok(tx
        .query_row(
            "SELECT t.id, t.seq, t.title, t.body, t.priority
             FROM task_plan_nodes n JOIN tasks t ON t.id = n.task_id
             WHERE n.project = ?1 AND n.plan = ?2 AND n.node = ?3",
            params![project, plan, node],
            |row| {
                Ok(Existing {
                    id: row.get(0)?,
                    seq: row.get(1)?,
                    title: row.get(2)?,
                    body: row.get(3)?,
                    priority: row.get(4)?,
                })
            },
        )
        .optional()?)
}

/// The first field the plan and the queue disagree about, if any.
fn drifted_field(existing: &Existing, task: &PlanTask) -> Option<&'static str> {
    if existing.title != task.title.trim() {
        return Some("title");
    }
    if existing.body != task.body {
        return Some("body");
    }
    if existing.priority != task.priority {
        return Some("priority");
    }
    None
}

/// Add one dependency edge, refusing anything that would close a cycle.
///
/// The plan itself is acyclic — validation saw to that — but a task an earlier
/// apply filed may have picked up edges since, from `hird dep add` or from an
/// agent splitting it. So the check is the same one [`super::Deps::add`] makes,
/// and the refusal reads the same way.
fn add_edge(
    tx: &Transaction<'_>,
    task_id: &str,
    needed_id: &str,
    seq: i64,
    needed_seq: i64,
    actor: &str,
    now: &str,
) -> Result<bool> {
    if let Some(path) = dependency_path(tx, needed_id, task_id)? {
        return Err(Error::DependencyCycle {
            seq,
            on: needed_seq,
            path,
        });
    }
    let existing: Option<i64> = tx
        .query_row(
            "SELECT 1 FROM task_deps WHERE task_id = ?1 AND depends_on_id = ?2",
            params![task_id, needed_id],
            |row| row.get(0),
        )
        .optional()?;
    if existing.is_some() {
        return Ok(false);
    }
    insert_dep(tx, task_id, needed_id, actor, now)?;
    insert_event(
        tx,
        task_id,
        now,
        actor,
        EventKind::DepAdded,
        &format!("now waits for task {needed_seq}"),
    )?;
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Db;
    use crate::model::Status;
    use crate::plan;
    use std::time::Duration;

    const PROJECT: &str = "/tmp/project";
    const ACTOR: &str = "cli";
    const TTL: Duration = Duration::from_secs(900);

    const SAMPLE: &str = r#"
plan = "serde-migration"

[[task]]
name = "schema"
title = "Design the storage schema"
priority = 3
paths = ["src/db.rs"]

[[task]]
name = "repos"
title = "Port the repository layer"
paths = ["src/repo/**"]
needs = ["schema"]

[[task]]
name = "renderer"
title = "Rewrite the renderer"
paths = ["src/tui/**"]
"#;

    fn db() -> Db {
        Db::open_in_memory().unwrap()
    }

    fn apply(db: &Db, source: &str) -> Applied {
        let plan = plan::parse(source).unwrap();
        db.plans().apply(PROJECT, &plan, ACTOR).unwrap()
    }

    #[test]
    fn a_plan_files_every_task_with_its_edges_and_scopes() {
        let db = db();
        let applied = apply(&db, SAMPLE);

        assert_eq!(applied.created.len(), 3);
        assert!(applied.reused.is_empty());
        assert_eq!(applied.edges_added, 1);
        // Numbered in plan order.
        assert_eq!(applied.created[0].name, "schema");
        assert_eq!(applied.created[0].seq, 1);
        assert_eq!(applied.created[2].seq, 3);

        assert_eq!(db.scopes().for_task(1).unwrap(), vec!["src/db.rs"]);
        let blockers = db.deps().blockers(2).unwrap();
        assert_eq!(blockers.len(), 1);
        assert_eq!(blockers[0].seq, 1);
    }

    #[test]
    fn applying_the_same_plan_again_files_nothing_new() {
        let db = db();
        apply(&db, SAMPLE);
        let again = apply(&db, SAMPLE);

        assert!(again.created.is_empty());
        assert_eq!(again.reused.len(), 3);
        assert_eq!(again.edges_added, 0);
        assert!(again.is_empty());
        assert_eq!(
            db.tasks()
                .list(&super::super::ProjectScope::All, None)
                .unwrap()
                .len(),
            3
        );
    }

    #[test]
    fn an_edited_plan_files_only_what_is_new() {
        let db = db();
        apply(&db, SAMPLE);
        let grown = apply(
            &db,
            &format!(
                "{SAMPLE}
[[task]]
name = \"notes\"
title = \"Write the release notes\"
needs = [\"repos\", \"renderer\"]
"
            ),
        );

        assert_eq!(grown.created.len(), 1);
        assert_eq!(grown.created[0].name, "notes");
        assert_eq!(grown.created[0].seq, 4);
        assert_eq!(grown.reused.len(), 3);
        assert_eq!(grown.edges_added, 2);
        assert_eq!(db.deps().blockers(4).unwrap().len(), 2);
    }

    #[test]
    fn a_task_the_plan_now_describes_differently_keeps_the_queues_version() {
        let db = db();
        apply(&db, SAMPLE);
        let edited = apply(
            &db,
            &SAMPLE.replace("Design the storage schema", "Design the schema"),
        );

        assert!(edited.created.is_empty());
        assert_eq!(edited.drifted.len(), 1);
        assert_eq!(edited.drifted[0].field, "title");
        assert_eq!(edited.drifted[0].seq, 1);
        assert!(edited.drifted[0]
            .describe()
            .contains("the queue's was kept"));
        assert_eq!(
            db.tasks().get(1).unwrap().title,
            "Design the storage schema"
        );
    }

    #[test]
    fn a_plan_applied_to_two_projects_files_each_separately() {
        let db = db();
        let plan = plan::parse(SAMPLE).unwrap();
        db.plans().apply(PROJECT, &plan, ACTOR).unwrap();
        let elsewhere = db.plans().apply("/tmp/other", &plan, ACTOR).unwrap();

        assert_eq!(elsewhere.created.len(), 3);
        assert_eq!(elsewhere.created[0].seq, 4);
    }

    #[test]
    fn nothing_is_written_when_an_edge_would_close_a_cycle() {
        // The plan itself is acyclic — validation saw to that. The ring can
        // only come from an edge added outside the plan, between two tasks an
        // earlier apply filed.
        let db = db();
        let first = "
plan = \"p\"
[[task]]
name = \"schema\"
title = \"Design the storage schema\"
[[task]]
name = \"repos\"
title = \"Port the repository layer\"
";
        apply(&db, first);
        // A human decides the schema should follow the port, and says so.
        db.deps().add(1, 2, ACTOR).unwrap();

        // The plan now claims the opposite, and brings a new task with it.
        let edited = plan::parse(
            "
plan = \"p\"
[[task]]
name = \"schema\"
title = \"Design the storage schema\"
[[task]]
name = \"repos\"
title = \"Port the repository layer\"
needs = [\"schema\"]
[[task]]
name = \"notes\"
title = \"Write the release notes\"
",
        )
        .unwrap();

        let err = db.plans().apply(PROJECT, &edited, ACTOR).unwrap_err();
        assert!(matches!(err, Error::DependencyCycle { .. }), "{err}");
        // The new task in the same plan was rolled back along with the edge.
        assert_eq!(
            db.tasks()
                .list(&super::super::ProjectScope::All, None)
                .unwrap()
                .len(),
            2
        );
    }

    #[test]
    fn filing_a_plan_over_live_work_reports_the_overlap() {
        let db = db();
        let held = db
            .tasks()
            .create(PROJECT, "Rework the renderer", "", 0, ACTOR)
            .unwrap();
        db.scopes()
            .declare(
                held.seq,
                &["src/tui/view.rs".into()],
                ACTOR,
                OnConflict::Report,
            )
            .unwrap();
        db.tasks().claim(held.seq, "codex:9f2c", TTL).unwrap();

        let applied = apply(&db, SAMPLE);
        assert_eq!(applied.created.len(), 3);
        assert_eq!(applied.conflicts.len(), 1);
        assert_eq!(applied.conflicts[0].other_seq, held.seq);
        assert_eq!(applied.conflicts[0].pattern, "src/tui/**");
    }

    #[test]
    fn re_applying_says_nothing_about_scopes_it_did_not_touch() {
        // The renderer goes live, which the audit has always overlapped. That
        // was worth saying when the audit's scope was declared; saying it again
        // on every re-apply would train the human to skip the warnings.
        let db = db();
        apply(&db, SAMPLE);
        db.tasks().claim(3, "codex:9f2c", TTL).unwrap();

        let again = apply(&db, SAMPLE);
        assert!(again.conflicts.is_empty(), "{:?}", again.conflicts);

        // A pattern the plan has actually gained is a different matter.
        let widened = apply(
            &db,
            &SAMPLE.replace(
                "paths = [\"src/repo/**\"]",
                "paths = [\"src/repo/**\", \"src/tui/view.rs\"]",
            ),
        );
        assert_eq!(widened.conflicts.len(), 1);
        assert_eq!(widened.conflicts[0].other_seq, 3);
        assert_eq!(
            db.scopes().for_task(2).unwrap(),
            vec!["src/repo/**", "src/tui/view.rs"]
        );
    }

    #[test]
    fn a_filed_task_remembers_the_plan_it_came_from() {
        let db = db();
        apply(&db, SAMPLE);

        assert_eq!(
            db.plans().origin_of(2).unwrap(),
            Some(("serde-migration".into(), "repos".into()))
        );
        assert_eq!(
            db.plans().nodes(PROJECT, "serde-migration").unwrap(),
            vec![
                ("schema".to_string(), 1),
                ("repos".to_string(), 2),
                ("renderer".to_string(), 3)
            ]
        );
        assert_eq!(
            db.plans().list(PROJECT).unwrap(),
            vec![("serde-migration".to_string(), 3)]
        );
    }

    #[test]
    fn a_task_filed_by_hand_has_no_plan_behind_it() {
        let db = db();
        let task = db.tasks().create(PROJECT, "By hand", "", 0, ACTOR).unwrap();
        assert_eq!(db.plans().origin_of(task.seq).unwrap(), None);
    }

    #[test]
    fn tasks_a_plan_filed_are_ordinary_tasks() {
        // Nothing about a planned task is special: it claims, works and
        // completes like any other, and its dependency still gates it.
        let db = db();
        apply(&db, SAMPLE);

        let err = db.tasks().claim(2, "codex:9f2c", TTL).unwrap_err();
        assert!(matches!(err, Error::Blocked { .. }), "{err}");

        db.tasks().claim(1, "codex:9f2c", TTL).unwrap();
        db.tasks().complete(1, "codex:9f2c", "schema done").unwrap();
        let claimed = db.tasks().claim(2, "codex:9f2c", TTL).unwrap();
        assert_eq!(claimed.status, Status::Claimed);
        assert_eq!(db.scopes().for_task(2).unwrap(), vec!["src/repo/**"]);
    }

    #[test]
    fn a_plan_files_capability_requirements_with_the_task() {
        let db = db();
        let source = SAMPLE.replace(
            "paths = [\"src/repo/**\"]",
            "paths = [\"src/repo/**\"]\nrequires = [\"browser\", \"network\"]",
        );
        apply(&db, &source);
        assert_eq!(
            db.requirements().for_task(2).unwrap(),
            vec!["browser", "network"]
        );
    }
}