use std::fmt;
use std::str::FromStr;
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
pub fn fmt_ts(at: DateTime<Utc>) -> String {
at.to_rfc3339_opts(SecondsFormat::Millis, true)
}
pub fn now_ts() -> String {
fmt_ts(Utc::now())
}
pub fn parse_ts(raw: &str) -> Option<DateTime<Utc>> {
DateTime::parse_from_rfc3339(raw)
.ok()
.map(|dt| dt.with_timezone(&Utc))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Open,
Claimed,
InProgress,
Done,
Failed,
Cancelled,
}
impl Status {
pub const ALL: [Status; 6] = [
Status::Open,
Status::Claimed,
Status::InProgress,
Status::Done,
Status::Failed,
Status::Cancelled,
];
pub fn as_str(self) -> &'static str {
match self {
Status::Open => "open",
Status::Claimed => "claimed",
Status::InProgress => "in_progress",
Status::Done => "done",
Status::Failed => "failed",
Status::Cancelled => "cancelled",
}
}
pub fn is_terminal(self) -> bool {
matches!(self, Status::Done | Status::Failed | Status::Cancelled)
}
pub fn is_active(self) -> bool {
matches!(self, Status::Claimed | Status::InProgress)
}
pub fn apply(self, transition: Transition) -> Option<Status> {
use Status::*;
use Transition::*;
match (self, transition) {
(Open, Claim) => Some(Claimed),
(Claimed, Start) | (InProgress, Start) => Some(InProgress),
(Claimed | InProgress, Complete) => Some(Done),
(Claimed | InProgress, Fail) => Some(Failed),
(Claimed | InProgress, LeaseExpiry | Release) => Some(Open),
(Open | Claimed | InProgress, Cancel) => Some(Cancelled),
(Done | Failed | Cancelled, Reopen) => Some(Open),
_ => None,
}
}
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.as_str())
}
}
impl FromStr for Status {
type Err = UnknownStatus;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"open" => Ok(Status::Open),
"claimed" => Ok(Status::Claimed),
"in_progress" | "in-progress" => Ok(Status::InProgress),
"done" => Ok(Status::Done),
"failed" => Ok(Status::Failed),
"cancelled" | "canceled" => Ok(Status::Cancelled),
other => Err(UnknownStatus(other.to_string())),
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
#[error(
"unknown status {0:?} (expected one of: open, claimed, in_progress, done, failed, cancelled)"
)]
pub struct UnknownStatus(pub String);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Transition {
Claim,
Start,
Complete,
Fail,
LeaseExpiry,
Release,
Cancel,
Reopen,
}
impl Transition {
pub const ALL: [Transition; 8] = [
Transition::Claim,
Transition::Start,
Transition::Complete,
Transition::Fail,
Transition::LeaseExpiry,
Transition::Release,
Transition::Cancel,
Transition::Reopen,
];
pub fn as_str(self) -> &'static str {
match self {
Transition::Claim => "claim",
Transition::Start => "start",
Transition::Complete => "complete",
Transition::Fail => "fail",
Transition::LeaseExpiry => "lease_expiry",
Transition::Release => "release",
Transition::Cancel => "cancel",
Transition::Reopen => "reopen",
}
}
}
impl fmt::Display for Transition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EventKind {
Created,
Claimed,
Status,
Note,
LeaseRenewed,
LeaseExpired,
Released,
Asked,
Answered,
Completed,
Failed,
Cancelled,
Reopened,
DepAdded,
DepRemoved,
Scoped,
Required,
Recused,
Reviewed,
Witnessed,
GroundShifted,
Reported,
Merged,
Linked,
}
impl EventKind {
pub fn as_str(self) -> &'static str {
match self {
EventKind::Created => "created",
EventKind::Claimed => "claimed",
EventKind::Status => "status",
EventKind::Note => "note",
EventKind::LeaseRenewed => "lease_renewed",
EventKind::LeaseExpired => "lease_expired",
EventKind::Released => "released",
EventKind::Asked => "asked",
EventKind::Answered => "answered",
EventKind::Completed => "completed",
EventKind::Failed => "failed",
EventKind::Cancelled => "cancelled",
EventKind::Reopened => "reopened",
EventKind::DepAdded => "dep_added",
EventKind::DepRemoved => "dep_removed",
EventKind::Scoped => "scoped",
EventKind::Required => "required",
EventKind::Recused => "recused",
EventKind::Reviewed => "reviewed",
EventKind::Witnessed => "witnessed",
EventKind::GroundShifted => "ground_shifted",
EventKind::Reported => "reported",
EventKind::Merged => "merged",
EventKind::Linked => "linked",
}
}
}
impl fmt::Display for EventKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.as_str())
}
}
impl FromStr for EventKind {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"created" => Ok(EventKind::Created),
"claimed" => Ok(EventKind::Claimed),
"status" => Ok(EventKind::Status),
"note" => Ok(EventKind::Note),
"lease_renewed" => Ok(EventKind::LeaseRenewed),
"lease_expired" => Ok(EventKind::LeaseExpired),
"released" => Ok(EventKind::Released),
"asked" => Ok(EventKind::Asked),
"answered" => Ok(EventKind::Answered),
"completed" => Ok(EventKind::Completed),
"failed" => Ok(EventKind::Failed),
"cancelled" => Ok(EventKind::Cancelled),
"reopened" => Ok(EventKind::Reopened),
"dep_added" => Ok(EventKind::DepAdded),
"dep_removed" => Ok(EventKind::DepRemoved),
"scoped" => Ok(EventKind::Scoped),
"required" => Ok(EventKind::Required),
"recused" => Ok(EventKind::Recused),
"reviewed" => Ok(EventKind::Reviewed),
"witnessed" => Ok(EventKind::Witnessed),
"ground_shifted" => Ok(EventKind::GroundShifted),
"reported" => Ok(EventKind::Reported),
"merged" => Ok(EventKind::Merged),
"linked" => Ok(EventKind::Linked),
other => Err(format!("unknown event kind {other:?}")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Task {
pub id: String,
pub seq: i64,
pub project: String,
pub title: String,
pub body: String,
pub status: Status,
pub priority: i64,
pub claimed_by: Option<String>,
pub lease_expires_at: Option<String>,
pub result: Option<String>,
pub review: bool,
pub created_at: String,
pub updated_at: String,
}
impl Task {
pub fn lease_remaining_secs(&self, now: DateTime<Utc>) -> Option<i64> {
let expires = parse_ts(self.lease_expires_at.as_deref()?)?;
Some((expires - now).num_seconds())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskSummary {
pub seq: i64,
pub project: String,
pub title: String,
pub status: Status,
pub priority: i64,
pub claimed_by: Option<String>,
pub lease_expires_at: Option<String>,
pub updated_at: String,
pub requirements: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskEvent {
pub id: String,
pub task_id: String,
pub at: String,
pub actor: String,
pub kind: EventKind,
pub detail: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskLinks {
#[serde(skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub worktree: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pr_url: Option<String>,
pub updated_by: String,
pub at: String,
}
impl TaskLinks {
pub fn is_empty(&self) -> bool {
self.branch.is_none() && self.worktree.is_none() && self.pr_url.is_none()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Question {
pub id: String,
pub task_id: String,
pub n: i64,
pub asked_by: String,
pub question: String,
pub asked_at: String,
pub answer: Option<String>,
pub answered_by: Option<String>,
pub answered_at: Option<String>,
}
impl Question {
pub fn is_answered(&self) -> bool {
self.answer.is_some()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Clearance {
#[default]
Done,
Reviewed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Blocker {
pub seq: i64,
pub title: String,
pub status: Status,
pub pending_review: Option<i64>,
}
impl Blocker {
pub fn is_cleared(&self, clearance: Clearance) -> bool {
self.status == Status::Done
&& (clearance == Clearance::Done || self.pending_review.is_none())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathClaim {
pub task_id: String,
pub pattern: String,
pub declared_by: String,
pub at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScopedTask {
pub seq: i64,
pub title: String,
pub status: Status,
pub holder: Option<String>,
pub patterns: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Conflict {
pub pattern: String,
pub other_seq: i64,
pub other_title: String,
pub other_pattern: String,
pub other_status: Status,
pub other_holder: Option<String>,
}
impl Conflict {
pub fn describe(&self) -> String {
match &self.other_holder {
Some(holder) => format!(
"{} overlaps {} on task {} ({}), held by {holder}",
self.pattern,
self.other_pattern,
self.other_seq,
truncate_title(&self.other_title),
),
None => format!(
"{} overlaps {} on task {} ({}, {})",
self.pattern,
self.other_pattern,
self.other_seq,
truncate_title(&self.other_title),
self.other_status,
),
}
}
}
fn truncate_title(title: &str) -> String {
crate::fmt::truncate(title, 40)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ground {
pub seq: i64,
pub title: String,
pub result: Option<String>,
pub standing: GroundStanding,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GroundStanding {
Done,
Upheld,
UnderReview { review: i64 },
}
impl GroundStanding {
pub fn describe(self) -> String {
match self {
GroundStanding::Done => "done".to_string(),
GroundStanding::Upheld => "upheld".to_string(),
GroundStanding::UnderReview { review } => {
format!("under review {review}, provisional")
}
}
}
pub fn is_provisional(self) -> bool {
matches!(self, GroundStanding::UnderReview { .. })
}
}
impl Ground {
pub fn label(&self) -> String {
format!("#{} {}", self.seq, self.standing.describe())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Shifted {
pub seq: i64,
pub title: String,
pub status: Status,
pub sent_back_by: Option<i64>,
}
impl Shifted {
pub fn describe(&self) -> String {
let name = format!("task {} ({})", self.seq, truncate_title(&self.title));
match (self.sent_back_by, self.status) {
(Some(review), _) => format!(
"{name}, which this task builds on, was sent back by review {review} and \
reopened; re-read it — the findings are in its brief — before building \
further on its work"
),
(None, Status::Cancelled) => format!(
"{name}, which this task builds on, has been cancelled since this task \
was claimed"
),
(None, Status::Failed) => {
format!("{name}, which this task builds on, has failed since this task was claimed")
}
(None, _) => format!(
"{name}, which this task builds on, was reopened since this task was \
claimed and is no longer done"
),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Observed {
pub path: String,
pub kind: String,
pub hash: String,
pub first_seen: String,
pub last_seen: String,
}
impl Observed {
pub fn describe(&self) -> String {
format!("{} ({})", self.path, self.kind)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tenure {
pub n: i64,
pub holder: String,
pub began_at: String,
pub ended: String,
pub ended_at: String,
pub changes: Vec<Observed>,
}
impl Tenure {
fn who(&self) -> &str {
if self.holder.is_empty() {
"an earlier holder"
} else {
&self.holder
}
}
fn ending(&self) -> &'static str {
match self.ended.as_str() {
"completed" => "completed it",
"failed" => "failed it",
"released" => "handed it back unfinished",
"lease_expired" => "went quiet until the lease expired",
"cancelled" => "held it when it was cancelled",
_ => "held it before this claim",
}
}
fn moved(&self) -> String {
const LISTED: usize = 6;
let mut listed: Vec<String> = self
.changes
.iter()
.take(LISTED)
.map(Observed::describe)
.collect();
if self.changes.len() > LISTED {
listed.push(format!("and {} more", self.changes.len() - LISTED));
}
listed.join(", ")
}
pub fn describe(&self, seq: i64) -> String {
if self.changes.is_empty() {
return format!(
"{} {} without the tree moving — there are no leftover edits to inherit",
self.who(),
self.ending()
);
}
format!(
"{} {}, and these files moved while they held it: {}. Whatever state they \
left is part of the tree this claim starts from — `hird diff {seq} --tenure \
{}` shows that round's changes before you build on or over them",
self.who(),
self.ending(),
self.moved(),
self.n
)
}
pub fn label(&self) -> String {
let ended = match self.ended.as_str() {
"" => "ended".to_string(),
kind => kind.replace('_', " "),
};
if self.changes.is_empty() {
format!("round {}: {} — {ended}; read-only", self.n, self.who())
} else {
format!(
"round {}: {} — {ended}; saw {}",
self.n,
self.who(),
self.moved()
)
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Footprint {
#[default]
Unwatched,
ReadOnly,
Modified {
paths: usize,
shared: bool,
},
}
impl Footprint {
pub fn is_watched(self) -> bool {
!matches!(self, Footprint::Unwatched)
}
pub fn label(self, live: bool) -> Option<String> {
match self {
Footprint::Unwatched => None,
Footprint::ReadOnly if live => Some("read-only so far".to_string()),
Footprint::ReadOnly => Some("read-only".to_string()),
Footprint::Modified { paths, .. } => Some(format!(
"modified {paths} file{}",
if paths == 1 { "" } else { "s" }
)),
}
}
pub fn badge(self) -> Option<String> {
match self {
Footprint::Unwatched => None,
Footprint::ReadOnly => Some("read-only".to_string()),
Footprint::Modified { paths, .. } => Some(format!("modified {paths}")),
}
}
pub fn describe(self, live: bool) -> Option<String> {
let label = self.label(live)?;
Some(match self {
Footprint::ReadOnly if live => {
format!("{label} — nothing in the working tree has moved since it was claimed")
}
Footprint::ReadOnly => {
format!("{label} — nothing in the working tree moved while it was held")
}
Footprint::Modified { shared: true, .. } => {
format!("{label}, though another agent was live in some of them")
}
_ => label,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WitnessedTask {
pub seq: i64,
pub title: String,
pub status: Status,
pub holder: Option<String>,
pub changes: Vec<Observed>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Contention {
pub path: String,
pub hash: String,
pub last_seen: String,
pub other_seq: i64,
pub other_title: String,
pub other_status: Status,
pub other_holder: Option<String>,
pub other_hash: String,
pub other_last_seen: String,
}
impl Contention {
pub fn is_stale(&self) -> bool {
self.hash != self.other_hash
}
pub fn describe(&self) -> String {
let who = match &self.other_holder {
Some(holder) => format!(
"task {} ({}), held by {holder}",
self.other_seq,
truncate_title(&self.other_title)
),
None => format!(
"task {} ({}, {})",
self.other_seq,
truncate_title(&self.other_title),
self.other_status
),
};
if self.last_seen > self.other_last_seen {
format!(
"{} changed under {who}, and again on your side afterwards — check you did \
not write over their edit",
self.path
)
} else {
format!(
"{} changed under {who} at {}, at or after the version hird last confirmed \
for you — re-read it before you write, or your edit will discard theirs",
self.path,
short_time(&self.other_last_seen),
)
}
}
}
fn short_time(ts: &str) -> String {
match parse_ts(ts) {
Some(dt) => dt.format("%H:%M UTC").to_string(),
None => ts.to_string(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attempt {
pub n: i64,
pub holder: String,
#[serde(skip_serializing_if = "String::is_empty", default)]
pub model: String,
pub outcome: String,
pub source: String,
pub actor: String,
pub output: String,
pub at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Recusal {
pub from_seq: i64,
pub from_title: String,
pub reason: String,
pub worker: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub earlier: Vec<String>,
}
impl Recusal {
pub fn holders(&self) -> impl Iterator<Item = &str> {
self.worker
.as_deref()
.into_iter()
.chain(self.earlier.iter().map(String::as_str))
}
pub fn describe(&self) -> String {
let what = format!(
"task {} ({})",
self.from_seq,
crate::fmt::truncate(&self.from_title, 40)
);
let why = if self.reason.is_empty() {
String::new()
} else {
format!(" — {}", self.reason)
};
match &self.worker {
Some(worker) => format!(
"not whoever worked {what}: that was {worker}, so this needs another harness{why}"
),
None => format!("not whoever works {what}; nobody has yet{why}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Recess {
pub project: String,
pub reason: String,
pub actor: String,
pub at: String,
}
impl Recess {
pub fn describe(&self) -> String {
format!(
"the human stood this queue down{} — nothing is handed out until \
`hird resume` lifts it, though work already claimed continues",
self.quoted_reason()
)
}
pub fn quoted_reason(&self) -> String {
if self.reason.is_empty() {
String::new()
} else {
format!(" ({:?})", self.reason)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
Upheld,
SentBack,
}
impl Verdict {
pub fn as_str(self) -> &'static str {
match self {
Verdict::Upheld => "upheld",
Verdict::SentBack => "sent_back",
}
}
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.as_str())
}
}
impl FromStr for Verdict {
type Err = UnknownVerdict;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim() {
"upheld" | "uphold" | "approve" | "approved" => Ok(Verdict::Upheld),
"sent_back" | "sent-back" | "send_back" | "send-back" | "needs_work" | "needs-work" => {
Ok(Verdict::SentBack)
}
other => Err(UnknownVerdict(other.to_string())),
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
#[error(
"unknown verdict {0:?}: say \"upheld\" if the work stands, or \"sent_back\" to return it \
to the pool carrying your findings"
)]
pub struct UnknownVerdict(pub String);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerdictRecord {
pub review_seq: i64,
pub task_seq: i64,
pub verdict: Verdict,
pub worker: String,
pub reviewer: String,
pub at: String,
}
impl VerdictRecord {
pub fn describe(&self) -> String {
match self.verdict {
Verdict::Upheld => format!(
"upheld by {} (review {})",
crate::identity::actor_harness(&self.reviewer),
self.review_seq
),
Verdict::SentBack => format!(
"sent back by {} (review {})",
crate::identity::actor_harness(&self.reviewer),
self.review_seq
),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordRow {
pub who: String,
pub judged: i64,
pub upheld: i64,
pub sent_back: i64,
pub tasks_judged: i64,
pub first_pass: i64,
pub upheld_given: i64,
pub sent_back_given: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Anchor {
pub path: String,
pub hash: String,
pub at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Shift {
pub path: String,
pub gone: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "standing")]
pub enum Standing {
Unanchored,
Firm { paths: Vec<String> },
Shaky {
moved: Vec<Shift>,
firm: Vec<String>,
},
Orphaned { paths: Vec<String> },
}
impl Standing {
pub fn as_str(&self) -> &'static str {
match self {
Standing::Unanchored => "unanchored",
Standing::Firm { .. } => "firm",
Standing::Shaky { .. } => "shaky",
Standing::Orphaned { .. } => "orphaned",
}
}
pub fn paths(&self) -> Vec<&str> {
match self {
Standing::Unanchored => Vec::new(),
Standing::Firm { paths } | Standing::Orphaned { paths } => {
paths.iter().map(String::as_str).collect()
}
Standing::Shaky { moved, firm } => moved
.iter()
.map(|s| s.path.as_str())
.chain(firm.iter().map(String::as_str))
.collect(),
}
}
pub fn needs_checking(&self) -> bool {
matches!(self, Standing::Shaky { .. } | Standing::Orphaned { .. })
}
pub fn rank(&self) -> u8 {
match self {
Standing::Firm { .. } => 0,
Standing::Unanchored => 1,
Standing::Shaky { .. } => 2,
Standing::Orphaned { .. } => 3,
}
}
pub fn describe(&self) -> Option<String> {
match self {
Standing::Unanchored => None,
Standing::Firm { paths } => Some(match paths.as_slice() {
[one] => format!("{one} is unchanged since this was recorded"),
many => format!(
"all {} files this was recorded against are unchanged",
many.len()
),
}),
Standing::Shaky { moved, .. } => Some(format!(
"{} since this was recorded — re-read before relying on it",
describe_shifts(moved)
)),
Standing::Orphaned { paths } => Some(match paths.as_slice() {
[one] => {
format!("{one} no longer exists — this was recorded about a file that has gone")
}
many => format!(
"all {} files this was recorded against have been deleted",
many.len()
),
}),
}
}
}
fn describe_shifts(moved: &[Shift]) -> String {
let verb = |s: &Shift| if s.gone { "is gone" } else { "has changed" };
match moved {
[] => "nothing has changed".to_string(),
[one] => format!("{} {}", one.path, verb(one)),
[first, rest @ ..] => {
let others = rest.len();
let tail = match (others == 1, rest.iter().all(|s| s.gone)) {
(true, true) => "is gone",
(true, false) => "has changed",
(false, true) => "are gone",
(false, false) => "have changed",
};
format!(
"{} {} and {others} other{} {tail}",
first.path,
verb(first),
if others == 1 { "" } else { "s" },
)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Voices {
pub actors: Vec<String>,
}
impl Voices {
pub fn harnesses(&self) -> Vec<&str> {
let mut out: Vec<&str> = Vec::new();
for actor in &self.actors {
let harness = crate::identity::actor_harness(actor);
if !out.contains(&harness) {
out.push(harness);
}
}
out
}
pub fn describe(&self) -> Option<String> {
let [_first, others @ ..] = self.actors.as_slice() else {
return None;
};
if others.is_empty() {
return None;
}
const NAMED: usize = 3;
let shown: Vec<&str> = others.iter().take(NAMED).map(String::as_str).collect();
let mut sentence = format!("also stated by {}", shown.join(", "));
if others.len() > shown.len() {
sentence.push_str(&format!(" and {} more", others.len() - shown.len()));
}
let harnesses = self.harnesses().len();
if harnesses > 1 {
sentence.push_str(&format!(", independently across {harnesses} harnesses"));
}
Some(sentence)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Assertion {
pub id: String,
pub project: String,
pub content: String,
pub tags: String,
pub actor: String,
pub task_id: Option<String>,
pub superseded_by: Option<String>,
pub created_at: String,
}
impl Assertion {
pub fn tag_list(&self) -> Vec<&str> {
self.tags
.split(',')
.map(str::trim)
.filter(|t| !t.is_empty())
.collect()
}
}
pub fn normalize_tags(raw: &str) -> String {
raw.split(',')
.map(str::trim)
.filter(|t| !t.is_empty())
.collect::<Vec<_>>()
.join(",")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_machine_has_no_edges_outside_the_diagram() {
let allowed: &[(Status, Transition, Status)] = &[
(Status::Open, Transition::Claim, Status::Claimed),
(Status::Claimed, Transition::Start, Status::InProgress),
(Status::InProgress, Transition::Start, Status::InProgress),
(Status::Claimed, Transition::Complete, Status::Done),
(Status::InProgress, Transition::Complete, Status::Done),
(Status::Claimed, Transition::Fail, Status::Failed),
(Status::InProgress, Transition::Fail, Status::Failed),
(Status::Claimed, Transition::LeaseExpiry, Status::Open),
(Status::InProgress, Transition::LeaseExpiry, Status::Open),
(Status::Claimed, Transition::Release, Status::Open),
(Status::InProgress, Transition::Release, Status::Open),
(Status::Open, Transition::Cancel, Status::Cancelled),
(Status::Claimed, Transition::Cancel, Status::Cancelled),
(Status::InProgress, Transition::Cancel, Status::Cancelled),
(Status::Done, Transition::Reopen, Status::Open),
(Status::Failed, Transition::Reopen, Status::Open),
(Status::Cancelled, Transition::Reopen, Status::Open),
];
for from in Status::ALL {
for transition in Transition::ALL {
let expected = allowed
.iter()
.find(|(f, t, _)| *f == from && *t == transition)
.map(|(_, _, to)| *to);
assert_eq!(
from.apply(transition),
expected,
"edge {from} --{transition}--> mismatch"
);
}
}
}
#[test]
fn every_status_is_reachable_from_open() {
let mut seen = std::collections::BTreeSet::from([Status::Open]);
loop {
let next: Vec<Status> = seen
.iter()
.flat_map(|s| Transition::ALL.iter().filter_map(|t| s.apply(*t)))
.collect();
let before = seen.len();
seen.extend(next);
if seen.len() == before {
break;
}
}
assert_eq!(seen, Status::ALL.into_iter().collect());
}
#[test]
fn terminal_statuses_only_leave_via_reopen() {
for status in Status::ALL.into_iter().filter(|s| s.is_terminal()) {
for transition in Transition::ALL {
let reached = status.apply(transition);
if transition == Transition::Reopen {
assert_eq!(reached, Some(Status::Open));
} else {
assert_eq!(reached, None, "{status} escaped via {transition}");
}
}
}
}
#[test]
fn status_round_trips_through_its_string_form() {
for status in Status::ALL {
assert_eq!(status.as_str().parse::<Status>().unwrap(), status);
}
}
#[test]
fn timestamps_sort_lexicographically() {
let early = fmt_ts(DateTime::from_timestamp(1_700_000_000, 0).unwrap());
let late = fmt_ts(DateTime::from_timestamp(1_800_000_000, 0).unwrap());
assert!(early < late);
assert_eq!(early.len(), late.len());
assert_eq!(parse_ts(&early).unwrap().timestamp(), 1_700_000_000);
}
#[test]
fn a_shaky_standing_names_the_file_and_stops_short_of_a_verdict() {
let one = Standing::Shaky {
moved: vec![Shift {
path: "src/config.rs".into(),
gone: false,
}],
firm: vec![],
};
assert_eq!(
one.describe().unwrap(),
"src/config.rs has changed since this was recorded — re-read before relying on it"
);
for word in ["wrong", "false", "stale", "invalid"] {
assert!(!one.describe().unwrap().contains(word), "{word}");
}
let several = Standing::Shaky {
moved: vec![
Shift {
path: "src/a.rs".into(),
gone: true,
},
Shift {
path: "src/b.rs".into(),
gone: false,
},
],
firm: vec!["src/c.rs".into()],
};
assert!(
several
.describe()
.unwrap()
.starts_with("src/a.rs is gone and 1 other has changed"),
"{:?}",
several.describe()
);
}
#[test]
fn standings_report_every_path_they_were_decided_from() {
let shaky = Standing::Shaky {
moved: vec![Shift {
path: "a".into(),
gone: false,
}],
firm: vec!["b".into()],
};
assert_eq!(shaky.paths(), vec!["a", "b"]);
assert!(Standing::Unanchored.paths().is_empty());
assert_eq!(
Standing::Firm {
paths: vec!["a".into()]
}
.paths(),
vec!["a"]
);
}
#[test]
fn corroboration_is_only_worth_a_sentence_when_it_crosses_agents() {
let alone = Voices {
actors: vec!["codex:9f2c".into()],
};
assert!(alone.describe().is_none());
let same_harness = Voices {
actors: vec!["codex:9f2c".into(), "codex:1a2b".into()],
};
assert_eq!(
same_harness.describe().unwrap(),
"also stated by codex:1a2b",
"two sessions of one harness are not independent confirmation"
);
assert_eq!(same_harness.harnesses(), vec!["codex"]);
let across = Voices {
actors: vec![
"codex:9f2c".into(),
"claude-code:af31".into(),
"copilot:77".into(),
],
};
assert_eq!(
across.describe().unwrap(),
"also stated by claude-code:af31, copilot:77, independently across 3 harnesses"
);
let many = Voices {
actors: (0..6).map(|i| format!("codex:{i}")).collect(),
};
let sentence = many.describe().unwrap();
assert!(sentence.contains("and 2 more"), "{sentence}");
}
#[test]
fn tags_are_normalized_to_a_compact_comma_list() {
assert_eq!(normalize_tags(" a , ,b,, c "), "a,b,c");
assert_eq!(normalize_tags(""), "");
}
#[test]
fn an_unwatched_task_makes_no_claim_either_way() {
assert_eq!(Footprint::Unwatched.label(false), None);
assert_eq!(Footprint::Unwatched.describe(false), None);
assert_eq!(Footprint::default(), Footprint::Unwatched);
assert!(!Footprint::Unwatched.is_watched());
assert!(Footprint::ReadOnly.is_watched());
}
#[test]
fn read_only_is_a_verdict_when_finished_and_a_running_total_while_held() {
assert_eq!(Footprint::ReadOnly.label(false).unwrap(), "read-only");
assert_eq!(Footprint::ReadOnly.label(true).unwrap(), "read-only so far");
assert!(Footprint::ReadOnly
.describe(false)
.unwrap()
.contains("while it was held"));
assert!(Footprint::ReadOnly
.describe(true)
.unwrap()
.contains("since it was claimed"));
}
#[test]
fn a_shared_file_stops_a_count_from_speaking_for_one_agent() {
let alone = Footprint::Modified {
paths: 1,
shared: false,
};
assert_eq!(alone.label(false).unwrap(), "modified 1 file");
assert_eq!(alone.describe(false).unwrap(), "modified 1 file");
let shared = Footprint::Modified {
paths: 3,
shared: true,
};
assert_eq!(shared.label(true).unwrap(), "modified 3 files");
let sentence = shared.describe(true).unwrap();
assert!(sentence.starts_with("modified 3 files,"), "{sentence}");
assert!(sentence.contains("another agent"), "{sentence}");
}
}