Interrupt the narrative turn instead of losing it

A scope digest that moved between a subject's prose and its commit is one
event with one detector — the kernel — and one handler, which renews the
turn's binding without re-running the Persona and lowers the same prose a
second time against an anonymous account of what moved.

Cut first. The narrative lane's three `ensure_scope_unchanged` calls are
gone: two detectors reporting different errors for one fact is what made
the pass need an entry point per stage. `exact_opportunity` is now the
sole authority on whether a scope moved, which is where the binding
already lives, and the operational lane keeps its early abort because it
holds nothing to preserve. `SubjectSnapshot` loses `holdings`,
`dependencies`, `incident_routes`, `authority`, and `controls` — each a
projection of a `ScopeComponents` field — and carries the components
whole instead.

The turn is re-recorded, never re-run. `PersonaTurnBinding` gains
`interrupted_from`, and a re-lowered turn's receipt commits to the
receipt it replaced by value; the prose and both inference receipts are
copied. One re-lowering is a property of the persisted shape rather than
a counter: a turn whose binding carries `interrupted_from` has no
successor arm.

What the Interpreter is shown is the typed component diff of the
subject's *own* components, named by meaning with no value, id, count or
actor, plus every statement told to it since its bound revision. The
renderer takes values rather than a snapshot, so a neighbour's state is
a compile error rather than a review note.

`controller_work.v11` and `persona_turn_receipt.v3` refuse prior rows
with no shim. No kernel arm changes: `ScopeComponents` gains
`Deserialize` and no field, so every scope digest is byte-identical.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-05 22:27:44 +02:00
commit 1ef973a861
5 changed files with 810 additions and 87 deletions

View file

@ -1065,7 +1065,9 @@ async fn dispatch_controller(
drop(permit);
let quarantine = match &result {
Ok(ControllerHttpResult::Pending { quarantine, .. }) => *quarantine,
Ok(ControllerHttpResult::Completed { .. }) => false,
Ok(ControllerHttpResult::Completed { .. } | ControllerHttpResult::Interrupted { .. }) => {
false
}
Err(error) => error.requires_quarantine(),
};
if quarantine {
@ -1106,6 +1108,18 @@ async fn dispatch_controller(
))
.into_response()
}
Ok(ControllerHttpResult::Interrupted { message, receipt }) => Json(eve::command_result(
&invocation,
"denied",
message,
current_world(state)
.await
.ok()
.map(|snapshot| eve::surface_version(snapshot.as_ref())),
None,
Some(receipt),
))
.into_response(),
Ok(ControllerHttpResult::Pending {
state_name,
message,
@ -1189,6 +1203,12 @@ enum ControllerHttpResult {
receipt: Value,
quarantine: bool,
},
/// The turn ended without reaching the world: its one re-lowering was spent
/// or refused. Not a commit, and not a retryable state.
Interrupted {
message: &'static str,
receipt: Value,
},
}
fn controller_narrative_result(run: NarrativeRun) -> ControllerHttpResult {
@ -1225,6 +1245,23 @@ fn controller_narrative_result(run: NarrativeRun) -> ControllerHttpResult {
NarrativeRun::Pending(pending) => {
controller_pending_result(pending.mode(), pending.reason(), pending.persona_prose())
}
NarrativeRun::Interrupted(interruption) => ControllerHttpResult::Interrupted {
message: "The world moved under this turn and it could not be lowered again.",
receipt: json!({
"kind":"narrative_interrupted",
"subject":interruption.subject(),
"boundScopeDigest":interruption.bound_scope_digest(),
"freshScopeDigest":interruption.fresh_scope_digest(),
"personaProse":interruption.persona_turn().source_prose(),
"personaReceiptDigest":interruption.persona_turn().receipt_digest(),
"gap":{
"kind":interruption.gap().kind,
"startByte":interruption.gap().source.start_byte,
"endByte":interruption.gap().source.end_byte,
"detail":interruption.gap().detail,
},
}),
},
}
}
@ -1940,6 +1977,19 @@ async fn run_cover_tick(state: &AppState) {
"a detail narrative cell is pending"
);
}
// The operator's record of a turn the world overtook. It is
// reached only after the one re-lowering was spent or refused:
// a turn that re-lowers and commits reports as completed like
// any other.
Ok(CellRun::Narrative(NarrativeRun::Interrupted(interruption))) => {
tracing::info!(
subject = ?interruption.subject(),
bound_scope_digest = interruption.bound_scope_digest(),
fresh_scope_digest = interruption.fresh_scope_digest().unwrap_or("none"),
detail = interruption.gap().detail.as_str(),
"a detail narrative cell was interrupted"
);
}
Ok(CellRun::Operational(OperationalRun::Pending(pending))) => {
tracing::info!(
reason = ?pending.reason(),

View file

@ -1040,7 +1040,7 @@ mod tests {
.subjects
.iter()
.find(|subject| subject.id == mirror.first)
.and_then(|subject| subject.holdings.get(&mirror.grain).copied()),
.and_then(|subject| subject.components.holdings.get(&mirror.grain).copied()),
Some(Quantity(6))
);
}

File diff suppressed because it is too large Load diff

View file

@ -859,14 +859,13 @@ pub(crate) struct SubjectSnapshot {
pub(crate) human_controller: Option<PrincipalId>,
pub(crate) affordances: BTreeSet<AffordanceId>,
pub(crate) position: Option<EntityId>,
/// Lowered from the one `scope_components` owner, so these are exactly what
/// the scope digest binds: this subject's own holdings, dependencies, and
/// grants, the routes incident to its place, and the offices it occupies
/// with what each lends. A counterparty's components never enter.
pub(crate) holdings: BTreeMap<EntityId, Quantity>,
pub(crate) dependencies: BTreeSet<DependencyTarget>,
pub(crate) incident_routes: Vec<EdgeId>,
pub(crate) authority: BTreeSet<AuthorityGrant>,
/// Exactly what the scope digest binds for this subject, carried whole
/// rather than lowered into projections that then have to be diffed back
/// together: its own position, incident routes, holdings, dependencies,
/// grants, delegated offices, known fact keys, controlled channels, and
/// commitments. A counterparty's components never enter. The narrative lane
/// persists this as the "before" an interruption is measured against.
pub(crate) components: ScopeComponents,
pub(crate) offices_held: Vec<OfficeSnapshot>,
/// View-only, and covered by no digest: an institution's own offices, so
/// its controller can see what it lends and to whom. No precondition reads
@ -880,11 +879,9 @@ pub(crate) struct SubjectSnapshot {
/// perception surface: a subject perceives a speech act if and only if it
/// holds `Knowledge` of that act's fact. Ordered by `spoken_at` then `fact`.
pub(crate) knowledge: Vec<KnowledgeSnapshot>,
/// The channels this subject controls, by id. Not their reach: who else is
/// in earshot is a question about other subjects.
pub(crate) controls: BTreeSet<EntityId>,
/// Digest-bound, lowered from the one `scope_components` call `snapshot`
/// already makes, so view and digest cannot drift.
/// already makes, so view and digest cannot drift. Carries `past_due`,
/// which the components do not.
pub(crate) commitments: Vec<CommitmentSnapshot>,
/// Pressure on self. View-only: read by no precondition, so covered by no
/// digest. Pressure this subject *sources* is excluded — it is another
@ -2954,7 +2951,13 @@ fn overlapping_holder(state: &WorldState) -> Option<SubjectId> {
/// restored by the front door. A target that walks out of a jurisdiction
/// mid-flight therefore fails at `Authorized` rather than rebinding, while a
/// revoked grant is a `ScopeChanged`.
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
///
/// `Deserialize` is here so the narrative lane can persist a subject's own
/// components as the "before" an interruption is measured against. No field
/// changes with it, so `ScopePreimage`'s serialization — and therefore every
/// scope digest — is byte-identical.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(super) struct ScopeComponents {
position: Option<Position>,
routes: BTreeMap<EdgeId, EdgeRecord>,
@ -3405,20 +3408,15 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
human_controller: controller.human_principal().cloned(),
affordances,
position: components.position.map(|position| position.place),
holdings: components.holdings,
dependencies: components.dependencies,
incident_routes: components.routes.into_keys().collect(),
authority: components.authority,
offices_held,
offices_granted,
redress,
knowledge,
controls: components.controls.into_keys().collect(),
commitments: components
.commitments
.into_iter()
.iter()
.map(|(key, commitment)| CommitmentSnapshot {
key,
key: *key,
kind: commitment.kind,
counterparty: commitment.counterparty,
due: commitment.due,
@ -3426,6 +3424,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
past_due: commitment.due <= state.now,
})
.collect(),
components,
pressures: state
.pressures
.get(subject_id)
@ -7873,14 +7872,14 @@ mod tests {
// Grants are the subject's own; offices held and offices granted are
// the two ends of one link and never merge.
assert!(of(civic.reeve).authority.is_empty());
assert!(of(civic.reeve).components.authority.is_empty());
assert_eq!(of(civic.reeve).offices_held.len(), 1);
assert!(of(civic.reeve).offices_granted.is_empty());
assert_eq!(of(civic.treasury).offices_granted.len(), 2);
assert!(of(civic.treasury).offices_held.is_empty());
assert!(of(civic.farmer).authority.is_empty());
assert!(of(civic.farmer).components.authority.is_empty());
assert_eq!(
of(civic.treasury).authority,
of(civic.treasury).components.authority,
BTreeSet::from([
AuthorityGrant {
kind: authority_kind(LEVY_KIND),
@ -8168,7 +8167,7 @@ mod custody_tests {
.into_iter()
.find(|subject| subject.id == custody.holder)
.expect("the holder is in the snapshot");
assert!(subject.holdings.is_empty());
assert!(subject.components.holdings.is_empty());
}
#[test]
@ -8261,7 +8260,7 @@ mod custody_tests {
.into_iter()
.find(|subject| subject.id == custody.counterparty)
.expect("the counterparty is in the snapshot");
assert!(counterparty.holdings.is_empty());
assert!(counterparty.components.holdings.is_empty());
}
#[test]
@ -8417,7 +8416,7 @@ mod custody_tests {
.find(|subject| subject.id == custody.holder)
.expect("the holder is in the snapshot");
assert_eq!(
subject.dependencies,
subject.components.dependencies,
BTreeSet::from([DependencyTarget::Route(topology.shutter)])
);
}

View file

@ -3,7 +3,7 @@ use sha2::{Digest, Sha256};
pub const MEMBRANE_SCHEMA: &str = "ghostlight.persona_projection_membrane.v1";
pub const COGNITION_CONTROLLER_SCHEMA: &str = "ghostlight.decision_controller.v1";
pub const PERSONA_TURN_RECEIPT_SCHEMA: &str = "ghostlight.persona_turn_receipt.v2";
pub const PERSONA_TURN_RECEIPT_SCHEMA: &str = "ghostlight.persona_turn_receipt.v3";
pub const RECORD_GAP_TOOL_NAME: &str = "record_gap";
pub const RECORD_GAP_TOOL_CONTRACT: &str = "record_gap(kind: ambiguity | missing_reference | missing_affordance | missing_primitive | unresolved, source_start_byte: integer, source_end_byte: integer, detail: string)";
@ -110,7 +110,7 @@ pub fn build_interpreter_prompt(input: &InterpreterPrompt<'_>) -> String {
None => "The harness supplies the current legal typed proposal tools immediately before each step. Use only those current contracts; never reuse a contract remembered from an earlier step.".into(),
};
format!(
"<!-- membrane:{MEMBRANE_SCHEMA}:interpreter -->\nYou are a private Interpreter. Translate a natural Persona turn into zero or more typed candidate proposals supported by the prose and permissioned context. The owning runtime validates and commits proposals; you never claim that a proposed consequence already happened. Do not invent knowledge, capability, custody, perception, identifiers, or state references.\n\nInterpretation is total: this turn cannot fail because some prose has no available translation. The harness has already preserved the Persona turn verbatim as noncanonical source prose. Capture every translation you can justify, citing its exact UTF-8 byte span in that source. Spoken words become a typed speech proposal; wondering, deciding, attempting, and narration are not automatically speech. If a meaningful passage cannot be represented safely, call `{gap_tool}` instead of guessing. A report containing only source prose, or source prose plus gaps, is valid. If the step budget ends, the harness completes the report and records the unresolved source instead of failing.\n\nThe always-available gap tool is:\n{gap_contract}\nUse `ambiguity` when several translations remain live, `missing_reference` when the prose lacks an exact world reference, `missing_affordance` when the subject lacks a permitted way to attempt it, `missing_primitive` when the ontology has no suitable proposal vocabulary, and `unresolved` only when no narrower account fits.\n\n{proposal_contract}\n\nDomain guidance and exact permissions:\n{guidance}\n\nIdentity:\n{identity}\n\nPermissioned typed context:\n{context}\n\nLived stream:\n{stream}\n\nPersona turn (already preserved verbatim as source evidence):\n{output}",
"<!-- membrane:{MEMBRANE_SCHEMA}:interpreter -->\nYou are a private Interpreter. Translate a natural Persona turn into zero or more typed candidate proposals supported by the prose and permissioned context. The owning runtime validates and commits proposals; you never claim that a proposed consequence already happened. Do not invent knowledge, capability, custody, perception, identifiers, or state references.\n\nInterpretation is total: this turn cannot fail because some prose has no available translation. The harness has already preserved the Persona turn verbatim as noncanonical source prose. Capture every translation you can justify, citing its exact UTF-8 byte span in that source. Spoken words become a typed speech proposal; wondering, deciding, attempting, and narration are not automatically speech. If a meaningful passage cannot be represented safely, call `{gap_tool}` instead of guessing. A report containing only source prose, or source prose plus gaps, is valid. If the step budget ends, the harness completes the report and records the unresolved source instead of failing.\n\nThe always-available gap tool is:\n{gap_contract}\nUse `ambiguity` when several translations remain live, `missing_reference` when the prose lacks an exact world reference, `missing_affordance` when the subject lacks a permitted way to attempt it, `missing_primitive` when the ontology has no suitable proposal vocabulary, and `unresolved` only when no narrower account fits.\n\nIf a section headed `Interrupted:` follows the Persona turn, the world moved after that prose was written and before it could take effect. The prose is not re-written and not re-authored; translate it again against what that section reports. You may capture a shorter or different span of the same prose, a different permitted action the prose supports, or call `{gap_tool}` with `unresolved` when the intent the prose carried has been overtaken. The reported change is not something this person said, did, or caused.\n\n{proposal_contract}\n\nDomain guidance and exact permissions:\n{guidance}\n\nIdentity:\n{identity}\n\nPermissioned typed context:\n{context}\n\nLived stream:\n{stream}\n\nPersona turn (already preserved verbatim as source evidence):\n{output}",
identity = input.identity,
guidance = input.domain_guidance,
context = input.typed_context,
@ -205,6 +205,13 @@ pub struct PersonaTurnBinding {
pub scope_digest: String,
pub projector_receipt_digest: String,
pub persona_inference_receipt_digest: String,
/// The binding this same prose was first receipted under. Present exactly
/// on a re-lowered turn: the world moved between the prose and its commit,
/// so the turn's binding was renewed against the fresh opportunity while the
/// prose and both inference receipts were carried across unchanged. Its own
/// `interrupted_from` is always `None` — prose is lowered at most twice, so
/// a chain is not a shape this type admits.
pub interrupted_from: Option<Box<PersonaTurnBinding>>,
}
/// Immutable source evidence persisted by the NarrativePersona runner before
@ -223,6 +230,9 @@ pub struct PersonaTurn {
pub enum PersonaTurnIntegrityError {
SourceDigestMismatch,
ReceiptDigestMismatch,
/// A re-lowered turn whose predecessor was itself re-lowered. One
/// re-lowering per turn is a property of the type, not a counter.
InterruptionChained,
}
impl std::fmt::Display for PersonaTurnIntegrityError {
@ -233,6 +243,8 @@ impl std::fmt::Display for PersonaTurnIntegrityError {
}
Self::ReceiptDigestMismatch => formatter
.write_str("Persona turn binding or source does not match its persisted receipt"),
Self::InterruptionChained => formatter
.write_str("Persona prose was already re-lowered once and admits no second"),
}
}
}
@ -287,6 +299,9 @@ impl PersonaTurn {
let source_prose = source_prose.into();
let source_digest = source_digest.into();
let receipt_digest = receipt_digest.into();
if !interruption_is_unchained(&binding) {
return Err(PersonaTurnIntegrityError::InterruptionChained);
}
if sha256(&source_prose) != source_digest {
return Err(PersonaTurnIntegrityError::SourceDigestMismatch);
}
@ -302,7 +317,8 @@ impl PersonaTurn {
}
pub fn receipt_is_valid(&self) -> bool {
sha256(&self.source_prose) == self.source_digest
interruption_is_unchained(&self.binding)
&& sha256(&self.source_prose) == self.source_digest
&& persona_turn_receipt_digest(&self.binding, &self.source_digest)
== self.receipt_digest
}
@ -595,7 +611,24 @@ pub fn sha256(value: &str) -> String {
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
}
/// One re-lowering, expressed as a shape rather than a count: the binding a
/// re-lowered turn replaced must itself be an original.
fn interruption_is_unchained(binding: &PersonaTurnBinding) -> bool {
binding
.interrupted_from
.as_ref()
.is_none_or(|prior| prior.interrupted_from.is_none())
}
fn persona_turn_receipt_digest(binding: &PersonaTurnBinding, source_digest: &str) -> String {
// The prior binding's receipt over the *same* source digest is exactly the
// receipt the first turn published, so a re-lowered turn's receipt commits
// to the turn it replaced by value.
let interrupted_from = binding
.interrupted_from
.as_ref()
.map(|prior| persona_turn_receipt_digest(prior, source_digest))
.unwrap_or_default();
let mut digest = Sha256::new();
for value in [
PERSONA_TURN_RECEIPT_SCHEMA.as_bytes(),
@ -605,6 +638,7 @@ fn persona_turn_receipt_digest(binding: &PersonaTurnBinding, source_digest: &str
binding.scope_digest.as_bytes(),
binding.projector_receipt_digest.as_bytes(),
binding.persona_inference_receipt_digest.as_bytes(),
interrupted_from.as_bytes(),
source_digest.as_bytes(),
] {
digest.update((value.len() as u64).to_le_bytes());
@ -635,6 +669,7 @@ mod tests {
scope_digest: "sha256:world-state".into(),
projector_receipt_digest: "sha256:projector-receipt".into(),
persona_inference_receipt_digest: "sha256:persona-inference-receipt".into(),
interrupted_from: None,
};
PersonaTurn::record(binding, source_prose)
}
@ -720,6 +755,49 @@ mod tests {
);
}
#[test]
fn a_re_lowered_turn_commits_to_the_receipt_it_replaced_and_admits_no_chain() {
let source = "I say, \"The western brace is giving way.\"";
let first = turn(source);
let mut renewed = first.binding().clone();
renewed.scope_digest = "sha256:world-state-moved".into();
renewed.interrupted_from = Some(Box::new(first.binding().clone()));
let second = PersonaTurn::record(renewed.clone(), source);
// The prose and both inference receipts are carried, never recomputed.
assert_eq!(second.source_prose(), first.source_prose());
assert_eq!(second.source_digest(), first.source_digest());
assert_eq!(
second.binding().projector_receipt_digest,
first.binding().projector_receipt_digest
);
assert_eq!(
second.binding().persona_inference_receipt_digest,
first.binding().persona_inference_receipt_digest
);
// The second receipt commits to the first by value.
assert_ne!(second.receipt_digest(), first.receipt_digest());
assert_eq!(
second.binding().interrupted_from.as_deref(),
Some(first.binding())
);
assert!(second.receipt_is_valid());
let mut chained = renewed.clone();
chained.interrupted_from = Some(Box::new(renewed));
let third = PersonaTurn::record(chained.clone(), source);
assert!(!third.receipt_is_valid());
assert_eq!(
PersonaTurn::rehydrate(
chained,
third.source_prose(),
third.source_digest(),
third.receipt_digest(),
),
Err(PersonaTurnIntegrityError::InterruptionChained)
);
}
#[test]
fn interpretation_is_total_at_step_exhaustion() {
let source = "I say, \"Mara, the bridge is unsafe.\" Then I try the rusted western gate.";