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 {