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
//! Database handle: connection setup, pragmas and schema migrations.
//!
//! One SQLite file backs every `hird` process on the machine. Concurrency is
//! handled by WAL plus a busy timeout; every write is a short transaction and
//! there is no daemon holding the file open.

use std::path::{Path, PathBuf};

use rusqlite::Connection;

use crate::error::Result;
use crate::repo::{
    Deps, Events, Footings, Memory, Plans, Questions, Recall, Recesses, Recusals, Requirements,
    Scopes, Tasks, Verdicts, Witnessed,
};

/// Numbered migrations, applied in order and recorded in `meta.schema_version`.
const MIGRATIONS: &[&str] = &[
    // 1 — initial schema
    r#"
CREATE TABLE tasks (
  id          TEXT PRIMARY KEY,
  seq         INTEGER UNIQUE NOT NULL,
  project     TEXT NOT NULL,
  title       TEXT NOT NULL,
  body        TEXT NOT NULL DEFAULT '',
  status      TEXT NOT NULL DEFAULT 'open'
              CHECK (status IN ('open','claimed','in_progress','done','failed','cancelled')),
  priority    INTEGER NOT NULL DEFAULT 0,
  claimed_by  TEXT,
  lease_expires_at TEXT,
  result      TEXT,
  created_at  TEXT NOT NULL,
  updated_at  TEXT NOT NULL
);

CREATE TABLE task_events (
  id         TEXT PRIMARY KEY,
  task_id    TEXT NOT NULL REFERENCES tasks(id),
  at         TEXT NOT NULL,
  actor      TEXT NOT NULL,
  kind       TEXT NOT NULL,
  detail     TEXT NOT NULL DEFAULT ''
);

CREATE TABLE assertions (
  id         TEXT PRIMARY KEY,
  project    TEXT NOT NULL,
  content    TEXT NOT NULL,
  tags       TEXT NOT NULL DEFAULT '',
  actor      TEXT NOT NULL,
  task_id    TEXT REFERENCES tasks(id),
  superseded_by TEXT REFERENCES assertions(id),
  created_at TEXT NOT NULL
);

CREATE VIRTUAL TABLE assertions_fts USING fts5(
  content, tags, content='assertions', content_rowid='rowid'
);

CREATE TRIGGER assertions_fts_ai AFTER INSERT ON assertions BEGIN
  INSERT INTO assertions_fts(rowid, content, tags)
  VALUES (new.rowid, new.content, new.tags);
END;

CREATE TRIGGER assertions_fts_ad AFTER DELETE ON assertions BEGIN
  INSERT INTO assertions_fts(assertions_fts, rowid, content, tags)
  VALUES ('delete', old.rowid, old.content, old.tags);
END;

CREATE TRIGGER assertions_fts_au AFTER UPDATE ON assertions BEGIN
  INSERT INTO assertions_fts(assertions_fts, rowid, content, tags)
  VALUES ('delete', old.rowid, old.content, old.tags);
  INSERT INTO assertions_fts(rowid, content, tags)
  VALUES (new.rowid, new.content, new.tags);
END;

CREATE INDEX idx_tasks_project_status ON tasks(project, status);
CREATE INDEX idx_tasks_status_lease ON tasks(status, lease_expires_at);
CREATE INDEX idx_task_events_task_at ON task_events(task_id, at);
CREATE INDEX idx_assertions_project_current ON assertions(project, superseded_by);

INSERT INTO meta(key, value) VALUES ('next_seq', '1');
"#,
    // 2 — dependencies between tasks, and the file scopes tasks declare
    r#"
CREATE TABLE task_deps (
  task_id       TEXT NOT NULL REFERENCES tasks(id),
  depends_on_id TEXT NOT NULL REFERENCES tasks(id),
  actor         TEXT NOT NULL,
  created_at    TEXT NOT NULL,
  PRIMARY KEY (task_id, depends_on_id),
  CHECK (task_id <> depends_on_id)
);

CREATE INDEX idx_task_deps_depends_on ON task_deps(depends_on_id);

CREATE TABLE task_paths (
  id          TEXT PRIMARY KEY,
  task_id     TEXT NOT NULL REFERENCES tasks(id),
  pattern     TEXT NOT NULL,
  declared_by TEXT NOT NULL,
  at          TEXT NOT NULL,
  UNIQUE (task_id, pattern)
);

CREATE INDEX idx_task_paths_task ON task_paths(task_id);
"#,
    // 3 — the witness: what the working tree says actually happened
    r#"
CREATE TABLE task_witness (
  task_id    TEXT PRIMARY KEY REFERENCES tasks(id),
  head       TEXT NOT NULL DEFAULT '',
  tree       TEXT NOT NULL DEFAULT '{}',
  at         TEXT NOT NULL
);

CREATE TABLE task_changes (
  id         TEXT PRIMARY KEY,
  task_id    TEXT NOT NULL REFERENCES tasks(id),
  path       TEXT NOT NULL,
  kind       TEXT NOT NULL CHECK (kind IN ('added','modified','deleted')),
  hash       TEXT NOT NULL DEFAULT '',
  first_seen TEXT NOT NULL,
  last_seen  TEXT NOT NULL,
  UNIQUE (task_id, path)
);

CREATE INDEX idx_task_changes_path ON task_changes(path);
CREATE INDEX idx_task_changes_task ON task_changes(task_id);
"#,
    // 4 — the name a plan file gave a task, so a plan can be applied twice
    r#"
CREATE TABLE task_plan_nodes (
  task_id    TEXT PRIMARY KEY REFERENCES tasks(id),
  project    TEXT NOT NULL,
  plan       TEXT NOT NULL,
  node       TEXT NOT NULL,
  at         TEXT NOT NULL,
  UNIQUE (project, plan, node)
);
"#,
    // 5 — the footing under an assertion: the files it was read off, the
    //     versions they were in, and everyone who has said it since
    r#"
CREATE TABLE assertion_footing (
  assertion_id TEXT NOT NULL REFERENCES assertions(id),
  path         TEXT NOT NULL,
  hash         TEXT NOT NULL DEFAULT '',
  -- 1 when the author named this file rather than hird deriving it from the
  -- task. A named footing is never overruled by settling.
  named        INTEGER NOT NULL DEFAULT 0,
  at           TEXT NOT NULL,
  PRIMARY KEY (assertion_id, path)
);

CREATE INDEX idx_assertion_footing_path ON assertion_footing(path);

CREATE TABLE assertion_affirmations (
  assertion_id TEXT NOT NULL REFERENCES assertions(id),
  actor        TEXT NOT NULL,
  at           TEXT NOT NULL,
  PRIMARY KEY (assertion_id, actor)
);
"#,
    // 6 — recusal: work one harness must not be the one to check
    r#"
CREATE TABLE task_recusals (
  task_id      TEXT NOT NULL REFERENCES tasks(id),
  -- Whoever worked this task is barred from working task_id.
  from_task_id TEXT NOT NULL REFERENCES tasks(id),
  reason       TEXT NOT NULL DEFAULT '',
  actor        TEXT NOT NULL,
  at           TEXT NOT NULL,
  PRIMARY KEY (task_id, from_task_id),
  CHECK (task_id <> from_task_id)
);

CREATE INDEX idx_task_recusals_from ON task_recusals(from_task_id);

-- 1 when finishing this task should put its work in front of somebody else.
ALTER TABLE tasks ADD COLUMN review INTEGER NOT NULL DEFAULT 0;
"#,
    // 7 — the verdict: what a review concluded, on the record, acted on
    r#"
CREATE TABLE task_verdicts (
  id        TEXT PRIMARY KEY,
  -- The review that delivered the verdict.
  review_id TEXT NOT NULL REFERENCES tasks(id),
  -- The work it judged.
  task_id   TEXT NOT NULL REFERENCES tasks(id),
  verdict   TEXT NOT NULL CHECK (verdict IN ('upheld','sent_back')),
  -- Whoever's work was judged: the holder of record when the verdict landed.
  worker    TEXT NOT NULL DEFAULT '',
  -- Whoever delivered it.
  reviewer  TEXT NOT NULL,
  at        TEXT NOT NULL,
  CHECK (review_id <> task_id)
);

CREATE INDEX idx_task_verdicts_task ON task_verdicts(task_id);
CREATE INDEX idx_task_verdicts_review ON task_verdicts(review_id);
"#,
    // 8 — the exhibit: the file versions the witness saw, kept by content
    r#"
CREATE TABLE witness_blobs (
  -- The same content hash the witness records everywhere else, so a hash in
  -- a baseline or a change row is also the key to what the file said.
  hash    TEXT PRIMARY KEY,
  content BLOB NOT NULL,
  size    INTEGER NOT NULL,
  -- When this version was last seen, not first: re-sighting refreshes it,
  -- which is what keeps pruning from throwing away versions still in play.
  at      TEXT NOT NULL
);
"#,
    // 9 — the tenure: a task remembers every hand that held it. A fresh claim
    //     used to overwrite the previous holder's baseline and footprint; now
    //     it archives them first, one row per holding.
    r#"
-- Who the baseline was taken for, so an archived tenure can say whose
-- holding it describes without replaying the event trail.
ALTER TABLE task_witness ADD COLUMN holder TEXT NOT NULL DEFAULT '';

CREATE TABLE task_tenures (
  id       TEXT PRIMARY KEY,
  task_id  TEXT NOT NULL REFERENCES tasks(id),
  -- 1-based per task, in the order the holdings ended.
  n        INTEGER NOT NULL,
  holder   TEXT NOT NULL DEFAULT '',
  began_at TEXT NOT NULL,
  -- How the holding ended: completed, failed, released, lease_expired or
  -- cancelled. Empty when the trail could not say.
  ended    TEXT NOT NULL DEFAULT '',
  ended_at TEXT NOT NULL DEFAULT '',
  -- The baseline the holding was measured against, verbatim from
  -- task_witness: the commit and the fingerprint of what was dirty.
  head     TEXT NOT NULL DEFAULT '',
  tree     TEXT NOT NULL DEFAULT '{}',
  archived_at TEXT NOT NULL,
  UNIQUE (task_id, n)
);

CREATE INDEX idx_task_tenures_task ON task_tenures(task_id);

CREATE TABLE tenure_changes (
  tenure_id  TEXT NOT NULL REFERENCES task_tenures(id),
  path       TEXT NOT NULL,
  kind       TEXT NOT NULL CHECK (kind IN ('added','modified','deleted')),
  hash       TEXT NOT NULL DEFAULT '',
  first_seen TEXT NOT NULL,
  last_seen  TEXT NOT NULL,
  PRIMARY KEY (tenure_id, path)
);

CREATE INDEX idx_tenure_changes_hash ON tenure_changes(hash);
"#,
    // 10 — the question: work that waits for an answer rather than churning
    //      through agents that cannot supply it
    r#"
CREATE TABLE task_questions (
  id          TEXT PRIMARY KEY,
  task_id     TEXT NOT NULL REFERENCES tasks(id),
  n           INTEGER NOT NULL,
  asked_by    TEXT NOT NULL,
  question    TEXT NOT NULL,
  asked_at    TEXT NOT NULL,
  answer      TEXT,
  answered_by TEXT,
  answered_at TEXT,
  UNIQUE (task_id, n)
);

CREATE INDEX idx_task_questions_task ON task_questions(task_id, n);
CREATE UNIQUE INDEX idx_task_questions_one_open
  ON task_questions(task_id) WHERE answer IS NULL;
"#,
    // 11 — the fit: work states what a claimant must be equipped to do
    r#"
CREATE TABLE task_requirements (
  task_id    TEXT NOT NULL REFERENCES tasks(id),
  capability TEXT NOT NULL,
  PRIMARY KEY (task_id, capability)
);

CREATE INDEX idx_task_requirements_capability
  ON task_requirements(capability, task_id);
"#,
    // 12 — the recess: a project's queue stood down by the human. A row here
    //      is the whole state: while it exists nothing is handed out, and
    //      `hird resume` deletes it.
    r#"
CREATE TABLE project_recess (
  project TEXT PRIMARY KEY,
  reason  TEXT NOT NULL DEFAULT '',
  actor   TEXT NOT NULL,
  at      TEXT NOT NULL
);
"#,
];

/// An open connection to the hird database.
///
/// All SQL lives behind this handle's repositories; the MCP, CLI and TUI
/// layers only ever touch [`Db::tasks`] and [`Db::memory`].
pub struct Db {
    conn: Connection,
    path: PathBuf,
}

impl Db {
    /// Open (creating if needed) the database at `path`.
    pub fn open(path: impl AsRef<Path>) -> Result<Db> {
        let path = path.as_ref().to_path_buf();
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    crate::error::Error::invalid(format!(
                        "cannot create database directory {}: {e}",
                        parent.display()
                    ))
                })?;
            }
        }
        let conn = Connection::open(&path)?;
        Self::from_connection(conn, path)
    }

    /// Open a private in-memory database. Used by tests.
    pub fn open_in_memory() -> Result<Db> {
        let conn = Connection::open_in_memory()?;
        Self::from_connection(conn, PathBuf::from(":memory:"))
    }

    fn from_connection(conn: Connection, path: PathBuf) -> Result<Db> {
        // `journal_mode` returns a row, so it needs `query_row` rather than
        // `execute_batch` on some builds; pragma_update_and_check handles both.
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "busy_timeout", 5000)?;
        conn.pragma_update(None, "synchronous", "NORMAL")?;
        conn.pragma_update(None, "foreign_keys", "ON")?;
        let db = Db { conn, path };
        db.migrate()?;
        Ok(db)
    }

    /// The path this handle was opened from.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Raw connection access, for tests that need to set up states the
    /// repository layer deliberately refuses to create.
    #[cfg(test)]
    pub(crate) fn conn(&self) -> &Connection {
        &self.conn
    }

    /// Task and task-event repository.
    pub fn tasks(&self) -> Tasks<'_> {
        Tasks::new(&self.conn)
    }

    /// Questions that keep otherwise-open tasks waiting for human input.
    pub fn questions(&self) -> Questions<'_> {
        Questions::new(&self.conn)
    }

    /// Capabilities a worker must advertise before claiming a task.
    pub fn requirements(&self) -> Requirements<'_> {
        Requirements::new(&self.conn)
    }

    /// The event trail read across tasks, in the order things happened.
    pub fn events(&self) -> Events<'_> {
        Events::new(&self.conn)
    }

    /// Assertion repository.
    pub fn memory(&self) -> Memory<'_> {
        Memory::new(&self.conn)
    }

    /// Task dependency graph repository.
    pub fn deps(&self) -> Deps<'_> {
        Deps::new(&self.conn)
    }

    /// Declared file scope repository.
    pub fn scopes(&self) -> Scopes<'_> {
        Scopes::new(&self.conn)
    }

    /// Plan filing: a whole graph of tasks in one transaction.
    pub fn plans(&self) -> Plans<'_> {
        Plans::new(&self.conn)
    }

    /// What the working tree was seen to do while tasks were held.
    pub fn witnessed(&self) -> Witnessed<'_> {
        Witnessed::new(&self.conn)
    }

    /// What assertions were learned against, and who else has said them.
    pub fn footings(&self) -> Footings<'_> {
        Footings::new(&self.conn)
    }

    /// Who must not work a task, because of what they already worked.
    pub fn recusals(&self) -> Recusals<'_> {
        Recusals::new(&self.conn)
    }

    /// Projects the human has stood down, and the standing down of them.
    pub fn recesses(&self) -> Recesses<'_> {
        Recesses::new(&self.conn)
    }

    /// What reviews concluded, and what the queue did about it.
    pub fn verdicts(&self) -> Verdicts<'_> {
        Verdicts::new(&self.conn)
    }

    /// The memory relevant to a task, derived from the other three.
    pub fn recall(&self) -> Recall<'_> {
        Recall::new(&self.conn)
    }

    /// The schema version currently applied.
    pub fn schema_version(&self) -> Result<u32> {
        let raw: Option<String> = self
            .conn
            .query_row(
                "SELECT value FROM meta WHERE key = 'schema_version'",
                [],
                |row| row.get(0),
            )
            .ok();
        Ok(raw.and_then(|v| v.parse().ok()).unwrap_or(0))
    }

    fn migrate(&self) -> Result<()> {
        // `meta` must exist before we can read the version out of it.
        self.conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
        )?;
        let applied = self.schema_version()?;
        let known = MIGRATIONS.len() as u32;
        if applied > known {
            return Err(crate::error::Error::invalid(schema_from_the_future(
                &self.path, applied, known,
            )));
        }
        for (idx, sql) in MIGRATIONS.iter().enumerate() {
            let version = idx as u32 + 1;
            if version <= applied {
                continue;
            }
            let tx = self.conn.unchecked_transaction()?;
            tx.execute_batch(sql)?;
            tx.execute(
                "INSERT INTO meta(key, value) VALUES ('schema_version', ?1)
                 ON CONFLICT(key) DO UPDATE SET value = excluded.value",
                [version.to_string()],
            )?;
            tx.commit()?;
        }
        Ok(())
    }
}

/// The refusal for a database migrated by a hird newer than this binary.
///
/// Left to run on, an old binary would fail later, mid-call, on a table or
/// column it has never heard of — an error indistinguishable from corruption.
/// Refusing at open costs nothing (no migration has run yet, so nothing has
/// been written) and can name both versions and the fix.
fn schema_from_the_future(path: &Path, found: u32, known: u32) -> String {
    let binary = std::env::current_exe()
        .ok()
        .map(|p| format!(" ({})", p.display()))
        .unwrap_or_default();
    format!(
        "database {} is at schema version {found}, but this hird binary{binary} only \
         knows versions up to {known} — a newer hird has migrated it. Upgrade this \
         binary (re-run scripts/install.sh) and try again; the database was not changed",
        path.display()
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn opening_applies_every_migration() {
        let db = Db::open_in_memory().unwrap();
        assert_eq!(db.schema_version().unwrap(), MIGRATIONS.len() as u32);
    }

    #[test]
    fn reopening_an_existing_file_is_a_no_op() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nested").join("hird.db");
        let first = Db::open(&path).unwrap();
        let seq = first.tasks().create("/p", "t", "", 0, "cli").unwrap().seq;
        drop(first);

        let second = Db::open(&path).unwrap();
        assert_eq!(second.schema_version().unwrap(), MIGRATIONS.len() as u32);
        assert_eq!(second.tasks().get(seq).unwrap().title, "t");
    }

    #[test]
    fn a_database_from_a_newer_hird_is_refused_by_name() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hird.db");
        let ahead = (MIGRATIONS.len() as u32 + 5).to_string();
        {
            let db = Db::open(&path).unwrap();
            db.conn()
                .execute(
                    "UPDATE meta SET value = ?1 WHERE key = 'schema_version'",
                    [&ahead],
                )
                .unwrap();
        }

        let err = match Db::open(&path) {
            Ok(_) => panic!("a database from the future must be refused"),
            Err(e) => e.to_string(),
        };
        assert!(err.contains(&format!("schema version {ahead}")), "{err}");
        assert!(
            err.contains(&format!("up to {}", MIGRATIONS.len())),
            "{err}"
        );
        assert!(err.contains("hird.db"), "{err}");

        // The refusal must not have moved the version it refused over.
        let reread = Connection::open(&path).unwrap();
        let stored: String = reread
            .query_row(
                "SELECT value FROM meta WHERE key = 'schema_version'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(stored, ahead);
    }

    #[test]
    fn fts5_is_available_in_the_bundled_sqlite() {
        let db = Db::open_in_memory().unwrap();
        db.conn()
            .execute_batch("CREATE VIRTUAL TABLE probe USING fts5(x)")
            .expect("bundled SQLite must be built with FTS5");
    }

    #[test]
    fn wal_and_foreign_keys_are_on_for_file_databases() {
        let dir = tempfile::tempdir().unwrap();
        let db = Db::open(dir.path().join("hird.db")).unwrap();
        let mode: String = db
            .conn()
            .query_row("PRAGMA journal_mode", [], |r| r.get(0))
            .unwrap();
        assert_eq!(mode.to_lowercase(), "wal");
        let fk: i64 = db
            .conn()
            .query_row("PRAGMA foreign_keys", [], |r| r.get(0))
            .unwrap();
        assert_eq!(fk, 1);
    }
}