use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use anyhow::Context;
use chrono::Utc;
use clap::{Args, Parser, Subcommand};
use crate::config::{self, Config};
use crate::db::Db;
use crate::exhibit;
use crate::fmt;
use crate::footing;
use crate::glob;
use crate::herald::{announce_claimable, sweep_announcing, Cause, Herald};
use crate::identity::{self, ACTOR_CLI};
use crate::model::{Footprint, Standing, Status, TaskSummary};
use crate::plan;
use crate::register::{self, Registration};
use crate::repo::{dispatch_waves, Called, MemoryQuery, NewAssertion, OnConflict, ProjectScope};
use crate::witness;
#[derive(Debug, Parser)]
#[command(
name = "hird",
version,
about,
long_about = None,
arg_required_else_help = true
)]
pub struct Cli {
#[arg(long, global = true, value_name = "PATH")]
pub db: Option<PathBuf>,
#[arg(long)]
pub install: bool,
#[arg(long)]
pub install_skill: bool,
#[command(subcommand)]
pub command: Option<Command>,
}
#[derive(Debug, Subcommand)]
pub enum Command {
Add(AddArgs),
#[command(visible_alias = "list")]
Ls(LsArgs),
Show { seq: i64 },
Why { seq: i64 },
Blame {
path: String,
},
Digest {
#[arg(long, value_name = "WHEN")]
since: Option<String>,
#[arg(long)]
peek: bool,
#[command(flatten)]
scope: ScopeFilterArgs,
},
Handoff { seq: i64 },
Diff {
seq: i64,
#[arg(long)]
path: Option<String>,
#[arg(long, value_name = "N")]
tenure: Option<i64>,
},
Salvage {
seq: i64,
path: String,
#[arg(long)]
baseline: bool,
#[arg(long, value_name = "N")]
tenure: Option<i64>,
#[arg(long, value_name = "FILE")]
out: Option<PathBuf>,
#[arg(long)]
force: bool,
},
Cancel {
seq: i64,
#[arg(long, default_value = "")]
reason: String,
},
Reopen {
seq: i64,
#[arg(long, default_value = "")]
reason: String,
},
Answer {
seq: i64,
answer: String,
},
Recess {
#[arg(default_value = "")]
reason: String,
#[arg(long, value_name = "PATH")]
project: Option<PathBuf>,
},
Resume {
#[arg(long, value_name = "PATH")]
project: Option<PathBuf>,
},
#[command(subcommand)]
Dep(DepCommand),
#[command(subcommand)]
Plan(PlanCommand),
Graph(GraphArgs),
Scope(ScopeArgs),
Require(RequireArgs),
Agents(ScopeFilterArgs),
Recuse(RecuseArgs),
Record(ScopeFilterArgs),
Events(EventsArgs),
Replay {
when: String,
#[command(flatten)]
scope: ScopeFilterArgs,
},
Recall {
seq: i64,
#[arg(long, value_name = "N")]
limit: Option<usize>,
},
#[command(subcommand)]
Mem(MemCommand),
Tui,
Web(WebArgs),
Mcp,
Register(RegisterArgs),
DbPath,
}
#[derive(Debug, Args)]
pub struct EventsArgs {
#[arg(long, short = 'f')]
pub follow: bool,
#[arg(long)]
pub json: bool,
#[arg(long = "kind", value_name = "KIND", value_delimiter = ',')]
pub kinds: Vec<crate::model::EventKind>,
#[arg(long, value_name = "SEQ")]
pub task: Option<i64>,
#[arg(long, value_name = "NAME")]
pub actor: Option<String>,
#[arg(long, value_name = "N", default_value_t = 30)]
pub limit: usize,
#[arg(long)]
pub all_projects: bool,
}
#[derive(Debug, Args)]
pub struct RegisterArgs {
pub harness: register::Harness,
#[arg(long, default_value = "hird", value_name = "NAME")]
pub name: String,
#[arg(long)]
pub print: bool,
#[arg(long, conflicts_with = "print")]
pub force: bool,
#[arg(long = "capability", value_name = "NAME", value_delimiter = ',')]
pub capabilities: Vec<String>,
}
#[derive(Debug, Args)]
pub struct AddArgs {
pub title: String,
#[arg(long, conflicts_with = "body_file")]
pub body: Option<String>,
#[arg(long, value_name = "PATH")]
pub body_file: Option<PathBuf>,
#[arg(long, default_value_t = 0, allow_negative_numbers = true)]
pub priority: i64,
#[arg(long, value_name = "PATH")]
pub project: Option<PathBuf>,
#[arg(long = "needs", value_name = "SEQ", value_delimiter = ',')]
pub needs: Vec<i64>,
#[arg(long = "path", value_name = "GLOB")]
pub paths: Vec<String>,
#[arg(long = "requires", value_name = "CAPABILITY", value_delimiter = ',')]
pub requirements: Vec<String>,
#[arg(long)]
pub review: bool,
}
#[derive(Debug, Subcommand)]
pub enum PlanCommand {
Apply {
file: PathBuf,
#[arg(long)]
dry_run: bool,
#[arg(long, value_name = "PATH")]
project: Option<PathBuf>,
},
Export {
#[arg(long, value_name = "NAME")]
plan: Option<String>,
#[arg(long, value_name = "NAME")]
name: Option<String>,
#[arg(long)]
all: bool,
#[arg(long, value_name = "PATH")]
project: Option<PathBuf>,
},
Lint {
file: PathBuf,
#[arg(long, value_name = "PATH")]
project: Option<PathBuf>,
},
}
#[derive(Debug, Subcommand)]
pub enum DepCommand {
Add {
seq: i64,
#[arg(
long = "needs",
value_name = "SEQ",
required = true,
value_delimiter = ','
)]
needs: Vec<i64>,
},
#[command(visible_alias = "remove")]
Rm {
seq: i64,
#[arg(
long = "needs",
value_name = "SEQ",
required = true,
value_delimiter = ','
)]
needs: Vec<i64>,
},
}
#[derive(Debug, Args)]
pub struct ScopeArgs {
pub seq: i64,
#[arg(long = "path", value_name = "GLOB")]
pub paths: Vec<String>,
#[arg(long, conflicts_with = "paths")]
pub clear: bool,
}
#[derive(Debug, Args)]
pub struct RecuseArgs {
pub seq: i64,
#[arg(long = "from", value_name = "SEQ", value_delimiter = ',')]
pub from: Vec<i64>,
#[arg(long, default_value = "")]
pub reason: String,
#[arg(long, conflicts_with = "from")]
pub clear: bool,
}
#[derive(Debug, Args)]
pub struct ScopeFilterArgs {
#[arg(long)]
pub all_projects: bool,
}
#[derive(Debug, Args)]
pub struct WebArgs {
#[arg(long, default_value_t = 7473)]
pub port: u16,
#[arg(long, default_value = "127.0.0.1", value_name = "ADDR")]
pub bind: String,
#[command(flatten)]
pub scope: ScopeFilterArgs,
}
#[derive(Debug, Args)]
pub struct GraphArgs {
#[command(flatten)]
pub scope: ScopeFilterArgs,
#[arg(long, conflicts_with_all = ["mermaid", "json"])]
pub dot: bool,
#[arg(long, conflicts_with = "json")]
pub mermaid: bool,
#[arg(long)]
pub json: bool,
#[arg(long, value_name = "NAME")]
pub plan: Option<String>,
}
#[derive(Debug, Args)]
pub struct RequireArgs {
pub seq: i64,
#[arg(long = "capability", value_name = "NAME", value_delimiter = ',')]
pub capabilities: Vec<String>,
#[arg(long, conflicts_with = "capabilities")]
pub clear: bool,
}
#[derive(Debug, Args)]
pub struct LsArgs {
#[arg(long, value_name = "STATUS")]
pub status: Option<String>,
#[arg(long)]
pub all_projects: bool,
}
#[derive(Debug, Subcommand)]
pub enum MemCommand {
Add {
content: String,
#[arg(long, default_value = "")]
tags: String,
#[arg(long, value_name = "SEQ")]
task: Option<i64>,
#[arg(long = "path", value_name = "PATH")]
paths: Vec<String>,
},
Search {
#[arg(default_value = "")]
query: String,
#[arg(long, default_value_t = 20)]
limit: usize,
#[arg(long)]
all_projects: bool,
#[arg(long)]
include_superseded: bool,
},
Standing {
#[arg(long)]
shaky: bool,
#[arg(long)]
all_projects: bool,
},
Export {
#[arg(long, value_name = "GLOB")]
path: Option<String>,
#[arg(long)]
firm: bool,
},
}
pub fn run(cli: &Cli, out: &mut impl Write) -> anyhow::Result<()> {
if let Some(Command::Register(args)) = &cli.command {
return register_cmd(args, cli.db.as_deref(), out);
}
let db_path = config::resolve_db_path(cli.db.as_deref());
if let Some(Command::DbPath) = &cli.command {
writeln!(out, "{}", db_path.display())?;
return Ok(());
}
let config = Config::load_default()?;
let db = Db::open(&db_path).with_context(|| format!("opening {}", db_path.display()))?;
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let project = identity::resolve_project(&cwd);
let herald = config.herald(&db_path);
sweep_announcing(&db, &config, herald.as_ref());
match cli
.command
.as_ref()
.context("a command or installer option is required")?
{
Command::DbPath | Command::Register(_) => unreachable!("handled above"),
Command::Tui | Command::Mcp | Command::Web(_) => {
anyhow::bail!(
"`hird {}` is served by the binary, not the command dispatcher",
match &cli.command {
Some(Command::Tui) => "tui",
Some(Command::Web(_)) => "web",
_ => "mcp",
}
)
}
Command::Add(args) => {
let seq = add(&db, &project, args, out)?;
announce_claimable(herald.as_ref(), &db, &config, Cause::Filed, seq);
Ok(())
}
Command::Ls(args) => {
look(&db, &config, &project);
ls(&db, &project, &config, args, out)
}
Command::Show { seq } => {
look(&db, &config, &project);
show(&db, *seq, &config, out)
}
Command::Why { seq } => why(&db, *seq, &config, out),
Command::Diff { seq, path, tenure } => {
diff(&db, *seq, path.as_deref(), *tenure, &config, out)
}
Command::Salvage {
seq,
path,
baseline,
tenure,
out: to,
force,
} => salvage(
&db,
*seq,
path,
*baseline,
*tenure,
to.as_deref(),
*force,
&config,
out,
),
Command::Recall { seq, limit } => recall(
&db,
&config,
&project,
*seq,
limit.map(|n| n.min(200)).unwrap_or(config.recall_limit()),
out,
),
Command::Cancel { seq, reason } => {
let task = db.tasks().cancel(*seq, ACTOR_CLI, reason)?;
writeln!(out, "task {} cancelled", task.seq)?;
Ok(())
}
Command::Reopen { seq, reason } => {
let task = db.tasks().reopen(*seq, ACTOR_CLI, reason)?;
writeln!(out, "task {} reopened", task.seq)?;
announce_claimable(herald.as_ref(), &db, &config, Cause::Reopened, task.seq);
Ok(())
}
Command::Answer { seq, answer } => {
let answered = db.questions().answer(*seq, ACTOR_CLI, answer)?;
writeln!(out, "task {} answered", seq)?;
writeln!(out, " question {}", answered.question)?;
writeln!(
out,
" answer {}",
answered.answer.as_deref().unwrap_or("")
)?;
announce_claimable(herald.as_ref(), &db, &config, Cause::Answered, *seq);
Ok(())
}
Command::Recess {
reason,
project: explicit,
} => recess_cmd(&db, &named_project(explicit, &project), reason, out),
Command::Resume { project: explicit } => resume_cmd(
&db,
&config,
herald.as_ref(),
&named_project(explicit, &project),
out,
),
Command::Mem(cmd) => mem(&db, &project, &config, cmd, out),
Command::Dep(cmd) => dep(&db, &config, herald.as_ref(), cmd, out),
Command::Plan(cmd) => plan_cmd(&db, &project, &config, herald.as_ref(), cmd, out),
Command::Graph(args) => {
let scope = scope_of(&project, &config, args.scope.all_projects);
let plan = args.plan.as_deref();
if args.json {
let snapshot = crate::graph::Snapshot::live(&db, &scope, plan)?;
writeln!(out, "{}", serde_json::to_string_pretty(&snapshot)?)?;
Ok(())
} else if args.dot || args.mermaid {
graph_render(&db, &scope, plan, args.mermaid, out)
} else {
graph(&db, &scope, plan, out)
}
}
Command::Blame { path } => {
look(&db, &config, &project);
blame(&db, &config, &project, path, out)
}
Command::Digest { since, peek, scope } => {
look(&db, &config, &project);
digest_cmd(
&db,
&scope_of(&project, &config, scope.all_projects),
since.as_deref(),
*peek,
out,
)
}
Command::Handoff { seq } => {
look(&db, &config, &project);
handoff(&db, &config, *seq, out)
}
Command::Scope(args) => scope_cmd(&db, args, out),
Command::Require(args) => require_cmd(&db, args, out),
Command::Agents(args) => {
look(&db, &config, &project);
agents(&db, &scope_of(&project, &config, args.all_projects), out)
}
Command::Recuse(args) => recuse(&db, args, out),
Command::Record(args) => record(&db, &scope_of(&project, &config, args.all_projects), out),
Command::Replay { when, scope } => replay(
&db,
&scope_of(&project, &config, scope.all_projects),
when,
out,
),
Command::Events(args) => events_cmd(&db, &project, &config, herald.as_ref(), args, out),
}
}
fn register_cmd(
args: &RegisterArgs,
db: Option<&Path>,
out: &mut impl Write,
) -> anyhow::Result<()> {
let harness = args.harness;
let registration =
Registration::new(harness, &args.name, db).with_capabilities(&args.capabilities)?;
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
if args.print {
writeln!(
out,
"# {} — {}",
harness.label(),
harness.config_path(&cwd).display()
)?;
write!(out, "{}", registration.render(harness))?;
return Ok(());
}
let (path, outcome) = register::apply(harness, ®istration, &cwd, args.force)?;
writeln!(out, "{}", outcome.describe(®istration.name, &path))?;
writeln!(
out,
" command {} {}",
registration.command,
registration.args.join(" ")
)?;
let env: Vec<String> = registration
.env
.iter()
.map(|(key, value)| format!("{key}={value}"))
.collect();
writeln!(out, " env {}", env.join(" "))?;
writeln!(out, "next: {}", harness.next_step())?;
Ok(())
}
fn look(db: &Db, config: &Config, project: &str) {
let Some(witness) = config.witness(Path::new(project)) else {
return;
};
let _ = witness::sweep(db, &witness, project, ACTOR_CLI);
}
fn scope_of(project: &str, config: &Config, all_projects: bool) -> ProjectScope {
ProjectScope::resolve(project, config.all_projects(Some(all_projects)))
}
fn named_project(explicit: &Option<PathBuf>, resolved: &str) -> String {
match explicit {
Some(root) => identity::canonical_project(root),
None => resolved.to_string(),
}
}
fn recess_cmd(db: &Db, project: &str, reason: &str, out: &mut impl Write) -> anyhow::Result<()> {
match db.recesses().call(project, reason, ACTOR_CLI)? {
Called::Began(recess) => {
writeln!(
out,
"queue for {project} in recess{}",
recess.quoted_reason()
)?;
writeln!(
out,
" nothing new is handed out; work already claimed continues"
)?;
writeln!(out, " hird resume lifts it")?;
}
Called::AlreadyStanding {
recess,
reason_changed,
} => {
let note = if reason_changed {
"; reason updated"
} else {
""
};
writeln!(
out,
"already in recess since {}{note}",
fmt::age_phrase(&recess.at, Utc::now())
)?;
}
}
Ok(())
}
fn resume_cmd(
db: &Db,
config: &Config,
herald: Option<&Herald>,
project: &str,
out: &mut impl Write,
) -> anyhow::Result<()> {
match db.recesses().lift(project)? {
None => writeln!(
out,
"the queue for {project} was not in recess; nothing to lift"
)?,
Some(_) => {
writeln!(out, "recess lifted for {project} — claims resume")?;
let scope = ProjectScope::Only(project.to_string());
for task in db.tasks().list(&scope, Some(Status::Open))? {
announce_claimable(herald, db, config, Cause::Resumed, task.seq);
}
}
}
Ok(())
}
fn recess_banner(recess: &crate::model::Recess, now: chrono::DateTime<Utc>) -> String {
format!(
"in recess{} — called {}; nothing new is handed out, hird resume lifts it",
recess.quoted_reason(),
fmt::age_phrase(&recess.at, now)
)
}
fn events_cmd(
db: &Db,
project: &str,
config: &Config,
herald: Option<&Herald>,
args: &EventsArgs,
out: &mut impl Write,
) -> anyhow::Result<()> {
let scope = scope_of(project, config, args.all_projects);
let filter = crate::repo::FeedFilter {
kinds: args.kinds.clone(),
task_seq: args.task,
actor: args.actor.clone(),
};
look(db, config, project);
let backlog = db.events().tail(&scope, &filter, args.limit)?;
let mut cursor = backlog.last().map(|e| e.cursor).unwrap_or(0);
if backlog.is_empty() && !args.follow && !args.json {
writeln!(out, "nothing on the record yet")?;
}
for event in &backlog {
write_event(out, event, args.json, scope.is_all())?;
}
if !args.follow {
return Ok(());
}
out.flush()?;
let mut last_look = Utc::now();
loop {
std::thread::sleep(crate::tui::app::POLL_INTERVAL);
if let Ok(outcome) = db.tasks().sweep_leases() {
for seq in outcome.expired {
announce_claimable(herald, db, config, Cause::LeaseExpired, seq);
}
}
let now = Utc::now();
if now - last_look >= crate::tui::app::WITNESS_INTERVAL {
last_look = now;
look(db, config, project);
}
for event in db.events().since(&scope, &filter, cursor)? {
cursor = event.cursor;
write_event(out, &event, args.json, scope.is_all())?;
}
out.flush()?;
}
}
fn write_event(
out: &mut impl Write,
event: &crate::repo::FeedEvent,
json: bool,
all_projects: bool,
) -> anyhow::Result<()> {
if json {
writeln!(
out,
"{}",
serde_json::json!({
"cursor": event.cursor,
"at": event.at,
"project": event.project,
"task": event.task_seq,
"title": event.task_title,
"actor": event.actor,
"kind": event.kind.as_str(),
"detail": event.detail,
})
)?;
return Ok(());
}
let clock = crate::model::parse_ts(&event.at)
.map(|at| at.format("%H:%M:%S").to_string())
.unwrap_or_else(|| "??:??:??".into());
let what = if event.detail.is_empty() {
fmt::truncate(&event.task_title, 76)
} else {
fmt::truncate(&event.detail, 76)
};
let task = format!("#{}", event.task_seq);
if all_projects {
writeln!(
out,
"{clock} {task:>4} {:<14} {:<18} {what} [{}]",
event.kind, event.actor, event.project
)?;
} else {
writeln!(
out,
"{clock} {task:>4} {:<14} {:<18} {what}",
event.kind, event.actor
)?;
}
Ok(())
}
fn add(db: &Db, project: &str, args: &AddArgs, out: &mut impl Write) -> anyhow::Result<i64> {
let body = match (&args.body, &args.body_file) {
(Some(body), _) => body.clone(),
(None, Some(path)) => read_text(path)?,
(None, None) => String::new(),
};
let project = match &args.project {
Some(explicit) => identity::canonical_project(explicit),
None => project.to_string(),
};
let task = db
.tasks()
.create(&project, &args.title, &body, args.priority, ACTOR_CLI)?;
for needed in &args.needs {
db.deps().add(task.seq, *needed, ACTOR_CLI)?;
}
if !args.paths.is_empty() {
db.scopes()
.declare(task.seq, &args.paths, ACTOR_CLI, OnConflict::Report)?;
}
if !args.requirements.is_empty() {
db.requirements()
.set(task.seq, &args.requirements, ACTOR_CLI)?;
}
if args.review {
db.tasks().set_review(task.seq, true, ACTOR_CLI)?;
}
writeln!(out, "{}", task.seq)?;
Ok(task.seq)
}
fn dep(
db: &Db,
config: &Config,
herald: Option<&Herald>,
cmd: &DepCommand,
out: &mut impl Write,
) -> anyhow::Result<()> {
match cmd {
DepCommand::Add { seq, needs } => {
for needed in needs {
if db.deps().add(*seq, *needed, ACTOR_CLI)? {
writeln!(out, "task {seq} now waits for task {needed}")?;
} else {
writeln!(out, "task {seq} already waited for task {needed}")?;
}
}
}
DepCommand::Rm { seq, needs } => {
for needed in needs {
if db.deps().remove(*seq, *needed, ACTOR_CLI)? {
writeln!(out, "task {seq} no longer waits for task {needed}")?;
} else {
writeln!(out, "task {seq} was not waiting for task {needed}")?;
}
}
announce_claimable(herald, db, config, Cause::Unblocked, *seq);
}
}
Ok(())
}
fn plan_cmd(
db: &Db,
project: &str,
config: &Config,
herald: Option<&Herald>,
cmd: &PlanCommand,
out: &mut impl Write,
) -> anyhow::Result<()> {
let (file, explicit) = match cmd {
PlanCommand::Apply { file, project, .. } | PlanCommand::Lint { file, project } => {
(file, project)
}
PlanCommand::Export {
plan: only,
name,
all,
project: explicit,
} => {
let project = match explicit {
Some(root) => identity::canonical_project(root),
None => project.to_string(),
};
return plan_export(db, &project, only.as_deref(), name.as_deref(), *all, out);
}
};
let source = read_text(file)?;
let parsed =
plan::parse(&source).with_context(|| format!("reading the plan in {}", file.display()))?;
let project = match explicit {
Some(root) => identity::canonical_project(root),
None => project.to_string(),
};
let dry_run = match cmd {
PlanCommand::Lint { .. } => return lint(db, &project, &parsed, out),
PlanCommand::Apply { dry_run, .. } => *dry_run,
PlanCommand::Export { .. } => unreachable!("handled above"),
};
if dry_run {
return preview(db, &project, &parsed, out);
}
let applied = db.plans().apply(&project, &parsed, ACTOR_CLI)?;
for placed in &applied.created {
announce_claimable(herald, db, config, Cause::Filed, placed.seq);
}
if applied.created.is_empty() {
writeln!(
out,
"plan {:?} is already filed in full; nothing to do",
parsed.plan
)?;
} else {
writeln!(
out,
"filed {} from plan {:?}",
count(applied.created.len(), "task"),
parsed.plan
)?;
for placed in &applied.created {
writeln!(
out,
" #{:<4} {:<14} {}",
placed.seq,
fmt::truncate(&placed.name, 14),
fmt::truncate(&placed.title, 44)
)?;
}
}
if !applied.reused.is_empty() && !applied.created.is_empty() {
let numbers: Vec<String> = applied
.reused
.iter()
.map(|p| format!("#{}", p.seq))
.collect();
writeln!(
out,
"{} already filed: {}",
count(applied.reused.len(), "task"),
numbers.join(", ")
)?;
}
if applied.edges_added > 0 {
writeln!(out, "{} recorded", count(applied.edges_added, "dependency"))?;
}
for drift in &applied.drifted {
writeln!(out, "note: {}", drift.describe())?;
}
for conflict in &applied.conflicts {
writeln!(out, "warning: {}", conflict.describe())?;
}
Ok(())
}
fn preview(
db: &Db,
project: &str,
parsed: &plan::Plan,
out: &mut impl Write,
) -> anyhow::Result<()> {
let preview = parsed.preview();
let filed: BTreeMap<String, i64> = db
.plans()
.nodes(project, &parsed.plan)?
.into_iter()
.collect();
writeln!(
out,
"plan {:?} — {}, {}, at most {} at once",
parsed.plan,
count(parsed.tasks.len(), "task"),
count(preview.waves.len(), "wave"),
preview.widest()
)?;
for (index, wave) in preview.waves.iter().enumerate() {
let label = match index {
0 => "wave 1 (workable now)".to_string(),
n => format!("wave {} (after wave {n})", n + 1),
};
writeln!(out, "\n{label}")?;
for name in wave {
let Some(task) = parsed.task(name) else {
continue;
};
let number = match filed.get(name) {
Some(seq) => format!("#{seq}"),
None => "new".to_string(),
};
let mut line = format!(
" {:<5} {:<14} {}",
number,
fmt::truncate(name, 14),
fmt::truncate(&task.title, 40)
);
if !task.needs.is_empty() {
line.push_str(&format!(" waits for {}", task.needs.join(", ")));
}
writeln!(out, "{line}")?;
if !task.paths.is_empty() {
writeln!(out, " files {}", task.paths.join(", "))?;
}
if !task.requires.is_empty() {
writeln!(out, " requires {}", task.requires.join(", "))?;
}
}
}
if !preview.collisions.is_empty() {
writeln!(
out,
"\nsame files, nothing ordering them — the queue hands these out one \
at a time, so the waves above are wider than the work really is"
)?;
for collision in &preview.collisions {
writeln!(out, " {}", collision.describe())?;
}
}
if !preview.unscoped.is_empty() {
writeln!(
out,
"\ndeclaring no files: {}\n the queue cannot keep another agent out \
of what these touch, and what earlier work learned reaches them by \
title alone",
preview.unscoped.join(", ")
)?;
}
let already = filed.len();
if already == 0 {
writeln!(out, "\nnothing was written; drop --dry-run to file it")?;
} else {
writeln!(
out,
"\nnothing was written; {} of these already filed, so applying would \
file the other {}",
already,
parsed.tasks.len() - already
)?;
}
Ok(())
}
fn mem_export(
db: &Db,
project: &str,
witness: Option<&witness::Witness>,
path: Option<&str>,
firm_only: bool,
out: &mut impl Write,
) -> anyhow::Result<()> {
let wanted = match path {
Some(raw) => Some(glob::normalize(raw).ok_or_else(|| {
anyhow::anyhow!("--path {raw:?} is not a usable glob; try src/**, or a literal path")
})?),
None => None,
};
if firm_only && witness.is_none() {
anyhow::bail!(
"--firm needs a watched tree to check anchors against; run inside the \
project's git checkout, or export without it"
);
}
let scope = ProjectScope::Only(project.to_string());
let mut facts = db
.memory()
.search(&MemoryQuery::new("", scope).limit(10_000))?;
facts.sort_by(|a, b| (&a.created_at, &a.id).cmp(&(&b.created_at, &b.id)));
let ids: Vec<String> = facts.iter().map(|a| a.id.clone()).collect();
let anchors = db.footings().anchors_for(Some(project), &ids)?;
let standings = footing::standings(db, witness, project, &ids);
let kept: Vec<&crate::model::Assertion> = facts
.iter()
.filter(|fact| match &wanted {
Some(glob) => anchors
.get(&fact.id)
.is_some_and(|list| list.iter().any(|a| crate::glob::intersects(glob, &a.path))),
None => true,
})
.filter(|fact| !firm_only || matches!(standings.get(&fact.id), Some(Standing::Firm { .. })))
.collect();
if kept.is_empty() {
writeln!(out, "nothing to export; hird mem add is how facts get here")?;
return Ok(());
}
writeln!(out, "## What earlier work here learned")?;
writeln!(out)?;
writeln!(
out,
"<!-- hird mem export, {}. Facts recorded by agents working this\n\
project, each anchored to the files it was read off. One marked\n\
\"re-check\" has had that ground rewritten since it was learned. -->",
Utc::now().format("%Y-%m-%d")
)?;
writeln!(out)?;
for fact in kept {
writeln!(out, "- {}", fact.content.trim())?;
let mut notes: Vec<String> = Vec::new();
if let Some(list) = anchors.get(&fact.id).filter(|l| !l.is_empty()) {
let paths: Vec<String> = list.iter().map(|a| format!("`{}`", a.path)).collect();
notes.push(paths.join(", "));
}
match standings.get(&fact.id) {
Some(Standing::Shaky { .. }) => {
notes.push("re-check: the ground under this has moved since".to_string());
}
Some(Standing::Orphaned { .. }) => {
notes.push("re-check: the files this was read off are gone".to_string());
}
_ => {}
}
if let Some(spoken) = footing::corroboration(db, fact) {
notes.push(spoken);
}
if !notes.is_empty() {
writeln!(out, " — {}", notes.join("; "))?;
}
}
Ok(())
}
fn plan_export(
db: &Db,
project: &str,
only: Option<&str>,
name: Option<&str>,
all: bool,
out: &mut impl Write,
) -> anyhow::Result<()> {
let scope = ProjectScope::Only(project.to_string());
let origins = db.plans().origins(project)?;
let mut tasks: Vec<TaskSummary> = db
.tasks()
.list(&scope, None)?
.into_iter()
.filter(|t| all || !t.status.is_terminal())
.filter(|t| match only {
Some(plan) => origins.get(&t.seq).is_some_and(|(p, _)| p == plan),
None => true,
})
.collect();
tasks.sort_by_key(|t| t.seq);
if tasks.is_empty() {
match only {
Some(plan) => writeln!(out, "# plan {plan:?} has filed nothing here to export")?,
None if all => writeln!(out, "# nothing filed in this project to export")?,
None => writeln!(
out,
"# no unfinished tasks to export; --all includes the finished ones"
)?,
}
return Ok(());
}
let mut taken: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
let mut names: BTreeMap<i64, String> = BTreeMap::new();
for task in &tasks {
let wanted = match origins.get(&task.seq) {
Some((plan, node)) if only.is_none_or(|p| p == plan) => node.clone(),
_ => slug(&task.title),
};
let name = if taken.insert(wanted.clone()) {
wanted
} else {
let numbered = format!("{wanted}-{}", task.seq);
taken.insert(numbered.clone());
numbered
};
names.insert(task.seq, name);
}
let mut dropped: Vec<String> = Vec::new();
let mut needs: BTreeMap<i64, Vec<String>> = BTreeMap::new();
for (task, on) in db.deps().edges(&scope)? {
let Some(from) = names.get(&task) else {
continue;
};
match names.get(&on) {
Some(to) => needs.entry(task).or_default().push(to.clone()),
None => dropped.push(format!("{from} waited for #{on}")),
}
}
let plan_name = name
.map(str::to_string)
.or_else(|| only.map(str::to_string))
.unwrap_or_else(|| {
Path::new(project)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "board".to_string())
});
let mut exported = plan::Plan {
plan: plan_name,
tasks: Vec::new(),
};
for summary in &tasks {
let task = db.tasks().get(summary.seq)?;
exported.tasks.push(plan::PlanTask {
name: names[&task.seq].clone(),
title: task.title.clone(),
body: task.body.trim().to_string(),
priority: task.priority,
paths: db.scopes().for_task(task.seq)?,
requires: db.requirements().for_task(task.seq)?,
needs: needs.remove(&task.seq).unwrap_or_default(),
review: task.review,
});
}
let toml = exported.to_toml();
plan::parse(&toml).context("the exported plan does not read back; this is a bug in hird")?;
writeln!(
out,
"# hird plan export, {}: {} from {project}",
Utc::now().format("%Y-%m-%d"),
count(tasks.len(), "task")
)?;
for (seq, name) in &names {
writeln!(out, "# {name} was #{seq}")?;
}
for line in &dropped {
writeln!(out, "# dropped: {line}, which is not in this export")?;
}
writeln!(out)?;
write!(out, "{toml}")?;
Ok(())
}
fn slug(title: &str) -> String {
let mut name = String::new();
let mut gap = false;
for c in title.chars() {
if c.is_ascii_alphanumeric() {
if gap && !name.is_empty() {
name.push('-');
}
name.push(c.to_ascii_lowercase());
gap = false;
} else {
gap = true;
}
}
let cut: String = name.chars().take(40).collect();
let cut = cut.trim_end_matches('-').to_string();
if cut.is_empty() {
"task".to_string()
} else {
cut
}
}
fn graph_render(
db: &Db,
scope: &ProjectScope,
plan: Option<&str>,
mermaid: bool,
out: &mut impl Write,
) -> anyhow::Result<()> {
let (tasks, edges) = graph_inputs(db, scope, plan)?;
let waves = dispatch_waves(&tasks, &edges);
let by_seq: BTreeMap<i64, &TaskSummary> = tasks.iter().map(|t| (t.seq, t)).collect();
let pending: std::collections::BTreeSet<i64> = waves.iter().flatten().copied().collect();
let shown: std::collections::BTreeSet<i64> = pending
.iter()
.copied()
.chain(
edges
.iter()
.filter(|(t, _)| pending.contains(t))
.map(|(_, on)| *on),
)
.collect();
let drawn: Vec<&(i64, i64)> = edges
.iter()
.filter(|(t, on)| shown.contains(t) && shown.contains(on))
.collect();
let label = |t: &TaskSummary| {
let title = fmt::truncate(&t.title, 40).replace('"', "'");
match &t.claimed_by {
Some(holder) => format!("#{} {title}\\n{} · {holder}", t.seq, t.status),
None => format!("#{} {title}\\n{}", t.seq, t.status),
}
};
if mermaid {
writeln!(out, "flowchart LR")?;
for (index, wave) in waves.iter().enumerate() {
writeln!(out, " subgraph wave{} [\"wave {}\"]", index + 1, index + 1)?;
for seq in wave {
if let Some(t) = by_seq.get(seq) {
writeln!(out, " t{seq}[\"{}\"]", label(t).replace("\\n", "<br/>"))?;
}
}
writeln!(out, " end")?;
}
for seq in shown.difference(&pending) {
if let Some(t) = by_seq.get(seq) {
writeln!(out, " t{seq}([\"{}\"])", label(t).replace("\\n", "<br/>"))?;
}
}
for (task, on) in drawn {
writeln!(out, " t{on} --> t{task}")?;
}
for seq in &shown {
if let Some(t) = by_seq.get(seq) {
writeln!(
out,
" style t{seq} fill:{},stroke:#555",
status_colour(t.status)
)?;
}
}
return Ok(());
}
writeln!(out, "digraph hird {{")?;
writeln!(out, " rankdir=LR;")?;
writeln!(
out,
" node [shape=box, style=\"rounded,filled\", fontname=\"Helvetica\"];"
)?;
for (index, wave) in waves.iter().enumerate() {
writeln!(out, " subgraph cluster_wave{} {{", index + 1)?;
writeln!(out, " label=\"wave {}\"; color=\"#999999\";", index + 1)?;
for seq in wave {
if let Some(t) = by_seq.get(seq) {
writeln!(
out,
" t{seq} [label=\"{}\", fillcolor=\"{}\"];",
label(t),
status_colour(t.status)
)?;
}
}
writeln!(out, " }}")?;
}
for seq in shown.difference(&pending) {
if let Some(t) = by_seq.get(seq) {
writeln!(
out,
" t{seq} [label=\"{}\", fillcolor=\"{}\", style=\"rounded,filled,dashed\"];",
label(t),
status_colour(t.status)
)?;
}
}
for (task, on) in drawn {
writeln!(out, " t{on} -> t{task};")?;
}
writeln!(out, "}}")?;
Ok(())
}
fn status_colour(status: Status) -> &'static str {
match status {
Status::Open => "#ffffff",
Status::Claimed => "#fff3b0",
Status::InProgress => "#ffe066",
Status::Done => "#c7f0c2",
Status::Failed => "#f5b7b1",
Status::Cancelled => "#dddddd",
}
}
fn blame(
db: &Db,
config: &Config,
project: &str,
raw: &str,
out: &mut impl Write,
) -> anyhow::Result<()> {
let path = raw.trim().trim_start_matches("./").trim_end_matches('/');
if path.is_empty() {
anyhow::bail!("blame wants a project-relative path, as `hird show` lists them");
}
let now = Utc::now();
let scope = ProjectScope::Only(project.to_string());
let mut lines = 0usize;
writeln!(out, "{path}")?;
let declared: Vec<_> = db
.scopes()
.declared(&scope, false)?
.into_iter()
.filter_map(|task| {
let via: Vec<&str> = task
.patterns
.iter()
.filter(|p| glob::matches(p, path))
.map(String::as_str)
.collect();
(!via.is_empty()).then(|| {
let holder = task
.holder
.as_deref()
.map(|h| format!(", {h}"))
.unwrap_or_default();
format!(
" #{:<4} {:<12} {}{holder} via {}",
task.seq,
task.status,
fmt::truncate(&task.title, 40),
via.join(", ")
)
})
})
.collect();
if !declared.is_empty() {
writeln!(out, "declared by")?;
for line in &declared {
writeln!(out, "{line}")?;
}
lines += declared.len();
}
let touches = db.witnessed().history_of(project, path)?;
if !touches.is_empty() {
writeln!(out, "changed under")?;
for touch in &touches {
let round = match touch.round {
Some(n) => format!(" round {n}"),
None => String::new(),
};
let holder = touch
.holder
.as_deref()
.map(|h| format!(", {h}"))
.unwrap_or_default();
writeln!(
out,
" #{:<4} {:<12} {}{round}{holder} {}, {}",
touch.seq,
touch.status,
fmt::truncate(&touch.title, 40),
touch.kind,
fmt::age_phrase(&touch.last_seen, now)
)?;
}
lines += touches.len();
}
let anchored = db.footings().anchored_to(project, path)?;
if !anchored.is_empty() {
let discovered = config.witness(Path::new(project));
let ids: Vec<String> = anchored.iter().map(|(a, _)| a.id.clone()).collect();
let standings = footing::standings(db, config.footing(discovered.as_ref()), project, &ids);
writeln!(out, "on record")?;
for (fact, anchor) in &anchored {
let standing = standings
.get(&fact.id)
.map(|s| s.as_str())
.unwrap_or("unchecked");
writeln!(out, " - {}", fmt::truncate(&fact.content, 88))?;
writeln!(
out,
" {standing}; {} recorded it {}",
fact.actor,
fmt::age_phrase(&anchor.at, now)
)?;
}
lines += anchored.len();
}
if lines == 0 {
writeln!(
out,
" nothing on record: no task declared it, the witness never saw it move, \
and no assertion is anchored to it"
)?;
}
Ok(())
}
fn digest_cmd(
db: &Db,
scope: &ProjectScope,
since: Option<&str>,
peek: bool,
out: &mut impl Write,
) -> anyhow::Result<()> {
const BOOKMARK: &str = "digest";
let now = Utc::now();
let filter = crate::repo::FeedFilter::default();
let mark = match scope {
ProjectScope::Only(project) => Some(project.as_str()),
_ => None,
};
let (events, window) = match since {
Some(raw) => {
let cutoff = parse_when(raw, now)?;
let events = db.events().after(scope, &filter, &cutoff)?;
(events, format!("since {}", fmt::age_phrase(&cutoff, now)))
}
None => {
let cursor = match mark {
Some(project) => db.bookmarks().get(BOOKMARK, project)?,
None => None,
};
let events = db.events().since(scope, &filter, cursor.unwrap_or(0))?;
let window = match (cursor, events.first()) {
(Some(_), Some(first)) => {
format!("since you last looked, {}", fmt::age_phrase(&first.at, now))
}
(Some(_), None) => "since you last looked".to_string(),
(None, _) => "since the board began".to_string(),
};
(events, window)
}
};
let digest = crate::digest::fold(&events);
if events.is_empty() {
writeln!(out, "nothing has happened {window}")?;
} else {
writeln!(
out,
"{} on {} {window}",
count(digest.events, "event"),
count(digest.tasks.len(), "task")
)?;
for section in digest.render(scope.is_all()) {
writeln!(out, "\n{section}")?;
}
}
if let (Some(project), None, false, Some(cursor)) = (mark, since, peek, digest.cursor) {
db.bookmarks().set(BOOKMARK, project, cursor)?;
}
Ok(())
}
fn handoff(db: &Db, config: &Config, seq: i64, out: &mut impl Write) -> anyhow::Result<()> {
let task = db.tasks().get(seq)?;
let now = Utc::now();
writeln!(out, "# Task #{}: {}", task.seq, task.title)?;
writeln!(out)?;
writeln!(
out,
"<!-- hird handoff, {}. Everything the queue would hand an agent on\n\
claiming this task. Report back through any harness registered with\n\
hird, or hand the result to whoever can. -->",
now.format("%Y-%m-%d")
)?;
writeln!(out)?;
let mut facts: Vec<String> = vec![format!("**status** {}", task.status)];
if let Some(holder) = &task.claimed_by {
facts.push(format!("**held by** {holder}"));
}
if task.priority != 0 {
facts.push(format!("**priority** {}", task.priority));
}
let requires = db.requirements().for_task(seq)?;
if !requires.is_empty() {
facts.push(format!("**requires** {}", requires.join(", ")));
}
if task.review {
facts.push("**review** on finishing, by another harness".to_string());
}
for recusal in db.recusals().for_task(seq)? {
facts.push(format!("**recused** {}", recusal.describe()));
}
writeln!(out, "{}", facts.join(" \n"))?;
writeln!(out, "\n## Instructions\n")?;
if task.body.trim().is_empty() {
writeln!(out, "_No body beyond the title._")?;
} else {
writeln!(out, "{}", task.body.trim())?;
}
let (blockers, _) = db.tasks().readiness(seq, config.clearance())?;
if !blockers.is_empty() {
writeln!(out, "\n## Still waiting for\n")?;
for b in &blockers {
match b.pending_review {
Some(review) if b.status == Status::Done => writeln!(
out,
"- #{} {} (done, under review {review})",
b.seq, b.title
)?,
_ => writeln!(out, "- #{} {} ({})", b.seq, b.title, b.status)?,
}
}
}
let ground = db.deps().ground(seq)?;
if !ground.is_empty() {
writeln!(out, "\n## Builds on\n")?;
for g in &ground {
writeln!(
out,
"- **#{} {}** — {}",
g.seq,
g.title,
g.standing.describe()
)?;
if let Some(result) = g.result.as_deref().filter(|r| !r.trim().is_empty()) {
writeln!(out, " {}", result.trim().replace('\n', "\n "))?;
}
}
}
let questions = db.questions().for_task(seq)?;
if !questions.is_empty() {
writeln!(out, "\n## Questions\n")?;
for q in &questions {
writeln!(out, "- **Q** {}", q.question.trim())?;
match &q.answer {
Some(a) => writeln!(out, " **A** {}", a.trim())?,
None => writeln!(out, " _unanswered — `hird answer {seq} <ANSWER>`_")?,
}
}
}
let judged = db.verdicts().for_task(seq)?;
if let Some(latest) = judged.last() {
writeln!(out, "\n## Verdict\n")?;
writeln!(out, "{}", latest.describe())?;
}
let patterns = db.scopes().for_task(seq)?;
let touched = db.witnessed().touched(seq).unwrap_or_default();
if !patterns.is_empty() || !touched.is_empty() {
writeln!(out, "\n## Files\n")?;
if !patterns.is_empty() {
writeln!(out, "Declared:")?;
for p in &patterns {
writeln!(out, "- `{p}`")?;
}
}
if !touched.is_empty() {
let footprint = db.witnessed().footprint(seq).unwrap_or_default();
match footprint.describe(task.status.is_active()) {
Some(sentence) => writeln!(out, "\nAlready moved under this task ({sentence}):")?,
None => writeln!(out, "\nAlready moved under this task:")?,
}
for o in &touched {
writeln!(out, "- `{}` ({})", o.path, o.kind)?;
}
}
for c in db.witnessed().contention(seq).unwrap_or_default() {
writeln!(out, "\n> {}", c.describe())?;
}
}
let discovered = config.witness(Path::new(&task.project));
let recalled = footing::decorate(
db,
config.footing(discovered.as_ref()),
db.recall().for_task(seq, config.recall_limit())?,
);
if !recalled.is_empty() {
writeln!(out, "\n## What earlier work learned\n")?;
for item in &recalled {
writeln!(out, "- {}", item.assertion.content.trim())?;
let mut notes = vec![item.reason.describe()];
if let Some(why) = item
.standing
.as_ref()
.filter(|s| s.needs_checking())
.and_then(Standing::describe)
{
notes.push(format!("re-check: {why}"));
}
if let Some(voices) = &item.corroboration {
notes.push(voices.clone());
}
writeln!(out, " — {}", notes.join("; "))?;
}
}
writeln!(out, "\n## Reporting back\n")?;
writeln!(
out,
"Through a harness that has hird: `task_claim {seq}`, then `task_complete {seq}` \
with a result, or `task_release {seq}` with a question. Facts worth keeping go in \
with `mem_store`, naming the files they were read off."
)?;
Ok(())
}
fn replay(db: &Db, scope: &ProjectScope, when: &str, out: &mut impl Write) -> anyhow::Result<()> {
let now = Utc::now();
let cutoff = parse_when(when, now)?;
let board = db.events().board_at(scope, &cutoff)?;
let age = crate::model::parse_ts(&cutoff)
.map(|_| format!(" — {}", fmt::age_phrase(&cutoff, now)))
.unwrap_or_default();
writeln!(out, "the board as of {cutoff}{age}")?;
if board.is_empty() {
writeln!(out, "nothing had been filed yet")?;
return Ok(());
}
for task in &board {
let mut line = format!(
"#{:<4} {:<11} {}",
task.seq,
task.status,
fmt::truncate(&task.title, 48)
);
if let Some(holder) = &task.holder {
line.push_str(&format!(" [{holder}]"));
}
if task.awaiting_answer {
line.push_str(" awaits answer");
}
if scope.is_all() {
line.push_str(&format!(" ({})", task.project));
}
writeln!(out, "{}", line.trim_end())?;
}
Ok(())
}
pub(crate) fn parse_when(raw: &str, now: chrono::DateTime<Utc>) -> anyhow::Result<String> {
let raw = raw.trim();
if let Some(digits) = raw.strip_suffix(['s', 'm', 'h', 'd']) {
if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) {
let n: i64 = digits.parse()?;
let delta = match raw.chars().last() {
Some('s') => chrono::Duration::seconds(n),
Some('m') => chrono::Duration::minutes(n),
Some('h') => chrono::Duration::hours(n),
_ => chrono::Duration::days(n),
};
return Ok(crate::model::fmt_ts(now - delta));
}
}
let looks_absolute = raw.len() >= 4
&& raw.starts_with(|c: char| c.is_ascii_digit())
&& raw
.chars()
.all(|c| c.is_ascii_digit() || matches!(c, '-' | ':' | 'T' | '.' | 'Z' | '+'));
if looks_absolute {
return Ok(raw.to_string());
}
anyhow::bail!(
"replay wants a moment: an RFC3339 UTC instant (\"2026-08-14T10:00\", prefixes \
welcome) or how long ago (\"90m\", \"2h\", \"3d\"), not {raw:?}"
)
}
fn lint(db: &Db, project: &str, parsed: &plan::Plan, out: &mut impl Write) -> anyhow::Result<()> {
let preview = parsed.preview();
let mut advisories = 0usize;
writeln!(
out,
"plan {:?} parses — {}, {}, at most {} at once",
parsed.plan,
count(parsed.tasks.len(), "task"),
count(preview.waves.len(), "wave"),
preview.widest()
)?;
for collision in &preview.collisions {
advisories += 1;
writeln!(out, "collision {}", collision.describe())?;
writeln!(
out,
" nothing orders them, so the queue hands them out one at a time"
)?;
}
if !preview.unscoped.is_empty() {
advisories += 1;
writeln!(out, "unscoped {}", preview.unscoped.join(", "))?;
writeln!(
out,
" declaring no files, the queue cannot keep another agent out \
of what these touch"
)?;
}
let reviewed: Vec<&plan::PlanTask> = parsed.tasks.iter().filter(|t| t.review).collect();
for task in reviewed.iter().filter(|t| t.paths.is_empty()) {
advisories += 1;
writeln!(
out,
"review {} declares no files — if the witness sees nothing move, \
finishing it files no review",
task.name
)?;
}
if !reviewed.is_empty() {
let seen = db
.events()
.harnesses_seen(&ProjectScope::Only(project.to_string()))?;
if seen.len() < 2 {
advisories += 1;
let present = match seen.as_slice() {
[] => "none has acted here yet".to_string(),
only => format!("this board has only seen {}", only.join(", ")),
};
writeln!(
out,
"review a review is refused to the harness that did the work, and \
{present} — a second harness is what makes these claimable",
)?;
}
}
match advisories {
0 => writeln!(out, "\nnothing to flag; hird plan apply files it")?,
n => writeln!(out, "\n{}; the plan files either way", count(n, "advisory"))?,
}
Ok(())
}
fn count(n: usize, noun: &str) -> String {
if n == 1 {
return format!("{n} {noun}");
}
match noun.strip_suffix('y') {
Some(stem) => format!("{n} {stem}ies"),
None => format!("{n} {noun}s"),
}
}
fn recuse(db: &Db, args: &RecuseArgs, out: &mut impl Write) -> anyhow::Result<()> {
if args.clear {
let removed = db.recusals().clear(args.seq, ACTOR_CLI)?;
writeln!(out, "lifted {removed} recusal(s) from task {}", args.seq)?;
return Ok(());
}
for from in &args.from {
db.recusals()
.add(args.seq, *from, &args.reason, ACTOR_CLI)?;
}
let recusals = db.recusals().for_task(args.seq)?;
if recusals.is_empty() {
writeln!(out, "task {} is recused from nothing", args.seq)?;
return Ok(());
}
for recusal in &recusals {
writeln!(out, "{}", recusal.describe())?;
}
Ok(())
}
fn record(db: &Db, scope: &ProjectScope, out: &mut impl Write) -> anyhow::Result<()> {
let records = db.verdicts().record(scope)?;
let workers: Vec<_> = records.iter().filter(|r| r.judged > 0).collect();
let reviewers: Vec<_> = records
.iter()
.filter(|r| r.upheld_given + r.sent_back_given > 0)
.collect();
if workers.is_empty() && reviewers.is_empty() {
writeln!(
out,
"no verdicts on record — file work with `hird add --review` and the reviews \
that finishing it files will deliver them"
)?;
return Ok(());
}
if !workers.is_empty() {
writeln!(
out,
"{:<14} {:>7} {:>7} {:>10} {:>11}",
"as worker", "judged", "upheld", "sent back", "first pass"
)?;
for r in workers {
writeln!(
out,
"{:<14} {:>7} {:>7} {:>10} {:>11}",
r.harness,
r.judged,
r.upheld,
r.sent_back,
format!("{}/{}", r.first_pass, r.tasks_judged)
)?;
}
}
if !reviewers.is_empty() {
writeln!(
out,
"\n{:<14} {:>7} {:>10}",
"as reviewer", "upheld", "sent back"
)?;
for r in reviewers {
writeln!(
out,
"{:<14} {:>7} {:>10}",
r.harness, r.upheld_given, r.sent_back_given
)?;
}
}
Ok(())
}
fn scope_cmd(db: &Db, args: &ScopeArgs, out: &mut impl Write) -> anyhow::Result<()> {
if args.clear {
let removed = db.scopes().clear(args.seq, ACTOR_CLI)?;
writeln!(out, "cleared {removed} pattern(s) from task {}", args.seq)?;
return Ok(());
}
if !args.paths.is_empty() {
let conflicts =
db.scopes()
.declare(args.seq, &args.paths, ACTOR_CLI, OnConflict::Report)?;
for conflict in &conflicts {
writeln!(out, "warning: {}", conflict.describe())?;
}
}
let patterns = db.scopes().for_task(args.seq)?;
if patterns.is_empty() {
writeln!(out, "task {} declares no files", args.seq)?;
} else {
for pattern in patterns {
writeln!(out, "{pattern}")?;
}
}
Ok(())
}
fn require_cmd(db: &Db, args: &RequireArgs, out: &mut impl Write) -> anyhow::Result<()> {
if args.clear {
db.requirements().set(args.seq, &[], ACTOR_CLI)?;
} else if !args.capabilities.is_empty() {
db.requirements()
.set(args.seq, &args.capabilities, ACTOR_CLI)?;
}
let required = db.requirements().for_task(args.seq)?;
if required.is_empty() {
writeln!(out, "task {} requires no capabilities", args.seq)?;
} else {
for capability in required {
writeln!(out, "{capability}")?;
}
}
Ok(())
}
type GraphInputs = (Vec<TaskSummary>, Vec<(i64, i64)>);
fn graph_inputs(db: &Db, scope: &ProjectScope, plan: Option<&str>) -> anyhow::Result<GraphInputs> {
let mut tasks = db.tasks().list(scope, None)?;
let mut edges = db.deps().edges(scope)?;
if let Some(name) = plan {
let members: std::collections::BTreeSet<i64> = tasks
.iter()
.map(|t| t.project.clone())
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.map(|project| db.plans().origins(&project))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.filter(|(_, (p, _))| p == name)
.map(|(seq, _)| seq)
.collect();
if members.is_empty() {
anyhow::bail!(
"no task here was filed from plan {name:?}; `hird plan apply` records the \
plan a task came from, and `hird plan export` lists the names in use"
);
}
tasks.retain(|t| members.contains(&t.seq));
edges.retain(|(t, on)| members.contains(t) && members.contains(on));
}
Ok((tasks, edges))
}
fn graph(
db: &Db,
scope: &ProjectScope,
plan: Option<&str>,
out: &mut impl Write,
) -> anyhow::Result<()> {
let (tasks, edges) = graph_inputs(db, scope, plan)?;
let waves = dispatch_waves(&tasks, &edges);
let questions = db.questions().unanswered_map(scope)?;
if let ProjectScope::Only(project) = scope {
if let Some(recess) = db.recesses().current(project)? {
writeln!(out, "{}", recess_banner(&recess, Utc::now()))?;
}
}
if waves.is_empty() {
writeln!(out, "no unfinished tasks")?;
return Ok(());
}
let waiting: BTreeMap<i64, Vec<i64>> = edges.iter().fold(BTreeMap::new(), |mut acc, (t, d)| {
acc.entry(*t).or_default().push(*d);
acc
});
let by_seq: BTreeMap<i64, &TaskSummary> = tasks.iter().map(|t| (t.seq, t)).collect();
for (index, wave) in waves.iter().enumerate() {
let label = match index {
0 => "wave 1 (workable now)".to_string(),
n => format!("wave {} (after wave {n})", n + 1),
};
writeln!(out, "{label}")?;
for seq in wave {
let Some(task) = by_seq.get(seq) else {
continue;
};
let mut line = format!(
" #{:<4} {:<12} {}",
task.seq,
task.status,
fmt::truncate(&task.title, 44)
);
if let Some(needs) = waiting.get(seq) {
let listed = needs
.iter()
.map(|s| format!("#{s}"))
.collect::<Vec<_>>()
.join(", ");
line.push_str(&format!(" waits for {listed}"));
}
if questions.contains_key(seq) {
line.push_str(" awaits answer");
}
writeln!(out, "{line}")?;
}
}
Ok(())
}
fn agents(db: &Db, scope: &ProjectScope, out: &mut impl Write) -> anyhow::Result<()> {
db.tasks().sweep_leases()?;
let tasks = db.tasks().list(scope, None)?;
let live: Vec<&TaskSummary> = tasks.iter().filter(|t| t.status.is_active()).collect();
if live.is_empty() {
writeln!(out, "no agent is working anything right now")?;
return Ok(());
}
let declared = db.scopes().declared(scope, true)?;
let scopes: BTreeMap<i64, Vec<String>> =
declared.into_iter().map(|s| (s.seq, s.patterns)).collect();
let now = Utc::now();
for task in &live {
let holder = task.claimed_by.as_deref().unwrap_or("unknown");
let lease = task
.lease_expires_at
.as_deref()
.map(|e| format!(" {}", fmt::lease_remaining(e, now)))
.unwrap_or_default();
writeln!(
out,
"{holder} #{} {} {}{lease}",
task.seq,
task.status,
fmt::truncate(&task.title, 40)
)?;
match scopes.get(&task.seq) {
Some(patterns) => writeln!(out, " files {}", patterns.join(", "))?,
None => writeln!(out, " files (undeclared)")?,
}
let seen = db.witnessed().touched(task.seq).unwrap_or_default();
if !seen.is_empty() {
let listed: Vec<String> = seen.iter().map(|o| o.path.clone()).collect();
writeln!(out, " moved {}", listed.join(", "))?;
} else if db.witnessed().footprint(task.seq).unwrap_or_default() == Footprint::ReadOnly {
writeln!(out, " moved nothing yet")?;
}
for other in &live {
if other.seq == task.seq {
continue;
}
for overlap in overlapping(&scopes, task.seq, other.seq) {
writeln!(
out,
" !! {overlap} also claimed by {} on #{}",
other.claimed_by.as_deref().unwrap_or("unknown"),
other.seq
)?;
}
}
for found in db.witnessed().contention(task.seq).unwrap_or_default() {
writeln!(out, " !!! {}", found.describe())?;
}
for shifted in db.deps().shifted(task.seq).unwrap_or_default() {
writeln!(out, " !!! {}", shifted.describe())?;
}
}
Ok(())
}
fn overlapping(scopes: &BTreeMap<i64, Vec<String>>, a: i64, b: i64) -> Vec<String> {
let (Some(ours), Some(theirs)) = (scopes.get(&a), scopes.get(&b)) else {
return Vec::new();
};
ours.iter()
.filter(|pattern| theirs.iter().any(|other| glob::intersects(pattern, other)))
.cloned()
.collect()
}
fn read_text(path: &Path) -> anyhow::Result<String> {
if path == Path::new("-") {
let mut buf = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)
.context("reading from stdin")?;
return Ok(buf);
}
std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))
}
fn ls(
db: &Db,
project: &str,
config: &Config,
args: &LsArgs,
out: &mut impl Write,
) -> anyhow::Result<()> {
let status = match args
.status
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
{
Some(raw) => Some(raw.parse::<Status>()?),
None => None,
};
let scope = ProjectScope::resolve(project, config.all_projects(Some(args.all_projects)));
let tasks = db.tasks().list(&scope, status)?;
if !scope.is_all() {
if let Some(recess) = db.recesses().current(project)? {
writeln!(out, "{}", recess_banner(&recess, Utc::now()))?;
}
}
if tasks.is_empty() {
writeln!(out, "no tasks")?;
return Ok(());
}
let unmet = db.deps().unmet_map(&scope, config.clearance())?;
let questions = db.questions().unanswered_map(&scope)?;
let footprints = db.witnessed().footprints(&scope).unwrap_or_default();
let now = Utc::now();
let width = tasks
.iter()
.map(|t| t.seq.to_string().len())
.max()
.unwrap_or(1);
for task in &tasks {
let blocked = unmet.get(&task.seq).map(Vec::as_slice).unwrap_or(&[]);
let question = questions.get(&task.seq).map(|q| q.question.as_str());
let footprint = footprints.get(&task.seq).copied().unwrap_or_default();
writeln!(
out,
"{}",
ls_line(
task,
width,
scope.is_all(),
now,
blocked,
question,
footprint,
)
)?;
}
Ok(())
}
fn ls_line(
task: &TaskSummary,
seq_width: usize,
show_project: bool,
now: chrono::DateTime<Utc>,
blocked_by: &[i64],
awaiting_answer: Option<&str>,
footprint: Footprint,
) -> String {
let mut line = format!(
"#{seq:<width$} {status:<11} {title}",
seq = task.seq,
width = seq_width,
status = task.status,
title = fmt::truncate(&task.title, 48),
);
if let Some(holder) = &task.claimed_by {
line.push_str(&format!(" [{holder}]"));
if let Some(expires) = &task.lease_expires_at {
line.push_str(&format!(" {}", fmt::lease_remaining(expires, now)));
}
}
if !blocked_by.is_empty() {
let listed = blocked_by
.iter()
.map(|s| format!("#{s}"))
.collect::<Vec<_>>()
.join(",");
line.push_str(&format!(" waits {listed}"));
}
if awaiting_answer.is_some() {
line.push_str(" awaits answer");
}
if task.priority != 0 {
line.push_str(&format!(" p{}", task.priority));
}
if !task.requirements.is_empty() {
line.push_str(&format!(" requires {}", task.requirements.join(",")));
}
if let Some(label) = footprint.label(task.status.is_active()) {
line.push_str(&format!(" {label}"));
}
if show_project {
line.push_str(&format!(" ({})", task.project));
}
line
}
fn recall(
db: &Db,
config: &Config,
project: &str,
seq: i64,
limit: usize,
out: &mut impl Write,
) -> anyhow::Result<()> {
let discovered = config.witness(Path::new(project));
let recalled = footing::decorate(
db,
config.footing(discovered.as_ref()),
db.recall().for_task(seq, limit)?,
);
if recalled.is_empty() {
writeln!(out, "nothing recorded so far touches task {seq}")?;
return Ok(());
}
let now = Utc::now();
for item in recalled {
writeln!(out, "{}", item.assertion.content)?;
writeln!(
out,
" {} ({}, {})",
item.reason.describe(),
item.assertion.actor,
fmt::age_phrase(&item.assertion.created_at, now)
)?;
if let Some(why) = item
.standing
.as_ref()
.filter(|s| s.needs_checking())
.and_then(Standing::describe)
{
writeln!(out, " {why}")?;
}
if let Some(voices) = &item.corroboration {
writeln!(out, " {voices}")?;
}
}
Ok(())
}
fn diff(
db: &Db,
seq: i64,
only: Option<&str>,
tenure: Option<i64>,
config: &Config,
out: &mut impl Write,
) -> anyhow::Result<()> {
let task = db.tasks().get(seq)?;
let Some(witness) = config.witness(Path::new(&task.project)) else {
anyhow::bail!(
"hird is not watching {} — no git repository there, or the witness is off — \
so there is no diff to show",
task.project
);
};
let mut shown = match tenure {
Some(n) => exhibit::assemble_tenure(db, &witness, seq, n)?,
None => {
let _ = witness::sweep(db, &witness, &task.project, ACTOR_CLI);
exhibit::assemble(db, &witness, seq)?
}
};
let round = tenure
.map(|n| format!(" in holding {n}"))
.unwrap_or_default();
if let Some(only) = only {
shown.retain(|e| e.path == only);
if shown.is_empty() {
writeln!(
out,
"the witness saw nothing move at {only} under task {seq}{round}"
)?;
return Ok(());
}
}
let text = exhibit::render(&shown);
if text.trim().is_empty() {
writeln!(
out,
"nothing moved under task {seq}{round} while the witness was watching"
)?;
return Ok(());
}
write!(out, "{text}")?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn salvage(
db: &Db,
seq: i64,
path: &str,
baseline: bool,
tenure: Option<i64>,
to: Option<&Path>,
force: bool,
config: &Config,
out: &mut impl Write,
) -> anyhow::Result<()> {
let task = db.tasks().get(seq)?;
let Some(witness) = config.witness(Path::new(&task.project)) else {
anyhow::bail!(
"hird is not watching {} — no git repository there, or the witness is off — \
so nothing was kept to salvage",
task.project
);
};
if tenure.is_none() {
let _ = witness::sweep(db, &witness, &task.project, ACTOR_CLI);
}
let bytes = exhibit::salvage(db, &witness, seq, path, baseline, tenure)?;
let which = match (baseline, tenure) {
(true, Some(n)) => format!("as it stood when holding {n} began"),
(false, Some(n)) => format!("as the witness last saw it under holding {n}"),
(true, None) => "as it stood when the task was claimed".to_string(),
(false, None) => "as the witness last saw it under the task".to_string(),
};
match to {
Some(dest) => {
if dest.exists() && !force {
anyhow::bail!(
"{} already exists; --force to say you meant to overwrite it",
dest.display()
);
}
if let Some(parent) = dest.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating {}", parent.display()))?;
}
std::fs::write(dest, &bytes).with_context(|| format!("writing {}", dest.display()))?;
writeln!(
out,
"salvaged {path} {which} — {} bytes into {}",
bytes.len(),
dest.display()
)?;
}
None => out.write_all(&bytes)?,
}
Ok(())
}
pub(crate) fn show(db: &Db, seq: i64, config: &Config, out: &mut impl Write) -> anyhow::Result<()> {
let task = db.tasks().get(seq)?;
let now = Utc::now();
writeln!(out, "#{} {}", task.seq, task.title)?;
writeln!(out, "status {}", task.status)?;
writeln!(out, "project {}", task.project)?;
if task.priority != 0 {
writeln!(out, "priority {}", task.priority)?;
}
if let Some(holder) = &task.claimed_by {
let lease = task
.lease_expires_at
.as_deref()
.map(|e| format!(" ({})", fmt::lease_remaining(e, now)))
.unwrap_or_default();
writeln!(out, "held by {holder}{lease}")?;
}
writeln!(out, "created {}", fmt::age_phrase(&task.created_at, now))?;
let (blockers, conflicts) = db.tasks().readiness(seq, config.clearance())?;
if !blockers.is_empty() {
let listed = blockers
.iter()
.map(|b| match b.pending_review {
Some(review) if b.status == Status::Done => {
format!("#{} (done, under review {review})", b.seq)
}
_ => format!("#{} ({})", b.seq, b.status),
})
.collect::<Vec<_>>()
.join(", ");
writeln!(out, "waits for {listed}")?;
}
for question in db.questions().for_task(seq)? {
writeln!(out, "question {}", question.question)?;
match question.answer {
Some(answer) => writeln!(out, "answer {answer}")?,
None => writeln!(out, "awaits hird answer {seq} <ANSWER>")?,
}
}
for ground in db.deps().ground(seq)? {
let result = ground
.result
.as_deref()
.map(|r| format!(" — {}", fmt::truncate(r, 60)))
.unwrap_or_default();
writeln!(out, "built on {}{result}", ground.label())?;
}
let dependents = db.deps().dependents(seq)?;
if !dependents.is_empty() {
let listed = dependents
.iter()
.map(|b| format!("#{}", b.seq))
.collect::<Vec<_>>()
.join(", ");
writeln!(out, "blocks {listed}")?;
}
let patterns = db.scopes().for_task(seq)?;
if !patterns.is_empty() {
writeln!(out, "files {}", patterns.join(", "))?;
}
let required = db.requirements().for_task(seq)?;
if !required.is_empty() {
writeln!(out, "requires {}", required.join(", "))?;
}
if task.review {
writeln!(out, "review on finishing, by another harness")?;
}
for recusal in db.recusals().for_task(seq)? {
writeln!(out, "recused {}", recusal.describe())?;
}
let judged = db.verdicts().for_task(seq)?;
if let Some(latest) = judged.last() {
let rounds = if judged.len() > 1 {
format!(", verdict {} on this work", judged.len())
} else {
String::new()
};
writeln!(out, "verdict {}{rounds}", latest.describe())?;
}
for delivered in db.verdicts().of_review(seq)? {
writeln!(
out,
"verdict {} on task {}, delivered by this review",
delivered.verdict, delivered.task_seq
)?;
}
for conflict in &conflicts {
writeln!(out, "overlap {}", conflict.describe())?;
}
let footprint = db.witnessed().footprint(seq).unwrap_or_default();
if let Some(sentence) = footprint.describe(task.status.is_active()) {
writeln!(out, "changed {sentence}")?;
}
for observed in db.witnessed().touched(seq).unwrap_or_default() {
writeln!(out, " {}", observed.describe())?;
}
for found in db.witnessed().contention(seq).unwrap_or_default() {
writeln!(out, "contended {}", found.describe())?;
}
for held in db.witnessed().tenures(seq).unwrap_or_default() {
writeln!(out, "held {}", held.label())?;
}
if !task.body.trim().is_empty() {
writeln!(out, "\n{}", task.body.trim_end())?;
}
if let Some(result) = &task.result {
writeln!(out, "\nresult: {result}")?;
}
let events = db.tasks().events(&task.id, 20)?;
if !events.is_empty() {
writeln!(out, "\nhistory")?;
for event in events {
let detail = if event.detail.is_empty() {
String::new()
} else {
format!(" {}", fmt::truncate(&event.detail, 72))
};
writeln!(
out,
" {:>9} {:<13} {}{}",
fmt::age_phrase(&event.at, now),
event.kind,
event.actor,
detail
)?;
}
}
let learned = db.memory().for_task(&task.id)?;
if !learned.is_empty() {
let discovered = config.witness(Path::new(&task.project));
let ids: Vec<String> = learned.iter().map(|a| a.id.clone()).collect();
let standings =
footing::standings(db, config.footing(discovered.as_ref()), &task.project, &ids);
writeln!(out, "\nassertions recorded on this task")?;
for assertion in learned {
writeln!(out, " - {}", fmt::truncate(&assertion.content, 88))?;
if let Some(why) = standings
.get(&assertion.id)
.filter(|s| s.needs_checking())
.and_then(Standing::describe)
{
writeln!(out, " {why}")?;
}
}
}
let elsewhere: Vec<_> = db
.recall()
.for_task(seq, config.recall_limit())?
.into_iter()
.filter(|r| r.reason != crate::repo::RecallReason::SameTask)
.collect();
if !elsewhere.is_empty() {
writeln!(out, "\nrecalled from earlier work")?;
for item in elsewhere {
writeln!(out, " - {}", fmt::truncate(&item.assertion.content, 88))?;
writeln!(out, " {}", item.reason.describe())?;
}
}
Ok(())
}
pub(crate) fn why(db: &Db, seq: i64, config: &Config, out: &mut impl Write) -> anyhow::Result<()> {
let (blockers, conflicts) = db.tasks().readiness(seq, config.clearance())?;
let task = db.tasks().get(seq)?;
let now = Utc::now();
let question = db.questions().unanswered(seq)?;
let recusals: Vec<_> = db
.recusals()
.for_task(seq)?
.into_iter()
.filter(|r| r.worker.is_some())
.collect();
let required = db.requirements().for_task(seq)?;
let refuses = config.on_conflict() == crate::repo::OnConflict::Refuse;
writeln!(out, "#{} {}", task.seq, task.title)?;
writeln!(out, "status {}", task.status)?;
if task.status.is_active() {
let holder = task.claimed_by.as_deref().unwrap_or("?");
let lease = task
.lease_expires_at
.as_deref()
.map(|e| format!(", {}", fmt::lease_remaining(e, now)))
.unwrap_or_default();
writeln!(out, "claimable no — held by {holder}{lease}")?;
return Ok(());
}
if task.status.is_terminal() {
writeln!(
out,
"claimable no — {}; hird reopen {seq} returns it to the pool",
task.status
)?;
return Ok(());
}
let mut stoppers: Vec<String> = Vec::new();
let recess = db.recesses().current(&task.project)?;
if recess.is_some() {
stoppers.push("hird resume — the queue is in recess".to_string());
}
if question.is_some() {
stoppers.push("an answer".to_string());
}
if !blockers.is_empty() {
let verdicts: Vec<String> = blockers
.iter()
.filter(|b| b.status == Status::Done)
.filter_map(|b| b.pending_review.map(|r| format!("#{r}")))
.collect();
let unfinished: Vec<String> = blockers
.iter()
.filter(|b| !(b.status == Status::Done && b.pending_review.is_some()))
.map(|b| format!("#{}", b.seq))
.collect();
if !unfinished.is_empty() {
stoppers.push(unfinished.join(", "));
}
if !verdicts.is_empty() {
stoppers.push(format!("the verdict of review {}", verdicts.join(", ")));
}
}
if refuses && !conflicts.is_empty() {
stoppers.push("the overlap below to clear".to_string());
}
let mut caveats: Vec<String> = Vec::new();
if !recusals.is_empty() {
let barred: Vec<&str> = recusals
.iter()
.filter_map(|r| r.worker.as_deref())
.map(crate::identity::actor_harness)
.collect();
caveats.push(format!("not by {}", barred.join(" or ")));
}
if !required.is_empty() {
caveats.push(format!(
"only by a harness advertising {}",
required.join(", ")
));
}
if !refuses && !conflicts.is_empty() && config.avoid_conflicts(None) {
caveats.push(
"task_next passes it over while the overlap lives; claiming it by number still works"
.to_string(),
);
}
if stoppers.is_empty() {
let trailing = if caveats.is_empty() {
String::new()
} else {
format!(" — {}", caveats.join("; "))
};
writeln!(out, "claimable yes{trailing}")?;
} else {
writeln!(out, "claimable no — waiting on {}", stoppers.join(" and "))?;
for caveat in &caveats {
writeln!(out, "and then {caveat}")?;
}
}
if let Some(recess) = &recess {
writeln!(
out,
"recess the human stood this queue down{}, {}",
recess.quoted_reason(),
fmt::age_phrase(&recess.at, now)
)?;
}
if let Some(question) = question {
writeln!(out, "awaits {}", question.question)?;
writeln!(
out,
" asked by {} {} — hird answer {seq} <ANSWER>",
question.asked_by,
fmt::age_phrase(&question.asked_at, now)
)?;
}
if !blockers.is_empty() {
let listed = blockers
.iter()
.map(|b| match b.pending_review {
Some(review) if b.status == Status::Done => {
format!("#{} (done, under review {review})", b.seq)
}
_ => format!("#{} ({})", b.seq, b.status),
})
.collect::<Vec<_>>()
.join(", ");
writeln!(out, "waits for {listed}")?;
}
for recusal in &recusals {
writeln!(out, "recused {}", recusal.describe())?;
}
if !required.is_empty() {
writeln!(out, "requires {}", required.join(", "))?;
}
for conflict in &conflicts {
writeln!(out, "overlap {}", conflict.describe())?;
}
if refuses && !conflicts.is_empty() {
writeln!(
out,
" path_conflicts = \"refuse\": a claim is rejected while the overlap lives"
)?;
}
Ok(())
}
fn mem(
db: &Db,
project: &str,
config: &Config,
cmd: &MemCommand,
out: &mut impl Write,
) -> anyhow::Result<()> {
let discovered = config.witness(Path::new(project));
let witness = config.footing(discovered.as_ref());
match cmd {
MemCommand::Add {
content,
tags,
task,
paths,
} => {
let recorded = db.memory().record(NewAssertion {
project,
content,
tags,
actor: ACTOR_CLI,
task_seq: *task,
})?;
let ground =
footing::ground(db, *task, Some(paths.as_slice()).filter(|p| !p.is_empty()));
let anchored = footing::anchor(db, witness, &recorded.assertion().id, &ground)?;
writeln!(out, "{}", recorded.assertion().id)?;
if recorded.was_affirmed() {
writeln!(
out,
" already on record — affirmed, not duplicated{}",
if anchored.is_empty() {
String::new()
} else {
" and re-anchored".to_string()
}
)?;
}
if !anchored.is_empty() {
let paths: Vec<&str> = anchored.iter().map(|a| a.path.as_str()).collect();
writeln!(out, " anchored to {}", paths.join(", "))?;
}
Ok(())
}
MemCommand::Standing {
shaky,
all_projects,
} => {
let scope = ProjectScope::resolve(project, config.all_projects(Some(*all_projects)));
standing(db, config, witness, &scope, *shaky, out)
}
MemCommand::Export { path, firm } => {
mem_export(db, project, witness, path.as_deref(), *firm, out)
}
MemCommand::Search {
query,
limit,
all_projects,
include_superseded,
} => {
let scope = ProjectScope::resolve(project, config.all_projects(Some(*all_projects)));
let hits = db.memory().search(
&MemoryQuery::new(query, scope.clone())
.limit((*limit).clamp(1, 500))
.include_superseded(*include_superseded),
)?;
if hits.is_empty() {
writeln!(out, "no assertions")?;
return Ok(());
}
let now = Utc::now();
let ids: Vec<String> = hits.iter().map(|a| a.id.clone()).collect();
let standings = footing::standings(db, witness, project, &ids);
for assertion in hits {
let standing = standings.get(&assertion.id);
let mut meta = vec![
assertion.actor.clone(),
fmt::age_phrase(&assertion.created_at, now),
];
if !assertion.tags.is_empty() {
meta.push(format!("#{}", assertion.tags.replace(',', " #")));
}
if assertion.superseded_by.is_some() {
meta.push("superseded".to_string());
}
if let Some(standing) = standing.filter(|s| **s != Standing::Unanchored) {
meta.push(standing.as_str().to_string());
}
if scope.is_all() {
meta.push(assertion.project.clone());
}
writeln!(out, "{}", assertion.content)?;
writeln!(out, " {} {}", assertion.id, meta.join(" "))?;
if let Some(why) = standing
.filter(|s| s.needs_checking())
.and_then(|s| s.describe())
{
writeln!(out, " {why}")?;
}
}
Ok(())
}
}
}
fn standing(
db: &Db,
config: &Config,
witness: Option<&witness::Witness>,
scope: &ProjectScope,
shaky_only: bool,
out: &mut impl Write,
) -> anyhow::Result<()> {
if witness.is_none() && !scope.is_all() {
writeln!(
out,
"no footing here: assertions are only anchored to files in a git checkout \
with `memory_footing` on"
)?;
return Ok(());
}
let anchored = db.footings().anchored(scope)?;
if anchored.is_empty() {
writeln!(out, "no anchored assertions")?;
return Ok(());
}
let now = Utc::now();
let mut by_project: BTreeMap<&str, Vec<String>> = BTreeMap::new();
for assertion in &anchored {
by_project
.entry(assertion.project.as_str())
.or_default()
.push(assertion.id.clone());
}
let mut standings: BTreeMap<String, Standing> = BTreeMap::new();
for (project, ids) in by_project {
let discovered = config.witness(Path::new(project));
standings.extend(footing::standings(
db,
config.footing(discovered.as_ref()),
project,
&ids,
));
}
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
let mut shown = 0usize;
for assertion in &anchored {
let standing = standings
.get(&assertion.id)
.cloned()
.unwrap_or(Standing::Unanchored);
*counts.entry(standing.as_str()).or_default() += 1;
if shaky_only && !standing.needs_checking() {
continue;
}
shown += 1;
writeln!(
out,
"{:<9} {}",
standing.as_str(),
fmt::truncate(&assertion.content, 78)
)?;
let mut meta = vec![
assertion.actor.clone(),
fmt::age_phrase(&assertion.created_at, now),
];
if scope.is_all() {
meta.push(assertion.project.clone());
}
writeln!(out, " {} {}", assertion.id, meta.join(" "))?;
writeln!(out, " {}", standing.paths().join(", "))?;
if let Some(why) = standing.describe().filter(|_| standing.needs_checking()) {
writeln!(out, " {why}")?;
}
if let Some(voices) = footing::corroboration(db, assertion) {
writeln!(out, " {voices}")?;
}
}
if shown == 0 {
writeln!(
out,
"nothing shaky: every anchored assertion still checks out"
)?;
}
let summary: Vec<String> = counts
.iter()
.map(|(label, n)| format!("{n} {label}"))
.collect();
writeln!(out, "\n{} anchored: {}", anchored.len(), summary.join(", "))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
const PROJECT: &str = "/tmp/project";
fn now() -> chrono::DateTime<Utc> {
DateTime::from_timestamp(1_800_000_000, 0).unwrap()
}
use chrono::DateTime;
fn summary(seq: i64, status: Status) -> TaskSummary {
TaskSummary {
seq,
project: PROJECT.into(),
title: "write the parser".into(),
status,
priority: 0,
claimed_by: None,
lease_expires_at: None,
updated_at: crate::model::fmt_ts(now()),
requirements: Vec::new(),
}
}
#[test]
fn the_command_tree_parses() {
Cli::command().debug_assert();
}
#[test]
fn ls_rows_line_up_and_omit_empty_columns() {
let line = ls_line(
&summary(7, Status::Open),
2,
false,
now(),
&[],
None,
Footprint::Unwatched,
);
assert_eq!(line, "#7 open write the parser");
}
#[test]
fn ls_rows_show_the_holder_and_lease_countdown() {
let mut task = summary(7, Status::Claimed);
task.claimed_by = Some("codex:9f2c".into());
task.lease_expires_at = Some(crate::model::fmt_ts(now() + chrono::Duration::minutes(12)));
let line = ls_line(&task, 1, false, now(), &[], None, Footprint::Unwatched);
assert!(line.contains("[codex:9f2c] 12m left"), "{line}");
}
#[test]
fn ls_rows_show_priority_and_project_only_when_relevant() {
let mut task = summary(7, Status::Open);
task.priority = 5;
assert!(ls_line(&task, 1, false, now(), &[], None, Footprint::Unwatched).ends_with(" p5"));
assert!(
ls_line(&task, 1, true, now(), &[], None, Footprint::Unwatched)
.ends_with(&format!("({PROJECT})"))
);
}
#[test]
fn add_body_flags_are_mutually_exclusive() {
let err = Cli::try_parse_from(["hird", "add", "t", "--body", "x", "--body-file", "y"])
.unwrap_err();
assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
}
#[test]
fn negative_priorities_parse() {
let cli = Cli::try_parse_from(["hird", "add", "t", "--priority", "-3"]).unwrap();
match cli.command {
Some(Command::Add(args)) => assert_eq!(args.priority, -3),
other => panic!("parsed as {other:?}"),
}
}
#[test]
fn list_is_an_alias_for_ls() {
assert!(matches!(
Cli::try_parse_from(["hird", "list"]).unwrap().command,
Some(Command::Ls(_))
));
}
#[test]
fn dependencies_can_be_given_as_a_list_or_repeated() {
let comma = Cli::try_parse_from(["hird", "add", "t", "--needs", "3,4"]).unwrap();
let repeated =
Cli::try_parse_from(["hird", "add", "t", "--needs", "3", "--needs", "4"]).unwrap();
for cli in [comma, repeated] {
match cli.command {
Some(Command::Add(args)) => assert_eq!(args.needs, vec![3, 4]),
other => panic!("parsed as {other:?}"),
}
}
}
#[test]
fn paths_are_repeatable_and_kept_verbatim_for_normalization() {
let cli = Cli::try_parse_from(["hird", "add", "t", "--path", "src/**", "--path", "tests/"])
.unwrap();
match cli.command {
Some(Command::Add(args)) => assert_eq!(args.paths, vec!["src/**", "tests/"]),
other => panic!("parsed as {other:?}"),
}
}
#[test]
fn a_plan_is_applied_from_a_file_and_dry_run_is_opt_in() {
let cli = Cli::try_parse_from(["hird", "plan", "apply", "plan.toml"]).unwrap();
match cli.command {
Some(Command::Plan(PlanCommand::Apply { file, dry_run, .. })) => {
assert_eq!(file, PathBuf::from("plan.toml"));
assert!(!dry_run);
}
other => panic!("parsed as {other:?}"),
}
let dry = Cli::try_parse_from(["hird", "plan", "apply", "-", "--dry-run"]).unwrap();
match dry.command {
Some(Command::Plan(PlanCommand::Apply { file, dry_run, .. })) => {
assert_eq!(file, PathBuf::from("-"));
assert!(dry_run);
}
other => panic!("parsed as {other:?}"),
}
}
#[test]
fn counted_nouns_agree_with_their_number() {
assert_eq!(count(1, "task"), "1 task");
assert_eq!(count(0, "task"), "0 tasks");
assert_eq!(count(3, "wave"), "3 waves");
assert_eq!(count(1, "dependency"), "1 dependency");
assert_eq!(count(2, "dependency"), "2 dependencies");
}
#[test]
fn clearing_a_scope_conflicts_with_setting_one() {
let err =
Cli::try_parse_from(["hird", "scope", "1", "--clear", "--path", "src/**"]).unwrap_err();
assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
}
#[test]
fn ls_rows_mark_the_tasks_that_cannot_start_yet() {
let line = ls_line(
&summary(7, Status::Open),
1,
false,
now(),
&[3, 4],
None,
Footprint::Unwatched,
);
assert!(line.contains("waits #3,#4"), "{line}");
}
#[test]
fn overlaps_are_reported_both_ways_or_not_at_all() {
let mut scopes = BTreeMap::new();
scopes.insert(1, vec!["src/**".to_string()]);
scopes.insert(2, vec!["src/db.rs".to_string()]);
scopes.insert(3, vec!["docs/**".to_string()]);
assert_eq!(overlapping(&scopes, 1, 2), vec!["src/**".to_string()]);
assert_eq!(overlapping(&scopes, 2, 1), vec!["src/db.rs".to_string()]);
assert!(overlapping(&scopes, 1, 3).is_empty());
assert!(overlapping(&scopes, 1, 99).is_empty());
}
#[test]
fn every_harness_is_registrable_by_name() {
for (word, expected) in [
("claude-code", register::Harness::ClaudeCode),
("codex", register::Harness::Codex),
("copilot", register::Harness::Copilot),
("copilot-cli", register::Harness::CopilotCli),
("gemini", register::Harness::Gemini),
("opencode", register::Harness::OpenCode),
] {
let cli = Cli::try_parse_from(["hird", "register", word]).unwrap();
match cli.command {
Some(Command::Register(args)) => {
assert_eq!(args.harness, expected);
assert_eq!(args.name, "hird");
assert!(!args.print && !args.force);
}
other => panic!("parsed as {other:?}"),
}
}
assert!(Cli::try_parse_from(["hird", "register", "emacs"]).is_err());
}
#[test]
fn printing_a_registration_cannot_also_force_one() {
let err =
Cli::try_parse_from(["hird", "register", "codex", "--print", "--force"]).unwrap_err();
assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
}
#[test]
fn mem_search_defaults_to_an_empty_query() {
let cli = Cli::try_parse_from(["hird", "mem", "search"]).unwrap();
match cli.command {
Some(Command::Mem(MemCommand::Search { query, limit, .. })) => {
assert_eq!(query, "");
assert_eq!(limit, 20);
}
other => panic!("parsed as {other:?}"),
}
}
#[test]
fn installer_options_parse_without_a_subcommand_and_may_be_combined() {
let mcp = Cli::try_parse_from(["hird", "--install"]).unwrap();
assert!(mcp.install);
assert!(mcp.command.is_none());
let both = Cli::try_parse_from(["hird", "--install", "--install-skill"]).unwrap();
assert!(both.install);
assert!(both.install_skill);
assert!(both.command.is_none());
}
#[test]
fn the_install_typo_is_not_an_option() {
let err = Cli::try_parse_from(["hird", "--insytall"]).unwrap_err();
assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument);
}
#[test]
fn installer_options_and_normal_commands_are_detectably_distinct() {
let cli = Cli::try_parse_from(["hird", "--install-skill", "ls"]).unwrap();
assert!(cli.install_skill);
assert!(matches!(cli.command, Some(Command::Ls(_))));
}
}