Complete assessment and evidence receipts

This commit is contained in:
Meta Vens 2026-08-16 23:16:18 +02:00
commit d4a21a4540
7 changed files with 330 additions and 36 deletions

View file

@ -18,8 +18,13 @@ pub enum KernelError {
Stale { expected: u64, actual: u64 },
#[error("action is impossible: {0}")]
Impossible(String),
#[error("assessment is stale or unknown")]
StaleAssessment,
#[error("assessment is unknown")]
UnknownAssessment,
#[error("assessment is stale at campaign revision {actual_revision}")]
StaleAssessment {
intent: ActionIntent,
actual_revision: u64,
},
#[error("invalid command: {0}")]
Invalid(String),
#[error("persistence failure: {0}")]
@ -144,11 +149,17 @@ fn execute(
}
WorldCommand::Attempt { assessment_digest } => {
let assessment = assessments
.remove(&assessment_digest)
.ok_or(KernelError::StaleAssessment)?;
.get(&assessment_digest)
.cloned()
.ok_or(KernelError::UnknownAssessment)?;
if assessment.revision != campaign.revision || assessment.expires_at < Utc::now() {
return Err(KernelError::StaleAssessment);
assessments.remove(&assessment_digest);
return Err(KernelError::StaleAssessment {
intent: assessment.intent,
actual_revision: campaign.revision,
});
}
assessments.remove(&assessment_digest);
if !assessment.admissible {
return Err(KernelError::Impossible(
assessment
@ -1242,12 +1253,10 @@ fn commit(
roll,
};
store
.append_with_replace(
.append_world_transition(
&row,
"ghostlight.campaign.v1",
&campaign,
"world_commit_receipt.v1",
"ghostlight.world_commit_receipt.v1",
&format!("{}-{}", campaign.id, campaign.revision),
&receipt,
)
@ -1469,6 +1478,65 @@ mod tests {
assert_eq!(campaign.revision, 1);
assert!(receipt.roll.is_some());
assert_eq!(store.keys("world_commit_receipt.v1").unwrap().len(), 1);
assert_eq!(store.keys("roll_receipt.v1").unwrap().len(), 1);
}
#[tokio::test]
async fn stale_assessment_returns_original_intent_for_fresh_compilation() {
let dir = tempfile::tempdir().unwrap();
let store = CampaignStore::open(dir.path().join("campaign.cc")).unwrap();
let kernel = WorldKernel::start(store.clone());
let seed = campaign();
kernel
.command(WorldCommand::CreateCampaign {
campaign: seed.clone(),
evidence_receipts: vec![],
model_stage_receipts: vec![],
})
.await
.unwrap();
let intent = ActionIntent {
actor_id: "player".into(),
description: "Open the ordinary door".into(),
intended_effect: "Pass through".into(),
};
let CommandResult::Assessed { assessment } = kernel
.command(WorldCommand::Assess {
expected_revision: 0,
intent: intent.clone(),
proposal: None,
})
.await
.unwrap()
else {
panic!()
};
kernel
.command(WorldCommand::Speak {
expected_revision: 0,
actor_id: "player".into(),
text: "Wait.".into(),
intended_effect: None,
})
.await
.unwrap();
let error = kernel
.command(WorldCommand::Attempt {
assessment_digest: assessment.digest,
})
.await
.unwrap_err();
match error {
KernelError::StaleAssessment {
intent: stale_intent,
actual_revision,
} => {
assert_eq!(stale_intent, intent);
assert_eq!(actual_revision, 1);
}
other => panic!("unexpected error: {other}"),
}
assert!(store.keys("roll_receipt.v1").unwrap().is_empty());
}
#[tokio::test]
@ -1636,7 +1704,14 @@ mod tests {
id: "vault:route".into(),
provider: "fixture".into(),
query_hash: "sha256:q".into(),
witnesses: vec![],
witnesses: vec![SourceWitness {
source_id: "lore/roads.md".into(),
exact_locator: "line:10".into(),
content_hash: "sha256:witness".into(),
excerpt: "The annex road remains open.".into(),
authority_lane: "canon".into(),
temporal_scope: "fixture-era".into(),
}],
retrieved_at: Utc::now(),
};
let candidate = CanonCandidate {
@ -1685,6 +1760,13 @@ mod tests {
assert_eq!(campaign.revision, 1);
assert_eq!(store.keys("vault_evidence_receipt.v1").unwrap().len(), 1);
assert_eq!(store.keys("canon_candidate.v1").unwrap().len(), 1);
let (_, manifest): (_, VaultManifest) = store
.load("vault_manifest.v1", &seed.id.to_string())
.unwrap()
.unwrap();
assert!(manifest.source_ids.contains("lore/roads.md"));
assert!(manifest.authority_lanes.contains("canon"));
assert!(manifest.temporal_scopes.contains("fixture-era"));
}
#[tokio::test]

View file

@ -15,7 +15,7 @@ use ghostlight_dungeon::{
RejectedProposalReceipt, WorldCommand, WorldCompilePreview,
},
gestalt::GestaltPresencePlanner,
kernel::CommandResult,
kernel::{CommandResult, KernelError},
mesh::{CampaignMeshSnapshot, MeshPublisher},
model::{DeepSeekPort, ModelPort, ModelStageRequest, run_validated_stage},
narrator::Narrator,
@ -238,6 +238,10 @@ async fn main() -> anyhow::Result<()> {
.route("/api/campaigns/fork", post(fork_campaign))
.route("/api/campaigns/reset", post(reset_campaign))
.route("/api/campaigns/export", get(export_campaign))
.route(
"/api/campaigns/canon-candidates.md",
get(export_canon_candidates_markdown),
)
.route("/api/operator", get(operator_inspector))
.fallback_service(ServeDir::new(web_root).append_index_html_on_directories(true))
.with_state(state);
@ -870,7 +874,10 @@ async fn command(
&receipt.output_hash,
&receipt,
);
if !plan.promotions.is_empty() || !plan.demotions.is_empty() {
if !plan.individuations.is_empty()
|| !plan.promotions.is_empty()
|| !plan.demotions.is_empty()
{
match runtime.kernel.command(WorldCommand::ReconcileGestaltPresence {
expected_revision: campaign.revision,
reason: summary.clone(),
@ -1012,6 +1019,66 @@ async fn command(
}
}
Err(error) => {
if let KernelError::StaleAssessment { intent, .. } = &error {
let Some(assessor) = &state.assessor else {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(ErrorBody {
error: "DeepSeek assessor is unavailable".into(),
}),
)
.into_response();
};
let campaign = match load_campaign(&runtime.store) {
Ok(value) => value,
Err(load_error) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorBody {
error: load_error.to_string(),
}),
)
.into_response();
}
};
match assessor.assess(&campaign, intent.clone()).await {
Ok((assessment, receipt)) => {
let _ = runtime.store.insert(
"persona_stage_receipt.v1",
"ghostlight.persona_stage_receipt.v1",
&receipt.output_hash,
&receipt,
);
return match runtime
.kernel
.command(WorldCommand::Assess {
expected_revision: campaign.revision,
intent: intent.clone(),
proposal: Some(assessment),
})
.await
{
Ok(result) => Json(result).into_response(),
Err(recompile_error) => (
StatusCode::CONFLICT,
Json(ErrorBody {
error: recompile_error.to_string(),
}),
)
.into_response(),
};
}
Err(recompile_error) => {
return (
StatusCode::BAD_GATEWAY,
Json(ErrorBody {
error: recompile_error.to_string(),
}),
)
.into_response();
}
}
}
if let Ok(campaign) = load_campaign(&runtime.store) {
let receipt = RejectedProposalReceipt {
schema: "ghostlight.rejected_proposal_receipt.v1".into(),
@ -1333,6 +1400,60 @@ async fn export_campaign(headers: HeaderMap, State(state): State<AppState>) -> R
}
}
async fn export_canon_candidates_markdown(
headers: HeaderMap,
State(state): State<AppState>,
) -> Response {
let session = match authenticated_session(&headers, &state).await {
Some(value) => value,
None => return StatusCode::UNAUTHORIZED.into_response(),
};
let runtime = match session_runtime(&state, &session).await {
Ok(Some(value)) => value,
Ok(None) => {
return (StatusCode::NOT_FOUND, "session has no selected campaign").into_response();
}
Err(error) => {
return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response();
}
};
let campaign = match load_campaign(&runtime.store) {
Ok(value) => value,
Err(error) => {
return (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response();
}
};
let mut markdown = format!(
"# Canon candidates — {}\n\nCampaign: `{}` \nRevision: `{}`\n\n",
campaign.name, campaign.id, campaign.revision
);
if campaign.canon_candidates.is_empty() {
markdown.push_str("No canon candidates have been recorded.\n");
}
for candidate in campaign.canon_candidates.values() {
markdown.push_str(&format!(
"## {}\n\n- Status: `{}`\n- Gap: {}\n- Proposed wording: {}\n- Evidence receipts: {}\n- Affected Vault sources: {}\n- Conflicts: {}\n\n",
candidate.id,
candidate.status,
candidate.gap,
candidate.proposed_wording,
candidate.evidence_receipt_ids.join(", "),
candidate.affected_vault_sources.join(", "),
candidate.conflicts.join("; "),
));
}
let mut response = Response::new(axum::body::Body::from(markdown));
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/markdown; charset=utf-8"),
);
response.headers_mut().insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_static("attachment; filename=canon-candidates.md"),
);
response
}
async fn operator_inspector(headers: HeaderMap, State(state): State<AppState>) -> Response {
let session = match authenticated_session(&headers, &state).await {
Some(value) => value,

View file

@ -1,12 +1,12 @@
use crate::domain::{
Campaign, GestaltMaterializationReceipt, StrategicTickReceipt, VaultEvidenceReceipt,
WorldCommitReceipt,
VaultManifest, WorldCommitReceipt,
};
use anyhow::{Context, Result, anyhow};
use chrono::Utc;
use cultcache_legacy::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Serialize, de::DeserializeOwned};
use std::path::Path;
use std::{collections::BTreeSet, path::Path};
#[derive(Clone)]
pub struct CampaignStore {
@ -92,6 +92,13 @@ impl CampaignStore {
&campaign.id.to_string(),
campaign,
)?);
let manifest = merge_vault_manifest(None, receipts);
rows.push(envelope(
"vault_manifest.v1",
"ghostlight.vault_manifest.v1",
&campaign.id.to_string(),
&manifest,
)?);
for receipt in receipts {
rows.push(envelope(
"vault_evidence_receipt.v1",
@ -144,22 +151,36 @@ impl CampaignStore {
Ok(next)
}
pub fn append_with_replace<T: Serialize, R: Serialize>(
pub fn append_world_transition<T: Serialize>(
&self,
expected: &CultCacheEnvelope,
next_schema: &str,
next: &T,
receipt_kind: &str,
receipt_schema: &str,
receipt_key: &str,
receipt: &R,
receipt: &WorldCommitReceipt,
) -> Result<CultCacheEnvelope> {
let next_row = envelope(&expected.r#type, next_schema, &expected.key, next)?;
let receipt_row = envelope(receipt_kind, receipt_schema, receipt_key, receipt)?;
if !self.inner.compare_and_swap_batch(
std::slice::from_ref(expected),
vec![next_row.clone(), receipt_row],
)? {
let mut rows = vec![
next_row.clone(),
envelope(
"world_commit_receipt.v1",
"ghostlight.world_commit_receipt.v1",
receipt_key,
receipt,
)?,
];
if let Some(roll) = &receipt.roll {
rows.push(envelope(
"roll_receipt.v1",
"ghostlight.roll_receipt.v1",
&roll.assessment_digest,
roll,
)?);
}
if !self
.inner
.compare_and_swap_batch(std::slice::from_ref(expected), rows)?
{
return Err(anyhow!("stale CultCache snapshot"));
}
Ok(next_row)
@ -190,6 +211,15 @@ impl CampaignStore {
receipt,
)?,
];
let existing_manifest = self.load::<VaultManifest>("vault_manifest.v1", &expected.key)?;
let manifest =
merge_vault_manifest(existing_manifest.as_ref().map(|(_, value)| value), evidence);
rows.push(envelope(
"vault_manifest.v1",
"ghostlight.vault_manifest.v1",
&expected.key,
&manifest,
)?);
for item in evidence {
rows.push(envelope(
"vault_evidence_receipt.v1",
@ -214,10 +244,11 @@ impl CampaignStore {
item,
)?);
}
if !self
.inner
.compare_and_swap_batch(std::slice::from_ref(expected), rows)?
{
let mut expected_rows = vec![expected.clone()];
if let Some((row, _)) = existing_manifest {
expected_rows.push(row);
}
if !self.inner.compare_and_swap_batch(&expected_rows, rows)? {
return Err(anyhow!("stale CultCache snapshot"));
}
Ok(next_row)
@ -300,6 +331,43 @@ impl CampaignStore {
}
}
fn merge_vault_manifest(
existing: Option<&VaultManifest>,
receipts: &[VaultEvidenceReceipt],
) -> VaultManifest {
let mut providers = existing
.map(|manifest| BTreeSet::from([manifest.provider.clone()]))
.unwrap_or_default();
let mut source_ids = existing
.map(|manifest| manifest.source_ids.clone())
.unwrap_or_default();
let mut authority_lanes = existing
.map(|manifest| manifest.authority_lanes.clone())
.unwrap_or_default();
let mut temporal_scopes = existing
.map(|manifest| manifest.temporal_scopes.clone())
.unwrap_or_default();
for receipt in receipts {
providers.insert(receipt.provider.clone());
for witness in &receipt.witnesses {
source_ids.insert(witness.source_id.clone());
authority_lanes.insert(witness.authority_lane.clone());
temporal_scopes.insert(witness.temporal_scope.clone());
}
}
VaultManifest {
schema: "ghostlight.vault_manifest.v1".into(),
provider: if providers.is_empty() {
"none".into()
} else {
providers.into_iter().collect::<Vec<_>>().join("+")
},
source_ids,
authority_lanes,
temporal_scopes,
}
}
fn envelope<T: Serialize>(
kind: &str,
schema: &str,

File diff suppressed because one or more lines are too long

4
web/dist/index.html vendored
View file

@ -1,5 +1,5 @@
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-DSqcLvft.js"></script>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GhostlightDungeon</title> <script type="module" crossorigin src="/assets/index-BINdyAeG.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Dt7lvyL0.css">
</head>
<body><header><p class="eyebrow">STARFIRE / PRIVATE VERSE</p><h1>GhostlightDungeon</h1><p id="status">Reading the world…</p></header><main>
@ -9,5 +9,5 @@
</div><div id="compiler-results"></div></section><section id="surface"></section>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
<form id="destination-form"><label>Compile a destination without moving there</label><input name="origin_location_id" placeholder="Current location id" required><input name="destination" placeholder="Where do you want the world to extend?" required><button type="submit">Retrieve destination</button></form>
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div><form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a><details><summary>Operator inspector</summary><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div><form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
</main></body></html>

View file

@ -7,5 +7,5 @@
</div><div id="compiler-results"></div></section><section id="surface"></section>
<form id="composer"><label for="attempt">Describe what you attempt</label><textarea id="attempt" required></textarea><div><button type="submit">Assess</button><button type="button" id="wait">Wait one hour</button></div></form><pre id="receipt" hidden></pre>
<form id="destination-form"><label>Compile a destination without moving there</label><input name="origin_location_id" placeholder="Current location id" required><input name="destination" placeholder="Where do you want the world to extend?" required><button type="submit">Retrieve destination</button></form>
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div><form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a><details><summary>Operator inspector</summary><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
<section id="campaign-lab" hidden><h2>Campaign laboratory</h2><div id="campaign-list"></div><form id="fork-form"><input name="name" placeholder="Fork name" required><button type="submit">Fork selected campaign</button></form><form id="reset-form"><input name="name" placeholder="Reset branch name" required><button type="submit">Reset from approved seed</button></form><a href="/api/campaigns/export" download>Export selected CultCache .cc</a> <a href="/api/campaigns/canon-candidates.md" download>Export canon candidates Markdown</a><details><summary>Operator inspector</summary><button type="button" id="load-operator">Load private state and receipts</button><div id="operator-output"></div></details></section>
</main><script type="module" src="/src/main.ts"></script></body></html>

View file

@ -59,7 +59,30 @@ async function showPreview(result: any) {
}
async function send(command: unknown) { status.textContent = "The world is considering the command…"; const response = await fetch("/api/command", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(command) }); const body = await response.json(); receipt.hidden = false; receipt.textContent = JSON.stringify(body, null, 2); if (!response.ok) { status.textContent = body.error ?? "The command was refused."; await refresh(); return body; } await refresh(); return body; }
composer.addEventListener("submit", async event => { event.preventDefault(); const text = document.querySelector<HTMLTextAreaElement>("#attempt")!.value.trim(); if (!text) return; const result=await send({ type: "assess", expected_revision: revision, intent: { actor_id: "player", description: text, intended_effect: text } }); if(result?.kind==="assessed"){const button=document.createElement("button");button.textContent=result.assessment.admissible?"Confirm server roll":"Revise attempt";button.addEventListener("click",async()=>{if(result.assessment.admissible){await send({type:"attempt",assessment_digest:result.assessment.digest});button.remove();}else{document.querySelector<HTMLTextAreaElement>("#attempt")!.focus();}});composer.append(button);} });
function installAssessment(result: any) {
if (result?.kind !== "assessed") return;
const button = document.createElement("button");
button.type = "button";
button.textContent = result.assessment.admissible ? "Confirm server roll" : "Revise attempt";
button.addEventListener("click", async () => {
if (!result.assessment.admissible) {
document.querySelector<HTMLTextAreaElement>("#attempt")!.focus();
return;
}
const attempted = await send({ type: "attempt", assessment_digest: result.assessment.digest });
button.remove();
// A stale preview is compiled again against the new revision. It still
// requires explicit confirmation; the server never rebases or auto-rolls it.
installAssessment(attempted);
});
composer.append(button);
}
composer.addEventListener("submit", async event => {
event.preventDefault();
const text = document.querySelector<HTMLTextAreaElement>("#attempt")!.value.trim();
if (!text) return;
installAssessment(await send({ type: "assess", expected_revision: revision, intent: { actor_id: "player", description: text, intended_effect: text } }));
});
document.querySelector<HTMLButtonElement>("#wait")!.addEventListener("click", () => void send({ type: "wait", expected_revision: revision, minutes: 60 }));
destinationForm.addEventListener("submit",async event=>{event.preventDefault();const result=await compilerPost("/api/compiler/destination",Object.fromEntries(new FormData(destinationForm)));const preview=result.preview;receipt.hidden=false;receipt.textContent=JSON.stringify(preview,null,2);status.textContent="Destination preview compiled; topology is unchanged until approval.";const button=document.createElement("button");button.textContent="Approve destination";button.addEventListener("click",async()=>{await compilerPost(`/api/compiler/destination/approve/${result.preview_id}`,{});button.remove();await refresh();});destinationForm.append(button);});
document.querySelector<HTMLFormElement>("#fork-form")!.addEventListener("submit",async event=>{event.preventDefault();await compilerPost("/api/campaigns/fork",Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)));await refresh();});