From a7a00ab198b836399bd1c714c7282b5bbc3a5805 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 23 Aug 2026 00:16:04 +0200 Subject: [PATCH] Separate Session Zero audit from preview proof --- .../bin/ghostlight-session-zero-inspect.rs | 29 ++- crates/ghostlight-dungeon/src/session_zero.rs | 245 +++++++++++++++++- .../ghostlight-dungeon-session-zero.md | 17 ++ notes/fresh-workspace-handoff.md | 2 + notes/ghostlight-current-system-map.md | 15 +- notes/ghostlight-implementation-plan.md | 5 + state/map.yaml | 1 + 7 files changed, 303 insertions(+), 11 deletions(-) diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs index 4b38aa8..973dd55 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-session-zero-inspect.rs @@ -1,6 +1,7 @@ use anyhow::{Context, Result, bail}; use ghostlight_dungeon::{persistence::CampaignStore, session_zero::SessionZeroState}; use serde_json::json; +use std::collections::BTreeMap; fn main() -> Result<()> { let mut arguments = std::env::args().skip(1); @@ -26,14 +27,33 @@ fn main() -> Result<()> { let (_, session) = store .load::("session_zero.v1", &key)? .context("session_zero.v1 row disappeared during inspection")?; - let first = session.preview_model_receipts.len().saturating_sub(limit); - let receipts = session.preview_model_receipts[first..] + let legacy_receipt_layout = + session.model_receipts.is_empty() && !session.preview_model_receipts.is_empty(); + let audit_receipts = if legacy_receipt_layout { + &session.preview_model_receipts + } else { + &session.model_receipts + }; + let first = audit_receipts.len().saturating_sub(limit); + let mut receipt_key_counts = BTreeMap::new(); + for receipt in audit_receipts { + *receipt_key_counts + .entry(receipt.storage_key().to_owned()) + .or_insert(0usize) += 1; + } + let duplicate_receipt_keys = receipt_key_counts + .into_iter() + .filter(|(_, count)| *count > 1) + .collect::>(); + let receipts = audit_receipts[first..] .iter() .map(|receipt| { json!({ + "storageKey": receipt.storage_key(), "stage": receipt.stage, "provider": receipt.provider, "model": receipt.model, + "snapshotBinding": receipt.snapshot_binding, "requestHash": receipt.request_hash, "outputHash": receipt.output_hash, "latencyMs": receipt.latency_ms, @@ -57,7 +77,10 @@ fn main() -> Result<()> { "sessionId": session.id, "revision": session.revision, "status": session.status, - "receiptCount": session.preview_model_receipts.len(), + "receiptCount": audit_receipts.len(), + "activePreviewReceiptCount": session.preview_model_receipts.len(), + "legacyReceiptLayout": legacy_receipt_layout, + "duplicateReceiptKeys": duplicate_receipt_keys, "receipts": receipts, }))? ); diff --git a/crates/ghostlight-dungeon/src/session_zero.rs b/crates/ghostlight-dungeon/src/session_zero.rs index 6efabff..d4a6c29 100644 --- a/crates/ghostlight-dungeon/src/session_zero.rs +++ b/crates/ghostlight-dungeon/src/session_zero.rs @@ -472,6 +472,9 @@ pub struct SessionZeroState { pub invites: BTreeMap, pub dm_persona: CampaignDmPersona, pub preview: Option, + #[serde(default)] + pub model_receipts: Vec, + #[serde(default)] pub preview_model_receipts: Vec, pub preview_evidence_coverage: Vec, pub preview_shared_digest: Option, @@ -606,6 +609,7 @@ impl SessionZeroState { private_member_memories: BTreeMap::new(), }, preview: None, + model_receipts: vec![], preview_model_receipts: vec![], preview_evidence_coverage: vec![], preview_shared_digest: None, @@ -749,6 +753,7 @@ impl SessionZeroState { invites: BTreeMap::new(), dm_persona, preview: None, + model_receipts: vec![], preview_model_receipts: vec![], preview_evidence_coverage: vec![], preview_shared_digest: None, @@ -1145,7 +1150,9 @@ impl SessionZeroRegistry { let (row, mut state) = store .load::("session_zero.v1", &id.to_string())? .ok_or_else(|| anyhow!("session zero state vanished during load"))?; - if demote_legacy_nonmaterial_decisions(&mut state) { + let changed = demote_legacy_nonmaterial_decisions(&mut state) + | migrate_legacy_model_receipts(&mut state); + if changed { store.replace(&row, "ghostlight.session_zero.v1", &state)?; } found.insert( @@ -3144,7 +3151,7 @@ fn execute( delta.dm_speech, )?; } - state.preview_model_receipts.extend(model_receipts); + state.model_receipts.extend(model_receipts); } SessionZeroCommand::SetBoundary { actor_account_hash, @@ -3464,7 +3471,8 @@ fn execute( .insert(member.id.clone(), state.character_digest(&member.id)?); } state.preview_evidence_coverage = preview.evidence_coverage.clone(); - state.preview_model_receipts.extend(model_receipts); + state.preview_model_receipts.clone_from(&model_receipts); + state.model_receipts.extend(model_receipts); let has_gaps = !preview.gaps.is_empty(); let gap_text = preview.gaps.join("\n- "); state.preview = Some(preview); @@ -3707,6 +3715,30 @@ fn demote_legacy_nonmaterial_decisions(state: &mut SessionZeroState) -> bool { changed } +fn migrate_legacy_model_receipts(state: &mut SessionZeroState) -> bool { + if !state.model_receipts.is_empty() || state.preview_model_receipts.is_empty() { + return false; + } + let legacy = std::mem::take(&mut state.preview_model_receipts); + if state.preview.is_some() + && state.review_campaign_id.is_none() + && let Some(current_start) = legacy + .iter() + .rposition(|receipt| receipt.stage == "custom_retrieval_plan") + && let Some(current_end) = legacy + .iter() + .enumerate() + .skip(current_start) + .filter(|(_, receipt)| receipt.stage == "agency_compile") + .map(|(index, _)| index) + .next_back() + { + state.preview_model_receipts = legacy[current_start..=current_end].to_vec(); + } + state.model_receipts = legacy; + true +} + fn validate_counter_replacement( countered: &SessionZeroDecision, member_id: Option<&str>, @@ -3891,6 +3923,7 @@ fn character_changed(state: &mut SessionZeroState, member_id: &str) { fn retire_preview(state: &mut SessionZeroState) { state.preview = None; + state.preview_model_receipts.clear(); state.preview_shared_digest = None; state.preview_character_digests.clear(); if state.roster_locked { @@ -4192,6 +4225,117 @@ mod tests { draft } + fn model_receipt(stage: &str, receipt_hash: &str, latency_ms: u64) -> ModelStageReceipt { + ModelStageReceipt { + schema: "ghostlight.persona_stage_receipt.v1".into(), + receipt_hash: receipt_hash.into(), + provider: "fixture".into(), + model: "fixture-model".into(), + stage: stage.into(), + snapshot_binding: "fixture-snapshot".into(), + request_hash: format!("request:{stage}"), + output_hash: format!("output:{stage}"), + source_receipt_ids: vec![], + latency_ms, + validation_result: "valid".into(), + local_validation_error: None, + input_chars: 100, + output_chars: 20, + provider_attempts: vec![], + } + } + + #[tokio::test] + async fn session_zero_keeps_inference_history_separate_from_active_preview_proof() { + let dir = tempdir().unwrap(); + let store = CampaignStore::open(dir.path().join("session-zero.cc")).unwrap(); + let mut initial = compilable_state(); + initial.roster_locked = true; + initial.status = SessionZeroStatus::Compiling; + let repeated_a = model_receipt("session_zero_dm_persona", "receipt:repeated", 10); + let repeated_b = model_receipt("session_zero_dm_persona", "receipt:repeated", 20); + initial.model_receipts = vec![repeated_a.clone(), repeated_b.clone()]; + SessionZeroKernel::initialize(&store, &initial).unwrap(); + let kernel = SessionZeroKernel::start(store, initial.id); + let current = model_receipt("custom_retrieval_plan", "receipt:current", 30); + let installed = kernel + .command(SessionZeroCommand::InstallPreview { + expected_revision: initial.revision, + preview: WorldCompilePreview { + schema: "ghostlight.world_compile_preview.v1".into(), + title: "Current preview".into(), + campaign: crate::resolution::tests::campaign(2, 1), + evidence_receipts: vec![], + evidence_coverage: vec![], + gaps: vec![], + branch_assumptions: vec![], + requires_approval: true, + }, + model_receipts: vec![current.clone()], + }) + .await + .unwrap(); + + assert_eq!( + installed.state.model_receipts, + [repeated_a, repeated_b, current.clone()] + ); + assert_eq!(installed.state.preview_model_receipts, [current]); + + let compiling = kernel + .command(SessionZeroCommand::BeginCompilation { + actor_account_hash: "account:host".into(), + expected_revision: installed.state.revision, + }) + .await + .unwrap(); + assert!(compiling.state.preview_model_receipts.is_empty()); + assert_eq!(compiling.state.model_receipts.len(), 3); + } + + #[test] + fn legacy_receipt_layout_migrates_without_changing_session_revision() { + let mut draft = compilable_state(); + draft.status = SessionZeroStatus::Review; + draft.preview = Some(WorldCompilePreview { + schema: "ghostlight.world_compile_preview.v1".into(), + title: "Current preview".into(), + campaign: crate::resolution::tests::campaign(2, 1), + evidence_receipts: vec![], + evidence_coverage: vec![], + gaps: vec![], + branch_assumptions: vec![], + requires_approval: true, + }); + let old = model_receipt("custom_retrieval_plan", "receipt:old-plan", 10); + let old_world = model_receipt("world_compile", "receipt:old-world", 20); + let current = model_receipt("custom_retrieval_plan", "receipt:current-plan", 30); + let current_world = model_receipt("world_compile", "receipt:current-world", 40); + let current_agency = model_receipt("agency_compile", "receipt:current-agency", 50); + let trailing_dm = model_receipt("session_zero_dm_persona", "receipt:later-dm", 60); + let legacy = vec![ + old, + old_world, + current.clone(), + current_world.clone(), + current_agency.clone(), + trailing_dm, + ]; + draft.preview_model_receipts.clone_from(&legacy); + let revision = draft.revision; + let status = draft.status.clone(); + + assert!(migrate_legacy_model_receipts(&mut draft)); + assert_eq!(draft.model_receipts, legacy); + assert_eq!( + draft.preview_model_receipts, + [current, current_world, current_agency] + ); + assert_eq!(draft.revision, revision); + assert_eq!(draft.status, status); + assert!(!migrate_legacy_model_receipts(&mut draft)); + } + #[tokio::test] async fn director_receives_stable_output_contracts_before_dynamic_context() { let director = SessionZeroDirector::new( @@ -4787,6 +4931,70 @@ mod tests { assert_eq!(loaded.revision, revision); } + #[tokio::test] + async fn registry_load_persists_legacy_receipt_ownership_migration() { + let root = tempdir().unwrap(); + let mut draft = compilable_state(); + let id = draft.id; + let revision = draft.revision; + draft.status = SessionZeroStatus::Review; + draft.preview = Some(WorldCompilePreview { + schema: "ghostlight.world_compile_preview.v1".into(), + title: "Current preview".into(), + campaign: crate::resolution::tests::campaign(2, 1), + evidence_receipts: vec![], + evidence_coverage: vec![], + gaps: vec![], + branch_assumptions: vec![], + requires_approval: true, + }); + let old = model_receipt("world_compile", "receipt:old-world", 10); + let current_plan = model_receipt("custom_retrieval_plan", "receipt:current-plan", 20); + let current_world = model_receipt("world_compile", "receipt:current-world", 30); + let current_agency = model_receipt("agency_compile", "receipt:current-agency", 40); + draft.preview_model_receipts = vec![ + old.clone(), + current_plan.clone(), + current_world.clone(), + current_agency.clone(), + ]; + let directory = root.path().join(id.to_string()); + fs::create_dir(&directory).unwrap(); + let store = CampaignStore::open(directory.join("session-zero.cc")).unwrap(); + SessionZeroKernel::initialize(&store, &draft).unwrap(); + drop(store); + + let registry = SessionZeroRegistry::new(root.path()).unwrap(); + registry.load_existing().await.unwrap(); + let loaded = registry.snapshot(id).await.unwrap(); + assert_eq!(loaded.revision, revision); + assert_eq!( + loaded.model_receipts, + [ + old, + current_plan.clone(), + current_world.clone(), + current_agency.clone() + ] + ); + assert_eq!( + loaded.preview_model_receipts, + [current_plan, current_world, current_agency] + ); + + let runtime = registry.runtime(id).await.unwrap(); + let (_, persisted) = runtime + .store + .load::("session_zero.v1", &id.to_string()) + .unwrap() + .unwrap(); + assert_eq!(persisted.model_receipts, loaded.model_receipts); + assert_eq!( + persisted.preview_model_receipts, + loaded.preview_model_receipts + ); + } + #[tokio::test] async fn actor_filtered_surface_never_projects_other_private_state_or_account_hashes() { let dir = tempdir().unwrap(); @@ -4967,9 +5175,14 @@ mod tests { let mut initial = compilable_state(); initial.roster_locked = true; initial.status = SessionZeroStatus::Compiling; + initial.model_receipts = vec![ + model_receipt("global_agency_doctrine_synthesis", "receipt:repeated", 10), + model_receipt("global_agency_doctrine_synthesis", "receipt:repeated", 20), + ]; SessionZeroKernel::initialize(&store, &initial).unwrap(); let kernel = SessionZeroKernel::start(store, initial.id); let gap = "The requested clinic district is branch-local.".to_owned(); + let current_receipt = model_receipt("custom_retrieval_plan", "receipt:current-preview", 30); let preview = WorldCompilePreview { schema: "ghostlight.world_compile_preview.v1".into(), title: "Hellas clinic pressure".into(), @@ -4984,7 +5197,7 @@ mod tests { .command(SessionZeroCommand::InstallPreview { expected_revision: initial.revision, preview, - model_receipts: vec![], + model_receipts: vec![current_receipt.clone()], }) .await .unwrap(); @@ -5034,6 +5247,26 @@ mod tests { .unwrap(); assert_eq!(publication.approved_world_preview_digest, exact_digest); assert_eq!(publication.approved_evidence_gaps, [gap]); + assert_eq!(approved.state.model_receipts.len(), 3); + assert_eq!( + approved.state.preview_model_receipts, + [current_receipt.clone()] + ); + let published_store = + CampaignStore::open(dir.path().join("published-campaign.cc")).unwrap(); + let published_campaign = approved.state.preview.as_ref().unwrap(); + published_store + .create_session_zero_campaign( + &published_campaign.campaign, + &published_campaign.evidence_receipts, + &approved.state.preview_model_receipts, + &publication, + ) + .unwrap(); + assert_eq!( + published_store.keys("persona_stage_receipt.v1").unwrap(), + [current_receipt.storage_key()] + ); let mut substituted = approved.state; substituted.preview.as_mut().unwrap().title = "A different world".into(); @@ -5291,6 +5524,7 @@ mod tests { .await .unwrap(); let before = posted.state.clone(); + let receipt = model_receipt("session_zero_dm_persona", "receipt:dm-notice", 10); let noticed = kernel .command(SessionZeroCommand::ApplyDmTurn { @@ -5303,7 +5537,7 @@ mod tests { dm_speech: "I couldn't finish that response. No draft state changed.".into(), ..Default::default() }, - model_receipts: vec![], + model_receipts: vec![receipt.clone()], }) .await .unwrap(); @@ -5314,6 +5548,7 @@ mod tests { assert_eq!(noticed.state.boundaries, before.boundaries); assert_eq!(noticed.state.shared_epoch, before.shared_epoch); assert_eq!(noticed.state.character_epochs, before.character_epochs); + assert_eq!(noticed.state.model_receipts, [receipt]); assert_eq!( noticed.state.preview_model_receipts, before.preview_model_receipts diff --git a/docs/architecture/ghostlight-dungeon-session-zero.md b/docs/architecture/ghostlight-dungeon-session-zero.md index 428898b..3877b42 100644 --- a/docs/architecture/ghostlight-dungeon-session-zero.md +++ b/docs/architecture/ghostlight-dungeon-session-zero.md @@ -17,6 +17,15 @@ shared/private channels, messages, contract, private character drafts, boundaries, decisions, approvals, DM Persona, evidence coverage, compilation preview, and publication receipt. +The store keeps two deliberately different model-receipt collections. The +inference audit contains every committed invocation, including two calls whose +semantic receipt hashes match but whose latency or provider-attempt telemetry +differs. The active-preview proof set contains only the compiler transaction +that produced the currently retained preview. Replacing or retiring a preview +clears that proof set without erasing the audit. A campaign publication carries +only the active proof set; historical DM turns and superseded compiler runs do +not become evidence for a seed they did not produce. + Player messages are durable conversation, not campaign facts. Projector, DM Persona, Interpreter, retrieval, and compilation stages return proposals. Only the kernel may change the draft. @@ -175,6 +184,14 @@ assumption lists beside the campaign seed. Substituting any preview makes every prior approval stale. Relevant edits retire the preview and invalidate the affected approvals. The host has no override. +Pre-cut Session Zero stores used one receipt list for both meanings. Registry +load migrates that list without advancing Session Zero revision or fictional +time: all entries become audit history, while an extant world-seed preview +receives the bounded final compiler transaction from its last +`custom_retrieval_plan` through `agency_compile` as its exact proof set. Later +conversation receipts and Contract Review previews are excluded. The migration +is an atomic CultCache replacement and is idempotent on restart. + Accepted extraordinary bargains become typed permissions. Later assessment receives their exact scope, prerequisites, costs, limits, exposure, evidence, and effect ceiling. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index b7184ae..a3dc3c8 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -44,6 +44,8 @@ rewrite. - `SessionZeroKernel` is the sole owner of pre-publication drafts, members, channels, boundaries, decisions, approvals, and the final approved digest. + It separately owns the complete model-invocation audit and the exact active + preview proof set; campaign publication may consume only the latter. - Each campaign `WorldKernel` mailbox is the sole owner of canonical world state and revision. Player commands, NPC proposals, ticks, travel, waits, imports, reloads, and contract amendments share its validated atomic commit path. diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md index 07476f2..bca342e 100644 --- a/notes/ghostlight-current-system-map.md +++ b/notes/ghostlight-current-system-map.md @@ -583,9 +583,13 @@ not stale suggestion materiality, owns that gate. Custom starts and characters use the same draft. The browser returns only decision commands and cannot echo a rewritten candidate into compilation. Candidate IDs, text, list sizes, and evidence references receive local -validation. Suggestion retrieval and model receipts remain in the Session Zero -store; publication compiles the unanimously approved brief, never the -conversation transcript. +validation. Suggestion retrieval and every committed model invocation remain +in the Session Zero audit, including repeated calls with the same semantic +receipt hash but different attempt telemetry. A separate active-preview receipt +set is replaced by each successful compiler transaction and cleared when that +preview is retired. Publication carries only that exact proof set; it never +treats DM turns or superseded compiler runs as evidence for the approved seed, +and it never compiles the conversation transcript. Gap-bearing compiler results are retained as exact non-canonical previews while Session Zero returns to drafting. The host can move that exact preview into @@ -646,6 +650,11 @@ exact staging directory and cannot poison daemon reload. Approval previews are retained until campaign publication, session selection, and reload all succeed; a retry may recover only an already-published store whose exact seed equals the preview. It cannot adopt a colliding campaign ID with different state. +Legacy Session Zero stores that used the preview receipt field as an append-only +audit migrate on registry load. The complete list remains audit history and the +final compiler transaction becomes the active proof set. This replacement is +idempotent and does not advance Session Zero revision, epochs, or fictional +time. The browser composer preserves the assessment contract's distinction between the character's described act or speech and the effect the player wants it to cause. The receipt panel is the sole owner of the current assessment, diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md index d2d2e03..3c067cc 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -31,6 +31,11 @@ persistent pins, approval-gated gestalt fission, graph and cover receipts, and a separate operator provider-concurrency limit. The specific authority map is `docs/architecture/ghostlight-multiresolution-agency.md`. +Session Zero model custody is split by purpose: every committed invocation is +retained in the audit for cost and failure analysis, while only the exact +compiler transaction behind the current preview is eligible for campaign +publication. Superseded previews and ordinary DM turns cannot contaminate the +seed proof set. The current interface cut makes that Eve publication the browser's actual product boundary. `ghostlight.play` is one stable actor-filtered surface across diff --git a/state/map.yaml b/state/map.yaml index cffd328..76e5872 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -88,6 +88,7 @@ live_architecture: - Approval-gated gestalt fission creates explicit child leaves plus `other/unknown`, preserves inactive parent lineage, and never erases member deltas. - Existing v0 training fixtures are regression evidence and have no runtime write authority. - SessionZeroKernel is the sole pre-world owner of persistent shared/private negotiation, typed contracts, character drafts, boundaries, decisions, invitations, and approvals. The WorldKernel receives only an unanimously approved brief at atomic publication. + - SessionZeroKernel keeps append-only model-invocation audit history separate from the active preview's exact compiler proof set. Repeated calls with one semantic receipt hash remain distinct audit entries; preview retirement clears only the proof set, and campaign publication receives only the receipts that produced the approved preview. Legacy conflated stores migrate atomically on registry load without changing revision, epochs, or fictional time. - SessionZeroKernel remains the identity and state owner for every human-controlled actor during compilation. Public player names and premises may inform the shared world frame, but actor and Gestalt-member outputs may not materialize those reserved people. The model-generated player object is only a provisional starting-position marker; Ghostlight removes it and installs the approved typed characters locally. A collision receives one same-snapshot correction and then rejects atomically. - Approved private relationships cross compilation through exact canonical subject IDs. Player references bind to approved actors; otherwise unresolved named people become stable server-generated relationship anchors. The shared world compiler receives no private subject name, identity handle, or relationship. After public topology validation, a separate private stage owns characterization and placement but cannot emit IDs, relationships, narration, facts, gaps, assumptions, or public changes; Ghostlight attaches the opaque ID and owner-only relationship locally. Omission, ambiguity, unknown placement, or collision rejects the candidate atomically, and links to actors, institutions, Gestalts, or named Gestalt members grant no knowledge or authority. - Gap-bearing compiler results remain non-canonical exact previews. Host review selection cannot approve them; every active member approval binds shared contract, private character, and the exact world-preview digest. Publication preserves that digest and the accepted evidence gaps and branch assumptions, while the Eve tree visibly renders the player-reviewable world shape without institution-private resources/goals or another player's relationship anchors.