diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 1b443ffb..9d9854dd 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -35,6 +35,7 @@ mod substrate_gate; mod surfaces; mod thread_state_store; mod weksa_interlingua; +mod workspace_retrieval_coverage; pub use agent_launch::EPIPHANY_IMAGINATION_OWNER_ROLE; pub use agent_launch::EPIPHANY_IMAGINATION_ROLE_BINDING_ID; @@ -1132,3 +1133,4 @@ pub use weksa_interlingua::build_weksa_interlingua_packet; pub use weksa_interlingua::build_weksa_lowering_prompt; pub use weksa_interlingua::build_weksa_target_lowering_request; pub use weksa_interlingua::record_weksa_target_lowering_receipt; +pub use workspace_retrieval_coverage::*; diff --git a/epiphany-core/src/repository_body_observer.rs b/epiphany-core/src/repository_body_observer.rs index 5e4916fd..dd90dc0a 100644 --- a/epiphany-core/src/repository_body_observer.rs +++ b/epiphany-core/src/repository_body_observer.rs @@ -322,6 +322,28 @@ pub fn validate_repository_body_observation_basis( Ok(()) } +pub fn authenticated_repository_body_manifest( + runtime_store: &Path, + basis: &RepositoryBodyObservationBasis, +) -> Result { + validate_repository_body_observation_basis(runtime_store, basis)?; + 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_env = find(&entries, BODY_BINDING_TYPE, BODY_BINDING_KEY) + .ok_or_else(|| anyhow!("runtime repository Body store has no Body binding"))?; + let binding: RepositoryBodyBinding = decode(binding_env)?; + let historical_head = RepositoryBodyHead { + schema_version: BODY_SCHEMA_VERSION.into(), + workspace_id: basis.workspace_id.clone(), + generation: basis.generation, + observation_id: basis.observation_id.clone(), + manifest_root_sha256: basis.manifest_root_sha256.clone(), + }; + let (_, manifest) = validate_body_chain(&entries, &binding, &historical_head)?; + Ok(manifest) +} + pub fn observe_repository_body( repo: &Path, store: &Path, @@ -1196,6 +1218,39 @@ mod tests { Ok(()) } #[test] + fn coverage_obligation_refuses_manifest_entries_substituted_under_declared_root() -> Result<()> + { + let d = repo()?; + let state = tempfile::tempdir()?; + let (store, runtime) = bound( + d.path(), + state.path(), + "coverage-workspace", + "runtime", + "swarm", + )?; + write(&d.path().join("source.rs"), "fn original() {}")?; + run(d.path(), &["add", "."])?; + let basis = observe_runtime_repository_body_basis(&runtime)?; + let opening = SingleFileMessagePackBackingStore::new(&store).pull_all()?; + let original = find(&opening, BODY_MANIFEST_TYPE, &basis.manifest_root_sha256) + .ok_or_else(|| anyhow!("test Body manifest missing"))?; + let mut substituted: RepositoryBodyManifest = decode(original)?; + substituted.entries[0].raw_sha256 = "attacker-chosen-content-hash".into(); + let replacement = envelope( + BODY_MANIFEST_TYPE, + &basis.manifest_root_sha256, + &substituted, + )?; + assert!( + SingleFileMessagePackBackingStore::new(&store) + .compare_and_swap_batch(&[original.clone()], vec![replacement])? + ); + let policy = crate::WorkspaceCoveragePolicy::bounded_regular_files_v0(1024)?; + assert!(crate::derive_workspace_coverage_obligation(&runtime, &basis, &policy).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_retrieval_coverage.rs b/epiphany-core/src/workspace_retrieval_coverage.rs new file mode 100644 index 00000000..4a7370df --- /dev/null +++ b/epiphany-core/src/workspace_retrieval_coverage.rs @@ -0,0 +1,679 @@ +use crate::{ + RepositoryBodyManifest, RepositoryBodyManifestEntry, RepositoryBodyObservationBasis, + authenticated_repository_body_manifest, +}; +use anyhow::{Result, anyhow, bail}; +use cultcache_rs::DatabaseEntry; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::path::Path; + +pub const WORKSPACE_COVERAGE_POLICY_SCHEMA_VERSION: &str = + "gamecult.epiphany.workspace_coverage_policy.v0"; +pub const WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION: &str = + "gamecult.epiphany.workspace_coverage_obligation.v0"; +pub const WORKSPACE_COVERAGE_RECEIPT_SCHEMA_VERSION: &str = + "gamecult.epiphany.workspace_coverage_receipt.v0"; +pub const WORKSPACE_COVERAGE_PROJECTION_PLAN_SCHEMA_VERSION: &str = + "gamecult.epiphany.workspace_coverage_projection_plan.v0"; +pub const WORKSPACE_COVERAGE_HEAD_SCHEMA_VERSION: &str = + "gamecult.epiphany.workspace_coverage_head.v0"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkspaceCoverageDisposition { + IncludeRegularFile, + ExcludeGitlink, + ExcludeSymlink, + ExcludeUnsupportedKind, + ExcludeOversize, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkspaceCoveragePolicy { + pub schema_version: String, + pub policy_id: String, + pub maximum_file_bytes: u64, +} + +impl WorkspaceCoveragePolicy { + pub fn bounded_regular_files_v0(maximum_file_bytes: u64) -> Result { + if maximum_file_bytes == 0 { + bail!("workspace coverage policy maximum_file_bytes must be positive"); + } + Ok(Self { + schema_version: WORKSPACE_COVERAGE_POLICY_SCHEMA_VERSION.into(), + policy_id: "bounded_regular_files_v0".into(), + maximum_file_bytes, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkspaceCoverageClassification { + pub path: String, + pub raw_sha256: String, + pub raw_byte_length: u64, + pub disposition: WorkspaceCoverageDisposition, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.epiphany.workspace_coverage_obligation", + schema = "WorkspaceCoverageObligation" +)] +pub struct WorkspaceCoverageObligation { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub obligation_id: String, + #[cultcache(key = 2)] + pub workspace_id: String, + #[cultcache(key = 3)] + pub swarm_id: String, + #[cultcache(key = 4)] + pub runtime_id: String, + #[cultcache(key = 5)] + pub body_binding_sha256: String, + #[cultcache(key = 6)] + pub body_observation_id: String, + #[cultcache(key = 7)] + pub body_generation: u64, + #[cultcache(key = 8)] + pub manifest_root_sha256: String, + #[cultcache(key = 9)] + pub policy_id: String, + #[cultcache(key = 10)] + pub policy_sha256: String, + #[cultcache(key = 11)] + pub classification_set_sha256: String, + #[cultcache(key = 12)] + pub classifications: Vec, + #[cultcache(key = 13)] + pub included_entry_count: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.epiphany.workspace_coverage_projection_plan", + schema = "WorkspaceCoverageProjectionPlan" +)] +pub struct WorkspaceCoverageProjectionPlan { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub plan_id: String, + #[cultcache(key = 2)] + pub obligation_id: String, + #[cultcache(key = 3)] + pub projection_schema_version: String, + #[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)] + pub embedding_model: String, + #[cultcache(key = 8)] + pub vector_dimensions: u32, + #[cultcache(key = 9)] + pub expected_point_ids: Vec, + #[cultcache(key = 10)] + pub expected_point_count: u64, + #[cultcache(key = 11)] + pub expected_point_set_sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.epiphany.workspace_coverage_receipt", + schema = "WorkspaceCoverageReceipt" +)] +pub struct WorkspaceCoverageReceipt { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub receipt_id: String, + #[cultcache(key = 2)] + pub obligation_id: String, + #[cultcache(key = 3)] + pub plan_id: String, + #[cultcache(key = 4)] + pub collection_name: String, + #[cultcache(key = 5)] + pub embedding_provider_id: String, + #[cultcache(key = 6)] + pub embedding_model: String, + #[cultcache(key = 7)] + pub vector_dimensions: u32, + #[cultcache(key = 8)] + pub observed_point_count: u64, + #[cultcache(key = 9)] + pub observed_point_set_sha256: String, + #[cultcache(key = 10)] + pub observed_at: String, + #[cultcache(key = 11)] + pub observation_method: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.epiphany.workspace_coverage_head", + schema = "WorkspaceCoverageHead" +)] +pub struct WorkspaceCoverageHead { + #[cultcache(key = 0)] + pub schema_version: String, + #[cultcache(key = 1)] + pub workspace_id: String, + #[cultcache(key = 2)] + pub obligation_id: String, + #[cultcache(key = 3)] + pub plan_id: String, + #[cultcache(key = 4)] + pub receipt_id: String, +} + +pub fn derive_workspace_coverage_obligation( + runtime_store: &Path, + basis: &RepositoryBodyObservationBasis, + policy: &WorkspaceCoveragePolicy, +) -> Result { + let manifest = authenticated_repository_body_manifest(runtime_store, basis)?; + derive_workspace_coverage_obligation_from_authenticated_manifest(basis, &manifest, policy) +} + +fn derive_workspace_coverage_obligation_from_authenticated_manifest( + basis: &RepositoryBodyObservationBasis, + manifest: &RepositoryBodyManifest, + policy: &WorkspaceCoveragePolicy, +) -> Result { + if policy.schema_version != WORKSPACE_COVERAGE_POLICY_SCHEMA_VERSION + || policy.policy_id.trim().is_empty() + || policy.maximum_file_bytes == 0 + { + bail!("unsupported or invalid workspace coverage policy"); + } + if manifest.workspace_id != basis.workspace_id + || manifest.scope != basis.scope + || manifest.manifest_root_sha256 != basis.manifest_root_sha256 + || basis.generation == 0 + { + bail!("workspace coverage input manifest disagrees with authenticated Body basis"); + } + let mut prior_path: Option<&str> = None; + let mut classifications = Vec::with_capacity(manifest.entries.len()); + for entry in &manifest.entries { + if entry.path.trim().is_empty() + || (entry.raw_sha256.trim().is_empty() && entry.kind != "gitlink_nonrecursive") + || prior_path.is_some_and(|prior| prior >= entry.path.as_str()) + { + bail!("Body manifest entries must have unique, strictly ordered paths and hashes"); + } + prior_path = Some(&entry.path); + classifications.push(classify(entry, policy)); + } + let policy_sha256 = digest(policy)?; + let classification_set_sha256 = digest(&classifications)?; + let included_entry_count = classifications + .iter() + .filter(|entry| entry.disposition == WorkspaceCoverageDisposition::IncludeRegularFile) + .count() as u64; + let obligation_id = format!( + "workspace-coverage:{}", + digest(&( + &basis.body_binding_sha256, + &basis.observation_id, + &basis.manifest_root_sha256, + &policy_sha256, + &classification_set_sha256, + ))? + ); + Ok(WorkspaceCoverageObligation { + schema_version: WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION.into(), + obligation_id, + workspace_id: basis.workspace_id.clone(), + swarm_id: basis.swarm_id.clone(), + runtime_id: basis.runtime_id.clone(), + body_binding_sha256: basis.body_binding_sha256.clone(), + body_observation_id: basis.observation_id.clone(), + body_generation: basis.generation, + manifest_root_sha256: basis.manifest_root_sha256.clone(), + policy_id: policy.policy_id.clone(), + policy_sha256, + classification_set_sha256, + classifications, + included_entry_count, + }) +} + +#[allow(clippy::too_many_arguments)] +pub 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, +) -> Result { + if obligation.schema_version != WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION + || projection_schema_version.trim().is_empty() + || chunker_id.trim().is_empty() + || 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() + { + 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 identity = ( + &obligation.obligation_id, + projection_schema_version, + chunker_id, + &collection_name, + embedding_provider_id, + embedding_model, + vector_dimensions, + &expected_point_ids, + &expected_point_set_sha256, + ); + Ok(WorkspaceCoverageProjectionPlan { + schema_version: WORKSPACE_COVERAGE_PROJECTION_PLAN_SCHEMA_VERSION.into(), + plan_id: format!("workspace-coverage-plan:{}", digest(&identity)?), + 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, + expected_point_count, + expected_point_set_sha256, + }) +} + +pub fn validate_workspace_coverage_projection_plan( + obligation: &WorkspaceCoverageObligation, + plan: &WorkspaceCoverageProjectionPlan, +) -> Result<()> { + let expected = derive_workspace_coverage_projection_plan( + obligation, + &plan.projection_schema_version, + &plan.chunker_id, + &plan.embedding_provider_id, + &plan.embedding_model, + plan.vector_dimensions, + plan.expected_point_ids.clone(), + )?; + if *plan != expected { + bail!("workspace coverage projection plan identity or derived fields were altered"); + } + Ok(()) +} + +pub fn validate_workspace_coverage_receipt( + obligation: &WorkspaceCoverageObligation, + plan: &WorkspaceCoverageProjectionPlan, + receipt: &WorkspaceCoverageReceipt, +) -> Result<()> { + validate_workspace_coverage_projection_plan(obligation, plan)?; + 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.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" + { + 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 + { + bail!("workspace coverage receipt does not prove the exact expected point set"); + } + Ok(()) +} + +pub fn validate_workspace_coverage_head( + obligation: &WorkspaceCoverageObligation, + plan: &WorkspaceCoverageProjectionPlan, + receipt: &WorkspaceCoverageReceipt, + head: &WorkspaceCoverageHead, +) -> Result<()> { + validate_workspace_coverage_receipt(obligation, plan, receipt)?; + if head.schema_version != WORKSPACE_COVERAGE_HEAD_SCHEMA_VERSION + || head.workspace_id != obligation.workspace_id + || head.obligation_id != obligation.obligation_id + || head.plan_id != plan.plan_id + || head.receipt_id != receipt.receipt_id + || receipt.obligation_id != obligation.obligation_id + || receipt.plan_id != plan.plan_id + { + 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]) +} + +fn classify( + entry: &RepositoryBodyManifestEntry, + policy: &WorkspaceCoveragePolicy, +) -> WorkspaceCoverageClassification { + let disposition = match entry.kind.as_str() { + "gitlink_nonrecursive" => WorkspaceCoverageDisposition::ExcludeGitlink, + "symlink_target" => WorkspaceCoverageDisposition::ExcludeSymlink, + "regular" if entry.raw_byte_length > policy.maximum_file_bytes => { + WorkspaceCoverageDisposition::ExcludeOversize + } + "regular" => WorkspaceCoverageDisposition::IncludeRegularFile, + _ => WorkspaceCoverageDisposition::ExcludeUnsupportedKind, + }; + WorkspaceCoverageClassification { + path: entry.path.clone(), + raw_sha256: entry.raw_sha256.clone(), + raw_byte_length: entry.raw_byte_length, + disposition, + } +} + +fn digest(value: &(impl Serialize + ?Sized)) -> Result { + Ok(format!( + "{:x}", + Sha256::digest(rmp_serde::to_vec_named(value).map_err(|error| anyhow!(error))?) + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn basis() -> RepositoryBodyObservationBasis { + RepositoryBodyObservationBasis { + schema_version: "epiphany.repository_body.v2".into(), + workspace_id: "workspace-1".into(), + swarm_id: "swarm-1".into(), + runtime_id: "runtime-1".into(), + scope: "git_worktree".into(), + body_binding_sha256: "binding-hash".into(), + observation_id: "workspace-1:7".into(), + generation: 7, + manifest_root_sha256: "manifest-hash".into(), + scan_started_at: "start".into(), + scan_finished_at: "finish".into(), + } + } + + fn entry(path: &str, kind: &str, size: u64) -> RepositoryBodyManifestEntry { + RepositoryBodyManifestEntry { + path: path.into(), + git_mode: "100644".into(), + kind: kind.into(), + raw_byte_length: size, + raw_sha256: format!("hash-{path}"), + gitlink_oid: None, + } + } + + #[test] + fn every_manifest_entry_receives_one_policy_disposition() -> Result<()> { + let manifest = RepositoryBodyManifest { + schema_version: "epiphany.repository_body.v2".into(), + manifest_root_sha256: "manifest-hash".into(), + workspace_id: "workspace-1".into(), + scope: "git_worktree".into(), + entries: vec![ + entry("a.rs", "regular", 12), + entry("b.bin", "regular", 101), + entry("c-link", "symlink_target", 3), + entry("d-submodule", "gitlink_nonrecursive", 0), + ], + }; + let obligation = derive_workspace_coverage_obligation_from_authenticated_manifest( + &basis(), + &manifest, + &WorkspaceCoveragePolicy::bounded_regular_files_v0(100)?, + )?; + assert_eq!(obligation.classifications.len(), manifest.entries.len()); + assert_eq!(obligation.included_entry_count, 1); + assert_eq!( + obligation.classifications[1].disposition, + WorkspaceCoverageDisposition::ExcludeOversize + ); + Ok(()) + } + + #[test] + fn manifest_substitution_and_duplicate_paths_are_refused() -> Result<()> { + let mut manifest = RepositoryBodyManifest { + schema_version: "epiphany.repository_body.v2".into(), + manifest_root_sha256: "wrong".into(), + workspace_id: "workspace-1".into(), + scope: "git_worktree".into(), + entries: vec![entry("a", "regular", 1)], + }; + let policy = WorkspaceCoveragePolicy::bounded_regular_files_v0(100)?; + assert!( + derive_workspace_coverage_obligation_from_authenticated_manifest( + &basis(), + &manifest, + &policy + ) + .is_err() + ); + manifest.manifest_root_sha256 = "manifest-hash".into(); + manifest.entries.push(entry("a", "regular", 1)); + assert!( + derive_workspace_coverage_obligation_from_authenticated_manifest( + &basis(), + &manifest, + &policy + ) + .is_err() + ); + Ok(()) + } + + #[test] + fn receipt_cannot_convert_counts_or_unobserved_points_into_coverage() -> Result<()> { + let obligation = WorkspaceCoverageObligation { + schema_version: WORKSPACE_COVERAGE_OBLIGATION_SCHEMA_VERSION.into(), + obligation_id: "obligation-1".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: 2, + }; + let points = vec!["point-a".to_string(), "point-b".to_string()]; + let plan = derive_workspace_coverage_projection_plan( + &obligation, + "projection-v0", + "chunker-v0", + "provider", + "model", + 3, + points.clone(), + )?; + 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(), + embedding_provider_id: "provider".into(), + embedding_model: "model".into(), + vector_dimensions: 3, + observed_point_count: 2, + observed_point_set_sha256: digest(&points)?, + observed_at: "now".into(), + observation_method: "claimed_upsert_count".into(), + }; + 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(), + workspace_id: obligation.workspace_id.clone(), + obligation_id: obligation.obligation_id.clone(), + plan_id: plan.plan_id.clone(), + receipt_id: receipt.receipt_id.clone(), + }; + assert!(validate_workspace_coverage_head(&obligation, &plan, &receipt, &head).is_ok()); + head.receipt_id = "some-other-receipt".into(); + 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, + }; + assert!( + derive_workspace_coverage_projection_plan( + &obligation, + "projection", + "chunker", + "provider", + "model", + 3, + vec!["duplicate".into(), "duplicate".into()] + ) + .is_err() + ); + assert!( + derive_workspace_coverage_projection_plan( + &obligation, + "projection", + "chunker", + "provider", + "model", + 3, + vec!["z".into(), "a".into()] + ) + .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(); + 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()); + Ok(()) + } + + #[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 + ); + Ok(()) + } +} diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 95cab49f..31897660 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -853,5 +853,23 @@ live bytes against Body hashes, builds a Body-root/policy/index-epoch isolated Qdrant projection, observes its deterministic point set, and only then publishes an immutable CultCache coverage receipt. Qdrant remains disposable. +## Body-bound workspace coverage substrate (2026-07-15) + +`workspace_retrieval_coverage.rs` now defines the truthful contract boundary +without pretending the projector exists. Obligation derivation reloads the exact +historical Body manifest through the authenticated runtime Body-store route; +callers cannot hand it a manifest-shaped claim. One versioned policy classifies +every ordered Body entry and seals the complete classification set into the +obligation. A separate projection plan seals chunker, projection, embedding, and +expected point-set identity, while deriving its physical Qdrant collection from +the Body-bound authority instead of accepting a caller-selected namespace. + +Receipts validate only when an exact Qdrant scroll observation matches that +sealed plan, and heads join one workspace, obligation, plan, and receipt. This +module has no store writer, Qdrant actuator, query gate, or readiness writer. +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. + 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 6ae0e9d7..7d10f7f1 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1705,6 +1705,23 @@ project into a Body-root/policy/epoch isolated collection, observe the exact expected point set, and publish an immutable CultCache coverage receipt. Do not resurrect the JSON manifest as a compatibility source. +## Body-bound coverage contracts landed (2026-07-15) + +The native coverage substrate now admits only an authenticated historical Body +manifest, exhaustively classifies its entries under a versioned policy, and +seals Body/policy/classification identity into an immutable obligation. A typed +projection plan binds the exact expected point set and derives an epoch-isolated +Qdrant collection from Body plus projection/embedding authority; the caller has +no collection-name lever. Receipt/head validators require an exact scroll- +observed point set and exact obligation/plan join. + +This is contract substrate, not operational coverage. There is deliberately no +persistence writer, projector, Qdrant call, query eligibility path, or readiness +join. Next action: build the single CAS-owned projector/store path that verifies +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. + 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 f4d412b4..300fa4c0 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 7033217e..ebaf499c 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -2,7 +2,7 @@ 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. It wrote JSON under CODEX_HOME, compared path/size/mtime/chunk counts, used incompatible exact/semantic filesystem walkers, named Qdrant collections from workspace path+model, and could emit Ready without a manifest or from query-time BM25; no runtime called it. Legacy EpiphanyRetrievalState is presentation-only: clean Ready now projects Missing and the indexing job is Unavailable/unowned, while explicit stale/dirty input may remain a warning. The replacement must consume an authenticated historical Body manifest, classify every entry under one versioned inclusion policy, verify eligible live bytes against Body hashes, build a Body-root/policy/index-epoch-isolated Qdrant projection, observe its exact point set, and publish an immutable CultCache coverage receipt before any query or Mind readiness join can trust it." + 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." 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