diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 6ca7ed1..f9b4f47 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -26,7 +26,7 @@ use crate::{ DecisionInvocation, DecisionOpportunity, DependencyTarget, EdgeId, ElaborationPort, EntityId, EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, Resolution, RoleBinding, - ScopeComponents, ScopeDigest, SeedPort, Statement, SubjectId, SubjectSnapshot, SubmitReceipt, + ScopeComponents, ScopeDigest, SeedPort, Statement, SubjectId, SubjectKind, SubjectSnapshot, SubmitReceipt, Target, TickIndex, WorldMailbox, WorldSnapshot, handle_for, }; use async_trait::async_trait; @@ -4963,6 +4963,9 @@ impl PersonaLane { } } +/// How many incumbents an institution's view carries. +const MEMBERS_DIGEST_CAP: usize = 6; + #[derive(Clone)] struct SelectedDecision { snapshot: WorldSnapshot, @@ -5372,7 +5375,7 @@ impl SelectedDecision { } fn typed_view(&self) -> Result { - serde_json::to_string_pretty(&json!({ + let mut view = json!({ "world": { "title": self.snapshot.title, "revision": self.snapshot.revision, @@ -5398,8 +5401,119 @@ impl SelectedDecision { "commitments": self.typed_commitments(), "pressures": self.typed_pressures(), "material": self.subject.material, - })) - .map_err(|error| ControllerError::Serialization(error.to_string())) + }); + // Cells carry no hierarchy, so an institution cannot know whether its + // node is closed: every institution's view carries its members digest. + if self.subject.kind == SubjectKind::Institution { + view["members"] = Value::Array(self.typed_members()); + } + serde_json::to_string_pretty(&view) + .map_err(|error| ControllerError::Serialization(error.to_string())) + } + + /// The seats this institution constitutes, so it acts for its members + /// knowingly: at most `MEMBERS_DIGEST_CAP` incumbents of its own offices, + /// in the opportunity order the kernel already owns (pressure, then + /// attention debt, then id), each with the state this institution is party + /// to and nothing else. A member's knowledge, opinions and persona material + /// are never read; a commitment or pressure naming a third party never + /// enters. A position shows only where it lies under a place this + /// institution holds a grant over. + fn typed_members(&self) -> Vec { + let institution = self.subject.id; + let mut seats: BTreeMap> = BTreeMap::new(); + for office in &self.subject.offices_granted { + if let Some(incumbent) = office.incumbent.filter(|incumbent| *incumbent != institution) { + seats.entry(incumbent).or_default().push(&office.office); + } + } + let rank = |member: SubjectId| { + self.snapshot + .opportunities + .iter() + .position(|opportunity| opportunity.scope.subject_id == member) + .unwrap_or(usize::MAX) + }; + let mut members: Vec<(&SubjectSnapshot, Vec<&super::patch::OfficeName>)> = seats + .into_iter() + .filter_map(|(id, offices)| { + let member = self.snapshot.subjects.iter().find(|candidate| candidate.id == id)?; + (!member.retired).then_some((member, offices)) + }) + .collect(); + members.sort_by_key(|(member, _)| (rank(member.id), member.id)); + members.truncate(MEMBERS_DIGEST_CAP); + let roots: Vec = self + .subject + .components + .authority + .iter() + .filter_map(|grant| match grant.over { + super::patch::AuthorityTarget::PlaceSubtree(root) => Some(root), + super::patch::AuthorityTarget::Subject(_) => None, + }) + .collect(); + members + .into_iter() + .map(|(member, offices)| { + let place = member.position.filter(|place| { + roots.iter().any(|root| { + super::elaboration::snapshot_covers_place(&self.snapshot, *root, *place) + }) + }); + let owed_to_us = member + .commitments + .iter() + .filter(|commitment| commitment.counterparty == Some(institution)) + .map(|commitment| ("to_institution", commitment)); + let owed_to_them = self + .subject + .commitments + .iter() + .filter(|commitment| commitment.counterparty == Some(member.id)) + .map(|commitment| ("from_institution", commitment)); + let commitments: Vec = owed_to_us + .chain(owed_to_them) + .map(|(direction, commitment)| { + json!({ + "direction": direction, + "kind": commitment.kind, + "statement": commitment.statement.as_str(), + "due": commitment.due, + "past_due": commitment.past_due, + }) + }) + .collect(); + let pressures: Vec = member + .pressures + .iter() + .filter(|pressure| match pressure.source { + super::patch::PressureSource::Subject(source) + | super::patch::PressureSource::Commitment { subject: source, .. } => { + source == institution + } + super::patch::PressureSource::Dependency(_) => false, + }) + .map(|pressure| json!({"source": pressure.source, "magnitude": pressure.magnitude})) + .collect(); + json!({ + "id": member.id, + "label": member.label, + "offices": offices, + "place": place.map(|place| self.typed_place_of(place)), + "commitments": commitments, + "pressures": pressures, + }) + }) + .collect() + } + + fn typed_place_of(&self, place: EntityId) -> Value { + self.snapshot + .places + .iter() + .find(|candidate| candidate.id == place) + .map_or(Value::Null, |place| json!({"id": place.id, "label": place.label})) } /// The acting subject's own promises. IDs, not labels: resolving a @@ -22580,3 +22694,230 @@ mod regard_projection_tests { assert!(narrator.contains("a grievance (-60)"), "{narrator}"); } } + +/// An institution's view carries a capped digest of the seats it constitutes +/// and nothing a member keeps to themselves. Built from the kernel's own +/// snapshot over a hand-assembled state, so the order under test is the +/// kernel's opportunity order and not a fixture's. +#[cfg(test)] +mod members_digest_tests { + use super::*; + use crate::hierarchy::tests::Fixture; + use crate::patch::{ + AuthorityTarget, Commitment, CommitmentKey, CommitmentKind, EntityRecord, FactRecord, + FactStanding, Knowledge, PersonaMaterial, PressureMagnitude, PressureSource, + }; + use crate::{CommandId, FictionalMinutes, WorldPhase}; + + fn said(text: &str) -> Statement { + Statement::new(text).unwrap() + } + + fn promise(counterparty: SubjectId, text: &str) -> Commitment { + Commitment { + kind: CommitmentKind::Obligation, + counterparty: Some(counterparty), + due: FictionalMinutes(500), + period: None, + checks: Vec::new(), + statement: said(text), + } + } + + fn key(index: u32) -> CommitmentKey { + CommitmentKey { command: CommandId::issue(), index } + } + + struct Council { + f: Fixture, + council: SubjectId, + town: EntityId, + elsewhere: EntityId, + } + + /// A council holding `town`, with `seats` incumbents standing in it. + fn council(seats: usize) -> (Council, Vec) { + let mut f = Fixture::new(); + f.state.phase = WorldPhase::Active; + let town = f.place("Town", None); + let elsewhere = f.place("Elsewhere", None); + let council = f.subject("Council", SubjectKind::Institution, None); + f.grant(council, AuthorityTarget::PlaceSubtree(town)); + let members = (0..seats) + .map(|index| { + let member = f.subject(&format!("Member{index}"), SubjectKind::Person, Some(town)); + f.office(council, &format!("seat{index}"), member); + member + }) + .collect(); + (Council { f, council, town, elsewhere }, members) + } + + fn view_of(world: &Council, subject: SubjectId) -> Value { + // Every subject may speak, so every subject has an opportunity. + let mut state = world.f.state.clone(); + let speak = AffordanceId::issue(); + state.affordance_catalog.insert(speak, crate::patch::kernel_speak_entry()); + for subject_id in state.subjects.keys().copied().collect::>() { + state + .affordance_grants + .entry(crate::DecisionScope { subject_id }) + .or_default() + .insert(speak); + } + let snapshot = crate::snapshot(&state).unwrap(); + let opportunity = snapshot + .opportunities + .iter() + .find(|opportunity| opportunity.scope.subject_id == subject) + .expect("an opportunity") + .clone(); + let selected = select_one(&snapshot, &opportunity).unwrap(); + serde_json::from_str(&selected.typed_view().unwrap()).unwrap() + } + + fn press(world: &mut Council, member: SubjectId, source: PressureSource, by: u32) { + world + .f + .state + .pressures + .entry(member) + .or_default() + .insert(source, PressureMagnitude(by)); + } + + #[test] + fn the_digest_holds_party_state_only() { + let (mut world, members) = council(2); + let (alice, bob) = (members[0], members[1]); + let third = world.f.subject("Outsider", SubjectKind::Person, Some(world.town)); + let council = world.council; + // What the council is party to. + world + .f + .state + .commitments + .entry(alice) + .or_default() + .insert(key(0), promise(council, "ALICE-OWES-THE-COUNCIL")); + world + .f + .state + .commitments + .entry(council) + .or_default() + .insert(key(1), promise(alice, "COUNCIL-OWES-ALICE")); + press(&mut world, alice, PressureSource::Subject(council), 7); + // What it is not: a side deal, pressure from a third party, and + // everything a member keeps to themselves. + world + .f + .state + .commitments + .entry(alice) + .or_default() + .insert(key(2), promise(third, "ALICE-SIDE-DEAL")); + press(&mut world, alice, PressureSource::Subject(third), 9); + world.f.state.persona_material.insert( + alice, + PersonaMaterial { + values: vec![said("VALUE-SECRET")], + voice: said("VOICE-SECRET"), + memories: vec![said("MEMORY-SECRET")], + reads: BTreeMap::from([(bob, said("READ-SECRET"))]), + }, + ); + let fact = EntityId::issue(); + world.f.state.entities.insert( + fact, + EntityRecord { label: "private".into(), kind: EntityKind::Fact, container: None }, + ); + world.f.state.facts.insert( + fact, + FactRecord { statement: said("FACT-SECRET"), standing: FactStanding::Ruled }, + ); + world.f.state.knowledge.entry(alice).or_default().insert( + fact, + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: 0, + }, + ); + // Bob stands outside every place the council holds. + world.f.state.positions.insert( + bob, + crate::patch::Position { place: world.elsewhere }, + ); + + let view = view_of(&world, council); + let text = serde_json::to_string(&view["members"]).unwrap(); + assert!(text.contains("ALICE-OWES-THE-COUNCIL"), "{text}"); + assert!(text.contains("COUNCIL-OWES-ALICE"), "{text}"); + for private in [ + "ALICE-SIDE-DEAL", + "VALUE-SECRET", + "VOICE-SECRET", + "MEMORY-SECRET", + "READ-SECRET", + "FACT-SECRET", + ] { + assert!(!text.contains(private), "{private} leaked: {text}"); + } + assert!(!text.contains(&serde_json::to_string(&third).unwrap()), "{text}"); + let members = view["members"].as_array().unwrap(); + let of = |id: SubjectId| { + members + .iter() + .find(|member| member["id"] == serde_json::to_value(id).unwrap()) + .unwrap() + }; + assert_eq!(of(alice)["pressures"].as_array().unwrap().len(), 1, "{text}"); + assert_eq!(of(alice)["commitments"].as_array().unwrap().len(), 2, "{text}"); + assert_eq!(of(alice)["place"]["label"], "Town"); + assert_eq!(of(alice)["offices"], json!(["seat0"])); + assert_eq!(of(bob)["place"], Value::Null, "outside every grant: {text}"); + } + + #[test] + fn the_digest_is_capped_and_ordered_by_pressure() { + let (mut world, members) = council(9); + let council = world.council; + for (index, member) in members.iter().enumerate() { + press(&mut world, *member, PressureSource::Subject(council), index as u32 + 1); + } + let view = view_of(&world, council); + let listed: Vec = view["members"] + .as_array() + .unwrap() + .iter() + .map(|member| member["id"].clone()) + .collect(); + let expected: Vec = members + .iter() + .rev() + .take(MEMBERS_DIGEST_CAP) + .map(|member| serde_json::to_value(member).unwrap()) + .collect(); + assert_eq!(MEMBERS_DIGEST_CAP, 6); + assert_eq!(listed, expected); + } + + #[test] + fn a_persons_view_has_no_digest_and_ignores_the_institution_state() { + let (mut world, members) = council(3); + let council = world.council; + let before = serde_json::to_string_pretty(&view_of(&world, members[0])).unwrap(); + assert!(view_of(&world, members[0]).get("members").is_none()); + press(&mut world, members[1], PressureSource::Subject(council), 5); + world + .f + .state + .commitments + .entry(members[2]) + .or_default() + .insert(key(0), promise(council, "ELSEWHERE-PROMISE")); + let after = serde_json::to_string_pretty(&view_of(&world, members[0])).unwrap(); + assert_eq!(before, after); + } +} diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index fed18c7..12498f4 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -1112,7 +1112,7 @@ fn boundary_in( } } -fn snapshot_covers_place(snapshot: &WorldSnapshot, root: EntityId, place: EntityId) -> bool { +pub(crate) fn snapshot_covers_place(snapshot: &WorldSnapshot, root: EntityId, place: EntityId) -> bool { let containers: BTreeMap> = snapshot .places .iter()