Merge ghostlight-verse/dungeon-runahead-fix: run-ahead elaboration commits (standing structure in the prompt, per-attempt round budget, fair claim order, loud failures) (seeded-begin report h2; Soul s1 runahead-wedges-and-starves)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	crates/ghostlight/src/elaboration.rs
This commit is contained in:
Meta Vens 2026-12-03 00:32:50 +01:00
commit 5949034ee1
5 changed files with 660 additions and 51 deletions

View file

@ -14034,7 +14034,11 @@ 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 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());
@ -14241,6 +14245,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()
}
@ -14283,7 +14297,7 @@ mod tests {
roads: Vec<(&'static str, EntityId)>,
) -> impl Fn(usize, &PreparedInference) -> Result<InferenceOutput, InferenceFault> {
move |call, request| {
let prompt = prompt_of(request);
let prompt = answer_of(request);
let (label, road) = roads
.iter()
.find(|(label, _)| prompt.contains(label))
@ -14425,6 +14439,219 @@ mod tests {
task.await.unwrap();
}
/// 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(
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).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_eq!(snapshot.boundaries.len(), 1, "one entry answered, one still refused");
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.
#[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();
}
/// The one elaboration row a store holds, whatever its stage.
fn store_row(store: &Arc<RecordingWorkStore>) -> 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());
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");
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]
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 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:?}");
}
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<crate::elaboration::Refusal>)| {
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));
// 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:?}");
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.
@ -14788,7 +15015,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)
@ -14907,7 +15134,7 @@ mod tests {
) -> Result<InferenceOutput, InferenceFault> {
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",
@ -15009,7 +15236,7 @@ mod tests {
request: PreparedInference,
) -> Result<InferenceOutput, InferenceFault> {
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);
@ -15424,11 +15651,20 @@ mod tests {
.unwrap();
results.push(runner.sweep(pool(1), usize::MAX).await);
assert_eq!(port.calls(), tick + 1, "tick {tick}: one inference per sweep");
assert_eq!(
store.journal.lock().unwrap().work.len(),
1,
"tick {tick}: the store gained a row"
// 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!(
store.elaboration_in_flight().await.unwrap().len() <= 1,
"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.
@ -15466,7 +15702,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)

View file

@ -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.
@ -212,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,
@ -272,6 +308,20 @@ 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),
_ => false,
}
}
@ -353,6 +403,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<String>,
}
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 +443,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
@ -546,25 +630,64 @@ 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,
});
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)),
};
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.
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);
}
}
}
@ -651,13 +774,16 @@ impl ElaborationRunner {
&self,
permits: Arc<Semaphore>,
max_sessions: usize,
) -> Result<(), ControllerError> {
) -> Result<SweepReport, ControllerError> {
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 +799,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 +814,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 +836,52 @@ impl ElaborationRunner {
}
}
}
quarantine.map_or(Ok(()), Err)
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)
}
/// 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<Vec<(CommandId, ElaboratorSession)>, 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
@ -1024,7 +1198,12 @@ 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",
);
prompt.push_str(&super::table::render_world_structure(snapshot));
prompt.push('\n');
prompt_body(&mut prompt, receipts);
prompt
@ -1062,12 +1241,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 guidance, when it has any: its era and its premise. The
/// seed session's optional sentence rides beside it; the two are not the same
/// thing.
@ -1104,6 +1290,62 @@ 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 { .. }) => 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"
}
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 {
@ -1147,6 +1389,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
@ -1198,17 +1442,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() {
@ -1235,7 +1481,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(),
));
@ -1303,6 +1549,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 {
@ -1314,11 +1561,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,
}
}
}
@ -1653,8 +1901,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)
}
}
}
}
@ -1702,6 +1953,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,
}
}
@ -1938,6 +2201,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)
@ -2765,4 +3054,74 @@ 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<InferenceOutput> = (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<InferenceOutput> = 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());
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)
);
}
}

View file

@ -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::{

View file

@ -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,
},
@ -1578,6 +1587,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 +3339,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 +8399,8 @@ mod tests {
assert_eq!(
rejected,
vec![Mismatch::DuplicateAffordanceKind {
handle: DraftHandle::new("second")
handle: DraftHandle::new("second"),
kind: AffordanceKindName("haul".into()),
}]
);

View file

@ -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 {