From d620918cbc0ac908c3a43c737fe730425ba386cb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 3 Nov 2026 05:19:45 +0100 Subject: [PATCH] wear-facts: a first line shows the specs with no report, open Soul findings and quiet campaigns her own mind holds, inside the one wear bound Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/persona.rs | 217 ++++++++++++- crates/mind-body/src/persona/tests.rs | 421 +++++++++++++++++++++++++- crates/mind-body/src/testkit.rs | 16 +- 3 files changed, 640 insertions(+), 14 deletions(-) diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 012b30e..515452a 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -54,13 +54,14 @@ use std::path::{Path, PathBuf}; use anyhow::{Result, anyhow, bail}; use chrono::{DateTime, Utc}; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; -use cultnet_rs::Selection; +use cultnet_rs::{Incoming, Selection}; use eureka_pipeline::{ Date, Label, Line, MemoryOrigin, MemorySort, OrgRepo, PipelineDocument, PipelineFollowUp, PipelineKind, PipelineMemory, PipelinePulse, PipelineRef, PipelineResolution, ResolutionOutcome, RunOperator, RunTurn, SALIENCE_MAX_PERMILLE, Short, Slug, TEMPO_VOTE_MAX_S, TEMPO_VOTE_MIN_S, URGENCY_MAX_PERMILLE, pipeline_key, }; use eureka_state::HuginnClient; -use huginn_mind::{HuginnMindResponse, PipelineAdmissionOutcome, PipelineFacts, PipelinePageItems, PipelineStatusSummary, PrAction, RepoActivity, RepoChange, RepoEvent}; +use eureka_state::hold::BLOCKING; +use huginn_mind::{HuginnMindResponse, PipelineAdmissionOutcome, PipelineFacts, PipelinePageItems, PipelineStatusSummary, PrAction, RepoActivity, RepoChange, RepoEvent, RootTouched}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use uuid::Uuid; @@ -1059,7 +1060,8 @@ impl PersonaInbox<'_, C, S> { let names = sender_names(deliveries); let goals = render_responsibilities(organs.mind, &instance, &names)?; self.repos = goals.repos.clone(); - let wear = self.first_repo_read(); + let (wear_at, wear_facts) = self.first_repo_read(&goals.open_roots); + let wear = render_wear(wear_at, &wear_facts); let senders = other_senders(self.config, deliveries); let cue = recall::Cue { senders, texts: deliveries.iter().rev().map(|delivery| delivery.text.as_str()).collect(), names: names.clone(), listed: &goals.listed, now: organs.clock.now() }; let recalled = recall::select(organs.mind, &cue)?; @@ -1114,17 +1116,19 @@ impl PersonaInbox<'_, C, S> { } } - /// The first line's read of the forge for her stewarded repos: what is open, what the forge cannot show, what others changed in the - /// last three days, as the wear section, and the cursor the later reads continue from. A read that fails leaves the cursor unset, - /// puts one line in the section saying repo facts are missing, and never fails the session; a Mind with no repos asks nothing. - fn first_repo_read(&mut self) -> String { + /// The first line's reads for her stewarded repos, as the wear section's facts and the instant they were read at: what is open, + /// what the forge cannot show, what others changed in the last three days, the cursor the later reads continue from, then what + /// her own mind holds of her machine (`record_wear_facts`). A read that fails leaves the cursor unset, puts one line in the + /// section saying repo facts are missing, and never fails the session; a Mind with no repos asks nothing, of the forge or of her + /// mind. + fn first_repo_read(&mut self, open_roots: &[String]) -> (u64, Vec) { if self.repos.is_empty() { - return String::new(); + return (0, Vec::new()); } let organs = self.organs; let now = unix_ms(organs.clock.now()); self.repo_read_due_ms = now + REPO_READ_EVERY_S * 1000; - let facts = match organs.mind.stewarded_activity(&self.repos, None) { + let mut facts = match organs.mind.stewarded_activity(&self.repos, None) { Ok(activity) => { self.repo_head = Some(activity.head); wear_facts(&activity, &self.repos, organs.mind.instance(), now) @@ -1134,7 +1138,8 @@ impl PersonaInbox<'_, C, S> { vec![WearFact::Missing] } }; - render_wear(now, &facts) + facts.extend(record_wear_facts(organs.mind, &self.repos, open_roots, now)); + (now, facts) } /// Her stewarded repos changed by someone else become one notice, at most once in `REPO_READ_EVERY_S`. A read that fails keeps the cursor @@ -1851,6 +1856,14 @@ fn render_responsibilities(mind: &dyn MindPort, instance: &Slug, names: &BTreeMa let open = Selection { descending: true, ..in_force(of_kind(PipelineKind::FollowUp)) }; let follow_ups = headers(mind, &open)?; let mut dropped = 0; + // Every open follow-up counts as open work for its campaign, whether or not the bound below lets its line show. + let mut open_roots: Vec = Vec::new(); + for follow_up in &follow_ups { + let campaign = follow_up.id.id.0.split_once(":follow_up:").map_or("", |(campaign, _)| campaign); + if !campaign.is_empty() && !open_roots.iter().any(|root| root == campaign) { + open_roots.push(campaign.to_owned()); + } + } if !follow_ups.is_empty() { out.push_str("Open follow-ups, newest first:\n"); } @@ -1901,7 +1914,7 @@ fn render_responsibilities(mind: &dyn MindPort, instance: &Slug, names: &BTreeMa if dropped_rulings > 0 { out.push_str(&format!("({dropped_rulings} more cited rulings not shown.)\n")); } - Ok(Responsibilities { text: out, listed, open: open_ids, people: open_people, repos }) + Ok(Responsibilities { text: out, listed, open: open_ids, people: open_people, repos, open_roots }) } /// The responsibilities section, and the ids of the follow-ups and rulings it lists, which recall @@ -1915,6 +1928,8 @@ struct Responsibilities { people: Vec, /// Her stewardships in force, by repo: the only map from her mind to the repos the forge is asked about. repos: Vec, + /// The campaigns that hold a follow-up in force in her mind, whether or not the bound showed its line. + open_roots: Vec, } /// Her latest runs with how each ended, one entry each, newest first. A Self @@ -2166,6 +2181,11 @@ fn repo_notice_line(activity: &RepoActivity, at_unix_ms: u64) -> Option /// The most the wear section may take of a first line. const WEAR_MAX_BYTES: usize = 1536; +/// A campaign of hers whose newest admission in her mind is this old or older, and which holds an unreported spec, an open Soul +/// finding or an open follow-up, is listed as quiet. It decides only what is listed: nothing gates or scores on it. +const STALE_AFTER_DAYS: u64 = 14; +/// The most entries one listing wear fact names; the rest are counted. +const WEAR_LIST_MAX: usize = 4; /// A fact about her machine from the forge. #[derive(Clone, Debug, PartialEq, Eq)] @@ -2174,22 +2194,45 @@ enum WearFact { Missing, /// The read stopped at a repo's page limit: the older entries there were not read. Capped(String), + /// A read of her own mind did not answer; `what` says which facts that leaves absent, not zero. + RecordsMissing(String), Awaiting { repo: String, number: u32, author: String, at: u64 }, /// A repo the anonymous read cannot see, and the repo the forge's redirect names for it when it names one. Unseen { repo: String, redirect: Option }, Changed { repo: String, words: String, at: u64 }, Yours { repo: String, number: u32, at: u64 }, + /// Specs in force with no report, on repos she stewards: `/.r` and the revision's admission, oldest first. + SpecsOnYours(Vec<(String, u64)>), + /// The same on repos she does not steward: how many, and the oldest admission. + SpecsElsewhere { count: usize, oldest: u64 }, + /// Open Soul findings in her mind, by campaign of her slice, largest first. + SoulFindings(Vec), + /// Campaigns of her slice with open work and no admission in her mind for `STALE_AFTER_DAYS`, by newest admission, oldest first. + QuietCampaigns(Vec<(String, u64)>), +} + +/// One campaign's open Soul findings in her mind: how many, how many block, and the oldest admission. +#[derive(Clone, Debug, PartialEq, Eq)] +struct FindingRow { + campaign: String, + open: usize, + blocking: usize, + oldest: u64, } impl WearFact { /// The priority order a full section drops from the end of. fn rank(&self) -> u8 { match self { - Self::Missing | Self::Capped(_) => 0, + Self::Missing | Self::RecordsMissing(_) | Self::Capped(_) => 0, Self::Awaiting { .. } => 1, Self::Unseen { .. } => 2, Self::Changed { .. } => 3, Self::Yours { .. } => 4, + Self::SpecsOnYours(_) => 5, + Self::SpecsElsewhere { .. } => 6, + Self::SoulFindings(_) => 7, + Self::QuietCampaigns(_) => 8, } } } @@ -2232,6 +2275,133 @@ fn wear_facts(activity: &RepoActivity, repos: &[OrgRepo], instance: &Slug, now_m facts } +/// The first `WEAR_LIST_MAX` entries joined by `sep`, then what `more` says of the rest, given how many are left and where they begin. +fn listed(entries: Vec, sep: &str, more: impl Fn(usize, usize) -> String) -> String { + let left = entries.len().saturating_sub(WEAR_LIST_MAX); + let mut text = entries.into_iter().take(WEAR_LIST_MAX).collect::>().join(sep); + if left > 0 { + text.push_str(sep); + text.push_str(&more(left, WEAR_LIST_MAX)); + } + text +} + +/// A spec in force with no report: its campaign and cut as one label, its repo, and the revision's admission. +struct UnreportedSpec { + label: String, + campaign: String, + repo: String, + at: u64, +} + +/// An instant of the mind's own records, in unix milliseconds; none when it is not one, so a record that cannot be dated makes its +/// read missing and never age 0. +fn instant_ms(text: &str) -> Option { + u64::try_from(DateTime::parse_from_rfc3339(text).ok()?.timestamp_millis()).ok() +} + +/// The campaign (the root of the id) a record of her mind sits under, as a plain token. +fn root_label(id: &PipelineRef) -> String { + plain(id.id.0.split(':').next().unwrap_or("")) +} + +/// Her slice: the roots whose repos in force meet hers (compared by identity, the forge's spelling being case-blind), each with its +/// newest admission. None when one cannot be dated. +fn slice_of(roots: &[RootTouched], hers: &[String]) -> Option> { + roots + .iter() + .filter(|root| root.repos.iter().any(|repo| hers.contains(&repo.identity()))) + .map(|root| Some((root.root.0.clone(), instant_ms(&root.admitted_at)?))) + .collect() +} + +/// Every spec in force whose cut has no report, from every page. +fn unreported_specs(mind: &dyn MindPort) -> Result> { + let selection = Selection { cited: Some(Incoming { role: "cut_spec".into(), exists: false }), ..in_force(of_kind(PipelineKind::CutSpec)) }; + let mut specs = Vec::new(); + for found in headers(mind, &selection)? { + let PipelineFacts::CutSpec { cut, revision, repo, .. } = &found.facts else { continue }; + let at = instant_ms(&found.admission.admitted_at).ok_or_else(|| anyhow!("a spec's admission has no instant"))?; + let campaign = root_label(&found.id); + specs.push(UnreportedSpec { label: format!("{campaign}/{}.r{revision}", plain(&cut.0)), campaign, repo: repo.identity(), at }); + } + Ok(specs) +} + +/// The Soul findings in force under the roots of her slice, counted by campaign, largest first, from every page. +fn open_soul_findings(mind: &dyn MindPort, slice: &[(String, u64)]) -> Result> { + let roots: Vec<&str> = slice.iter().map(|(root, _)| root.as_str()).collect(); + let selection = any_of(any_of(in_force(of_kind(PipelineKind::Finding)), "faculty", &["Soul"]), "root", &roots); + let mut rows: BTreeMap = BTreeMap::new(); + for found in headers(mind, &selection)? { + let PipelineFacts::Finding { severity, .. } = &found.facts else { continue }; + let at = instant_ms(&found.admission.admitted_at).ok_or_else(|| anyhow!("a finding's admission has no instant"))?; + let campaign = root_label(&found.id); + let row = rows.entry(campaign.clone()).or_insert(FindingRow { campaign, open: 0, blocking: 0, oldest: at }); + row.open += 1; + row.blocking += usize::from(BLOCKING.contains(&format!("{severity:?}").as_str())); + row.oldest = row.oldest.min(at); + } + let mut rows: Vec = rows.into_values().collect(); + rows.sort_by(|a, b| b.open.cmp(&a.open).then_with(|| a.campaign.cmp(&b.campaign))); + Ok(rows) +} + +/// The facts her own mind holds about her machine, derived at the first line and written nowhere: her unreported specs (those on +/// her repos named, the rest counted), the open Soul findings of her slice, and the campaigns of her slice that have gone quiet. +/// Each read walks every page. A read that fails says so in a fact of its own, and so does every fact that needed it; a quiet +/// campaign is listed only when all three reads answered. +fn record_wear_facts(mind: &dyn MindPort, repos: &[OrgRepo], open_roots: &[String], now_ms: u64) -> Vec { + let hers: Vec = repos.iter().map(OrgRepo::identity).collect(); + let slice = mind.roots_touched().ok().and_then(|roots| slice_of(&roots, &hers)); + let specs = unreported_specs(mind).ok(); + let findings = match &slice { + None => None, + Some(slice) if slice.is_empty() => Some(Vec::new()), + Some(slice) => open_soul_findings(mind, slice).ok(), + }; + let mut facts = Vec::new(); + let missing = |what: &str| WearFact::RecordsMissing(what.to_owned()); + if slice.is_none() { + facts.push(missing("the campaigns on your repos could not be read, so open Soul findings and quiet campaigns are absent")); + } + if specs.is_none() { + facts.push(missing("specs with no report could not be read, so they and quiet campaigns are absent")); + } + if slice.is_some() && findings.is_none() { + facts.push(missing("open Soul findings could not be read, so they and quiet campaigns are absent")); + } + if let Some(specs) = &specs { + let (mut mine, elsewhere): (Vec<&UnreportedSpec>, Vec<&UnreportedSpec>) = specs.iter().partition(|spec| hers.contains(&spec.repo)); + mine.sort_by_key(|spec| spec.at); + if !mine.is_empty() { + facts.push(WearFact::SpecsOnYours(mine.iter().map(|spec| (spec.label.clone(), spec.at)).collect())); + } + if let Some(oldest) = elsewhere.iter().map(|spec| spec.at).min() { + facts.push(WearFact::SpecsElsewhere { count: elsewhere.len(), oldest }); + } + } + if let Some(rows) = findings.as_ref().filter(|rows| !rows.is_empty()) { + facts.push(WearFact::SoulFindings(rows.clone())); + } + if let (Some(slice), Some(specs), Some(findings)) = (&slice, &specs, &findings) { + let mut quiet: Vec<(String, u64)> = slice + .iter() + .filter(|(root, newest)| { + let campaign = plain(root); + let open = specs.iter().any(|spec| spec.campaign == campaign) || findings.iter().any(|row| row.campaign == campaign) || open_roots.contains(root); + open && now_ms.saturating_sub(*newest) >= STALE_AFTER_DAYS * 86_400_000 + }) + .map(|(root, newest)| (plain(root), *newest)) + .collect(); + quiet.sort_by_key(|(_, newest)| *newest); + if !quiet.is_empty() { + facts.push(WearFact::QuietCampaigns(quiet)); + } + } + facts +} + /// `(N h)` under a day, `(N d)` from a day on. fn age_text(now_ms: u64, at_ms: u64) -> String { let hours = now_ms.saturating_sub(at_ms) / 3_600_000; @@ -2257,6 +2427,29 @@ fn render_wear(now_ms: u64, facts: &[WearFact]) -> String { WearFact::Unseen { repo, redirect: Some(to) } => format!("- a repo the forge read cannot see: {repo} (the forge redirects it to {to})\n"), WearFact::Changed { repo, words, at } => format!("- changed by others: {repo}: {words} {}\n", age_text(now_ms, *at)), WearFact::Yours { repo, number, at } => format!("- your open PR: {repo}#{number} {}\n", age_text(now_ms, *at)), + WearFact::RecordsMissing(what) => format!("- records are missing: {what}.\n"), + WearFact::SpecsOnYours(specs) => { + let named = specs.iter().map(|(label, at)| format!("{label} {}", age_text(now_ms, *at))).collect(); + format!("- specs with no report in your mind, on your repos: {}\n", listed(named, ", ", |left, _| format!("+{left} more"))) + } + WearFact::SpecsElsewhere { count, oldest } => { + format!("- specs with no report in your mind, on repos you do not steward: {count}, oldest {}\n", age_text(now_ms, *oldest)) + } + WearFact::SoulFindings(rows) => { + let named = rows.iter().map(|row| format!("{} {}, {} blocking, oldest {}", row.campaign, row.open, row.blocking, age_text(now_ms, row.oldest))).collect(); + let more = |left: usize, from: usize| { + let held: usize = rows[from..].iter().map(|row| row.open).sum(); + format!("+{held} more in {left} {}", if left == 1 { "campaign" } else { "campaigns" }) + }; + format!("- open Soul findings in your mind: {}\n", listed(named, "; ", more)) + } + WearFact::QuietCampaigns(quiet) => { + let named = quiet.iter().map(|(campaign, at)| format!("{campaign} {}", age_text(now_ms, *at))).collect(); + format!( + "- campaigns on your repos with open work and no admission in your mind for {STALE_AFTER_DAYS} d or more: {}\n", + listed(named, ", ", |left, _| format!("+{left} more")) + ) + } }) .collect(); // The tail line is "(N more facts not shown)"; keep room for it whenever a fact is dropped. diff --git a/crates/mind-body/src/persona/tests.rs b/crates/mind-body/src/persona/tests.rs index 3d6dcb8..9b8f769 100644 --- a/crates/mind-body/src/persona/tests.rs +++ b/crates/mind-body/src/persona/tests.rs @@ -4553,11 +4553,17 @@ struct Forged<'a> { script: RefCell>>, asked: RefCell>>, head: Cell, + /// Every read of her mind, by the schema it names (`roots` for the roots read), in order. + reads: RefCell>, } impl<'a> Forged<'a> { fn over(mind: &'a TestMind, script: Vec>) -> Self { - Self { mind, script: RefCell::new(script.into()), asked: RefCell::default(), head: Cell::new(0) } + Self { mind, script: RefCell::new(script.into()), asked: RefCell::default(), head: Cell::new(0), reads: RefCell::default() } + } + + fn reads_of(&self, kind: K) -> usize { + self.reads.borrow().iter().filter(|read| read.as_str() == kind.type_id()).count() } } @@ -4567,9 +4573,15 @@ impl MindPort for Forged<'_> { } fn query(&self, selection: &cultnet_rs::Selection) -> Result { + self.reads.borrow_mut().extend(selection.schemas.iter().flatten().cloned()); self.mind.query(selection) } + fn roots_touched(&self) -> Result> { + self.reads.borrow_mut().push("roots".into()); + self.mind.roots_touched() + } + fn admit(&self, agent: &str, session: &str, documents: Vec) -> Result { self.mind.admit(agent, session, documents) } @@ -4959,3 +4971,410 @@ fn the_wear_bound_is_exact_to_the_byte() { assert!(over.len() <= WEAR_MAX_BYTES, "{} bytes: {over}", over.len()); assert!(over.trim_end().ends_with("more facts not shown)"), "{over}"); } + + +// ---- The wear her own mind holds: specs with no report, open Soul findings and quiet campaigns. ---- + +const DAY_MS: i64 = 86_400_000; + +fn t(days_ago: i64) -> u64 { + unix_ms(at(0)) - (days_ago * DAY_MS) as u64 +} + +fn pipeline_range() -> eureka_pipeline::CommitRange { + eureka_pipeline::CommitRange { base: eureka_pipeline::Sha("df7507b".into()), head: eureka_pipeline::Sha("df7507b".into()) } +} + +/// A spec in force whose cut has no report. +fn unreported_spec(campaign: &str, cut: &str, repo: &str) -> PipelineDocument { + let PipelineDocument::CutSpec(mut spec) = spec(cut) else { unreachable!("a spec") }; + spec.campaign = Slug(campaign.into()); + spec.repo = repo.into(); + PipelineDocument::CutSpec(spec) +} + +/// A spec with its report and a verdict that holds: the chain a Soul finding stands on. +fn chain(campaign: &str, cut: &str, repo: &str) -> Vec { + let PipelineDocument::CutReport(mut report) = report(cut) else { unreachable!("a report") }; + report.campaign = Slug(campaign.into()); + report.cut_spec = format!("{campaign}:cut_spec:cut-{cut}.r1").as_str().into(); + report.repo = repo.into(); + let verdict = eureka_pipeline::PipelineVerdict { + campaign: Slug(campaign.into()), + cut_report: format!("{campaign}:cut_report:cut-{cut}.h1").as_str().into(), + pass: 1, + range: pipeline_range(), + claims: vec![eureka_pipeline::VerdictClaim { + claim: "It holds.".into(), + outcome: eureka_pipeline::ClaimOutcome::Holds, + evidence: vec![evidence()], + findings: vec![], + promise: None, + mutations: vec![], + }], + }; + vec![unreported_spec(campaign, cut, repo), PipelineDocument::CutReport(report), PipelineDocument::Verdict(verdict)] +} + +fn evidence() -> eureka_pipeline::Evidence { + eureka_pipeline::Evidence { kind: eureka_pipeline::EvidenceKind::Test, locator: "cargo test".into(), result: "ok".into() } +} + +fn soul_finding(campaign: &str, cut: &str, label: &str, severity: eureka_pipeline::FindingSeverity) -> PipelineDocument { + PipelineDocument::Finding(eureka_pipeline::PipelineFinding { + campaign: Slug(campaign.into()), + verdict: format!("{campaign}:verdict:cut-{cut}.s1").as_str().into(), + label: label.into(), + range: pipeline_range(), + confidence: eureka_pipeline::FindingConfidence::Confirmed, + severity, + claim: "A claim.".into(), + invariants: vec![], + locations: vec![eureka_pipeline::CodeLocation { path: "a.rs".into(), line: 1, end_line: None, symbol: None }], + failure_scenario: "It fails.".into(), + evidence: vec![evidence()], + precedents: vec![], + origin: eureka_pipeline::FindingOrigin::Introduced, + }) +} + +/// Admits `documents` in batches the mind takes, the first at `first_days_ago` and the rest at `rest_days_ago`. +fn put_in_batches(mind: &TestMind, faculty: huginn_mind::Faculty, documents: Vec, first_days_ago: i64, rest_days_ago: i64) { + let mut first = true; + for batch in documents.chunks(60) { + mind.admit_at(at(-(if first { first_days_ago } else { rest_days_ago }) * DAY_MS)); + first = false; + let outcome = mind.put_as(faculty, batch.to_vec()); + assert!(matches!(outcome, AdmissionOutcome::Committed { .. }), "{outcome:?}"); + } +} + +#[derive(Clone, Copy)] +enum Fault { + Refused, + Client, +} + +/// Her mind as a daemon answers it, every read through the real adapter: the `nth` request (1-based) that names `schema` (`roots` +/// for the roots read) fails the way the daemon does, as a refusal, or the way a dead socket does, as a client error. Every read +/// is logged by the schema it names. The forge answers a quiet org. +fn through<'a>(mind: &'a TestMind, fail: Option<(String, usize, Fault)>, log: &'a RefCell>) -> crate::queue::HuginnMind<'a> { + let seen = Cell::new(0usize); + crate::queue::HuginnMind::over( + mind.instance().clone(), + Box::new(move |request| { + let which = match &request { + huginn_mind::HuginnMindRequest::RootsTouched { .. } => Some("roots".to_string()), + huginn_mind::HuginnMindRequest::Query { selection, .. } => selection.schemas.as_ref().and_then(|schemas| schemas.first().cloned()), + _ => None, + }; + if let Some(which) = &which { + log.borrow_mut().push(which.clone()); + } + if let (Some((name, nth, fault)), Some(which)) = (&fail, &which) + && which == name + { + seen.set(seen.get() + 1); + if seen.get() == *nth { + return match fault { + Fault::Refused => Ok(huginn_mind::HuginnMindResponse::Refused(huginn_mind::MindRefusal::Unavailable { detail: "canary".into() })), + Fault::Client => Err(eureka_state::ClientError::Unencodable { detail: "canary".into() }), + }; + } + } + if let huginn_mind::HuginnMindRequest::StewardedActivity { .. } = request { + return Ok(huginn_mind::HuginnMindResponse::Activity(RepoActivity { head: 1, events: vec![], capped: vec![], open_prs: vec![], unseen: vec![], moved: vec![] })); + } + Ok(mind.answer(request)) + }), + ) +} + +fn soul(mind: &TestMind, documents: Vec) { + let outcome = mind.put_as(huginn_mind::Faculty::Soul, documents); + assert!(matches!(outcome, AdmissionOutcome::Committed { .. }), "{outcome:?}"); +} + +fn hers() -> Vec { + vec![OrgRepo::from(REPO)] +} + +fn lines_of(wear: &str) -> Vec<&str> { + wear.lines().skip(1).collect() +} + +/// A spec on a repo she does not steward is only a count, a differently cased repo is hers, a finding outside her slice prints +/// nothing, and an empty slice makes no findings read. +#[test] +fn wear_lists_only_her_slice() { + let mind = TestMind::seeded(); + for (slug, repo) in [("elsewhere", "GameCult/Elsewhere"), ("cased", "gamecult/huginn")] { + mind.admit_at(at(-9 * DAY_MS)); + mind.committed(campaign_on(slug, &[repo])); + } + mind.admit_at(at(-3 * DAY_MS)); + mind.committed(vec![unreported_spec(CAMPAIGN, "mine", REPO)]); + mind.admit_at(at(-2 * DAY_MS)); + mind.committed(vec![unreported_spec("cased", "low", "gamecult/huginn")]); + mind.admit_at(at(-5 * DAY_MS)); + mind.committed(vec![unreported_spec("elsewhere", "theirs", "GameCult/Elsewhere")]); + for (campaign, repo) in [(CAMPAIGN, REPO), ("elsewhere", "GameCult/Elsewhere")] { + mind.admit_at(at(-6 * DAY_MS)); + mind.committed(chain(campaign, "f", repo)); + mind.admit_at(at(-4 * DAY_MS)); + soul(&mind, vec![soul_finding(campaign, "f", "one", eureka_pipeline::FindingSeverity::High)]); + } + let log = RefCell::default(); + let facts = record_wear_facts(&through(&mind, None, &log), &hers(), &[], t(0)); + assert_eq!( + facts, + [ + WearFact::SpecsOnYours(vec![("eureka-body/mine.r1".into(), t(3)), ("cased/low.r1".into(), t(2))]), + WearFact::SpecsElsewhere { count: 1, oldest: t(5) }, + WearFact::SoulFindings(vec![FindingRow { campaign: "eureka-body".into(), open: 1, blocking: 1, oldest: t(4) }]), + ] + ); + let wear = render_wear(t(0), &facts); + assert!(!wear.contains("elsewhere") && !wear.contains("Elsewhere"), "{wear}"); + + let none = TestMind::without_campaigns(); + let log = RefCell::default(); + assert_eq!(record_wear_facts(&through(&none, None, &log), &hers(), &[], t(0)), []); + assert_eq!(*log.borrow(), ["roots", K::CutSpec.type_id()], "an empty slice makes no findings read"); +} + +/// A mind with `specs` unreported specs in `eureka-body` and `findings` open Soul findings there, the first batch of each ten +/// days old and the rest one. +fn crowded(specs: usize, findings: usize) -> TestMind { + let mind = TestMind::seeded(); + put_in_batches(&mind, huginn_mind::Faculty::Hands, (0..specs).map(|n| unreported_spec(CAMPAIGN, &format!("s{n:03}"), REPO)).collect(), 9, 1); + mind.admit_at(at(-11 * DAY_MS)); + mind.committed(chain(CAMPAIGN, "v", REPO)); + let severity = |n: usize| if n % 4 == 0 { eureka_pipeline::FindingSeverity::Blocker } else { eureka_pipeline::FindingSeverity::Low }; + put_in_batches(&mind, huginn_mind::Faculty::Soul, (0..findings).map(|n| soul_finding(CAMPAIGN, "v", &format!("f{n:03}"), severity(n))).collect(), 10, 1); + mind +} + +/// A count crosses the page: 201 open findings print 201 with the oldest's age, and 201 unreported specs are all named by the fact +/// (the line prints four), not one page's worth. +#[test] +fn wear_counts_cross_a_page() { + let mind = crowded(201, 201); + let log = RefCell::default(); + let facts = record_wear_facts(&through(&mind, None, &log), &hers(), &[], t(0)); + let [WearFact::SpecsOnYours(specs), WearFact::SoulFindings(rows)] = facts.as_slice() else { panic!("{facts:?}") }; + assert_eq!((specs.len(), specs[0].1, specs[200].1), (201, t(9), t(1))); + assert_eq!(rows, &[FindingRow { campaign: "eureka-body".into(), open: 201, blocking: 51, oldest: t(10) }]); + assert!(log.borrow().iter().filter(|read| read.as_str() == K::Finding.type_id()).count() >= 2, "more than one page of findings was walked"); + assert!(log.borrow().iter().filter(|read| read.as_str() == K::CutSpec.type_id()).count() >= 2, "and of specs"); + let wear = render_wear(t(0), &facts); + assert!(wear.contains("- open Soul findings in your mind: eureka-body 201, 51 blocking, oldest (10 d)\n"), "{wear}"); +} + +/// A walk that fails on a later page fails that read whole, as a refusal or as a dead socket: its own missing line, no partial count, +/// the other reads' lines, and no quiet campaign from partial inputs. +#[test] +fn a_later_page_refused_fails_that_read_whole() { + let mind = crowded(201, 201); + for fault in [Fault::Refused, Fault::Client] { + let log = RefCell::default(); + let facts = record_wear_facts(&through(&mind, Some((K::Finding.type_id().into(), 2, fault)), &log), &hers(), &["eureka-body".into()], t(0) + 30 * DAY_MS as u64); + assert_eq!(facts.len(), 2, "{facts:?}"); + assert!(matches!(&facts[0], WearFact::RecordsMissing(what) if what.contains("open Soul findings could not be read")), "{facts:?}"); + assert!(matches!(&facts[1], WearFact::SpecsOnYours(specs) if specs.len() == 201), "the specs print whole: {facts:?}"); + + let log = RefCell::default(); + let facts = record_wear_facts(&through(&mind, Some((K::CutSpec.type_id().into(), 2, fault)), &log), &hers(), &[], t(0)); + assert_eq!(facts.len(), 2, "{facts:?}"); + assert!(matches!(&facts[0], WearFact::RecordsMissing(what) if what.contains("specs with no report could not be read")), "{facts:?}"); + assert!(matches!(&facts[1], WearFact::SoulFindings(rows) if rows[0].open == 201), "{facts:?}"); + } +} + +/// Each read in turn answers as the daemon does, as a refusal and as a client error: its own missing line prints, the others' +/// facts print, no quiet campaign comes of partial inputs, and a session still runs and shows it. +#[test] +fn a_failed_wear_read_says_so() { + let mind = TestMind::seeded(); + mind.admit_at(at(-30 * DAY_MS)); + mind.committed(vec![unreported_spec(CAMPAIGN, "old", REPO)]); + mind.committed(chain(CAMPAIGN, "f", REPO)); + soul(&mind, vec![soul_finding(CAMPAIGN, "f", "one", eureka_pipeline::FindingSeverity::Low)]); + let all = |facts: &[WearFact]| facts.iter().filter(|fact| matches!(fact, WearFact::QuietCampaigns(_))).count(); + let log = RefCell::default(); + let quiet_at = t(0) + DAY_MS as u64 * 60; + let whole = record_wear_facts(&through(&mind, None, &log), &hers(), &[], quiet_at); + assert_eq!(all(&whole), 1, "with every read answered the old campaign is quiet: {whole:?}"); + for fault in [Fault::Refused, Fault::Client] { + for (read, missing) in [ + ("roots", "campaigns on your repos could not be read"), + (K::CutSpec.type_id(), "specs with no report could not be read"), + (K::Finding.type_id(), "open Soul findings could not be read"), + ] { + let log = RefCell::default(); + let facts = record_wear_facts(&through(&mind, Some((read.into(), 1, fault)), &log), &hers(), &[], quiet_at); + assert!(facts.iter().any(|fact| matches!(fact, WearFact::RecordsMissing(what) if what.contains(missing))), "{read}: {facts:?}"); + assert_eq!(facts.len(), 2, "{read}: its missing line and the facts of the reads that answered: {facts:?}"); + assert_eq!(all(&facts), 0, "{read}: no quiet campaign from partial inputs"); + } + } + + let mut rig = stewarding_rig(2); + rig.mind = mind; + let log = RefCell::default(); + let broken = through(&rig.mind, Some(("roots".into(), 1, Fault::Client)), &log); + live_session(&rig, &broken, 1000, false, 1); + let input = input_of(&rig, 0); + assert!(input.contains("- records are missing: the campaigns on your repos could not be read"), "{input}"); + assert!(input.contains("- specs with no report in your mind, on your repos: eureka-body/old.r1"), "the session ran and the specs printed: {input}"); +} + +/// A campaign is quiet exactly at the window: 14 d lists, a millisecond less does not; it needs open work (an unreported spec, an +/// open Soul finding or an open follow-up) and a campaign with none is not listed. +#[test] +fn a_quiet_campaign_needs_open_work_and_the_full_window() { + let mind = TestMind::seeded(); + let opened = t(20); + for slug in ["q-spec", "q-find", "q-follow", "q-none"] { + mind.admit_at(at(-20 * DAY_MS)); + mind.committed(campaign_on(slug, &[REPO])); + } + mind.admit_at(at(-20 * DAY_MS)); + mind.committed(vec![unreported_spec("q-spec", "x", REPO)]); + mind.admit_at(at(-20 * DAY_MS)); + mind.committed(chain("q-find", "x", REPO)); + mind.admit_at(at(-20 * DAY_MS)); + soul(&mind, vec![soul_finding("q-find", "x", "one", eureka_pipeline::FindingSeverity::Low)]); + let log = RefCell::default(); + let port = through(&mind, None, &log); + let window = opened + 14 * DAY_MS as u64; + let quiet = |now: u64, open: &[String]| record_wear_facts(&port, &hers(), open, now).into_iter().find_map(|fact| if let WearFact::QuietCampaigns(q) = fact { Some(q) } else { None }); + let follow = ["q-follow".to_string(), "q-none-but-not-in-the-slice".to_string()]; + assert_eq!(quiet(window, &follow), Some(vec![("q-find".into(), opened), ("q-follow".into(), opened), ("q-spec".into(), opened)]), "exactly 14 d lists, and q-none has no open work"); + assert_eq!(quiet(window - 1, &follow), None, "a millisecond less lists none"); + assert_eq!(quiet(window + 1, &follow).map(|q| q.len()), Some(3)); + assert_eq!(quiet(window, &[]).map(|q| q.len()), Some(2), "without the follow-up q-follow has no open work"); +} + +/// A follow-up the goals bound hides still counts as open work: the roots come from the whole list. +#[test] +fn a_follow_up_the_goals_bound_hides_still_counts_as_open_work() { + let mind = TestMind::seeded(); + mind.committed(campaign_on("hidden-in", &[REPO])); + mind.committed(chain("hidden-in", "src", REPO)); + let PipelineDocument::FollowUp(mut hidden) = follow_up("old", &reference(K::CutSpec, "hidden-in:cut_spec:cut-src.r1")) else { unreachable!("a follow-up") }; + hidden.campaign = Slug("hidden-in".into()); + mind.committed(vec![PipelineDocument::FollowUp(hidden)]); + mind.committed(chain(CAMPAIGN, "src", REPO)); + for n in 0..12 { + let PipelineDocument::FollowUp(mut long) = follow_up(&format!("long{n}"), &spec_ref("src")) else { unreachable!("a follow-up") }; + long.item = Line("x".repeat(900)); + mind.committed(vec![PipelineDocument::FollowUp(long)]); + } + let goals = render_responsibilities(&mind, &Slug(INSTANCE.into()), &BTreeMap::new()).unwrap(); + assert!(goals.text.contains("older open follow-ups not shown") && !goals.text.contains("hidden-in/old"), "the bound hid it: {}", goals.text); + assert_eq!(goals.open_roots, ["eureka-body", "hidden-in"], "{:?}", goals.open_roots); +} + +/// The caps are exact: four entries print with no tail, five print four and `+1 more`, on all three listing lines, and the finding +/// line's `+N more in M campaigns` counts what it left out. +#[test] +fn wear_caps_are_exact() { + let now = t(0); + let entries = |n: usize| (0..n).map(|k| (format!("c{k}"), now - (k as u64 + 1) * DAY_MS as u64)).collect::>(); + let line = |fact: WearFact| render_wear(now, &[fact]).lines().nth(1).unwrap().to_string(); + for (make, head) in [ + (WearFact::SpecsOnYours as fn(Vec<(String, u64)>) -> WearFact, "- specs with no report in your mind, on your repos: "), + (WearFact::QuietCampaigns, "- campaigns on your repos with open work and no admission in your mind for 14 d or more: "), + ] { + assert_eq!(line(make(entries(4))), format!("{head}c0 (1 d), c1 (2 d), c2 (3 d), c3 (4 d)")); + assert_eq!(line(make(entries(5))), format!("{head}c0 (1 d), c1 (2 d), c2 (3 d), c3 (4 d), +1 more")); + assert_eq!(line(make(entries(7))), format!("{head}c0 (1 d), c1 (2 d), c2 (3 d), c3 (4 d), +3 more")); + } + let rows = |n: usize| (0..n).map(|k| FindingRow { campaign: format!("c{k}"), open: 10 - k, blocking: k, oldest: now - 3 * 3_600_000 }).collect::>(); + let named = "- open Soul findings in your mind: c0 10, 0 blocking, oldest (3 h); c1 9, 1 blocking, oldest (3 h); c2 8, 2 blocking, oldest (3 h); c3 7, 3 blocking, oldest (3 h)"; + assert_eq!(line(WearFact::SoulFindings(rows(4))), named); + assert_eq!(line(WearFact::SoulFindings(rows(5))), format!("{named}; +6 more in 1 campaign")); + assert_eq!(line(WearFact::SoulFindings(rows(7))), format!("{named}; +15 more in 3 campaigns")); + assert_eq!(line(WearFact::SpecsElsewhere { count: 9, oldest: now - 40 * DAY_MS as u64 }), "- specs with no report in your mind, on repos you do not steward: 9, oldest (40 d)"); +} + +/// Forge facts and record facts share the one bound: built to exactly the bound they all print with no tail; one byte more drops +/// from the end, the section stays inside the bound and the tail's count is exact; the forge's facts rank first. +#[test] +fn record_facts_share_the_one_bound() { + let now = t(0); + let forge = |n: usize| WearFact::Changed { repo: format!("GameCult/r{n:03}"), words: "1 commit pushed by nibu".into(), at: now - 3_600_000 }; + let record = |pad: usize| WearFact::QuietCampaigns(vec![(format!("q{}", "x".repeat(pad)), now - 15 * DAY_MS as u64)]); + let header = render_wear(now, &[forge(0)]).lines().next().unwrap().len() + 1; + let each = render_wear(now, &[forge(0)]).len() - header; + let record_len = |pad: usize| render_wear(now, &[record(pad)]).len() - header; + let count = (WEAR_MAX_BYTES - header - record_len(0)) / each; + let spare = WEAR_MAX_BYTES - header - record_len(0) - count * each; + let mut facts: Vec = vec![record(spare)]; + facts.extend((0..count).map(forge)); + let exact = render_wear(now, &facts); + assert_eq!(exact.len(), WEAR_MAX_BYTES, "built to the byte"); + assert!(!exact.contains("not shown") && exact.contains("campaigns on your repos with open work"), "all print: {exact}"); + assert!(exact.lines().nth(1).unwrap().starts_with("- changed by others"), "the forge's facts rank first: {exact}"); + + facts[0] = record(spare + 1); + let over = render_wear(now, &facts); + assert!(over.len() <= WEAR_MAX_BYTES, "{} bytes", over.len()); + assert!(!over.contains("campaigns on your repos with open work"), "the record fact drops from the end: {over}"); + let shown = over.lines().filter(|line| line.starts_with("- ")).count(); + assert!(over.trim_end().ends_with(&format!("({} more facts not shown)", facts.len() - shown)) && shown < facts.len(), "{over}"); + assert!(shown + 1 >= count, "forge facts are kept before it: {shown} of {count}"); +} + +/// A settled record leaves the next first line: resolving a finding and reporting a spec removes them, and the reads wrote nothing. +#[test] +fn a_settled_record_leaves_the_next_first_line() { + let mind = TestMind::seeded(); + mind.admit_at(at(-3 * DAY_MS)); + mind.committed(vec![unreported_spec(CAMPAIGN, "open", REPO)]); + mind.committed(chain(CAMPAIGN, "f", REPO)); + soul(&mind, vec![soul_finding(CAMPAIGN, "f", "one", eureka_pipeline::FindingSeverity::High)]); + let held = || [K::CutSpec, K::CutReport, K::Verdict, K::Finding, K::Resolution, K::Campaign].iter().map(|kind| mind.ids(*kind).len()).sum::(); + let log = RefCell::default(); + let before = held(); + let facts = record_wear_facts(&through(&mind, None, &log), &hers(), &[], t(0)); + assert_eq!(facts.len(), 2, "{facts:?}"); + assert_eq!(held(), before, "the reads wrote nothing"); + + let finding = mind.ids(K::Finding).remove(0); + mind.committed(vec![close(reference(K::Finding, &finding), recorded())]); + let PipelineDocument::CutReport(mut report) = report("open") else { unreachable!("a report") }; + report.cut_spec = id("cut_spec", "cut-open.r1").as_str().into(); + mind.committed(vec![PipelineDocument::CutReport(report)]); + assert_eq!(record_wear_facts(&through(&mind, None, &log), &hers(), &[], t(0)), [], "both are gone from the next first line"); +} + +/// One session over a mind that holds an unreported spec: how many roots, spec and Soul-finding reads it made, and its first line. +fn wear_reads(steward: bool, polls: u64, messages: bool) -> (usize, usize, usize, String) { + let rig = stewarding_rig(polls as usize + 5); + rig.mind.committed(vec![unreported_spec(CAMPAIGN, "open", REPO)]); + if !steward { + for stewardship in rig.mind.ids(K::Stewardship) { + rig.mind.committed(vec![close(reference(K::Stewardship, &stewardship), withdrawn())]); + } + } + let forged = Forged::over(&rig.mind, vec![activity(100, vec![])]); + live_session(&rig, &forged, 5_000, messages, polls); + let roots = forged.reads.borrow().iter().filter(|read| read.as_str() == "roots").count(); + (roots, forged.reads_of(K::CutSpec), forged.reads_of(K::Finding), input_of(&rig, 0)) +} + +/// Wear reads her mind on a first line and nowhere else: a session's start adds one roots read, one specs read and one findings +/// read to a Mind that stewards nothing, and a session of many polls and tells adds none beyond the first line's. +#[test] +fn wear_reads_only_on_a_first_line() { + let (roots, specs, findings, input) = wear_reads(true, 1, false); + let (none_roots, none_specs, none_findings, bare) = wear_reads(false, 1, false); + assert_eq!((roots, specs - none_specs, findings - none_findings), (1, 1, 1), "three reads on a start"); + assert_eq!(none_roots, 0, "a Mind with no stewardship makes none of them"); + assert!(input.contains("eureka-body/open.r1") && !bare.contains("Where your machine shows wear"), "{input} +{bare}"); + let long = wear_reads(true, 25, true); + assert_eq!((long.0, long.1, long.2), (roots, specs, findings), "polls and tells read nothing more"); +} diff --git a/crates/mind-body/src/testkit.rs b/crates/mind-body/src/testkit.rs index 6d39aa6..24f6c8f 100644 --- a/crates/mind-body/src/testkit.rs +++ b/crates/mind-body/src/testkit.rs @@ -135,10 +135,15 @@ impl TestMind { /// Admits as Hands, one second after the last admission. pub(crate) fn put(&self, documents: Vec) -> PipelineAdmissionOutcome { + self.put_as(Faculty::Hands, documents) + } + + /// Admits as `faculty`, one second after the last admission. + pub(crate) fn put_as(&self, faculty: Faculty, documents: Vec) -> PipelineAdmissionOutcome { self.now.set(self.now.get() + Duration::seconds(1)); let batch = PipelineAdmissionBatch { instance: self.instance.clone(), - provenance: PipelineProvenance { faculty: Faculty::Hands, agent: "test".into(), session: "test".into(), tool: "test".into() }, + provenance: PipelineProvenance { faculty, agent: "test".into(), session: "test".into(), tool: "test".into() }, documents, }; self.mind.borrow_mut().admit(batch, self.now.get()) @@ -304,6 +309,15 @@ pub(crate) fn campaign_named(slug: &str, title: &str) -> PipelineDocument { }) } +/// A campaign opened on `repos`, with its first target and the one invariant. +pub(crate) fn campaign_on(slug: &str, repos: &[&str]) -> Vec { + let PipelineDocument::Campaign(mut opened) = campaign_named(slug, slug) else { unreachable!("a campaign") }; + opened.repos = repos.iter().map(|repo| (*repo).into()).collect(); + let PipelineDocument::Target(mut first) = target() else { unreachable!("a target") }; + first.campaign = Slug(slug.into()); + vec![PipelineDocument::Campaign(opened), PipelineDocument::Target(first)] +} + fn target() -> PipelineDocument { PipelineDocument::Target(PipelineTarget { campaign: Slug(CAMPAIGN.into()),