gestalt: focus is the outer key of the claim order; plan_wave takes the nodes a driver forces

fair_claims ranks in-focus demand before the rest, untried before tried inside each band, so a tried entry the player looks at no longer waits behind untried demand elsewhere. plan_wave opens each forced node like a focus node, treats it as due whatever its band and runs it ahead of every other node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 13:27:39 +01:00
commit 59c28830ab
4 changed files with 131 additions and 25 deletions

View file

@ -15075,6 +15075,46 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur
task.await.unwrap();
}
/// Focus is the outer key of the claim order: the entry the kernel refused
/// at the place the player is looking at is retried ahead of untried demand
/// elsewhere, where without a focus the untried entry goes first.
#[tokio::test]
async fn a_refused_entry_in_focus_goes_ahead_of_untried_demand_out_of_focus() {
let (_directory, mailbox, task, _commons, roads) = dead_end_world(
crate::tests::stock_weights(),
&["The Unwalked Road", "The Far Road"],
Roots::Commons,
0,
)
.await;
let good = shed_on_the_named_road(vec![
("The Unwalked Road", roads[0]),
("The Far Road", roads[1]),
]);
let port = Arc::new(SweepPort::new(move |call, request| {
if call == 0 || wire_of(request).contains(REFUSAL_TURN) {
refused_round(call)
} else {
good(call, request)
}
}));
let runner = sweep_runner(&mailbox, port.clone(), fresh_store());
let first = runner.sweep(pool(2), 1, &Focus::default()).await.unwrap();
assert_eq!((first.started, first.rejected), (1, 1));
let order = crate::elaboration::claim_order(&mailbox.snapshot().await.unwrap(), &Focus::default());
let tried = if boundary_at(roads[0])(&order[0]) { roads[0] } else { roads[1] };
let focus = Focus { places: vec![tried], nodes: Vec::new() };
let second = runner.sweep(pool(2), 1, &focus).await.unwrap();
assert_eq!(
(second.started, second.rejected, second.committed),
(1, 1, 0),
"the tried entry at the focus was retried, not the untried one elsewhere: {second:?}"
);
drop(runner);
drop(mailbox);
task.await.unwrap();
}
/// A patch the resolver admits but that leaves its boundary standing is
/// refused with no site. The session is repaired like any refusal, and the
/// repair turn says what the answer needs; it does not fail the session.

View file

@ -793,7 +793,7 @@ impl ElaborationRunner {
&in_flight,
focus,
)?;
let entries = self.fair_claims(entries, &in_flight).await?;
let entries = self.fair_claims(entries, &in_flight, &snapshot, focus).await?;
report.claimed = entries.len();
let snapshot = Arc::new(snapshot);
// Raised by a session before it releases its permit, so the sweep sees
@ -861,20 +861,28 @@ impl ElaborationRunner {
quarantine.map_or(Ok(report), Err)
}
/// The claim set in the order a bounded sweep should spend on it. An entry
/// no session has touched goes before one a session already tried, so an
/// entry the kernel refused is not retried ahead of untried demand; the
/// tried ones follow least recently stored first, so they rotate. An entry
/// whose stored session ended without a patch is a fixed point that runs no
/// inference, and it takes no slot.
/// The claim set in the order a bounded sweep should spend on it. Focus is
/// the outer key: demand at a focus place goes before the rest, so a tried
/// entry the player is looking at is not parked behind untried demand
/// elsewhere. Inside each band an entry no session has touched goes before
/// one a session already tried, so an entry the kernel refused is not
/// retried ahead of untried demand; the tried ones follow least recently
/// stored first, so they rotate. An entry whose stored session ended
/// without a patch is a fixed point that runs no inference, and it takes no
/// slot.
async fn fair_claims(
&self,
entries: Vec<(CommandId, ElaboratorSession)>,
in_flight: &[(CommandId, ElaboratorSession)],
snapshot: &WorldSnapshot,
focus: &Focus,
) -> Result<Vec<(CommandId, ElaboratorSession)>, ControllerError> {
let mut untried = Vec::new();
let mut tried: Vec<((CommandId, ElaboratorSession), usize)> = Vec::new();
// Band 0 is the focus; each band holds its untried and its tried.
type Tried = Vec<((CommandId, ElaboratorSession), usize)>;
let mut bands: [(Vec<(CommandId, ElaboratorSession)>, Tried); 2] = Default::default();
for entry in entries {
let band = usize::from(!entry_in_focus(snapshot, focus, &entry.1));
let (untried, tried) = &mut bands[band];
if let Some(position) = in_flight.iter().position(|(id, _)| *id == entry.0) {
tried.push((entry, position));
continue;
@ -890,9 +898,13 @@ impl ElaborationRunner {
_ => tried.push((entry, usize::MAX)),
}
}
tried.sort_by_key(|(_, position)| *position);
untried.extend(tried.into_iter().map(|(entry, _)| entry));
Ok(untried)
let mut ordered = Vec::new();
for (mut untried, mut tried) in bands {
tried.sort_by_key(|(_, position)| *position);
untried.extend(tried.into_iter().map(|(entry, _)| entry));
ordered.append(&mut untried);
}
Ok(ordered)
}
/// The first entry of one jurisdiction's claim set, stepped: what a sweep
@ -998,9 +1010,8 @@ fn demand_entries(
}
}
}
let (focused, rest): (Vec<_>, Vec<_>) = entries.into_iter().partition(|(_, session)| {
answer_place(snapshot, &session.answer).is_some_and(|place| in_focus(snapshot, focus, place))
});
let (focused, rest): (Vec<_>, Vec<_>) =
entries.into_iter().partition(|(_, session)| entry_in_focus(snapshot, focus, session));
Ok(focused.into_iter().chain(rest).collect())
}
@ -1033,6 +1044,11 @@ fn answer_place(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Option<Entity
}
}
/// Whether the demand an entry answers sits at a focus place.
fn entry_in_focus(snapshot: &WorldSnapshot, focus: &Focus, session: &ElaboratorSession) -> bool {
answer_place(snapshot, &session.answer).is_some_and(|place| in_focus(snapshot, focus, place))
}
/// A place is in focus when it is a focus place, inside one, or one open route
/// from one, the route read either way: the player's exits and the way back.
pub(super) fn in_focus(snapshot: &WorldSnapshot, focus: &Focus, place: EntityId) -> bool {

View file

@ -898,6 +898,7 @@ fn open_or_find(
opportunities,
graph,
&Focus::default(),
&[],
&config.knobs,
)?;
let tick = VerseTick {

View file

@ -226,17 +226,22 @@ fn folded(hierarchy: &Hierarchy, open: &BTreeSet<NodeId>, node: &Node) -> bool {
/// The wave: pure over its arguments. `opportunities` arrives in the kernel's
/// attention order and is never re-sorted; `graph` is the whole agency graph,
/// restricted here to each node's voices.
/// restricted here to each node's voices. `forced` names nodes a driver wants
/// turned now: each is opened like a focus node, is due whatever its band, and
/// runs before every node that is not forced.
pub fn plan_wave(
clock: WaveClock,
hierarchy: &Hierarchy,
opportunities: &[DecisionOpportunity],
graph: &AgencyGraph,
focus: &Focus,
forced: &[NodeId],
knobs: &GestaltKnobs,
) -> Result<Wave, GestaltKnobsError> {
knobs.validate()?;
let (open, distance) = open_and_distance(hierarchy, focus, knobs);
let mut attended = focus.clone();
attended.nodes.extend(forced.iter().copied());
let (open, distance) = open_and_distance(hierarchy, &attended, knobs);
let active: BTreeSet<SubjectId> = opportunities
.iter()
.filter(|opportunity| opportunity.controller_mode != super::ControllerMode::Human)
@ -291,7 +296,7 @@ pub fn plan_wave(
// Due-ness: the most neglected voice against the band's period. `None`
// sorts first, so a never-attended voice is both due and most neglected.
let mut due: Vec<(u8, Option<FictionalMinutes>, NodeId)> = Vec::new();
let mut due: Vec<(bool, u8, Option<FictionalMinutes>, NodeId)> = Vec::new();
let mut deferred: Vec<(NodeId, Deferral)> = Vec::new();
for (id, at, voices) in &units {
let oldest = if voices.iter().all(|voice| hierarchy.last_attended.contains_key(voice)) {
@ -302,24 +307,26 @@ pub fn plan_wave(
} else {
None
};
let is_due = match oldest {
None => true,
Some(stamp) => clock.now.since(stamp) >= u64::from(knobs.period(*at)),
};
let forced_now = forced.contains(id);
let is_due = forced_now
|| match oldest {
None => true,
Some(stamp) => clock.now.since(stamp) >= u64::from(knobs.period(*at)),
};
if is_due {
due.push((*at, oldest, *id));
due.push((!forced_now, *at, oldest, *id));
} else {
deferred.push((*id, Deferral::NotDue));
}
}
due.sort();
let bound = usize::from(knobs.max_node_turns);
for (_, _, id) in due.iter().skip(bound) {
for (_, _, _, id) in due.iter().skip(bound) {
deferred.push((*id, Deferral::OverBound));
}
let mut turns = Vec::new();
for (at, _, id) in due.into_iter().take(bound) {
for (_, at, _, id) in due.into_iter().take(bound) {
let voices = &units
.iter()
.find(|(unit, _, _)| *unit == id)
@ -1018,6 +1025,7 @@ mod tests {
&opportunities(&f.state),
&AgencyGraph::default(),
focus,
&[],
knobs,
)
.unwrap()
@ -1087,6 +1095,46 @@ mod tests {
}
}
/// A forced node is open at the head of the wave and due whatever its
/// band, ahead of a node that is due by itself and inside the node-turn
/// bound; planned without it, nothing about it runs.
#[test]
fn a_forced_node_runs_first_though_its_band_has_not_passed() {
let r = realm();
let knobs = knobs(&[10, 360, 5000], 1, 1);
let empire_node = node(&r.f, NodeAnchor::Institution(r.empire));
let mut hierarchy = derive_hierarchy(&r.f.state);
let root = hierarchy.root();
for voice in [r.empire, r.herald, r.council, r.drinker, r.wanderers] {
hierarchy.last_attended.insert(voice, FictionalMinutes(999));
}
let world = r.f.state.world_id;
let opportunities = opportunities(&r.f.state);
let run = |forced: &[NodeId]| {
plan_wave(
WaveClock { world, ordinal: TickIndex(7), now: FictionalMinutes(1000) },
&hierarchy,
&opportunities,
&AgencyGraph::default(),
&Focus::default(),
forced,
&knobs,
)
.unwrap()
};
let plain = run(&[]);
assert!(plain.turns.iter().all(|turn| turn.node != empire_node), "the empire attended a minute ago is not due");
let forced = run(&[empire_node]);
assert_eq!(forced.turns.len(), 1, "the node-turn bound still holds");
assert_eq!(forced.turns[0].node, empire_node);
assert!(forced.turns[0].open && forced.turns[0].distance == 0);
assert!(
forced.deferred.contains(&(root, Deferral::OverBound)),
"the never-attended world waits behind the forced node: {:?}",
forced.deferred
);
}
#[test]
fn a_node_is_due_by_its_band_and_not_a_minute_sooner() {
let r = realm();
@ -1219,6 +1267,7 @@ mod tests {
&opportunities(&r.f.state),
&AgencyGraph::default(),
&at_tap_room(&r),
&[],
&knobs,
)
.unwrap();