From bc85d70f9194e48ef38a0ddc514e03a6d231474c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:09:07 +0100 Subject: [PATCH 01/11] Elaboration: per-attempt round budget, bounded repairs, world structure in the prompt, fair claim order, sweep report Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/elaboration.rs | 181 ++++++++++++++++++++++++--- crates/ghostlight/src/lib.rs | 2 +- crates/ghostlight/src/patch.rs | 7 +- crates/ghostlight/src/table.rs | 2 +- 4 files changed, 174 insertions(+), 18 deletions(-) diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index e969f74..99f12d0 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -49,7 +49,15 @@ use uuid::Uuid; /// The elaborator wants many tool calls inside one round and several rounds for /// repair, where the operational agent wants one terminal choice. /// `TOOL_STEP_BUDGET` is left alone for the lane it belongs to. +/// +/// A round budget is per attempt: the rounds since the last refusal, or since +/// the start. A refusal opens a fresh attempt with the whole budget, so a repair +/// is never starved by the rounds the refused draft spent. pub(super) const ELABORATION_ROUND_BUDGET: usize = 6; +/// How many times the kernel may refuse one session's patch and the session +/// still be repaired. The refusal after these is terminal: the session ends +/// without a patch and says why, instead of being re-chosen forever. +pub(super) const MAX_REFUSALS: usize = 2; /// A seed session authors a whole shortfall, not one answer: several subjects, /// each with a grant, a goal, and an obligation, then a submit. Measured on /// the road at one declaration per response, six rounds discarded everything. @@ -353,6 +361,36 @@ pub(super) enum ElaborationLoopEvaluation { Complete { capture: ElaborationCapture }, } +/// What one sweep did: how much demand it saw, how many sessions it started, +/// what each ended as, and every session that failed outright. The caller logs +/// or surfaces it; the library has no sink of its own for the run. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SweepReport { + pub claimed: usize, + pub started: usize, + pub committed: usize, + pub rejected: usize, + pub superseded: usize, + pub no_patch: usize, + /// Sessions the world refused past `MAX_REFUSALS`; each was logged at error + /// with its last refusal and is no longer claimed. + pub abandoned: usize, + /// Sessions that ended in an error, with the error. + pub failed: Vec, +} + +impl SweepReport { + fn count(&mut self, outcome: ElaborationOutcome) { + match outcome { + ElaborationOutcome::Committed => self.committed += 1, + ElaborationOutcome::Rejected => self.rejected += 1, + ElaborationOutcome::Superseded => self.superseded += 1, + ElaborationOutcome::NoPatch => self.no_patch += 1, + ElaborationOutcome::Abandoned => self.abandoned += 1, + } + } +} + /// What one session's step did. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum ElaborationOutcome { @@ -363,6 +401,10 @@ pub(super) enum ElaborationOutcome { Superseded, /// The round budget was spent without a submit. The boundary stays derived. NoPatch, + /// The world refused the session's patch past `MAX_REFUSALS`. The session + /// is stored as `NoPatch`, with the last refusal in its gap, and no sweep + /// claims it again. + Abandoned, } /// The authoring lane's runner. Holds no state between sweeps; every field is a @@ -556,6 +598,32 @@ impl ElaborationRunner { after_round: completed.len(), mismatches, }); + if refusals.len() > MAX_REFUSALS { + let last = refusals.last().map_or_else(String::new, |refusal| { + render_refusal_sites(&refusal.mismatches) + }); + tracing::error!( + command_id = ?command_id, + refusals = refusals.len(), + last_refusal = %last, + "elaboration session abandoned: the world kept refusing its patch" + ); + self.persist(ElaborationCheckpoint::NoPatch { + command_id, + session, + agent_prompt, + refusals, + completed, + gaps: vec![ControllerNeed { + detail: format!( + "The world refused the patch {} times; last refusal: {last}", + MAX_REFUSALS + 1 + ), + }], + }) + .await?; + return Ok(ElaborationOutcome::Abandoned); + } self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed) .await?; Ok(ElaborationOutcome::Rejected) @@ -651,13 +719,16 @@ impl ElaborationRunner { &self, permits: Arc, max_sessions: usize, - ) -> Result<(), ControllerError> { + ) -> Result { + let mut report = SweepReport::default(); let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?; if snapshot.phase != WorldPhase::Active { - return Ok(()); + return Ok(report); } let in_flight = self.work.elaboration_in_flight().await?; let entries = demand_entries(&snapshot, &sweep_jurisdictions(&snapshot), &in_flight)?; + let entries = self.fair_claims(entries, &in_flight).await?; + report.claimed = entries.len(); let snapshot = Arc::new(snapshot); // Raised by a session before it releases its permit, so the sweep sees // it before it starts the session that permit admits. @@ -673,6 +744,7 @@ impl ElaborationRunner { if stopped.load(Ordering::SeqCst) { break; } + report.started += 1; let runner = self.clone(); let snapshot = snapshot.clone(); let stopped = stopped.clone(); @@ -687,18 +759,20 @@ impl ElaborationRunner { .as_ref() .is_err_and(ControllerError::requires_quarantine); drop(held); - outcome + (command_id, outcome) }); } let mut quarantine = None; while let Some(joined) = running.join_next().await { match joined { - Ok(Ok(_)) => {} - Ok(Err(error)) if error.requires_quarantine() => { + Ok((_, Ok(outcome))) => report.count(outcome), + Ok((command_id, Err(error))) if error.requires_quarantine() => { + report.failed.push(format!("{command_id:?}: {error}")); quarantine.get_or_insert(error); } - Ok(Err(error)) => { - tracing::debug!(%error, "elaboration step did not admit a patch"); + Ok((command_id, Err(error))) => { + tracing::error!(command_id = ?command_id, %error, "elaboration session failed"); + report.failed.push(format!("{command_id:?}: {error}")); } Err(error) => { quarantine.get_or_insert(ControllerError::Serialization(format!( @@ -707,7 +781,41 @@ impl ElaborationRunner { } } } - quarantine.map_or(Ok(()), Err) + 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. + async fn fair_claims( + &self, + entries: Vec<(CommandId, ElaboratorSession)>, + in_flight: &[(CommandId, ElaboratorSession)], + ) -> Result, ControllerError> { + let mut untried = Vec::new(); + let mut tried: Vec<((CommandId, ElaboratorSession), usize)> = Vec::new(); + for entry in entries { + if let Some(position) = in_flight.iter().position(|(id, _)| *id == entry.0) { + tried.push((entry, position)); + continue; + } + match self.work.lookup(entry.0).await? { + ControllerWorkLookup::Missing => untried.push(entry), + ControllerWorkLookup::Confirmed(ControllerWork::Elaboration( + ElaborationCheckpoint::NoPatch { .. }, + )) + | ControllerWorkLookup::CustodyUncertain(ControllerWork::Elaboration( + ElaborationCheckpoint::NoPatch { .. }, + )) => {} + _ => tried.push((entry, usize::MAX)), + } + } + tried.sort_by_key(|(_, position)| *position); + untried.extend(tried.into_iter().map(|(entry, _)| entry)); + Ok(untried) } /// The first entry of one jurisdiction's claim set, stepped: what a sweep @@ -1025,6 +1133,10 @@ fn build_prompt( render_answer(snapshot, &session.answer) )); prompt.push_str(&render_clock(snapshot)); + prompt.push_str( + "\nEverything below already stands. Reference it by its bracketed id and declare only what is missing. An affordance kind that already stands, the kernel's own speak among them, cannot be declared again: grant it by id.\n\n", + ); + prompt.push_str(&super::table::render_world_structure(snapshot)); prompt.push('\n'); prompt_body(&mut prompt, receipts); prompt @@ -1062,12 +1174,19 @@ fn render_refusal(mismatches: &[Mismatch]) -> String { "The world refused the patch you submitted; every site below failed a structural check. \ The draft is discarded. Author the complete patch again with tool calls, repairing every site, then submit again:\n", ); - for mismatch in mismatches { - text.push_str(&format!("- {}\n", render_mismatch(mismatch))); - } + text.push_str(&render_refusal_sites(mismatches)); text } +/// The refusal's sites, one per line, as the model reads them and as the logs +/// record them. +fn render_refusal_sites(mismatches: &[Mismatch]) -> String { + mismatches + .iter() + .map(|mismatch| format!("- {}\n", render_mismatch(mismatch))) + .collect() +} + /// The world's own premise, when it has one. The seed session's optional /// sentence rides beside it; the two are not the same thing. fn render_brief(snapshot: &WorldSnapshot) -> String { @@ -1145,6 +1264,8 @@ pub(super) fn evaluate_elaboration_loop( }]; let mut fold = DraftFold::default(); let mut receipts = Vec::new(); + // The first round of the current attempt; a refusal moves it. + let mut attempt_start = 0; for (round, output) in completed.iter().enumerate() { if output.receipt_digest.is_empty() || output.receipt_digest.trim() != output.receipt_digest @@ -1196,17 +1317,19 @@ pub(super) fn evaluate_elaboration_loop( text: render_refusal(&refusal.mismatches), }); fold = DraftFold::default(); + attempt_start = round + 1; continue; } - let is_complete = fold.submitted || !called_tool || round + 1 == budget; + let is_complete = + fold.submitted || !called_tool || round + 1 - attempt_start == budget; if is_complete { if round + 1 != completed.len() { return Err(ControllerError::Serialization( "elaboration evidence continued after total finalization".into(), )); } - if !fold.submitted && called_tool && round + 1 == budget { + if !fold.submitted && called_tool && round + 1 - attempt_start == budget { // What was authored is still a patch; the resolver decides it, // not the round counter. An empty draft has nothing to submit. if fold.draft.declarations.is_empty() && fold.draft.operations.is_empty() { @@ -1233,7 +1356,7 @@ pub(super) fn evaluate_elaboration_loop( } } - if completed.len() >= budget { + if completed.len() - attempt_start >= budget { return Err(ControllerError::Serialization( "elaboration evidence exceeded its round budget".into(), )); @@ -1301,6 +1424,7 @@ pub(super) struct ElaborationOracle { impl ElaborationOracle { pub(super) fn new(completed: &[InferenceOutput], refusals: &[Refusal], budget: usize) -> Self { let mut fold = DraftFold::default(); + let mut attempt_start = 0; for (round, output) in completed.iter().enumerate() { for event in &output.events { if let InferenceEvent::ToolCall { @@ -1312,11 +1436,12 @@ impl ElaborationOracle { } if refusal_after(refusals, round + 1).is_some() { fold = DraftFold::default(); + attempt_start = round + 1; } } Self { fold, - remaining: budget.saturating_sub(completed.len()) as u32, + remaining: budget.saturating_sub(completed.len() - attempt_start) as u32, } } } @@ -1936,6 +2061,32 @@ impl SeedRunner { after_round: completed.len(), mismatches, }); + if refusals.len() > MAX_REFUSALS { + let last = refusals.last().map_or_else(String::new, |refusal| { + render_refusal_sites(&refusal.mismatches) + }); + tracing::error!( + command_id = ?command_id, + refusals = refusals.len(), + last_refusal = %last, + "seed session abandoned: the world kept refusing its patch" + ); + self.persist(SeedCheckpoint::NoPatch { + command_id, + session, + agent_prompt, + refusals, + completed, + gaps: vec![ControllerNeed { + detail: format!( + "The world refused the patch {} times; last refusal: {last}", + MAX_REFUSALS + 1 + ), + }], + }) + .await?; + return Ok(SeedOutcome::NoPatch); + } self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed) .await?; Ok(SeedOutcome::Rejected) diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index bc45a01..4f495e5 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -101,7 +101,7 @@ pub use aetheria::{ }; pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; pub use elaboration::{ - ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery, + ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, }; pub use grammar::{ diff --git a/crates/ghostlight/src/patch.rs b/crates/ghostlight/src/patch.rs index a838ac0..5dd2905 100644 --- a/crates/ghostlight/src/patch.rs +++ b/crates/ghostlight/src/patch.rs @@ -1578,6 +1578,9 @@ pub enum Mismatch { /// tool catalog would have two tools with one name. DuplicateAffordanceKind { handle: DraftHandle, + /// The kind name already taken, by the kernel's own speak entry or by + /// a standing or earlier declared entry: grant that entry instead. + kind: AffordanceKindName, }, DuplicateRole { handle: DraftHandle, @@ -3327,6 +3330,7 @@ pub(super) fn resolve_patch( if !kind_names.insert(affordance.kind.clone()) { mismatches.push(Mismatch::DuplicateAffordanceKind { handle: affordance.handle.clone(), + kind: affordance.kind.clone(), }); } } @@ -8386,7 +8390,8 @@ mod tests { assert_eq!( rejected, vec![Mismatch::DuplicateAffordanceKind { - handle: DraftHandle::new("second") + handle: DraftHandle::new("second"), + kind: AffordanceKindName("haul".into()), }] ); diff --git a/crates/ghostlight/src/table.rs b/crates/ghostlight/src/table.rs index 1eccbb5..d3c5267 100644 --- a/crates/ghostlight/src/table.rs +++ b/crates/ghostlight/src/table.rs @@ -1108,7 +1108,7 @@ pub fn id_text_matches(id: impl std::fmt::Debug, text: &str) -> bool { /// The world the seed session is authoring into, rendered from snapshot /// fields that already exist. Moved from the elaboration lane, byte-for-byte: /// the seed prompt calls it here now, and its text does not change with the -/// move. Seed-only; `table_view` below is the play agent's own, richer +/// move. Read by the seed and the Active elaboration prompts; `table_view` below is the play agent's own, richer /// renderer over the same snapshot and does not build on this one, so a /// change to one never reaches the other's bytes. pub(super) fn render_world_structure(snapshot: &WorldSnapshot) -> String { From 00e3467ed76e338aa7ab75cf5f87b5ea688bb64e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:20:31 +0100 Subject: [PATCH 02/11] Tests: a repair has a fresh round budget, a refused entry yields to untried ones, a refused session is abandoned Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 95 ++++++++++++++++++++++++++-- crates/ghostlight/src/elaboration.rs | 42 ++++++++++++ 2 files changed, 132 insertions(+), 5 deletions(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index b855d3d..5d43704 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -14150,6 +14150,16 @@ mod tests { } } + /// The prompt's `Answer:` line alone: the world structure the prompt also + /// prints names every road, so a script choosing by road reads this line. + fn answer_of(request: &PreparedInference) -> String { + prompt_of(request) + .lines() + .find(|line| line.starts_with("Answer:")) + .expect("the prompt carries its answer") + .to_owned() + } + fn wire_of(request: &PreparedInference) -> String { serde_json::to_string(&request.invocation.request.input).unwrap() } @@ -14192,7 +14202,7 @@ mod tests { roads: Vec<(&'static str, EntityId)>, ) -> impl Fn(usize, &PreparedInference) -> Result { move |call, request| { - let prompt = prompt_of(request); + let prompt = answer_of(request); let (label, road) = roads .iter() .find(|(label, _)| prompt.contains(label)) @@ -14334,6 +14344,81 @@ mod tests { task.await.unwrap(); } + /// Fair claims: the first entry's patch is always refused. A bound of one + /// starts it in the first sweep; the second sweep starts the entry nobody + /// has tried, not the refused one again, and commits it. + #[tokio::test] + async fn a_refused_entry_is_not_retried_ahead_of_an_untried_one() { + let (_directory, mailbox, task, _commons, roads) = dead_end_world( + crate::tests::stock_weights(), + &["The Unwalked Road", "The Far Road"], + Roots::Commons, + 0, + ) + .await; + let far = roads[1]; + let port = Arc::new(SweepPort::new(move |call, request| { + if answer_of(request).contains("The Unwalked Road") { + shed_round( + json!({"ref": "draft", "value": "nowhere"}), + "The Shed on The Unwalked Road", + &format!("refused-{call}"), + ) + } else { + shed_round( + json!({"ref": "existing", "value": serde_json::to_value(far).unwrap()}), + "The Shed on The Far Road", + &format!("shed-{call}"), + ) + } + })); + let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); + let first = runner.sweep(pool(2), 1).await.unwrap(); + assert_eq!((first.started, first.rejected), (1, 1)); + let second = runner.sweep(pool(2), 1).await.unwrap(); + assert_eq!((second.started, second.committed), (1, 1), "{second:?}"); + let snapshot = mailbox.snapshot().await.unwrap(); + assert!(place_labelled(&snapshot, "The Shed on The Far Road").is_some()); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// A session the world keeps refusing ends after `MAX_REFUSALS` repairs, is + /// stored without a patch, counted in the report, and takes no slot after. + #[tokio::test] + async fn a_session_the_world_keeps_refusing_is_abandoned_and_no_longer_claimed() { + let (_directory, mailbox, task, _commons, roads) = dead_end_world( + crate::tests::stock_weights(), + &["The Unwalked Road"], + Roots::Commons, + 0, + ) + .await; + let _ = roads; + let port = Arc::new(SweepPort::new(|call, _| { + shed_round( + json!({"ref": "draft", "value": "nowhere"}), + "The Shed on The Unwalked Road", + &format!("refused-{call}"), + ) + })); + let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); + for _ in 0..crate::elaboration::MAX_REFUSALS { + let report = runner.sweep(pool(1), 1).await.unwrap(); + assert_eq!(report.rejected, 1, "{report:?}"); + } + let last = runner.sweep(pool(1), 1).await.unwrap(); + assert_eq!(last.abandoned, 1, "{last:?}"); + let calls = port.calls(); + let after = runner.sweep(pool(1), 1).await.unwrap(); + assert_eq!((after.claimed, after.started), (0, 0), "{after:?}"); + assert_eq!(port.calls(), calls, "an abandoned session ran inference again"); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + /// The same two entries under a pool of one: the first session is held /// inside the provider boundary with no permit free, and the second starts /// only after the first has finished. @@ -14696,7 +14781,7 @@ mod tests { .await; let far = shed_on_the_named_road(vec![("The Far Road", roads[1])]); let port = Arc::new(SweepPort::new(move |call, request| { - if prompt_of(request).contains("The Unwalked Road") { + if answer_of(request).contains("The Unwalked Road") { Err(InferenceFault::retryable("the fixture connector is at capacity")) } else { far(call, request) @@ -14815,7 +14900,7 @@ mod tests { ) -> Result { let call = self.calls.fetch_add(1, Ordering::SeqCst); self.both.wait().await; - if prompt_of(&request).contains("The Unwalked Road") { + if answer_of(&request).contains("The Unwalked Road") { self.faulted.add_permits(1); return Err(InferenceFault::integrity_violation( "the fixture port disputes this receipt", @@ -14917,7 +15002,7 @@ mod tests { request: PreparedInference, ) -> Result { let call = self.calls.fetch_add(1, Ordering::SeqCst); - if prompt_of(&request).contains("The Unwalked Road") { + if answer_of(&request).contains("The Unwalked Road") { if self.first_unwalked.swap(false, Ordering::SeqCst) { self.both.wait().await; self.panicking.add_permits(1); @@ -15374,7 +15459,7 @@ mod tests { .find(|jurisdiction| *jurisdiction != claimed) .unwrap(); let port = Arc::new(SweepPort::new(|call, request| { - if prompt_of(request).contains("The Unwalked Road") && call == 0 { + if answer_of(request).contains("The Unwalked Road") && call == 0 { refused_round(call) } else { idle_round(call) diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 99f12d0..438e908 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -2914,4 +2914,46 @@ mod tests { if evidence == &EvidenceRef::new("vault:forged")) )); } + /// The refusal that follows a round which spent the whole budget is still + /// repairable: the repair attempt has the whole budget again, and the oracle + /// reports it, rather than the session dying at "exceeded its round budget". + #[test] + fn a_refusal_opens_a_fresh_round_budget_for_the_repair() { + let drafting = || output(vec![("declare_place", place("shed"))]); + let submitting = || output(vec![("declare_place", place("shed")), ("submit", serde_json::json!({}))]); + let mut completed: Vec = (0..ELABORATION_ROUND_BUDGET - 1).map(|_| drafting()).collect(); + completed.push(submitting()); + let refusals = vec![Refusal { + after_round: completed.len(), + mismatches: vec![Mismatch::EmptyHandle { position: 0 }], + }]; + // The refused draft used every round the budget allows. + assert!(matches!( + evaluate_elaboration_loop("p", &refusals, &completed, ELABORATION_ROUND_BUDGET), + Ok(ElaborationLoopEvaluation::Continue { .. }) + )); + assert_eq!( + ElaborationOracle::new(&completed, &refusals, ELABORATION_ROUND_BUDGET).remaining_rounds() + as usize, + ELABORATION_ROUND_BUDGET + ); + // The repair submits in one round and finalizes. + completed.push(submitting()); + assert!(matches!( + evaluate_elaboration_loop("p", &refusals, &completed, ELABORATION_ROUND_BUDGET), + Ok(ElaborationLoopEvaluation::Complete { capture }) if capture.submitted + )); + // A repair that never submits ends at the budget, not before and not after. + let mut idle: Vec = completed[..completed.len() - 1].to_vec(); + idle.extend((0..ELABORATION_ROUND_BUDGET - 1).map(|_| drafting())); + assert!(matches!( + evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET), + Ok(ElaborationLoopEvaluation::Continue { .. }) + )); + idle.push(drafting()); + assert!(matches!( + evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET), + Ok(ElaborationLoopEvaluation::Complete { .. }) + )); + } } From 7c63ec2829f45776bac5ca18efe5dc1a1c7f5839 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:24:00 +0100 Subject: [PATCH 03/11] Elaboration: a refusal that ends a session is a legal progression; tests follow the prompt's new structure Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 54 ++++++++++++++++++---------- crates/ghostlight/src/elaboration.rs | 26 ++++++++++++++ 2 files changed, 61 insertions(+), 19 deletions(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 5d43704..3badf70 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -13943,7 +13943,18 @@ mod tests { ); assert_eq!(session.lens, lens); assert_eq!(session.instructions, lens.instructions()); - prompts.insert(agent_prompt.clone()); + // The world structure prints this world's ids, which differ + // between the eight worlds; everything else must not. + prompts.insert( + agent_prompt + .split('[') + .enumerate() + .map(|(index, part)| match (index, part.split_once(']')) { + (0, _) | (_, None) => part.to_owned(), + (_, Some((_, rest))) => rest.to_owned(), + }) + .collect::(), + ); texts.insert(session.instructions.clone()); } let second = elaboration_runner(&mailbox, script.clone(), store.clone()); @@ -14344,9 +14355,9 @@ mod tests { task.await.unwrap(); } - /// Fair claims: the first entry's patch is always refused. A bound of one - /// starts it in the first sweep; the second sweep starts the entry nobody - /// has tried, not the refused one again, and commits it. + /// Fair claims: whichever entry a bound of one starts first is refused, and + /// so is its repair. The second sweep starts the entry nobody has tried, not + /// the refused one again, and commits it. #[tokio::test] async fn a_refused_entry_is_not_retried_ahead_of_an_untried_one() { let (_directory, mailbox, task, _commons, roads) = dead_end_world( @@ -14356,20 +14367,15 @@ mod tests { 0, ) .await; - let far = roads[1]; + 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 answer_of(request).contains("The Unwalked Road") { - shed_round( - json!({"ref": "draft", "value": "nowhere"}), - "The Shed on The Unwalked Road", - &format!("refused-{call}"), - ) + if call == 0 || wire_of(request).contains(REFUSAL_TURN) { + refused_round(call) } else { - shed_round( - json!({"ref": "existing", "value": serde_json::to_value(far).unwrap()}), - "The Shed on The Far Road", - &format!("shed-{call}"), - ) + good(call, request) } })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); @@ -14378,7 +14384,7 @@ mod tests { let second = runner.sweep(pool(2), 1).await.unwrap(); assert_eq!((second.started, second.committed), (1, 1), "{second:?}"); let snapshot = mailbox.snapshot().await.unwrap(); - assert!(place_labelled(&snapshot, "The Shed on The Far Road").is_some()); + assert_eq!(snapshot.boundaries.len(), 1, "one entry answered, one still refused"); drop(runner); drop(mailbox); task.await.unwrap(); @@ -15417,11 +15423,21 @@ mod tests { .unwrap(); results.push(runner.sweep(pool(1), usize::MAX).await); assert_eq!(port.calls(), tick + 1, "tick {tick}: one inference per sweep"); + // Past `MAX_REFUSALS` the session ends and its deficit id, which + // moves with the ancestry, starts a new one; rows may grow then, + // but only one session is ever in flight. assert_eq!( - store.journal.lock().unwrap().work.len(), + store.elaboration_in_flight().await.unwrap().len(), 1, - "tick {tick}: the store gained a row" + "tick {tick}: an orphan session is in flight" ); + if tick < crate::elaboration::MAX_REFUSALS { + assert_eq!( + store.journal.lock().unwrap().work.len(), + 1, + "tick {tick}: the store gained a row" + ); + } } // The sixth round is the last the budget allows; how that round ends // is not this test's subject. diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 438e908..0dbd105 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -280,6 +280,32 @@ pub(super) fn valid_elaboration_progression( .. }, ) => refusal_reopens(existing, existing_refusals, next, next_refusals), + // The refusal that ends the session: the same reopening, stored as the + // end instead of another repair. + ( + ElaborationCheckpoint::ReadyToSubmit { + completed: existing, + refusals: existing_refusals, + .. + }, + ElaborationCheckpoint::NoPatch { + completed: next, + refusals: next_refusals, + .. + }, + ) => refusal_reopens(existing, existing_refusals, next, next_refusals), + ( + SeedCheckpoint::ReadyToSubmit { + completed: existing, + refusals: existing_refusals, + .. + }, + SeedCheckpoint::NoPatch { + completed: next, + refusals: next_refusals, + .. + }, + ) => refusal_reopens(existing, existing_refusals, next, next_refusals), _ => false, } } From cdf43237fcff8e6cccc21a4078be114a6b52cae5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:25:10 +0100 Subject: [PATCH 04/11] Elaboration: the ending refusal's progression belongs to each lane's own checkpoint Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/elaboration.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 0dbd105..ea247e9 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -294,18 +294,6 @@ pub(super) fn valid_elaboration_progression( .. }, ) => refusal_reopens(existing, existing_refusals, next, next_refusals), - ( - SeedCheckpoint::ReadyToSubmit { - completed: existing, - refusals: existing_refusals, - .. - }, - SeedCheckpoint::NoPatch { - completed: next, - refusals: next_refusals, - .. - }, - ) => refusal_reopens(existing, existing_refusals, next, next_refusals), _ => false, } } @@ -1851,6 +1839,18 @@ pub(super) fn valid_seed_progression(existing: &SeedCheckpoint, next: &SeedCheck .. }, ) => refusal_reopens(existing, existing_refusals, next, next_refusals), + ( + SeedCheckpoint::ReadyToSubmit { + completed: existing, + refusals: existing_refusals, + .. + }, + SeedCheckpoint::NoPatch { + completed: next, + refusals: next_refusals, + .. + }, + ) => refusal_reopens(existing, existing_refusals, next, next_refusals), _ => false, } } From 2c17cf8fa3f7ec8ac5c390a892194a55c7057eb3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:27:05 +0100 Subject: [PATCH 05/11] Elaboration: a session ended by its last refusal is a valid NoPatch row Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 22 ++++--------- crates/ghostlight/src/elaboration.rs | 49 +++++++++++++++++++++++----- 2 files changed, 47 insertions(+), 24 deletions(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 3badf70..26bfae8 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -13943,18 +13943,11 @@ mod tests { ); assert_eq!(session.lens, lens); assert_eq!(session.instructions, lens.instructions()); - // The world structure prints this world's ids, which differ - // between the eight worlds; everything else must not. - prompts.insert( - agent_prompt - .split('[') - .enumerate() - .map(|(index, part)| match (index, part.split_once(']')) { - (0, _) | (_, None) => part.to_owned(), - (_, Some((_, rest))) => rest.to_owned(), - }) - .collect::(), - ); + // The world structure prints this world's ids and their order, + // which differ between the eight worlds; the rest must not. + let before = agent_prompt.split("Standing structure").next().unwrap(); + let after = agent_prompt.rsplit("Tools:").next().unwrap(); + prompts.insert(format!("{before}{after}")); texts.insert(session.instructions.clone()); } let second = elaboration_runner(&mailbox, script.clone(), store.clone()); @@ -15426,9 +15419,8 @@ mod tests { // Past `MAX_REFUSALS` the session ends and its deficit id, which // moves with the ancestry, starts a new one; rows may grow then, // but only one session is ever in flight. - assert_eq!( - store.elaboration_in_flight().await.unwrap().len(), - 1, + assert!( + store.elaboration_in_flight().await.unwrap().len() <= 1, "tick {tick}: an orphan session is in flight" ); if tick < crate::elaboration::MAX_REFUSALS { diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index ea247e9..58633b1 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -220,17 +220,45 @@ impl ElaborationCheckpoint { refusals, completed, .. - } => derive_elaboration_capture( - agent_prompt, - refusals, - completed, - ELABORATION_ROUND_BUDGET, - ) - .is_ok_and(|capture| !capture.submitted), + } => { + derive_elaboration_capture( + agent_prompt, + refusals, + completed, + ELABORATION_ROUND_BUDGET, + ) + .is_ok_and(|capture| !capture.submitted) + || ended_by_refusal( + agent_prompt, + refusals, + completed, + ELABORATION_ROUND_BUDGET, + ) + } } } } +/// Whether the conversation ends in the refusal past `MAX_REFUSALS`: the last +/// refusal follows the last round, and the repair it would have opened was +/// never authored. A `NoPatch` row is either this or a conversation that +/// ended without a submit. +fn ended_by_refusal( + agent_prompt: &str, + refusals: &[Refusal], + completed: &[InferenceOutput], + budget: usize, +) -> bool { + refusals.len() > MAX_REFUSALS + && refusals + .last() + .is_some_and(|refusal| refusal.after_round == completed.len()) + && matches!( + evaluate_elaboration_loop(agent_prompt, refusals, completed, budget), + Ok(ElaborationLoopEvaluation::Continue { .. }) + ) +} + /// A session may gather more evidence and may end, but it may never rewrite the /// answer it bound to, the ancestry it was built against, the lens it drew, or /// the text it was built with. This compares a row to the row that follows it, @@ -1790,8 +1818,11 @@ impl SeedCheckpoint { refusals, completed, .. - } => derive_elaboration_capture(agent_prompt, refusals, completed, SEED_ROUND_BUDGET) - .is_ok_and(|capture| !capture.submitted), + } => { + derive_elaboration_capture(agent_prompt, refusals, completed, SEED_ROUND_BUDGET) + .is_ok_and(|capture| !capture.submitted) + || ended_by_refusal(agent_prompt, refusals, completed, SEED_ROUND_BUDGET) + } } } } From 2ac36ddc6819955e1b36cc5b7ff4eb211521ecf4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:33:32 +0100 Subject: [PATCH 06/11] Elaboration: a clean patch that leaves its boundary standing is a refusal with what the answer needs, not a failed session Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 37 +++++++++ crates/ghostlight/src/elaboration.rs | 109 +++++++++++++++++---------- crates/ghostlight/src/patch.rs | 9 +++ 3 files changed, 115 insertions(+), 40 deletions(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 26bfae8..47b2657 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -14383,6 +14383,43 @@ mod tests { 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. + #[tokio::test] + async fn a_patch_that_leaves_its_boundary_standing_is_repaired_with_what_it_needs() { + let (_directory, mailbox, task, commons, roads) = dead_end_world( + crate::tests::stock_weights(), + &["The Unwalked Road"], + Roots::Commons, + 0, + ) + .await; + let good = shed_on_the_named_road(vec![("The Unwalked Road", roads[0])]); + let port = Arc::new(SweepPort::new(move |call, request| { + if call == 0 { + // Admissible, and nowhere near the dead end. + shed_round( + json!({"ref": "existing", "value": serde_json::to_value(commons).unwrap()}), + "The Shed Elsewhere", + "elsewhere", + ) + } else { + good(call, request) + } + })); + let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); + let first = runner.sweep(pool(1), 1).await.unwrap(); + assert_eq!((first.rejected, first.failed.len()), (1, 0), "{first:?}"); + let second = runner.sweep(pool(1), 1).await.unwrap(); + assert_eq!(second.committed, 1, "{second:?}"); + let repair = wire_of(&port.seen.lock().unwrap()[1]); + assert!(repair.contains(REFUSAL_TURN) && repair.contains("dead end"), "{repair}"); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + /// A session the world keeps refusing ends after `MAX_REFUSALS` repairs, is /// stored without a patch, counted in the report, and takes no slot after. #[tokio::test] diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 58633b1..aafb0e0 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -630,51 +630,58 @@ impl ElaborationRunner { draft, ) .await; - return match submitted { - Ok(_) => Ok(ElaborationOutcome::Committed), + let mismatches = match submitted { + Ok(_) => return Ok(ElaborationOutcome::Committed), Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) => { - // A rejected command mutates nothing, so reusing the - // id is correct and the idempotency probe never sees - // a conflicting commit. - refusals.push(Refusal { - after_round: completed.len(), - mismatches, - }); - if refusals.len() > MAX_REFUSALS { - let last = refusals.last().map_or_else(String::new, |refusal| { - render_refusal_sites(&refusal.mismatches) - }); - tracing::error!( - command_id = ?command_id, - refusals = refusals.len(), - last_refusal = %last, - "elaboration session abandoned: the world kept refusing its patch" - ); - self.persist(ElaborationCheckpoint::NoPatch { - command_id, - session, - agent_prompt, - refusals, - completed, - gaps: vec![ControllerNeed { - detail: format!( - "The world refused the patch {} times; last refusal: {last}", - MAX_REFUSALS + 1 - ), - }], - }) - .await?; - return Ok(ElaborationOutcome::Abandoned); - } - self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed) - .await?; - Ok(ElaborationOutcome::Rejected) + mismatches + } + // The patch resolved and the answer still stands: the + // kernel names no site, so the repair is told what the + // answer needs. + Err(MailboxError::Kernel(KernelError::AnswerNotSatisfied)) => { + vec![unsatisfied_answer(snapshot, &session.answer)] } Err(MailboxError::Kernel(KernelError::AnswerNotDerived)) => { - Ok(ElaborationOutcome::Superseded) + return Ok(ElaborationOutcome::Superseded); } - Err(error) => Err(snapshot_error(error)), + Err(error) => return Err(snapshot_error(error)), }; + // A rejected command mutates nothing, so reusing the + // id is correct and the idempotency probe never sees + // a conflicting commit. + refusals.push(Refusal { + after_round: completed.len(), + mismatches, + }); + if refusals.len() > MAX_REFUSALS { + let last = refusals.last().map_or_else(String::new, |refusal| { + render_refusal_sites(&refusal.mismatches) + }); + tracing::error!( + command_id = ?command_id, + refusals = refusals.len(), + last_refusal = %last, + "elaboration session abandoned: the world kept refusing its patch" + ); + self.persist(ElaborationCheckpoint::NoPatch { + command_id, + session, + agent_prompt, + refusals, + completed, + gaps: vec![ControllerNeed { + detail: format!( + "The world refused the patch {} times; last refusal: {last}", + MAX_REFUSALS + 1 + ), + }], + }) + .await?; + return Ok(ElaborationOutcome::Abandoned); + } + self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed) + .await?; + return Ok(ElaborationOutcome::Rejected); } } } @@ -1263,6 +1270,28 @@ pub(super) fn render_jurisdiction(snapshot: &WorldSnapshot, jurisdiction: Jurisd } } +/// What the world still lacks when a clean patch did not answer. The wording +/// follows each boundary's own predicate: the repair is a patch that makes the +/// predicate stop holding. +fn unsatisfied_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Mismatch { + let needs = match answer { + PatchAnswer::Boundary(CausalBoundary::MissingStructure { .. }) => { + "the promise's counterparty must be able to command the promisor (grant_authority over it) or the promisor must fall under a standing forum (open_forum with standing over the counterparty); declaring more subjects or facts does not answer it" + } + PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { .. }) => { + "the place must stop being a dead end: put something in it, or give it a second route" + } + PatchAnswer::Boundary(_) => "the boundary's own structure must change", + PatchAnswer::Deficit(_) => { + "more subjects must qualify in this jurisdiction: each needs a controller, an affordance grant, a position inside it and a held goal" + } + }; + Mismatch::AnswerNotSatisfied { + answered: render_answer(snapshot, answer), + needs: needs.to_owned(), + } +} + fn render_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String { let referents = answer_referents(snapshot, answer).join(", "); match answer { diff --git a/crates/ghostlight/src/patch.rs b/crates/ghostlight/src/patch.rs index 5dd2905..23633e0 100644 --- a/crates/ghostlight/src/patch.rs +++ b/crates/ghostlight/src/patch.rs @@ -1444,6 +1444,15 @@ pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeErro #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(tag = "mismatch", rename_all = "snake_case")] pub enum Mismatch { + /// The patch resolved cleanly and was admitted, and the boundary or deficit + /// it answered still stands, so the world refused it with + /// `KernelError::AnswerNotSatisfied`. That refusal names no site, so the + /// elaboration runner states what the answer needs here, and the repair + /// round has something to author against. + AnswerNotSatisfied { + answered: String, + needs: String, + }, EmptyHandle { position: usize, }, From 66cc6509ead937499b5de2831e39bc244f0d0462 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:41:28 +0100 Subject: [PATCH 07/11] Elaboration: log each refusal's sites and each sweep's report Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/elaboration.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index aafb0e0..7a5deff 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -646,6 +646,12 @@ impl ElaborationRunner { } Err(error) => return Err(snapshot_error(error)), }; + tracing::info!( + command_id = ?command_id, + refusal = refusals.len() + 1, + sites = %render_refusal_sites(&mismatches), + "elaboration patch refused" + ); // A rejected command mutates nothing, so reusing the // id is correct and the idempotency probe never sees // a conflicting commit. @@ -830,6 +836,17 @@ impl ElaborationRunner { } } } + tracing::info!( + claimed = report.claimed, + started = report.started, + committed = report.committed, + rejected = report.rejected, + superseded = report.superseded, + no_patch = report.no_patch, + abandoned = report.abandoned, + failed = report.failed.len(), + "elaboration sweep" + ); quarantine.map_or(Ok(report), Err) } From c9a5ce3d29484f737e9f3ac4c8bf5cbb0abbae33 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:46:20 +0100 Subject: [PATCH 08/11] Elaboration: a missing-structure prompt names the promise, its holder, its counterparty and what answers it Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/elaboration.rs | 41 ++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 7a5deff..c45a711 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -1198,6 +1198,7 @@ fn build_prompt( "Answer: {}\n", render_answer(snapshot, &session.answer) )); + prompt.push_str(&render_promise(snapshot, &session.answer)); prompt.push_str(&render_clock(snapshot)); prompt.push_str( "\nEverything below already stands. Reference it by its bracketed id and declare only what is missing. An affordance kind that already stands, the kernel's own speak among them, cannot be declared again: grant it by id.\n\n", @@ -1287,14 +1288,48 @@ pub(super) fn render_jurisdiction(snapshot: &WorldSnapshot, jurisdiction: Jurisd } } +/// What answers a promise whose counterparty can neither command nor litigate it. +const MISSING_STRUCTURE_NEEDS: &str = "the promise's counterparty must be able to command the promisor (grant_authority to the counterparty, over the promisor or a ground that covers it) or a forum must stand over the counterparty (open_forum with standing over the counterparty); declaring more subjects or facts does not answer it"; + +/// The promise a missing-structure boundary is about, with who holds it and who +/// it is owed to, by id, and what answers it. Empty for every other answer. +fn render_promise(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String { + let PatchAnswer::Boundary(CausalBoundary::MissingStructure { subject, key, .. }) = answer + else { + return String::new(); + }; + let named = |id: SubjectId| { + snapshot.subjects.iter().find(|entry| entry.id == id).map_or_else( + || format!("[{}]", super::table::id_text(id)), + |entry| format!("{} [{}]", entry.label, super::table::id_text(entry.id)), + ) + }; + let Some(commitment) = snapshot + .subjects + .iter() + .find(|entry| entry.id == *subject) + .and_then(|entry| entry.commitments.iter().find(|held| held.key == *key)) + else { + return String::new(); + }; + let owed = commitment + .counterparty + .map_or_else(|| "no one".to_owned(), named); + format!( + "Promise: {} promised \"{}\" to {}. It is answered when {MISSING_STRUCTURE_NEEDS}. +", + named(*subject), + commitment.statement.as_str(), + owed + ) +} + /// What the world still lacks when a clean patch did not answer. The wording /// follows each boundary's own predicate: the repair is a patch that makes the /// predicate stop holding. fn unsatisfied_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Mismatch { let needs = match answer { - PatchAnswer::Boundary(CausalBoundary::MissingStructure { .. }) => { - "the promise's counterparty must be able to command the promisor (grant_authority over it) or the promisor must fall under a standing forum (open_forum with standing over the counterparty); declaring more subjects or facts does not answer it" - } + PatchAnswer::Boundary(CausalBoundary::MissingStructure { .. }) => MISSING_STRUCTURE_NEEDS, PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { .. }) => { "the place must stop being a dead end: put something in it, or give it a second route" } From b31f1e551d45f13f4e681bba35b198ec66f970ba Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:58:16 +0100 Subject: [PATCH 09/11] Tests: the promise prompt, abandoned rows' integrity in both lanes, sweep report counts, repair budget end Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 96 ++++++++++++++++++++++++++++ crates/ghostlight/src/elaboration.rs | 36 +++++++++-- 2 files changed, 128 insertions(+), 4 deletions(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 47b2657..6f5d9c5 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -14420,6 +14420,84 @@ mod tests { task.await.unwrap(); } + /// The one elaboration row a store holds, whatever its stage. + fn store_row(store: &Arc) -> ElaborationCheckpoint { + let stored = store.work.lock().unwrap(); + let ControllerWork::Elaboration(checkpoint) = stored.values().next().unwrap().clone() else { + panic!("not an elaboration row"); + }; + checkpoint + } + + /// A missing-structure session's first prompt names the promise, who holds + /// it, who it is owed to, and what answers it. + #[tokio::test] + async fn a_missing_structure_prompt_names_the_promise_and_what_answers_it() { + let (_directory, mailbox, task, snapshot) = + unpositioned_debtor_world(WorldScaleIntentRef::default()).await; + let debtor = snapshot.subjects.iter().find_map(|subject| { + subject.commitments.iter().find(|held| held.counterparty.is_some()).map(|held| (subject, held)) + }); + let (holder, held) = debtor.expect("the fixture's debtor holds a promise"); + let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); + let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); + runner.sweep(pool(1), usize::MAX).await.unwrap(); + let prompt = prompt_of(&port.seen.lock().unwrap()[0]); + let promise = prompt.lines().find(|line| line.starts_with("Promise:")).expect("a Promise line"); + assert!(promise.contains(&holder.label), "{promise}"); + assert!(promise.contains(held.statement.as_str()), "{promise}"); + assert!(promise.contains("grant_authority") && promise.contains("open_forum"), "{promise}"); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// The same ending in the seed lane: the third refusal stores the session + /// as a valid row without a patch, and a further step runs no inference. + #[tokio::test] + async fn a_seed_session_the_world_keeps_refusing_is_abandoned() { + let forged = |receipt: &str| { + tool_round( + vec![ + ( + "declare_fact", + json!({ + "handle": "dry", + "label": "The Dry Season", + "statement": "The sere runs dry nine months a year.", + "standing": {"standing": "canonical", "evidence": "Public/Places/Nowhere.md"}, + }), + ), + ("submit", json!({})), + ], + receipt, + ) + }; + let fixture = seed_mailbox(6).await; + let store = fresh_store(); + let script = seed_script(vec![forged("r0"), forged("r1"), forged("r2")]); + let runner = seed_runner(&fixture, script.clone(), store.clone(), Arc::new(NullEvidenceSource)); + for _ in 0..crate::elaboration::MAX_REFUSALS { + assert_eq!(runner.step().await.unwrap(), SeedOutcome::Rejected); + } + assert_eq!(runner.step().await.unwrap(), SeedOutcome::NoPatch); + let seen = script.seen.lock().unwrap().len(); + let stored = store.work.lock().unwrap(); + let ControllerWork::Seed(row @ SeedCheckpoint::NoPatch { refusals, .. }) = + stored.values().next().unwrap() + else { + panic!("an abandoned seed session is not stored as NoPatch"); + }; + assert_eq!(refusals.len(), crate::elaboration::MAX_REFUSALS + 1); + assert!(row.integrity_is_valid()); + drop(stored); + assert_eq!(runner.step().await.unwrap(), SeedOutcome::NoPatch); + assert_eq!(script.seen.lock().unwrap().len(), seen, "an abandoned seed session ran inference again"); + drop(runner); + drop(fixture.mailbox); + fixture.task.await.unwrap(); + } + /// A session the world keeps refusing ends after `MAX_REFUSALS` repairs, is /// stored without a patch, counted in the report, and takes no slot after. #[tokio::test] @@ -14446,6 +14524,24 @@ mod tests { } let last = runner.sweep(pool(1), 1).await.unwrap(); assert_eq!(last.abandoned, 1, "{last:?}"); + // The stored end is a valid row; the same row with its ending refusal + // moved or removed is not. + let ended = store_row(&store); + assert!(ended.integrity_is_valid()); + let ElaborationCheckpoint::NoPatch { refusals, .. } = &ended else { + panic!("an abandoned session is not stored as NoPatch"); + }; + assert_eq!(refusals.len(), crate::elaboration::MAX_REFUSALS + 1); + let tamper = |edit: &dyn Fn(&mut Vec)| { + let mut row = ended.clone(); + let ElaborationCheckpoint::NoPatch { refusals, .. } = &mut row else { unreachable!() }; + edit(refusals); + row.integrity_is_valid() + }; + assert!(!tamper(&|refusals| { + refusals.pop(); + })); + assert!(!tamper(&|refusals| refusals.last_mut().unwrap().after_round = 1)); let calls = port.calls(); let after = runner.sweep(pool(1), 1).await.unwrap(); assert_eq!((after.claimed, after.started), (0, 0), "{after:?}"); diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index c45a711..bf7181b 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -3089,9 +3089,37 @@ mod tests { Ok(ElaborationLoopEvaluation::Continue { .. }) )); idle.push(drafting()); - assert!(matches!( - evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET), - Ok(ElaborationLoopEvaluation::Complete { .. }) - )); + let Ok(ElaborationLoopEvaluation::Complete { capture }) = + evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET) + else { + panic!("the repair's last round did not finalize"); + }; + // What the repair authored is submitted as authored, with the gap named. + assert!(capture.submitted); + assert!(capture.gaps.iter().any(|gap| gap.detail.contains("round budget ended"))); + } + + #[test] + fn a_sweep_report_counts_each_outcome_once() { + let mut report = SweepReport::default(); + for outcome in [ + ElaborationOutcome::Committed, + ElaborationOutcome::Rejected, + ElaborationOutcome::Rejected, + ElaborationOutcome::Superseded, + ElaborationOutcome::Superseded, + ElaborationOutcome::Superseded, + ElaborationOutcome::NoPatch, + ElaborationOutcome::NoPatch, + ElaborationOutcome::NoPatch, + ElaborationOutcome::NoPatch, + ElaborationOutcome::Abandoned, + ] { + report.count(outcome); + } + assert_eq!( + (report.committed, report.rejected, report.superseded, report.no_patch, report.abandoned), + (1, 2, 3, 4, 1) + ); } } From d3b904bd41d85307c813cd5b8ce027c4c8ab33ed Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:59:23 +0100 Subject: [PATCH 10/11] Tests: the abandonment test holds its store Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 6f5d9c5..a5d5ce1 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -14517,7 +14517,8 @@ mod tests { &format!("refused-{call}"), ) })); - let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); + let store = fresh_store(); + let runner = sweep_runner(&mailbox, port.clone(), store.clone()); for _ in 0..crate::elaboration::MAX_REFUSALS { let report = runner.sweep(pool(1), 1).await.unwrap(); assert_eq!(report.rejected, 1, "{report:?}"); From 2f6cc5241246e31590a59e4c0e22333fef37805a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 00:14:11 +0100 Subject: [PATCH 11/11] Tests: an abandoned row cut short of the repair limit is not a valid ending Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/controllers.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index a5d5ce1..577ff70 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -14490,6 +14490,11 @@ mod tests { }; assert_eq!(refusals.len(), crate::elaboration::MAX_REFUSALS + 1); assert!(row.integrity_is_valid()); + let mut cut = row.clone(); + if let SeedCheckpoint::NoPatch { refusals, .. } = &mut cut { + refusals.remove(0); + } + assert!(!cut.integrity_is_valid(), "a seed session cut short of its limit read as ended"); drop(stored); assert_eq!(runner.step().await.unwrap(), SeedOutcome::NoPatch); assert_eq!(script.seen.lock().unwrap().len(), seen, "an abandoned seed session ran inference again"); @@ -14543,6 +14548,10 @@ mod tests { refusals.pop(); })); assert!(!tamper(&|refusals| refusals.last_mut().unwrap().after_round = 1)); + // At exactly the repair limit the session was still repairable. + assert!(!tamper(&|refusals| { + refusals.remove(0); + })); let calls = port.calls(); let after = runner.sweep(pool(1), 1).await.unwrap(); assert_eq!((after.claimed, after.started), (0, 0), "{after:?}");