From a13358986c794b69b8ce83f11353dc8e43e594ec Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 15 Jul 2026 23:26:51 +0100 Subject: [PATCH] Seal workspace coverage projector authority --- epiphany-core/src/lib.rs | 6 + epiphany-core/src/repository_body_observer.rs | 230 ++++++++ .../src/workspace_coverage_projector.rs | 491 ++++++++++++++++ .../src/workspace_retrieval_coverage.rs | 527 +++++++++++++----- notes/epiphany-current-algorithmic-map.md | 34 ++ notes/fresh-workspace-handoff.md | 20 + state/ledgers.msgpack | Bin 513851 -> 514848 bytes state/map.yaml | 1 + 8 files changed, 1164 insertions(+), 145 deletions(-) create mode 100644 epiphany-core/src/workspace_coverage_projector.rs diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 9d9854dd..9699eb53 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -35,6 +35,12 @@ mod substrate_gate; mod surfaces; mod thread_state_store; mod weksa_interlingua; +// Sealed foundation: intentionally unreachable until terminal success and +// abandoned-claim recovery exist. Keeping the lint local makes that boundary +// explicit without exporting mutation authority merely to silence dead-code. +#[allow(dead_code)] +mod workspace_coverage_projector; +#[allow(dead_code)] mod workspace_retrieval_coverage; pub use agent_launch::EPIPHANY_IMAGINATION_OWNER_ROLE; diff --git a/epiphany-core/src/repository_body_observer.rs b/epiphany-core/src/repository_body_observer.rs index dd90dc0a..0c290d9f 100644 --- a/epiphany-core/src/repository_body_observer.rs +++ b/epiphany-core/src/repository_body_observer.rs @@ -175,6 +175,14 @@ pub struct RepositoryBodyManifest { pub entries: Vec, } +#[derive(Clone, Debug, PartialEq, Eq)] +#[allow(dead_code)] // Sealed input for the not-yet-wired coverage projector. +pub(crate) struct VerifiedRepositoryBodyBytes { + pub relative_path: String, + pub raw_sha256: String, + pub bytes: Vec, +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache(type = "epiphany.repository_body.head", schema = "RepositoryBodyHead")] pub struct RepositoryBodyHead { @@ -344,6 +352,116 @@ pub fn authenticated_repository_body_manifest( Ok(manifest) } +#[allow(dead_code)] // Sealed input for the not-yet-wired coverage projector. +pub(crate) fn read_verified_repository_body_bytes( + runtime_store: &Path, + basis: &RepositoryBodyObservationBasis, + relative_path: &str, +) -> Result { + let manifest = authenticated_repository_body_manifest(runtime_store, basis)?; + validate_portable_relative_path(relative_path)?; + let entry = manifest + .entries + .iter() + .find(|entry| entry.path == relative_path) + .ok_or_else(|| { + anyhow!("path {relative_path:?} is not included in the historical Body manifest") + })?; + if entry.kind != "regular" + || (entry.git_mode != "100644" && entry.git_mode != "100755") + || entry.gitlink_oid.is_some() + || entry.raw_sha256.len() != 64 + || !entry + .raw_sha256 + .bytes() + .all(|byte| byte.is_ascii_hexdigit()) + { + bail!("historical Body entry {relative_path:?} is not an authenticated regular file"); + } + + let route = runtime_repository_body_store_binding(runtime_store)? + .ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?; + let entries = load_body_envelopes(Path::new(&route.body_store_path))?; + let binding: RepositoryBodyBinding = decode( + find(&entries, BODY_BINDING_TYPE, BODY_BINDING_KEY) + .ok_or_else(|| anyhow!("runtime repository Body store has no Body binding"))?, + )?; + let root = std::fs::canonicalize(&binding.git_top_level) + .context("bound repository root is missing")?; + if root != PathBuf::from(&binding.git_top_level) { + bail!("bound repository root is no longer canonical"); + } + let path = safe_worktree_path(&root, relative_path)?; + reject_reparse_or_symlink_components(&root, relative_path)?; + let resolved = std::fs::canonicalize(&path) + .with_context(|| format!("historical Body path {relative_path:?} is missing"))?; + if !resolved.starts_with(&root) || resolved != path { + bail!( + "historical Body path {relative_path:?} does not resolve canonically beneath its bound root" + ); + } + + let before = std::fs::symlink_metadata(&path)?; + if !before.file_type().is_file() || metadata_is_reparse_point(&before) { + bail!("historical Body path {relative_path:?} is no longer a regular file"); + } + let bytes = std::fs::read(&path) + .with_context(|| format!("cannot read historical Body path {relative_path:?}"))?; + let after = std::fs::symlink_metadata(&path)?; + require_stable_metadata(relative_path, &before, &after)?; + if metadata_is_reparse_point(&after) || !after.file_type().is_file() { + bail!("historical Body path {relative_path:?} changed kind during raw read"); + } + let actual_sha256 = format!("{:x}", Sha256::digest(&bytes)); + if bytes.len() as u64 != entry.raw_byte_length || actual_sha256 != entry.raw_sha256 { + bail!( + "historical Body path {relative_path:?} bytes disagree with its authenticated manifest entry" + ); + } + Ok(VerifiedRepositoryBodyBytes { + relative_path: relative_path.into(), + raw_sha256: actual_sha256, + bytes, + }) +} + +fn validate_portable_relative_path(path: &str) -> Result<()> { + if path.is_empty() || path.starts_with('/') || path.contains('\\') { + bail!("unsafe or non-portable Body path {path:?}"); + } + if path + .split('/') + .any(|part| part.is_empty() || part == "." || part == "..") + { + bail!("unsafe or non-portable Body path {path:?}"); + } + Ok(()) +} + +fn reject_reparse_or_symlink_components(root: &Path, relative: &str) -> Result<()> { + let mut cursor = root.to_path_buf(); + for component in relative.split('/') { + cursor.push(component); + let metadata = std::fs::symlink_metadata(&cursor) + .with_context(|| format!("historical Body path {relative:?} is missing"))?; + if metadata.file_type().is_symlink() || metadata_is_reparse_point(&metadata) { + bail!("historical Body path {relative:?} traverses a symlink or reparse point"); + } + } + Ok(()) +} + +#[cfg(windows)] +fn metadata_is_reparse_point(metadata: &std::fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt; + metadata.file_attributes() & 0x400 != 0 +} + +#[cfg(not(windows))] +fn metadata_is_reparse_point(_: &std::fs::Metadata) -> bool { + false +} + pub fn observe_repository_body( repo: &Path, store: &Path, @@ -713,11 +831,30 @@ fn require_stable_metadata( if before.len() != after.len() || before.file_type() != after.file_type() || before.modified().ok() != after.modified().ok() + || !metadata_identity_matches(before, after) { bail!("indexed path {relative:?} changed during raw read"); } Ok(()) } + +#[cfg(unix)] +fn metadata_identity_matches(before: &std::fs::Metadata, after: &std::fs::Metadata) -> bool { + use std::os::unix::fs::MetadataExt; + before.dev() == after.dev() && before.ino() == after.ino() +} + +#[cfg(windows)] +fn metadata_identity_matches(before: &std::fs::Metadata, after: &std::fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt; + before.creation_time() == after.creation_time() + && before.file_attributes() == after.file_attributes() +} + +#[cfg(not(any(unix, windows)))] +fn metadata_identity_matches(_: &std::fs::Metadata, _: &std::fs::Metadata) -> bool { + true +} fn raw_entry( path: &str, mode: &str, @@ -1251,6 +1388,99 @@ mod tests { Ok(()) } #[test] + fn verified_body_bytes_match_authenticated_historical_entry() -> Result<()> { + let d = repo()?; + let state = tempfile::tempdir()?; + let (_, runtime) = bound(d.path(), state.path(), "verified", "runtime", "swarm")?; + std::fs::write(d.path().join("source.bin"), [0_u8, 255, 7, 9])?; + run(d.path(), &["add", "."])?; + let basis = observe_runtime_repository_body_basis(&runtime)?; + let verified = read_verified_repository_body_bytes(&runtime, &basis, "source.bin")?; + assert_eq!(verified.relative_path, "source.bin"); + assert_eq!(verified.bytes, [0_u8, 255, 7, 9]); + assert_eq!( + verified.raw_sha256, + format!("{:x}", Sha256::digest(&verified.bytes)) + ); + Ok(()) + } + #[test] + fn verified_body_bytes_refuse_changed_or_substituted_current_body() -> Result<()> { + let d = repo()?; + let state = tempfile::tempdir()?; + let (_, runtime) = bound(d.path(), state.path(), "verified", "runtime", "swarm")?; + write(&d.path().join("tracked"), "AAAA")?; + run(d.path(), &["add", "."])?; + let historical = observe_runtime_repository_body_basis(&runtime)?; + + write(&d.path().join("tracked"), "BBBB")?; + assert!( + read_verified_repository_body_bytes(&runtime, &historical, "tracked") + .unwrap_err() + .to_string() + .contains("bytes disagree") + ); + let advanced = observe_runtime_repository_body_basis(&runtime)?; + assert!(advanced.generation > historical.generation); + assert_eq!( + read_verified_repository_body_bytes(&runtime, &advanced, "tracked")?.bytes, + b"BBBB" + ); + + std::fs::remove_file(d.path().join("tracked"))?; + std::fs::create_dir(d.path().join("tracked"))?; + assert!( + read_verified_repository_body_bytes(&runtime, &advanced, "tracked") + .unwrap_err() + .to_string() + .contains("regular file") + ); + Ok(()) + } + #[test] + fn verified_body_bytes_refuse_noncanonical_and_nonmanifest_paths() -> Result<()> { + let d = repo()?; + let state = tempfile::tempdir()?; + let (_, runtime) = bound(d.path(), state.path(), "verified", "runtime", "swarm")?; + write(&d.path().join("tracked"), "body")?; + run(d.path(), &["add", "."])?; + let basis = observe_runtime_repository_body_basis(&runtime)?; + for path in [ + "", + "/tracked", + "../tracked", + "a/../tracked", + "./tracked", + "a\\tracked", + ] { + assert!(read_verified_repository_body_bytes(&runtime, &basis, path).is_err()); + } + assert!(read_verified_repository_body_bytes(&runtime, &basis, "untracked").is_err()); + Ok(()) + } + #[cfg(unix)] + #[test] + fn verified_body_bytes_refuse_symlink_substitution_and_parent_escape() -> Result<()> { + use std::os::unix::fs::symlink; + + let d = repo()?; + let state = tempfile::tempdir()?; + let (_, runtime) = bound(d.path(), state.path(), "verified", "runtime", "swarm")?; + std::fs::create_dir(d.path().join("inside"))?; + write(&d.path().join("inside/tracked"), "body")?; + run(d.path(), &["add", "."])?; + let basis = observe_runtime_repository_body_basis(&runtime)?; + std::fs::remove_file(d.path().join("inside/tracked"))?; + symlink("../.git/HEAD", d.path().join("inside/tracked"))?; + assert!(read_verified_repository_body_bytes(&runtime, &basis, "inside/tracked").is_err()); + + std::fs::remove_file(d.path().join("inside/tracked"))?; + std::fs::remove_dir(d.path().join("inside"))?; + symlink(".git", d.path().join("inside"))?; + assert!(read_verified_repository_body_bytes(&runtime, &basis, "inside/tracked").is_err()); + Ok(()) + } + #[test] fn ignored_and_mtime_only_are_unchanged() -> Result<()> { let d = repo()?; let state = tempfile::tempdir()?; diff --git a/epiphany-core/src/workspace_coverage_projector.rs b/epiphany-core/src/workspace_coverage_projector.rs new file mode 100644 index 00000000..7ae1da8d --- /dev/null +++ b/epiphany-core/src/workspace_coverage_projector.rs @@ -0,0 +1,491 @@ +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, +}; +use anyhow::{Result, anyhow, bail}; +use cultcache_rs::{ + CacheBackingStore, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, +}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; + +const CLAIM_TYPE: &str = "gamecult.epiphany.workspace_coverage_projection_claim"; +const ATTEMPT_TYPE: &str = "gamecult.epiphany.workspace_coverage_projection_attempt"; +const CLAIM_KEY: &str = "workspace-coverage-projector-current"; +const CLAIM_SCHEMA: &str = "gamecult.epiphany.workspace_coverage_projection_claim.v0"; +const ATTEMPT_SCHEMA: &str = "gamecult.epiphany.workspace_coverage_projection_attempt.v0"; +const PROJECTION_SCHEMA: &str = "gamecult.epiphany.workspace_bytes_projection.v0"; +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; + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.epiphany.workspace_coverage_projection_claim", + schema = "WorkspaceCoverageProjectionClaim" +)] +pub(crate) struct WorkspaceCoverageProjectionClaim { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + claim_id: String, + #[cultcache(key = 2)] + claim_epoch: u64, + #[cultcache(key = 3)] + plan_id: String, + #[cultcache(key = 4)] + attempt_id: String, + #[cultcache(key = 5)] + obligation_id: String, + #[cultcache(key = 6)] + body_observation_id: String, + #[cultcache(key = 7)] + body_generation: u64, + #[cultcache(key = 8)] + manifest_root_sha256: String, + #[cultcache(key = 9)] + status: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.epiphany.workspace_coverage_projection_attempt", + schema = "WorkspaceCoverageProjectionAttempt" +)] +pub(crate) struct WorkspaceCoverageProjectionAttempt { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + attempt_id: String, + #[cultcache(key = 2)] + claim_id: String, + #[cultcache(key = 3)] + claim_epoch: u64, + #[cultcache(key = 4)] + plan_id: String, + #[cultcache(key = 5)] + status: String, + #[cultcache(key = 6)] + started_at: String, + #[cultcache(key = 7)] + completed_at: Option, + #[cultcache(key = 8)] + error: Option, +} + +#[derive(Clone, Debug)] +pub(crate) struct WorkspaceCoverageAcquisition { + pub body_store: PathBuf, + pub obligation: WorkspaceCoverageObligation, + pub plan: WorkspaceCoverageProjectionPlan, + pub claim: WorkspaceCoverageProjectionClaim, + pub attempt: WorkspaceCoverageProjectionAttempt, +} + +pub(crate) fn acquire_workspace_coverage_projection( + runtime_store: &Path, + basis: &RepositoryBodyObservationBasis, + embedding_provider_id: &str, + embedding_model: &str, + vector_dimensions: u32, +) -> Result { + let policy = WorkspaceCoveragePolicy::bounded_regular_files_v0(MAXIMUM_FILE_BYTES)?; + let raw_obligation = derive_workspace_coverage_obligation(runtime_store, basis, &policy)?; + let mut verified_text = Vec::new(); + let mut non_utf8_paths = Vec::new(); + for entry in &raw_obligation.classifications { + if !matches!( + entry.disposition, + crate::WorkspaceCoverageDisposition::IncludeRegularFile + ) { + continue; + } + let verified = read_verified_repository_body_bytes(runtime_store, basis, &entry.path)?; + if verified.relative_path != entry.path || verified.raw_sha256 != entry.raw_sha256 { + bail!("verified Body bytes lost their manifest identity"); + } + if std::str::from_utf8(&verified.bytes).is_ok() { + verified_text.push(verified); + } else { + non_utf8_paths.push(entry.path.clone()); + } + } + let obligation = refine_workspace_coverage_obligation_utf8(&raw_obligation, &non_utf8_paths)?; + let mut descriptors = Vec::new(); + for verified in verified_text { + descriptors.extend(chunk_descriptors( + &verified.relative_path, + &verified.raw_sha256, + &verified.bytes, + )?); + } + let plan = derive_workspace_coverage_projection_plan( + &obligation, + PROJECTION_SCHEMA, + CHUNKER_ID, + embedding_provider_id, + embedding_model, + vector_dimensions, + descriptors, + )?; + let route = runtime_repository_body_store_binding(runtime_store)? + .ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?; + let body_store = PathBuf::from(route.body_store_path); + let backing = SingleFileMessagePackBackingStore::new(&body_store); + let opening = backing.pull_all()?; + let authority = exact_body_authority(&opening, basis)?; + let existing_claim = find(&opening, CLAIM_TYPE, CLAIM_KEY); + let claim_epoch = match existing_claim { + Some(envelope) => { + let prior: WorkspaceCoverageProjectionClaim = decode(envelope)?; + if prior.status == "running" { + bail!("workspace coverage projection already has a running claim"); + } + prior + .claim_epoch + .checked_add(1) + .ok_or_else(|| anyhow!("claim epoch exhausted"))? + } + None => 1, + }; + let claim_id = uuid::Uuid::new_v4().to_string(); + let attempt_id = uuid::Uuid::new_v4().to_string(); + let claim = WorkspaceCoverageProjectionClaim { + schema_version: CLAIM_SCHEMA.into(), + claim_id: claim_id.clone(), + claim_epoch, + plan_id: plan.plan_id.clone(), + attempt_id: attempt_id.clone(), + obligation_id: obligation.obligation_id.clone(), + body_observation_id: basis.observation_id.clone(), + body_generation: basis.generation, + manifest_root_sha256: basis.manifest_root_sha256.clone(), + status: "running".into(), + }; + let attempt = WorkspaceCoverageProjectionAttempt { + schema_version: ATTEMPT_SCHEMA.into(), + attempt_id: attempt_id.clone(), + claim_id, + claim_epoch, + plan_id: plan.plan_id.clone(), + status: "running".into(), + started_at: chrono::Utc::now().to_rfc3339(), + completed_at: None, + error: None, + }; + let mut expected = authority.clone(); + if let Some(existing) = existing_claim { + expected.push(existing.clone()); + } + let mut replacements = authority; + let obligation_env = envelope( + "gamecult.epiphany.workspace_coverage_obligation", + &obligation.obligation_id, + &obligation, + )?; + let plan_env = envelope( + "gamecult.epiphany.workspace_coverage_projection_plan", + &plan.plan_id, + &plan, + )?; + preserve_or_insert_immutable(&opening, &mut expected, &mut replacements, obligation_env)?; + preserve_or_insert_immutable(&opening, &mut expected, &mut replacements, plan_env)?; + replacements.push(envelope(CLAIM_TYPE, CLAIM_KEY, &claim)?); + replacements.push(envelope(ATTEMPT_TYPE, &attempt_id, &attempt)?); + if !backing.compare_and_swap_batch(&expected, replacements)? { + bail!("workspace coverage acquisition lost exact Body/claim CAS"); + } + Ok(WorkspaceCoverageAcquisition { + body_store, + obligation, + plan, + claim, + attempt, + }) +} + +pub(crate) fn fail_workspace_coverage_projection( + acquisition: &WorkspaceCoverageAcquisition, + error: &str, +) -> Result<()> { + if error.trim().is_empty() { + bail!("projection failure requires an error"); + } + let backing = SingleFileMessagePackBackingStore::new(&acquisition.body_store); + let opening = backing.pull_all()?; + 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"))?; + let claim: WorkspaceCoverageProjectionClaim = decode(claim_env)?; + let attempt: WorkspaceCoverageProjectionAttempt = decode(attempt_env)?; + 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"))?; + if decode::(obligation_env)? != acquisition.obligation + || decode::(plan_env)? != acquisition.plan + { + bail!("projection failure refuses substituted obligation or plan"); + } + if claim != acquisition.claim || attempt != acquisition.attempt || claim.status != "running" { + bail!("projection failure refuses substituted claim or attempt"); + } + let mut failed_claim = claim.clone(); + failed_claim.status = "failed".into(); + let mut failed_attempt = attempt.clone(); + failed_attempt.status = "failed".into(); + failed_attempt.completed_at = Some(chrono::Utc::now().to_rfc3339()); + failed_attempt.error = Some(error.into()); + let expected = vec![ + obligation_env.clone(), + plan_env.clone(), + claim_env.clone(), + attempt_env.clone(), + ]; + let replacements = vec![ + obligation_env.clone(), + plan_env.clone(), + envelope(CLAIM_TYPE, CLAIM_KEY, &failed_claim)?, + envelope(ATTEMPT_TYPE, &failed_attempt.attempt_id, &failed_attempt)?, + ]; + if !backing.compare_and_swap_batch(&expected, replacements)? { + bail!("projection failure lost exact claim/attempt CAS"); + } + Ok(()) +} + +fn preserve_or_insert_immutable( + opening: &[CultCacheEnvelope], + expected: &mut Vec, + replacements: &mut Vec, + proposed: CultCacheEnvelope, +) -> Result<()> { + if let Some(existing) = find(opening, &proposed.r#type, &proposed.key) { + let mut comparable = proposed; + comparable.stored_at = existing.stored_at.clone(); + if &comparable != existing { + bail!("immutable workspace coverage document identity collision"); + } + expected.push(existing.clone()); + replacements.push(existing.clone()); + } else { + replacements.push(proposed); + } + Ok(()) +} + +fn chunk_descriptors( + path: &str, + raw_sha256: &str, + bytes: &[u8], +) -> Result> { + let text = std::str::from_utf8(bytes) + .map_err(|_| anyhow!("named text chunker refuses non-UTF-8 bytes"))?; + let mut line_starts = vec![0usize]; + for (index, byte) in text.bytes().enumerate() { + if byte == b'\n' && index + 1 < bytes.len() { + line_starts.push(index + 1); + } + } + let mut result = Vec::new(); + let mut start_line = 0usize; + let mut chunk_index = 0u32; + while start_line < line_starts.len() { + let end_line = (start_line + CHUNK_LINES).min(line_starts.len()); + let start = line_starts[start_line]; + let end = if end_line == line_starts.len() { + bytes.len() + } else { + line_starts[end_line] + }; + result.push(WorkspaceCoverageChunkDescriptor { + body_path: path.into(), + source_raw_sha256: raw_sha256.into(), + source_raw_byte_length: bytes.len() as u64, + chunk_index, + byte_start: start as u64, + byte_end: end as u64, + chunk_sha256: format!("{:x}", Sha256::digest(&bytes[start..end])), + }); + if end_line == line_starts.len() { + break; + } + start_line = end_line - CHUNK_OVERLAP_LINES; + chunk_index = chunk_index + .checked_add(1) + .ok_or_else(|| anyhow!("chunk index exhausted"))?; + } + Ok(result) +} + +fn exact_body_authority( + opening: &[CultCacheEnvelope], + basis: &RepositoryBodyObservationBasis, +) -> 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 != basis.workspace_id + || head.generation != basis.generation + || head.observation_id != basis.observation_id + || head.manifest_root_sha256 != basis.manifest_root_sha256 + { + bail!("workspace coverage acquisition requires the exact current Body head"); + } + [ + (BODY_BINDING_TYPE, BODY_BINDING_KEY), + (BODY_HEAD_TYPE, BODY_HEAD_KEY), + (BODY_OBSERVATION_TYPE, basis.observation_id.as_str()), + (BODY_MANIFEST_TYPE, basis.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 find<'a>( + entries: &'a [CultCacheEnvelope], + ty: &str, + key: &str, +) -> Option<&'a CultCacheEnvelope> { + entries + .iter() + .find(|entry| entry.r#type == ty && entry.key == key) +} +fn decode(value: &CultCacheEnvelope) -> Result { + Ok(rmp_serde::from_slice(&value.payload)?) +} +fn envelope(ty: &str, key: &str, value: &T) -> Result { + Ok(CultCacheEnvelope { + key: key.into(), + r#type: ty.into(), + payload: rmp_serde::to_vec(value)?, + stored_at: chrono::Utc::now().to_rfc3339(), + schema_id: Some(ty.into()), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + #[test] + fn named_chunker_preserves_utf8_boundaries_and_eight_line_overlap() -> Result<()> { + let text = (0..105) + .map(|index| format!("line {index} λ\n")) + .collect::(); + let chunks = chunk_descriptors("a", &"11".repeat(32), text.as_bytes())?; + assert_eq!(chunks.len(), 2); + let overlap = &text.as_bytes()[chunks[1].byte_start as usize..chunks[0].byte_end as usize]; + assert_eq!(overlap.iter().filter(|byte| **byte == b'\n').count(), 8); + assert!( + std::str::from_utf8( + &text.as_bytes()[chunks[0].byte_start as usize..chunks[0].byte_end as usize] + ) + .is_ok() + ); + assert!( + std::str::from_utf8( + &text.as_bytes()[chunks[1].byte_start as usize..chunks[1].byte_end as usize] + ) + .is_ok() + ); + assert_eq!(chunks[0].chunk_index, 0); + assert_eq!(chunks[1].chunk_index, 1); + assert!(chunk_descriptors("binary", &"22".repeat(32), &[0xff, 0xfe]).is_err()); + Ok(()) + } + + fn git(repo: &Path, args: &[&str]) -> Result<()> { + let output = Command::new("git") + .args(["-C", repo.to_str().unwrap()]) + .args(args) + .output()?; + if !output.status.success() { + bail!("git failed: {}", String::from_utf8_lossy(&output.stderr)); + } + Ok(()) + } + + #[test] + fn acquisition_is_exclusive_and_failure_can_terminalize_after_body_advance() -> Result<()> { + let repo = tempfile::tempdir()?; + let state = tempfile::tempdir()?; + git(repo.path(), &["init"])?; + std::fs::write(repo.path().join("source.rs"), "fn one() {}")?; + std::fs::write(repo.path().join("binary.dat"), [0xff, 0xfe, 0xfd])?; + 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: "projector-runtime".into(), + display_name: "projector test".into(), + created_at: "2026-07-15T00:00:00Z".into(), + }, + )?; + crate::ensure_agent_memory_swarm_identity(&agents, "projector-swarm")?; + crate::bind_runtime_to_agent_memory_swarm(&runtime, &agents, "2026-07-15T00:00:01Z")?; + crate::bind_repository_body(repo.path(), &body, &runtime, "projector-workspace")?; + let basis = crate::observe_runtime_repository_body_basis(&runtime)?; + let first = + acquire_workspace_coverage_projection(&runtime, &basis, "provider", "model", 3)?; + assert!(first.obligation.classifications.iter().any(|entry| { + entry.path == "binary.dat" + && entry.disposition + == crate::WorkspaceCoverageDisposition::ExcludeNonUtf8RegularFile + })); + assert_eq!(first.obligation.included_entry_count, 1); + assert!( + acquire_workspace_coverage_projection(&runtime, &basis, "provider", "model", 3) + .is_err() + ); + fail_workspace_coverage_projection(&first, "expected test failure")?; + let second = + acquire_workspace_coverage_projection(&runtime, &basis, "provider", "model", 3)?; + assert_eq!(second.claim.claim_epoch, first.claim.claim_epoch + 1); + std::fs::write(repo.path().join("source.rs"), "fn two() {}")?; + let advanced = crate::observe_runtime_repository_body_basis(&runtime)?; + assert!(advanced.generation > basis.generation); + fail_workspace_coverage_projection(&second, "Body advanced during projection")?; + let entries = SingleFileMessagePackBackingStore::new(&second.body_store).pull_all()?; + assert!( + find( + &entries, + "gamecult.epiphany.workspace_coverage_receipt", + "current" + ) + .is_none() + ); + assert!( + find( + &entries, + "gamecult.epiphany.workspace_coverage_head", + "current" + ) + .is_none() + ); + Ok(()) + } +} diff --git a/epiphany-core/src/workspace_retrieval_coverage.rs b/epiphany-core/src/workspace_retrieval_coverage.rs index 4a7370df..d5ab31a3 100644 --- a/epiphany-core/src/workspace_retrieval_coverage.rs +++ b/epiphany-core/src/workspace_retrieval_coverage.rs @@ -26,6 +26,8 @@ pub enum WorkspaceCoverageDisposition { ExcludeGitlink, ExcludeSymlink, ExcludeUnsupportedKind, + ExcludeEmptyRegularFile, + ExcludeNonUtf8RegularFile, ExcludeOversize, } @@ -62,7 +64,7 @@ pub struct WorkspaceCoverageClassification { type = "gamecult.epiphany.workspace_coverage_obligation", schema = "WorkspaceCoverageObligation" )] -pub struct WorkspaceCoverageObligation { +pub(crate) struct WorkspaceCoverageObligation { #[cultcache(key = 0)] pub schema_version: String, #[cultcache(key = 1)] @@ -93,12 +95,59 @@ pub struct WorkspaceCoverageObligation { pub included_entry_count: u64, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceCoverageChunkDescriptor { + pub body_path: String, + pub source_raw_sha256: String, + pub source_raw_byte_length: u64, + pub chunk_index: u32, + pub byte_start: u64, + pub byte_end: u64, + pub chunk_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceCoveragePlannedPoint { + pub point_id: String, + pub body_path: String, + pub source_raw_sha256: String, + pub source_raw_byte_length: u64, + pub chunk_index: u32, + pub byte_start: u64, + pub byte_end: u64, + pub chunk_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceCoveragePointPayload { + pub obligation_id: String, + pub projection_schema_version: String, + pub chunker_id: String, + pub body_path: String, + pub source_raw_sha256: String, + pub source_raw_byte_length: u64, + pub chunk_index: u32, + pub byte_start: u64, + pub byte_end: u64, + pub chunk_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceCoveragePointBinding { + pub point_id: String, + pub payload_sha256: String, +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "gamecult.epiphany.workspace_coverage_projection_plan", schema = "WorkspaceCoverageProjectionPlan" )] -pub struct WorkspaceCoverageProjectionPlan { +pub(crate) struct WorkspaceCoverageProjectionPlan { #[cultcache(key = 0)] pub schema_version: String, #[cultcache(key = 1)] @@ -110,19 +159,21 @@ pub struct WorkspaceCoverageProjectionPlan { #[cultcache(key = 4)] pub chunker_id: String, #[cultcache(key = 5)] - pub collection_name: String, - #[cultcache(key = 6)] pub embedding_provider_id: String, - #[cultcache(key = 7)] + #[cultcache(key = 6)] pub embedding_model: String, - #[cultcache(key = 8)] + #[cultcache(key = 7)] pub vector_dimensions: u32, + #[cultcache(key = 8)] + pub planned_points: Vec, #[cultcache(key = 9)] - pub expected_point_ids: Vec, - #[cultcache(key = 10)] pub expected_point_count: u64, - #[cultcache(key = 11)] + #[cultcache(key = 10)] pub expected_point_set_sha256: String, + #[cultcache(key = 11)] + pub point_bindings: Vec, + #[cultcache(key = 12)] + pub point_binding_set_sha256: String, } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] @@ -130,7 +181,7 @@ pub struct WorkspaceCoverageProjectionPlan { type = "gamecult.epiphany.workspace_coverage_receipt", schema = "WorkspaceCoverageReceipt" )] -pub struct WorkspaceCoverageReceipt { +pub(crate) struct WorkspaceCoverageReceipt { #[cultcache(key = 0)] pub schema_version: String, #[cultcache(key = 1)] @@ -155,6 +206,12 @@ pub struct WorkspaceCoverageReceipt { pub observed_at: String, #[cultcache(key = 11)] pub observation_method: String, + #[cultcache(key = 12)] + pub observed_point_binding_set_sha256: String, + #[cultcache(key = 13)] + pub claim_id: String, + #[cultcache(key = 14)] + pub claim_epoch: u64, } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] @@ -162,7 +219,7 @@ pub struct WorkspaceCoverageReceipt { type = "gamecult.epiphany.workspace_coverage_head", schema = "WorkspaceCoverageHead" )] -pub struct WorkspaceCoverageHead { +pub(crate) struct WorkspaceCoverageHead { #[cultcache(key = 0)] pub schema_version: String, #[cultcache(key = 1)] @@ -173,9 +230,19 @@ pub struct WorkspaceCoverageHead { pub plan_id: String, #[cultcache(key = 4)] pub receipt_id: String, + #[cultcache(key = 5)] + pub body_observation_id: String, + #[cultcache(key = 6)] + pub body_generation: u64, + #[cultcache(key = 7)] + pub manifest_root_sha256: String, + #[cultcache(key = 8)] + pub claim_id: String, + #[cultcache(key = 9)] + pub claim_epoch: u64, } -pub fn derive_workspace_coverage_obligation( +pub(crate) fn derive_workspace_coverage_obligation( runtime_store: &Path, basis: &RepositoryBodyObservationBasis, policy: &WorkspaceCoveragePolicy, @@ -248,15 +315,53 @@ fn derive_workspace_coverage_obligation_from_authenticated_manifest( }) } +pub(crate) fn refine_workspace_coverage_obligation_utf8( + obligation: &WorkspaceCoverageObligation, + non_utf8_paths: &[String], +) -> Result { + if !non_utf8_paths.windows(2).all(|pair| pair[0] < pair[1]) { + bail!("non-UTF-8 Body paths must be unique and canonically ordered"); + } + let mut refined = obligation.clone(); + for path in non_utf8_paths { + let classification = refined + .classifications + .iter_mut() + .find(|entry| &entry.path == path) + .ok_or_else(|| anyhow!("non-UTF-8 path is absent from Body obligation"))?; + if classification.disposition != WorkspaceCoverageDisposition::IncludeRegularFile { + bail!("non-UTF-8 refinement may only demote an included regular file"); + } + classification.disposition = WorkspaceCoverageDisposition::ExcludeNonUtf8RegularFile; + } + refined.included_entry_count = refined + .classifications + .iter() + .filter(|entry| entry.disposition == WorkspaceCoverageDisposition::IncludeRegularFile) + .count() as u64; + refined.classification_set_sha256 = digest(&refined.classifications)?; + refined.obligation_id = format!( + "workspace-coverage:{}", + digest(&( + &refined.body_binding_sha256, + &refined.body_observation_id, + &refined.manifest_root_sha256, + &refined.policy_sha256, + &refined.classification_set_sha256, + ))? + ); + Ok(refined) +} + #[allow(clippy::too_many_arguments)] -pub fn derive_workspace_coverage_projection_plan( +pub(crate) fn derive_workspace_coverage_projection_plan( obligation: &WorkspaceCoverageObligation, projection_schema_version: &str, chunker_id: &str, embedding_provider_id: &str, embedding_model: &str, vector_dimensions: u32, - expected_point_ids: Vec, + chunk_descriptors: Vec, ) -> Result { if obligation.schema_version != WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION || projection_schema_version.trim().is_empty() @@ -264,50 +369,120 @@ pub fn derive_workspace_coverage_projection_plan( || embedding_provider_id.trim().is_empty() || embedding_model.trim().is_empty() || vector_dimensions == 0 - || !strictly_ordered_nonempty(&expected_point_ids) - || (obligation.included_entry_count == 0) != expected_point_ids.is_empty() + || (obligation.included_entry_count == 0) != chunk_descriptors.is_empty() { bail!("workspace coverage projection plan is incomplete or noncanonical"); } - let expected_point_count = expected_point_ids.len() as u64; - let expected_point_set_sha256 = digest(&expected_point_ids)?; - let collection_namespace_hash = digest(&( - &obligation.obligation_id, - projection_schema_version, - chunker_id, - embedding_provider_id, - embedding_model, - vector_dimensions, - ))?; - let collection_name = format!("epiphany_workspace_{}", &collection_namespace_hash[..40]); + let included = obligation + .classifications + .iter() + .filter(|entry| entry.disposition == WorkspaceCoverageDisposition::IncludeRegularFile) + .map(|entry| (entry.path.as_str(), entry)) + .collect::>(); + let mut planned_points = Vec::with_capacity(chunk_descriptors.len()); + let mut prior_descriptor: Option<(String, u32)> = None; + for descriptor in chunk_descriptors { + let Some(source) = included.get(descriptor.body_path.as_str()) else { + bail!("workspace coverage chunk does not name an included Body entry"); + }; + let valid_range = descriptor.byte_start < descriptor.byte_end + && descriptor.byte_end <= descriptor.source_raw_byte_length; + if descriptor.source_raw_sha256 != source.raw_sha256 + || descriptor.source_raw_byte_length != source.raw_byte_length + || !sha256_hex(&descriptor.source_raw_sha256) + || !sha256_hex(&descriptor.chunk_sha256) + || !valid_range + || (prior_descriptor.is_none() && descriptor.chunk_index != 0) + || prior_descriptor.as_ref().is_some_and(|prior| { + if prior.0 == descriptor.body_path { + prior.1.checked_add(1) != Some(descriptor.chunk_index) + } else { + descriptor.body_path <= prior.0 || descriptor.chunk_index != 0 + } + }) + { + bail!("workspace coverage chunk descriptor disagrees with Body or canonical order"); + } + prior_descriptor = Some((descriptor.body_path.clone(), descriptor.chunk_index)); + let point_id = uuid::Uuid::new_v5( + &uuid::Uuid::NAMESPACE_URL, + rmp_serde::to_vec_named(&( + &obligation.obligation_id, + projection_schema_version, + chunker_id, + &descriptor, + ))? + .as_slice(), + ) + .to_string(); + planned_points.push(WorkspaceCoveragePlannedPoint { + point_id, + body_path: descriptor.body_path, + source_raw_sha256: descriptor.source_raw_sha256, + source_raw_byte_length: descriptor.source_raw_byte_length, + chunk_index: descriptor.chunk_index, + byte_start: descriptor.byte_start, + byte_end: descriptor.byte_end, + chunk_sha256: descriptor.chunk_sha256, + }); + } + if included.values().any(|entry| { + !planned_points + .iter() + .any(|point| point.body_path == entry.path) + }) { + bail!("workspace coverage plan omits an included Body entry"); + } + let mut point_ids = planned_points + .iter() + .map(|point| point.point_id.clone()) + .collect::>(); + point_ids.sort(); + let mut point_bindings = planned_points + .iter() + .map(|point| { + let payload = point_payload(obligation, projection_schema_version, chunker_id, point); + Ok(WorkspaceCoveragePointBinding { + point_id: point.point_id.clone(), + payload_sha256: digest(&payload)?, + }) + }) + .collect::>>()?; + point_bindings.sort_by(|left, right| left.point_id.cmp(&right.point_id)); + let expected_point_count = point_ids.len() as u64; + let expected_point_set_sha256 = digest(&point_ids)?; + let point_binding_set_sha256 = digest(&point_bindings)?; let identity = ( &obligation.obligation_id, projection_schema_version, chunker_id, - &collection_name, embedding_provider_id, embedding_model, vector_dimensions, - &expected_point_ids, + &planned_points, &expected_point_set_sha256, + &point_bindings, + &point_binding_set_sha256, ); + let plan_id = format!("workspace-coverage-plan:{}", digest(&identity)?); Ok(WorkspaceCoverageProjectionPlan { schema_version: WORKSPACE_COVERAGE_PROJECTION_PLAN_SCHEMA_VERSION.into(), - plan_id: format!("workspace-coverage-plan:{}", digest(&identity)?), + plan_id, obligation_id: obligation.obligation_id.clone(), projection_schema_version: projection_schema_version.into(), chunker_id: chunker_id.into(), - collection_name, embedding_provider_id: embedding_provider_id.into(), embedding_model: embedding_model.into(), vector_dimensions, - expected_point_ids, + planned_points, expected_point_count, expected_point_set_sha256, + point_bindings, + point_binding_set_sha256, }) } -pub fn validate_workspace_coverage_projection_plan( +pub(crate) fn validate_workspace_coverage_projection_plan( obligation: &WorkspaceCoverageObligation, plan: &WorkspaceCoverageProjectionPlan, ) -> Result<()> { @@ -318,7 +493,18 @@ pub fn validate_workspace_coverage_projection_plan( &plan.embedding_provider_id, &plan.embedding_model, plan.vector_dimensions, - plan.expected_point_ids.clone(), + plan.planned_points + .iter() + .map(|point| WorkspaceCoverageChunkDescriptor { + 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(), + }) + .collect(), )?; if *plan != expected { bail!("workspace coverage projection plan identity or derived fields were altered"); @@ -326,34 +512,40 @@ pub fn validate_workspace_coverage_projection_plan( Ok(()) } -pub fn validate_workspace_coverage_receipt( +pub(crate) fn validate_workspace_coverage_receipt( obligation: &WorkspaceCoverageObligation, plan: &WorkspaceCoverageProjectionPlan, receipt: &WorkspaceCoverageReceipt, ) -> Result<()> { validate_workspace_coverage_projection_plan(obligation, plan)?; + let expected_collection = workspace_coverage_execution_collection( + &plan.plan_id, + &receipt.claim_id, + receipt.claim_epoch, + )?; if receipt.schema_version != WORKSPACE_COVERAGE_RECEIPT_SCHEMA_VERSION || receipt.obligation_id != obligation.obligation_id || receipt.plan_id != plan.plan_id || receipt.receipt_id.trim().is_empty() - || receipt.collection_name != plan.collection_name + || receipt.collection_name != expected_collection || receipt.embedding_provider_id != plan.embedding_provider_id || receipt.embedding_model != plan.embedding_model || receipt.vector_dimensions != plan.vector_dimensions || receipt.observed_at.trim().is_empty() - || receipt.observation_method != "qdrant_scroll_exact_point_ids" + || receipt.observation_method != "qdrant_scroll_exact_point_bindings" { bail!("workspace coverage receipt lacks exact observed-index authority"); } if receipt.observed_point_count != plan.expected_point_count || receipt.observed_point_set_sha256 != plan.expected_point_set_sha256 + || receipt.observed_point_binding_set_sha256 != plan.point_binding_set_sha256 { bail!("workspace coverage receipt does not prove the exact expected point set"); } Ok(()) } -pub fn validate_workspace_coverage_head( +pub(crate) fn validate_workspace_coverage_head( obligation: &WorkspaceCoverageObligation, plan: &WorkspaceCoverageProjectionPlan, receipt: &WorkspaceCoverageReceipt, @@ -367,15 +559,54 @@ pub fn validate_workspace_coverage_head( || head.receipt_id != receipt.receipt_id || receipt.obligation_id != obligation.obligation_id || receipt.plan_id != plan.plan_id + || head.body_observation_id != obligation.body_observation_id + || head.body_generation != obligation.body_generation + || head.manifest_root_sha256 != obligation.manifest_root_sha256 + || head.claim_id != receipt.claim_id + || head.claim_epoch != receipt.claim_epoch { bail!("workspace coverage head does not join one obligation to its exact receipt"); } Ok(()) } -fn strictly_ordered_nonempty(values: &[String]) -> bool { - values.iter().all(|value| !value.trim().is_empty()) - && values.windows(2).all(|pair| pair[0] < pair[1]) +pub fn workspace_coverage_execution_collection( + plan_id: &str, + claim_id: &str, + claim_epoch: u64, +) -> Result { + if plan_id.trim().is_empty() || uuid::Uuid::parse_str(claim_id).is_err() || claim_epoch == 0 { + bail!("workspace coverage execution collection requires plan and fenced UUID claim"); + } + let namespace = digest(&(plan_id, claim_id, claim_epoch))?; + Ok(format!("epiphany_workspace_{}", &namespace[..40])) +} + +fn point_payload( + obligation: &WorkspaceCoverageObligation, + projection_schema_version: &str, + chunker_id: &str, + point: &WorkspaceCoveragePlannedPoint, +) -> WorkspaceCoveragePointPayload { + WorkspaceCoveragePointPayload { + obligation_id: obligation.obligation_id.clone(), + projection_schema_version: projection_schema_version.into(), + chunker_id: chunker_id.into(), + 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 sha256_hex(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) } fn classify( @@ -385,6 +616,9 @@ fn classify( let disposition = match entry.kind.as_str() { "gitlink_nonrecursive" => WorkspaceCoverageDisposition::ExcludeGitlink, "symlink_target" => WorkspaceCoverageDisposition::ExcludeSymlink, + "regular" if entry.raw_byte_length == 0 => { + WorkspaceCoverageDisposition::ExcludeEmptyRegularFile + } "regular" if entry.raw_byte_length > policy.maximum_file_bytes => { WorkspaceCoverageDisposition::ExcludeOversize } @@ -445,6 +679,7 @@ mod tests { workspace_id: "workspace-1".into(), scope: "git_worktree".into(), entries: vec![ + entry("a-empty", "regular", 0), entry("a.rs", "regular", 12), entry("b.bin", "regular", 101), entry("c-link", "symlink_target", 3), @@ -459,7 +694,11 @@ mod tests { assert_eq!(obligation.classifications.len(), manifest.entries.len()); assert_eq!(obligation.included_entry_count, 1); assert_eq!( - obligation.classifications[1].disposition, + obligation.classifications[0].disposition, + WorkspaceCoverageDisposition::ExcludeEmptyRegularFile + ); + assert_eq!( + obligation.classifications[2].disposition, WorkspaceCoverageDisposition::ExcludeOversize ); Ok(()) @@ -496,11 +735,10 @@ mod tests { Ok(()) } - #[test] - fn receipt_cannot_convert_counts_or_unobserved_points_into_coverage() -> Result<()> { - let obligation = WorkspaceCoverageObligation { + fn coverage_obligation(id: &str) -> WorkspaceCoverageObligation { + WorkspaceCoverageObligation { schema_version: WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION.into(), - obligation_id: "obligation-1".into(), + obligation_id: id.into(), workspace_id: "workspace-1".into(), swarm_id: "swarm-1".into(), runtime_id: "runtime-1".into(), @@ -511,10 +749,54 @@ mod tests { policy_id: "bounded_regular_files_v0".into(), policy_sha256: "policy".into(), classification_set_sha256: "classes".into(), - classifications: vec![], - included_entry_count: 2, - }; - let points = vec!["point-a".to_string(), "point-b".to_string()]; + classifications: vec![WorkspaceCoverageClassification { + path: "src/lib.rs".into(), + raw_sha256: "11".repeat(32), + raw_byte_length: 10, + disposition: WorkspaceCoverageDisposition::IncludeRegularFile, + }], + included_entry_count: 1, + } + } + + fn chunks() -> Vec { + vec![ + WorkspaceCoverageChunkDescriptor { + body_path: "src/lib.rs".into(), + source_raw_sha256: "11".repeat(32), + source_raw_byte_length: 10, + chunk_index: 0, + byte_start: 0, + byte_end: 5, + chunk_sha256: "22".repeat(32), + }, + WorkspaceCoverageChunkDescriptor { + body_path: "src/lib.rs".into(), + source_raw_sha256: "11".repeat(32), + source_raw_byte_length: 10, + chunk_index: 1, + byte_start: 3, + byte_end: 10, + chunk_sha256: "33".repeat(32), + }, + ] + } + + fn plan(obligation: &WorkspaceCoverageObligation) -> Result { + derive_workspace_coverage_projection_plan( + obligation, + "projection-v0", + "chunker-v0", + "provider", + "model", + 3, + chunks(), + ) + } + + #[test] + fn receipt_and_head_cannot_substitute_payload_or_claim_authority() -> Result<()> { + let obligation = coverage_obligation("obligation-1"); let plan = derive_workspace_coverage_projection_plan( &obligation, "projection-v0", @@ -522,24 +804,31 @@ mod tests { "provider", "model", 3, - points.clone(), + chunks(), )?; + let claim_id = uuid::Uuid::new_v4().to_string(); + let claim_epoch = 7; let mut receipt = WorkspaceCoverageReceipt { schema_version: WORKSPACE_COVERAGE_RECEIPT_SCHEMA_VERSION.into(), receipt_id: "receipt-1".into(), obligation_id: obligation.obligation_id.clone(), plan_id: plan.plan_id.clone(), - collection_name: plan.collection_name.clone(), + collection_name: workspace_coverage_execution_collection( + &plan.plan_id, + &claim_id, + claim_epoch, + )?, embedding_provider_id: "provider".into(), embedding_model: "model".into(), vector_dimensions: 3, - observed_point_count: 2, - observed_point_set_sha256: digest(&points)?, + observed_point_count: plan.expected_point_count, + observed_point_set_sha256: plan.expected_point_set_sha256.clone(), observed_at: "now".into(), - observation_method: "claimed_upsert_count".into(), + observation_method: "qdrant_scroll_exact_point_bindings".into(), + observed_point_binding_set_sha256: plan.point_binding_set_sha256.clone(), + claim_id: claim_id.clone(), + claim_epoch, }; - assert!(validate_workspace_coverage_receipt(&obligation, &plan, &receipt).is_err()); - receipt.observation_method = "qdrant_scroll_exact_point_ids".into(); assert!(validate_workspace_coverage_receipt(&obligation, &plan, &receipt).is_ok()); let mut head = WorkspaceCoverageHead { schema_version: WORKSPACE_COVERAGE_HEAD_SCHEMA_VERSION.into(), @@ -547,36 +836,34 @@ mod tests { obligation_id: obligation.obligation_id.clone(), plan_id: plan.plan_id.clone(), receipt_id: receipt.receipt_id.clone(), + body_observation_id: obligation.body_observation_id.clone(), + body_generation: obligation.body_generation, + manifest_root_sha256: obligation.manifest_root_sha256.clone(), + claim_id, + claim_epoch, }; assert!(validate_workspace_coverage_head(&obligation, &plan, &receipt, &head).is_ok()); - head.receipt_id = "some-other-receipt".into(); + receipt.observed_point_binding_set_sha256 = "44".repeat(32); + assert!(validate_workspace_coverage_receipt(&obligation, &plan, &receipt).is_err()); + receipt.observed_point_binding_set_sha256 = plan.point_binding_set_sha256.clone(); + receipt.claim_epoch += 1; + assert!(validate_workspace_coverage_receipt(&obligation, &plan, &receipt).is_err()); + receipt.claim_epoch = claim_epoch; + receipt.claim_id = "not-a-uuid".into(); + assert!(validate_workspace_coverage_receipt(&obligation, &plan, &receipt).is_err()); + receipt.claim_id = head.claim_id.clone(); + head.claim_id = uuid::Uuid::new_v4().to_string(); assert!(validate_workspace_coverage_head(&obligation, &plan, &receipt, &head).is_err()); - head.receipt_id = receipt.receipt_id.clone(); receipt.observation_method = "claimed_upsert_count".into(); assert!(validate_workspace_coverage_head(&obligation, &plan, &receipt, &head).is_err()); - receipt.observed_point_count = 1; - assert!(validate_workspace_coverage_receipt(&obligation, &plan, &receipt).is_err()); Ok(()) } #[test] fn projection_plan_seals_point_set_and_rejects_cross_obligation_use() -> Result<()> { - let mut obligation = WorkspaceCoverageObligation { - schema_version: WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION.into(), - obligation_id: "obligation-a".into(), - workspace_id: "workspace-1".into(), - swarm_id: "swarm-1".into(), - runtime_id: "runtime-1".into(), - body_binding_sha256: "binding".into(), - body_observation_id: "workspace-1:1".into(), - body_generation: 1, - manifest_root_sha256: "manifest".into(), - policy_id: "bounded_regular_files_v0".into(), - policy_sha256: "policy".into(), - classification_set_sha256: "classes".into(), - classifications: vec![], - included_entry_count: 1, - }; + let mut obligation = coverage_obligation("obligation-a"); + let mut duplicate = chunks(); + duplicate[1].chunk_index = 0; assert!( derive_workspace_coverage_projection_plan( &obligation, @@ -585,10 +872,12 @@ mod tests { "provider", "model", 3, - vec!["duplicate".into(), "duplicate".into()] + duplicate ) .is_err() ); + let mut invalid = chunks(); + invalid[0].byte_end = 11; assert!( derive_workspace_coverage_projection_plan( &obligation, @@ -597,20 +886,13 @@ mod tests { "provider", "model", 3, - vec!["z".into(), "a".into()] + invalid ) .is_err() ); - let mut plan = derive_workspace_coverage_projection_plan( - &obligation, - "projection", - "chunker", - "provider", - "model", - 3, - vec!["a".into(), "z".into()], - )?; - plan.expected_point_ids[1] = "y".into(); + let mut plan = plan(&obligation)?; + assert!(uuid::Uuid::parse_str(&plan.planned_points[0].point_id).is_ok()); + plan.planned_points[0].chunk_sha256 = "44".repeat(32); assert!(validate_workspace_coverage_projection_plan(&obligation, &plan).is_err()); obligation.obligation_id = "obligation-b".into(); assert!(validate_workspace_coverage_projection_plan(&obligation, &plan).is_err()); @@ -618,62 +900,17 @@ mod tests { } #[test] - fn collection_namespace_is_derived_from_body_and_embedding_authority() -> Result<()> { - let obligation = WorkspaceCoverageObligation { - schema_version: WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION.into(), - obligation_id: "body-policy-epoch-a".into(), - workspace_id: "workspace-1".into(), - swarm_id: "swarm-1".into(), - runtime_id: "runtime-1".into(), - body_binding_sha256: "binding".into(), - body_observation_id: "workspace-1:1".into(), - body_generation: 1, - manifest_root_sha256: "manifest".into(), - policy_id: "bounded_regular_files_v0".into(), - policy_sha256: "policy".into(), - classification_set_sha256: "classes".into(), - classifications: vec![], - included_entry_count: 1, - }; - let point_ids = vec!["point".into()]; - let first = derive_workspace_coverage_projection_plan( - &obligation, - "projection", - "chunker", - "provider", - "model", - 3, - point_ids.clone(), - )?; - let mut other_obligation = obligation.clone(); - other_obligation.obligation_id = "body-policy-epoch-b".into(); - let other_body = derive_workspace_coverage_projection_plan( - &other_obligation, - "projection", - "chunker", - "provider", - "model", - 3, - point_ids.clone(), - )?; - let other_embedding = derive_workspace_coverage_projection_plan( - &obligation, - "projection", - "chunker", - "provider", - "model-v2", - 4, - point_ids, - )?; - assert_ne!(first.collection_name, other_body.collection_name); - assert_ne!(first.plan_id, other_body.plan_id); - assert_ne!(first.collection_name, other_embedding.collection_name); - assert_ne!(first.plan_id, other_embedding.plan_id); - assert!(first.collection_name.starts_with("epiphany_workspace_")); - assert_eq!( - first.collection_name.len(), - "epiphany_workspace_".len() + 40 - ); + fn execution_claim_fences_collection_without_changing_plan() -> Result<()> { + let obligation = coverage_obligation("body-policy-epoch-a"); + let first = plan(&obligation)?; + let claim_a = uuid::Uuid::new_v4().to_string(); + let claim_b = uuid::Uuid::new_v4().to_string(); + let collection_a = workspace_coverage_execution_collection(&first.plan_id, &claim_a, 1)?; + let collection_b = workspace_coverage_execution_collection(&first.plan_id, &claim_b, 2)?; + assert_ne!(collection_a, collection_b); + assert_eq!(first, plan(&obligation)?); + assert!(collection_a.starts_with("epiphany_workspace_")); + assert_eq!(collection_a.len(), "epiphany_workspace_".len() + 40); Ok(()) } } diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 31897660..94610247 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -871,5 +871,39 @@ The next organ must own CAS persistence and execution: verify eligible bytes against the historical Body hashes, project, scroll-observe, then atomically publish the receipt/head. Until then coverage remains absent. +### Projector authority map + +Coverage state belongs in the Repository Body CultCache store. That is the only +existing lock domain able to CAS the exact Body head and its immutable evidence +with coverage obligation, plan, claim, attempt, receipt, and head. The runtime +store remains only the immutable route to that Body store. Qdrant mutation stays +outside the transaction; a lost terminal CAS leaves disposable orphan vectors, +not counterfeit readiness. + +The sealed execution path is acquire against the exact current Body chain, +verify every included live file against its historical length and SHA-256, +derive deterministic chunks and UUIDv5 point descriptors, embed and write into +a claim/epoch-fenced plan collection, scroll the whole collection with typed +payloads, then terminal-CAS success against the still-current Body head. Plans +must seal an ID-to-payload binding root; equal counts or equal IDs do not prove +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 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. + 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 7d10f7f1..96cd8dcb 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1722,6 +1722,26 @@ eligible live bytes against the selected Body manifest, executes the sealed plan, scroll-observes the physical point set, and only then publishes the receipt and head. +Projector ownership is now mapped before implementation. Persist all coverage +state in the Repository Body store so terminal success can CAS against the exact +current Body head; never create a runtime-store coverage oracle. Add a sealed +claim/attempt lifecycle, verified historical-byte reads, deterministic UUIDv5 +point descriptors, and a plan-sealed ID-to-payload binding root. Whole- +collection typed scroll must reject duplicate, extra, missing, or payload- +mismatched points before terminal success. Qdrant writes outside the CAS may +leave orphan namespaces after races or crashes, but those namespaces own no +readiness. + +The sealed acquisition/failure foundation is now implemented but intentionally +unwired. It authenticates current Body authority, verifies bytes, excludes +empty/oversize/non-UTF-8 files, derives named UTF-8-safe line chunks, and CAS- +installs immutable obligation/plan with a running claim/attempt in the Body +store. Exact failure may terminalize after Body advance; no code can publish a +coverage receipt/head. Next work must add observed-binding Qdrant execution, +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. + 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 300fa4c060f3d61e8751fad55fa9acbcdfa347e2..2ff23a1832c2258a304f2930f288a96a6bdf0e5b 100644 GIT binary patch delta 990 zcmZWoJ!@1!6m=6dh1gmJb3yF(?aFF`#wuA60yb)5VK+N-H*ef|Gn4t)LJQ^8F3zQ0deuu@zTocZzpeN7cZS(-yMxkhL@Mu7Rw*Dlww7K zA`8Q+Pl}D6a1e=2OFlT2Wzx=8*#;J}78ApC=)x>|A(^C`qjsN53*+RBlxu{x1KN@YS);H(MF!F)EwM->J`ysK%po9m z+N2b?pi|o?te~eFWwnl&0*s+a3tS&SZ?x12xA2iPS(RpuPwlWQ9vAvK4=t|S+r3}i zrl~dsq|k4U!Y)}wF=e{5Q5kJ$MDYYKG3!p69Y3D_%k-~ggd{lYRiSJ#qjvlHYERKy? zN{-uLJ93z7%=Fnr?$bf$08L>e_zmoEj8qyzKd2iA^yE}+(AUzf8|x=Ozpq@q-lszm z3KP{daIqzZgTpF`u+MN#&2rX1x%y*eb@5+*0D~3-79K^AwN5Z{4lvOaKHr3hsyoOdLMpniqQO6kAuSslHW-Mf6JlQ;zseLLFBM^gVW*}w(Vpbq# L+dh?vec2TNh6WTK diff --git a/state/map.yaml b/state/map.yaml index ebaf499c..2e1ec2b0 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -3,6 +3,7 @@ experiment: 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." 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