use std::collections::BTreeMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
use rmcp::handler::server::tool::ToolCallContext;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
CacheScope, CallToolRequestParams, CallToolResponse, DiscoverResult, ErrorCode, Implementation,
ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig,
};
use rmcp::service::RequestContext;
use rmcp::{tool, tool_handler, tool_router, ErrorData, RoleServer, ServerHandler, ServiceExt};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::db::Db;
use crate::error::Error;
use crate::footing;
use crate::herald::{Announcement, Cause, Herald};
use crate::identity::{self, AgentId};
use crate::model::{
Assertion, Blocker, Conflict, Contention, Footprint, Ground, Observed, Question, Recusal,
Shifted, Standing, Status, Task, TaskEvent, TaskLinks, TaskSummary, Verdict, VerdictRecord,
};
use crate::repo::{
Claim, Claimable, Delivered, Dispatch, Finished, LinkChange, MemoryQuery, NewAssertion,
ProjectScope, Recalled, Subtask,
};
use crate::witness::{self, Witness};
const EVENT_WINDOW: usize = 20;
const SELF_CONTAINED: &str =
"a connection now opens either with an `initialize` request or with a \
self-contained one, and a self-contained request carries \
io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo and \
io.modelcontextprotocol/clientCapabilities in its `params._meta`";
pub async fn serve(db_path: &Path, config: Config) -> anyhow::Result<()> {
serve_session(db_path, config, &Attributes::default()).await
}
pub async fn serve_session(
db_path: &Path,
config: Config,
attributes: &Attributes,
) -> anyhow::Result<()> {
let session = Session::resolve(attributes, &config)?;
let shared = Arc::new(Shared::new(Db::open(db_path)?, config));
let server = HirdMcp::connect(shared, session);
let running = match server.serve(rmcp::transport::stdio()).await {
Ok(running) => running,
Err(rmcp::service::ServerInitializeError::ExpectedInitializeRequest(opener)) => {
refuse_opener(opener.as_ref());
anyhow::bail!("this connection was never opened: {SELF_CONTAINED}");
}
Err(rmcp::service::ServerInitializeError::ConnectionClosed(_)) => return Ok(()),
Err(other) => return Err(other.into()),
};
running.waiting().await?;
Ok(())
}
fn refuse_opener(opener: Option<&rmcp::model::ClientJsonRpcMessage>) {
use std::io::Write;
let Some(rmcp::model::JsonRpcMessage::Request(request)) = opener else {
return;
};
let response = serde_json::json!({
"jsonrpc": "2.0",
"id": request.id,
"error": {
"code": ErrorCode::INVALID_REQUEST.0,
"message": format!("this request cannot open a connection: {SELF_CONTAINED}"),
},
});
let Ok(line) = serde_json::to_string(&response) else {
return;
};
let mut stdout = std::io::stdout().lock();
let _ = writeln!(stdout, "{line}");
let _ = stdout.flush();
}
pub struct Shared {
db: Mutex<Db>,
config: Config,
herald: Option<Herald>,
question_herald: Option<crate::herald::QuestionHerald>,
}
impl Shared {
pub fn new(db: Db, config: Config) -> Shared {
let herald = config.herald(db.path());
let question_herald = config.question_herald(db.path());
Shared {
db: Mutex::new(db),
config,
herald,
question_herald,
}
}
pub fn with_db<T>(&self, f: impl FnOnce(&Db) -> T) -> T {
let db = self.db.lock().unwrap_or_else(|e| e.into_inner());
f(&db)
}
pub fn sweep(&self) {
self.with_db(|db| {
if self.herald.is_some() {
crate::herald::sweep_announcing(db, &self.config, self.herald.as_ref());
} else {
let _ = db.tasks().sweep_leases();
}
});
}
}
pub struct Session {
agent: AgentId,
project: String,
capabilities: Vec<String>,
witness: Option<Witness>,
role: Option<String>,
gate: Option<Arc<dyn crate::gate::Gate>>,
declared: Mutex<Option<String>>,
}
impl Session {
pub fn new(
agent: AgentId,
project: String,
capabilities: Vec<String>,
config: &Config,
) -> crate::Result<Session> {
let witness = config.witness(Path::new(&project));
Ok(Session {
agent,
project,
capabilities: crate::capability::normalize_all(&capabilities)?,
witness,
role: None,
gate: None,
declared: Mutex::new(None),
})
}
pub fn with_role(mut self, role: impl Into<String>) -> Session {
self.role = Some(role.into());
self
}
pub fn with_gate(mut self, gate: Arc<dyn crate::gate::Gate>) -> Session {
self.gate = Some(gate);
self
}
pub fn gate(&self) -> Option<&dyn crate::gate::Gate> {
self.gate.as_deref()
}
pub fn role(&self) -> Option<&str> {
self.role.as_deref()
}
pub fn stamp(&self) -> crate::repo::Stamp {
crate::repo::Stamp {
model: self.agent.model().map(str::to_string),
role: self.role.clone(),
}
}
pub fn from_env(config: &Config) -> crate::Result<Session> {
Session::resolve(&Attributes::default(), config)
}
pub fn resolve(attributes: &Attributes, config: &Config) -> crate::Result<Session> {
let agent = match &attributes.harness {
Some(harness) => AgentId::fresh(harness.clone()),
None => AgentId::from_env(),
};
let agent = match &attributes.identity {
Some(who) => agent.acting_for(who.clone()),
None => agent,
};
let agent = agent.running(std::env::var(identity::MODEL_ENV).unwrap_or_default());
let project = match &attributes.project {
Some(project) => identity::resolve_project(Path::new(project)),
None => {
let cwd = std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf());
identity::resolve_project(&cwd)
}
};
let capabilities = if attributes.capabilities.is_empty() {
crate::capability::from_env()?
} else {
attributes.capabilities.clone()
};
Session::new(agent, project, capabilities, config)
}
pub fn principal(&self) -> Option<&str> {
self.agent.principal()
}
}
#[derive(Debug, Default, Clone)]
pub struct Attributes {
pub identity: Option<String>,
pub harness: Option<String>,
pub project: Option<String>,
pub capabilities: Vec<String>,
}
pub struct HirdMcp {
shared: Arc<Shared>,
session: Session,
}
impl HirdMcp {
pub fn new(db: Db, agent: AgentId, project: String, config: Config) -> HirdMcp {
HirdMcp::with_capabilities(db, agent, project, config, Vec::new())
.expect("an empty capability set is valid")
}
pub fn with_capabilities(
db: Db,
agent: AgentId,
project: String,
config: Config,
capabilities: Vec<String>,
) -> crate::Result<HirdMcp> {
let session = Session::new(agent, project, capabilities, &config)?;
Ok(HirdMcp::connect(Arc::new(Shared::new(db, config)), session))
}
pub fn connect(shared: Arc<Shared>, session: Session) -> HirdMcp {
HirdMcp { shared, session }
}
pub fn actor(&self) -> String {
self.session.agent.as_actor()
}
pub fn session(&self) -> &Session {
&self.session
}
pub fn name_from_client(&self, client_name: &str) -> bool {
self.session.agent.name_from_client(client_name)
}
pub fn project(&self) -> &str {
&self.session.project
}
pub fn with_db<T>(&self, f: impl FnOnce(&Db) -> T) -> T {
let db = self.shared.db.lock().unwrap_or_else(|e| e.into_inner());
self.declare(&db);
f(&db)
}
fn declare(&self, db: &Db) {
let stamp = self.session.stamp();
if stamp.is_empty() {
return;
}
let actor = self.actor();
let mut declared = self
.session
.declared
.lock()
.unwrap_or_else(|e| e.into_inner());
if declared.as_deref() == Some(actor.as_str()) {
return;
}
if db.audit().declare(&actor, &stamp).is_ok() {
*declared = Some(actor);
}
}
fn scope(&self, all_projects: Option<bool>) -> ProjectScope {
ProjectScope::resolve(
&self.session.project,
self.shared.config.all_projects(all_projects),
)
}
fn announce(&self, list: &[Announcement]) {
crate::herald::announce(self.shared.herald.as_ref(), list);
}
fn dispatchable(&self, db: &Db, cause: Cause, seq: i64) -> Option<Announcement> {
self.shared.herald.as_ref()?;
let claimable = db
.deps()
.claimable(seq, self.shared.config.clearance())
.ok()
.flatten()?;
if self.held(db, seq) {
return None;
}
Some(announcement(cause, claimable))
}
fn held(&self, db: &Db, seq: i64) -> bool {
let Some(gate) = self.session.gate() else {
return false;
};
!matches!(db.tasks().held_by(seq, gate), Ok(None))
}
pub fn announce_unblocked_by(&self, seq: i64) {
if self.shared.herald.is_none() {
return;
}
let clearance = self.shared.config.clearance();
let announcements = self.with_db(|db| {
db.deps()
.released_by(seq, clearance)
.unwrap_or_default()
.into_iter()
.filter(|c| !self.held(db, c.seq))
.map(|c| announcement(Cause::Unblocked, c))
.collect::<Vec<_>>()
});
self.announce(&announcements);
}
fn expired_announcements(&self, db: &Db, expired: &[i64]) -> Vec<Announcement> {
expired
.iter()
.filter_map(|&seq| self.dispatchable(db, Cause::LeaseExpired, seq))
.collect()
}
fn sweep_announcing(&self) {
if self.shared.herald.is_none() {
return;
}
let announcements = self.with_db(|db| {
let expired = db
.tasks()
.sweep_leases()
.map(|s| s.expired)
.unwrap_or_default();
self.expired_announcements(db, &expired)
});
self.announce(&announcements);
}
fn dispatched(&self, db: &Db, finished: &Finished) -> Vec<Announcement> {
if self.shared.herald.is_none() {
return Vec::new();
}
let clearance = self.shared.config.clearance();
let mut released = db
.deps()
.released_by(finished.task.seq, clearance)
.unwrap_or_default();
for delivered in &finished.verdicts {
if delivered.verdict == Verdict::Upheld {
released.extend(
db.deps()
.released_by(delivered.seq, clearance)
.unwrap_or_default(),
);
}
}
released.sort_by_key(|c| c.seq);
released.dedup_by_key(|c| c.seq);
released.retain(|c| !self.held(db, c.seq));
let mut out: Vec<Announcement> = released
.into_iter()
.map(|c| announcement(Cause::Unblocked, c))
.collect();
for delivered in &finished.verdicts {
if delivered.reopened {
out.extend(self.dispatchable(db, Cause::SentBack, delivered.seq));
}
}
if let Some(review) = finished.review {
out.extend(self.dispatchable(db, Cause::ReviewFiled, review));
}
out
}
fn witnessed(&self, db: &Db, seq: i64) -> Evidence {
let Some(witness) = &self.session.witness else {
return Evidence::default();
};
let swept = witness::sweep(db, witness, &self.session.project, &self.actor()).ok();
let mut evidence = self.evidence(db, seq);
if let Some(swept) = swept {
let _ = db.witnessed().confirm(seq, swept.changes_for(seq));
if swept.tree.truncated {
evidence.partial = Some(
"the working tree has more uncommitted files than hird will fingerprint \
in one go, so `changed` is a floor and not the whole story"
.to_string(),
);
}
}
evidence
}
fn identity_instructions(&self) -> String {
match self.session.agent.principal() {
Some(who) => format!(
"\nThis session acts for {who}, and every claim, review and assertion it \
makes is recorded under that name alongside the harness. More than one \
person files into this queue: work you did not do may be waiting, and \
work you do will be read back to somebody else.\n"
),
None => String::new(),
}
}
fn footing(&self) -> Option<&Witness> {
self.shared.config.footing(self.session.witness.as_ref())
}
fn recall(&self, db: &Db, seq: i64, limit: usize) -> Vec<Recalled> {
let recalled = db.recall().for_task(seq, limit).unwrap_or_default();
footing::decorate(db, self.footing(), recalled)
}
fn begin_witnessing(&self, db: &Db, seq: i64) {
let Some(witness) = &self.session.witness else {
return;
};
let _ = witness::begin(db, witness, &self.session.project, seq, &self.actor());
}
fn inheritance(&self, db: &Db, seq: i64) -> Option<String> {
self.session.witness.as_ref()?;
let held = db.witnessed().tenures(seq).ok()?;
let last = held.last()?;
let mut sentence = last.describe(seq);
if held.len() > 1 {
sentence = format!(
"{sentence}. This task has changed hands {} times — `hird show {seq}` \
lists every holding",
held.len()
);
}
Some(sentence)
}
fn evidence(&self, db: &Db, seq: i64) -> Evidence {
if self.session.witness.is_none() {
return Evidence::default();
}
let live = db
.tasks()
.get(seq)
.map(|task| task.status.is_active())
.unwrap_or(false);
let watched = db.witnessed().footprint(seq).unwrap_or_default();
Evidence {
footprint: watched.describe(live),
watched,
changed: db
.witnessed()
.touched(seq)
.map(|seen| seen.iter().map(Observed::describe).collect())
.unwrap_or_default(),
contended: db
.witnessed()
.contention(seq)
.map(|seen| seen.iter().map(Contention::describe).collect())
.unwrap_or_default(),
undeclared: db.witnessed().undeclared(seq).unwrap_or_default(),
partial: None,
alone: db
.witnessed()
.baselines(&self.session.project)
.map(|live| live.len() <= 1)
.unwrap_or(true),
}
}
fn heartbeat_minutes(&self) -> u64 {
(self.shared.config.lease_ttl_minutes / 2).max(1)
}
fn instructions(&self) -> String {
format!(
"hird is a shared work queue and memory, used at the same time by other agents \
in other harnesses and by a human watching a TUI. Assume you are not alone.\n\
\n\
Tasks are referred to by their number (`seq`), the way the human says them: \
\"pick up task 42\" means seq 42. Always quote that number back.\n\
\n\
Getting work:\n\
- Told a number (\"pick up task 42\") → `task_claim`.\n\
- Told to work the queue, with no number → `task_next`. It picks the most \
important task that is actually workable and claims it for you. Call it again \
when you finish; keep going until it comes back with nothing.\n\
\n\
Working a task:\n\
1. `task_get` to read the full instructions.\n\
2. Claim BEFORE doing any work. Claims are atomic — if another agent holds the \
task the call fails and tells you who has it; relay that to the human instead of \
working the task anyway.\n\
3. `task_scope` with the files you are about to change, as soon as you know \
them. This is how the queue keeps two agents out of the same file: it answers \
with any overlap with work already under way. If it reports one, say so and \
coordinate rather than editing over someone.\n\
4. `task_update` with a short note as you go. A claim is a lease of {ttl} minutes \
and every update renews it, so call it at least every {heartbeat} minutes or the \
task returns to the pool and another agent may take it.\n\
5. `task_complete` with a result summary, or `task_fail` with a reason. \
Only the lease holder may do either.\n\
\n\
When a task turns out to be bigger than one job, `task_split` files the pieces \
as real tasks, makes the original wait for them, and puts it back in the pool — \
so the other agents can work the pieces in parallel while it waits. When you \
simply cannot do a task, `task_release` hands it back without marking it failed. \
When no agent can continue until a human decides or supplies something, pass the \
exact `question`: the task stays out of dispatch until `hird answer` records the \
response, and the next claim receives that question and answer.\n\
\n\
Tasks can depend on other tasks. A task whose dependencies are unfinished \
cannot be claimed, and the refusal names what it is waiting for. When you do \
claim, `built_on` carries each finished dependency's own result — the work \
this task was ordered after, summarised by whoever did it. Read it before \
the body: it is the context the dependency existed to produce. A `built_on` \
entry marked provisional is done but still under review; if its verdict \
sends that work back while you hold this task, your next `task_update` \
answers with `ground_shifted` — stop and re-read the reopened task before \
building further on what it made.\n\
\n\
A task may require capabilities such as `browser` or `network`. This session \
advertises [{capabilities}]. Named claims are refused when those do not fit, \
and `task_next` routes around incompatible work. That is not a transient race: \
relay it to the human, who must use a suitably configured harness.\n\
\n\
Some tasks are reviews, and a review is barred to the harness whose work it \
reviews — including this one. If a claim comes back saying the task is recused, \
that is not a race you can retry: relay it to the human, who needs to point a \
different tool at it. When a task you finish was marked for review, the answer \
names the review it filed; say that number out loud too. You are not being \
distrusted, you are being read by somebody who was not in the room, which is \
the whole reason the human is running more than one of us.\n\
\n\
A review ends in a verdict, not just prose: `task_complete` on a review \
requires `verdict` — \"upheld\" if the work stands, \"sent_back\" if it does \
not. Sending work back acts immediately: the queue reopens it with your \
findings appended to its brief, any agent (its author included) may pick it \
up, and completing it again files a fresh review — so write the result as \
instructions for whoever redoes it. Upholding is a signature: the board marks \
the work upheld on your harness's word, on the record.\n\
\n\
Memory: `mem_store` durable facts you learn — where something lives, why a \
decision was made, what a command is — one assertion per call, in plain prose \
that will still make sense to a different agent next week. Pass `task_seq` when \
you learned it working a task. `mem_search` before exploring from scratch; \
another agent may already have found the answer.\n\
\n\
Recall: a claimed task comes back with `recalled` — facts earlier agents \
recorded while working the same files, each with a `why` saying where it came \
from. Read those before you start; they are the reason to declare your paths \
early, because file scope is how the queue knows what to hand you. They are \
assertions, not gospel: if one turns out to be wrong, `mem_store` the truth.\n\
{footing}\
{witness}\n\
{identity}\
Everything is scoped to the current project ({project}) unless you pass \
`all_projects: true`.",
ttl = self.shared.config.lease_ttl_minutes,
heartbeat = self.heartbeat_minutes(),
capabilities = self.session.capabilities.join(", "),
identity = self.identity_instructions(),
project = self.session.project,
footing = self.footing_instructions(),
witness = self.witness_instructions(),
)
}
fn footing_instructions(&self) -> &'static str {
if self.footing().is_none() {
return "";
}
"\nHow much to trust a fact: assertions carry a `standing`, because hird records \
which files each one was read off and what those files said at the time. `firm` \
means the code has not moved since; `shaky` means it has, so the fact is \
unverified rather than wrong — re-read the file before you act on it; `orphaned` \
means the file is gone. Nothing marks a fact false; that is your call after \
looking. When you check a shaky fact and it still holds, `mem_store` it again \
word for word: that does not duplicate it, it re-anchors it to today's code and \
records you as another voice for it, and the next agent gets it marked firm. When \
it does not hold, `mem_store` the truth instead. Pass `paths` (or `task_seq`) so \
what you record gets a footing of its own.\n"
}
fn witness_instructions(&self) -> &'static str {
if self.session.witness.is_none() {
return "";
}
"\nThe working tree: hird watches it. A claim fingerprints the repository, and \
every task_update, task_scope and finishing call compares it again, so results \
come back with `changed` — the files that moved while you held the task, off the \
disk rather than out of anyone's summary. Two things there are worth acting on. \
`undeclared` lists files you have changed that you never declared: call \
task_scope with them, because the other agents' collision checks are reading \
your declaration and not your edits. `contended` means a file you declared has \
moved under another agent that declared it too — whoever read it first is \
holding a copy that no longer matches, so re-read it before your next write and \
tell the human. hird watched the file change; it cannot see who typed, so treat \
`changed` as what happened in your window, not as a list of your own edits. \
`footprint` is the same evidence in one sentence — `read-only` when nothing has \
moved, `modified 3 files` when something has — and it is what to tell the human \
when they ask whether the work changed anything. A claim that answers with \
`previously` is handing you a task that has been held before — a lease that \
expired, work released or sent back — and whatever that holder left uncommitted \
is in your working tree now, looking exactly like code that was always there. \
The sentence says who held it, how it ended and which files moved; re-read \
those files before building on or over them.\n"
}
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskListArgs {
#[serde(default)]
pub status: Option<String>,
#[serde(default)]
pub all_projects: Option<bool>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SeqArgs {
pub seq: i64,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskClaimArgs {
pub seq: i64,
#[serde(default)]
pub paths: Option<Vec<String>>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskNextArgs {
#[serde(default)]
pub all_projects: Option<bool>,
#[serde(default)]
pub avoid_conflicts: Option<bool>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskScopeArgs {
pub seq: i64,
pub paths: Vec<String>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskSplitArgs {
pub seq: i64,
pub subtasks: Vec<SubtaskArgs>,
#[serde(default)]
pub sequential: Option<bool>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SubtaskArgs {
pub title: String,
#[serde(default)]
pub body: Option<String>,
#[serde(default)]
pub priority: Option<i64>,
#[serde(default)]
pub paths: Option<Vec<String>>,
#[serde(default)]
pub requires: Option<Vec<String>>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskReleaseArgs {
pub seq: i64,
pub reason: String,
#[serde(default)]
pub question: Option<String>,
}
#[derive(Debug, Default, Deserialize, JsonSchema)]
pub struct TaskUpdateArgs {
pub seq: i64,
pub note: String,
#[serde(default)]
pub status: Option<String>,
#[serde(default)]
pub branch: Option<String>,
#[serde(default)]
pub worktree: Option<String>,
#[serde(default)]
pub pr_url: Option<String>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskCompleteArgs {
pub seq: i64,
pub result: String,
#[serde(default)]
pub verdict: Option<String>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskFailArgs {
pub seq: i64,
pub reason: String,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct MemStoreArgs {
pub content: String,
#[serde(default)]
pub tags: Option<String>,
#[serde(default)]
pub task_seq: Option<i64>,
#[serde(default)]
pub paths: Option<Vec<String>>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct MemSearchArgs {
pub query: String,
#[serde(default)]
pub limit: Option<usize>,
#[serde(default)]
pub all_projects: Option<bool>,
#[serde(default)]
pub include_superseded: Option<bool>,
}
#[derive(Debug, Serialize)]
struct TaskListResult<'a> {
project: &'a str,
all_projects: bool,
count: usize,
tasks: Vec<TaskRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
released: Vec<i64>,
}
#[derive(Debug, Serialize)]
struct TaskRow {
seq: i64,
title: String,
status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
holder: Option<String>,
priority: i64,
#[serde(skip_serializing_if = "Vec::is_empty")]
requires: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
missing_capabilities: Vec<String>,
updated_at: String,
#[serde(skip_serializing_if = "Option::is_none")]
project: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
blocked_by: Vec<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
awaiting_answer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
recused_from_you: Option<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
upheld: bool,
}
impl TaskRow {
fn from_summary(
summary: TaskSummary,
show_project: bool,
blocked_by: Vec<i64>,
awaiting_answer: Option<Question>,
recused: Option<Recusal>,
verdict: Option<Verdict>,
capabilities: &[String],
) -> TaskRow {
let missing_capabilities = crate::capability::missing(&summary.requirements, capabilities);
TaskRow {
seq: summary.seq,
title: summary.title,
upheld: summary.status == Status::Done && verdict == Some(Verdict::Upheld),
status: summary.status,
holder: summary.claimed_by,
priority: summary.priority,
requires: summary.requirements,
missing_capabilities,
updated_at: summary.updated_at,
project: show_project.then_some(summary.project),
blocked_by,
awaiting_answer: awaiting_answer.map(|q| q.question),
recused_from_you: recused.map(|r| r.describe()),
}
}
}
#[derive(Debug, Serialize)]
struct TaskDetail {
seq: i64,
project: String,
title: String,
body: String,
status: Status,
priority: i64,
#[serde(skip_serializing_if = "Vec::is_empty")]
requires: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
holder: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
lease_expires_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
result: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
links: Option<TaskLinks>,
#[serde(skip_serializing_if = "Vec::is_empty")]
questions: Vec<QuestionRow>,
created_at: String,
updated_at: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
waiting_for: Vec<BlockerRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
built_on: Vec<GroundRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
blocks: Vec<i64>,
#[serde(skip_serializing_if = "Vec::is_empty")]
paths: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
overlaps: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
recused_from: Vec<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
review_on_finish: bool,
#[serde(skip_serializing_if = "Option::is_none")]
verdict: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
verdicts_delivered: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
recalled: Vec<RecallRow>,
#[serde(flatten)]
witness: Evidence,
#[serde(skip_serializing_if = "Vec::is_empty")]
events: Vec<EventRow>,
}
#[derive(Debug, Serialize)]
struct BlockerRow {
seq: i64,
title: String,
status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
pending_review: Option<i64>,
}
impl From<Blocker> for BlockerRow {
fn from(b: Blocker) -> BlockerRow {
BlockerRow {
seq: b.seq,
title: b.title,
status: b.status,
pending_review: b.pending_review,
}
}
}
#[derive(Debug, Serialize)]
struct GroundRow {
seq: i64,
title: String,
#[serde(skip_serializing_if = "Option::is_none")]
result: Option<String>,
standing: String,
}
impl From<Ground> for GroundRow {
fn from(g: Ground) -> GroundRow {
GroundRow {
seq: g.seq,
title: g.title,
result: g.result,
standing: g.standing.describe(),
}
}
}
fn ground_rows(ground: Vec<Ground>) -> Vec<GroundRow> {
ground.into_iter().map(GroundRow::from).collect()
}
struct TaskContext {
waiting_for: Vec<Blocker>,
ground: Vec<Ground>,
blocks: Vec<i64>,
paths: Vec<String>,
conflicts: Vec<Conflict>,
recusals: Vec<Recusal>,
verdicts: Vec<VerdictRecord>,
delivered: Vec<VerdictRecord>,
recalled: Vec<Recalled>,
witness: Evidence,
events: Vec<TaskEvent>,
questions: Vec<Question>,
requirements: Vec<String>,
links: Option<TaskLinks>,
}
impl TaskDetail {
fn new(task: Task, context: TaskContext) -> TaskDetail {
TaskDetail {
seq: task.seq,
project: task.project,
title: task.title,
body: task.body,
status: task.status,
priority: task.priority,
requires: context.requirements,
holder: task.claimed_by,
lease_expires_at: task.lease_expires_at,
result: task.result,
links: context.links,
questions: context
.questions
.into_iter()
.map(QuestionRow::from)
.collect(),
created_at: task.created_at,
updated_at: task.updated_at,
waiting_for: context
.waiting_for
.into_iter()
.map(BlockerRow::from)
.collect(),
built_on: ground_rows(context.ground),
blocks: context.blocks,
paths: context.paths,
overlaps: describe_all(&context.conflicts),
recused_from: context.recusals.iter().map(Recusal::describe).collect(),
review_on_finish: task.review,
verdict: verdict_sentence(&context.verdicts),
verdicts_delivered: context
.delivered
.iter()
.map(|v| format!("task {}: {}", v.task_seq, v.verdict))
.collect(),
recalled: recall_rows(context.recalled),
witness: context.witness,
events: context.events.into_iter().map(EventRow::from).collect(),
}
}
}
#[derive(Debug, Serialize)]
struct QuestionRow {
n: i64,
question: String,
asked_by: String,
asked_at: String,
#[serde(skip_serializing_if = "Option::is_none")]
answer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
answered_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
answered_at: Option<String>,
}
impl From<Question> for QuestionRow {
fn from(q: Question) -> QuestionRow {
QuestionRow {
n: q.n,
question: q.question,
asked_by: q.asked_by,
asked_at: q.asked_at,
answer: q.answer,
answered_by: q.answered_by,
answered_at: q.answered_at,
}
}
}
fn describe_all(conflicts: &[Conflict]) -> Vec<String> {
conflicts.iter().map(Conflict::describe).collect()
}
fn verdict_sentence(verdicts: &[VerdictRecord]) -> Option<String> {
let latest = verdicts.last()?;
Some(if verdicts.len() > 1 {
format!(
"{}, verdict {} on this work",
latest.describe(),
verdicts.len()
)
} else {
latest.describe()
})
}
#[derive(Debug, Serialize)]
struct EventRow {
at: String,
actor: String,
kind: String,
#[serde(skip_serializing_if = "String::is_empty")]
detail: String,
}
impl From<TaskEvent> for EventRow {
fn from(e: TaskEvent) -> EventRow {
EventRow {
at: e.at,
actor: e.actor,
kind: e.kind.as_str().to_string(),
detail: e.detail,
}
}
}
#[derive(Debug, Serialize)]
struct RecallRow {
content: String,
why: String,
actor: String,
#[serde(skip_serializing_if = "Option::is_none")]
task_seq: Option<i64>,
created_at: String,
id: String,
#[serde(skip_serializing_if = "Option::is_none")]
standing: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
caution: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
corroboration: Option<String>,
}
impl RecallRow {
fn new(r: Recalled) -> RecallRow {
let standing = r.standing.filter(|s| *s != Standing::Unanchored);
RecallRow {
why: r.reason.describe(),
content: r.assertion.content,
actor: r.assertion.actor,
task_seq: r.task_seq,
created_at: r.assertion.created_at,
id: r.assertion.id,
standing: standing.as_ref().map(|s| s.as_str()),
caution: standing
.filter(Standing::needs_checking)
.and_then(|s| s.describe()),
corroboration: r.corroboration,
}
}
}
fn recall_rows(recalled: Vec<Recalled>) -> Vec<RecallRow> {
recalled.into_iter().map(RecallRow::new).collect()
}
#[derive(Debug, Serialize)]
struct ClaimResult {
claimed: i64,
holder: String,
lease_expires_at: String,
title: String,
body: String,
priority: i64,
project: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
requires: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
paths: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
overlaps: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
recalled: Vec<RecallRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
built_on: Vec<GroundRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
questions: Vec<QuestionRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
attempts: Vec<crate::model::Attempt>,
#[serde(skip_serializing_if = "Option::is_none")]
previously: Option<String>,
reminder: String,
}
impl ClaimResult {
fn new(
claim: Claim,
holder: String,
heartbeat: u64,
recalled: Vec<Recalled>,
previously: Option<String>,
) -> ClaimResult {
let overlaps = describe_all(&claim.conflicts);
let questions: Vec<QuestionRow> = claim
.questions
.iter()
.cloned()
.map(QuestionRow::from)
.collect();
let provisional: Vec<i64> = claim
.ground
.iter()
.filter(|g| g.standing.is_provisional())
.map(|g| g.seq)
.collect();
let heartbeat_rule = format!(
"call task_update at least every {heartbeat} minutes to keep this lease, \
then task_complete or task_fail when you are done"
);
let mut reminder = if overlaps.is_empty() {
heartbeat_rule
} else {
format!(
"another agent is already in some of these files — say so before you edit \
them. Otherwise: {heartbeat_rule}"
)
};
if !provisional.is_empty() {
let listed = provisional
.iter()
.map(|seq| format!("task {seq}"))
.collect::<Vec<_>>()
.join(", ");
reminder = format!(
"{listed} in `built_on` {} finished but still under review — a sent-back \
verdict would reopen {}, and your next check-in will say so if it happens. \
{reminder}",
plural(provisional.len(), "is", "are"),
plural(provisional.len(), "it", "them"),
);
}
if !recalled.is_empty() {
reminder = format!(
"read `recalled` first — earlier agents left those notes about this work, \
and each says where it came from. Then: {reminder}"
);
}
if previously.is_some() {
reminder = format!(
"this task has been held before — `previously` says by whom and what moved \
under them; re-read those files rather than assuming the tree is untouched. \
{reminder}"
);
}
if let Some(last) = claim.attempts.last() {
reminder = format!(
"this work has been rejected {} time{} — read `attempts`, newest last, and \
fix what the latest one ({} by {}) says before anything else. {reminder}",
claim.attempts.len(),
if claim.attempts.len() == 1 { "" } else { "s" },
last.outcome,
last.source,
);
}
if !questions.is_empty() {
reminder = format!(
"read `questions` before continuing — an earlier holder stopped for those \
decisions, and the answers are part of this task's brief. Then: {reminder}"
);
}
ClaimResult {
claimed: claim.task.seq,
holder,
lease_expires_at: claim.task.lease_expires_at.unwrap_or_default(),
title: claim.task.title,
body: claim.task.body,
priority: claim.task.priority,
project: claim.task.project,
requires: claim.requirements,
paths: claim.paths,
overlaps,
recalled: recall_rows(recalled),
built_on: ground_rows(claim.ground),
questions,
attempts: claim.attempts,
previously,
reminder,
}
}
}
#[derive(Debug, Serialize)]
struct NextResult {
#[serde(skip_serializing_if = "Option::is_none")]
claimed: Option<ClaimResult>,
#[serde(skip_serializing_if = "Option::is_none")]
idle: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
recess: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
blocked: Vec<i64>,
#[serde(skip_serializing_if = "Vec::is_empty")]
held: Vec<HeldRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
awaiting_answer: Vec<AwaitingAnswerRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
deferred: Vec<DeferredRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
recused: Vec<RecusedRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
gated: Vec<RecusedRow>,
#[serde(skip_serializing_if = "Vec::is_empty")]
incompatible: Vec<IncompatibleRow>,
}
#[derive(Debug, Serialize)]
struct DeferredRow {
seq: i64,
overlaps: Vec<String>,
}
#[derive(Debug, Serialize)]
struct HeldRow {
seq: i64,
review: i64,
}
#[derive(Debug, Serialize)]
struct AwaitingAnswerRow {
seq: i64,
question: String,
}
#[derive(Debug, Serialize)]
struct RecusedRow {
seq: i64,
why: String,
}
#[derive(Debug, Serialize)]
struct IncompatibleRow {
seq: i64,
missing: Vec<String>,
}
impl NextResult {
fn new(
dispatch: Dispatch,
holder: String,
heartbeat: u64,
recalled: Vec<Recalled>,
previously: Option<String>,
) -> NextResult {
let idle = dispatch.claim.is_none().then(|| idle_reason(&dispatch));
NextResult {
claimed: dispatch
.claim
.map(|claim| ClaimResult::new(claim, holder, heartbeat, recalled, previously)),
idle,
recess: dispatch.recess.map(|r| r.describe()),
blocked: dispatch.blocked,
held: dispatch
.held
.into_iter()
.map(|(seq, review)| HeldRow { seq, review })
.collect(),
awaiting_answer: dispatch
.awaiting_answer
.into_iter()
.map(|(seq, question)| AwaitingAnswerRow {
seq,
question: question.question,
})
.collect(),
deferred: dispatch
.deferred
.into_iter()
.map(|(seq, conflicts)| DeferredRow {
seq,
overlaps: describe_all(&conflicts),
})
.collect(),
recused: dispatch
.recused
.into_iter()
.map(|(seq, recusal)| RecusedRow {
seq,
why: recusal.describe(),
})
.collect(),
gated: dispatch
.gated
.into_iter()
.map(|(seq, why)| RecusedRow { seq, why })
.collect(),
incompatible: dispatch
.incompatible
.into_iter()
.map(|(seq, missing)| IncompatibleRow { seq, missing })
.collect(),
}
}
}
fn idle_reason(dispatch: &Dispatch) -> String {
if let Some(recess) = &dispatch.recess {
return format!(
"in recess, not idle: {}. Stand by rather than retrying; the human \
decides when claims resume",
recess.describe()
);
}
if dispatch.claim.is_none()
&& dispatch.recused.is_empty()
&& dispatch.held.is_empty()
&& dispatch.awaiting_answer.is_empty()
&& dispatch.blocked.is_empty()
&& dispatch.deferred.is_empty()
&& dispatch.incompatible.is_empty()
{
if let Some((seq, why)) = dispatch.gated.first() {
return format!(
"{} task{} ready, but this connection may not take {}: task {seq}: {why}",
dispatch.gated.len(),
plural(dispatch.gated.len(), " is", "s are"),
if dispatch.gated.len() == 1 {
"it"
} else {
"them"
}
);
}
}
let recused = dispatch.recused.len();
let held = dispatch.held.len();
let awaiting = dispatch.awaiting_answer.len();
let blocked = dispatch.blocked.len();
let deferred = dispatch.deferred.len();
let incompatible = dispatch.incompatible.len();
if recused > 0
&& held == 0
&& awaiting == 0
&& blocked == 0
&& deferred == 0
&& incompatible == 0
{
return format!(
"{recused} task{} ready, but every one of them is a review of work this harness \
did — they need an agent in another harness. Tell the human; waiting will not \
change it",
plural(recused, " is", "s are")
);
}
if held > 0
&& recused == 0
&& awaiting == 0
&& blocked == 0
&& deferred == 0
&& incompatible == 0
{
let mut reviews: Vec<i64> = dispatch.held.iter().map(|(_, review)| *review).collect();
reviews.sort_unstable();
reviews.dedup();
let listed = reviews
.iter()
.map(|s| format!("{s}"))
.collect::<Vec<_>>()
.join(", ");
return format!(
"{held} task{} finished but for a verdict: this queue holds dependents until \
review {listed} concludes. The way forward is that review, not waiting",
plural(held, " is", "s are")
);
}
if awaiting > 0
&& recused == 0
&& held == 0
&& blocked == 0
&& deferred == 0
&& incompatible == 0
{
return format!(
"{awaiting} open task{} awaiting a human answer; `awaiting_answer` names the \
question{}. No agent can make progress on {} until the answer is recorded",
plural(awaiting, " is", "s are"),
plural(awaiting, "", "s"),
plural(awaiting, "it", "them"),
);
}
let mut tail = String::new();
if held > 0 {
tail.push_str(&format!(
", and {held} held until a review delivers its verdict"
));
}
if recused > 0 {
tail.push_str(&format!(
", and {recused} that this harness is recused from (they need another harness)"
));
}
if awaiting > 0 {
tail.push_str(&format!(
", and {awaiting} awaiting a human answer before any agent can continue"
));
}
if incompatible > 0 {
tail.push_str(&format!(
", and {incompatible} requiring capabilities this session does not advertise"
));
}
let standing_down = dispatch.in_recess.len();
if standing_down > 0 {
tail.push_str(&format!(
", and {standing_down} in a project whose queue the human stood down"
));
}
match (blocked, deferred) {
(0, 0) if !tail.is_empty() => {
format!("nothing is workable: {}", tail.trim_start_matches(", and "))
}
(0, 0) => "nothing is open in this project; the queue is empty".to_string(),
(0, n) => format!(
"{n} task{} ready, but every one of them touches files another agent is \
working right now; try again once they finish{tail}",
plural(n, " is", "s are")
),
(n, 0) => format!(
"{n} task{} open, but all of them are waiting on unfinished dependencies{tail}",
plural(n, " is", "s are")
),
(blocked, deferred) => format!(
"nothing is workable: {blocked} task{} waiting on dependencies and \
{deferred} overlapping files another agent is in{tail}",
plural(blocked, " is", "s are")
),
}
}
fn plural(n: usize, one: &'static str, many: &'static str) -> &'static str {
if n == 1 {
one
} else {
many
}
}
#[derive(Debug, Default, Serialize)]
struct Evidence {
#[serde(skip_serializing_if = "Option::is_none")]
footprint: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
changed: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
contended: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
undeclared: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
partial: Option<String>,
#[serde(skip)]
alone: bool,
#[serde(skip)]
watched: Footprint,
}
impl Evidence {
fn settled(mut self) -> Evidence {
self.footprint = self.watched.describe(false);
self
}
fn advice(&self) -> Option<String> {
if !self.contended.is_empty() {
return Some(
"a file you declared has changed under another agent that declared it too — \
re-read it before your next write, and tell the human"
.to_string(),
);
}
if !self.undeclared.is_empty() {
let listed = self.undeclared.join(", ");
return Some(if self.alone {
format!(
"you have changed {} nobody was told about: {listed}. Call task_scope \
with {} so the other agents' collision checks can see it",
plural(self.undeclared.len(), "a file", "files"),
plural(self.undeclared.len(), "it", "them"),
)
} else {
format!(
"{listed} moved while you held this task and nobody has declared {}. If \
the edit was yours, call task_scope so the other agents can see it; if \
it was not, another agent is working outside what it declared",
plural(self.undeclared.len(), "it", "them"),
)
});
}
None
}
}
#[derive(Debug, Serialize)]
struct ScopeResult {
seq: i64,
paths: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
overlaps: Vec<String>,
#[serde(flatten)]
witness: Evidence,
advice: String,
}
#[derive(Debug, Serialize)]
struct SplitResult {
seq: i64,
status: Status,
subtasks: Vec<SubtaskRow>,
note: String,
}
#[derive(Debug, Serialize)]
struct SubtaskRow {
seq: i64,
title: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
waiting_for: Vec<i64>,
#[serde(skip_serializing_if = "Vec::is_empty")]
requires: Vec<String>,
}
#[derive(Debug, Serialize)]
struct UpdateResult {
seq: i64,
status: Status,
lease_expires_at: String,
note_recorded: String,
#[serde(skip_serializing_if = "Option::is_none")]
links: Option<TaskLinks>,
#[serde(skip_serializing_if = "Vec::is_empty")]
ground_shifted: Vec<String>,
#[serde(flatten)]
witness: Evidence,
#[serde(skip_serializing_if = "Option::is_none")]
advice: Option<String>,
}
#[derive(Debug, Serialize)]
struct FinishResult {
seq: i64,
status: Status,
result: String,
#[serde(flatten)]
witness: Evidence,
#[serde(skip_serializing_if = "Option::is_none")]
review_filed: Option<i64>,
#[serde(skip_serializing_if = "Vec::is_empty")]
verdicts: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
advice: Option<String>,
}
#[derive(Debug, Serialize)]
struct ReleaseResult {
#[serde(flatten)]
finish: FinishResult,
#[serde(skip_serializing_if = "Option::is_none")]
awaiting_answer: Option<String>,
}
impl FinishResult {
fn new(
seq: i64,
status: Status,
result: String,
witness: Evidence,
review_filed: Option<i64>,
delivered: &[Delivered],
) -> FinishResult {
let witness = witness.settled();
let advice = match (review_filed, delivered) {
(Some(review), _) => Some(format!(
"this work was marked for review, so task {review} is now open for an agent in \
another harness — you cannot take it yourself. Tell the human."
)),
(None, [.., _]) if delivered.iter().any(|d| d.reopened) => Some(
"the work you sent back is open again carrying your findings; any agent — \
its author included — may pick it up, and completing it will file a fresh \
review. Tell the human the verdict."
.to_string(),
),
(None, [.., _]) => Some(
"your verdict is on the record. Tell the human what you concluded.".to_string(),
),
(None, []) => witness.advice(),
};
FinishResult {
seq,
status,
result,
advice,
witness,
review_filed,
verdicts: delivered.iter().map(Delivered::describe).collect(),
}
}
}
#[derive(Debug, Serialize)]
struct MemStoreResult {
id: String,
project: String,
content: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
tags: Vec<String>,
actor: String,
#[serde(skip_serializing_if = "Option::is_none")]
task_seq: Option<i64>,
created_at: String,
#[serde(skip_serializing_if = "std::ops::Not::not")]
affirmed: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
anchored_to: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
corroboration: Option<String>,
}
#[derive(Debug, Serialize)]
struct MemSearchResult<'a> {
query: &'a str,
project: &'a str,
all_projects: bool,
count: usize,
assertions: Vec<AssertionRow>,
}
#[derive(Debug, Serialize)]
struct AssertionRow {
id: String,
content: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
tags: Vec<String>,
actor: String,
created_at: String,
#[serde(skip_serializing_if = "Option::is_none")]
project: Option<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
superseded: bool,
#[serde(skip_serializing_if = "Option::is_none")]
standing: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
footing: Option<String>,
}
impl AssertionRow {
fn new(a: Assertion, show_project: bool, standing: Option<&Standing>) -> AssertionRow {
let tags = a.tag_list().into_iter().map(str::to_string).collect();
let standing = standing.filter(|s| **s != Standing::Unanchored);
AssertionRow {
id: a.id,
tags,
content: a.content,
actor: a.actor,
created_at: a.created_at,
project: show_project.then_some(a.project),
superseded: a.superseded_by.is_some(),
standing: standing.map(Standing::as_str),
footing: standing.and_then(Standing::describe),
}
}
}
#[tool_router]
impl HirdMcp {
#[tool(name = "task_list")]
async fn task_list(
&self,
Parameters(args): Parameters<TaskListArgs>,
) -> Result<String, String> {
let status = match args
.status
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
{
Some(raw) => Some(raw.parse::<Status>().map_err(|e| e.to_string())?),
None => None,
};
let scope = self.scope(args.all_projects);
let show_project = scope.is_all();
let actor = self.actor();
let (released, dispatched, tasks, unmet, questions, recused, standing) =
self.with_db(|db| {
let released = db
.tasks()
.sweep_leases()
.map(|s| s.expired)
.unwrap_or_default();
let dispatched = self.expired_announcements(db, &released);
let listed = db.tasks().list(&scope, status);
let recused: BTreeMap<i64, Recusal> = listed
.as_ref()
.map(|tasks| {
tasks
.iter()
.filter(|t| t.status == Status::Open)
.filter_map(|t| {
db.recusals()
.bars(t.seq, &actor)
.ok()
.flatten()
.map(|r| (t.seq, r))
})
.collect()
})
.unwrap_or_default();
(
released,
dispatched,
listed,
db.deps()
.unmet_map(&scope, self.shared.config.clearance())
.unwrap_or_default(),
db.questions().unanswered_map(&scope).unwrap_or_default(),
recused,
db.verdicts().standing(&scope).unwrap_or_default(),
)
});
self.announce(&dispatched);
let tasks = tasks.map_err(stringify)?;
json(&TaskListResult {
project: &self.session.project,
all_projects: scope.is_all(),
count: tasks.len(),
tasks: tasks
.into_iter()
.map(|t| {
let blocked = unmet.get(&t.seq).cloned().unwrap_or_default();
let question = questions.get(&t.seq).cloned();
let barred = recused.get(&t.seq).cloned();
let verdict = standing.get(&t.seq).copied();
TaskRow::from_summary(
t,
show_project,
blocked,
question,
barred,
verdict,
&self.session.capabilities,
)
})
.collect(),
released,
})
}
#[tool(name = "task_get")]
async fn task_get(&self, Parameters(args): Parameters<SeqArgs>) -> Result<String, String> {
self.sweep_announcing();
let recall_limit = self.shared.config.recall_limit();
let detail = self.with_db(|db| {
let task = db.tasks().get(args.seq)?;
let (waiting_for, conflicts) = db
.tasks()
.readiness(args.seq, self.shared.config.clearance())?;
Ok::<_, Error>(TaskDetail::new(
task.clone(),
TaskContext {
waiting_for,
ground: db.deps().ground(args.seq)?,
blocks: db
.deps()
.dependents(args.seq)?
.into_iter()
.map(|b| b.seq)
.collect(),
paths: db.scopes().for_task(args.seq)?,
conflicts,
recusals: db.recusals().for_task(args.seq)?,
verdicts: db.verdicts().for_task(args.seq)?,
delivered: db.verdicts().of_review(args.seq)?,
recalled: self.recall(db, args.seq, recall_limit),
witness: self.evidence(db, args.seq),
events: db.tasks().events(&task.id, EVENT_WINDOW)?,
questions: db.questions().for_task(args.seq)?,
requirements: db.requirements().for_task(args.seq)?,
links: db.links().for_task(args.seq)?,
},
))
});
json(&detail.map_err(stringify)?)
}
#[tool(name = "task_claim")]
async fn task_claim(
&self,
Parameters(args): Parameters<TaskClaimArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let actor = self.actor();
let ttl = self.shared.config.lease_ttl();
let paths = args.paths.unwrap_or_default();
let policy = self.shared.config.on_conflict();
let recall_limit = self.shared.config.recall_limit();
let (claim, recalled, previously) = self
.with_db(|db| {
let claim = db
.tasks()
.gated(self.session.gate.as_deref())
.escalating_after(self.shared.config.max_attempts)
.claim_scoped_with_capabilities(
args.seq,
&actor,
ttl,
&paths,
policy,
self.shared.config.clearance(),
&self.session.capabilities,
)?;
self.begin_witnessing(db, args.seq);
Ok::<_, Error>((
claim,
self.recall(db, args.seq, recall_limit),
self.inheritance(db, args.seq),
))
})
.map_err(stringify)?;
json(&ClaimResult::new(
claim,
actor,
self.heartbeat_minutes(),
recalled,
previously,
))
}
#[tool(name = "task_next")]
async fn task_next(
&self,
Parameters(args): Parameters<TaskNextArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let actor = self.actor();
let ttl = self.shared.config.lease_ttl();
let scope = self.scope(args.all_projects);
let avoid = self.shared.config.avoid_conflicts(args.avoid_conflicts);
let recall_limit = self.shared.config.recall_limit();
let (dispatch, recalled, previously) = self
.with_db(|db| {
let dispatch = db
.tasks()
.gated(self.session.gate.as_deref())
.escalating_after(self.shared.config.max_attempts)
.claim_next_with_capabilities(
&actor,
ttl,
&scope,
avoid,
self.shared.config.clearance(),
&self.session.capabilities,
)?;
let (recalled, previously) = match &dispatch.claim {
Some(claim) => {
self.begin_witnessing(db, claim.task.seq);
(
self.recall(db, claim.task.seq, recall_limit),
self.inheritance(db, claim.task.seq),
)
}
None => (Vec::new(), None),
};
Ok::<_, Error>((dispatch, recalled, previously))
})
.map_err(stringify)?;
json(&NextResult::new(
dispatch,
actor,
self.heartbeat_minutes(),
recalled,
previously,
))
}
#[tool(name = "task_scope")]
async fn task_scope(
&self,
Parameters(args): Parameters<TaskScopeArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let actor = self.actor();
let policy = self.shared.config.on_conflict();
let (paths, conflicts, evidence) = self
.with_db(|db| {
let task = db.tasks().get(args.seq)?;
if !task.status.is_active() || task.claimed_by.as_deref() != Some(actor.as_str()) {
return Err(Error::NotHolder {
seq: args.seq,
status: task.status,
holder: task.claimed_by,
actor: actor.clone(),
});
}
let conflicts = db.scopes().declare(args.seq, &args.paths, &actor, policy)?;
Ok::<_, Error>((
db.scopes().for_task(args.seq)?,
conflicts,
self.witnessed(db, args.seq),
))
})
.map_err(stringify)?;
let overlaps = describe_all(&conflicts);
let advice = match (evidence.advice(), overlaps.is_empty()) {
(Some(urgent), _) => urgent,
(None, false) => "tell the human about the overlap before editing those files, \
and prefer to work elsewhere until it clears"
.to_string(),
(None, true) => "no other agent is in these files; go ahead".to_string(),
};
json(&ScopeResult {
seq: args.seq,
paths,
overlaps,
witness: evidence,
advice,
})
}
#[tool(name = "task_split")]
async fn task_split(
&self,
Parameters(args): Parameters<TaskSplitArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let actor = self.actor();
let empty: Vec<String> = Vec::new();
let subtasks: Vec<Subtask<'_>> = args
.subtasks
.iter()
.map(|s| Subtask {
title: &s.title,
body: s.body.as_deref().unwrap_or(""),
priority: s.priority,
paths: s.paths.as_ref().unwrap_or(&empty),
requirements: s.requires.as_ref().unwrap_or(&empty),
})
.collect();
let sequential = args.sequential.unwrap_or(false);
let (parent, children, dispatched) = self
.with_db(|db| {
let (parent, children) =
db.tasks().split(args.seq, &actor, &subtasks, sequential)?;
let dispatched: Vec<Announcement> = children
.iter()
.filter_map(|child| self.dispatchable(db, Cause::Filed, child.seq))
.collect();
Ok::<_, Error>((parent, children, dispatched))
})
.map_err(stringify)?;
self.announce(&dispatched);
let mut previous: Option<i64> = None;
let rows = children
.iter()
.enumerate()
.map(|(index, child)| {
let waiting_for = match previous.replace(child.seq) {
Some(prior) if sequential => vec![prior],
_ => Vec::new(),
};
SubtaskRow {
seq: child.seq,
title: child.title.clone(),
waiting_for,
requires: args.subtasks[index]
.requires
.as_ref()
.map(|r| {
crate::capability::normalize_all(r)
.expect("subtask requirements were validated before filing")
})
.unwrap_or_default(),
}
})
.collect();
json(&SplitResult {
seq: parent.seq,
status: parent.status,
subtasks: rows,
note: format!(
"task {} is back in the pool and now waits for {} piece{}; you no longer \
hold it. Call task_next for your own next piece of work",
parent.seq,
children.len(),
if children.len() == 1 { "" } else { "s" }
),
})
}
#[tool(name = "task_release")]
async fn task_release(
&self,
Parameters(args): Parameters<TaskReleaseArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let actor = self.actor();
let question = args.question.as_deref().map(str::trim);
let (task, evidence, dispatched, asked) = self
.with_db(|db| {
let evidence = self.witnessed(db, args.seq);
let (task, asked) = match question {
Some(question) => {
let (task, asked) =
db.tasks()
.release_asking(args.seq, &actor, &args.reason, question)?;
(task, Some(asked))
}
None => (db.tasks().release(args.seq, &actor, &args.reason)?, None),
};
let dispatched = asked
.is_none()
.then(|| self.dispatchable(db, Cause::Released, task.seq))
.flatten();
Ok::<_, Error>((task, evidence, dispatched, asked))
})
.map_err(stringify)?;
self.announce(dispatched.as_slice());
if let (Some(hook), Some(asked)) = (self.shared.question_herald.as_ref(), asked.as_ref()) {
hook.announce(&crate::herald::RaisedQuestion {
seq: task.seq,
title: task.title.clone(),
project: task.project.clone(),
question: asked.question.clone(),
asked_by: asked.asked_by.clone(),
});
}
json(&ReleaseResult {
finish: FinishResult::new(
task.seq,
task.status,
args.reason.trim().to_string(),
evidence,
None,
&[],
),
awaiting_answer: asked.map(|q| q.question),
})
}
#[tool(name = "task_update")]
async fn task_update(
&self,
Parameters(args): Parameters<TaskUpdateArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let start = match args
.status
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
{
None => false,
Some(raw) => match raw.parse::<Status>() {
Ok(Status::InProgress) => true,
_ => {
return Err(format!(
"task_update can only set status to \"in_progress\" (got {raw:?}); \
use task_complete or task_fail to finish a task"
))
}
},
};
let actor = self.actor();
let ttl = self.shared.config.lease_ttl();
let change = LinkChange {
branch: args.branch,
worktree: args.worktree,
pr_url: args.pr_url,
};
let asked_to_link = !change.is_empty();
let (task, links, evidence, shifted) = self
.with_db(|db| {
let (task, links) = db
.tasks()
.update_linked(args.seq, &actor, start, &args.note, ttl, &change)?;
let shifted = db.deps().shifted(args.seq).unwrap_or_default();
Ok::<_, Error>((task, links, self.witnessed(db, args.seq), shifted))
})
.map_err(stringify)?;
let ground_shifted: Vec<String> = shifted.iter().map(Shifted::describe).collect();
let advice = ground_shifted
.first()
.cloned()
.or_else(|| evidence.advice());
json(&UpdateResult {
seq: task.seq,
status: task.status,
lease_expires_at: task.lease_expires_at.unwrap_or_default(),
note_recorded: args.note.trim().to_string(),
links: links.filter(|_| asked_to_link),
ground_shifted,
advice,
witness: evidence,
})
}
#[tool(name = "task_complete")]
async fn task_complete(
&self,
Parameters(args): Parameters<TaskCompleteArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let verdict = match args
.verdict
.as_deref()
.map(str::trim)
.filter(|v| !v.is_empty())
{
Some(raw) => Some(raw.parse::<Verdict>().map_err(|e| e.to_string())?),
None => None,
};
let actor = self.actor();
let (task, evidence, dispatched) = self
.with_db(|db| {
let evidence = self.witnessed(db, args.seq);
let exhibit = self.session.witness.as_ref().and_then(|witness| {
let marked = db.tasks().get(args.seq).map(|t| t.review).unwrap_or(false);
if !marked {
return None;
}
let shown = crate::exhibit::assemble(db, witness, args.seq).ok()?;
let text = crate::exhibit::render(&shown);
if text.trim().is_empty() {
return None;
}
Some(crate::exhibit::clipped(
&text,
crate::exhibit::BRIEF_MAX_BYTES,
args.seq,
))
});
footing::settle(db, self.footing(), args.seq);
let task = db
.tasks()
.gated(self.session.gate.as_deref())
.escalating_after(self.shared.config.max_attempts)
.complete_showing(
args.seq,
&actor,
&args.result,
verdict,
exhibit.as_deref(),
)?;
let dispatched = self.dispatched(db, &task);
Ok::<_, Error>((task, evidence, dispatched))
})
.map_err(stringify)?;
self.announce(&dispatched);
json(&FinishResult::new(
task.task.seq,
task.task.status,
task.task.result.unwrap_or_default(),
evidence,
task.review,
&task.verdicts,
))
}
#[tool(name = "task_fail")]
async fn task_fail(
&self,
Parameters(args): Parameters<TaskFailArgs>,
) -> Result<String, String> {
self.sweep_announcing();
let actor = self.actor();
let (task, evidence) = self
.with_db(|db| {
let evidence = self.witnessed(db, args.seq);
footing::settle(db, self.footing(), args.seq);
let task = db
.tasks()
.gated(self.session.gate.as_deref())
.escalating_after(self.shared.config.max_attempts)
.fail(args.seq, &actor, &args.reason)?;
Ok::<_, Error>((task, evidence))
})
.map_err(stringify)?;
json(&FinishResult::new(
task.task.seq,
task.task.status,
task.task.result.unwrap_or_default(),
evidence,
task.review,
&task.verdicts,
))
}
#[tool(name = "mem_store")]
async fn mem_store(
&self,
Parameters(args): Parameters<MemStoreArgs>,
) -> Result<String, String> {
let actor = self.actor();
let (recorded, anchored, corroboration) = self
.with_db(|db| {
let recorded = db.memory().record(NewAssertion {
project: &self.session.project,
content: &args.content,
tags: args.tags.as_deref().unwrap_or(""),
actor: &actor,
task_seq: args.task_seq,
})?;
let ground = footing::ground(db, args.task_seq, args.paths.as_deref());
let anchored =
footing::anchor(db, self.footing(), &recorded.assertion().id, &ground)
.unwrap_or_default();
let corroboration = footing::corroboration(db, recorded.assertion());
Ok::<_, Error>((recorded, anchored, corroboration))
})
.map_err(stringify)?;
let affirmed = recorded.was_affirmed();
let assertion = recorded.into_assertion();
let tags = assertion
.tag_list()
.into_iter()
.map(str::to_string)
.collect();
json(&MemStoreResult {
id: assertion.id,
project: assertion.project,
tags,
content: assertion.content,
actor: assertion.actor,
task_seq: args.task_seq,
created_at: assertion.created_at,
affirmed,
anchored_to: anchored.into_iter().map(|a| a.path).collect(),
corroboration,
})
}
#[tool(name = "mem_search")]
async fn mem_search(
&self,
Parameters(args): Parameters<MemSearchArgs>,
) -> Result<String, String> {
let scope = self.scope(args.all_projects);
let show_project = scope.is_all();
let query = MemoryQuery::new(&args.query, scope.clone())
.limit(args.limit.unwrap_or(20).clamp(1, 200))
.include_superseded(args.include_superseded.unwrap_or(false));
let (hits, standings) = self
.with_db(|db| {
let hits = db.memory().search(&query)?;
let ids: Vec<String> = hits.iter().map(|a| a.id.clone()).collect();
let standings = footing::standings(db, self.footing(), &self.session.project, &ids);
Ok::<_, Error>((hits, standings))
})
.map_err(stringify)?;
json(&MemSearchResult {
query: &args.query,
project: &self.session.project,
all_projects: scope.is_all(),
count: hits.len(),
assertions: hits
.into_iter()
.map(|a| {
let standing = standings.get(&a.id).cloned();
AssertionRow::new(a, show_project, standing.as_ref())
})
.collect(),
})
}
}
#[tool_handler]
impl ServerHandler for HirdMcp {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(
Implementation::new("hird", env!("CARGO_PKG_VERSION"))
.with_title("hird work queue & memory"),
)
.with_instructions(self.instructions())
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
if let Some(client) = context.client_info() {
self.session.agent.name_from_client(&client.name);
}
Self::tool_router()
.call(ToolCallContext::new(self, request, context))
.await
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(
ListToolsResult::with_all_items(Self::tool_router().list_all())
.with_ttl_ms(0)
.with_cache_scope(CacheScope::Private),
)
}
async fn discover(
&self,
_context: RequestContext<RoleServer>,
) -> Result<DiscoverResult, ErrorData> {
Ok(DiscoverResult::from_server_info(
self.supported_protocol_versions().into_owned(),
self.get_info(),
)
.with_ttl_ms(0)
.with_cache_scope(CacheScope::Private))
}
}
fn announcement(cause: Cause, claimable: Claimable) -> Announcement {
Announcement {
cause,
seq: claimable.seq,
title: claimable.title,
project: claimable.project,
recused: claimable.recused,
requirements: claimable.requirements,
}
}
fn json<T: Serialize>(value: &T) -> Result<String, String> {
serde_json::to_string(value).map_err(|e| format!("failed to encode result: {e}"))
}
fn stringify(err: Error) -> String {
err.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Value;
const PROJECT: &str = "/tmp/project";
fn server() -> HirdMcp {
HirdMcp::new(
Db::open_in_memory().unwrap(),
AgentId::new("claude-code", "af31"),
PROJECT.to_string(),
Config::default(),
)
}
fn capable_server(capabilities: &[&str]) -> HirdMcp {
HirdMcp::with_capabilities(
Db::open_in_memory().unwrap(),
AgentId::new("codex", "fit1"),
PROJECT.to_string(),
Config::default(),
capabilities.iter().map(|c| c.to_string()).collect(),
)
.unwrap()
}
fn just(seq: i64) -> TaskClaimArgs {
TaskClaimArgs { seq, paths: None }
}
fn parse(raw: Result<String, String>) -> Value {
serde_json::from_str(&raw.expect("tool call succeeded")).unwrap()
}
fn seed(server: &HirdMcp, title: &str, body: &str) -> i64 {
server
.with_db(|db| db.tasks().create(PROJECT, title, body, 0, "cli"))
.unwrap()
.seq
}
struct Closed;
impl crate::gate::Gate for Closed {
fn may_claim(&self, _: &rusqlite::Connection, _: &Task, _: &str) -> Result<(), String> {
Err("this connection only reviews".into())
}
}
fn gated_server() -> HirdMcp {
let config = Config::default();
let session = Session::new(
AgentId::new("codex", "g1"),
PROJECT.to_string(),
Vec::new(),
&config,
)
.unwrap()
.with_role("reviewer")
.with_gate(Arc::new(Closed));
HirdMcp::connect(
Arc::new(Shared::new(Db::open_in_memory().unwrap(), config)),
session,
)
}
#[tokio::test]
async fn the_existing_tools_obey_the_gate_a_session_carries() {
let s = gated_server();
let seq = seed(&s, "write the parser", "");
let err = s.task_claim(Parameters(just(seq))).await.unwrap_err();
assert!(err.contains("this connection only reviews"), "{err}");
let out = parse(
s.task_next(Parameters(TaskNextArgs {
all_projects: None,
avoid_conflicts: None,
}))
.await,
);
assert!(out["claimed"].is_null(), "{out}");
assert_eq!(out["gated"][0]["seq"], seq);
assert!(
out["idle"].as_str().unwrap().contains("may not take"),
"{out}"
);
s.with_db(|db| db.tasks().create(PROJECT, "x", "", 0, &s.actor()))
.unwrap();
let trail = s.with_db(|db| db.audit().for_task(2)).unwrap();
assert_eq!(trail[0].role, "reviewer");
}
struct Holding;
impl crate::gate::Gate for Holding {
fn holds(&self, _: &rusqlite::Connection, task: &Task) -> Option<String> {
task.title
.starts_with("held")
.then(|| "it waits on something the queue cannot see".into())
}
}
#[tokio::test]
async fn the_herald_stays_quiet_about_work_the_gate_holds() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("herald.log");
let config = Config {
dispatch_hook: format!("echo \"$HIRD_EVENT $HIRD_TASK\" >> {}", log.display()),
..Config::default()
};
let session = Session::new(
AgentId::new("claude-code", "h1"),
PROJECT.to_string(),
Vec::new(),
&config,
)
.unwrap()
.with_gate(Arc::new(Holding));
let s = HirdMcp::connect(
Arc::new(Shared::new(Db::open_in_memory().unwrap(), config)),
session,
);
let dep = seed(&s, "lay the ground", "");
let held = seed(&s, "held on the ground", "");
let free = seed(&s, "free on the ground", "");
s.with_db(|db| {
db.deps().add(held, dep, "cli").unwrap();
db.deps().add(free, dep, "cli").unwrap();
});
s.task_claim(Parameters(just(dep))).await.unwrap();
s.task_complete(Parameters(TaskCompleteArgs {
seq: dep,
result: "laid".into(),
verdict: None,
}))
.await
.unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
let contents = loop {
let contents = std::fs::read_to_string(&log).unwrap_or_default();
if contents.contains(&format!("unblocked {free}")) {
break contents;
}
assert!(
std::time::Instant::now() < deadline,
"the hook never heard the release; log so far:\n{contents}"
);
std::thread::sleep(std::time::Duration::from_millis(20));
};
std::thread::sleep(std::time::Duration::from_millis(300));
let contents = std::fs::read_to_string(&log).unwrap_or(contents);
assert!(!contents.contains(&format!(" {held}")), "{contents}");
s.with_db(|db| {
let reason = db.tasks().held_by(held, &Holding).unwrap().unwrap();
assert!(reason.contains("cannot see"), "{reason}");
assert!(db.tasks().held_by(free, &Holding).unwrap().is_none());
});
}
#[tokio::test]
async fn a_claim_hands_over_every_rejected_attempt_and_says_to_read_them() {
let s = server();
let seq = seed(&s, "write the parser", "");
s.with_db(|db| {
let ttl = std::time::Duration::from_secs(900);
db.tasks().set_review(seq, true, "cli").unwrap();
db.scopes()
.declare(
seq,
&["src/p.rs".into()],
"cli",
crate::repo::OnConflict::Report,
)
.unwrap();
db.tasks().claim(seq, "codex:b", ttl).unwrap();
let review = db.tasks().complete(seq, "codex:b", "built").unwrap();
let review = review.review.unwrap();
db.tasks().claim(review, "copilot:r", ttl).unwrap();
db.tasks()
.complete_with(
review,
"copilot:r",
"the lexer drops tabs",
Some(Verdict::SentBack),
)
.unwrap();
});
let out = parse(s.task_claim(Parameters(just(seq))).await);
assert_eq!(out["attempts"][0]["outcome"], "sent_back");
assert_eq!(out["attempts"][0]["output"], "the lexer drops tabs");
assert!(
out["reminder"]
.as_str()
.unwrap()
.contains("read `attempts`"),
"{out}"
);
let fresh = seed(&s, "another", "");
let out = parse(s.task_claim(Parameters(just(fresh))).await);
assert!(out.get("attempts").is_none(), "{out}");
}
#[tokio::test]
async fn task_list_reports_scope_and_rows() {
let s = server();
seed(&s, "write the parser", "full instructions here");
let out = parse(
s.task_list(Parameters(TaskListArgs {
status: None,
all_projects: None,
}))
.await,
);
assert_eq!(out["project"], PROJECT);
assert_eq!(out["all_projects"], false);
assert_eq!(out["count"], 1);
assert_eq!(out["tasks"][0]["seq"], 1);
assert_eq!(out["tasks"][0]["status"], "open");
assert!(out["tasks"][0].get("holder").is_none());
assert!(out["tasks"][0].get("project").is_none());
}
#[tokio::test]
async fn task_list_rejects_an_unknown_status_with_the_valid_set() {
let s = server();
let err = s
.task_list(Parameters(TaskListArgs {
status: Some("blocked".into()),
all_projects: None,
}))
.await
.unwrap_err();
assert!(err.contains("unknown status"), "{err}");
assert!(err.contains("in_progress"), "{err}");
}
#[tokio::test]
async fn task_list_can_widen_to_every_project() {
let s = server();
seed(&s, "here", "");
s.with_db(|db| db.tasks().create("/elsewhere", "there", "", 0, "cli"))
.unwrap();
let scoped = parse(
s.task_list(Parameters(TaskListArgs {
status: None,
all_projects: None,
}))
.await,
);
assert_eq!(scoped["count"], 1);
let wide = parse(
s.task_list(Parameters(TaskListArgs {
status: None,
all_projects: Some(true),
}))
.await,
);
assert_eq!(wide["count"], 2);
assert!(wide["tasks"][0]["project"].is_string());
}
#[tokio::test]
async fn task_get_returns_the_body_and_history() {
let s = server();
let seq = seed(&s, "write the parser", "start with the lexer");
let out = parse(s.task_get(Parameters(SeqArgs { seq })).await);
assert_eq!(out["body"], "start with the lexer");
assert_eq!(out["events"][0]["kind"], "created");
assert_eq!(out["events"][0]["actor"], "cli");
}
#[tokio::test]
async fn task_get_on_a_missing_task_is_a_plain_sentence() {
let s = server();
assert_eq!(
s.task_get(Parameters(SeqArgs { seq: 99 }))
.await
.unwrap_err(),
"task 99 not found"
);
}
#[tokio::test]
async fn claiming_returns_the_body_and_the_heartbeat_reminder() {
let s = server();
let seq = seed(&s, "write the parser", "start with the lexer");
let out = parse(s.task_claim(Parameters(just(seq))).await);
assert_eq!(out["claimed"], seq);
assert_eq!(out["holder"], "claude-code:af31");
assert_eq!(out["body"], "start with the lexer");
assert!(out["lease_expires_at"].as_str().unwrap().ends_with('Z'));
assert!(out["reminder"].as_str().unwrap().contains("task_update"));
}
#[tokio::test]
async fn a_losing_claim_names_the_holder_and_the_deadline() {
let s = server();
let seq = seed(&s, "t", "");
s.with_db(|db| {
db.tasks()
.claim(seq, "codex:9f2c", Config::default().lease_ttl())
})
.unwrap();
let err = s.task_claim(Parameters(just(seq))).await.unwrap_err();
assert!(
err.starts_with("task 1 is claimed by codex:9f2c until "),
"{err}"
);
}
#[tokio::test]
async fn update_starts_work_and_renews_the_lease() {
let s = server();
let seq = seed(&s, "t", "");
s.task_claim(Parameters(just(seq))).await.unwrap();
let out = parse(
s.task_update(Parameters(TaskUpdateArgs {
seq,
note: " read the lexer ".into(),
status: Some("in_progress".into()),
..Default::default()
}))
.await,
);
assert_eq!(out["status"], "in_progress");
assert_eq!(out["note_recorded"], "read the lexer");
assert!(out["lease_expires_at"].as_str().unwrap().ends_with('Z'));
}
#[tokio::test]
async fn update_refuses_to_be_used_as_a_finishing_move() {
let s = server();
let seq = seed(&s, "t", "");
s.task_claim(Parameters(just(seq))).await.unwrap();
let err = s
.task_update(Parameters(TaskUpdateArgs {
seq,
note: "n".into(),
status: Some("done".into()),
..Default::default()
}))
.await
.unwrap_err();
assert!(err.contains("task_complete or task_fail"), "{err}");
}
#[tokio::test]
async fn only_the_holder_can_update_or_finish() {
let s = server();
let seq = seed(&s, "t", "");
s.with_db(|db| {
db.tasks()
.claim(seq, "codex:9f2c", Config::default().lease_ttl())
})
.unwrap();
for err in [
s.task_update(Parameters(TaskUpdateArgs {
seq,
note: "n".into(),
status: None,
..Default::default()
}))
.await
.unwrap_err(),
s.task_complete(Parameters(TaskCompleteArgs {
seq,
result: "r".into(),
verdict: None,
}))
.await
.unwrap_err(),
s.task_fail(Parameters(TaskFailArgs {
seq,
reason: "r".into(),
}))
.await
.unwrap_err(),
] {
assert!(err.contains("held by codex:9f2c"), "{err}");
}
}
#[tokio::test]
async fn completing_and_failing_report_the_final_state() {
let s = server();
let done = seed(&s, "a", "");
s.task_claim(Parameters(just(done))).await.unwrap();
let out = parse(
s.task_complete(Parameters(TaskCompleteArgs {
seq: done,
result: "merged".into(),
verdict: None,
}))
.await,
);
assert_eq!(out["status"], "done");
assert_eq!(out["result"], "merged");
let bad = seed(&s, "b", "");
s.task_claim(Parameters(just(bad))).await.unwrap();
let out = parse(
s.task_fail(Parameters(TaskFailArgs {
seq: bad,
reason: "no credentials".into(),
}))
.await,
);
assert_eq!(out["status"], "failed");
assert_eq!(out["result"], "no credentials");
}
async fn reviewed_work(s: &HirdMcp) -> (i64, i64) {
let seq = seed(s, "port the loader", "keep the precedence");
let review = s
.with_db(|db| {
db.tasks().set_review(seq, true, "cli")?;
db.scopes().declare(
seq,
&["src/loader.rs".to_string()],
"cli",
crate::repo::OnConflict::Report,
)?;
db.tasks()
.claim(seq, "codex:9f2c", Config::default().lease_ttl())?;
db.tasks().complete(seq, "codex:9f2c", "ported")
})
.unwrap()
.review
.expect("a review was filed");
s.task_claim(Parameters(just(review))).await.unwrap();
(seq, review)
}
#[tokio::test]
async fn a_review_must_end_in_a_verdict_and_sent_back_reopens_the_work() {
let s = server();
let (seq, review) = reviewed_work(&s).await;
let err = s
.task_complete(Parameters(TaskCompleteArgs {
seq: review,
result: "the empty case is missed".into(),
verdict: None,
}))
.await
.unwrap_err();
assert!(err.contains("upheld"), "{err}");
assert!(err.contains("sent_back"), "{err}");
let out = parse(
s.task_complete(Parameters(TaskCompleteArgs {
seq: review,
result: "the empty case is missed; handle it in parse()".into(),
verdict: Some("sent_back".into()),
}))
.await,
);
assert_eq!(out["status"], "done");
assert!(
out["verdicts"][0].as_str().unwrap().contains("sent back"),
"{out}"
);
assert!(
out["advice"].as_str().unwrap().contains("findings"),
"{out}"
);
let detail = parse(s.task_get(Parameters(SeqArgs { seq })).await);
assert_eq!(detail["status"], "open");
assert!(
detail["body"].as_str().unwrap().contains("empty case"),
"the findings travel in the brief: {detail}"
);
assert!(
detail["verdict"]
.as_str()
.unwrap()
.contains("sent back by claude-code"),
"{detail}"
);
}
#[tokio::test]
async fn a_claim_arrives_knowing_what_it_builds_on() {
let s = server();
let schema = seed(&s, "design the schema", "");
let api = seed(&s, "port the api", "");
s.with_db(|db| {
db.deps().add(api, schema, "cli")?;
db.tasks()
.claim(schema, "codex:9f2c", Config::default().lease_ttl())?;
db.tasks()
.complete(schema, "codex:9f2c", "the schema lives in db.rs")
})
.unwrap();
let out = parse(s.task_claim(Parameters(just(api))).await);
assert_eq!(out["built_on"][0]["seq"], schema);
assert_eq!(out["built_on"][0]["result"], "the schema lives in db.rs");
assert_eq!(out["built_on"][0]["standing"], "done");
assert!(
!out["reminder"].as_str().unwrap().contains("under review"),
"{out}"
);
}
#[tokio::test]
async fn provisional_ground_is_flagged_on_the_claim_and_shifts_at_the_check_in() {
let s = server();
let (work, review) = reviewed_work(&s).await;
let dependent = seed(&s, "use the loader", "");
s.with_db(|db| db.deps().add(dependent, work, "cli"))
.unwrap();
let out = parse(s.task_claim(Parameters(just(dependent))).await);
let standing = out["built_on"][0]["standing"].as_str().unwrap();
assert!(
standing.contains(&format!("under review {review}")),
"{out}"
);
assert!(standing.contains("provisional"), "{out}");
assert!(
out["reminder"]
.as_str()
.unwrap()
.contains("still under review"),
"{out}"
);
parse(
s.task_complete(Parameters(TaskCompleteArgs {
seq: review,
result: "the empty case is missed".into(),
verdict: Some("sent_back".into()),
}))
.await,
);
let out = parse(
s.task_update(Parameters(TaskUpdateArgs {
seq: dependent,
note: "wiring the loader in".into(),
status: None,
..Default::default()
}))
.await,
);
let shifted = out["ground_shifted"][0].as_str().unwrap();
assert!(
shifted.contains(&format!("sent back by review {review}")),
"{out}"
);
assert_eq!(out["advice"].as_str().unwrap(), shifted, "{out}");
}
#[tokio::test]
async fn holds_keeps_dependents_off_the_board_until_the_verdict() {
let s = HirdMcp::new(
Db::open_in_memory().unwrap(),
AgentId::new("claude-code", "af31"),
PROJECT.to_string(),
Config {
under_review: crate::config::UnderReview::Holds,
..Config::default()
},
);
let work = seed(&s, "port the loader", "");
let dependent = seed(&s, "use the loader", "");
let review = s
.with_db(|db| {
db.deps().add(dependent, work, "cli")?;
db.tasks().set_review(work, true, "cli")?;
db.scopes().declare(
work,
&["src/loader.rs".to_string()],
"cli",
crate::repo::OnConflict::Report,
)?;
db.tasks()
.claim(work, "claude-code:9x9x", Config::default().lease_ttl())?;
db.tasks().complete(work, "claude-code:9x9x", "ported")
})
.unwrap()
.review
.expect("a review was filed");
let err = s.task_claim(Parameters(just(dependent))).await.unwrap_err();
assert!(err.contains(&format!("under review {review}")), "{err}");
assert!(err.contains("verdict"), "{err}");
let out = parse(
s.task_next(Parameters(TaskNextArgs {
all_projects: None,
avoid_conflicts: None,
}))
.await,
);
assert!(out.get("claimed").is_none(), "{out}");
assert_eq!(out["held"][0]["seq"], dependent);
assert_eq!(out["held"][0]["review"], review);
assert!(out["idle"].as_str().unwrap().contains("verdict"), "{out}");
}
#[tokio::test]
async fn an_upheld_verdict_marks_the_work_on_the_board() {
let s = server();
let (seq, review) = reviewed_work(&s).await;
parse(
s.task_complete(Parameters(TaskCompleteArgs {
seq: review,
result: "read it; it holds".into(),
verdict: Some("upheld".into()),
}))
.await,
);
let list = parse(
s.task_list(Parameters(TaskListArgs {
status: None,
all_projects: None,
}))
.await,
);
let row = list["tasks"]
.as_array()
.unwrap()
.iter()
.find(|t| t["seq"] == seq)
.unwrap();
assert_eq!(row["upheld"], true, "{row}");
let detail = parse(s.task_get(Parameters(SeqArgs { seq: review })).await);
assert!(
detail["verdicts_delivered"][0]
.as_str()
.unwrap()
.contains("upheld"),
"{detail}"
);
}
#[tokio::test]
async fn a_verdict_on_ordinary_work_is_refused() {
let s = server();
let seq = seed(&s, "t", "");
s.task_claim(Parameters(just(seq))).await.unwrap();
let err = s
.task_complete(Parameters(TaskCompleteArgs {
seq,
result: "done".into(),
verdict: Some("upheld".into()),
}))
.await
.unwrap_err();
assert!(err.contains("not a review"), "{err}");
}
#[tokio::test]
async fn mem_store_records_provenance_and_the_task_link() {
let s = server();
let seq = seed(&s, "t", "");
let out = parse(
s.mem_store(Parameters(MemStoreArgs {
content: "the lexer lives in src/lex.rs".into(),
tags: Some(" parser , code ".into()),
task_seq: Some(seq),
paths: None,
}))
.await,
);
assert_eq!(out["actor"], "claude-code:af31");
assert_eq!(out["project"], PROJECT);
assert_eq!(out["tags"], serde_json::json!(["parser", "code"]));
assert_eq!(out["task_seq"], seq);
}
#[tokio::test]
async fn mem_store_rejects_a_link_to_a_task_that_does_not_exist() {
let s = server();
let err = s
.mem_store(Parameters(MemStoreArgs {
content: "x".into(),
tags: None,
task_seq: Some(404),
paths: None,
}))
.await
.unwrap_err();
assert_eq!(err, "task 404 not found");
}
#[tokio::test]
async fn mem_search_finds_what_mem_store_wrote() {
let s = server();
s.mem_store(Parameters(MemStoreArgs {
content: "the lexer lives in src/lex.rs".into(),
tags: None,
task_seq: None,
paths: None,
}))
.await
.unwrap();
let out = parse(
s.mem_search(Parameters(MemSearchArgs {
query: "lexer".into(),
limit: None,
all_projects: None,
include_superseded: None,
}))
.await,
);
assert_eq!(out["count"], 1);
assert_eq!(
out["assertions"][0]["content"],
"the lexer lives in src/lex.rs"
);
assert_eq!(out["assertions"][0]["actor"], "claude-code:af31");
}
#[tokio::test]
async fn mem_search_clamps_absurd_limits() {
let s = server();
for i in 0..5 {
s.mem_store(Parameters(MemStoreArgs {
content: format!("fact {i} about widgets"),
tags: None,
task_seq: None,
paths: None,
}))
.await
.unwrap();
}
let out = parse(
s.mem_search(Parameters(MemSearchArgs {
query: "widgets".into(),
limit: Some(0),
all_projects: None,
include_superseded: None,
}))
.await,
);
assert_eq!(out["count"], 1, "limit 0 is clamped to 1, not to nothing");
}
#[tokio::test]
async fn an_expiry_noticed_by_task_next_is_announced() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("herald.log");
let s = HirdMcp::new(
Db::open_in_memory().unwrap(),
AgentId::new("claude-code", "af31"),
PROJECT.to_string(),
Config {
dispatch_hook: format!("echo \"$HIRD_EVENT $HIRD_TASK\" >> {}", log.display()),
..Config::default()
},
);
let dead = seed(&s, "abandoned", "");
let other = seed(&s, "other work", "");
s.with_db(|db| {
db.tasks()
.claim(dead, "codex:dead", Config::default().lease_ttl())
.unwrap();
db.conn()
.execute(
"UPDATE tasks SET lease_expires_at = '2000-01-01T00:00:00.000Z' WHERE seq = ?1",
[dead],
)
.unwrap();
});
let out = parse(
s.task_next(Parameters(TaskNextArgs {
all_projects: None,
avoid_conflicts: None,
}))
.await,
);
assert!(out["claimed"]["claimed"].is_i64(), "{out}");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
let contents = loop {
let contents = std::fs::read_to_string(&log).unwrap_or_default();
if contents.contains("lease_expired") {
break contents;
}
assert!(
std::time::Instant::now() < deadline,
"the hook never heard the expiry; log so far:\n{contents}"
);
std::thread::sleep(std::time::Duration::from_millis(20));
};
assert!(
contents.contains(&format!("lease_expired {dead}")),
"{contents}"
);
assert!(!contents.contains(&format!(" {other}")), "{contents}");
}
#[tokio::test]
async fn task_list_reports_leases_it_released() {
let s = server();
let seq = seed(&s, "t", "");
s.with_db(|db| {
db.tasks()
.claim(seq, "codex:dead", Config::default().lease_ttl())
.unwrap();
db.conn()
.execute(
"UPDATE tasks SET lease_expires_at = '2000-01-01T00:00:00.000Z' WHERE seq = ?1",
[seq],
)
.unwrap();
});
let out = parse(
s.task_list(Parameters(TaskListArgs {
status: None,
all_projects: None,
}))
.await,
);
assert_eq!(out["released"], serde_json::json!([seq]));
assert_eq!(out["tasks"][0]["status"], "open");
}
fn claim_with(seq: i64, paths: &[&str]) -> TaskClaimArgs {
TaskClaimArgs {
seq,
paths: Some(paths.iter().map(|p| p.to_string()).collect()),
}
}
fn next_args() -> TaskNextArgs {
TaskNextArgs {
all_projects: None,
avoid_conflicts: None,
}
}
#[tokio::test]
async fn next_claims_the_best_available_task_and_reads_like_a_claim() {
let s = server();
seed(&s, "low priority", "");
let important = s
.with_db(|db| db.tasks().create(PROJECT, "important", "do it", 5, "cli"))
.unwrap()
.seq;
let out = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(out["claimed"]["claimed"], important);
assert_eq!(out["claimed"]["body"], "do it");
assert_eq!(out["claimed"]["holder"], "claude-code:af31");
assert!(out.get("idle").is_none());
}
#[tokio::test]
async fn capability_matching_is_visible_on_named_and_next_claims() {
let s = capable_server(&["network"]);
let browser = s
.with_db(|db| db.tasks().create(PROJECT, "visual QA", "", 5, "cli"))
.unwrap()
.seq;
s.with_db(|db| {
db.requirements()
.set(browser, &["browser".into()], "cli")
.unwrap()
});
let ordinary = seed(&s, "write docs", "");
let listed = parse(
s.task_list(Parameters(TaskListArgs {
status: None,
all_projects: None,
}))
.await,
);
let browser_row = listed["tasks"]
.as_array()
.unwrap()
.iter()
.find(|row| row["seq"] == browser)
.unwrap();
assert_eq!(browser_row["requires"][0], "browser");
assert_eq!(browser_row["missing_capabilities"][0], "browser");
let refused = s.task_claim(Parameters(just(browser))).await.unwrap_err();
assert!(refused.contains("requires browser"), "{refused}");
assert!(refused.contains("advertises network"), "{refused}");
let handed = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(handed["claimed"]["claimed"], ordinary);
assert_eq!(handed["incompatible"][0]["seq"], browser);
assert_eq!(handed["incompatible"][0]["missing"][0], "browser");
}
#[tokio::test]
async fn next_explains_an_empty_queue_rather_than_going_quiet() {
let s = server();
let out = parse(s.task_next(Parameters(next_args())).await);
assert!(out.get("claimed").is_none());
assert_eq!(
out["idle"],
"nothing is open in this project; the queue is empty"
);
}
#[tokio::test]
async fn next_names_the_dependencies_that_left_it_empty_handed() {
let s = server();
let gate = seed(&s, "gate", "");
let waiting = seed(&s, "waiting", "");
s.with_db(|db| db.deps().add(waiting, gate, "cli")).unwrap();
s.with_db(|db| {
db.tasks()
.claim(gate, "codex:9f2c", Config::default().lease_ttl())
})
.unwrap();
let out = parse(s.task_next(Parameters(next_args())).await);
assert!(out.get("claimed").is_none());
assert_eq!(out["blocked"], serde_json::json!([waiting]));
assert!(
out["idle"]
.as_str()
.unwrap()
.contains("waiting on unfinished dependencies"),
"{out}"
);
}
#[tokio::test]
async fn next_reports_the_files_that_made_it_hold_back() {
let s = server();
let held = seed(&s, "held", "");
let overlapping = seed(&s, "overlapping", "");
s.with_db(|db| {
db.scopes().declare(
held,
&["src/**".into()],
"cli",
crate::repo::OnConflict::Report,
)?;
db.scopes().declare(
overlapping,
&["src/db.rs".into()],
"cli",
crate::repo::OnConflict::Report,
)?;
db.tasks()
.claim(held, "codex:9f2c", Config::default().lease_ttl())
})
.unwrap();
let out = parse(s.task_next(Parameters(next_args())).await);
assert!(out.get("claimed").is_none());
assert_eq!(out["deferred"][0]["seq"], overlapping);
let overlap = out["deferred"][0]["overlaps"][0].as_str().unwrap();
assert!(overlap.contains("src/db.rs overlaps src/**"), "{overlap}");
assert!(overlap.contains("codex:9f2c"), "{overlap}");
}
#[tokio::test]
async fn a_blocked_task_cannot_be_claimed_and_the_error_says_what_to_wait_for() {
let s = server();
let gate = seed(&s, "write the schema", "");
let waiting = seed(&s, "write the api", "");
s.with_db(|db| db.deps().add(waiting, gate, "cli")).unwrap();
let err = s.task_claim(Parameters(just(waiting))).await.unwrap_err();
assert!(err.contains("task 2 is blocked by task 1"), "{err}");
assert!(err.contains("write the schema"), "{err}");
}
#[tokio::test]
async fn claiming_with_paths_records_them_and_warns_about_overlaps() {
let s = server();
let held = seed(&s, "held", "");
let mine = seed(&s, "mine", "");
s.with_db(|db| {
db.scopes().declare(
held,
&["src/**".into()],
"cli",
crate::repo::OnConflict::Report,
)?;
db.tasks()
.claim(held, "codex:9f2c", Config::default().lease_ttl())
})
.unwrap();
let out = parse(
s.task_claim(Parameters(claim_with(mine, &["src/db.rs"])))
.await,
);
assert_eq!(out["paths"], serde_json::json!(["src/db.rs"]));
assert!(out["overlaps"][0].as_str().unwrap().contains("codex:9f2c"));
assert!(out["reminder"]
.as_str()
.unwrap()
.contains("already in some of these files"));
}
fn earlier_work(s: &HirdMcp, title: &str, paths: &[&str], learned: &str) -> i64 {
let seq = seed(s, title, "");
s.with_db(|db| {
let owned: Vec<String> = paths.iter().map(|p| p.to_string()).collect();
db.scopes()
.declare(seq, &owned, "cli", crate::repo::OnConflict::Report)?;
db.memory().store(NewAssertion {
project: PROJECT,
content: learned,
tags: "",
actor: "codex:9f2c",
task_seq: Some(seq),
})?;
db.tasks()
.claim(seq, "codex:9f2c", Config::default().lease_ttl())?;
db.tasks().complete(seq, "codex:9f2c", "done")
})
.unwrap();
seq
}
#[tokio::test]
async fn a_claim_arrives_with_what_earlier_work_in_those_files_learned() {
let s = server();
let earlier = earlier_work(
&s,
"Port the config loader",
&["src/config.rs"],
"env vars beat the config file",
);
let mine = seed(&s, "Audit the loader", "");
let out = parse(
s.task_claim(Parameters(claim_with(mine, &["src/*.rs"])))
.await,
);
let recalled = &out["recalled"][0];
assert_eq!(recalled["content"], "env vars beat the config file");
assert_eq!(recalled["task_seq"], earlier);
assert_eq!(recalled["actor"], "codex:9f2c");
let why = recalled["why"].as_str().unwrap();
assert!(why.contains(&format!("task {earlier}")), "{why}");
assert!(why.contains("src/config.rs"), "{why}");
assert!(out["reminder"]
.as_str()
.unwrap()
.starts_with("read `recalled` first"));
}
#[tokio::test]
async fn self_dispatch_carries_the_same_recall_as_a_named_claim() {
let s = server();
earlier_work(
&s,
"Rewrite the renderer",
&["src/tui/**"],
"the renderer redraws on every poll",
);
let mine = seed(&s, "Speed up the renderer", "");
s.with_db(|db| {
db.scopes().declare(
mine,
&["src/tui/view.rs".into()],
"cli",
crate::repo::OnConflict::Report,
)
})
.unwrap();
let out = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(out["claimed"]["claimed"], mine);
assert_eq!(
out["claimed"]["recalled"][0]["content"],
"the renderer redraws on every poll"
);
}
#[tokio::test]
async fn a_claim_with_nothing_to_recall_says_nothing() {
let s = server();
let seq = seed(&s, "Xyzzy", "");
let out = parse(s.task_claim(Parameters(just(seq))).await);
assert!(out.get("recalled").is_none(), "{out}");
assert!(out["reminder"]
.as_str()
.unwrap()
.starts_with("call task_update"));
}
#[tokio::test]
async fn task_get_shows_the_same_recall_without_claiming_anything() {
let s = server();
earlier_work(
&s,
"Port the config loader",
&["src/config.rs"],
"env vars beat the config file",
);
let mine = seed(&s, "Audit the loader", "");
s.with_db(|db| {
db.scopes().declare(
mine,
&["src/config.rs".into()],
"cli",
crate::repo::OnConflict::Report,
)
})
.unwrap();
let out = parse(s.task_get(Parameters(SeqArgs { seq: mine })).await);
assert_eq!(
out["recalled"][0]["content"],
"env vars beat the config file"
);
assert_eq!(out["status"], "open");
}
#[tokio::test]
async fn recall_can_be_switched_off_in_the_configuration() {
let s = HirdMcp::new(
Db::open_in_memory().unwrap(),
AgentId::new("claude-code", "af31"),
PROJECT.to_string(),
Config {
recall_limit: 0,
..Config::default()
},
);
earlier_work(&s, "Port the loader", &["src/config.rs"], "a fact");
let mine = seed(&s, "Audit the loader", "");
let out = parse(
s.task_claim(Parameters(claim_with(mine, &["src/config.rs"])))
.await,
);
assert!(out.get("recalled").is_none(), "{out}");
}
#[tokio::test]
async fn scope_is_holder_only_and_answers_with_advice() {
let s = server();
let seq = seed(&s, "t", "");
let err = s
.task_scope(Parameters(TaskScopeArgs {
seq,
paths: vec!["src/lib.rs".into()],
}))
.await
.unwrap_err();
assert!(err.contains("must claim it first"), "{err}");
s.task_claim(Parameters(just(seq))).await.unwrap();
let out = parse(
s.task_scope(Parameters(TaskScopeArgs {
seq,
paths: vec!["./src/lib.rs".into(), "tests/".into()],
}))
.await,
);
assert_eq!(out["paths"], serde_json::json!(["src/lib.rs", "tests/**"]));
assert!(out.get("overlaps").is_none());
assert!(out["advice"].as_str().unwrap().contains("go ahead"));
}
#[tokio::test]
async fn splitting_files_the_pieces_and_hands_the_parent_back() {
let s = server();
let seq = seed(&s, "port the loader", "big job");
s.task_claim(Parameters(just(seq))).await.unwrap();
let out = parse(
s.task_split(Parameters(TaskSplitArgs {
seq,
sequential: None,
subtasks: vec![
SubtaskArgs {
title: "extract the parser".into(),
body: Some("start with the lexer".into()),
priority: None,
paths: Some(vec!["src/parse.rs".into()]),
requires: None,
},
SubtaskArgs {
title: "port the tests".into(),
body: None,
priority: Some(3),
paths: None,
requires: None,
},
],
}))
.await,
);
assert_eq!(out["seq"], seq);
assert_eq!(out["status"], "open", "the parent goes back in the pool");
assert_eq!(out["subtasks"][0]["title"], "extract the parser");
assert_eq!(out["subtasks"][1]["seq"], 3);
assert!(out["subtasks"][0].get("waiting_for").is_none());
let err = s.task_claim(Parameters(just(seq))).await.unwrap_err();
assert!(err.contains("is blocked by task 2"), "{err}");
let handed = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(handed["claimed"]["claimed"], 3, "priority 3 goes first");
}
#[tokio::test]
async fn a_sequential_split_queues_the_pieces_behind_each_other() {
let s = server();
let seq = seed(&s, "migrate", "");
s.task_claim(Parameters(just(seq))).await.unwrap();
let out = parse(
s.task_split(Parameters(TaskSplitArgs {
seq,
sequential: Some(true),
subtasks: vec![
SubtaskArgs {
title: "write the migration".into(),
body: None,
priority: None,
paths: None,
requires: None,
},
SubtaskArgs {
title: "backfill".into(),
body: None,
priority: None,
paths: None,
requires: None,
},
],
}))
.await,
);
assert_eq!(out["subtasks"][1]["waiting_for"], serde_json::json!([2]));
let handed = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(handed["claimed"]["claimed"], 2);
let nothing = parse(s.task_next(Parameters(next_args())).await);
assert!(nothing.get("claimed").is_none());
assert_eq!(nothing["blocked"], serde_json::json!([1, 3]));
}
#[tokio::test]
async fn splitting_is_holder_only_and_needs_at_least_one_piece() {
let s = server();
let seq = seed(&s, "t", "");
let err = s
.task_split(Parameters(TaskSplitArgs {
seq,
sequential: None,
subtasks: vec![SubtaskArgs {
title: "a piece".into(),
body: None,
priority: None,
paths: None,
requires: None,
}],
}))
.await
.unwrap_err();
assert!(err.contains("must claim it first"), "{err}");
s.task_claim(Parameters(just(seq))).await.unwrap();
let err = s
.task_split(Parameters(TaskSplitArgs {
seq,
sequential: None,
subtasks: vec![],
}))
.await
.unwrap_err();
assert!(err.contains("at least one subtask"), "{err}");
}
#[tokio::test]
async fn releasing_puts_a_task_back_without_marking_it_failed() {
let s = server();
let seq = seed(&s, "t", "");
s.task_claim(Parameters(just(seq))).await.unwrap();
let out = parse(
s.task_release(Parameters(TaskReleaseArgs {
seq,
reason: "needs credentials I do not have".into(),
question: None,
}))
.await,
);
assert_eq!(out["status"], "open");
assert_eq!(out["result"], "needs credentials I do not have");
let handed = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(handed["claimed"]["claimed"], seq);
}
#[tokio::test]
async fn a_question_parks_work_until_its_answer_is_handed_to_the_next_claim() {
let s = server();
let seq = seed(&s, "choose compatibility", "implement after the decision");
s.task_claim(Parameters(just(seq))).await.unwrap();
let released = parse(
s.task_release(Parameters(TaskReleaseArgs {
seq,
reason: "the implementation point is isolated".into(),
question: Some("Preserve the legacy config format?".into()),
}))
.await,
);
assert_eq!(
released["awaiting_answer"],
"Preserve the legacy config format?"
);
let refused = s.task_claim(Parameters(just(seq))).await.unwrap_err();
assert!(refused.contains("awaiting an answer"), "{refused}");
let idle = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(idle["awaiting_answer"][0]["seq"], seq);
assert!(idle["idle"].as_str().unwrap().contains("human answer"));
let detail = parse(s.task_get(Parameters(SeqArgs { seq })).await);
assert_eq!(
detail["questions"][0]["question"],
"Preserve the legacy config format?"
);
assert!(detail["questions"][0].get("answer").is_none());
s.with_db(|db| db.questions().answer(seq, "cli", "No; migrate it."))
.unwrap();
let claimed = parse(s.task_claim(Parameters(just(seq))).await);
assert_eq!(claimed["questions"][0]["answer"], "No; migrate it.");
assert!(claimed["reminder"]
.as_str()
.unwrap()
.contains("`questions`"));
}
#[tokio::test]
async fn a_recess_answers_task_next_with_standing_by_not_idle() {
let s = server();
let seq = seed(&s, "ready work", "");
s.with_db(|db| db.recesses().call(PROJECT, "rebasing main", "cli"))
.unwrap();
let out = parse(s.task_next(Parameters(next_args())).await);
assert!(out.get("claimed").is_none());
let recess = out["recess"].as_str().unwrap();
assert!(recess.contains("rebasing main"), "{recess}");
let idle = out["idle"].as_str().unwrap();
assert!(idle.starts_with("in recess, not idle"), "{idle}");
assert!(idle.contains("Stand by"), "{idle}");
assert!(
out.get("blocked").is_none() && out.get("deferred").is_none(),
"a recess enumerates nothing: {out}"
);
let refused = s.task_claim(Parameters(just(seq))).await.unwrap_err();
assert!(refused.contains("in recess"), "{refused}");
assert!(refused.contains("rebasing main"), "{refused}");
s.with_db(|db| db.recesses().lift(PROJECT)).unwrap();
let handed = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(handed["claimed"]["claimed"], seq);
}
#[tokio::test]
async fn a_task_both_blocked_and_parked_is_reported_as_both() {
let s = server();
let groundwork = seed(&s, "land the migration", "");
let seq = seed(&s, "choose compatibility", "");
s.task_claim(Parameters(just(seq))).await.unwrap();
s.task_release(Parameters(TaskReleaseArgs {
seq,
reason: "the implementation point is isolated".into(),
question: Some("Preserve the legacy config format?".into()),
}))
.await
.unwrap();
s.with_db(|db| db.deps().add(seq, groundwork, "cli"))
.unwrap();
s.with_db(|db| {
db.tasks().claim(
groundwork,
"codex:other",
std::time::Duration::from_secs(900),
)
})
.unwrap();
let idle = parse(s.task_next(Parameters(next_args())).await);
assert_eq!(idle["awaiting_answer"][0]["seq"], seq);
let reason = idle["idle"].as_str().unwrap();
assert!(reason.contains("awaiting a human answer"), "{reason}");
assert!(
!reason.contains("No agent can make progress"),
"the answer is not the only thing in the way: {reason}"
);
}
#[tokio::test]
async fn task_get_shows_dependencies_scope_and_overlaps() {
let s = server();
let gate = seed(&s, "gate", "");
let held = seed(&s, "held", "");
let mine = seed(&s, "mine", "");
s.with_db(|db| {
db.deps().add(mine, gate, "cli")?;
db.scopes().declare(
held,
&["src/**".into()],
"cli",
crate::repo::OnConflict::Report,
)?;
db.scopes().declare(
mine,
&["src/db.rs".into()],
"cli",
crate::repo::OnConflict::Report,
)?;
db.tasks()
.claim(held, "codex:9f2c", Config::default().lease_ttl())
})
.unwrap();
let out = parse(s.task_get(Parameters(SeqArgs { seq: mine })).await);
assert_eq!(out["waiting_for"][0]["seq"], gate);
assert_eq!(out["waiting_for"][0]["status"], "open");
assert_eq!(out["paths"], serde_json::json!(["src/db.rs"]));
assert!(out["overlaps"][0].as_str().unwrap().contains("codex:9f2c"));
let gate_view = parse(s.task_get(Parameters(SeqArgs { seq: gate })).await);
assert_eq!(gate_view["blocks"], serde_json::json!([mine]));
}
#[tokio::test]
async fn task_list_marks_the_tasks_nobody_can_start_yet() {
let s = server();
let gate = seed(&s, "gate", "");
let waiting = seed(&s, "waiting", "");
s.with_db(|db| db.deps().add(waiting, gate, "cli")).unwrap();
let out = parse(
s.task_list(Parameters(TaskListArgs {
status: None,
all_projects: None,
}))
.await,
);
let rows = out["tasks"].as_array().unwrap();
let blocked = rows.iter().find(|r| r["seq"] == waiting).unwrap();
assert_eq!(blocked["blocked_by"], serde_json::json!([gate]));
let ready = rows.iter().find(|r| r["seq"] == gate).unwrap();
assert!(ready.get("blocked_by").is_none());
}
#[test]
fn the_instructions_state_the_queue_rules() {
let text = server().instructions();
for expected in [
"seq",
"task_claim",
"BEFORE",
"task_update",
"task_complete",
"mem_store",
"mem_search",
"all_projects",
PROJECT,
] {
assert!(text.contains(expected), "instructions omit {expected:?}");
}
assert!(text.contains("15 minutes"), "{text}");
assert!(text.contains("every 7 minutes"), "{text}");
}
#[test]
fn server_info_advertises_tools_and_carries_the_instructions() {
let s = server();
let info = s.get_info();
assert!(info.capabilities.tools.is_some());
assert_eq!(info.server_info.name, "hird");
assert_eq!(
info.instructions.as_deref(),
Some(s.instructions().as_str())
);
}
#[test]
fn exactly_the_designed_tools_are_exposed() {
let mut names: Vec<String> = HirdMcp::tool_router()
.list_all()
.into_iter()
.map(|t| t.name.to_string())
.collect();
names.sort();
assert_eq!(
names,
vec![
"mem_search",
"mem_store",
"task_claim",
"task_complete",
"task_fail",
"task_get",
"task_list",
"task_next",
"task_release",
"task_scope",
"task_split",
"task_update",
]
);
}
#[test]
fn every_tool_has_a_description_and_an_input_schema() {
for tool in HirdMcp::tool_router().list_all() {
let name = &tool.name;
assert!(
tool.description.as_ref().is_some_and(|d| d.len() > 20),
"{name} needs a real description"
);
assert!(
tool.input_schema.contains_key("properties")
|| tool.input_schema.contains_key("type"),
"{name} has no input schema"
);
}
}
}