From 7162412bc22c5ad25d47b45adf8361900bdf9932 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:11:48 +0100 Subject: [PATCH 01/12] Add EscalateGoal wire request, schema, and daemon enforcement Add HuginnMindRequest::EscalateGoal (accepted by Door::Persona while Admit(_) remains NotThisDoor), regenerate huginn.mind_request.v1.schema.json, and enforce owner=self-run, agent=mind-persona, locations=[], source=:campaign:self, and no imported_from in Daemon::handle. --- crates/huginn-daemon/src/daemon.rs | 175 +++++++++++++++++- crates/huginn-mind/src/wire.rs | 64 ++++++- .../huginn.mind_request.v1.schema.json | 55 ++++++ 3 files changed, 280 insertions(+), 14 deletions(-) diff --git a/crates/huginn-daemon/src/daemon.rs b/crates/huginn-daemon/src/daemon.rs index 03cc29c..8b5880b 100644 --- a/crates/huginn-daemon/src/daemon.rs +++ b/crates/huginn-daemon/src/daemon.rs @@ -6,9 +6,12 @@ use chrono::{DateTime, Utc}; use cultnet_rs::Selection; use crate::sources::forge::HttpForge; use huginn_mind::desk_wire::{DeskRequest, DeskResponse}; -use huginn_mind::eureka_pipeline::{AccountId, PipelineRef, Short, Slug}; +use huginn_mind::eureka_pipeline::{AccountId, PipelineDocument, PipelineFollowUp, PipelineKind, PipelineRef, Short, Slug}; use huginn_mind::wire::{ACTIVITY_REPOS_MAX, HuginnMindRequest, HuginnMindResponse, IndexStatus}; -use huginn_mind::{ChatHits, ChatQuery, ChatWindow, ChatWindowQuery, Members, Mind, MindRefusal, MindStore, PipelineAdmissionOutcome, SemanticQuery, SourceHits, SourceQuery}; +use huginn_mind::{ + ChatHits, ChatQuery, ChatWindow, ChatWindowQuery, Members, Mind, MindRefusal, MindStore, PipelineAdmissionBatch, + PipelineAdmissionOutcome, SemanticQuery, SourceHits, SourceQuery, +}; /// Where the index attaches. Called after a batch commits, with the refs the /// batch landed, derived writes included; the sink may read each through @@ -213,15 +216,43 @@ impl> Daemon { } let answer = match request { HuginnMindRequest::Whoami => HuginnMindResponse::Whoami(self.mind.status(self.index.status())), - HuginnMindRequest::Admit(batch) => { - let outcome = self.mind.admit(batch, now); - if let PipelineAdmissionOutcome::Committed { writes, .. } = &outcome - && let Err(error) = self.index.committed(&self.mind, writes) - { - let refs = writes.iter().map(|write| write.id.0.clone()).collect::>().join(", "); - eprintln!("huginn: the index refused the landed writes [{refs}]: {error:#}"); + HuginnMindRequest::Admit(batch) => self.admit_and_index(batch, now), + HuginnMindRequest::EscalateGoal { + instance, + mut provenance, + campaign, + label, + repo, + item, + why_it_can_wait, + origin, + } => { + if provenance.imported_from.is_some() { + return Handled::Answered(HuginnMindResponse::Refused(MindRefusal::SelectionInvalid { + field: "provenance.imported_from".into(), + value: None, + message: "an escalated goal cannot carry imported_from".into(), + })); } - HuginnMindResponse::Admit(outcome) + provenance.agent = Short("mind-persona".into()); + let follow_up = PipelineDocument::FollowUp(PipelineFollowUp { + source: PipelineRef { + kind: PipelineKind::Campaign, + id: Short(format!("{}:campaign:self", campaign.0)), + }, + campaign, + label, + repo, + locations: Vec::new(), + item, + why_it_can_wait, + owner: Short("self-run".into()), + origin, + }); + self.admit_and_index( + PipelineAdmissionBatch { instance, provenance, documents: vec![follow_up] }, + now, + ) } HuginnMindRequest::View { id, .. } => match self.mind.view(&id) { Ok(view) => HuginnMindResponse::View(view.map(Box::new)), @@ -308,6 +339,17 @@ impl> Daemon { } } + fn admit_and_index(&mut self, batch: PipelineAdmissionBatch, now: DateTime) -> HuginnMindResponse { + let outcome = self.mind.admit(batch, now); + if let PipelineAdmissionOutcome::Committed { writes, .. } = &outcome + && let Err(error) = self.index.committed(&self.mind, writes) + { + let refs = writes.iter().map(|write| write.id.0.clone()).collect::>().join(", "); + eprintln!("huginn: the index refused the landed writes [{refs}]: {error:#}"); + } + HuginnMindResponse::Admit(outcome) + } + /// A semantic query starts only if the mind accepts it, and the mind /// decides its members before the index is asked anything. A selection /// with no members is answered at once: nothing is embedded and the index @@ -1102,6 +1144,119 @@ pub(crate) mod tests { ); } + #[test] + fn daemon_escalate_goal_enforces_persona_door_bounds() { + use huginn_mind::eureka_pipeline::{Label, MemoryOrigin, PipelineFollowUp}; + use huginn_mind::ImportSource; + + let indexed = Arc::new(Mutex::new(Vec::::new())); + struct RecordingIndex(Arc>>); + impl IndexSink for RecordingIndex { + fn committed(&mut self, _mind: &Mind, writes: &[PipelineRef]) -> anyhow::Result<()> { + self.0.lock().unwrap().extend(writes.iter().cloned()); + Ok(()) + } + fn status(&self) -> IndexStatus { IndexStatus::Current } + fn search(&mut self, _t: &str, _k: u32, _a: Vec) -> Result { Err("unused".into()) } + fn search_sources(&mut self, _q: &SourceQuery) -> Result { Err("unused".into()) } + fn search_chat(&mut self, _q: &ChatQuery) -> Result { Err("unused".into()) } + fn chat_window(&mut self, _q: &ChatWindowQuery) -> Result { Err("unused".into()) } + fn sources_searched(&mut self) -> Vec<(SearchTicket, Found)> { Vec::new() } + fn search_deadline(&self) -> std::time::Duration { std::time::Duration::ZERO } + fn searched(&mut self) -> Vec<(SearchTicket, Result)> { Vec::new() } + fn abandon(&mut self, _t: SearchTicket) {} + } + + let root = tempfile::tempdir().unwrap(); + let mind = Mind::open(root.path(), &slug(INSTANCE)).unwrap(); + let mut daemon = Daemon::new(mind, RecordingIndex(Arc::clone(&indexed))); + let seed = daemon.handle_at(Door::Full, HuginnMindRequest::Admit(batch(INSTANCE, campaign_seed())), now()).answered(); + assert!(matches!(seed, HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })), "{seed:?}"); + indexed.lock().unwrap().clear(); + + let admit = HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])); + assert_eq!(daemon.handle_at(Door::Persona, admit, now()).answered(), HuginnMindResponse::Refused(MindRefusal::NotThisDoor)); + + let mut caller_prov = provenance(); + caller_prov.agent = Short("forged-agent".into()); + let escalate = HuginnMindRequest::EscalateGoal { + instance: slug(INSTANCE), + provenance: caller_prov, + campaign: slug(CAMPAIGN), + label: Label("esc-door-1".into()), + repo: OrgRepo(REPO.into()), + item: Line("Check lock stall.".into()), + why_it_can_wait: Line("Next Self run.".into()), + origin: Some(MemoryOrigin::Direct { room: Short("!dm:gamecult.org".into()), with: vec![Short("@meta:gamecult.org".into())] }), + }; + let HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { writes, .. }) = + daemon.handle_at(Door::Persona, escalate, now()).answered() + else { + panic!("EscalateGoal must commit through Door::Persona"); + }; + assert_eq!(writes.len(), 1); + assert_eq!(indexed.lock().unwrap().as_slice(), writes.as_slice()); + + let HuginnMindResponse::View(Some(view)) = + daemon.handle_at(Door::Persona, HuginnMindRequest::View { instance: slug(INSTANCE), id: writes[0].clone() }, now()).answered() + else { + panic!("committed FollowUp must be viewable"); + }; + assert_eq!(view.admission.provenance.agent.0, "mind-persona"); + assert!(view.admission.provenance.imported_from.is_none()); + let PipelineDocument::FollowUp(PipelineFollowUp { source, owner, locations, origin, .. }) = view.document else { + panic!("expected FollowUp"); + }; + assert_eq!(owner.0, "self-run"); + assert!(locations.is_empty()); + assert_eq!(source, PipelineRef { kind: PipelineKind::Campaign, id: Short(format!("{CAMPAIGN}:campaign:self")) }); + assert_eq!(origin, Some(MemoryOrigin::Direct { room: Short("!dm:gamecult.org".into()), with: vec![Short("@meta:gamecult.org".into())] })); + + // Foreign instance refused before admission. + let foreign = HuginnMindRequest::EscalateGoal { + instance: slug(OTHER), + provenance: provenance(), + campaign: slug(CAMPAIGN), + label: Label("esc-foreign".into()), + repo: OrgRepo(REPO.into()), + item: Line("Foreign.".into()), + why_it_can_wait: Line("Wait.".into()), + origin: None, + }; + assert_eq!( + daemon.handle_at(Door::Persona, foreign, now()).answered(), + HuginnMindResponse::Refused(MindRefusal::ForeignInstance { declared: OTHER.into(), mind: INSTANCE.into() }) + ); + + // imported_from refused. + let mut with_import = provenance(); + with_import.imported_from = Some(ImportSource { + instance: slug(OTHER), + receipt_id: Short("mind-commit-1".into()), + ordinal: 1, + committed_at: Short("2026-10-10T10:00:00Z".into()), + faculty: Faculty::Hands, + agent: Short("importer".into()), + session: Short("s1".into()), + tool: Short("huginn".into()), + external: vec![], + }); + let imported = HuginnMindRequest::EscalateGoal { + instance: slug(INSTANCE), + provenance: with_import, + campaign: slug(CAMPAIGN), + label: Label("esc-import".into()), + repo: OrgRepo(REPO.into()), + item: Line("Imported.".into()), + why_it_can_wait: Line("Wait.".into()), + origin: None, + }; + assert!(matches!( + daemon.handle_at(Door::Persona, imported, now()).answered(), + HuginnMindResponse::Refused(MindRefusal::SelectionInvalid { ref field, .. }) if field == "provenance.imported_from" + )); + } + /// Every read the persona door answers reaches the mind there: none of the /// source, chat, activity and roots reads is refused as `NotThisDoor`. /// What the mind then says (a search, or `Unavailable` with no index or diff --git a/crates/huginn-mind/src/wire.rs b/crates/huginn-mind/src/wire.rs index 0c9bcc0..2565a89 100644 --- a/crates/huginn-mind/src/wire.rs +++ b/crates/huginn-mind/src/wire.rs @@ -6,7 +6,7 @@ use cultcache_rs::DatabaseEntry; use cultnet_rs::{CultMeshCdnArtifactManifest, Selection}; -use eureka_pipeline::{Line, OrgRepo, PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Short, Slug}; +use eureka_pipeline::{Label, Line, MemoryOrigin, OrgRepo, PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Short, Slug}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -108,6 +108,17 @@ pub enum HuginnMindRequest { /// Every root the mind holds a document under, with its newest admission and a campaign's repos in force: the mind's own /// records, one pass at the head. RootsTouched { instance: Slug }, + /// Escalates a follow-up brief from a Persona session to Self on the persona door. + EscalateGoal { + instance: Slug, + provenance: PipelineProvenance, + campaign: Slug, + label: Label, + repo: OrgRepo, + item: Line, + why_it_can_wait: Line, + origin: Option, + }, } /// The most repos one activity read names. @@ -427,6 +438,7 @@ impl HuginnMindRequest { Self::ChatWindow { .. } => "chat_window", Self::StewardedActivity { .. } => "stewarded_activity", Self::RootsTouched { .. } => "roots_touched", + Self::EscalateGoal { .. } => "escalate_goal", } } @@ -447,7 +459,8 @@ impl HuginnMindRequest { | Self::SearchChat { .. } | Self::ChatWindow { .. } | Self::StewardedActivity { .. } - | Self::RootsTouched { .. } => true, + | Self::RootsTouched { .. } + | Self::EscalateGoal { .. } => true, Self::Admit(_) => false, } } @@ -465,7 +478,8 @@ impl HuginnMindRequest { | Self::SearchChat { instance, .. } | Self::ChatWindow { instance, .. } | Self::StewardedActivity { instance, .. } - | Self::RootsTouched { instance } => Some(instance), + | Self::RootsTouched { instance } + | Self::EscalateGoal { instance, .. } => Some(instance), } } } @@ -626,6 +640,19 @@ mod tests { }, HuginnMindRequest::ChatWindow { instance: slug(INSTANCE), query: ChatWindowQuery { event_id: Short("$a".into()), before: 5, after: 0 } }, HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) }, + HuginnMindRequest::EscalateGoal { + instance: slug(INSTANCE), + provenance: provenance(Faculty::Member), + campaign: slug(CAMPAIGN), + label: Label("esc-1".into()), + repo: OrgRepo("GameCult/Huginn".into()), + item: Line("Investigate lock stall.".into()), + why_it_can_wait: Line("Next Self run.".into()), + origin: Some(MemoryOrigin::Room { + rooms: Short("#swarm:gamecult.org".into()), + heard_from: vec![Short("@alice:gamecult.org".into())], + }), + }, ] } @@ -713,13 +740,42 @@ mod tests { #[test] fn the_wire_vocabulary_is_the_minds_methods_and_status_is_derived_from_the_response() { let names: Vec<&str> = requests().iter().map(|request| request.operation()).collect(); - assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put", "search_sources", "search_sources", "search_chat", "chat_window", "roots_touched"]); + assert_eq!( + names, + [ + "whoami", + "admit", + "view", + "query", + "persona_get", + "persona_put", + "search_sources", + "search_sources", + "search_chat", + "chat_window", + "roots_touched", + "escalate_goal", + ] + ); for request in requests() { + assert_eq!(request.reaches_persona_door(), !matches!(request, HuginnMindRequest::Admit(_)), "{request:?}"); let declared = request.instance().is_none(); assert_eq!(declared, matches!(request, HuginnMindRequest::Whoami), "{request:?}"); let bytes = rmp_serde::to_vec_named(&request).unwrap(); assert_eq!(rmp_serde::from_slice::(&bytes).unwrap(), request); } + let escalate_no_origin = HuginnMindRequest::EscalateGoal { + instance: slug(INSTANCE), + provenance: provenance(Faculty::Member), + campaign: slug(CAMPAIGN), + label: Label("esc-2".into()), + repo: OrgRepo("GameCult/Huginn".into()), + item: Line("Follow up.".into()), + why_it_can_wait: Line("Next run.".into()), + origin: None, + }; + let bytes = rmp_serde::to_vec_named(&escalate_no_origin).unwrap(); + assert_eq!(rmp_serde::from_slice::(&bytes).unwrap(), escalate_no_origin); assert_eq!( requests()[3].instance(), Some(&slug(OTHER_INSTANCE)), diff --git a/schemas/cultnet/huginn.mind_request.v1.schema.json b/schemas/cultnet/huginn.mind_request.v1.schema.json index bca4ea2..cb4b3e8 100644 --- a/schemas/cultnet/huginn.mind_request.v1.schema.json +++ b/schemas/cultnet/huginn.mind_request.v1.schema.json @@ -264,6 +264,61 @@ "required": [ "RootsTouched" ] + }, + { + "description": "Escalates a follow-up brief from a Persona session to Self on the persona door.", + "type": "object", + "properties": { + "EscalateGoal": { + "type": "object", + "properties": { + "campaign": { + "$ref": "#/$defs/Slug" + }, + "instance": { + "$ref": "#/$defs/Slug" + }, + "item": { + "$ref": "#/$defs/Line" + }, + "label": { + "$ref": "#/$defs/Label" + }, + "origin": { + "anyOf": [ + { + "$ref": "#/$defs/MemoryOrigin" + }, + { + "type": "null" + } + ] + }, + "provenance": { + "$ref": "#/$defs/PipelineProvenance" + }, + "repo": { + "$ref": "#/$defs/OrgRepo" + }, + "why_it_can_wait": { + "$ref": "#/$defs/Line" + } + }, + "required": [ + "instance", + "provenance", + "campaign", + "label", + "repo", + "item", + "why_it_can_wait" + ] + } + }, + "additionalProperties": false, + "required": [ + "EscalateGoal" + ] } ], "$defs": { From 3f352681a79962bb4ce57b15579ffbf764712b51 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:15:46 +0100 Subject: [PATCH 02/12] Add huginn activity and escalate CLI subcommands Expose StewardedActivity as huginn activity (auto-discovering in-force Stewardship repos for the instance when --repo is omitted, plain-text rendering, exit 3 on unavailable forge) and EscalateGoal as huginn escalate (over Door::Persona or Door::Full with read_back verification), with no --json flags. --- crates/eureka-state/src/bin/huginn/main.rs | 249 ++++++++++++++++++- crates/eureka-state/src/bin/huginn/render.rs | 46 +++- crates/eureka-state/tests/cli.rs | 246 ++++++++++++++++++ 3 files changed, 533 insertions(+), 8 deletions(-) diff --git a/crates/eureka-state/src/bin/huginn/main.rs b/crates/eureka-state/src/bin/huginn/main.rs index 280ae96..3e8ef08 100644 --- a/crates/eureka-state/src/bin/huginn/main.rs +++ b/crates/eureka-state/src/bin/huginn/main.rs @@ -39,11 +39,13 @@ use clap::{CommandFactory, FromArgMatches, Parser, Subcommand}; use cultnet_rs::{PROJECTION_DOCUMENT, Selection}; use eureka_state::hold; use huginn_mind::eureka_pipeline::{ - Line, PipelineDocument, PipelineRef, Short, Slug, pipeline_key, + Label, Line, MemoryOrigin, OrgRepo, PipelineDocument, PipelineFollowUp, PipelineKind, PipelineRef, Short, Slug, + pipeline_key, }; use huginn_mind::{ - BATCH_MAX, ChatQuery, ChatWindowQuery, Faculty, HuginnMindRequest, HuginnMindResponse, MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome, - PipelinePageItems, PipelineProvenance, PipelineSelectionPage, SemanticQuery, SourceQuery, + ACTIVITY_REPOS_MAX, BATCH_MAX, ChatQuery, ChatWindowQuery, Faculty, HuginnMindRequest, HuginnMindResponse, + MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome, PipelineFacts, PipelinePageItems, + PipelineProvenance, PipelineSelectionPage, SemanticQuery, SourceQuery, }; use serde_json::Value; @@ -68,7 +70,7 @@ After Committed or AlreadyAdmitted the batch is read back and compared with what const IMPORT_HELP: &str = "Reads the giver's mind (it sends Query alone) and admits its receipts for the campaign into this one, one batch per source receipt, in order, each naming the giver's receipt in imported_from. It refuses unless the campaign is moved to this mind (exit 1), and when this mind already holds records under the campaign that it did not import from the giver, except follow-ups and ideas it admitted after the import began, which stay in place and are named (exit 1). A rerun after any stop resumes at the first batch this mind does not hold; it prints `imported from : ... verified` only after comparing every document it holds with the giver's (exit 5 if one differs). Until it prints imported, this mind writes nothing else under the campaign; a write that collides stops the import with the refusal (exit 1). Exit 3 Unavailable (rerun), 4 the history cannot be replayed whole (a receipt over 64 documents, too many external referents, a receipt held in part). Only a Self run can run it: a Persona's traffic to a peer's huginn port is fenced."; #[derive(Parser, Debug)] -#[command(name = "huginn", about = "Huginn's mind: whoami, view, query, recipes, persona, admit, import, recall, schema", arg_required_else_help = true)] +#[command(name = "huginn", about = "Huginn's mind: whoami, view, query, recipes, persona, activity, escalate, admit, import, recall, schema", arg_required_else_help = true)] struct Cli { #[command(subcommand)] command: Command, @@ -221,6 +223,50 @@ enum Command { #[command(subcommand)] command: Box, }, + /// Recent forge activity and open PRs in stewarded (or named) repositories. + Activity { + /// Repository as `Org/Repo`. Repeat for several; defaults to in-force stewardships for this instance. + #[arg(long = "repo")] + repos: Vec, + /// Only events after this forge feed cursor (from a previous `head`). + #[arg(long)] + after: Option, + }, + /// Escalate a follow-up brief to Self (usable over the persona door). + Escalate { + /// The campaign's slug; the brief's source is `:campaign:self`. + #[arg(long)] + campaign: String, + /// The repository as `Org/Repo`. + #[arg(long)] + repo: String, + /// What needs attention in the next Self run. + #[arg(long)] + item: String, + /// Why this can wait for a Self run rather than blocking now. + #[arg(long)] + why_it_can_wait: String, + /// The follow-up's label; generated from the timestamp if omitted. + #[arg(long)] + label: Option, + /// The room alias or id where the need arose (conflicts with --dm). + #[arg(long, conflicts_with = "dm")] + room: Option, + /// The direct-message room id where the need arose (conflicts with --room). + #[arg(long, conflicts_with = "room")] + dm: Option, + /// Sender(s) heard from in --room or --dm. Repeat for several. + #[arg(long = "heard-from")] + heard_from: Vec, + #[arg(long, value_parser = faculty, default_value = "Member")] + faculty: Faculty, + /// The escalating agent's name (the daemon pins `mind-persona` on the receipt). + #[arg(long, default_value = "mind-persona")] + agent: String, + /// The escalating session; else HUGINN_SESSION. + #[arg(long)] + session: Option, + }, } #[derive(Subcommand, Debug)] @@ -375,6 +421,33 @@ fn run(settings: &Settings, command: Command) -> Result { import::run(settings, import::Flags { campaign, from, from_endpoint, faculty, agent, session }) } Command::Persona { command } => persona::run(settings, *command), + Command::Activity { repos, after } => activity(settings, repos, after), + Command::Escalate { + campaign, + repo, + item, + why_it_can_wait, + label, + room, + dm, + heard_from, + faculty, + agent, + session, + } => escalate( + settings, + campaign, + repo, + item, + why_it_can_wait, + label, + room, + dm, + heard_from, + faculty, + agent, + session, + ), Command::Recall { command: RecallCommand::Dispatch { top_k, max_anchors, budget, deadline_ms } } => Ok(recall::dispatch( settings, &recall::Flags { top_k: top_k as usize, max_anchors: max_anchors as usize, budget: budget as usize, deadline_ms }, @@ -652,17 +725,22 @@ fn admit( let request = |instance: &Slug| { HuginnMindRequest::Admit(PipelineAdmissionBatch { instance: instance.clone(), provenance, documents }) }; - match settings.ask(request)? { + let response = settings.ask(request)?; + handle_admit_outcome(settings, response, &sent) +} + +fn handle_admit_outcome(settings: &Settings, response: HuginnMindResponse, sent: &[PipelineDocument]) -> Result { + match response { HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { receipt_id, committed_at, writes }) => { say(format_args!("Committed {receipt_id} at {committed_at}")); for write in &writes { say(format_args!("wrote {}", write.id.0)); } - read_back(settings, &sent) + read_back(settings, sent) } HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id }) => { say(format_args!("AlreadyAdmitted {receipt_id}")); - read_back(settings, &sent) + read_back(settings, sent) } HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal)) | HuginnMindResponse::Refused(refusal) => { Ok(refused(&refusal)) @@ -678,6 +756,163 @@ fn admit( } } +fn stewarded_repos(settings: &Settings) -> Result, Trouble> { + let owner = settings.client()?.instance().0.clone(); + let mut selection = door::selection_value(&serde_json::json!({ + "schemas": [PipelineKind::Stewardship.type_id()], + "fields": [{ "index": "in_force", "op": "any_of", "values": ["true"] }], + "limit": DEFAULT_LIMIT, + }))?; + let mut repos: Vec = Vec::new(); + loop { + let page = match settings.ask(|instance| HuginnMindRequest::Query { + instance: instance.clone(), + selection: selection.clone(), + semantic: None, + })? { + HuginnMindResponse::Query(page) => page, + HuginnMindResponse::Refused(refusal) => { + return Err(Trouble::Internal(format!("stewardship query refused: {refusal:?}"))); + } + other => return Err(unexpected(&other)), + }; + let PipelinePageItems::Headers(headers) = page.items else { + return Err(Trouble::Internal("stewardship query answered documents, not headers".into())); + }; + for header in headers { + if let PipelineFacts::Stewardship { instance, repo, .. } = header.facts + && instance.0 == owner + && !repos.iter().any(|held| held.0.eq_ignore_ascii_case(&repo.0)) + { + repos.push(repo); + if repos.len() >= ACTIVITY_REPOS_MAX { + return Ok(repos); + } + } + } + let Some(next) = page.next else { + return Ok(repos); + }; + selection.cursor = Some(next); + } +} + +fn activity(settings: &Settings, repos: Vec, after: Option) -> Result { + let repos = if repos.is_empty() { + stewarded_repos(settings)? + } else { + if repos.len() > ACTIVITY_REPOS_MAX { + return Err(Trouble::invalid(format!( + "at most {ACTIVITY_REPOS_MAX} repositories may be queried at once" + ))); + } + let mut parsed = Vec::with_capacity(repos.len()); + for raw in repos { + let repo = OrgRepo(raw); + repo.validate_org_repo() + .map_err(|refusal| Trouble::invalid(format!("--repo is not Org/Repo: {refusal:?}")))?; + if !parsed.iter().any(|held: &OrgRepo| held.0.eq_ignore_ascii_case(&repo.0)) { + parsed.push(repo); + } + } + parsed + }; + match settings.ask(|instance| HuginnMindRequest::StewardedActivity { + instance: instance.clone(), + repos, + after, + })? { + HuginnMindResponse::Activity(found) => { + say(render::activity(&found)); + Ok(0) + } + HuginnMindResponse::Refused(MindRefusal::Unavailable { detail }) => Err(Trouble::Unavailable(detail)), + HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)), + other => Err(unexpected(&other)), + } +} + +#[allow(clippy::too_many_arguments)] +fn escalate( + settings: &Settings, + campaign: String, + repo: String, + item: String, + why_it_can_wait: String, + label: Option, + room: Option, + dm: Option, + heard_from: Vec, + faculty: Faculty, + agent: String, + session: Option, +) -> Result { + let session = settings.session(session)?; + if !heard_from.is_empty() && room.is_none() && dm.is_none() { + return Err(Trouble::invalid("--heard-from requires --room or --dm")); + } + if item.trim().is_empty() { + return Err(Trouble::invalid("--item must not be blank")); + } + if why_it_can_wait.trim().is_empty() { + return Err(Trouble::invalid("--why-it-can-wait must not be blank")); + } + let campaign = Slug(campaign); + let label = Label(label.unwrap_or_else(|| { + format!("esc-{}-{}", chrono::Utc::now().timestamp_millis(), std::process::id()) + })); + let repo = OrgRepo(repo); + let item = Line(item); + let why_it_can_wait = Line(why_it_can_wait); + let origin = match (room, dm) { + (Some(rooms), None) => Some(MemoryOrigin::Room { + rooms: Short(rooms), + heard_from: heard_from.into_iter().map(Short).collect(), + }), + (None, Some(room)) => Some(MemoryOrigin::Direct { + room: Short(room), + with: heard_from.into_iter().map(Short).collect(), + }), + (None, None) => None, + (Some(_), Some(_)) => return Err(Trouble::invalid("--room and --dm cannot both be given")), + }; + let expected = PipelineDocument::FollowUp(PipelineFollowUp { + campaign: campaign.clone(), + label: label.clone(), + source: PipelineRef { + kind: PipelineKind::Campaign, + id: Short(format!("{}:campaign:self", campaign.0)), + }, + repo: repo.clone(), + locations: Vec::new(), + item: item.clone(), + why_it_can_wait: why_it_can_wait.clone(), + owner: Short("self-run".into()), + origin: origin.clone(), + }); + expected + .validate() + .map_err(|refusal| Trouble::invalid(format!("invalid escalation field: {refusal:?}")))?; + let provenance = PipelineProvenance { + faculty, + agent: Short(agent), + session: Short(session), + tool: Short(TOOL.to_string()), + imported_from: None, + }; + let response = settings.ask(|instance| HuginnMindRequest::EscalateGoal { + instance: instance.clone(), + provenance, + campaign, + label, + repo, + item, + why_it_can_wait, + origin, + })?; + handle_admit_outcome(settings, response, &[expected]) +} + /// The end-to-end check that the mind kept what was sent: one `keys` query, /// each stored document compared with the one sent. A difference is exit 5, /// not silence, whatever dropped it (an older leaf, a serde default, skew). diff --git a/crates/eureka-state/src/bin/huginn/render.rs b/crates/eureka-state/src/bin/huginn/render.rs index 5da647e..5ee34e1 100644 --- a/crates/eureka-state/src/bin/huginn/render.rs +++ b/crates/eureka-state/src/bin/huginn/render.rs @@ -3,7 +3,10 @@ use std::fmt::Write; use huginn_mind::eureka_pipeline::{PipelineResolution, ResolutionOutcome}; -use huginn_mind::{ChatHits, ChatWindow, SourceHits, IndexStatus, PersonaStatus, PipelineDocumentSummary, PipelineDocumentView, PipelineStatus, PipelineStatusSummary}; +use huginn_mind::{ + ChatHits, ChatWindow, IndexStatus, PersonaStatus, PipelineDocumentSummary, PipelineDocumentView, PipelineStatus, + PipelineStatusSummary, RepoActivity, RepoChange, SourceHits, +}; use serde::Serialize; use serde_json::Value; @@ -213,6 +216,47 @@ pub fn chat_window(found: &ChatWindow) -> String { out } +/// Forge activity as plain text: `head `, then events, open PRs, and +/// any `capped`, `unseen`, or `moved` repositories. +pub fn activity(found: &RepoActivity) -> String { + let mut out = format!("head {}\n", found.head); + for event in &found.events { + let what = match event.change { + RepoChange::Pushed { commits } => format!("pushed {commits}"), + RepoChange::Pr { number, action } => format!("pr #{number} {}", name_of(&action)), + }; + let _ = writeln!( + out, + "event {} {} {} {} {what}", + event.id, + crate::chat::shown(event.at), + event.repo.0, + event.actor.0 + ); + } + for pr in &found.open_prs { + let _ = writeln!( + out, + "open_pr {} #{} {} {}", + pr.repo.0, + pr.number, + pr.author.0, + crate::chat::shown(pr.updated_at) + ); + } + for repo in &found.capped { + let _ = writeln!(out, "capped {}", repo.0); + } + for repo in &found.unseen { + let _ = writeln!(out, "unseen {}", repo.0); + } + for moved in &found.moved { + let _ = writeln!(out, "moved {} -> {}", moved.from.0, moved.to.0); + } + out.pop(); + out +} + /// A fact as one token: a string, a number, a flag, a reference's id, or a /// list of those joined by commas. Anything deeper is not a header fact. fn scalar(value: &Value) -> Option { diff --git a/crates/eureka-state/tests/cli.rs b/crates/eureka-state/tests/cli.rs index 860f5ae..3272299 100644 --- a/crates/eureka-state/tests/cli.rs +++ b/crates/eureka-state/tests/cli.rs @@ -4035,3 +4035,249 @@ fn persona_bond_custom_kind_and_expired_intention_semantics() { assert_eq!(seed_after.code, 0, "{} {}", seed_after.out, seed_after.err); assert!(seed_after.out.contains("deru [my_custom]"), "{}", seed_after.out); } + +fn serve_with_persona( + root: TempDir, + mut daemon: huginn_daemon::Daemon, +) -> (Server, SocketAddr) { + let mut hub = huginn_daemon::serve::bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap(); + let mut persona_hub = huginn_daemon::serve::bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap(); + let addr = hub.local_addr().unwrap(); + let persona_addr = persona_hub.local_addr().unwrap(); + let stopping = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let loop_stopping = Arc::clone(&stopping); + let registry = huginn_daemon::serve::schema_registry().unwrap(); + let thread = std::thread::spawn(move || { + huginn_daemon::serve::run( + &mut daemon, + &mut hub, + Some(&mut persona_hub), + ®istry, + None, + &loop_stopping, + &huginn_daemon::ServeOptions::default(), + ) + .unwrap(); + }); + (Server { addr, stopping, thread: Some(thread), ended: Arc::default(), _root: Some(root) }, persona_addr) +} + +#[test] +fn huginn_escalate_and_activity_cli_round_trip() { + use huginn_mind::eureka_pipeline::{MemoryOrigin, PipelineFollowUp}; + use huginn_mind::{ + OpenPr, PipelineDocumentSummary, PipelineFacts, PipelineStatusSummary, PrAction, RepoActivity, RepoChange, + RepoEvent, RepoMoved, + }; + + // 1. Live daemon with Door::Persona: escalate commits FollowUp with server-pinned fields, + // read_back verifies, while plain `admit` is still refused with NotThisDoor, and + // `activity` exits 3 when the daemon has no forge. + let (root, daemon) = mind(vec![vec![campaign(), stewardship()]]); + let (_server, persona_addr) = serve_with_persona(root, daemon); + + let escalated = at( + persona_addr, + &[ + "escalate", + "--campaign", + CAMPAIGN, + "--repo", + REPO, + "--label", + "esc-cli-1", + "--item", + "Investigate mutex contention.", + "--why-it-can-wait", + "Next Self run can inspect.", + "--room", + "#swarm:gamecult.org", + "--heard-from", + "@meta:gamecult.org", + "--agent", + "spoofed-agent", + "--session", + "p-session-1", + ], + None, + ); + assert_eq!(escalated.code, 0, "{} {}", escalated.out, escalated.err); + assert!(escalated.out.contains("Committed mind-commit-"), "{}", escalated.out); + assert!(escalated.out.contains(&format!("wrote {CAMPAIGN}:follow_up:esc-cli-1")), "{}", escalated.out); + assert!(escalated.out.contains("read back 1 equal"), "{}", escalated.out); + + let viewed = at(persona_addr, &["view", &format!("{CAMPAIGN}:follow_up:esc-cli-1")], None); + assert_eq!(viewed.code, 0, "{} {}", viewed.out, viewed.err); + assert!(viewed.out.contains("Member/mind-persona session p-session-1"), "{}", viewed.out); + let raw = at(persona_addr, &["view", "--raw", &format!("{CAMPAIGN}:follow_up:esc-cli-1")], None); + assert_eq!(raw.code, 0, "{} {}", raw.out, raw.err); + let doc: PipelineDocument = serde_json::from_str(&raw.out).unwrap(); + let PipelineDocument::FollowUp(PipelineFollowUp { source, owner, locations, origin, .. }) = doc else { + panic!("expected FollowUp"); + }; + assert_eq!(owner.0, "self-run"); + assert!(locations.is_empty()); + assert_eq!(source, PipelineRef { kind: PipelineKind::Campaign, id: Short(format!("{CAMPAIGN}:campaign:self")) }); + assert_eq!( + origin, + Some(MemoryOrigin::Room { + rooms: Short("#swarm:gamecult.org".into()), + heard_from: vec![Short("@meta:gamecult.org".into())], + }) + ); + + // Omitting --label auto-generates a valid label and --dm sets Direct origin. + let dm_escalated = at( + persona_addr, + &[ + "escalate", + "--campaign", + CAMPAIGN, + "--repo", + REPO, + "--item", + "Follow up from DM.", + "--why-it-can-wait", + "Next Self run.", + "--dm", + "!dm:gamecult.org", + "--heard-from", + "@meta:gamecult.org", + "--session", + "p-session-2", + ], + None, + ); + assert_eq!(dm_escalated.code, 0, "{} {}", dm_escalated.out, dm_escalated.err); + assert!(dm_escalated.out.contains("read back 1 equal"), "{}", dm_escalated.out); + + // Admit still refuses over Door::Persona. + let dir = tempfile::tempdir().unwrap(); + let batch_file = write(&dir, "c.json", &json!([campaign_json()])); + let admit_refused = at(persona_addr, &admit_args(&batch_file), None); + assert_eq!(admit_refused.code, 1, "{} {}", admit_refused.out, admit_refused.err); + assert!(admit_refused.out.contains("NotThisDoor"), "{}", admit_refused.out); + + // escalate negative validations: no --json, no --heard-from without --room/--dm, no blank item. + for bad in [ + vec!["escalate", "--json", "--campaign", CAMPAIGN, "--repo", REPO, "--item", "x", "--why-it-can-wait", "y", "--session", "s"], + vec!["escalate", "--campaign", CAMPAIGN, "--repo", REPO, "--item", "x", "--why-it-can-wait", "y", "--heard-from", "@a", "--session", "s"], + vec!["escalate", "--campaign", CAMPAIGN, "--repo", REPO, "--item", " ", "--why-it-can-wait", "y", "--session", "s"], + ] { + let ran = at(persona_addr, &bad, None); + assert_eq!(ran.code, 2, "{bad:?}: {} {}", ran.out, ran.err); + } + + // activity against a daemon without a forge exits 3 (Unavailable). + let no_forge = at(persona_addr, &["activity"], None); + assert_eq!(no_forge.code, 3, "{} {}", no_forge.out, no_forge.err); + assert!(no_forge.err.starts_with("Unavailable: "), "{}", no_forge.err); + + // 2. Scripted server verifying Stewardship autodiscovery, --repo/--after, and plain-text rendering. + let seen = Arc::new(Mutex::new(Vec::::new())); + let sink = Arc::clone(&seen); + let activity_payload = RepoActivity { + head: 42, + events: vec![RepoEvent { + id: 41, + at: 1_765_000_000_000, + repo: OrgRepo("GameCult/Huginn".into()), + actor: Short("alice".into()), + change: RepoChange::Pr { number: 12, action: PrAction::Opened }, + }], + capped: vec![OrgRepo("GameCult/Capped".into())], + open_prs: vec![OpenPr { + repo: OrgRepo("GameCult/Huginn".into()), + number: 12, + author: Short("alice".into()), + updated_at: 1_765_000_000_000, + }], + unseen: vec![OrgRepo("GameCult/Secret".into())], + moved: vec![RepoMoved { + from: OrgRepo("GameCult/Old".into()), + to: OrgRepo("GameCult/New".into()), + }], + }; + let payload_for_srv = activity_payload.clone(); + let spy = scripted(move |message| { + let (_, request) = decode_request(message).unwrap(); + sink.lock().unwrap().push(request.clone()); + match request { + HuginnMindRequest::Query { .. } => { + let make_hdr = |id: &str, inst: &str, repo_name: &str| PipelineDocumentSummary { + id: PipelineRef { kind: PipelineKind::Stewardship, id: Short(id.into()) }, + status: PipelineStatusSummary::InForce, + admission: AdmissionFacts { + receipt_id: "r1".into(), + admitted_at: "2026-10-10T10:00:00Z".into(), + provenance: provenance(), + ordinal: 1, + }, + facts: PipelineFacts::Stewardship { + instance: slug(inst), + repo: OrgRepo(repo_name.into()), + sequence: 1, + assigned_on: Date("2026-10-10".into()), + note: "assigned".into(), + names: vec![], + }, + }; + let page = PipelineSelectionPage { + matched: 2, + as_of: 1, + next: None, + items: PipelinePageItems::Headers(vec![ + make_hdr(&format!("{INSTANCE}:stewardship:GameCult.Huginn.s1"), INSTANCE, "GameCult/Huginn"), + make_hdr("other-mind:stewardship:GameCult.Foreign.s1", "other-mind", "GameCult/Foreign"), + ]), + edges: None, + scores: None, + }; + answer("query", &HuginnMindResponse::Query(page)) + } + HuginnMindRequest::StewardedActivity { .. } => { + answer("stewarded_activity", &HuginnMindResponse::Activity(payload_for_srv.clone())) + } + other => panic!("unexpected request: {other:?}"), + } + }); + + let auto = at(spy.addr, &["activity"], None); + assert_eq!(auto.code, 0, "{} {}", auto.out, auto.err); + assert!(auto.out.contains("head 42"), "{}", auto.out); + assert!(auto.out.contains("event 41 "), "{}", auto.out); + assert!(auto.out.contains("GameCult/Huginn alice pr #12 Opened"), "{}", auto.out); + assert!(auto.out.contains("open_pr GameCult/Huginn #12 alice "), "{}", auto.out); + assert!(auto.out.contains("capped GameCult/Capped"), "{}", auto.out); + assert!(auto.out.contains("unseen GameCult/Secret"), "{}", auto.out); + assert!(auto.out.contains("moved GameCult/Old -> GameCult/New"), "{}", auto.out); + + let explicit = at(spy.addr, &["activity", "--repo", "GameCult/Epiphany", "--after", "10"], None); + assert_eq!(explicit.code, 0, "{} {}", explicit.out, explicit.err); + + let recorded = seen.lock().unwrap(); + assert_eq!(recorded.len(), 3, "{recorded:?}"); + assert!(matches!(&recorded[0], HuginnMindRequest::Query { .. })); + assert_eq!( + recorded[1], + HuginnMindRequest::StewardedActivity { + instance: slug(INSTANCE), + repos: vec![OrgRepo("GameCult/Huginn".into())], + after: None, + } + ); + assert_eq!( + recorded[2], + HuginnMindRequest::StewardedActivity { + instance: slug(INSTANCE), + repos: vec![OrgRepo("GameCult/Epiphany".into())], + after: Some(10), + } + ); + + // Negative activity flags: no --json, invalid --repo. + for bad in [vec!["activity", "--json"], vec!["activity", "--repo", "not-org-repo"]] { + let ran = at(spy.addr, &bad, None); + assert_eq!(ran.code, 2, "{bad:?}: {} {}", ran.out, ran.err); + } +} From 29f1926be3bfad7f5e7d812b705eb3fa6fd629f7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:19:42 +0100 Subject: [PATCH 03/12] Add mind_body::chat_gate and clap-free mind-chat CLI Add host Matrix mouth gate and dual-mode Engine (chat-gate.json atomic state, 0600 Unix socket outside bwrap, persona pinning, seen_event_id only on pending/tail display, RoomMoved refusal without blind cursor bump, 1800s unsettled pending_send + --resend, MIND_RUN_BACKSTOP via heartbeat::line_facts, UTC daily outbound cap) plus clap-free mind-chat. --- crates/mind-body/Cargo.toml | 4 + crates/mind-body/src/bin/mind-chat.rs | 317 +++++ crates/mind-body/src/chat_gate.rs | 1299 +++++++++++++++++++++ crates/mind-body/src/lib.rs | 1 + crates/mind-body/tests/public_surface.txt | 13 + 5 files changed, 1634 insertions(+) create mode 100644 crates/mind-body/src/bin/mind-chat.rs create mode 100644 crates/mind-body/src/chat_gate.rs diff --git a/crates/mind-body/Cargo.toml b/crates/mind-body/Cargo.toml index 5a77bdf..2e64aed 100644 --- a/crates/mind-body/Cargo.toml +++ b/crates/mind-body/Cargo.toml @@ -94,3 +94,7 @@ path = "src/bin/mind-persona.rs" [[bin]] name = "mind-heartbeat" path = "src/bin/mind-heartbeat.rs" + +[[bin]] +name = "mind-chat" +path = "src/bin/mind-chat.rs" diff --git a/crates/mind-body/src/bin/mind-chat.rs b/crates/mind-body/src/bin/mind-chat.rs new file mode 100644 index 0000000..6a6af27 --- /dev/null +++ b/crates/mind-body/src/bin/mind-chat.rs @@ -0,0 +1,317 @@ +//! `mind-chat`: dual-mode Matrix mouth gate and sandbox/host client CLI. +//! +//! Host gate mode (outside `bwrap`): +//! `mind-chat gate --instance --socket --state-dir --minds --operators --own-sender [--daily-cap ]` +//! +//! Client modes (sandboxed via `MIND_CHAT_SOCKET`, or direct host RUDP when unset): +//! `mind-chat pending [--ack]` +//! `mind-chat tail [--room ]` +//! `mind-chat say --room (--text | --resend )` +//! `mind-chat ack --through ` +//! `mind-chat mark-read --room --event --at ` +//! `mind-chat open-direct --user --text ` +//! `mind-chat status` + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{Context, Result, anyhow, bail}; +use chrono::Utc; +use eureka_pipeline::Slug; +use mind_body::chat_gate::{Answer, Config, Engine, Request, call_socket, serve_gate}; +use mind_body::chat_rudp::{RudpChat, connection_id}; + +const CHAT_TIMEOUT: Duration = Duration::from_secs(20); + +const USAGE: &str = "\ +usage: + mind-chat gate --instance --socket --state-dir --minds --operators --own-sender [--daily-cap ] + mind-chat pending [--ack] + mind-chat tail [--room ] + mind-chat say --room (--text | --resend ) + mind-chat ack --through + mind-chat mark-read --room --event --at + mind-chat open-direct --user --text + mind-chat status"; + +#[cfg(unix)] +fn restrict_umask() { + // SAFETY: umask only sets this process's file-creation mask. + unsafe { + libc::umask(0o077); + } +} + +#[cfg(not(unix))] +fn restrict_umask() {} + +#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")] +fn setting(name: &str) -> Option { + std::env::var(name).ok().filter(|value| !value.is_empty()) +} + +fn required_env(name: &str) -> Result { + setting(name).ok_or_else(|| anyhow!("{name} is not set")) +} + +fn split_csv(raw: &str) -> Vec { + raw.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect() +} + +fn now_ms() -> u64 { + u64::try_from(Utc::now().timestamp_millis()).unwrap_or(0) +} + +fn open_rudp(instance: &str) -> Result { + let endpoint_raw = required_env("BIFROST_CHAT_ENDPOINT")?; + let endpoint: SocketAddr = endpoint_raw + .strip_prefix("rudp://") + .and_then(|addr| addr.parse().ok()) + .ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://:"))?; + let key_path = required_env("BIFROST_CHAT_KEY_FILE")?; + let key_text = std::fs::read_to_string(&key_path) + .with_context(|| format!("failed to read BIFROST_CHAT_KEY_FILE {key_path}"))?; + let conn_id = connection_id(&key_text); + Ok(RudpChat::new(endpoint, conn_id, instance, CHAT_TIMEOUT).with_reply_link(true)) +} + +fn run_gate(args: &[String]) -> Result<()> { + let (mut instance, mut socket, mut state_dir, mut minds, mut operators, mut own_sender, mut daily_cap) = + (None, None, None, None, None, None, None); + let mut it = args.iter(); + while let Some(flag) = it.next() { + let mut val = || it.next().cloned().ok_or_else(|| anyhow!("{USAGE}")); + match flag.as_str() { + "--instance" => instance = Some(val()?), + "--socket" => socket = Some(PathBuf::from(val()?)), + "--state-dir" => state_dir = Some(PathBuf::from(val()?)), + "--minds" => minds = Some(split_csv(&val()?)), + "--operators" => operators = Some(split_csv(&val()?)), + "--own-sender" => own_sender = Some(val()?), + "--daily-cap" => { + let parsed: u32 = val()?.parse().map_err(|_| anyhow!("--daily-cap must be an integer"))?; + daily_cap = Some(parsed); + } + _ => bail!("{USAGE}"), + } + } + let instance = Slug(instance.ok_or_else(|| anyhow!("--instance is required"))?); + let socket = socket.ok_or_else(|| anyhow!("--socket is required"))?; + let state_dir = state_dir.ok_or_else(|| anyhow!("--state-dir is required"))?; + let minds = minds.unwrap_or_else(|| setting("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default()); + let operators = operators.unwrap_or_else(|| setting("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default()); + let own_sender = own_sender + .or_else(|| setting("MIND_PERSONA_SELF_SENDER")) + .ok_or_else(|| anyhow!("--own-sender is required"))?; + let daily_cap = match daily_cap { + Some(cap) => Some(cap), + None => setting("MIND_CHAT_DAILY_CAP") + .map(|v| v.parse::().map_err(|_| anyhow!("MIND_CHAT_DAILY_CAP must be an integer"))) + .transpose()?, + }; + let chat = open_rudp(&instance.0)?; + let config = Config { instance, state_dir, minds, operators, own_sender, daily_cap }; + serve_gate(config, chat, &socket, now_ms) +} + +fn parse_client_request(cmd: &str, args: &[String]) -> Result { + let mut it = args.iter(); + match cmd { + "pending" => { + let mut ack = false; + while let Some(flag) = it.next() { + match flag.as_str() { + "--ack" if !ack => ack = true, + _ => bail!("{USAGE}"), + } + } + Ok(Request::Pending { ack }) + } + "tail" => { + let mut room = None; + while let Some(flag) = it.next() { + match flag.as_str() { + "--room" => { + let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?; + if room.replace(val).is_some() { + bail!("{USAGE}"); + } + } + _ => bail!("{USAGE}"), + } + } + Ok(Request::Tail { room }) + } + "say" => { + let (mut room, mut text, mut resend) = (None, None, None); + while let Some(flag) = it.next() { + let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?; + let slot = match flag.as_str() { + "--room" => &mut room, + "--text" => &mut text, + "--resend" => &mut resend, + _ => bail!("{USAGE}"), + }; + if slot.replace(val).is_some() { + bail!("{USAGE}"); + } + } + let room = room.ok_or_else(|| anyhow!("{USAGE}"))?; + if text.is_some() == resend.is_some() { + bail!("{USAGE}"); + } + Ok(Request::Say { room, text, resend }) + } + "ack" => { + let mut through = None; + while let Some(flag) = it.next() { + match flag.as_str() { + "--through" => { + let raw = it.next().ok_or_else(|| anyhow!("{USAGE}"))?; + let parsed = raw.parse::().map_err(|_| anyhow!("--through must be u64"))?; + if through.replace(parsed).is_some() { + bail!("{USAGE}"); + } + } + _ => bail!("{USAGE}"), + } + } + Ok(Request::Ack { through: through.ok_or_else(|| anyhow!("{USAGE}"))? }) + } + "mark-read" => { + let (mut room, mut event, mut at) = (None, None, None); + while let Some(flag) = it.next() { + let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?; + match flag.as_str() { + "--room" => { + if room.replace(val).is_some() { + bail!("{USAGE}"); + } + } + "--event" => { + if event.replace(val).is_some() { + bail!("{USAGE}"); + } + } + "--at" => { + let parsed = val.parse::().map_err(|_| anyhow!("--at must be u64"))?; + if at.replace(parsed).is_some() { + bail!("{USAGE}"); + } + } + _ => bail!("{USAGE}"), + } + } + Ok(Request::MarkRead { + room: room.ok_or_else(|| anyhow!("{USAGE}"))?, + event: event.ok_or_else(|| anyhow!("{USAGE}"))?, + at_unix_ms: at.ok_or_else(|| anyhow!("{USAGE}"))?, + }) + } + "open-direct" => { + let (mut user, mut text) = (None, None); + while let Some(flag) = it.next() { + let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?; + let slot = match flag.as_str() { + "--user" => &mut user, + "--text" => &mut text, + _ => bail!("{USAGE}"), + }; + if slot.replace(val).is_some() { + bail!("{USAGE}"); + } + } + Ok(Request::OpenDirect { + user: user.ok_or_else(|| anyhow!("{USAGE}"))?, + text: text.ok_or_else(|| anyhow!("{USAGE}"))?, + }) + } + "status" => { + if !args.is_empty() { + bail!("{USAGE}"); + } + Ok(Request::Status) + } + _ => bail!("{USAGE}"), + } +} + +enum DirectFailure { + Misconfigured(anyhow::Error), + Unavailable(anyhow::Error), +} + +fn run_direct(request: Request) -> std::result::Result { + let load_config = || -> Result<(Config, RudpChat)> { + let instance = Slug(required_env("EUREKA_INSTANCE")?); + instance.validate_slug().map_err(|r| anyhow!("invalid EUREKA_INSTANCE: {r:?}"))?; + let state_dir = PathBuf::from(required_env("STATE_DIRECTORY")?); + let minds = setting("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default(); + let operators = setting("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default(); + let own_sender = setting("MIND_PERSONA_SELF_SENDER").unwrap_or_else(|| format!("@{}:gamecult.org", instance.0)); + let daily_cap = setting("MIND_CHAT_DAILY_CAP") + .map(|v| v.parse::().map_err(|_| anyhow!("MIND_CHAT_DAILY_CAP must be an integer"))) + .transpose()?; + let chat = open_rudp(&instance.0)?; + Ok((Config { instance, state_dir, minds, operators, own_sender, daily_cap }, chat)) + }; + let (config, chat) = load_config().map_err(DirectFailure::Misconfigured)?; + let mut engine = Engine::open(config, chat, now_ms()).map_err(DirectFailure::Unavailable)?; + engine.handle(request, now_ms()).map_err(DirectFailure::Unavailable) +} + +#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments")] +fn main() { + restrict_umask(); + let args: Vec = std::env::args().skip(1).collect(); + if args.is_empty() || matches!(args[0].as_str(), "-h" | "--help" | "help") { + println!("{USAGE}"); + return; + } + if args[0] == "gate" { + if let Err(error) = run_gate(&args[1..]) { + eprintln!("mind-chat: {error:#}"); + std::process::exit(2); + } + return; + } + + let request = match parse_client_request(&args[0], &args[1..]) { + Ok(req) => req, + Err(error) => { + eprintln!("InvalidInput: {error:#}"); + std::process::exit(2); + } + }; + + let answer = if let Some(socket) = setting("MIND_CHAT_SOCKET") { + match call_socket(Path::new(&socket), &request) { + Ok(ans) => ans, + Err(error) => { + eprintln!("Unavailable: {error:#}"); + std::process::exit(3); + } + } + } else { + match run_direct(request) { + Ok(ans) => ans, + Err(DirectFailure::Misconfigured(error)) => { + eprintln!("Misconfigured: {error:#}"); + std::process::exit(2); + } + Err(DirectFailure::Unavailable(error)) => { + eprintln!("Unavailable: {error:#}"); + std::process::exit(3); + } + } + }; + + if !answer.stdout.is_empty() { + println!("{}", answer.stdout); + } + if !answer.stderr.is_empty() { + eprintln!("{}", answer.stderr); + } + std::process::exit(i32::from(answer.exit)); +} diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs new file mode 100644 index 0000000..9b9c327 --- /dev/null +++ b/crates/mind-body/src/chat_gate.rs @@ -0,0 +1,1299 @@ +//! Host Matrix mouth gate and shared dual-mode `Engine` for `mind-chat`. +//! +//! Keeps `BIFROST_CHAT_KEY_FILE` outside `bwrap` and pins `persona = instance` +//! on every mouth request so sandboxed tools cannot impersonate peers. Persists +//! per-room `seen_event_id` (updated only when `pending` or `tail` displays +//! room events, never bumped blindly on `RoomMoved`), unsettled 1800s +//! `pending_send`, `MIND_RUN_BACKSTOP` (via `heartbeat::line_facts`), and the +//! UTC daily outbound send cap atomically in `/chat-gate.json`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, anyhow, bail, ensure}; +use chrono::DateTime; +use eureka_pipeline::Slug; +use serde::{Deserialize, Serialize}; + +use crate::chat_client::{ + Chat, ChatDelivery, ChatOpenDirectRequest, ChatRead, ChatSendRequest, DirectOutcome, MouthRefused, Reading, + Refusal, SendBasis, TailLine, reply_warnings, +}; +use crate::heartbeat::{EXCHANGE_MINUTES, FactLine, MIND_RUN_BACKSTOP, line_facts}; + +/// Canonical state file inside `state_dir`. +pub const STATE_FILE: &str = "chat-gate.json"; +/// How long an unsettled send stays open for `--resend` (seconds). +pub const UNSETTLED_WINDOW_S: i64 = 1800; + +const UNSETTLED_WINDOW_MS: u64 = (UNSETTLED_WINDOW_S as u64) * 1000; +const ROOM_LINES_CAP: usize = 32; + +/// Host gate / engine configuration. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Config { + pub instance: Slug, + pub state_dir: PathBuf, + pub minds: Vec, + pub operators: Vec, + pub own_sender: String, + pub daily_cap: Option, +} + +/// One client operation sent to `Engine` (either directly or over the Unix gate socket). +/// Intentionally carries no `persona` field: the host engine owns `config.instance`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] +pub enum Request { + Pending { ack: bool }, + Tail { room: Option }, + Say { room: String, text: Option, resend: Option }, + Ack { through: u64 }, + MarkRead { room: String, event: String, at_unix_ms: u64 }, + OpenDirect { user: String, text: String }, + Status, +} + +/// Plain-text response and process exit code (`0` ok, `1` refused, `2` invalid input, `3` unavailable). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Answer { + pub exit: u8, + pub stdout: String, + pub stderr: String, +} + +impl Answer { + fn ok(stdout: impl Into) -> Self { + Self { exit: 0, stdout: stdout.into(), stderr: String::new() } + } + + fn refused(stdout: impl Into) -> Self { + Self { exit: 1, stdout: stdout.into(), stderr: String::new() } + } + + fn invalid(stderr: impl Into) -> Self { + Self { exit: 2, stdout: String::new(), stderr: stderr.into() } + } + + fn unavailable(stderr: impl Into) -> Self { + Self { exit: 3, stdout: String::new(), stderr: stderr.into() } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct GateState { + instance: String, + after_seq: u64, + since_unix_ms: u64, + next_send_seq: u64, + daily_says: DailySays, + #[serde(default)] + aliases: BTreeMap, + #[serde(default)] + rooms: BTreeMap, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +struct DailySays { + utc_day: String, + count: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +struct RoomState { + seen_event_id: Option, + seen_at_unix_ms: u64, + pending_send: Option, + #[serde(default)] + lines: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct PendingSend { + request_id: String, + text: String, + basis: Option, + started_unix_ms: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct RecordedLine { + event_id: String, + sender: String, + at_unix_ms: u64, +} + +/// Stateful host gate engine driving a `Chat` mouth. +pub struct Engine { + config: Config, + chat: C, + state_path: PathBuf, + state: GateState, + warned_replies: BTreeSet, +} + +impl Engine { + /// Opens (or initializes) `/chat-gate.json` for `config.instance`. + pub fn open(config: Config, chat: C, now_ms: u64) -> Result { + config.instance.validate_slug().map_err(|refusal| anyhow!("invalid instance slug: {refusal:?}"))?; + ensure!(!config.own_sender.trim().is_empty(), "own-sender must not be empty"); + fs::create_dir_all(&config.state_dir) + .with_context(|| format!("failed to create state dir {}", config.state_dir.display()))?; + let state_path = config.state_dir.join(STATE_FILE); + let state = if state_path.exists() { + let text = fs::read_to_string(&state_path) + .with_context(|| format!("failed to read {}", state_path.display()))?; + let loaded: GateState = serde_json::from_str(&text) + .with_context(|| format!("failed to parse {}", state_path.display()))?; + ensure!( + loaded.instance == config.instance.0, + "chat-gate state belongs to instance {}, not {}", + loaded.instance, + config.instance.0 + ); + loaded + } else { + let fresh = GateState { + instance: config.instance.0.clone(), + after_seq: 0, + since_unix_ms: now_ms, + next_send_seq: 1, + daily_says: DailySays { utc_day: utc_day(now_ms), count: 0 }, + aliases: BTreeMap::new(), + rooms: BTreeMap::new(), + }; + write_state_atomic(&state_path, &fresh)?; + fresh + }; + Ok(Self { config, chat, state_path, state, warned_replies: BTreeSet::new() }) + } + + /// Executes one gate request against the mouth and updates state atomically. + pub fn handle(&mut self, request: Request, now_ms: u64) -> Result { + match request { + Request::Pending { ack } => self.pending(ack), + Request::Tail { room } => self.tail(room), + Request::Say { room, text, resend } => self.say(room, text, resend, now_ms), + Request::Ack { through } => self.ack(through), + Request::MarkRead { room, event, at_unix_ms } => self.mark_read(room, event, at_unix_ms), + Request::OpenDirect { user, text } => self.open_direct(user, text, now_ms), + Request::Status => Ok(Answer::ok(self.render_status(now_ms))), + } + } + + fn all_minds(&self) -> Vec { + let mut minds = self.config.minds.clone(); + if !minds.iter().any(|mind| mind == &self.config.own_sender) { + minds.push(self.config.own_sender.clone()); + } + minds + } + + fn canonical_room(&self, room: &str) -> String { + self.state.aliases.get(room).cloned().unwrap_or_else(|| room.to_string()) + } + + fn pending(&mut self, ack: bool) -> Result { + let pending = match self.chat.pending(self.state.after_seq) { + Ok(pending) => pending, + Err(err) => return Ok(mouth_error_answer(&err)), + }; + if pending.persona != self.config.instance.0 { + return Ok(Answer::refused(format!( + "Refused PersonaMismatch: mouth answered for {}, expected {}", + pending.persona, self.config.instance.0 + ))); + } + + let mut lines = Vec::new(); + for warning in reply_warnings(&pending, &mut self.warned_replies) { + lines.push(format!("warning {warning}")); + } + + let minds = self.all_minds(); + let window_ms = u64::try_from(EXCHANGE_MINUTES * 60_000).unwrap_or(0); + let fact_lines = collect_delivery_fact_lines(&pending.deliveries); + let facts = line_facts( + &fact_lines.iter().map(|(line, _)| *line).collect::>(), + &self.config.own_sender, + &minds, + &[], + window_ms, + ); + let batch_hit_backstop = facts.iter().any(|fact| fact.mind_run >= MIND_RUN_BACKSTOP); + + let mut max_seq = self.state.after_seq; + let mut touched_rooms = BTreeSet::new(); + for delivery in &pending.deliveries { + max_seq = max_seq.max(delivery.seq); + if delivery.room_id != delivery.room_alias { + self.state.aliases.insert(delivery.room_id.clone(), delivery.room_alias.clone()); + } + let room_key = delivery.room_alias.clone(); + touched_rooms.insert(room_key.clone()); + let room = self.state.rooms.entry(room_key).or_default(); + for ctx in &delivery.context { + record_line( + room, + RecordedLine { + event_id: format!("ctx:{}:{}", ctx.at_unix_ms, ctx.sender), + sender: ctx.sender.clone(), + at_unix_ms: ctx.at_unix_ms, + }, + true, + ); + } + record_line( + room, + RecordedLine { + event_id: delivery.event_id.clone(), + sender: delivery.sender.clone(), + at_unix_ms: delivery.at_unix_ms, + }, + false, + ); + advance_seen(room, &delivery.event_id, delivery.at_unix_ms); + lines.push(format_delivery(delivery)); + } + + if pending.deliveries.is_empty() { + lines.push("none".to_string()); + } + for gap in &pending.tail_gaps { + lines.push(format!("tail_gap {gap}")); + } + let trailing_hit_backstop = touched_rooms.iter().any(|room_key| { + let Some(room) = self.state.rooms.get(room_key) else { return false }; + let last_at = room.lines.last().map(|line| line.at_unix_ms).unwrap_or(0); + trailing_mind_run(room, room_key, &self.config.own_sender, &minds, last_at) >= MIND_RUN_BACKSTOP + }); + if batch_hit_backstop || trailing_hit_backstop { + lines.push(format!("backstop: MIND_RUN_BACKSTOP ({MIND_RUN_BACKSTOP}) reached")); + } + + if ack && max_seq > self.state.after_seq { + if let Err(err) = self.chat.ack(max_seq) { + write_state_atomic(&self.state_path, &self.state)?; + return Ok(mouth_error_answer(&err)); + } + self.state.after_seq = max_seq; + lines.push(format!("acked {max_seq}")); + } + write_state_atomic(&self.state_path, &self.state)?; + Ok(Answer::ok(lines.join("\n"))) + } + + fn tail(&mut self, room_filter: Option) -> Result { + if let Some(ref room) = room_filter + && room.trim().is_empty() + { + return Ok(Answer::invalid("InvalidInput: --room must not be blank")); + } + let pending = match self.chat.pending(self.state.after_seq) { + Ok(pending) => pending, + Err(err) => return Ok(mouth_error_answer(&err)), + }; + if pending.persona != self.config.instance.0 { + return Ok(Answer::refused(format!( + "Refused PersonaMismatch: mouth answered for {}, expected {}", + pending.persona, self.config.instance.0 + ))); + } + + let canonical_filter = room_filter.as_deref().map(|r| self.canonical_room(r)); + let mut lines = Vec::new(); + let tail_entries = pending.tail.unwrap_or_default(); + for entry in &tail_entries { + if let Some(ref filter) = canonical_filter + && &entry.room != filter + && room_filter.as_deref() != Some(entry.room.as_str()) + { + continue; + } + let room = self.state.rooms.entry(entry.room.clone()).or_default(); + record_line( + room, + RecordedLine { + event_id: entry.event_id.clone(), + sender: entry.sender.clone(), + at_unix_ms: entry.at_unix_ms, + }, + false, + ); + advance_seen(room, &entry.event_id, entry.at_unix_ms); + lines.push(format_tail_line(entry)); + } + + if lines.is_empty() { + lines.push("none".to_string()); + } + for gap in &pending.tail_gaps { + if let Some(ref filter) = canonical_filter + && gap != filter + && room_filter.as_deref() != Some(gap.as_str()) + { + continue; + } + lines.push(format!("tail_gap {gap}")); + } + + write_state_atomic(&self.state_path, &self.state)?; + Ok(Answer::ok(lines.join("\n"))) + } + + fn say(&mut self, room_arg: String, text: Option, resend: Option, now_ms: u64) -> Result { + let room_arg = room_arg.trim().to_string(); + if room_arg.is_empty() { + return Ok(Answer::invalid("InvalidInput: --room must not be blank")); + } + if text.is_some() == resend.is_some() { + return Ok(Answer::invalid("InvalidInput: pass exactly one of --text or --resend")); + } + + let room_key = self.canonical_room(&room_arg); + let is_resend = resend.is_some(); + let send_request = if let Some(resend_id) = resend { + let pending = match self.state.rooms.get(&room_key).and_then(|r| r.pending_send.clone()) { + Some(pending) => pending, + None => { + return Ok(Answer::refused(format!( + "Refused ResendUnknown: no unsettled pending send for {room_arg}" + ))); + } + }; + if pending.request_id != resend_id { + return Ok(Answer::refused(format!( + "Refused ResendUnknown: unsettled pending send is {} not {resend_id}", + pending.request_id + ))); + } + if now_ms.saturating_sub(pending.started_unix_ms) >= UNSETTLED_WINDOW_MS { + if let Some(room) = self.state.rooms.get_mut(&room_key) { + room.pending_send = None; + } + write_state_atomic(&self.state_path, &self.state)?; + return Ok(Answer::refused(format!( + "Refused ResendUnknown: pending send {resend_id} exceeded {UNSETTLED_WINDOW_S}s window" + ))); + } + ChatSendRequest { + request_id: pending.request_id, + persona: self.config.instance.0.clone(), + room_alias: room_arg.clone(), + text: pending.text, + basis: pending.basis, + resend: true, + } + } else { + let text = text.unwrap_or_default(); + if text.trim().is_empty() { + return Ok(Answer::invalid("InvalidInput: --text must not be blank")); + } + if let Some(existing) = self.state.rooms.get(&room_key).and_then(|r| r.pending_send.clone()) { + if now_ms.saturating_sub(existing.started_unix_ms) < UNSETTLED_WINDOW_MS { + return Ok(Answer::refused(format!( + "Refused room_unsettled: pending send {} is unsettled for {room_arg}; retry with --resend {}", + existing.request_id, existing.request_id + ))); + } + if let Some(room) = self.state.rooms.get_mut(&room_key) { + room.pending_send = None; + } + write_state_atomic(&self.state_path, &self.state)?; + } + + if let Some(refused) = self.check_daily_cap(now_ms) { + return Ok(refused); + } + + let minds = self.all_minds(); + if let Some(room) = self.state.rooms.get(&room_key) { + let run = trailing_mind_run(room, &room_key, &self.config.own_sender, &minds, now_ms); + if run >= MIND_RUN_BACKSTOP { + return Ok(Answer::refused(format!( + "Refused mind_run_backstop: {run} consecutive Mind lines in {room_arg} within {EXCHANGE_MINUTES}m" + ))); + } + } + + let request_id = format!("mc-{now_ms}-{}", self.state.next_send_seq); + self.state.next_send_seq += 1; + let seen_event_id = self.state.rooms.get(&room_key).and_then(|r| r.seen_event_id.clone()); + let basis = SendBasis { seen_event_id, since_unix_ms: self.state.since_unix_ms }; + let pending = PendingSend { + request_id: request_id.clone(), + text: text.clone(), + basis: Some(basis.clone()), + started_unix_ms: now_ms, + }; + self.state.rooms.entry(room_key.clone()).or_default().pending_send = Some(pending); + write_state_atomic(&self.state_path, &self.state)?; + + ChatSendRequest { + request_id, + persona: self.config.instance.0.clone(), + room_alias: room_arg.clone(), + text, + basis: Some(basis), + resend: false, + } + }; + + let req_id = send_request.request_id.clone(); + match self.chat.send(&send_request) { + Ok(receipt) => match (receipt.event_id, receipt.refusal) { + (_, Some(refusal)) => match refusal.reading(is_resend) { + Reading::NoAnswer => Ok(Answer::unavailable(format!( + "Unavailable: {} on {req_id}; retry with --resend {req_id}", + refusal.name() + ))), + Reading::NotSent | Reading::Unknown | Reading::Declined => { + if let Some(room) = self.state.rooms.get_mut(&room_key) { + room.pending_send = None; + } + write_state_atomic(&self.state_path, &self.state)?; + if refusal == Refusal::RoomMoved { + let newer = if receipt.newer.is_empty() { + "-".to_string() + } else { + receipt.newer.join(",") + }; + Ok(Answer::refused(format!("Refused RoomMoved newer={newer}"))) + } else { + Ok(Answer::refused(format!("Refused {}", refusal.name()))) + } + } + }, + (Some(event_id), None) => { + let room = self.state.rooms.entry(room_key).or_default(); + room.pending_send = None; + record_line( + room, + RecordedLine { + event_id: event_id.clone(), + sender: self.config.own_sender.clone(), + at_unix_ms: now_ms, + }, + false, + ); + self.increment_daily_says(now_ms); + write_state_atomic(&self.state_path, &self.state)?; + Ok(Answer::ok(format!("Posted {event_id} request_id={req_id}"))) + } + (None, None) => { + if let Some(room) = self.state.rooms.get_mut(&room_key) { + room.pending_send = None; + } + write_state_atomic(&self.state_path, &self.state)?; + let reason = if is_resend { "ResendUnknown" } else { "NotSent" }; + Ok(Answer::refused(format!("Refused {reason}"))) + } + }, + Err(err) => { + if let Some(MouthRefused(refusal)) = err.downcast_ref::() { + match refusal.reading(is_resend) { + Reading::NoAnswer => Ok(Answer::unavailable(format!( + "Unavailable: {} on {req_id}; retry with --resend {req_id}", + refusal.name() + ))), + Reading::NotSent | Reading::Unknown | Reading::Declined => { + if let Some(room) = self.state.rooms.get_mut(&room_key) { + room.pending_send = None; + } + write_state_atomic(&self.state_path, &self.state)?; + Ok(Answer::refused(format!("Refused {}", refusal.name()))) + } + } + } else { + Ok(Answer::unavailable(format!( + "Unavailable: {err:#}; retry with --resend {req_id}" + ))) + } + } + } + } + + fn ack(&mut self, through: u64) -> Result { + if let Err(err) = self.chat.ack(through) { + return Ok(mouth_error_answer(&err)); + } + self.state.after_seq = self.state.after_seq.max(through); + write_state_atomic(&self.state_path, &self.state)?; + Ok(Answer::ok(format!("Acked {through}"))) + } + + fn mark_read(&mut self, room: String, event: String, at_unix_ms: u64) -> Result { + let room = room.trim().to_string(); + let event = event.trim().to_string(); + if room.is_empty() || event.is_empty() { + return Ok(Answer::invalid("InvalidInput: --room and --event must not be blank")); + } + let read = ChatRead { + persona: self.config.instance.0.clone(), + room: room.clone(), + event_id: event.clone(), + at_unix_ms, + }; + if let Err(err) = self.chat.read(&read) { + return Ok(mouth_error_answer(&err)); + } + Ok(Answer::ok(format!("Read {room} {event}"))) + } + + fn open_direct(&mut self, user: String, text: String, now_ms: u64) -> Result { + let user = user.trim().to_string(); + if user.is_empty() || text.trim().is_empty() { + return Ok(Answer::invalid("InvalidInput: --user and --text must not be blank")); + } + if let Some(refused) = self.check_daily_cap(now_ms) { + return Ok(refused); + } + let request_id = format!("od-{now_ms}-{}", self.state.next_send_seq); + self.state.next_send_seq += 1; + write_state_atomic(&self.state_path, &self.state)?; + + let request = ChatOpenDirectRequest { + request_id, + persona: self.config.instance.0.clone(), + user_id: user, + text, + }; + let receipt = match self.chat.open_direct(&request) { + Ok(receipt) => receipt, + Err(err) => return Ok(mouth_error_answer(&err)), + }; + match receipt.outcome { + DirectOutcome::Opened => { + self.increment_daily_says(now_ms); + write_state_atomic(&self.state_path, &self.state)?; + Ok(Answer::ok(format!( + "Opened room={} event={}", + receipt.room_id.as_deref().unwrap_or("-"), + receipt.event_id.as_deref().unwrap_or("-") + ))) + } + DirectOutcome::Existing => Ok(Answer::ok(format!( + "Existing room={} event={}", + receipt.room_id.as_deref().unwrap_or("-"), + receipt.event_id.as_deref().unwrap_or("-") + ))), + DirectOutcome::SendFailed => Ok(Answer::unavailable("Unavailable: SendFailed")), + other => Ok(Answer::refused(format!("Refused {}", other.name()))), + } + } + + fn check_daily_cap(&self, now_ms: u64) -> Option { + let cap = self.config.daily_cap?; + let today = utc_day(now_ms); + let used = if self.state.daily_says.utc_day == today { self.state.daily_says.count } else { 0 }; + (used >= cap).then(|| Answer::refused(format!("Refused daily_cap: {used}/{cap} outbound sends on {today}"))) + } + + fn increment_daily_says(&mut self, now_ms: u64) { + let today = utc_day(now_ms); + if self.state.daily_says.utc_day == today { + self.state.daily_says.count += 1; + } else { + self.state.daily_says = DailySays { utc_day: today, count: 1 }; + } + } + + fn render_status(&self, now_ms: u64) -> String { + let today = utc_day(now_ms); + let used = if self.state.daily_says.utc_day == today { self.state.daily_says.count } else { 0 }; + let cap = self.config.daily_cap.map_or_else(|| "none".to_string(), |c| c.to_string()); + let mut out = format!( + "instance {}\nafter_seq {}\nsince_unix_ms {}\ndaily_says {}/{}\n", + self.state.instance, self.state.after_seq, self.state.since_unix_ms, used, cap + ); + let minds = self.all_minds(); + for (room_key, room) in &self.state.rooms { + let seen = room.seen_event_id.as_deref().unwrap_or("-"); + let pending = room.pending_send.as_ref().map_or("-", |p| p.request_id.as_str()); + let run = trailing_mind_run(room, room_key, &self.config.own_sender, &minds, now_ms); + out.push_str(&format!("room {room_key} seen={seen} pending={pending} mind_run={run}\n")); + } + out.pop(); + out + } +} + +/// Runs the host gate on a `0600` Unix socket until stopped or an I/O error occurs. +pub fn serve_gate(config: Config, chat: impl Chat, socket: &Path, now_ms: impl Fn() -> u64) -> Result<()> { + socket::serve(config, chat, socket, now_ms, None) +} + +/// Sends one `Request` to a running `mind-chat gate` Unix socket. +pub fn call_socket(socket: &Path, request: &Request) -> Result { + socket::call(socket, request) +} + +#[cfg(unix)] +mod socket { + use std::fs::{self, Permissions}; + use std::io::{BufRead, BufReader, Read, Write}; + use std::os::unix::fs::PermissionsExt; + use std::os::unix::net::{UnixListener, UnixStream}; + use std::path::Path; + use std::time::Duration; + + use anyhow::{Context, Result}; + + use super::{Answer, Config, Engine, Request}; + use crate::chat_client::Chat; + + const MAX_LINE_BYTES: u64 = 1024 * 1024; + const IO_TIMEOUT: Duration = Duration::from_secs(30); + + pub(super) fn serve( + config: Config, + chat: impl Chat, + socket: &Path, + now_ms: impl Fn() -> u64, + max_requests: Option, + ) -> Result<()> { + let mut engine = Engine::open(config, chat, now_ms())?; + if let Some(parent) = socket.parent() + && !parent.as_os_str().is_empty() + { + fs::create_dir_all(parent).with_context(|| format!("failed to create {}", parent.display()))?; + } + if socket.exists() { + fs::remove_file(socket).with_context(|| format!("failed to remove stale socket {}", socket.display()))?; + } + let listener = UnixListener::bind(socket) + .with_context(|| format!("failed to bind chat gate socket {}", socket.display()))?; + fs::set_permissions(socket, Permissions::from_mode(0o600)) + .with_context(|| format!("failed to chmod 0600 {}", socket.display()))?; + + let mut served = 0usize; + for stream in listener.incoming() { + let mut stream = stream.context("accept failed on chat gate socket")?; + let _ = stream.set_read_timeout(Some(IO_TIMEOUT)); + let _ = stream.set_write_timeout(Some(IO_TIMEOUT)); + let answer = handle_stream(&mut engine, &stream, &now_ms); + let encoded = serde_json::to_string(&answer)?; + let _ = writeln!(stream, "{encoded}").and_then(|()| stream.flush()); + served += 1; + if max_requests.is_some_and(|max| served >= max) { + break; + } + } + Ok(()) + } + + fn handle_stream(engine: &mut Engine, stream: &UnixStream, now_ms: &dyn Fn() -> u64) -> Answer { + let mut reader = BufReader::new(stream.take(MAX_LINE_BYTES)); + let mut line = String::new(); + if let Err(err) = reader.read_line(&mut line) { + return Answer::unavailable(format!("Unavailable: socket read failed: {err}")); + } + let request: Request = match serde_json::from_str(&line) { + Ok(request) => request, + Err(err) => return Answer::invalid(format!("InvalidInput: malformed gate request: {err}")), + }; + match engine.handle(request, now_ms()) { + Ok(answer) => answer, + Err(err) => Answer::unavailable(format!("Unavailable: {err:#}")), + } + } + + pub(super) fn call(socket: &Path, request: &Request) -> Result { + let mut stream = UnixStream::connect(socket) + .with_context(|| format!("could not connect to chat gate socket {}", socket.display()))?; + let _ = stream.set_read_timeout(Some(IO_TIMEOUT)); + let _ = stream.set_write_timeout(Some(IO_TIMEOUT)); + let encoded = serde_json::to_string(request)?; + writeln!(stream, "{encoded}")?; + stream.flush()?; + let mut reader = BufReader::new(stream.take(MAX_LINE_BYTES)); + let mut line = String::new(); + reader.read_line(&mut line)?; + serde_json::from_str(&line).context("chat gate returned invalid JSON answer") + } +} + +#[cfg(not(unix))] +mod socket { + use std::path::Path; + + use anyhow::{Result, bail}; + + use super::{Answer, Config, Request}; + use crate::chat_client::Chat; + + pub(super) fn serve( + _config: Config, + _chat: impl Chat, + _socket: &Path, + _now_ms: impl Fn() -> u64, + _max_requests: Option, + ) -> Result<()> { + bail!("mind-chat Unix socket gate is only supported on Unix") + } + + pub(super) fn call(_socket: &Path, _request: &Request) -> Result { + bail!("mind-chat Unix socket gate is only supported on Unix") + } +} + +fn mouth_error_answer(err: &anyhow::Error) -> Answer { + if let Some(MouthRefused(refusal)) = err.downcast_ref::() { + Answer::refused(format!("Refused {}", refusal.name())) + } else { + Answer::unavailable(format!("Unavailable: {err:#}")) + } +} + +fn advance_seen(room: &mut RoomState, event_id: &str, at_unix_ms: u64) { + if room.seen_event_id.is_none() || at_unix_ms >= room.seen_at_unix_ms { + room.seen_event_id = Some(event_id.to_string()); + room.seen_at_unix_ms = at_unix_ms; + } +} + +fn record_line(room: &mut RoomState, line: RecordedLine, is_context: bool) { + if is_context { + if room.lines.iter().any(|held| held.at_unix_ms == line.at_unix_ms && held.sender == line.sender) { + return; + } + } else { + room.lines.retain(|held| { + held.event_id != line.event_id + && !(held.event_id.starts_with("ctx:") + && held.at_unix_ms == line.at_unix_ms + && held.sender == line.sender) + }); + } + if !room.lines.iter().any(|held| held.event_id == line.event_id) { + room.lines.push(line); + room.lines.sort_by_key(|held| held.at_unix_ms); + if room.lines.len() > ROOM_LINES_CAP { + let drop_count = room.lines.len() - ROOM_LINES_CAP; + room.lines.drain(..drop_count); + } + } +} + +fn trailing_mind_run(room: &RoomState, room_key: &str, own_sender: &str, minds: &[String], now_ms: u64) -> usize { + let window_ms = u64::try_from(EXCHANGE_MINUTES * 60_000).unwrap_or(0); + let mut fact_lines: Vec> = room + .lines + .iter() + .map(|line| FactLine { sender: &line.sender, room: room_key, at_ms: line.at_unix_ms }) + .collect(); + fact_lines.push(FactLine { sender: own_sender, room: room_key, at_ms: now_ms }); + line_facts(&fact_lines, own_sender, minds, &[], window_ms) + .last() + .map_or(0, |facts| facts.mind_run) +} + +fn collect_delivery_fact_lines<'a>(deliveries: &'a [ChatDelivery]) -> Vec<(FactLine<'a>, Option)> { + let mut lines: Vec<(FactLine<'a>, Option)> = Vec::new(); + for (index, delivery) in deliveries.iter().enumerate() { + let room = delivery.room_alias.as_str(); + for ctx in &delivery.context { + if !lines + .iter() + .any(|(held, _)| held.room == room && held.sender == ctx.sender && held.at_ms == ctx.at_unix_ms) + { + lines.push((FactLine { sender: &ctx.sender, room, at_ms: ctx.at_unix_ms }, None)); + } + } + match lines + .iter_mut() + .find(|(held, _)| held.room == room && held.sender == delivery.sender && held.at_ms == delivery.at_unix_ms) + { + Some((_, slot)) => *slot = Some(index), + None => lines.push(( + FactLine { sender: &delivery.sender, room, at_ms: delivery.at_unix_ms }, + Some(index), + )), + } + } + lines.sort_by_key(|(line, _)| line.at_ms); + lines +} + +fn format_delivery(delivery: &ChatDelivery) -> String { + let basis = delivery.basis.map_or("none", |b| b.name()); + let mut extra = String::new(); + if delivery.is_direct { + extra.push_str(" direct=true"); + } + if let Some(reply) = delivery.reply_to.quote() { + extra.push_str(&format!(" reply_to={}({})", reply.event_id, reply.sender)); + } + if let Some(image) = &delivery.image { + extra.push_str(&format!(" image={}", image.path)); + } + format!( + "delivery seq={} room={} room_id={} event={} at={} sender={} form={} basis={}{} body={}", + delivery.seq, + delivery.room_alias, + delivery.room_id, + delivery.event_id, + shown_ms(delivery.at_unix_ms), + delivery.sender, + delivery.form.name(), + basis, + extra, + one_line(&delivery.text), + ) +} + +fn format_tail_line(line: &TailLine) -> String { + let basis = line.basis.map_or("none", |b| b.name()); + let mut extra = String::new(); + if let Some(reply) = line.reply_to.quote() { + extra.push_str(&format!(" reply_to={}({})", reply.event_id, reply.sender)); + } + format!( + "tail room={} event={} at={} sender={} form={} basis={}{} body={}", + line.room, + line.event_id, + shown_ms(line.at_unix_ms), + line.sender, + line.form.name(), + basis, + extra, + one_line(&line.body), + ) +} + +fn one_line(text: &str) -> String { + text.replace('\r', "\\r").replace('\n', "\\n") +} + +fn shown_ms(ms: u64) -> String { + DateTime::from_timestamp_millis(i64::try_from(ms).unwrap_or(i64::MAX)) + .map_or_else(|| ms.to_string(), |dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)) +} + +fn utc_day(ms: u64) -> String { + DateTime::from_timestamp_millis(i64::try_from(ms).unwrap_or(i64::MAX)) + .map_or_else(|| "1970-01-01".to_string(), |dt| dt.format("%Y-%m-%d").to_string()) +} + +fn write_state_atomic(path: &Path, state: &GateState) -> Result<()> { + let json = serde_json::to_string_pretty(state)?; + let tmp = path.with_extension(format!("json.tmp.{}", std::process::id())); + fs::write(&tmp, json.as_bytes()).with_context(|| format!("failed to write {}", tmp.display()))?; + restrict_state_file(&tmp)?; + fs::rename(&tmp, path).with_context(|| format!("failed to rename {} to {}", tmp.display(), path.display()))?; + Ok(()) +} + +#[cfg(unix)] +fn restrict_state_file(path: &Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o600)) + .with_context(|| format!("failed to chmod 0600 {}", path.display())) +} + +#[cfg(not(unix))] +fn restrict_state_file(_path: &Path) -> Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::collections::VecDeque; + + use super::*; + use crate::chat_client::{ + Basis, ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatPending, ChatSendReceipt, Form, + ReplyLink, + }; + + struct MockChat { + pending_replies: RefCell>>, + send_replies: RefCell>>, + open_replies: RefCell>>, + acks: RefCell>, + reads: RefCell>, + sent: RefCell>, + opened: RefCell>, + } + + impl MockChat { + fn new() -> Self { + Self { + pending_replies: RefCell::new(VecDeque::new()), + send_replies: RefCell::new(VecDeque::new()), + open_replies: RefCell::new(VecDeque::new()), + acks: RefCell::new(Vec::new()), + reads: RefCell::new(Vec::new()), + sent: RefCell::new(Vec::new()), + opened: RefCell::new(Vec::new()), + } + } + } + + impl Chat for MockChat { + fn pending(&self, _after_seq: u64) -> Result { + self.pending_replies.borrow_mut().pop_front().expect("queued pending reply") + } + fn send(&self, request: &ChatSendRequest) -> Result { + self.sent.borrow_mut().push(request.clone()); + self.send_replies.borrow_mut().pop_front().expect("queued send reply") + } + fn open_direct(&self, request: &ChatOpenDirectRequest) -> Result { + self.opened.borrow_mut().push(request.clone()); + self.open_replies.borrow_mut().pop_front().expect("queued open_direct reply") + } + fn fetch(&self, _request: &ChatFetchRequest) -> Result { + bail!("unused in chat_gate tests") + } + fn ack(&self, through_seq: u64) -> Result<()> { + self.acks.borrow_mut().push(through_seq); + Ok(()) + } + fn read(&self, read: &ChatRead) -> Result<()> { + self.reads.borrow_mut().push(read.clone()); + Ok(()) + } + } + + fn cfg(dir: &Path, daily_cap: Option) -> Config { + Config { + instance: Slug("nibu".into()), + state_dir: dir.to_path_buf(), + minds: vec!["@nibu:gamecult.org".into(), "@eureka:gamecult.org".into()], + operators: vec!["@meta:gamecult.org".into()], + own_sender: "@nibu:gamecult.org".into(), + daily_cap, + } + } + + fn delivery(seq: u64, room: &str, event_id: &str, sender: &str, at_unix_ms: u64, text: &str) -> ChatDelivery { + ChatDelivery { + seq, + room_alias: room.into(), + room_id: format!("!{room}:gamecult.org"), + event_id: event_id.into(), + sender: sender.into(), + sender_display: sender.into(), + text: text.into(), + at_unix_ms, + context: vec![], + mentions: vec![], + is_direct: false, + image: None, + basis: Some(Basis::Tag), + form: Form::Message, + reply_to: ReplyLink::Absent, + } + } + + #[test] + fn chat_gate_enforces_key_pinning_room_moved_resend_backstop_and_daily_cap() { + let dir = tempfile::tempdir().unwrap(); + let mock = MockChat::new(); + let t0 = 1_765_000_000_000_u64; + + // 1. pending advances seen_event_id and records lines. + mock.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![delivery(1, "#swarm:gamecult.org", "$ev1", "@meta:gamecult.org", t0 + 1000, "hi")], + tail: None, + tail_gaps: vec![], + })); + let mut engine = Engine::open(cfg(dir.path(), Some(2)), mock, t0).unwrap(); + let p = engine.handle(Request::Pending { ack: true }, t0 + 1000).unwrap(); + assert_eq!(p.exit, 0); + assert!(p.stdout.contains("$ev1"), "{}", p.stdout); + assert_eq!(engine.chat.acks.borrow().as_slice(), &[1]); + + // 2. RoomMoved refuses say exit 1 with newer IDs and does NOT advance seen_event_id. + engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: None, + refusal: Some(Refusal::RoomMoved), + newer: vec!["$ev2".into(), "$ev3".into()], + })); + let moved = engine + .handle( + Request::Say { room: "#swarm:gamecult.org".into(), text: Some("reply".into()), resend: None }, + t0 + 2000, + ) + .unwrap(); + assert_eq!(moved.exit, 1); + assert!(moved.stdout.contains("RoomMoved") && moved.stdout.contains("$ev2,$ev3"), "{}", moved.stdout); + assert_eq!( + engine.chat.sent.borrow().last().unwrap().basis, + Some(SendBasis { seen_event_id: Some("$ev1".into()), since_unix_ms: t0 }) + ); + assert_eq!( + engine.state.rooms.get("#swarm:gamecult.org").and_then(|r| r.seen_event_id.as_deref()), + Some("$ev1") + ); + + // tail displays $ev3 and advances seen_event_id. + engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![], + tail: Some(vec![TailLine { + room: "#swarm:gamecult.org".into(), + event_id: "$ev3".into(), + at_unix_ms: t0 + 2500, + sender: "@meta:gamecult.org".into(), + form: Form::Message, + basis: None, + body: "later".into(), + reply_to: ReplyLink::Absent, + }]), + tail_gaps: vec![], + })); + let tailed = engine.handle(Request::Tail { room: Some("#swarm:gamecult.org".into()) }, t0 + 2600).unwrap(); + assert_eq!(tailed.exit, 0); + assert_eq!( + engine.state.rooms.get("#swarm:gamecult.org").and_then(|r| r.seen_event_id.as_deref()), + Some("$ev3") + ); + + // 3. NoAnswer leaves unsettled 1800s pending_send blocking second say until --resend. + engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: None, + refusal: Some(Refusal::SendFailed), + newer: vec![], + })); + let no_ans = engine + .handle( + Request::Say { room: "#swarm:gamecult.org".into(), text: Some("first try".into()), resend: None }, + t0 + 3000, + ) + .unwrap(); + assert_eq!(no_ans.exit, 3); + let pending_id = engine + .state + .rooms + .get("#swarm:gamecult.org") + .and_then(|r| r.pending_send.as_ref()) + .unwrap() + .request_id + .clone(); + + // Second say inside 1800s is blocked. + let blocked = engine + .handle( + Request::Say { room: "#swarm:gamecult.org".into(), text: Some("second".into()), resend: None }, + t0 + 4000, + ) + .unwrap(); + assert_eq!(blocked.exit, 1); + assert!(blocked.stdout.contains("room_unsettled"), "{}", blocked.stdout); + + // --resend settles it and increments daily_says (1/2). + engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: pending_id.clone(), + event_id: Some("$ev4".into()), + refusal: None, + newer: vec![], + })); + let resent = engine + .handle( + Request::Say { room: "#swarm:gamecult.org".into(), text: None, resend: Some(pending_id.clone()) }, + t0 + 5000, + ) + .unwrap(); + assert_eq!(resent.exit, 0); + assert!(resent.stdout.contains("$ev4"), "{}", resent.stdout); + assert!(engine.chat.sent.borrow().last().unwrap().resend); + + // 4. 4 consecutive Mind lines inside 30m trigger MIND_RUN_BACKSTOP. + // We already have $ev4 from @nibu at t0+5000 (1 Mind line). Add 3 more Mind lines in #swarm. + engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![ + delivery(2, "#swarm:gamecult.org", "$ev5", "@eureka:gamecult.org", t0 + 6000, "m2"), + delivery(3, "#swarm:gamecult.org", "$ev6", "@nibu:gamecult.org", t0 + 7000, "m3"), + delivery(4, "#swarm:gamecult.org", "$ev7", "@eureka:gamecult.org", t0 + 8000, "m4"), + ], + tail: None, + tail_gaps: vec![], + })); + let p2 = engine.handle(Request::Pending { ack: false }, t0 + 8500).unwrap(); + assert!(p2.stdout.contains("MIND_RUN_BACKSTOP"), "{}", p2.stdout); + let backstopped = engine + .handle( + Request::Say { room: "#swarm:gamecult.org".into(), text: Some("5th mind line".into()), resend: None }, + t0 + 9000, + ) + .unwrap(); + assert_eq!(backstopped.exit, 1); + assert!(backstopped.stdout.contains("mind_run_backstop"), "{}", backstopped.stdout); + + // 5. UTC daily cap (2/2) blocks both say (in another room) and open-direct. + engine.chat.open_replies.borrow_mut().push_back(Ok(ChatOpenDirectReceipt { + request_id: "od".into(), + outcome: DirectOutcome::Opened, + room_id: Some("!dm:gamecult.org".into()), + event_id: Some("$dm1".into()), + })); + let dm_ok = engine + .handle( + Request::OpenDirect { user: "@meta:gamecult.org".into(), text: "hello".into() }, + t0 + 10_000, + ) + .unwrap(); + assert_eq!(dm_ok.exit, 0); + + let say_capped = engine + .handle( + Request::Say { room: "#other:gamecult.org".into(), text: Some("over cap".into()), resend: None }, + t0 + 11_000, + ) + .unwrap(); + assert_eq!(say_capped.exit, 1); + assert!(say_capped.stdout.contains("daily_cap"), "{}", say_capped.stdout); + + let dm_capped = engine + .handle( + Request::OpenDirect { user: "@meta:gamecult.org".into(), text: "over cap".into() }, + t0 + 12_000, + ) + .unwrap(); + assert_eq!(dm_capped.exit, 1); + assert!(dm_capped.stdout.contains("daily_cap"), "{}", dm_capped.stdout); + + // 6. mark-read, ack, and status round-trip. + let rd = engine + .handle( + Request::MarkRead { room: "!#swarm:gamecult.org:gamecult.org".into(), event: "$ev7".into(), at_unix_ms: t0 + 8000 }, + t0 + 12_100, + ) + .unwrap(); + assert_eq!(rd.exit, 0); + assert_eq!(engine.chat.reads.borrow().last().unwrap().persona, "nibu"); + + let ak = engine.handle(Request::Ack { through: 4 }, t0 + 12_200).unwrap(); + assert_eq!(ak.exit, 0); + assert_eq!(engine.state.after_seq, 4); + + let st = engine.handle(Request::Status, t0 + 12_300).unwrap(); + assert_eq!(st.exit, 0); + assert!(st.stdout.contains("after_seq 4") && st.stdout.contains("daily_says 2/2"), "{}", st.stdout); + + // 7. Reloading from chat-gate.json preserves cursors & refuses wrong instance; + // next UTC day resets daily cap, and 30m silence resets MIND_RUN_BACKSTOP. + let mut wrong_cfg = cfg(dir.path(), Some(2)); + wrong_cfg.instance = Slug("eureka".into()); + assert!(Engine::open(wrong_cfg, MockChat::new(), t0 + 13_000).is_err()); + + let t_next_day = t0 + 24 * 3600 * 1000 + 1000; + let mock2 = MockChat::new(); + mock2.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: Some("$ev8".into()), + refusal: None, + newer: vec![], + })); + let mut reloaded = Engine::open(cfg(dir.path(), Some(2)), mock2, t_next_day).unwrap(); + assert_eq!(reloaded.state.after_seq, 4); + let after_silence = reloaded + .handle( + Request::Say { room: "#swarm:gamecult.org".into(), text: Some("after silence".into()), resend: None }, + t_next_day, + ) + .unwrap(); + assert_eq!(after_silence.exit, 0, "{}", after_silence.stdout); + + // 8. Unsettled pending_send expires past 1800s allowing fresh say, while --resend refuses. + reloaded.chat.send_replies.borrow_mut().push_back(Err(anyhow!("socket timeout"))); + let timed_out = reloaded + .handle( + Request::Say { room: "#exp:gamecult.org".into(), text: Some("lost".into()), resend: None }, + t_next_day + 1000, + ) + .unwrap(); + assert_eq!(timed_out.exit, 3); + let exp_id = reloaded + .state + .rooms + .get("#exp:gamecult.org") + .and_then(|r| r.pending_send.as_ref()) + .unwrap() + .request_id + .clone(); + let t_expired = t_next_day + 1000 + (UNSETTLED_WINDOW_S as u64) * 1000; + let late_resend = reloaded + .handle( + Request::Say { room: "#exp:gamecult.org".into(), text: None, resend: Some(exp_id) }, + t_expired, + ) + .unwrap(); + assert_eq!(late_resend.exit, 1); + assert!(late_resend.stdout.contains("ResendUnknown"), "{}", late_resend.stdout); + + reloaded.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: Some("$ev9".into()), + refusal: None, + newer: vec![], + })); + let fresh_after_exp = reloaded + .handle( + Request::Say { room: "#exp:gamecult.org".into(), text: Some("fresh".into()), resend: None }, + t_expired + 1, + ) + .unwrap(); + assert_eq!(fresh_after_exp.exit, 0); + } + + #[cfg(unix)] + #[test] + fn unix_socket_gate_forces_instance_persona_and_0600_mode() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let sock = dir.path().join("gate.sock"); + let mock = MockChat::new(); + let t0 = 1_765_000_000_000_u64; + mock.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: Some("$s1".into()), + refusal: None, + newer: vec![], + })); + let recorded_persona = std::sync::Arc::new(std::sync::Mutex::new(String::new())); + let recorded_clone = std::sync::Arc::clone(&recorded_persona); + + struct SpyChat(MockChat, std::sync::Arc>); + impl Chat for SpyChat { + fn pending(&self, a: u64) -> Result { self.0.pending(a) } + fn send(&self, r: &ChatSendRequest) -> Result { + *self.1.lock().unwrap() = r.persona.clone(); + self.0.send(r) + } + fn open_direct(&self, r: &ChatOpenDirectRequest) -> Result { self.0.open_direct(r) } + fn fetch(&self, r: &ChatFetchRequest) -> Result { self.0.fetch(r) } + fn ack(&self, t: u64) -> Result<()> { self.0.ack(t) } + fn read(&self, r: &ChatRead) -> Result<()> { self.0.read(r) } + } + + let sock_srv = sock.clone(); + let state_dir = dir.path().join("state"); + let handle = std::thread::spawn(move || { + socket::serve(cfg(&state_dir, None), SpyChat(mock, recorded_clone), &sock_srv, || t0, Some(1)).unwrap(); + }); + while !sock.exists() { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let mode = fs::metadata(&sock).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + + let ans = call_socket( + &sock, + &Request::Say { room: "#swarm:gamecult.org".into(), text: Some("from sandbox".into()), resend: None }, + ) + .unwrap(); + assert_eq!(ans.exit, 0); + assert!(ans.stdout.contains("Posted $s1"), "{}", ans.stdout); + handle.join().unwrap(); + assert_eq!(recorded_persona.lock().unwrap().as_str(), "nibu"); + } +} diff --git a/crates/mind-body/src/lib.rs b/crates/mind-body/src/lib.rs index dfad1c0..0c4de72 100644 --- a/crates/mind-body/src/lib.rs +++ b/crates/mind-body/src/lib.rs @@ -35,6 +35,7 @@ mod address; pub mod chat_client; +pub mod chat_gate; #[allow(dead_code, reason = "the loader is kept for the three-stage turn's perception (map C3): its first caller removes this allow; `Image` is live through `self_run::session`")] mod chat_image; pub mod chat_rudp; diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index cc3d02f..447160b 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -1,4 +1,5 @@ mind_body: mod chat_client +mind_body: mod chat_gate mind_body: mod chat_rudp mind_body: mod cli mind_body: mod connector @@ -100,6 +101,18 @@ mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , Pa mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool] mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64] mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String, reply_to: ReplyLink] +mind_body::chat_gate: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "op" , rename_all = "snake_case" , deny_unknown_fields)] pub enum Request { Pending { ack : bool , } , Tail { room : Option < String > , } , Say { room : String , text : Option < String > , resend : Option < String > , } , Ack { through : u64 , } , MarkRead { room : String , event : String , at_unix_ms : u64 , } , OpenDirect { user : String , text : String , } , Status , } +mind_body::chat_gate: const STATE_FILE : & str +mind_body::chat_gate: const UNSETTLED_WINDOW_S : i64 +mind_body::chat_gate: fn call_socket (socket : & Path , request : & Request) -> Result < Answer > +mind_body::chat_gate: fn serve_gate (config : Config , chat : impl Chat , socket : & Path , now_ms : impl Fn () -> u64) -> Result < () > +mind_body::chat_gate: impl Answer +mind_body::chat_gate: impl< C : Chat > Engine < C > +mind_body::chat_gate: impl< C : Chat > Engine < C >: fn handle (& mut self , request : Request , now_ms : u64) -> Result < Answer > +mind_body::chat_gate: impl< C : Chat > Engine < C >: fn open (config : Config , chat : C , now_ms : u64) -> Result < Self > +mind_body::chat_gate: struct Answer # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[exit: u8, stdout: String, stderr: String] +mind_body::chat_gate: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[instance: Slug, state_dir: PathBuf, minds: Vec < String >, operators: Vec < String >, own_sender: String, daily_cap: Option < u32 >] +mind_body::chat_gate: struct Engine< C : Chat > pub-fields[] mind_body::chat_image: impl Skip mind_body::chat_rudp: fn connection_id (key_file_text : & str) -> u32 mind_body::chat_rudp: impl Chat for RudpChat From 232d6e3e15dbce20a3f97bcf5c9f9c763bc3693a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:22:43 +0100 Subject: [PATCH 04/12] Sync public_surface.txt and drop unused import in chat_gate Remove unused bail import in chat_gate.rs and synchronize tests/public_surface.txt with the current mind-body library surface. --- crates/mind-body/src/chat_gate.rs | 2 +- crates/mind-body/tests/public_surface.txt | 21 ++++++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs index 9b9c327..e3fc701 100644 --- a/crates/mind-body/src/chat_gate.rs +++ b/crates/mind-body/src/chat_gate.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; -use anyhow::{Context, Result, anyhow, bail, ensure}; +use anyhow::{Context, Result, anyhow, ensure}; use chrono::DateTime; use eureka_pipeline::Slug; use serde::{Deserialize, Serialize}; diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 447160b..24acd5f 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -101,15 +101,15 @@ mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , Pa mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool] mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64] mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String, reply_to: ReplyLink] -mind_body::chat_gate: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "op" , rename_all = "snake_case" , deny_unknown_fields)] pub enum Request { Pending { ack : bool , } , Tail { room : Option < String > , } , Say { room : String , text : Option < String > , resend : Option < String > , } , Ack { through : u64 , } , MarkRead { room : String , event : String , at_unix_ms : u64 , } , OpenDirect { user : String , text : String , } , Status , } +mind_body::chat_gate: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "op" , rename_all = "snake_case" , deny_unknown_fields)] pub enum Request { Pending { ack : bool } , Tail { room : Option < String > } , Say { room : String , text : Option < String > , resend : Option < String > } , Ack { through : u64 } , MarkRead { room : String , event : String , at_unix_ms : u64 } , OpenDirect { user : String , text : String } , Status , } mind_body::chat_gate: const STATE_FILE : & str mind_body::chat_gate: const UNSETTLED_WINDOW_S : i64 mind_body::chat_gate: fn call_socket (socket : & Path , request : & Request) -> Result < Answer > mind_body::chat_gate: fn serve_gate (config : Config , chat : impl Chat , socket : & Path , now_ms : impl Fn () -> u64) -> Result < () > mind_body::chat_gate: impl Answer +mind_body::chat_gate: impl Engine < C >: fn handle (& mut self , request : Request , now_ms : u64) -> Result < Answer > +mind_body::chat_gate: impl Engine < C >: fn open (config : Config , chat : C , now_ms : u64) -> Result < Self > mind_body::chat_gate: impl< C : Chat > Engine < C > -mind_body::chat_gate: impl< C : Chat > Engine < C >: fn handle (& mut self , request : Request , now_ms : u64) -> Result < Answer > -mind_body::chat_gate: impl< C : Chat > Engine < C >: fn open (config : Config , chat : C , now_ms : u64) -> Result < Self > mind_body::chat_gate: struct Answer # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[exit: u8, stdout: String, stderr: String] mind_body::chat_gate: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[instance: Slug, state_dir: PathBuf, minds: Vec < String >, operators: Vec < String >, own_sender: String, daily_cap: Option < u32 >] mind_body::chat_gate: struct Engine< C : Chat > pub-fields[] @@ -231,7 +231,7 @@ mind_body::lease_client: struct LeaseRequest # [derive (Clone , Debug , PartialE mind_body::lease_client: struct SocketLender pub-fields[] mind_body::lease_client: struct TokenFd pub-fields[] mind_body::lease_client::socket: impl Lease for Granted -mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , Drained { wakes : usize , acked_through : Option < u64 > } , Failed (String) , } +mind_body::persona: # [derive (Debug , PartialEq , Eq)] pub enum Outcome { Dead (HeldReason) , Drained { wakes : usize , turns : usize , ended : Option < End > , acked_through : Option < u64 > } , Held { until : DateTime < Utc > } , Failed (String) , } mind_body::persona: const AGENT : & str mind_body::persona: const ENV_MINDS : & str mind_body::persona: const ENV_MODEL : & str @@ -257,11 +257,16 @@ mind_body::persona: impl TraceView for TraceSnapshot mind_body::persona: impl fmt :: Display for Outcome mind_body::persona: pub trait Trace : TraceView { fn record (& self , key : & str , record : & Value) -> Result < () > ; } mind_body::persona: pub trait TraceView { fn records (& self) -> Result < Vec < Value > > ; } +mind_body::persona: pub use live :: End ; mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String, review_room: Option < String >] mind_body::persona: struct FileTrace pub-fields[] -mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, agent: Box < dyn Steps >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, session: PathBuf, box_socket: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >] +mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, agent: Box < dyn Steps >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, session: PathBuf, box_socket: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >, pause: Box < dyn Fn (std :: time :: Duration) >] mind_body::persona: struct TraceSnapshot pub-fields[] mind_body::persona: struct TurnRecord # [derive (Clone , Debug , PartialEq , DatabaseEntry)] pub-fields[value: Value] +mind_body::persona::live: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum End { Failed , DayCap , Spend , Span , Idle , } +mind_body::persona::live: impl End +mind_body::persona::live: impl Hearing < '_ > +mind_body::persona::live: impl std :: fmt :: Display for End mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , } mind_body::projection: # [derive (Debug , PartialEq , Eq)] pub enum Put { Committed , Stale , Refused (String) , } mind_body::projection: fn project (organs : & Organs , request : & Request , now : DateTime < Utc >) -> Result < Value > @@ -314,7 +319,7 @@ mind_body::projection::agent: struct Receipt # [derive (Clone , Debug , PartialE mind_body::projection::agent: struct Session # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[items: Vec < InputItem >, digest: String, retention: CacheRetention, created_at: DateTime < Utc >, last_call_at: DateTime < Utc >, last_usage: Option < Spent >] mind_body::projection::agent: struct TraceLedger< 'a > pub-fields[] mind_body::projection::agent: struct Turn # [derive (Clone , Debug , PartialEq)] pub-fields[ended: Ended, text: String, receipts: Vec < Receipt >, model_calls: usize, tool_calls: usize, usd: f64] -mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, instructions: & 'a str, input: & 'a str, fresh: & 'a str] +mind_body::projection::agent: struct Wake< 'a > pub-fields[id: & 'a str, wake: & 'a str, instructions: & 'a str, opening: & 'a str, input: & 'a str, fresh: & 'a str, first: bool] mind_body::projection::agent::read: impl Executor for Read < '_ > mind_body::projection::agent::read: struct Read< 'a > pub-fields[source: Option < & 'a dyn ReadSource >, since: DateTime < Utc >] mind_body::projection::agent::request_tool: impl Executor for RequestTool @@ -407,6 +412,8 @@ mind_body::projection::select: impl< 'a > Inputs < 'a > mind_body::projection::simulate: fn simulate (harness : & Harness , plan_path : & Path) -> Result < String > mind_body::projection::simulate: impl HeartbeatView for Names < '_ > mind_body::projection::simulate: impl MouthReader for View < '_ > +mind_body::projection::simulate: impl PersonaSource for InRun +mind_body::projection::simulate: impl PersonaStore for InRun mind_body::projection::simulate: impl ReadSource for CastReads < '_ > mind_body::projection::tuning: const TUNING_FILE : & str mind_body::projection::tuning: const TUNING_ROOT : & str @@ -423,7 +430,7 @@ mind_body::projection::tuning: impl Default for SelectTuning mind_body::projection::tuning: impl Default for Tuning mind_body::projection::tuning: impl Price mind_body::projection::tuning: impl Tuning -mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >] +mind_body::projection::tuning: struct AgentTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, tool_calls: usize, model_calls: usize, wake_usd: f64, day_usd: f64, unmetered_usd: f64, idle_s: u64, span_s: u64, max_session_tokens: u64, retention: CacheRetention, ttl_s: CacheTtl, cache_min_tokens: u64, prices: BTreeMap < String , Price >] mind_body::projection::tuning: struct CacheTtl # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[short: u64, long: u64] mind_body::projection::tuning: struct InterpreterTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String] mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64] From 744c312cf493b40260a1fa2a6169d6d9a3add5b8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:23:36 +0100 Subject: [PATCH 05/12] Qualify anyhow::bail in chat_gate test mock Avoid unused bail import in non-test builds so clippy passes cleanly. --- crates/mind-body/src/chat_gate.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs index e3fc701..d14fd95 100644 --- a/crates/mind-body/src/chat_gate.rs +++ b/crates/mind-body/src/chat_gate.rs @@ -945,7 +945,7 @@ mod tests { self.open_replies.borrow_mut().pop_front().expect("queued open_direct reply") } fn fetch(&self, _request: &ChatFetchRequest) -> Result { - bail!("unused in chat_gate tests") + anyhow::bail!("unused in chat_gate tests") } fn ack(&self, through_seq: u64) -> Result<()> { self.acks.borrow_mut().push(through_seq); From d3b57a804858b5ff4b8aac3d1296b726f54d58b0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:25:29 +0100 Subject: [PATCH 06/12] Use enumerate loop in chat_gate socket accept Satisfy clippy::explicit_counter_loop in chat_gate::socket::serve. --- crates/mind-body/src/chat_gate.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs index d14fd95..ced7893 100644 --- a/crates/mind-body/src/chat_gate.rs +++ b/crates/mind-body/src/chat_gate.rs @@ -667,16 +667,14 @@ mod socket { fs::set_permissions(socket, Permissions::from_mode(0o600)) .with_context(|| format!("failed to chmod 0600 {}", socket.display()))?; - let mut served = 0usize; - for stream in listener.incoming() { + for (served, stream) in listener.incoming().enumerate() { let mut stream = stream.context("accept failed on chat gate socket")?; let _ = stream.set_read_timeout(Some(IO_TIMEOUT)); let _ = stream.set_write_timeout(Some(IO_TIMEOUT)); let answer = handle_stream(&mut engine, &stream, &now_ms); let encoded = serde_json::to_string(&answer)?; let _ = writeln!(stream, "{encoded}").and_then(|()| stream.flush()); - served += 1; - if max_requests.is_some_and(|max| served >= max) { + if max_requests.is_some_and(|max| served + 1 >= max) { break; } } From 87f815af7f569d86309a670bfcf1fd74366206d5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:30:58 +0100 Subject: [PATCH 07/12] Use for-loop over pending args in mind-chat CLI --- crates/mind-body/src/bin/mind-chat.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mind-body/src/bin/mind-chat.rs b/crates/mind-body/src/bin/mind-chat.rs index 6a6af27..e3df688 100644 --- a/crates/mind-body/src/bin/mind-chat.rs +++ b/crates/mind-body/src/bin/mind-chat.rs @@ -120,7 +120,7 @@ fn parse_client_request(cmd: &str, args: &[String]) -> Result { match cmd { "pending" => { let mut ack = false; - while let Some(flag) = it.next() { + for flag in it { match flag.as_str() { "--ack" if !ack => ack = true, _ => bail!("{USAGE}"), From f025e0ecb2d6860db9b46d06d40c4a0dc9570a0a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 08:39:48 +0100 Subject: [PATCH 08/12] Test ACTIVITY_REPOS_MAX bounds in huginn activity CLI round trip --- crates/eureka-state/tests/cli.rs | 81 +++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 2 deletions(-) diff --git a/crates/eureka-state/tests/cli.rs b/crates/eureka-state/tests/cli.rs index 3272299..0f68415 100644 --- a/crates/eureka-state/tests/cli.rs +++ b/crates/eureka-state/tests/cli.rs @@ -4066,8 +4066,8 @@ fn serve_with_persona( fn huginn_escalate_and_activity_cli_round_trip() { use huginn_mind::eureka_pipeline::{MemoryOrigin, PipelineFollowUp}; use huginn_mind::{ - OpenPr, PipelineDocumentSummary, PipelineFacts, PipelineStatusSummary, PrAction, RepoActivity, RepoChange, - RepoEvent, RepoMoved, + ACTIVITY_REPOS_MAX, OpenPr, PipelineDocumentSummary, PipelineFacts, PipelineStatusSummary, PrAction, RepoActivity, + RepoChange, RepoEvent, RepoMoved, }; // 1. Live daemon with Door::Persona: escalate commits FollowUp with server-pinned fields, @@ -4280,4 +4280,81 @@ fn huginn_escalate_and_activity_cli_round_trip() { let ran = at(spy.addr, &bad, None); assert_eq!(ran.code, 2, "{bad:?}: {} {}", ran.out, ran.err); } + + // Boundary checks on ACTIVITY_REPOS_MAX (64): autodiscovery collects all up to the cap + // instead of stopping at 1, explicit --repo allows exact cap (64), and rejects cap + 1 (65). + let seen_cap = Arc::new(Mutex::new(Vec::::new())); + let sink_cap = Arc::clone(&seen_cap); + let empty_activity = RepoActivity { + head: 1, + events: vec![], + capped: vec![], + open_prs: vec![], + unseen: vec![], + moved: vec![], + }; + let cap_srv = scripted(move |message| { + let (_, request) = decode_request(message).unwrap(); + sink_cap.lock().unwrap().push(request.clone()); + match request { + HuginnMindRequest::Query { .. } => { + let items: Vec = (0..=ACTIVITY_REPOS_MAX) + .map(|idx| PipelineDocumentSummary { + id: PipelineRef { kind: PipelineKind::Stewardship, id: Short(format!("{INSTANCE}:stewardship:r{idx}")) }, + status: PipelineStatusSummary::InForce, + admission: AdmissionFacts { + receipt_id: "r1".into(), + admitted_at: "2026-10-10T10:00:00Z".into(), + provenance: provenance(), + ordinal: idx as u64 + 1, + }, + facts: PipelineFacts::Stewardship { + instance: slug(INSTANCE), + repo: OrgRepo(format!("GameCult/R{idx:02}")), + sequence: 1, + assigned_on: Date("2026-10-10".into()), + note: "assigned".into(), + names: vec![], + }, + }) + .collect(); + let page = PipelineSelectionPage { + matched: items.len() as u32, + as_of: 1, + next: None, + items: PipelinePageItems::Headers(items), + edges: None, + scores: None, + }; + answer("query", &HuginnMindResponse::Query(page)) + } + HuginnMindRequest::StewardedActivity { .. } => { + answer("stewarded_activity", &HuginnMindResponse::Activity(empty_activity.clone())) + } + other => panic!("unexpected request: {other:?}"), + } + }); + let capped_auto = at(cap_srv.addr, &["activity"], None); + assert_eq!(capped_auto.code, 0, "{} {}", capped_auto.out, capped_auto.err); + + let exact_args: Vec = std::iter::once("activity".to_string()) + .chain((0..ACTIVITY_REPOS_MAX).flat_map(|idx| ["--repo".to_string(), format!("GameCult/R{idx:02}")])) + .collect(); + let exact_refs: Vec<&str> = exact_args.iter().map(String::as_str).collect(); + let exact_cap = at(cap_srv.addr, &exact_refs, None); + assert_eq!(exact_cap.code, 0, "{} {}", exact_cap.out, exact_cap.err); + + let over_args: Vec = std::iter::once("activity".to_string()) + .chain((0..=ACTIVITY_REPOS_MAX).flat_map(|idx| ["--repo".to_string(), format!("GameCult/R{idx:02}")])) + .collect(); + let over_refs: Vec<&str> = over_args.iter().map(String::as_str).collect(); + let over_cap = at(cap_srv.addr, &over_refs, None); + assert_eq!(over_cap.code, 2, "{} {}", over_cap.out, over_cap.err); + + let cap_recorded = seen_cap.lock().unwrap(); + assert_eq!(cap_recorded.len(), 3, "over-cap must not send"); + let HuginnMindRequest::StewardedActivity { repos: auto_repos, .. } = &cap_recorded[1] else { + panic!("expected StewardedActivity"); + }; + assert_eq!(auto_repos.len(), ACTIVITY_REPOS_MAX); } From 2b9920470eba9b72adb57115dd3a9ece5f5f0c73 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 10:58:43 +0100 Subject: [PATCH 09/12] Add tests for mind-chat CLI/gate boundaries and chat_gate edge cases --- crates/mind-body/src/bin/mind-chat.rs | 141 +++++++++- crates/mind-body/src/chat_gate.rs | 326 ++++++++++++++++++------ crates/mind-body/tests/mind_chat_bin.rs | 129 ++++++++++ 3 files changed, 508 insertions(+), 88 deletions(-) create mode 100644 crates/mind-body/tests/mind_chat_bin.rs diff --git a/crates/mind-body/src/bin/mind-chat.rs b/crates/mind-body/src/bin/mind-chat.rs index e3df688..12b50f5 100644 --- a/crates/mind-body/src/bin/mind-chat.rs +++ b/crates/mind-body/src/bin/mind-chat.rs @@ -76,7 +76,7 @@ fn open_rudp(instance: &str) -> Result { Ok(RudpChat::new(endpoint, conn_id, instance, CHAT_TIMEOUT).with_reply_link(true)) } -fn run_gate(args: &[String]) -> Result<()> { +fn parse_gate_args(args: &[String], get_env: &dyn Fn(&str) -> Option) -> Result<(Config, PathBuf)> { let (mut instance, mut socket, mut state_dir, mut minds, mut operators, mut own_sender, mut daily_cap) = (None, None, None, None, None, None, None); let mut it = args.iter(); @@ -99,19 +99,24 @@ fn run_gate(args: &[String]) -> Result<()> { let instance = Slug(instance.ok_or_else(|| anyhow!("--instance is required"))?); let socket = socket.ok_or_else(|| anyhow!("--socket is required"))?; let state_dir = state_dir.ok_or_else(|| anyhow!("--state-dir is required"))?; - let minds = minds.unwrap_or_else(|| setting("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default()); - let operators = operators.unwrap_or_else(|| setting("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default()); + let minds = minds.unwrap_or_else(|| get_env("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default()); + let operators = + operators.unwrap_or_else(|| get_env("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default()); let own_sender = own_sender - .or_else(|| setting("MIND_PERSONA_SELF_SENDER")) + .or_else(|| get_env("MIND_PERSONA_SELF_SENDER")) .ok_or_else(|| anyhow!("--own-sender is required"))?; let daily_cap = match daily_cap { Some(cap) => Some(cap), - None => setting("MIND_CHAT_DAILY_CAP") + None => get_env("MIND_CHAT_DAILY_CAP") .map(|v| v.parse::().map_err(|_| anyhow!("MIND_CHAT_DAILY_CAP must be an integer"))) .transpose()?, }; - let chat = open_rudp(&instance.0)?; - let config = Config { instance, state_dir, minds, operators, own_sender, daily_cap }; + Ok((Config { instance, state_dir, minds, operators, own_sender, daily_cap }, socket)) +} + +fn run_gate(args: &[String]) -> Result<()> { + let (config, socket) = parse_gate_args(args, &setting)?; + let chat = open_rudp(&config.instance.0)?; serve_gate(config, chat, &socket, now_ms) } @@ -315,3 +320,125 @@ fn main() { } std::process::exit(i32::from(answer.exit)); } + +#[cfg(test)] +mod tests { + use super::*; + + fn s(items: &[&str]) -> Vec { + items.iter().map(|v| (*v).to_string()).collect() + } + + #[test] + fn parse_client_requests_covers_every_subcommand_and_rejection() { + assert_eq!(parse_client_request("pending", &[]).unwrap(), Request::Pending { ack: false }); + assert_eq!(parse_client_request("pending", &s(&["--ack"])).unwrap(), Request::Pending { ack: true }); + assert!(parse_client_request("pending", &s(&["--ack", "--ack"])).is_err()); + assert!(parse_client_request("pending", &s(&["--bad"])).is_err()); + + assert_eq!(parse_client_request("tail", &[]).unwrap(), Request::Tail { room: None }); + assert_eq!( + parse_client_request("tail", &s(&["--room", "#r:x"])).unwrap(), + Request::Tail { room: Some("#r:x".into()) } + ); + assert!(parse_client_request("tail", &s(&["--room", "a", "--room", "b"])).is_err()); + + assert_eq!( + parse_client_request("say", &s(&["--room", "#r:x", "--text", "hi"])).unwrap(), + Request::Say { room: "#r:x".into(), text: Some("hi".into()), resend: None } + ); + assert_eq!( + parse_client_request("say", &s(&["--room", "#r:x", "--resend", "mc-1"])).unwrap(), + Request::Say { room: "#r:x".into(), text: None, resend: Some("mc-1".into()) } + ); + assert!(parse_client_request("say", &s(&["--room", "#r:x"])).is_err()); + assert!(parse_client_request("say", &s(&["--room", "#r:x", "--text", "hi", "--resend", "mc-1"])).is_err()); + + assert_eq!(parse_client_request("ack", &s(&["--through", "42"])).unwrap(), Request::Ack { through: 42 }); + assert!(parse_client_request("ack", &s(&["--through", "nope"])).is_err()); + assert!(parse_client_request("ack", &[]).is_err()); + + assert_eq!( + parse_client_request("mark-read", &s(&["--room", "!r:x", "--event", "$e1", "--at", "99"])).unwrap(), + Request::MarkRead { room: "!r:x".into(), event: "$e1".into(), at_unix_ms: 99 } + ); + assert!(parse_client_request("mark-read", &s(&["--room", "!r:x", "--event", "$e1", "--at", "x"])).is_err()); + + assert_eq!( + parse_client_request("open-direct", &s(&["--user", "@u:x", "--text", "hello"])).unwrap(), + Request::OpenDirect { user: "@u:x".into(), text: "hello".into() } + ); + assert!(parse_client_request("open-direct", &s(&["--user", "@u:x"])).is_err()); + + assert_eq!(parse_client_request("status", &[]).unwrap(), Request::Status); + assert!(parse_client_request("status", &s(&["extra"])).is_err()); + assert!(parse_client_request("unknown", &[]).is_err()); + } + + #[test] + fn parse_gate_args_and_helpers() { + assert_eq!(split_csv(" @a:x , , @b:x "), s(&["@a:x", "@b:x"])); + assert_eq!(split_csv(" , "), Vec::::new()); + assert!(now_ms() > 1_700_000_000_000); + + #[cfg(unix)] + { + restrict_umask(); + // SAFETY: restores the prior umask after observing restrict_umask(). + let prev = unsafe { libc::umask(0o022) }; + assert_eq!(prev, 0o077); + } + + let no_env = |_: &str| None; + let (cfg, sock) = parse_gate_args( + &s(&[ + "--instance", + "nibu", + "--socket", + "/tmp/g.sock", + "--state-dir", + "/tmp/st", + "--minds", + "@nibu:x,@eureka:x", + "--operators", + "@meta:x", + "--own-sender", + "@nibu:x", + "--daily-cap", + "12", + ]), + &no_env, + ) + .unwrap(); + assert_eq!(cfg.instance.0, "nibu"); + assert_eq!(sock, PathBuf::from("/tmp/g.sock")); + assert_eq!(cfg.state_dir, PathBuf::from("/tmp/st")); + assert_eq!(cfg.minds, s(&["@nibu:x", "@eureka:x"])); + assert_eq!(cfg.operators, s(&["@meta:x"])); + assert_eq!(cfg.own_sender, "@nibu:x"); + assert_eq!(cfg.daily_cap, Some(12)); + + let from_env = |k: &str| match k { + "MIND_PERSONA_MINDS" => Some("@a:x,@b:x".into()), + "MIND_PERSONA_OPERATOR" => Some("@op:x".into()), + "MIND_PERSONA_SELF_SENDER" => Some("@a:x".into()), + "MIND_CHAT_DAILY_CAP" => Some("5".into()), + _ => None, + }; + let (env_cfg, _) = parse_gate_args( + &s(&["--instance", "a", "--socket", "/tmp/s", "--state-dir", "/tmp/d"]), + &from_env, + ) + .unwrap(); + assert_eq!(env_cfg.minds, s(&["@a:x", "@b:x"])); + assert_eq!(env_cfg.operators, s(&["@op:x"])); + assert_eq!(env_cfg.own_sender, "@a:x"); + assert_eq!(env_cfg.daily_cap, Some(5)); + + assert!(parse_gate_args(&s(&["--instance", "nibu", "--socket", "/s", "--state-dir", "/d", "--own-sender", "@a", "--daily-cap", "bad"]), &no_env).is_err()); + assert!(parse_gate_args(&s(&["--socket", "/s", "--state-dir", "/d", "--own-sender", "@a"]), &no_env).is_err()); + assert!(parse_gate_args(&s(&["--instance", "nibu", "--state-dir", "/d", "--own-sender", "@a"]), &no_env).is_err()); + assert!(parse_gate_args(&s(&["--instance", "nibu", "--socket", "/s", "--own-sender", "@a"]), &no_env).is_err()); + assert!(parse_gate_args(&s(&["--instance", "nibu", "--socket", "/s", "--state-dir", "/d"]), &no_env).is_err()); + } +} diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs index ced7893..7e4092b 100644 --- a/crates/mind-body/src/chat_gate.rs +++ b/crates/mind-body/src/chat_gate.rs @@ -214,13 +214,7 @@ impl Engine { let minds = self.all_minds(); let window_ms = u64::try_from(EXCHANGE_MINUTES * 60_000).unwrap_or(0); let fact_lines = collect_delivery_fact_lines(&pending.deliveries); - let facts = line_facts( - &fact_lines.iter().map(|(line, _)| *line).collect::>(), - &self.config.own_sender, - &minds, - &[], - window_ms, - ); + let facts = line_facts(&fact_lines, &self.config.own_sender, &minds, &[], window_ms); let batch_hit_backstop = facts.iter().any(|fact| fact.mind_run >= MIND_RUN_BACKSTOP); let mut max_seq = self.state.after_seq; @@ -787,30 +781,21 @@ fn trailing_mind_run(room: &RoomState, room_key: &str, own_sender: &str, minds: .map_or(0, |facts| facts.mind_run) } -fn collect_delivery_fact_lines<'a>(deliveries: &'a [ChatDelivery]) -> Vec<(FactLine<'a>, Option)> { - let mut lines: Vec<(FactLine<'a>, Option)> = Vec::new(); - for (index, delivery) in deliveries.iter().enumerate() { +fn collect_delivery_fact_lines<'a>(deliveries: &'a [ChatDelivery]) -> Vec> { + let mut lines: Vec> = Vec::new(); + let mut push_unique = |sender: &'a str, room: &'a str, at_ms: u64| { + if !lines.iter().any(|held| held.room == room && held.sender == sender && held.at_ms == at_ms) { + lines.push(FactLine { sender, room, at_ms }); + } + }; + for delivery in deliveries { let room = delivery.room_alias.as_str(); for ctx in &delivery.context { - if !lines - .iter() - .any(|(held, _)| held.room == room && held.sender == ctx.sender && held.at_ms == ctx.at_unix_ms) - { - lines.push((FactLine { sender: &ctx.sender, room, at_ms: ctx.at_unix_ms }, None)); - } - } - match lines - .iter_mut() - .find(|(held, _)| held.room == room && held.sender == delivery.sender && held.at_ms == delivery.at_unix_ms) - { - Some((_, slot)) => *slot = Some(index), - None => lines.push(( - FactLine { sender: &delivery.sender, room, at_ms: delivery.at_unix_ms }, - Some(index), - )), + push_unique(&ctx.sender, room, ctx.at_unix_ms); } + push_unique(&delivery.sender, room, delivery.at_unix_ms); } - lines.sort_by_key(|(line, _)| line.at_ms); + lines.sort_by_key(|line| line.at_ms); lines } @@ -1002,10 +987,40 @@ mod tests { let mut engine = Engine::open(cfg(dir.path(), Some(2)), mock, t0).unwrap(); let p = engine.handle(Request::Pending { ack: true }, t0 + 1000).unwrap(); assert_eq!(p.exit, 0); - assert!(p.stdout.contains("$ev1"), "{}", p.stdout); + assert!(p.stdout.contains("$ev1") && !p.stdout.contains("backstop"), "{}", p.stdout); + assert_eq!(engine.chat.acks.borrow().as_slice(), &[1]); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let state_mode = fs::metadata(dir.path().join(STATE_FILE)).unwrap().permissions().mode() & 0o777; + assert_eq!(state_mode, 0o600); + } + + // Empty pending with ack=true must not re-ack; unacked pending must not ack at all. + engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![], + tail: None, + tail_gaps: vec![], + })); + let empty_ack = engine.handle(Request::Pending { ack: true }, t0 + 1100).unwrap(); + assert_eq!(empty_ack.exit, 0); + assert!(!empty_ack.stdout.contains("acked"), "{}", empty_ack.stdout); assert_eq!(engine.chat.acks.borrow().as_slice(), &[1]); - // 2. RoomMoved refuses say exit 1 with newer IDs and does NOT advance seen_event_id. + engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![delivery(2, "#swarm:gamecult.org", "$ev1b", "@meta:gamecult.org", t0 + 1200, "h2")], + tail: None, + tail_gaps: vec![], + })); + let no_ack = engine.handle(Request::Pending { ack: false }, t0 + 1200).unwrap(); + assert_eq!(no_ack.exit, 0); + assert!(!no_ack.stdout.contains("acked"), "{}", no_ack.stdout); + assert_eq!(engine.chat.acks.borrow().as_slice(), &[1]); + assert_eq!(engine.state.after_seq, 1); + + // RoomMoved using room_id alias proves alias mapping was recorded on pending, refuses say exit 1 with newer IDs, and does NOT advance seen_event_id. engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { request_id: "x".into(), event_id: None, @@ -1014,43 +1029,67 @@ mod tests { })); let moved = engine .handle( - Request::Say { room: "#swarm:gamecult.org".into(), text: Some("reply".into()), resend: None }, + Request::Say { room: "!#swarm:gamecult.org:gamecult.org".into(), text: Some("reply".into()), resend: None }, t0 + 2000, ) .unwrap(); assert_eq!(moved.exit, 1); assert!(moved.stdout.contains("RoomMoved") && moved.stdout.contains("$ev2,$ev3"), "{}", moved.stdout); + assert_eq!(engine.chat.sent.borrow().last().unwrap().request_id, format!("mc-{}-1", t0 + 2000)); assert_eq!( engine.chat.sent.borrow().last().unwrap().basis, - Some(SendBasis { seen_event_id: Some("$ev1".into()), since_unix_ms: t0 }) + Some(SendBasis { seen_event_id: Some("$ev1b".into()), since_unix_ms: t0 }) ); assert_eq!( engine.state.rooms.get("#swarm:gamecult.org").and_then(|r| r.seen_event_id.as_deref()), - Some("$ev1") + Some("$ev1b") ); - // tail displays $ev3 and advances seen_event_id. + // tail filters out other rooms and formats lines, newlines, timestamps, and matching tail_gaps. engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { persona: "nibu".into(), deliveries: vec![], - tail: Some(vec![TailLine { - room: "#swarm:gamecult.org".into(), - event_id: "$ev3".into(), - at_unix_ms: t0 + 2500, - sender: "@meta:gamecult.org".into(), - form: Form::Message, - basis: None, - body: "later".into(), - reply_to: ReplyLink::Absent, - }]), - tail_gaps: vec![], + tail: Some(vec![ + TailLine { + room: "#other:gamecult.org".into(), + event_id: "$other1".into(), + at_unix_ms: t0 + 2400, + sender: "@meta:gamecult.org".into(), + form: Form::Message, + basis: None, + body: "skip me".into(), + reply_to: ReplyLink::Absent, + }, + TailLine { + room: "#swarm:gamecult.org".into(), + event_id: "$ev3".into(), + at_unix_ms: t0 + 2500, + sender: "@meta:gamecult.org".into(), + form: Form::Message, + basis: None, + body: "later\nline2".into(), + reply_to: ReplyLink::Absent, + }, + ]), + tail_gaps: vec!["#other:gamecult.org".into(), "#swarm:gamecult.org".into()], })); - let tailed = engine.handle(Request::Tail { room: Some("#swarm:gamecult.org".into()) }, t0 + 2600).unwrap(); + let tailed = engine.handle(Request::Tail { room: Some("!#swarm:gamecult.org:gamecult.org".into()) }, t0 + 2600).unwrap(); assert_eq!(tailed.exit, 0); + assert!( + tailed.stdout.contains("tail room=#swarm:gamecult.org event=$ev3 at=") + && tailed.stdout.contains("T") + && tailed.stdout.contains("body=later\\nline2") + && tailed.stdout.contains("tail_gap #swarm:gamecult.org") + && !tailed.stdout.contains("$other1") + && !tailed.stdout.contains("tail_gap #other:gamecult.org"), + "{}", + tailed.stdout + ); assert_eq!( engine.state.rooms.get("#swarm:gamecult.org").and_then(|r| r.seen_event_id.as_deref()), Some("$ev3") ); + assert_eq!(engine.state.rooms.get("#other:gamecult.org").and_then(|r| r.seen_event_id.as_deref()), None); // 3. NoAnswer leaves unsettled 1800s pending_send blocking second say until --resend. engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { @@ -1074,16 +1113,19 @@ mod tests { .unwrap() .request_id .clone(); + assert_eq!(pending_id, format!("mc-{}-2", t0 + 3000)); - // Second say inside 1800s is blocked. - let blocked = engine - .handle( - Request::Say { room: "#swarm:gamecult.org".into(), text: Some("second".into()), resend: None }, - t0 + 4000, - ) - .unwrap(); - assert_eq!(blocked.exit, 1); - assert!(blocked.stdout.contains("room_unsettled"), "{}", blocked.stdout); + // Second say inside 1800s (beyond 2.8s AND at exact UNSETTLED_WINDOW_MS - 1) is blocked. + for dt in [5000_u64, UNSETTLED_WINDOW_MS - 1] { + let blocked = engine + .handle( + Request::Say { room: "#swarm:gamecult.org".into(), text: Some("second".into()), resend: None }, + t0 + 3000 + dt, + ) + .unwrap(); + assert_eq!(blocked.exit, 1, "dt={dt}: {}", blocked.stdout); + assert!(blocked.stdout.contains("room_unsettled"), "{}", blocked.stdout); + } // --resend settles it and increments daily_says (1/2). engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { @@ -1102,30 +1144,31 @@ mod tests { assert!(resent.stdout.contains("$ev4"), "{}", resent.stdout); assert!(engine.chat.sent.borrow().last().unwrap().resend); - // 4. 4 consecutive Mind lines inside 30m trigger MIND_RUN_BACKSTOP. - // We already have $ev4 from @nibu at t0+5000 (1 Mind line). Add 3 more Mind lines in #swarm. + // 4. 4 consecutive Mind lines spaced 2 minutes apart (< 30m EXCHANGE_MINUTES, > 60s) trigger MIND_RUN_BACKSTOP. + // $ev4 from @nibu is at t0+5000 (1 Mind line). Add 3 more Mind lines spaced 120_000ms apart. engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { persona: "nibu".into(), deliveries: vec![ - delivery(2, "#swarm:gamecult.org", "$ev5", "@eureka:gamecult.org", t0 + 6000, "m2"), - delivery(3, "#swarm:gamecult.org", "$ev6", "@nibu:gamecult.org", t0 + 7000, "m3"), - delivery(4, "#swarm:gamecult.org", "$ev7", "@eureka:gamecult.org", t0 + 8000, "m4"), + delivery(3, "#swarm:gamecult.org", "$ev5", "@eureka:gamecult.org", t0 + 125_000, "m2"), + delivery(4, "#swarm:gamecult.org", "$ev6", "@nibu:gamecult.org", t0 + 245_000, "m3"), + delivery(5, "#swarm:gamecult.org", "$ev7", "@eureka:gamecult.org", t0 + 365_000, "m4"), ], tail: None, tail_gaps: vec![], })); - let p2 = engine.handle(Request::Pending { ack: false }, t0 + 8500).unwrap(); + let p2 = engine.handle(Request::Pending { ack: false }, t0 + 365_500).unwrap(); assert!(p2.stdout.contains("MIND_RUN_BACKSTOP"), "{}", p2.stdout); let backstopped = engine .handle( Request::Say { room: "#swarm:gamecult.org".into(), text: Some("5th mind line".into()), resend: None }, - t0 + 9000, + t0 + 366_000, ) .unwrap(); assert_eq!(backstopped.exit, 1); assert!(backstopped.stdout.contains("mind_run_backstop"), "{}", backstopped.stdout); - // 5. UTC daily cap (2/2) blocks both say (in another room) and open-direct. + // 5. UTC daily cap (2/2) blocks both say (in another room) and open-direct; + // next_send_seq advances past 2 (to 3) on open-direct and 4 on next say. engine.chat.open_replies.borrow_mut().push_back(Ok(ChatOpenDirectReceipt { request_id: "od".into(), outcome: DirectOutcome::Opened, @@ -1135,15 +1178,16 @@ mod tests { let dm_ok = engine .handle( Request::OpenDirect { user: "@meta:gamecult.org".into(), text: "hello".into() }, - t0 + 10_000, + t0 + 370_000, ) .unwrap(); assert_eq!(dm_ok.exit, 0); + assert_eq!(engine.chat.opened.borrow().last().unwrap().request_id, format!("od-{}-3", t0 + 370_000)); let say_capped = engine .handle( Request::Say { room: "#other:gamecult.org".into(), text: Some("over cap".into()), resend: None }, - t0 + 11_000, + t0 + 371_000, ) .unwrap(); assert_eq!(say_capped.exit, 1); @@ -1152,35 +1196,45 @@ mod tests { let dm_capped = engine .handle( Request::OpenDirect { user: "@meta:gamecult.org".into(), text: "over cap".into() }, - t0 + 12_000, + t0 + 372_000, ) .unwrap(); assert_eq!(dm_capped.exit, 1); assert!(dm_capped.stdout.contains("daily_cap"), "{}", dm_capped.stdout); - // 6. mark-read, ack, and status round-trip. + // 6. mark-read / open-direct blank validation, valid mark-read, ack, and status round-trip. + for bad_req in [ + Request::MarkRead { room: " ".into(), event: "$ev7".into(), at_unix_ms: 1 }, + Request::MarkRead { room: "#swarm:gamecult.org".into(), event: " ".into(), at_unix_ms: 1 }, + Request::OpenDirect { user: " ".into(), text: "hi".into() }, + Request::OpenDirect { user: "@meta:gamecult.org".into(), text: " ".into() }, + ] { + let bad = engine.handle(bad_req, t0 + 372_050).unwrap(); + assert_eq!(bad.exit, 2, "{}", bad.stderr); + } + let rd = engine .handle( - Request::MarkRead { room: "!#swarm:gamecult.org:gamecult.org".into(), event: "$ev7".into(), at_unix_ms: t0 + 8000 }, - t0 + 12_100, + Request::MarkRead { room: "!#swarm:gamecult.org:gamecult.org".into(), event: "$ev7".into(), at_unix_ms: t0 + 365_000 }, + t0 + 372_100, ) .unwrap(); assert_eq!(rd.exit, 0); assert_eq!(engine.chat.reads.borrow().last().unwrap().persona, "nibu"); - let ak = engine.handle(Request::Ack { through: 4 }, t0 + 12_200).unwrap(); + let ak = engine.handle(Request::Ack { through: 5 }, t0 + 372_200).unwrap(); assert_eq!(ak.exit, 0); - assert_eq!(engine.state.after_seq, 4); + assert_eq!(engine.state.after_seq, 5); - let st = engine.handle(Request::Status, t0 + 12_300).unwrap(); + let st = engine.handle(Request::Status, t0 + 372_300).unwrap(); assert_eq!(st.exit, 0); - assert!(st.stdout.contains("after_seq 4") && st.stdout.contains("daily_says 2/2"), "{}", st.stdout); + assert!(st.stdout.contains("after_seq 5") && st.stdout.contains("daily_says 2/2"), "{}", st.stdout); // 7. Reloading from chat-gate.json preserves cursors & refuses wrong instance; // next UTC day resets daily cap, and 30m silence resets MIND_RUN_BACKSTOP. let mut wrong_cfg = cfg(dir.path(), Some(2)); wrong_cfg.instance = Slug("eureka".into()); - assert!(Engine::open(wrong_cfg, MockChat::new(), t0 + 13_000).is_err()); + assert!(Engine::open(wrong_cfg, MockChat::new(), t0 + 373_000).is_err()); let t_next_day = t0 + 24 * 3600 * 1000 + 1000; let mock2 = MockChat::new(); @@ -1191,7 +1245,7 @@ mod tests { newer: vec![], })); let mut reloaded = Engine::open(cfg(dir.path(), Some(2)), mock2, t_next_day).unwrap(); - assert_eq!(reloaded.state.after_seq, 4); + assert_eq!(reloaded.state.after_seq, 5); let after_silence = reloaded .handle( Request::Say { room: "#swarm:gamecult.org".into(), text: Some("after silence".into()), resend: None }, @@ -1199,6 +1253,7 @@ mod tests { ) .unwrap(); assert_eq!(after_silence.exit, 0, "{}", after_silence.stdout); + assert_eq!(reloaded.chat.sent.borrow().last().unwrap().request_id, format!("mc-{t_next_day}-4")); // 8. Unsettled pending_send expires past 1800s allowing fresh say, while --resend refuses. reloaded.chat.send_replies.borrow_mut().push_back(Err(anyhow!("socket timeout"))); @@ -1242,13 +1297,100 @@ mod tests { assert_eq!(fresh_after_exp.exit, 0); } + #[test] + fn context_dedupe_batch_backstop_own_sender_inclusion_and_room_lines_cap() { + use crate::chat_client::ContextLine; + + let dir = tempfile::tempdir().unwrap(); + let t0 = 1_765_100_000_000_u64; + + // 1. config.minds omits own_sender: all_minds includes own_sender (no duplicate if absent); + // 3 distinct Mind lines (with shared context across 2 deliveries) must NOT hit backstop, + // while 4 Mind lines in one batch followed by a human line MUST trigger batch_hit_backstop. + let mut own_omitted = cfg(dir.path(), None); + own_omitted.minds = vec!["@eureka:gamecult.org".into()]; + let mut eng = Engine::open(own_omitted, MockChat::new(), t0).unwrap(); + + let shared_ctx = vec![ + ContextLine { sender: "@nibu:gamecult.org".into(), at_unix_ms: t0 + 1000, text: "c1".into() }, + ContextLine { sender: "@eureka:gamecult.org".into(), at_unix_ms: t0 + 1000, text: "c2".into() }, + ContextLine { sender: "@meta:gamecult.org".into(), at_unix_ms: t0 + 2000, text: "c3".into() }, + ]; + let mut d_overlap = delivery(1, "#dedupe:gamecult.org", "$d1", "@nibu:gamecult.org", t0 + 1000, "real c1"); + d_overlap.context = shared_ctx.clone(); + let d_human_ctx = delivery(2, "#dedupe:gamecult.org", "$d0", "@meta:gamecult.org", t0 + 1000, "human same ts"); + let mut d_third = delivery(3, "#dedupe:gamecult.org", "$d2", "@nibu:gamecult.org", t0 + 2500, "m3"); + d_third.context = vec![ + ContextLine { sender: "@nibu:gamecult.org".into(), at_unix_ms: t0 + 1000, text: "c1".into() }, + ContextLine { sender: "@nibu:gamecult.org".into(), at_unix_ms: t0 + 2500, text: "c4".into() }, + ]; + let mut d_after_ctx = delivery(4, "#dedupe:gamecult.org", "$d2b", "@nibu:gamecult.org", t0 + 2500, "real m3"); + d_after_ctx.context = vec![ContextLine { sender: "@nibu:gamecult.org".into(), at_unix_ms: t0 + 3000, text: "c5".into() }]; + // Same timestamp + sender in another room + distinct sender @meta at same timestamp in #dedupe: + let d_other_room = delivery(5, "#b:gamecult.org", "$b1", "@nibu:gamecult.org", t0 + 1000, "other room"); + let d_human_same_ts = delivery(6, "#dedupe:gamecult.org", "$h1", "@meta:gamecult.org", t0 + 2500, "human"); + eng.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![d_overlap, d_human_ctx, d_third, d_after_ctx, d_other_room, d_human_same_ts], + tail: None, + tail_gaps: vec![], + })); + let no_bs = eng.handle(Request::Pending { ack: true }, t0 + 4000).unwrap(); + assert!(!no_bs.stdout.contains("backstop"), "3 distinct Mind lines must not backstop: {}", no_bs.stdout); + // Ensure real deliveries replace matching ctx:... entries while preserving distinct senders/timestamps. + let dedupe_lines = &eng.state.rooms.get("#dedupe:gamecult.org").unwrap().lines; + let ids: Vec<&str> = dedupe_lines.iter().map(|l| l.event_id.as_str()).collect(); + assert!(ids.contains(&"$d1") && ids.contains(&"$d0") && ids.contains(&"$d2b") && ids.contains(&"$h1"), "{ids:?}"); + assert!(ids.contains(&format!("ctx:{}:@eureka:gamecult.org", t0 + 1000).as_str()), "{ids:?}"); + assert!(ids.contains(&format!("ctx:{}:@meta:gamecult.org", t0 + 2000).as_str()), "{ids:?}"); + assert!(ids.contains(&format!("ctx:{}:@nibu:gamecult.org", t0 + 3000).as_str()), "{ids:?}"); + assert!(!ids.contains(&format!("ctx:{}:@nibu:gamecult.org", t0 + 1000).as_str()), "{ids:?}"); + assert!(!ids.contains(&format!("ctx:{}:@nibu:gamecult.org", t0 + 2500).as_str()), "{ids:?}"); + + // 2. Batch with 4 Mind lines in #b followed by human line -> batch_hit_backstop fires + // even though trailing_mind_run in #b is 0! Putting an identical (sender, ts) in #other2 + // and a second Mind sender at the same ts in #b kills room/sender/at_ms predicate mutants. + eng.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![ + delivery(5, "#other2:gamecult.org", "$o1", "@nibu:gamecult.org", t0 + 130_000, "other"), + delivery(6, "#b:gamecult.org", "$b2", "@nibu:gamecult.org", t0 + 130_000, "m1"), + delivery(7, "#b:gamecult.org", "$b3", "@eureka:gamecult.org", t0 + 130_000, "m2"), + delivery(8, "#b:gamecult.org", "$b4", "@nibu:gamecult.org", t0 + 250_000, "m3"), + delivery(9, "#b:gamecult.org", "$b4b", "@eureka:gamecult.org", t0 + 370_000, "m4"), + delivery(10, "#b:gamecult.org", "$b5", "@meta:gamecult.org", t0 + 380_000, "human break"), + ], + tail: None, + tail_gaps: vec![], + })); + let batch_bs = eng.handle(Request::Pending { ack: true }, t0 + 381_000).unwrap(); + assert!(batch_bs.stdout.contains("MIND_RUN_BACKSTOP"), "{}", batch_bs.stdout); + + // 3. Pushing 35 lines into a room caps stored history at ROOM_LINES_CAP (32), keeping newest. + let many: Vec = (0..35_u64) + .map(|i| delivery(20 + i, "#cap:gamecult.org", &format!("$c{i}"), "@meta:gamecult.org", t0 + 500_000 + i * 1000, "x")) + .collect(); + eng.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: many, + tail: None, + tail_gaps: vec![], + })); + let cap_ans = eng.handle(Request::Pending { ack: true }, t0 + 600_000).unwrap(); + assert_eq!(cap_ans.exit, 0); + let kept = &eng.state.rooms.get("#cap:gamecult.org").unwrap().lines; + assert_eq!(kept.len(), ROOM_LINES_CAP); + assert_eq!(kept[0].event_id, "$c3"); + assert_eq!(kept[ROOM_LINES_CAP - 1].event_id, "$c34"); + } + #[cfg(unix)] #[test] fn unix_socket_gate_forces_instance_persona_and_0600_mode() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); - let sock = dir.path().join("gate.sock"); + let sock = dir.path().join("nested").join("gate.sock"); let mock = MockChat::new(); let t0 = 1_765_000_000_000_u64; mock.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { @@ -1257,6 +1399,12 @@ mod tests { refusal: None, newer: vec![], })); + mock.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: Some("$s2".into()), + refusal: None, + newer: vec![], + })); let recorded_persona = std::sync::Arc::new(std::sync::Mutex::new(String::new())); let recorded_clone = std::sync::Arc::clone(&recorded_persona); @@ -1276,21 +1424,37 @@ mod tests { let sock_srv = sock.clone(); let state_dir = dir.path().join("state"); let handle = std::thread::spawn(move || { - socket::serve(cfg(&state_dir, None), SpyChat(mock, recorded_clone), &sock_srv, || t0, Some(1)).unwrap(); + socket::serve(cfg(&state_dir, None), SpyChat(mock, recorded_clone), &sock_srv, || t0, Some(2)).unwrap(); }); - while !sock.exists() { + for _ in 0..300 { + if sock.exists() { + break; + } std::thread::sleep(std::time::Duration::from_millis(10)); } + assert!(sock.exists(), "socket did not bind in time"); let mode = fs::metadata(&sock).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o600); - let ans = call_socket( + // Request > 2048 bytes catches MAX_LINE_BYTES (1024 * 1024 vs 1024 + 1024). + let big_text = "a".repeat(4096); + let ans1 = call_socket( &sock, - &Request::Say { room: "#swarm:gamecult.org".into(), text: Some("from sandbox".into()), resend: None }, + &Request::Say { room: "#swarm:gamecult.org".into(), text: Some(big_text), resend: None }, ) .unwrap(); - assert_eq!(ans.exit, 0); - assert!(ans.stdout.contains("Posted $s1"), "{}", ans.stdout); + assert_eq!(ans1.exit, 0); + assert!(ans1.stdout.contains("Posted $s1"), "{}", ans1.stdout); + + // Second request exercises max_requests = Some(2) boundary (0+1 < 2, 1+1 >= 2). + let ans2 = call_socket( + &sock, + &Request::Say { room: "#swarm:gamecult.org".into(), text: Some("second".into()), resend: None }, + ) + .unwrap(); + assert_eq!(ans2.exit, 0); + assert!(ans2.stdout.contains("Posted $s2"), "{}", ans2.stdout); + handle.join().unwrap(); assert_eq!(recorded_persona.lock().unwrap().as_str(), "nibu"); } diff --git a/crates/mind-body/tests/mind_chat_bin.rs b/crates/mind-body/tests/mind_chat_bin.rs new file mode 100644 index 0000000..7a3cd26 --- /dev/null +++ b/crates/mind-body/tests/mind_chat_bin.rs @@ -0,0 +1,129 @@ +//! Subprocess boundary checks for the `mind-chat` binary (`main`, `setting`, `required_env`, `run_gate`, `MIND_CHAT_SOCKET`). + +use std::process::{Command, Output}; + +fn run(envs: &[(&str, &str)], args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_mind-chat")) + .args(args) + .env_clear() + .envs(envs.iter().copied()) + .output() + .unwrap() +} + +fn text(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() +} + +#[test] +fn mind_chat_binary_modes_env_handling_and_usage() { + let dir = tempfile::tempdir().unwrap(); + + // 1. Empty args and --help print usage and exit 0. + for help_args in [&[][..], &["--help"][..]] { + let out = run(&[], help_args); + assert_eq!(out.status.code(), Some(0), "{help_args:?}: {}", text(&out.stderr)); + assert!(text(&out.stdout).contains("usage:"), "{}", text(&out.stdout)); + } + + // 2. Client usage errors exit 2. + let bad_client = run(&[], &["say", "--room", "#r:x"]); + assert_eq!(bad_client.status.code(), Some(2), "{}", text(&bad_client.stderr)); + assert!(text(&bad_client.stderr).starts_with("InvalidInput:"), "{}", text(&bad_client.stderr)); + + // 3. `gate` dispatches cleanly and validates required settings (no ok(()) bypass). + let bad_gate = run(&[], &["gate", "--unknown"]); + assert_eq!(bad_gate.status.code(), Some(2)); + assert!(text(&bad_gate.stderr).starts_with("mind-chat:"), "{}", text(&bad_gate.stderr)); + + let sock_path = dir.path().join("gate.sock"); + let state_dir = dir.path().join("state"); + let missing_endpoint = run( + &[], + &[ + "gate", + "--instance", + "nibu", + "--socket", + sock_path.to_str().unwrap(), + "--state-dir", + state_dir.to_str().unwrap(), + "--own-sender", + "@nibu:gamecult.org", + ], + ); + assert_eq!(missing_endpoint.status.code(), Some(2)); + assert!( + text(&missing_endpoint.stderr).contains("BIFROST_CHAT_ENDPOINT is not set"), + "{}", + text(&missing_endpoint.stderr) + ); + + // 4. Empty MIND_CHAT_SOCKET falls back to direct mode (Misconfigured exit 2); + // missing socket path connects over Unix socket (Unavailable exit 3). + for envs in [&[][..], &[("MIND_CHAT_SOCKET", "")][..]] { + let empty_sock = run(envs, &["status"]); + assert_eq!(empty_sock.status.code(), Some(2), "{envs:?}: {}", text(&empty_sock.stderr)); + assert!( + text(&empty_sock.stderr).contains("EUREKA_INSTANCE is not set"), + "{}", + text(&empty_sock.stderr) + ); + } + + let missing_sock = run(&[("MIND_CHAT_SOCKET", sock_path.to_str().unwrap())], &["status"]); + assert_eq!(missing_sock.status.code(), Some(3)); + assert!(text(&missing_sock.stderr).starts_with("Unavailable:"), "{}", text(&missing_sock.stderr)); + + // 5. Direct mode checks BIFROST_CHAT_KEY_FILE via required_env (Misconfigured exit 2, not Unavailable). + let missing_key = run( + &[ + ("EUREKA_INSTANCE", "nibu"), + ("STATE_DIRECTORY", state_dir.to_str().unwrap()), + ("BIFROST_CHAT_ENDPOINT", "rudp://127.0.0.1:9"), + ], + &["status"], + ); + assert_eq!(missing_key.status.code(), Some(2), "{}", text(&missing_key.stderr)); + assert!( + text(&missing_key.stderr).contains("BIFROST_CHAT_KEY_FILE is not set"), + "{}", + text(&missing_key.stderr) + ); +} + +#[cfg(unix)] +#[test] +fn mind_chat_client_relays_socket_stdout_stderr_and_exit_code() { + use std::io::{BufRead, BufReader, Write}; + use std::os::unix::net::UnixListener; + + let dir = tempfile::tempdir().unwrap(); + let sock = dir.path().join("mock-gate.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + + let srv = std::thread::spawn(move || { + for reply in [ + r#"{"exit":0,"stdout":"ok-status","stderr":""}"#, + r#"{"exit":1,"stdout":"","stderr":"refused-detail"}"#, + ] { + let (mut stream, _) = listener.accept().unwrap(); + let mut line = String::new(); + BufReader::new(&stream).read_line(&mut line).unwrap(); + writeln!(stream, "{reply}").unwrap(); + stream.flush().unwrap(); + } + }); + + let ok = run(&[("MIND_CHAT_SOCKET", sock.to_str().unwrap())], &["status"]); + assert_eq!(ok.status.code(), Some(0)); + assert_eq!(text(&ok.stdout), "ok-status\n"); + assert_eq!(text(&ok.stderr), ""); + + let refused = run(&[("MIND_CHAT_SOCKET", sock.to_str().unwrap())], &["pending"]); + assert_eq!(refused.status.code(), Some(1)); + assert_eq!(text(&refused.stdout), ""); + assert_eq!(text(&refused.stderr), "refused-detail\n"); + + srv.join().unwrap(); +} From bc98bf088e5ad125f116c6fccd741e1a12b62cd9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 12:40:02 +0100 Subject: [PATCH 10/12] Kill remaining testable chat_gate mutants with boundary tests --- crates/mind-body/src/chat_gate.rs | 47 +++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs index 7e4092b..e1c62a3 100644 --- a/crates/mind-body/src/chat_gate.rs +++ b/crates/mind-body/src/chat_gate.rs @@ -1282,6 +1282,15 @@ mod tests { assert_eq!(late_resend.exit, 1); assert!(late_resend.stdout.contains("ResendUnknown"), "{}", late_resend.stdout); + // Fresh say at EXACT UNSETTLED_WINDOW_MS boundary succeeds even while pending_send is still stored. + reloaded.chat.send_replies.borrow_mut().push_back(Err(anyhow!("socket timeout"))); + let timed_out_exact = reloaded + .handle( + Request::Say { room: "#exp2:gamecult.org".into(), text: Some("lost2".into()), resend: None }, + t_expired + 100, + ) + .unwrap(); + assert_eq!(timed_out_exact.exit, 3); reloaded.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { request_id: "x".into(), event_id: Some("$ev9".into()), @@ -1290,11 +1299,11 @@ mod tests { })); let fresh_after_exp = reloaded .handle( - Request::Say { room: "#exp:gamecult.org".into(), text: Some("fresh".into()), resend: None }, - t_expired + 1, + Request::Say { room: "#exp2:gamecult.org".into(), text: Some("fresh".into()), resend: None }, + t_expired + 100 + UNSETTLED_WINDOW_MS, ) .unwrap(); - assert_eq!(fresh_after_exp.exit, 0); + assert_eq!(fresh_after_exp.exit, 0, "{}", fresh_after_exp.stdout); } #[test] @@ -1366,6 +1375,26 @@ mod tests { let batch_bs = eng.handle(Request::Pending { ack: true }, t0 + 381_000).unwrap(); assert!(batch_bs.stdout.contains("MIND_RUN_BACKSTOP"), "{}", batch_bs.stdout); + // 2b. Human break in #hbreak at the exact same (sender, ts) as a prior human line in #other_h + // must NOT be deduped across rooms (kills held.room == room -> !=). + eng.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![ + delivery(11, "#hbreak:gamecult.org", "$hb1", "@nibu:gamecult.org", t0 + 400_000, "m1"), + delivery(12, "#hbreak:gamecult.org", "$hb2", "@eureka:gamecult.org", t0 + 405_000, "m2"), + delivery(13, "#hbreak:gamecult.org", "$hb3", "@nibu:gamecult.org", t0 + 410_000, "m3"), + delivery(14, "#other_h:gamecult.org", "$oh1", "@meta:gamecult.org", t0 + 415_000, "other human"), + delivery(15, "#hbreak:gamecult.org", "$hb_human", "@meta:gamecult.org", t0 + 415_000, "human break"), + delivery(16, "#hbreak:gamecult.org", "$hb4", "@nibu:gamecult.org", t0 + 420_000, "m4"), + delivery(17, "#hbreak:gamecult.org", "$hb5", "@eureka:gamecult.org", t0 + 425_000, "m5"), + delivery(18, "#hbreak:gamecult.org", "$hb6", "@meta:gamecult.org", t0 + 430_000, "final human"), + ], + tail: None, + tail_gaps: vec![], + })); + let broken_by_human = eng.handle(Request::Pending { ack: true }, t0 + 431_000).unwrap(); + assert!(!broken_by_human.stdout.contains("backstop"), "human break in #hbreak must reset run: {}", broken_by_human.stdout); + // 3. Pushing 35 lines into a room caps stored history at ROOM_LINES_CAP (32), keeping newest. let many: Vec = (0..35_u64) .map(|i| delivery(20 + i, "#cap:gamecult.org", &format!("$c{i}"), "@meta:gamecult.org", t0 + 500_000 + i * 1000, "x")) @@ -1455,7 +1484,19 @@ mod tests { assert_eq!(ans2.exit, 0); assert!(ans2.stdout.contains("Posted $s2"), "{}", ans2.stdout); + for _ in 0..100 { + if handle.is_finished() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(handle.is_finished(), "socket::serve did not stop after max_requests"); handle.join().unwrap(); assert_eq!(recorded_persona.lock().unwrap().as_str(), "nibu"); + + // serve_gate fails loudly when socket parent is an existing regular file. + let regular_file = dir.path().join("not-a-dir"); + fs::write(®ular_file, b"x").unwrap(); + assert!(serve_gate(cfg(&dir.path().join("bad-state"), None), MockChat::new(), ®ular_file.join("gate.sock"), || t0).is_err()); } } From dde1e58df967448d5569629b0f2f70bde998c940 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 13:27:01 +0100 Subject: [PATCH 11/12] Fix four chat_gate Soul findings (pending ack, resend NotSent, socket/tmp race, status deny_unknown_fields) --- crates/mind-body/Cargo.toml | 2 +- crates/mind-body/src/bin/mind-chat.rs | 4 +- crates/mind-body/src/chat_gate.rs | 422 ++++++++++++++++++---- crates/mind-body/tests/public_surface.txt | 2 +- 4 files changed, 355 insertions(+), 75 deletions(-) diff --git a/crates/mind-body/Cargo.toml b/crates/mind-body/Cargo.toml index 2e64aed..dfa5131 100644 --- a/crates/mind-body/Cargo.toml +++ b/crates/mind-body/Cargo.toml @@ -61,7 +61,7 @@ libc = "0.2" # duplicates, as safe calls (the library forbids unsafe code). Already in the # graph through tempfile; this adds its `net` feature, and `fs` for the attachment # saver's descriptor-relative writes (openat, linkat, unlinkat). -rustix = { version = "1", default-features = false, features = ["std", "net", "fs"] } +rustix = { version = "1", default-features = false, features = ["std", "net", "fs", "process"] } # `syn`, `quote` and `proc-macro2` read the library's own source for # tests/public_surface.rs, which pins its public surface. All three are already diff --git a/crates/mind-body/src/bin/mind-chat.rs b/crates/mind-body/src/bin/mind-chat.rs index 12b50f5..55cdf2e 100644 --- a/crates/mind-body/src/bin/mind-chat.rs +++ b/crates/mind-body/src/bin/mind-chat.rs @@ -236,7 +236,7 @@ fn parse_client_request(cmd: &str, args: &[String]) -> Result { if !args.is_empty() { bail!("{USAGE}"); } - Ok(Request::Status) + Ok(Request::Status {}) } _ => bail!("{USAGE}"), } @@ -370,7 +370,7 @@ mod tests { ); assert!(parse_client_request("open-direct", &s(&["--user", "@u:x"])).is_err()); - assert_eq!(parse_client_request("status", &[]).unwrap(), Request::Status); + assert_eq!(parse_client_request("status", &[]).unwrap(), Request::Status {}); assert!(parse_client_request("status", &s(&["extra"])).is_err()); assert!(parse_client_request("unknown", &[]).is_err()); } diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs index e1c62a3..233ab3e 100644 --- a/crates/mind-body/src/chat_gate.rs +++ b/crates/mind-body/src/chat_gate.rs @@ -52,7 +52,7 @@ pub enum Request { Ack { through: u64 }, MarkRead { room: String, event: String, at_unix_ms: u64 }, OpenDirect { user: String, text: String }, - Status, + Status {}, } /// Plain-text response and process exit code (`0` ok, `1` refused, `2` invalid input, `3` unavailable). @@ -178,7 +178,7 @@ impl Engine { Request::Ack { through } => self.ack(through), Request::MarkRead { room, event, at_unix_ms } => self.mark_read(room, event, at_unix_ms), Request::OpenDirect { user, text } => self.open_direct(user, text, now_ms), - Request::Status => Ok(Answer::ok(self.render_status(now_ms))), + Request::Status {} => Ok(Answer::ok(self.render_status(now_ms))), } } @@ -206,6 +206,19 @@ impl Engine { ))); } + let max_seq = pending + .deliveries + .iter() + .fold(self.state.after_seq, |acc, delivery| acc.max(delivery.seq)); + let acked = if ack && max_seq > self.state.after_seq { + if let Err(err) = self.chat.ack(max_seq) { + return Ok(mouth_error_answer(&err)); + } + true + } else { + false + }; + let mut lines = Vec::new(); for warning in reply_warnings(&pending, &mut self.warned_replies) { lines.push(format!("warning {warning}")); @@ -217,10 +230,8 @@ impl Engine { let facts = line_facts(&fact_lines, &self.config.own_sender, &minds, &[], window_ms); let batch_hit_backstop = facts.iter().any(|fact| fact.mind_run >= MIND_RUN_BACKSTOP); - let mut max_seq = self.state.after_seq; let mut touched_rooms = BTreeSet::new(); for delivery in &pending.deliveries { - max_seq = max_seq.max(delivery.seq); if delivery.room_id != delivery.room_alias { self.state.aliases.insert(delivery.room_id.clone(), delivery.room_alias.clone()); } @@ -266,11 +277,7 @@ impl Engine { lines.push(format!("backstop: MIND_RUN_BACKSTOP ({MIND_RUN_BACKSTOP}) reached")); } - if ack && max_seq > self.state.after_seq { - if let Err(err) = self.chat.ack(max_seq) { - write_state_atomic(&self.state_path, &self.state)?; - return Ok(mouth_error_answer(&err)); - } + if acked { self.state.after_seq = max_seq; lines.push(format!("acked {max_seq}")); } @@ -437,28 +444,7 @@ impl Engine { let req_id = send_request.request_id.clone(); match self.chat.send(&send_request) { Ok(receipt) => match (receipt.event_id, receipt.refusal) { - (_, Some(refusal)) => match refusal.reading(is_resend) { - Reading::NoAnswer => Ok(Answer::unavailable(format!( - "Unavailable: {} on {req_id}; retry with --resend {req_id}", - refusal.name() - ))), - Reading::NotSent | Reading::Unknown | Reading::Declined => { - if let Some(room) = self.state.rooms.get_mut(&room_key) { - room.pending_send = None; - } - write_state_atomic(&self.state_path, &self.state)?; - if refusal == Refusal::RoomMoved { - let newer = if receipt.newer.is_empty() { - "-".to_string() - } else { - receipt.newer.join(",") - }; - Ok(Answer::refused(format!("Refused RoomMoved newer={newer}"))) - } else { - Ok(Answer::refused(format!("Refused {}", refusal.name()))) - } - } - }, + (_, Some(refusal)) => self.settle_send_refusal(&room_key, &req_id, is_resend, refusal, &receipt.newer), (Some(event_id), None) => { let room = self.state.rooms.entry(room_key).or_default(); room.pending_send = None; @@ -486,19 +472,7 @@ impl Engine { }, Err(err) => { if let Some(MouthRefused(refusal)) = err.downcast_ref::() { - match refusal.reading(is_resend) { - Reading::NoAnswer => Ok(Answer::unavailable(format!( - "Unavailable: {} on {req_id}; retry with --resend {req_id}", - refusal.name() - ))), - Reading::NotSent | Reading::Unknown | Reading::Declined => { - if let Some(room) = self.state.rooms.get_mut(&room_key) { - room.pending_send = None; - } - write_state_atomic(&self.state_path, &self.state)?; - Ok(Answer::refused(format!("Refused {}", refusal.name()))) - } - } + self.settle_send_refusal(&room_key, &req_id, is_resend, *refusal, &[]) } else { Ok(Answer::unavailable(format!( "Unavailable: {err:#}; retry with --resend {req_id}" @@ -508,6 +482,34 @@ impl Engine { } } + fn settle_send_refusal( + &mut self, + room_key: &str, + req_id: &str, + is_resend: bool, + refusal: Refusal, + newer: &[String], + ) -> Result { + match (refusal.reading(is_resend), is_resend) { + (Reading::NoAnswer, _) | (Reading::NotSent, true) => Ok(Answer::unavailable(format!( + "Unavailable: {} on {req_id}; retry with --resend {req_id}", + refusal.name() + ))), + (Reading::NotSent, false) | (Reading::Unknown | Reading::Declined, _) => { + if let Some(room) = self.state.rooms.get_mut(room_key) { + room.pending_send = None; + } + write_state_atomic(&self.state_path, &self.state)?; + if refusal == Refusal::RoomMoved { + let newer_str = if newer.is_empty() { "-".to_string() } else { newer.join(",") }; + Ok(Answer::refused(format!("Refused RoomMoved newer={newer_str}"))) + } else { + Ok(Answer::refused(format!("Refused {}", refusal.name()))) + } + } + } + } + fn ack(&mut self, through: u64) -> Result { if let Err(err) = self.chat.ack(through) { return Ok(mouth_error_answer(&err)); @@ -625,11 +627,12 @@ pub fn call_socket(socket: &Path, request: &Request) -> Result { #[cfg(unix)] mod socket { - use std::fs::{self, Permissions}; + use std::fs::{self, DirBuilder, Permissions}; use std::io::{BufRead, BufReader, Read, Write}; - use std::os::unix::fs::PermissionsExt; + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; use std::os::unix::net::{UnixListener, UnixStream}; - use std::path::Path; + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use anyhow::{Context, Result}; @@ -639,6 +642,40 @@ mod socket { const MAX_LINE_BYTES: u64 = 1024 * 1024; const IO_TIMEOUT: Duration = Duration::from_secs(30); + static BIND_SEQ: AtomicU64 = AtomicU64::new(0); + + struct StagingDir(PathBuf); + + impl Drop for StagingDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn bind_restricted(socket: &Path) -> Result { + let parent = socket.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + fs::create_dir_all(parent).with_context(|| format!("failed to create {}", parent.display()))?; + let seq = BIND_SEQ.fetch_add(1, Ordering::Relaxed); + let stage_path = parent.join(format!(".cg-{}-{seq}", std::process::id())); + let _ = fs::remove_dir_all(&stage_path); + let mut dir_builder = DirBuilder::new(); + dir_builder.mode(0o700); + dir_builder + .create(&stage_path) + .with_context(|| format!("failed to create staging dir {}", stage_path.display()))?; + let _stage_guard = StagingDir(stage_path.clone()); + fs::set_permissions(&stage_path, Permissions::from_mode(0o700)) + .with_context(|| format!("failed to chmod 0700 {}", stage_path.display()))?; + + let staged_sock = stage_path.join("s"); + let listener = UnixListener::bind(&staged_sock) + .with_context(|| format!("failed to bind chat gate socket {}", socket.display()))?; + fs::set_permissions(&staged_sock, Permissions::from_mode(0o600)) + .with_context(|| format!("failed to chmod 0600 {}", staged_sock.display()))?; + fs::rename(&staged_sock, socket) + .with_context(|| format!("failed to install chat gate socket {}", socket.display()))?; + Ok(listener) + } pub(super) fn serve( config: Config, @@ -646,26 +683,27 @@ mod socket { socket: &Path, now_ms: impl Fn() -> u64, max_requests: Option, + ) -> Result<()> { + let expected_uid = rustix::process::geteuid().as_raw(); + serve_with_uid(config, chat, socket, expected_uid, now_ms, max_requests) + } + + pub(super) fn serve_with_uid( + config: Config, + chat: impl Chat, + socket: &Path, + expected_uid: u32, + now_ms: impl Fn() -> u64, + max_requests: Option, ) -> Result<()> { let mut engine = Engine::open(config, chat, now_ms())?; - if let Some(parent) = socket.parent() - && !parent.as_os_str().is_empty() - { - fs::create_dir_all(parent).with_context(|| format!("failed to create {}", parent.display()))?; - } - if socket.exists() { - fs::remove_file(socket).with_context(|| format!("failed to remove stale socket {}", socket.display()))?; - } - let listener = UnixListener::bind(socket) - .with_context(|| format!("failed to bind chat gate socket {}", socket.display()))?; - fs::set_permissions(socket, Permissions::from_mode(0o600)) - .with_context(|| format!("failed to chmod 0600 {}", socket.display()))?; + let listener = bind_restricted(socket)?; for (served, stream) in listener.incoming().enumerate() { let mut stream = stream.context("accept failed on chat gate socket")?; let _ = stream.set_read_timeout(Some(IO_TIMEOUT)); let _ = stream.set_write_timeout(Some(IO_TIMEOUT)); - let answer = handle_stream(&mut engine, &stream, &now_ms); + let answer = handle_stream(&mut engine, &stream, expected_uid, &now_ms); let encoded = serde_json::to_string(&answer)?; let _ = writeln!(stream, "{encoded}").and_then(|()| stream.flush()); if max_requests.is_some_and(|max| served + 1 >= max) { @@ -675,7 +713,27 @@ mod socket { Ok(()) } - fn handle_stream(engine: &mut Engine, stream: &UnixStream, now_ms: &dyn Fn() -> u64) -> Answer { + fn check_peer_uid(stream: &UnixStream, expected_uid: u32) -> std::result::Result<(), Answer> { + let creds = rustix::net::sockopt::socket_peercred(stream) + .map_err(|err| Answer::refused(format!("Refused PeerCred: {err}")))?; + let peer_uid = creds.uid.as_raw(); + if peer_uid != expected_uid { + return Err(Answer::refused(format!( + "Refused PeerUid: peer uid {peer_uid} != expected {expected_uid}" + ))); + } + Ok(()) + } + + pub(super) fn handle_stream( + engine: &mut Engine, + stream: &UnixStream, + expected_uid: u32, + now_ms: &dyn Fn() -> u64, + ) -> Answer { + if let Err(refused) = check_peer_uid(stream, expected_uid) { + return refused; + } let mut reader = BufReader::new(stream.take(MAX_LINE_BYTES)); let mut line = String::new(); if let Err(err) = reader.read_line(&mut line) { @@ -862,22 +920,32 @@ fn utc_day(ms: u64) -> String { fn write_state_atomic(path: &Path, state: &GateState) -> Result<()> { let json = serde_json::to_string_pretty(state)?; let tmp = path.with_extension(format!("json.tmp.{}", std::process::id())); - fs::write(&tmp, json.as_bytes()).with_context(|| format!("failed to write {}", tmp.display()))?; - restrict_state_file(&tmp)?; + write_restricted_file(&tmp, json.as_bytes())?; fs::rename(&tmp, path).with_context(|| format!("failed to rename {} to {}", tmp.display(), path.display()))?; Ok(()) } #[cfg(unix)] -fn restrict_state_file(path: &Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(path, fs::Permissions::from_mode(0o600)) - .with_context(|| format!("failed to chmod 0600 {}", path.display())) +fn write_restricted_file(path: &Path, bytes: &[u8]) -> Result<()> { + use std::io::Write; + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + + let _ = fs::remove_file(path); + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .with_context(|| format!("failed to create {}", path.display()))?; + file.write_all(bytes).with_context(|| format!("failed to write {}", path.display()))?; + file.set_permissions(fs::Permissions::from_mode(0o600)) + .with_context(|| format!("failed to chmod 0600 {}", path.display()))?; + Ok(()) } #[cfg(not(unix))] -fn restrict_state_file(_path: &Path) -> Result<()> { - Ok(()) +fn write_restricted_file(path: &Path, bytes: &[u8]) -> Result<()> { + fs::write(path, bytes).with_context(|| format!("failed to write {}", path.display())) } #[cfg(test)] @@ -895,6 +963,7 @@ mod tests { pending_replies: RefCell>>, send_replies: RefCell>>, open_replies: RefCell>>, + ack_replies: RefCell>>, acks: RefCell>, reads: RefCell>, sent: RefCell>, @@ -907,6 +976,7 @@ mod tests { pending_replies: RefCell::new(VecDeque::new()), send_replies: RefCell::new(VecDeque::new()), open_replies: RefCell::new(VecDeque::new()), + ack_replies: RefCell::new(VecDeque::new()), acks: RefCell::new(Vec::new()), reads: RefCell::new(Vec::new()), sent: RefCell::new(Vec::new()), @@ -932,7 +1002,10 @@ mod tests { } fn ack(&self, through_seq: u64) -> Result<()> { self.acks.borrow_mut().push(through_seq); - Ok(()) + match self.ack_replies.borrow_mut().pop_front() { + Some(reply) => reply, + None => Ok(()), + } } fn read(&self, read: &ChatRead) -> Result<()> { self.reads.borrow_mut().push(read.clone()); @@ -1226,7 +1299,7 @@ mod tests { assert_eq!(ak.exit, 0); assert_eq!(engine.state.after_seq, 5); - let st = engine.handle(Request::Status, t0 + 372_300).unwrap(); + let st = engine.handle(Request::Status {}, t0 + 372_300).unwrap(); assert_eq!(st.exit, 0); assert!(st.stdout.contains("after_seq 5") && st.stdout.contains("daily_says 2/2"), "{}", st.stdout); @@ -1464,6 +1537,7 @@ mod tests { assert!(sock.exists(), "socket did not bind in time"); let mode = fs::metadata(&sock).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o600); + assert_eq!(fs::read_dir(sock.parent().unwrap()).unwrap().count(), 1); // Request > 2048 bytes catches MAX_LINE_BYTES (1024 * 1024 vs 1024 + 1024). let big_text = "a".repeat(4096); @@ -1499,4 +1573,210 @@ mod tests { fs::write(®ular_file, b"x").unwrap(); assert!(serve_gate(cfg(&dir.path().join("bad-state"), None), MockChat::new(), ®ular_file.join("gate.sock"), || t0).is_err()); } + + #[test] + fn pending_ack_failure_leaves_state_and_seen_untouched() { + use crate::chat_client::ContextLine; + + let dir = tempfile::tempdir().unwrap(); + let t0 = 1_765_200_000_000_u64; + let mut engine = Engine::open(cfg(dir.path(), None), MockChat::new(), t0).unwrap(); + let state_before = fs::read_to_string(dir.path().join(STATE_FILE)).unwrap(); + + let mut deliv = delivery(7, "#swarm:gamecult.org", "$ev_unshown", "@meta:gamecult.org", t0 + 1000, "secret"); + deliv.context.push(ContextLine { sender: "@meta:gamecult.org".into(), at_unix_ms: t0 + 500, text: "ctx".into() }); + engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![deliv.clone()], + tail: None, + tail_gaps: vec![], + })); + engine.chat.ack_replies.borrow_mut().push_back(Err(anyhow!("simulated rudp ack timeout"))); + + let failed = engine.handle(Request::Pending { ack: true }, t0 + 1000).unwrap(); + assert_eq!(failed.exit, 3); + assert!(failed.stdout.is_empty(), "{}", failed.stdout); + assert!(failed.stderr.contains("simulated rudp ack timeout"), "{}", failed.stderr); + assert_eq!(engine.state.after_seq, 0); + assert!(engine.state.aliases.is_empty()); + assert!(engine.state.rooms.is_empty()); + assert_eq!(fs::read_to_string(dir.path().join(STATE_FILE)).unwrap(), state_before); + + // Follow-on say must NOT carry $ev_unshown in SendBasis. + engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: Some("$sent_clean".into()), + refusal: None, + newer: vec![], + })); + let clean_say = engine + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: Some("hi".into()), resend: None }, t0 + 1500) + .unwrap(); + assert_eq!(clean_say.exit, 0); + assert_eq!( + engine.chat.sent.borrow().last().unwrap().basis, + Some(SendBasis { seen_event_id: None, since_unix_ms: t0 }) + ); + + // Once ack succeeds, the delivery IS displayed, recorded, and acked. + engine.chat.pending_replies.borrow_mut().push_back(Ok(ChatPending { + persona: "nibu".into(), + deliveries: vec![deliv], + tail: None, + tail_gaps: vec![], + })); + let ok = engine.handle(Request::Pending { ack: true }, t0 + 2000).unwrap(); + assert_eq!(ok.exit, 0); + assert!(ok.stdout.contains("$ev_unshown") && ok.stdout.contains("acked 7"), "{}", ok.stdout); + assert_eq!(engine.state.after_seq, 7); + assert_eq!( + engine.state.aliases.get("!#swarm:gamecult.org:gamecult.org").map(String::as_str), + Some("#swarm:gamecult.org") + ); + let room = engine.state.rooms.get("#swarm:gamecult.org").unwrap(); + assert_eq!(room.seen_event_id.as_deref(), Some("$ev_unshown")); + assert!(room.lines.iter().any(|l| l.event_id == "$ev_unshown")); + } + + #[test] + fn resend_not_sent_preserves_unsettled_pending_send_until_settled() { + let dir = tempfile::tempdir().unwrap(); + let t0 = 1_765_300_000_000_u64; + let mut engine = Engine::open(cfg(dir.path(), None), MockChat::new(), t0).unwrap(); + + // 1. Initial say gets SendFailed -> pending_send stays unsettled. + engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: None, + refusal: Some(Refusal::SendFailed), + newer: vec![], + })); + let first = engine + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: Some("one".into()), resend: None }, t0 + 1000) + .unwrap(); + assert_eq!(first.exit, 3); + let req_id = format!("mc-{}-1", t0 + 1000); + + // 2. --resend returning Refusal::NotSent (both via receipt and via MouthRefused) must NOT clear pending_send. + engine.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: req_id.clone(), + event_id: None, + refusal: Some(Refusal::NotSent), + newer: vec![], + })); + let resend_receipt = engine + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: None, resend: Some(req_id.clone()) }, t0 + 2000) + .unwrap(); + assert_eq!(resend_receipt.exit, 3); + assert!(resend_receipt.stderr.contains("NotSent") && resend_receipt.stderr.contains(&req_id), "{}", resend_receipt.stderr); + + let fresh_blocked = engine + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: Some("dup".into()), resend: None }, t0 + 3000) + .unwrap(); + assert_eq!(fresh_blocked.exit, 1, "{}", fresh_blocked.stdout); + assert!(fresh_blocked.stdout.contains("room_unsettled"), "{}", fresh_blocked.stdout); + assert_eq!(engine.chat.sent.borrow().len(), 2); + + engine.chat.send_replies.borrow_mut().push_back(Err(anyhow::Error::from(MouthRefused(Refusal::NotSent)))); + let resend_err = engine + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: None, resend: Some(req_id.clone()) }, t0 + 4000) + .unwrap(); + assert_eq!(resend_err.exit, 3); + assert!(resend_err.stderr.contains("NotSent") && resend_err.stderr.contains(&req_id), "{}", resend_err.stderr); + + // Reloading from disk confirms pending_send stayed persisted as unsettled. + let mut reloaded = Engine::open(cfg(dir.path(), None), MockChat::new(), t0 + 5000).unwrap(); + let still_blocked = reloaded + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: Some("dup2".into()), resend: None }, t0 + 5000) + .unwrap(); + assert_eq!(still_blocked.exit, 1, "{}", still_blocked.stdout); + assert!(still_blocked.stdout.contains("room_unsettled"), "{}", still_blocked.stdout); + + // Resend succeeds -> settles pending_send. + reloaded.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: req_id.clone(), + event_id: Some("$ev_ok".into()), + refusal: None, + newer: vec![], + })); + let settled = reloaded + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: None, resend: Some(req_id) }, t0 + 6000) + .unwrap(); + assert_eq!(settled.exit, 0); + assert!(reloaded.state.rooms.get("#swarm:gamecult.org").unwrap().pending_send.is_none()); + + // Non-resend say returning Refusal::NotSent DOES clear pending_send so a fresh say works. + reloaded.chat.send_replies.borrow_mut().push_back(Ok(ChatSendReceipt { + request_id: "x".into(), + event_id: None, + refusal: Some(Refusal::NotSent), + newer: vec![], + })); + let initial_not_sent = reloaded + .handle(Request::Say { room: "#swarm:gamecult.org".into(), text: Some("not sent".into()), resend: None }, t0 + 7000) + .unwrap(); + assert_eq!(initial_not_sent.exit, 1); + assert_eq!(initial_not_sent.stdout, "Refused NotSent"); + assert!(reloaded.state.rooms.get("#swarm:gamecult.org").unwrap().pending_send.is_none()); + } + + #[cfg(unix)] + #[test] + fn status_rejects_unknown_fields_and_socket_enforces_peer_uid() { + use std::io::{BufRead, BufReader, Write}; + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + use std::os::unix::net::UnixStream; + + let dir = tempfile::tempdir().unwrap(); + let sock = dir.path().join("gate.sock"); + fs::write(&sock, b"stale").unwrap(); + let state_dir = dir.path().join("state"); + let t0 = 1_765_400_000_000_u64; + + let sock_srv = sock.clone(); + let state_srv = state_dir.clone(); + let handle = std::thread::spawn(move || { + socket::serve(cfg(&state_srv, None), MockChat::new(), &sock_srv, || t0, Some(2)).unwrap(); + }); + for _ in 0..300 { + if fs::symlink_metadata(&sock).is_ok_and(|m| m.file_type().is_socket() && m.permissions().mode() & 0o777 == 0o600) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(fs::metadata(&sock).unwrap().permissions().mode() & 0o777, 0o600); + // Send raw JSON with unknown field on status -> rejected with exit 2. + let mut raw = UnixStream::connect(&sock).unwrap(); + writeln!(raw, r#"{{"op":"status","persona":"eureka"}}"#).unwrap(); + raw.flush().unwrap(); + let mut resp = String::new(); + BufReader::new(raw).read_line(&mut resp).unwrap(); + let bad_status: Answer = serde_json::from_str(&resp).unwrap(); + assert_eq!(bad_status.exit, 2, "{bad_status:?}"); + assert!(bad_status.stdout.is_empty()); + assert!(bad_status.stderr.contains("unknown field `persona`"), "{}", bad_status.stderr); + + // Valid Request::Status {} succeeds over the socket. + let good_status = call_socket(&sock, &Request::Status {}).unwrap(); + assert_eq!(good_status.exit, 0); + assert!(good_status.stdout.contains("instance nibu"), "{}", good_status.stdout); + handle.join().unwrap(); + + // Peer-UID guard refuses mismatched uid before reading a single byte, and admits matching uid. + let mut eng = Engine::open(cfg(&dir.path().join("peer-state"), None), MockChat::new(), t0).unwrap(); + let my_uid = rustix::process::geteuid().as_raw(); + let (mut client, server) = UnixStream::pair().unwrap(); + writeln!(client, "not-even-json").unwrap(); + client.flush().unwrap(); + let refused = socket::handle_stream(&mut eng, &server, my_uid.wrapping_add(1), &|| t0); + assert_eq!(refused.exit, 1, "{refused:?}"); + assert!(refused.stdout.contains("Refused PeerUid"), "{}", refused.stdout); + + let (mut ok_client, ok_server) = UnixStream::pair().unwrap(); + writeln!(ok_client, r#"{{"op":"status"}}"#).unwrap(); + ok_client.flush().unwrap(); + let admitted = socket::handle_stream(&mut eng, &ok_server, my_uid, &|| t0); + assert_eq!(admitted.exit, 0, "{admitted:?}"); + assert!(admitted.stdout.contains("instance nibu"), "{}", admitted.stdout); + } } diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 24acd5f..750f7ec 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -101,7 +101,7 @@ mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , Pa mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool] mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64] mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String, reply_to: ReplyLink] -mind_body::chat_gate: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "op" , rename_all = "snake_case" , deny_unknown_fields)] pub enum Request { Pending { ack : bool } , Tail { room : Option < String > } , Say { room : String , text : Option < String > , resend : Option < String > } , Ack { through : u64 } , MarkRead { room : String , event : String , at_unix_ms : u64 } , OpenDirect { user : String , text : String } , Status , } +mind_body::chat_gate: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "op" , rename_all = "snake_case" , deny_unknown_fields)] pub enum Request { Pending { ack : bool } , Tail { room : Option < String > } , Say { room : String , text : Option < String > , resend : Option < String > } , Ack { through : u64 } , MarkRead { room : String , event : String , at_unix_ms : u64 } , OpenDirect { user : String , text : String } , Status { } , } mind_body::chat_gate: const STATE_FILE : & str mind_body::chat_gate: const UNSETTLED_WINDOW_S : i64 mind_body::chat_gate: fn call_socket (socket : & Path , request : & Request) -> Result < Answer > From 492c5e61e151b64b047d3e6ccebfc30c6d6a97db Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 13:30:36 +0100 Subject: [PATCH 12/12] Clean up StagingDir in chat_gate::socket to avoid public_surface impl Drop --- crates/mind-body/src/chat_gate.rs | 36 +++++++++++++------------------ 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/crates/mind-body/src/chat_gate.rs b/crates/mind-body/src/chat_gate.rs index 233ab3e..30524e7 100644 --- a/crates/mind-body/src/chat_gate.rs +++ b/crates/mind-body/src/chat_gate.rs @@ -631,7 +631,7 @@ mod socket { use std::io::{BufRead, BufReader, Read, Write}; use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; use std::os::unix::net::{UnixListener, UnixStream}; - use std::path::{Path, PathBuf}; + use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; @@ -644,14 +644,6 @@ mod socket { const IO_TIMEOUT: Duration = Duration::from_secs(30); static BIND_SEQ: AtomicU64 = AtomicU64::new(0); - struct StagingDir(PathBuf); - - impl Drop for StagingDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } - } - fn bind_restricted(socket: &Path) -> Result { let parent = socket.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); fs::create_dir_all(parent).with_context(|| format!("failed to create {}", parent.display()))?; @@ -663,18 +655,20 @@ mod socket { dir_builder .create(&stage_path) .with_context(|| format!("failed to create staging dir {}", stage_path.display()))?; - let _stage_guard = StagingDir(stage_path.clone()); - fs::set_permissions(&stage_path, Permissions::from_mode(0o700)) - .with_context(|| format!("failed to chmod 0700 {}", stage_path.display()))?; - - let staged_sock = stage_path.join("s"); - let listener = UnixListener::bind(&staged_sock) - .with_context(|| format!("failed to bind chat gate socket {}", socket.display()))?; - fs::set_permissions(&staged_sock, Permissions::from_mode(0o600)) - .with_context(|| format!("failed to chmod 0600 {}", staged_sock.display()))?; - fs::rename(&staged_sock, socket) - .with_context(|| format!("failed to install chat gate socket {}", socket.display()))?; - Ok(listener) + let outcome = (|| { + fs::set_permissions(&stage_path, Permissions::from_mode(0o700)) + .with_context(|| format!("failed to chmod 0700 {}", stage_path.display()))?; + let staged_sock = stage_path.join("s"); + let listener = UnixListener::bind(&staged_sock) + .with_context(|| format!("failed to bind chat gate socket {}", socket.display()))?; + fs::set_permissions(&staged_sock, Permissions::from_mode(0o600)) + .with_context(|| format!("failed to chmod 0600 {}", staged_sock.display()))?; + fs::rename(&staged_sock, socket) + .with_context(|| format!("failed to install chat gate socket {}", socket.display()))?; + Ok(listener) + })(); + let _ = fs::remove_dir_all(&stage_path); + outcome } pub(super) fn serve(