From aa6b3efe4ce45426f6502c9d57c41265020b3984 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 15 Jul 2026 23:45:22 +0100 Subject: [PATCH] Execute sealed workspace coverage projections --- epiphany-core/src/semantic_backend.rs | 37 + .../src/workspace_coverage_projector.rs | 711 +++++++++++++++++- notes/epiphany-current-algorithmic-map.md | 32 +- notes/fresh-workspace-handoff.md | 21 + state/ledgers.msgpack | Bin 514848 -> 515233 bytes state/map.yaml | 4 +- 6 files changed, 786 insertions(+), 19 deletions(-) diff --git a/epiphany-core/src/semantic_backend.rs b/epiphany-core/src/semantic_backend.rs index fb42fe51..2b175ce7 100644 --- a/epiphany-core/src/semantic_backend.rs +++ b/epiphany-core/src/semantic_backend.rs @@ -144,6 +144,29 @@ impl QdrantBackend { Ok(()) } + /// Ensures a collection exists under one exact managed contract. A + /// concurrent creator may win between exists/create; that is acceptable + /// only when the collection it created has the identical contract. + pub(crate) fn ensure_exact_collection( + &self, + name: &str, + contract: &CollectionCompatibility, + ) -> Result<()> { + if !self.collection_exists(name)? { + if let Err(create_error) = self.create_collection(name, contract) { + if !self.collection_exists(name)? { + return Err(create_error).with_context(|| { + format!("failed to create managed Qdrant collection {name}") + }); + } + } + } + if self.collection_compatibility(name)? != *contract { + anyhow::bail!("managed Qdrant collection {name} has incompatible metadata"); + } + Ok(()) + } + pub(crate) fn upsert_points( &self, name: &str, @@ -233,6 +256,7 @@ impl QdrantBackend { .map(|(key, value)| json!({ "key": key, "match": { "value": value } })) .collect::>(); let mut offset: Option = None; + let mut seen_offsets = Vec::::new(); let mut ids = Vec::new(); loop { let response = self @@ -255,6 +279,12 @@ impl QdrantBackend { .with_context(|| format!("failed to decode Qdrant scroll response for {name}"))?; ids.extend(envelope.result.points.into_iter().map(|point| point.id)); offset = envelope.result.next_page_offset; + if let Some(next_offset) = offset.as_ref() { + if seen_offsets.contains(next_offset) { + anyhow::bail!("Qdrant scroll repeated a prior page offset for {name}"); + } + seen_offsets.push(next_offset.clone()); + } if offset.is_none() { break; } @@ -272,6 +302,7 @@ impl QdrantBackend { .map(|(key, value)| json!({ "key": key, "match": { "value": value } })) .collect::>(); let mut offset: Option = None; + let mut seen_offsets = Vec::::new(); let mut points = Vec::new(); loop { let response = self @@ -303,6 +334,12 @@ impl QdrantBackend { }), ); offset = envelope.result.next_page_offset; + if let Some(next_offset) = offset.as_ref() { + if seen_offsets.contains(next_offset) { + anyhow::bail!("Qdrant payload scroll repeated a prior page offset for {name}"); + } + seen_offsets.push(next_offset.clone()); + } if offset.is_none() { break; } diff --git a/epiphany-core/src/workspace_coverage_projector.rs b/epiphany-core/src/workspace_coverage_projector.rs index 7ae1da8d..635d5989 100644 --- a/epiphany-core/src/workspace_coverage_projector.rs +++ b/epiphany-core/src/workspace_coverage_projector.rs @@ -1,10 +1,17 @@ +use crate::semantic_backend::{ + CollectionCompatibility, QdrantBackend, SemanticPoint, SemanticStoredPoint, +}; use crate::{ BODY_BINDING_KEY, BODY_BINDING_TYPE, BODY_HEAD_KEY, BODY_HEAD_TYPE, BODY_MANIFEST_TYPE, BODY_OBSERVATION_TYPE, RepositoryBodyHead, RepositoryBodyObservationBasis, - WorkspaceCoverageChunkDescriptor, WorkspaceCoverageObligation, WorkspaceCoveragePolicy, - WorkspaceCoverageProjectionPlan, derive_workspace_coverage_obligation, - derive_workspace_coverage_projection_plan, read_verified_repository_body_bytes, - refine_workspace_coverage_obligation_utf8, runtime_repository_body_store_binding, + WORKSPACE_COVERAGE_HEAD_SCHEMA_VERSION, WORKSPACE_COVERAGE_RECEIPT_SCHEMA_VERSION, + WorkspaceCoverageChunkDescriptor, WorkspaceCoverageHead, WorkspaceCoverageObligation, + WorkspaceCoveragePointBinding, WorkspaceCoveragePointPayload, WorkspaceCoveragePolicy, + WorkspaceCoverageProjectionPlan, WorkspaceCoverageReceipt, + derive_workspace_coverage_obligation, derive_workspace_coverage_projection_plan, + read_verified_repository_body_bytes, refine_workspace_coverage_obligation_utf8, + runtime_repository_body_store_binding, validate_workspace_coverage_head, + workspace_coverage_execution_collection, }; use anyhow::{Result, anyhow, bail}; use cultcache_rs::{ @@ -24,6 +31,64 @@ const CHUNKER_ID: &str = "utf8_lines_96_overlap_8_v0"; const MAXIMUM_FILE_BYTES: u64 = 4 * 1024 * 1024; const CHUNK_LINES: usize = 96; const CHUNK_OVERLAP_LINES: usize = 8; +const RECEIPT_TYPE: &str = "gamecult.epiphany.workspace_coverage_receipt"; +const HEAD_TYPE: &str = "gamecult.epiphany.workspace_coverage_head"; +const HEAD_KEY: &str = "current"; + +#[derive(Clone, Debug)] +pub(crate) struct WorkspaceCoverageProjectionInput { + pub point_id: String, + pub text: String, + pub vector: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct WorkspaceCoverageObservedBinding { + collection_name: String, + point_count: u64, + point_set_sha256: String, + point_binding_set_sha256: String, +} + +pub(crate) trait WorkspaceCoverageProjectionPort { + fn ensure_exact_collection( + &mut self, + collection: &str, + compatibility: &CollectionCompatibility, + ) -> Result<()>; + fn upsert( + &mut self, + collection: &str, + points: &[SemanticPoint], + ) -> Result<()>; + fn observe_all( + &mut self, + collection: &str, + ) -> Result>>; +} + +impl WorkspaceCoverageProjectionPort for QdrantBackend { + fn ensure_exact_collection( + &mut self, + name: &str, + expected: &CollectionCompatibility, + ) -> Result<()> { + QdrantBackend::ensure_exact_collection(self, name, expected) + } + fn upsert( + &mut self, + name: &str, + points: &[SemanticPoint], + ) -> Result<()> { + self.upsert_points(name, points) + } + fn observe_all( + &mut self, + name: &str, + ) -> Result>> { + self.points_for_scope(name, &[]) + } +} #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( @@ -86,6 +151,7 @@ pub(crate) struct WorkspaceCoverageAcquisition { pub plan: WorkspaceCoverageProjectionPlan, pub claim: WorkspaceCoverageProjectionClaim, pub attempt: WorkspaceCoverageProjectionAttempt, + prior_head: Option, } pub(crate) fn acquire_workspace_coverage_projection( @@ -207,6 +273,7 @@ pub(crate) fn acquire_workspace_coverage_projection( plan, claim, attempt, + prior_head: find(&opening, HEAD_TYPE, HEAD_KEY).cloned(), }) } @@ -269,6 +336,284 @@ pub(crate) fn fail_workspace_coverage_projection( Ok(()) } +pub(crate) fn execute_workspace_coverage_projection( + acquisition: &WorkspaceCoverageAcquisition, + inputs: Vec, + port: &mut impl WorkspaceCoverageProjectionPort, +) -> Result { + let result = execute_and_commit(acquisition, inputs, port); + match result { + Ok(receipt) => Ok(receipt), + Err(error) => { + let message = format!("{error:#}"); + if let Err(terminal_error) = fail_workspace_coverage_projection(acquisition, &message) { + bail!( + "projection failed ({message}) and failure terminalization failed: {terminal_error:#}" + ); + } + Err(error) + } + } +} + +fn execute_and_commit( + acquisition: &WorkspaceCoverageAcquisition, + mut inputs: Vec, + port: &mut impl WorkspaceCoverageProjectionPort, +) -> Result { + inputs.sort_by(|left, right| left.point_id.cmp(&right.point_id)); + let mut planned = acquisition.plan.planned_points.clone(); + planned.sort_by(|left, right| left.point_id.cmp(&right.point_id)); + if inputs.len() != planned.len() { + bail!("projection inputs do not equal the sealed plan point count"); + } + let mut points = Vec::with_capacity(planned.len()); + for (input, expected) in inputs.into_iter().zip(&planned) { + if input.point_id != expected.point_id + || input.vector.len() != acquisition.plan.vector_dimensions as usize + || format!("{:x}", Sha256::digest(input.text.as_bytes())) != expected.chunk_sha256 + { + bail!("projection input does not match its sealed point descriptor"); + } + points.push(SemanticPoint { + id: expected.point_id.clone(), + vector: input.vector, + payload: payload_for(&acquisition.obligation, &acquisition.plan, expected), + }); + } + let collection_name = workspace_coverage_execution_collection( + &acquisition.plan.plan_id, + &acquisition.claim.claim_id, + acquisition.claim.claim_epoch, + )?; + let compatibility = CollectionCompatibility { + managed_by: "epiphany-workspace-coverage-projector".into(), + corpus_kind: "repository_body_workspace_coverage".into(), + schema_version: 0, + projection_version: acquisition.plan.plan_id.clone(), + embedding_provider_id: acquisition.plan.embedding_provider_id.clone(), + embedding_model: acquisition.plan.embedding_model.clone(), + vector_size: acquisition.plan.vector_dimensions as usize, + }; + port.ensure_exact_collection(&collection_name, &compatibility)?; + if !points.is_empty() { + port.upsert(&collection_name, &points)?; + } + let observed = observe_exact_bindings( + acquisition, + &collection_name, + port.observe_all(&collection_name)?, + )?; + commit_workspace_coverage_success(acquisition, observed) +} + +fn observe_exact_bindings( + acquisition: &WorkspaceCoverageAcquisition, + collection_name: &str, + observed: Vec>, +) -> Result { + let mut bindings = Vec::with_capacity(observed.len()); + for point in observed { + let payload = point + .payload + .ok_or_else(|| anyhow!("observed workspace point omitted payload"))?; + bindings.push(WorkspaceCoveragePointBinding { + point_id: point.id, + payload_sha256: digest(&payload)?, + }); + } + bindings.sort_by(|left, right| left.point_id.cmp(&right.point_id)); + if bindings + .windows(2) + .any(|pair| pair[0].point_id == pair[1].point_id) + { + bail!("observed workspace collection contains duplicate point IDs"); + } + if bindings != acquisition.plan.point_bindings { + bail!("observed workspace point bindings do not equal the sealed plan"); + } + let ids = bindings + .iter() + .map(|binding| binding.point_id.clone()) + .collect::>(); + Ok(WorkspaceCoverageObservedBinding { + collection_name: collection_name.into(), + point_count: bindings.len() as u64, + point_set_sha256: digest(&ids)?, + point_binding_set_sha256: digest(&bindings)?, + }) +} + +fn commit_workspace_coverage_success( + acquisition: &WorkspaceCoverageAcquisition, + observed: WorkspaceCoverageObservedBinding, +) -> Result { + if observed.point_count != acquisition.plan.expected_point_count + || observed.point_set_sha256 != acquisition.plan.expected_point_set_sha256 + || observed.point_binding_set_sha256 != acquisition.plan.point_binding_set_sha256 + { + bail!("observed binding proof is not the sealed plan"); + } + let backing = SingleFileMessagePackBackingStore::new(&acquisition.body_store); + let opening = backing.pull_all()?; + let authority = exact_obligation_body_authority(&opening, &acquisition.obligation)?; + let obligation_env = find( + &opening, + "gamecult.epiphany.workspace_coverage_obligation", + &acquisition.obligation.obligation_id, + ) + .ok_or_else(|| anyhow!("persisted projection obligation missing"))?; + let plan_env = find( + &opening, + "gamecult.epiphany.workspace_coverage_projection_plan", + &acquisition.plan.plan_id, + ) + .ok_or_else(|| anyhow!("persisted projection plan missing"))?; + let claim_env = + find(&opening, CLAIM_TYPE, CLAIM_KEY).ok_or_else(|| anyhow!("running claim missing"))?; + let attempt_env = find(&opening, ATTEMPT_TYPE, &acquisition.attempt.attempt_id) + .ok_or_else(|| anyhow!("running attempt missing"))?; + if decode::(obligation_env)? != acquisition.obligation + || decode::(plan_env)? != acquisition.plan + || decode::(claim_env)? != acquisition.claim + || decode::(attempt_env)? != acquisition.attempt + { + bail!("success refuses substituted obligation, plan, claim, or attempt"); + } + if find(&opening, HEAD_TYPE, HEAD_KEY) != acquisition.prior_head.as_ref() { + bail!("workspace coverage success lost its acquired prior head"); + } + let observed_at = chrono::Utc::now().to_rfc3339(); + let receipt_id = digest(&( + &acquisition.obligation.obligation_id, + &acquisition.plan.plan_id, + &observed.collection_name, + &observed.point_binding_set_sha256, + &acquisition.claim.claim_id, + acquisition.claim.claim_epoch, + ))?; + let receipt = WorkspaceCoverageReceipt { + schema_version: WORKSPACE_COVERAGE_RECEIPT_SCHEMA_VERSION.into(), + receipt_id, + obligation_id: acquisition.obligation.obligation_id.clone(), + plan_id: acquisition.plan.plan_id.clone(), + collection_name: observed.collection_name, + embedding_provider_id: acquisition.plan.embedding_provider_id.clone(), + embedding_model: acquisition.plan.embedding_model.clone(), + vector_dimensions: acquisition.plan.vector_dimensions, + observed_point_count: observed.point_count, + observed_point_set_sha256: observed.point_set_sha256, + observed_at, + observation_method: "qdrant_scroll_exact_point_bindings".into(), + observed_point_binding_set_sha256: observed.point_binding_set_sha256, + claim_id: acquisition.claim.claim_id.clone(), + claim_epoch: acquisition.claim.claim_epoch, + }; + let head = WorkspaceCoverageHead { + schema_version: WORKSPACE_COVERAGE_HEAD_SCHEMA_VERSION.into(), + workspace_id: acquisition.obligation.workspace_id.clone(), + obligation_id: acquisition.obligation.obligation_id.clone(), + plan_id: acquisition.plan.plan_id.clone(), + receipt_id: receipt.receipt_id.clone(), + body_observation_id: acquisition.obligation.body_observation_id.clone(), + body_generation: acquisition.obligation.body_generation, + manifest_root_sha256: acquisition.obligation.manifest_root_sha256.clone(), + claim_id: acquisition.claim.claim_id.clone(), + claim_epoch: acquisition.claim.claim_epoch, + }; + validate_workspace_coverage_head(&acquisition.obligation, &acquisition.plan, &receipt, &head)?; + let mut completed_claim = acquisition.claim.clone(); + completed_claim.status = "succeeded".into(); + let mut completed_attempt = acquisition.attempt.clone(); + completed_attempt.status = "succeeded".into(); + completed_attempt.completed_at = Some(chrono::Utc::now().to_rfc3339()); + let mut expected = authority.clone(); + expected.extend([ + obligation_env.clone(), + plan_env.clone(), + claim_env.clone(), + attempt_env.clone(), + ]); + if let Some(prior_head) = &acquisition.prior_head { + expected.push(prior_head.clone()); + } + let mut replacements = authority; + replacements.extend([ + obligation_env.clone(), + plan_env.clone(), + envelope(CLAIM_TYPE, CLAIM_KEY, &completed_claim)?, + envelope( + ATTEMPT_TYPE, + &completed_attempt.attempt_id, + &completed_attempt, + )?, + envelope(RECEIPT_TYPE, &receipt.receipt_id, &receipt)?, + envelope(HEAD_TYPE, HEAD_KEY, &head)?, + ]); + if !backing.compare_and_swap_batch(&expected, replacements)? { + bail!("workspace coverage success lost exact Body/plan/claim CAS"); + } + Ok(receipt) +} + +fn payload_for( + obligation: &WorkspaceCoverageObligation, + plan: &WorkspaceCoverageProjectionPlan, + point: &crate::WorkspaceCoveragePlannedPoint, +) -> WorkspaceCoveragePointPayload { + WorkspaceCoveragePointPayload { + obligation_id: obligation.obligation_id.clone(), + projection_schema_version: plan.projection_schema_version.clone(), + chunker_id: plan.chunker_id.clone(), + body_path: point.body_path.clone(), + source_raw_sha256: point.source_raw_sha256.clone(), + source_raw_byte_length: point.source_raw_byte_length, + chunk_index: point.chunk_index, + byte_start: point.byte_start, + byte_end: point.byte_end, + chunk_sha256: point.chunk_sha256.clone(), + } +} + +fn exact_obligation_body_authority( + opening: &[CultCacheEnvelope], + obligation: &WorkspaceCoverageObligation, +) -> Result> { + let head_env = find(opening, BODY_HEAD_TYPE, BODY_HEAD_KEY) + .ok_or_else(|| anyhow!("current Body head missing"))?; + let head: RepositoryBodyHead = decode(head_env)?; + if head.workspace_id != obligation.workspace_id + || head.generation != obligation.body_generation + || head.observation_id != obligation.body_observation_id + || head.manifest_root_sha256 != obligation.manifest_root_sha256 + { + bail!("workspace coverage success requires its exact current Body authority"); + } + [ + (BODY_BINDING_TYPE, BODY_BINDING_KEY), + (BODY_HEAD_TYPE, BODY_HEAD_KEY), + ( + BODY_OBSERVATION_TYPE, + obligation.body_observation_id.as_str(), + ), + (BODY_MANIFEST_TYPE, obligation.manifest_root_sha256.as_str()), + ] + .into_iter() + .map(|(ty, key)| { + find(opening, ty, key) + .cloned() + .ok_or_else(|| anyhow!("Body authority envelope {ty}/{key} missing")) + }) + .collect() +} + +fn digest(value: &(impl Serialize + ?Sized)) -> Result { + Ok(format!( + "{:x}", + Sha256::digest(rmp_serde::to_vec_named(value)?) + )) +} + fn preserve_or_insert_immutable( opening: &[CultCacheEnvelope], expected: &mut Vec, @@ -388,6 +733,98 @@ fn envelope(ty: &str, key: &str, value: &T) -> Result>, + upsert_calls: usize, + } + + impl FakeProjectionPort { + fn new(hostility: Hostility) -> Self { + Self { + hostility, + points: Vec::new(), + upsert_calls: 0, + } + } + } + + impl WorkspaceCoverageProjectionPort for FakeProjectionPort { + fn ensure_exact_collection(&mut self, _: &str, _: &CollectionCompatibility) -> Result<()> { + if matches!(self.hostility, Hostility::IncompatibleCollection) { + bail!("incompatible preexisting collection metadata"); + } + Ok(()) + } + fn upsert( + &mut self, + _: &str, + points: &[SemanticPoint], + ) -> Result<()> { + self.upsert_calls += 1; + self.points = points + .iter() + .map(|point| SemanticStoredPoint { + id: point.id.clone(), + payload: Some(point.payload.clone()), + }) + .collect(); + Ok(()) + } + fn observe_all( + &mut self, + _: &str, + ) -> Result>> { + let mut points = self.points.clone(); + match self.hostility { + Hostility::Honest | Hostility::IncompatibleCollection => {} + Hostility::WrongPayload => points[0].payload.as_mut().unwrap().chunk_index += 1, + Hostility::Extra => points.push(SemanticStoredPoint { + id: uuid::Uuid::new_v4().to_string(), + payload: points[0].payload.clone(), + }), + Hostility::Missing => { + points.pop(); + } + Hostility::Duplicate => points.push(points[0].clone()), + } + Ok(points) + } + } + + fn projection_inputs( + acquisition: &WorkspaceCoverageAcquisition, + repo: &Path, + ) -> Result> { + acquisition + .plan + .planned_points + .iter() + .map(|point| { + let bytes = std::fs::read(repo.join(&point.body_path))?; + let text = std::str::from_utf8( + &bytes[point.byte_start as usize..point.byte_end as usize], + )? + .to_string(); + Ok(WorkspaceCoverageProjectionInput { + point_id: point.point_id.clone(), + text, + vector: vec![0.25; acquisition.plan.vector_dimensions as usize], + }) + }) + .collect() + } #[test] fn named_chunker_preserves_utf8_boundaries_and_eight_line_overlap() -> Result<()> { let text = (0..105) @@ -488,4 +925,270 @@ mod tests { ); Ok(()) } + + #[test] + fn exact_observation_commits_receipt_and_hostile_point_sets_terminalize() -> Result<()> { + for hostility in [ + Hostility::Honest, + Hostility::IncompatibleCollection, + Hostility::WrongPayload, + Hostility::Extra, + Hostility::Missing, + Hostility::Duplicate, + ] { + let repo = tempfile::tempdir()?; + let state = tempfile::tempdir()?; + git(repo.path(), &["init"])?; + std::fs::write(repo.path().join("source.rs"), "fn one() {}\n")?; + git(repo.path(), &["add", "."])?; + let runtime = state.path().join("runtime.cc"); + let agents = state.path().join("agents.cc"); + let body = state.path().join("body.cc"); + crate::initialize_runtime_spine( + &runtime, + crate::RuntimeSpineInitOptions { + runtime_id: "projection-execution-runtime".into(), + display_name: "projection execution".into(), + created_at: "2026-07-15T00:00:00Z".into(), + }, + )?; + crate::ensure_agent_memory_swarm_identity(&agents, "projection-execution-swarm")?; + crate::bind_runtime_to_agent_memory_swarm(&runtime, &agents, "2026-07-15T00:00:01Z")?; + crate::bind_repository_body( + repo.path(), + &body, + &runtime, + "projection-execution-workspace", + )?; + let basis = crate::observe_runtime_repository_body_basis(&runtime)?; + let acquisition = + acquire_workspace_coverage_projection(&runtime, &basis, "provider", "model", 3)?; + let inputs = projection_inputs(&acquisition, repo.path())?; + let result = execute_workspace_coverage_projection( + &acquisition, + inputs, + &mut FakeProjectionPort::new(hostility), + ); + let entries = + SingleFileMessagePackBackingStore::new(&acquisition.body_store).pull_all()?; + match hostility { + Hostility::Honest => { + let receipt = result?; + assert!(find(&entries, RECEIPT_TYPE, &receipt.receipt_id).is_some()); + assert!(find(&entries, HEAD_TYPE, HEAD_KEY).is_some()); + } + _ => { + assert!(result.is_err()); + assert!(find(&entries, RECEIPT_TYPE, HEAD_KEY).is_none()); + let claim: WorkspaceCoverageProjectionClaim = + decode(find(&entries, CLAIM_TYPE, CLAIM_KEY).unwrap())?; + assert_eq!(claim.status, "failed"); + } + } + } + Ok(()) + } + + #[test] + fn body_advance_prevents_receipt_and_terminalizes_attempt() -> Result<()> { + let repo = tempfile::tempdir()?; + let state = tempfile::tempdir()?; + git(repo.path(), &["init"])?; + std::fs::write(repo.path().join("source.rs"), "fn one() {}\n")?; + git(repo.path(), &["add", "."])?; + let runtime = state.path().join("runtime.cc"); + let agents = state.path().join("agents.cc"); + let body = state.path().join("body.cc"); + crate::initialize_runtime_spine( + &runtime, + crate::RuntimeSpineInitOptions { + runtime_id: "body-advance-runtime".into(), + display_name: "body advance".into(), + created_at: "2026-07-15T00:00:00Z".into(), + }, + )?; + crate::ensure_agent_memory_swarm_identity(&agents, "body-advance-swarm")?; + crate::bind_runtime_to_agent_memory_swarm(&runtime, &agents, "2026-07-15T00:00:01Z")?; + crate::bind_repository_body(repo.path(), &body, &runtime, "body-advance-workspace")?; + let basis = crate::observe_runtime_repository_body_basis(&runtime)?; + let acquisition = + acquire_workspace_coverage_projection(&runtime, &basis, "provider", "model", 3)?; + let inputs = projection_inputs(&acquisition, repo.path())?; + std::fs::write(repo.path().join("source.rs"), "fn two() {}\n")?; + crate::observe_runtime_repository_body_basis(&runtime)?; + assert!( + execute_workspace_coverage_projection( + &acquisition, + inputs, + &mut FakeProjectionPort::new(Hostility::Honest) + ) + .is_err() + ); + let entries = SingleFileMessagePackBackingStore::new(&acquisition.body_store).pull_all()?; + assert!(find(&entries, HEAD_TYPE, HEAD_KEY).is_none()); + let claim: WorkspaceCoverageProjectionClaim = + decode(find(&entries, CLAIM_TYPE, CLAIM_KEY).unwrap())?; + assert_eq!(claim.status, "failed"); + Ok(()) + } + + #[test] + fn terminal_cas_loser_and_forged_observation_cannot_mint_receipts() -> Result<()> { + let repo = tempfile::tempdir()?; + let state = tempfile::tempdir()?; + git(repo.path(), &["init"])?; + std::fs::write(repo.path().join("source.rs"), "fn one() {}\n")?; + git(repo.path(), &["add", "."])?; + let runtime = state.path().join("runtime.cc"); + let agents = state.path().join("agents.cc"); + let body = state.path().join("body.cc"); + crate::initialize_runtime_spine( + &runtime, + crate::RuntimeSpineInitOptions { + runtime_id: "cas-loser-runtime".into(), + display_name: "cas loser".into(), + created_at: "2026-07-15T00:00:00Z".into(), + }, + )?; + crate::ensure_agent_memory_swarm_identity(&agents, "cas-loser-swarm")?; + crate::bind_runtime_to_agent_memory_swarm(&runtime, &agents, "2026-07-15T00:00:01Z")?; + crate::bind_repository_body(repo.path(), &body, &runtime, "cas-loser-workspace")?; + let basis = crate::observe_runtime_repository_body_basis(&runtime)?; + let acquisition = + acquire_workspace_coverage_projection(&runtime, &basis, "provider", "model", 3)?; + let collection_name = workspace_coverage_execution_collection( + &acquisition.plan.plan_id, + &acquisition.claim.claim_id, + acquisition.claim.claim_epoch, + )?; + let forged = WorkspaceCoverageObservedBinding { + collection_name: collection_name.clone(), + point_count: acquisition.plan.expected_point_count, + point_set_sha256: acquisition.plan.expected_point_set_sha256.clone(), + point_binding_set_sha256: "ff".repeat(32), + }; + assert!(commit_workspace_coverage_success(&acquisition, forged).is_err()); + fail_workspace_coverage_projection(&acquisition, "another terminal writer won")?; + let exact_but_late = WorkspaceCoverageObservedBinding { + collection_name, + point_count: acquisition.plan.expected_point_count, + point_set_sha256: acquisition.plan.expected_point_set_sha256.clone(), + point_binding_set_sha256: acquisition.plan.point_binding_set_sha256.clone(), + }; + assert!(commit_workspace_coverage_success(&acquisition, exact_but_late).is_err()); + let entries = SingleFileMessagePackBackingStore::new(&acquisition.body_store).pull_all()?; + assert!(find(&entries, HEAD_TYPE, HEAD_KEY).is_none()); + assert!(!entries.iter().any(|entry| entry.r#type == RECEIPT_TYPE)); + Ok(()) + } + + #[test] + fn empty_plan_observes_empty_collection_without_empty_upsert() -> Result<()> { + let repo = tempfile::tempdir()?; + let state = tempfile::tempdir()?; + git(repo.path(), &["init"])?; + std::fs::write(repo.path().join("empty.txt"), "")?; + git(repo.path(), &["add", "."])?; + let runtime = state.path().join("runtime.cc"); + let agents = state.path().join("agents.cc"); + let body = state.path().join("body.cc"); + crate::initialize_runtime_spine( + &runtime, + crate::RuntimeSpineInitOptions { + runtime_id: "empty-runtime".into(), + display_name: "empty".into(), + created_at: "2026-07-15T00:00:00Z".into(), + }, + )?; + crate::ensure_agent_memory_swarm_identity(&agents, "empty-swarm")?; + crate::bind_runtime_to_agent_memory_swarm(&runtime, &agents, "2026-07-15T00:00:01Z")?; + crate::bind_repository_body(repo.path(), &body, &runtime, "empty-workspace")?; + let basis = crate::observe_runtime_repository_body_basis(&runtime)?; + let acquisition = + acquire_workspace_coverage_projection(&runtime, &basis, "provider", "model", 3)?; + assert!(acquisition.plan.planned_points.is_empty()); + let mut port = FakeProjectionPort::new(Hostility::Honest); + let receipt = execute_workspace_coverage_projection(&acquisition, Vec::new(), &mut port)?; + assert_eq!(port.upsert_calls, 0); + assert_eq!(receipt.observed_point_count, 0); + Ok(()) + } + + #[test] + fn successive_generations_replace_only_the_acquired_prior_head() -> Result<()> { + let repo = tempfile::tempdir()?; + let state = tempfile::tempdir()?; + git(repo.path(), &["init"])?; + std::fs::write(repo.path().join("source.rs"), "fn a() {}\n")?; + git(repo.path(), &["add", "."])?; + let runtime = state.path().join("runtime.cc"); + let agents = state.path().join("agents.cc"); + let body = state.path().join("body.cc"); + crate::initialize_runtime_spine( + &runtime, + crate::RuntimeSpineInitOptions { + runtime_id: "head-cas-runtime".into(), + display_name: "head cas".into(), + created_at: "2026-07-15T00:00:00Z".into(), + }, + )?; + crate::ensure_agent_memory_swarm_identity(&agents, "head-cas-swarm")?; + crate::bind_runtime_to_agent_memory_swarm(&runtime, &agents, "2026-07-15T00:00:01Z")?; + crate::bind_repository_body(repo.path(), &body, &runtime, "head-cas-workspace")?; + + let basis_a = crate::observe_runtime_repository_body_basis(&runtime)?; + let acquisition_a = + acquire_workspace_coverage_projection(&runtime, &basis_a, "provider", "model", 3)?; + let inputs_a = projection_inputs(&acquisition_a, repo.path())?; + execute_workspace_coverage_projection( + &acquisition_a, + inputs_a, + &mut FakeProjectionPort::new(Hostility::Honest), + )?; + let backing = SingleFileMessagePackBackingStore::new(&acquisition_a.body_store); + let after_a = backing.pull_all()?; + let head_a = find(&after_a, HEAD_TYPE, HEAD_KEY).unwrap().clone(); + + std::fs::write(repo.path().join("source.rs"), "fn b() {}\n")?; + let basis_b = crate::observe_runtime_repository_body_basis(&runtime)?; + let acquisition_b = + acquire_workspace_coverage_projection(&runtime, &basis_b, "provider", "model", 3)?; + assert_eq!(acquisition_b.prior_head.as_ref(), Some(&head_a)); + let inputs_b = projection_inputs(&acquisition_b, repo.path())?; + execute_workspace_coverage_projection( + &acquisition_b, + inputs_b, + &mut FakeProjectionPort::new(Hostility::Honest), + )?; + let after_b = backing.pull_all()?; + let head_b = find(&after_b, HEAD_TYPE, HEAD_KEY).unwrap().clone(); + let decoded_b: WorkspaceCoverageHead = decode(&head_b)?; + assert_eq!(decoded_b.body_generation, basis_b.generation); + + std::fs::write(repo.path().join("source.rs"), "fn c() {}\n")?; + let basis_c = crate::observe_runtime_repository_body_basis(&runtime)?; + let acquisition_c = + acquire_workspace_coverage_projection(&runtime, &basis_c, "provider", "model", 3)?; + assert_eq!(acquisition_c.prior_head.as_ref(), Some(&head_b)); + assert!(backing.compare_and_swap_batch(&[head_b], vec![head_a.clone()])?); + let inputs_c = projection_inputs(&acquisition_c, repo.path())?; + assert!( + execute_workspace_coverage_projection( + &acquisition_c, + inputs_c, + &mut FakeProjectionPort::new(Hostility::Honest) + ) + .is_err() + ); + let final_entries = backing.pull_all()?; + assert_eq!(find(&final_entries, HEAD_TYPE, HEAD_KEY), Some(&head_a)); + assert!( + !final_entries + .iter() + .filter(|entry| entry.r#type == RECEIPT_TYPE) + .any(|entry| decode::(entry) + .is_ok_and(|receipt| receipt.claim_id == acquisition_c.claim.claim_id)) + ); + Ok(()) + } } diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 94610247..3c06f6d4 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -890,20 +890,26 @@ the indexed content. Receipt/head constructors and writers remain projector- private. Live query eligibility re-observes Qdrant; a stored receipt proves only that one exact observation completed. -The crate-private acquisition/failure foundation now exists but is deliberately -not production-reachable. Acquisition rechecks the exact current Body chain, -verifies historical bytes, excludes empty/oversize/non-UTF-8 files, derives the -named UTF-8-safe 96-line/8-line-overlap chunks, and CAS-installs immutable -obligation/plan plus a running claim/attempt in the Body store. Failure can -terminalize the exact attempt after Body advance and cannot publish a receipt or -head. There is no Qdrant actuator, terminal-success path, recovery path, service -pulse, query gate, or readiness claim yet. +The crate-private execution path now exists but remains deliberately +production-unreachable. It validates plan-sealed text hashes and vector +dimensions, creates or authenticates one exact managed claim/epoch Qdrant +collection, writes no empty upsert, whole-scrolls typed payloads, rejects cyclic +pagination plus duplicate/extra/missing/substituted points, and terminal-CASes +the receipt/head against the exact current Body authority, immutable plan, +running claim/attempt, and prior coverage head acquired at start. A CAS loser +cannot mint a receipt; failure can terminalize after Body advance. -The service shell remains an explicit design fork. Reusing the reserved memory -semantic-projector process minimizes process machinery but risks mixing -Mind/Modeling projection authority with repository Body coverage. A dedicated -workspace-coverage projector preserves ownership more visibly. Do not wire a -convenient CLI or generic job while this is unresolved. +The service fork is resolved in favor of a dedicated workspace-coverage +projector. Before it becomes reachable, claims must bind an executor +incarnation and startup lifecycle receipt authenticated by the reserved managed +service. The pulse needs an exact `Current` result to avoid endless reprojection +and a sealed text-rematerialization path rather than caller-supplied workspace +bytes. Abandoned-claim recovery may use only a newer latest managed launch and +its correlated ready heartbeat to fence the old incarnation in one Body-store +CAS. Time, Qdrant state, generic policy, process guesses, and caller strings are +not abandonment authority. If Body advanced, recovery terminalizes the stale +claim and lets normal acquisition derive a new plan; it never resurrects stale +work. This map must change when ownership changes. Historical scars belong in git, evidence, or an explicitly archived note—not in the machine's Modeling state. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 96cd8dcb..ef41fc25 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1742,6 +1742,27 @@ terminal-success CAS, and abandoned-claim recovery before choosing either a dedicated coverage service (preferred for ownership clarity) or a strictly separated lane in the reserved memory semantic-projector process. No CLI shim. +## Exact coverage execution port (2026-07-15) + +The crate-private projector now executes a sealed plan through the shared typed +Qdrant boundary. It validates text hashes and vector dimensions, authenticates +exact collection metadata, skips empty upserts, observes the whole typed +collection, rejects cyclic page offsets and duplicate/extra/missing/substituted +point payloads, and publishes receipt/head only through an exact terminal CAS +over Body authority, obligation, plan, claim, attempt, and the prior coverage +head seen at acquisition. Body advance and stale-head competitors cannot mint +success; ordinary failures terminalize the exact running attempt. + +This is still sealed foundation, not operational coverage. The dedicated +workspace-coverage service is now the chosen owner, but claims first need an +authenticated executor incarnation/startup receipt. Its pulse also needs an +exact already-current classification and sealed chunk-text rematerialization. +Recovery must consume a newer latest reserved-service launch plus its correlated +ready heartbeat and fence the old claim in one Body-store CAS. Timeouts, generic +managed policy, Qdrant contents, and process guesses are forbidden recovery +authority. If Body advanced, terminalize the obsolete claim and acquire a fresh +plan; never resurrect it. + The deployment next action is unchanged and permission-bound. Do not reboot without exact live operator approval. With that approval, run the real reboot/logon recovery proof already specified above. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 2ff23a1832c2258a304f2930f288a96a6bdf0e5b..e8ad9c23ebd39cb8afb345cf2503bed05ca0a7fe 100644 GIT binary patch delta 390 zcmW-cJxc>Y5Qe?@afqEDq!9;fb6#>J3b9hbUK9ko$=)Qly4hWK=Mt~c!otGVXsiD~ z5EKhr8~=dlpK(p`FwOfh@8j#*)BDYL#29?o0Mqm2Mj>Ea z7)8L94JvD-=G0=P4Cc_2I+uD7B$5jdl~7V7rr-C(;OI1zg?Ac&IvC5IlD-IWjs!`| zX+a^u9BWkp7tWM}B1}NRuxs)vwF-4A6v|<0oir|)%J+5-x1nDu1?^Td3F{b?>^XE5 Y_);=WtAufsK3x99^+gXBy{CNR59geVRsaA1 delta 61 zcmZ3uQ+~lV`3(|`+(u?r#s*Qx7}#(A-K@-5$jErAc`8%;R3=6s2GPtw%mT!$K+Lv% JDieG64FHMN6m$Rp diff --git a/state/map.yaml b/state/map.yaml index 2e1ec2b0..e262fe74 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -2,8 +2,8 @@ experiment: name: EpiphanyAgent repository_body_observer: "Native Rust explicitly binds caller workspace ID to an existing validated runtime/swarm/source identity plus canonical Git root/object format/scope/policy. Bind also installs one immutable runtime-side RuntimeRepositoryBodyStoreBinding naming the canonical external Body-store locator and exact Body-binding hash; every read revalidates runtime/swarm/workspace/path/body identity and refuses a second store. Two equal sanitized temporary-index scans enumerate ignore-aware UTF-8 paths, Git modes, and nonrecursive gitlinks with global excludes disabled; raw regular bytes/lengths and non-followed symlink-target bytes are SHA-256 hashed. The domain-separated ordered raw manifest root, not the clean-filtered auxiliary tree OID, is authoritative Body identity. Every Git subprocess strips ambient repository/worktree/object/ref/index/namespace/replacement/graft/shallow and config-injection authority. Observe cannot mint identity. CultCache MessagePack atomically commits immutable manifest+observation and a manifest-root head by exact CAS. Canonical store-path checks precede writes; corrupt HEAD, sparse checkout, unsafe/unrepresentable paths, racing reads, and repo/runtime substitution fail closed. Only accepted stable observations persist; errors advance no head. Unchanged raw manifest preserves generation; status is read-pure. The observer owns bounded current-state identity, makes no historical continuity claim, and has no Ready field. The runtime route is locator authority only, not proof of model grounding." modeling_body_grounding: "Every coordinator-owned Modeling launch observes and carries one typed RepositoryBodyObservationBasis before worker thought. The immutable launch binds runtime/swarm/workspace/scope, Body-binding hash, observation generation/id/root, and scan interval. Modeling output contract v3 requires the exact worker-authored echo; ingress reloads the immutable launch and rejects missing/swapped basis, while non-Modeling cargo is forbidden. Mind admission review v1 and receipt v5 preserve that basis; admission validates exact launch/result/review equality plus the immutable historical Body artifacts, then copies it into the CAS receipt. Admission never samples current Body as a substitute. Direct Mind plan adoption and legacy migration remain explicitly ungrounded." - workspace_retrieval_coverage: "The production-unwired retrieval.rs oracle was deleted. Legacy EpiphanyRetrievalState is presentation-only: clean Ready projects Missing and the indexing job is Unavailable/unowned. Native v0 coverage contracts now load only an authenticated historical Repository Body manifest through the immutable runtime Body-store route, classify every ordered Body entry under a versioned bounded-regular-file policy, and seal the Body binding/root/generation, policy, and complete classification set into one obligation. A separate immutable projection plan seals projection/chunker/embedding identity plus the deterministic expected point set and derives a Qdrant-safe physical collection from that authority; callers cannot choose a shared collection. Receipt validation requires an exact post-write Qdrant scroll point-set match against the sealed plan, and the head joins the exact workspace+obligation+plan+receipt. No persistence writer, Qdrant executor, query gate, or readiness join exists yet, so these contracts cannot mint success by themselves. The next owner is a CAS-persisted projector that verifies Body bytes, writes and scroll-observes Qdrant, then atomically publishes the exact receipt/head." - workspace_coverage_projector: "The sealed projector is the only coverage writer and is intentionally production-unreachable until execution, terminal success, and abandoned-claim recovery exist. Its crate-private foundation persists in the Repository Body CultCache store, not the runtime store. Acquisition authenticates the exact current Body binding/head/observation/manifest, verifies live regular-file bytes against the historical manifest, explicitly excludes empty/oversize/non-UTF-8 files, derives UTF-8-safe 96-line chunks with 8-line overlap, seals UUIDv5 point descriptors plus ID-to-payload binding root, and CAS-installs immutable obligation/plan with one running claim/attempt. Failure terminalizes that exact claim/attempt even after Body advances and cannot write receipt/head. No Qdrant call, success writer, query gate, service pulse, or readiness exists. Future physical work uses claim+epoch fenced collections; success requires whole-collection typed payload scroll and terminal CAS against the still-current Body head. Runtime shell choice remains open: a separately owned workspace-coverage projector service is cleaner than smuggling Body authority into the Mind/Modeling memory projector, while a shared transport daemon could host strictly separated typed lanes if ownership remains explicit." + workspace_retrieval_coverage: "The production-unwired retrieval.rs oracle was deleted. Legacy EpiphanyRetrievalState is presentation-only: clean Ready projects Missing and the indexing job is Unavailable/unowned. Native v0 coverage contracts load only an authenticated historical Repository Body manifest through the immutable runtime Body-store route, classify every ordered Body entry under a versioned bounded-regular-file policy, and seal Body binding/root/generation, policy, complete classification, projection/chunker/embedding identity, and the deterministic point/payload binding set. The crate-private projector now owns exact Qdrant execution and receipt/head publication, but remains production-unreachable pending authenticated service identity and abandoned-claim fencing. Query admission and the readiness join remain absent." + workspace_coverage_projector: "The sealed projector is the only coverage writer and persists in the Repository Body CultCache store. Acquisition authenticates the exact current Body chain, verifies regular-file bytes, excludes empty/oversize/non-UTF-8 files, derives UTF-8-safe 96-line chunks with 8-line overlap, seals UUIDv5 point descriptors plus the ID-to-payload binding root, and CAS-installs immutable obligation/plan with one running claim/attempt. Execution validates every supplied text/vector against that plan, ensures an exact managed claim/epoch Qdrant collection, skips empty upserts, whole-scrolls typed payloads while rejecting cyclic offsets and duplicate/extra/missing/substituted points, and terminal-CAS publishes receipt/head only while Body, plan, claim, attempt, and the acquired prior coverage head remain exact. Failure terminalizes the exact attempt even after Body advance. The module remains production-unreachable: claims do not yet bind an authenticated executor incarnation/startup receipt, there is no current/no-op pulse classification or sealed text rematerialization surface, and abandoned claims cannot yet be fenced. The selected shell is a dedicated workspace-coverage projector service; it must use a reserved managed policy and latest launch-correlated ready heartbeat, never timeout, generic policy, Qdrant state, or caller strings, as recovery authority." repository_readiness_join: "Mind must own one race-bounded derived repository-readiness operation from exact authenticated authorities: freshly observe Body root R1, validate canonical RepoModel plus exact Mind admission and Body-grounding receipt, authenticated semantic projection eligibility for that admitted model, and workspace retrieval coverage bound to R1 and a named scope policy, then freshly observe R2 and require R2=R1. Its output is observed-ready-at with a truth interval ending at the second scan, not timeless Ready; later reads revalidate. A→B→A is harmless for content-addressed artifacts. Watcher/journal continuity and Hands receipts are invalidation triggers only. Legacy retrieval Ready/empty dirty paths, timestamps, watcher silence, Git OIDs, Qdrant existence, counts, and unrelated generations are forbidden substitutes." status: active phase: phase_6_reflection_boundary