diff --git a/crates/tracedecay-application/src/advisory/fixtures/mod.rs b/crates/tracedecay-application/src/advisory/fixtures/mod.rs index c8a158fbc95..f153cb3b6cc 100644 --- a/crates/tracedecay-application/src/advisory/fixtures/mod.rs +++ b/crates/tracedecay-application/src/advisory/fixtures/mod.rs @@ -183,9 +183,7 @@ impl AdvisorySourceBackedCompositeFixtureV1 { } } -/// Loads and cross-checks the captured source files. The acceptance agent can -/// combine this identity with its existing diagnostic/impact result, -/// authorized anchors, and effective Plan 20 threshold snapshot. +/// Loads and cross-checks the captured source files. pub fn load_advisory_source_backed_composite_fixture_v1() -> Result { let scenario = parse(SCENARIO_JSON)?; diff --git a/crates/tracedecay-application/src/advisory/mod.rs b/crates/tracedecay-application/src/advisory/mod.rs index d61c5b71154..3bd9803519f 100644 --- a/crates/tracedecay-application/src/advisory/mod.rs +++ b/crates/tracedecay-application/src/advisory/mod.rs @@ -103,8 +103,8 @@ pub use production::{ pub use proximity_runtime::{ CanonicalProximityEvidenceAuthorityV1, CanonicalProximityEvidenceBatchV1, CanonicalProximityEvidenceV1, ConcreteProximityRuntimeOwnerV1, FeedbackProximityReadRuntimeV1, - ProductionProximityEvidenceAuthorityV1, ProximityFindingContributorV1, - ProximityRuntimeOutcomeV1, ProximityRuntimeOwnerV1, ProximityThresholdPinV1, + ProductionProximityEvidenceAuthorityV1, ProximityFindingContributorV1, ProximityPolicyPinV1, + ProximityRuntimeOutcomeV1, ProximityRuntimeOwnerV1, SharedCanonicalProximityEvidenceAuthorityV1, open_proximity_runtime, production_feedback_proximity_read_runtime_v1, }; diff --git a/crates/tracedecay-application/src/advisory/proximity_runtime.rs b/crates/tracedecay-application/src/advisory/proximity_runtime.rs index f7b0f69902a..0688f80e522 100644 --- a/crates/tracedecay-application/src/advisory/proximity_runtime.rs +++ b/crates/tracedecay-application/src/advisory/proximity_runtime.rs @@ -1,7 +1,7 @@ //! One-shot concurrent-work proximity provider. //! //! The provider consumes canonical observation/graph evidence, resolves the -//! effective Plan 20 threshold, and projects one Plan 09 contribution batch. +//! effective proximity policy, and projects one canonical contribution batch. //! Shared feedback publication owns durable dedupe. This module creates no //! fixture authority, evidence store, lock, task, schedule, or continuation. @@ -19,7 +19,7 @@ use tracedecay_contracts::{ }; use tracedecay_domain::configuration::{ConfigurationRevisionId, ConfigurationValueV1, SettingKey}; use tracedecay_domain::feedback::{ - FeedbackScopeV1, PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1, ProviderEvaluationStateV1, + FeedbackScopeV1, PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1, ProviderEvaluationStateV1, ProximityAddressV1, ProximityContributionIdV1, ProximityContributionV1, ProximityCoverageV1, ProximityInclusionV1, ProximityObservationIdV1, ProximityRelationPathV1, ProximityWarningClassV1, @@ -46,57 +46,50 @@ pub use authority::{ const PROXIMITY_CONTRIBUTION_ID_DOMAIN_V1: &str = "tracedecay.advisory.proximity.contribution-id.v1"; -/// Preserves the published numeric setting's relationship-hint admission. -const RELATIONSHIP_HINT_MAX_THRESHOLD_BASIS_POINTS_V1: u16 = 7_500; - -/// Exact Plan 20 threshold input for one evaluation. Revision and effective +/// Exact proximity policy input for one evaluation. Revision and effective /// behavior digest are pinned together before provider evidence is read. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] -pub struct ProximityThresholdPinV1 { +pub struct ProximityPolicyPinV1 { pub configuration_revision: ConfigurationRevisionId, pub configuration_digest: ManifestDigest, - pub value_basis_points: u16, + pub relationship_hints: bool, } -impl ProximityThresholdPinV1 { +impl ProximityPolicyPinV1 { pub fn from_current_configuration(current: &ConfigurationCurrentStateV1) -> Option { current.revision_id.validate().ok()?; current.snapshot.validate().ok()?; - let key = SettingKey::new(PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1).ok()?; - let ConfigurationValueV1::Unsigned(value) = current.snapshot.effective_values.get(&key)? + let key = SettingKey::new(PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1).ok()?; + let ConfigurationValueV1::Boolean(relationship_hints) = + current.snapshot.effective_values.get(&key)? else { return None; }; Self::new( current.revision_id.clone(), current.snapshot.effective_behavior_digest.clone(), - u16::try_from(*value).ok()?, + *relationship_hints, ) } pub fn new( configuration_revision: ConfigurationRevisionId, configuration_digest: ManifestDigest, - value_basis_points: u16, + relationship_hints: bool, ) -> Option { configuration_revision.validate().ok()?; configuration_digest.validate().ok()?; - (value_basis_points <= 10_000).then_some(Self { + Some(Self { configuration_revision, configuration_digest, - value_basis_points, + relationship_hints, }) } pub fn validate(&self) -> bool { self.configuration_revision.validate().is_ok() && self.configuration_digest.validate().is_ok() - && self.value_basis_points <= 10_000 - } - - const fn admits_relationship_hints(&self) -> bool { - self.value_basis_points <= RELATIONSHIP_HINT_MAX_THRESHOLD_BASIS_POINTS_V1 } } @@ -430,11 +423,11 @@ where /// Evaluates against the exact configuration snapshot already authorized /// for the enclosing feedback cycle. The provider never rereads mutable /// configuration while that cycle is in flight. - pub async fn evaluate_with_threshold_pin( + pub async fn evaluate_with_policy_pin( &self, context: &RequestContext, request: &ProximityEvaluationRequestV1, - threshold: &ProximityThresholdPinV1, + policy: &ProximityPolicyPinV1, ) -> ProximityRuntimeOutcomeV1 { if let Some(interruption) = interrupted(context) { return interruption; @@ -450,7 +443,7 @@ where ) { return ProximityRuntimeOutcomeV1::Denied; } - if !threshold.validate() { + if !policy.validate() { return ProximityRuntimeOutcomeV1::Unavailable; } let Some(batch) = self.evidence.current_evidence(context, request).await else { @@ -461,7 +454,7 @@ where } let mut contributions = Vec::with_capacity(batch.evidence.len()); for item in batch.evidence { - let Some(contribution) = build_proximity_contribution(request, threshold, item) else { + let Some(contribution) = build_proximity_contribution(request, policy, item) else { return ProximityRuntimeOutcomeV1::Unavailable; }; contributions.push(contribution); @@ -479,9 +472,9 @@ where A: CanonicalProximityEvidenceAuthorityV1 + Sync, C: ConfigurationControlStore, { - /// Compatibility entry for the aggregate advisory runtime. The current - /// threshold is accepted only when its behavior digest is the exact - /// configuration identity already authorized by the enclosing request. + /// The current policy is accepted only when its behavior digest is the + /// exact configuration identity already authorized by the enclosing + /// request. pub async fn evaluate_for_configuration_digest( &self, context: &RequestContext, @@ -508,14 +501,13 @@ where if let Some(interruption) = interrupted(context) { return interruption; } - let Some(threshold) = ProximityThresholdPinV1::from_current_configuration(&configuration) - else { + let Some(policy) = ProximityPolicyPinV1::from_current_configuration(&configuration) else { return ProximityRuntimeOutcomeV1::Unavailable; }; - if threshold.configuration_digest != *expected_configuration_digest { + if policy.configuration_digest != *expected_configuration_digest { return ProximityRuntimeOutcomeV1::Denied; } - self.evaluate_with_threshold_pin(context, request, &threshold) + self.evaluate_with_policy_pin(context, request, &policy) .await } } @@ -532,10 +524,10 @@ fn interrupted(context: &RequestContext) -> Option { fn build_proximity_contribution( request: &ProximityEvaluationRequestV1, - threshold: &ProximityThresholdPinV1, + policy: &ProximityPolicyPinV1, evidence: CanonicalProximityEvidenceV1, ) -> Option { - if !threshold.validate() || !evidence.validate_for(request) { + if !policy.validate() || !evidence.validate_for(request) { return None; } let source_observation_ids = evidence @@ -549,7 +541,7 @@ fn build_proximity_contribution( || evidence.coverage == ProximityCoverageV1::Stale { ProximityInclusionV1::Stale - } else if exact || threshold.admits_relationship_hints() { + } else if exact || policy.relationship_hints { ProximityInclusionV1::Included } else { ProximityInclusionV1::BelowThreshold @@ -570,10 +562,7 @@ fn build_proximity_contribution( evidence.observed_at, evidence.expires_at, if exact { "immediate" } else { "configured" }, - (!exact).then_some(( - &threshold.configuration_revision, - &threshold.configuration_digest, - )), + (!exact).then_some((&policy.configuration_revision, &policy.configuration_digest)), )) .ok()?; let suffix = sha256_hex_suffix(identity.as_str()).unwrap_or(identity.as_str()); @@ -725,20 +714,23 @@ mod tests { (scope, context) } - fn configuration(revision: &str, threshold: Option) -> ConfigurationCurrentStateV1 { - let layers = threshold - .map( - |threshold| tracedecay_configuration::config::resolver::ConfigurationLayerV1 { + fn configuration( + revision: &str, + relationship_hints: Option, + ) -> ConfigurationCurrentStateV1 { + let layers = relationship_hints + .map(|relationship_hints| { + tracedecay_configuration::config::resolver::ConfigurationLayerV1 { layer: ConfigurationLayerIdV1::Project { project_id: ProjectId::new("project.proximity-pin").expect("project"), }, revision_id: ConfigurationRevisionId::new(revision).expect("revision"), entries: BTreeMap::from([( - SettingKey::new(PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1).expect("key"), - ConfigurationValueV1::Unsigned(threshold), + SettingKey::new(PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1).expect("key"), + ConfigurationValueV1::Boolean(relationship_hints), )]), - }, - ) + } + }) .into_iter() .collect::>(); let snapshot = tracedecay_configuration::config::resolver::resolve_configuration( @@ -754,15 +746,35 @@ mod tests { } } + #[test] + fn policy_pin_reads_the_relationship_hint_setting() { + let default = configuration("configuration.proximity-policy.default", None); + let disabled = configuration("configuration.proximity-policy.disabled", Some(false)); + let default_pin = + ProximityPolicyPinV1::from_current_configuration(&default).expect("default policy pin"); + let disabled_pin = ProximityPolicyPinV1::from_current_configuration(&disabled) + .expect("disabled policy pin"); + assert!( + default_pin.relationship_hints, + "the registry default admits relationship hints" + ); + assert!(!disabled_pin.relationship_hints); + assert_ne!( + default_pin.configuration_digest, + disabled_pin.configuration_digest + ); + assert!(default_pin.validate() && disabled_pin.validate()); + } + #[tokio::test] - async fn threshold_pin_is_immutable_in_cycle_and_refreshes_next_cycle() { + async fn policy_pin_is_immutable_in_cycle_and_refreshes_next_cycle() { let (scope, context) = scope_and_context(); let authorized = configuration("configuration.proximity-pin.authorized", None); - let authorized_pin = ProximityThresholdPinV1::from_current_configuration(&authorized) - .expect("authorized threshold"); - let drifted = configuration("configuration.proximity-pin.drifted", Some(7_500)); - let drifted_pin = ProximityThresholdPinV1::from_current_configuration(&drifted) - .expect("drifted threshold"); + let authorized_pin = ProximityPolicyPinV1::from_current_configuration(&authorized) + .expect("authorized policy"); + let drifted = configuration("configuration.proximity-pin.drifted", Some(false)); + let drifted_pin = + ProximityPolicyPinV1::from_current_configuration(&drifted).expect("drifted policy"); assert_ne!( authorized_pin.configuration_revision, drifted_pin.configuration_revision @@ -790,7 +802,7 @@ mod tests { assert!(matches!( owner - .evaluate_with_threshold_pin(&context, &request, &authorized_pin) + .evaluate_with_policy_pin(&context, &request, &authorized_pin) .await, ProximityRuntimeOutcomeV1::Completed(_) )); @@ -805,33 +817,17 @@ mod tests { assert!(matches!( owner - .evaluate_with_threshold_pin(&context, &request, &drifted_pin) + .evaluate_with_policy_pin(&context, &request, &drifted_pin) .await, ProximityRuntimeOutcomeV1::Completed(_) )); assert_eq!( calls.load(Ordering::SeqCst), 2, - "a later cycle must use its newly authorized threshold pin" + "a later cycle must use its newly authorized policy pin" ); } - #[test] - fn relationship_hints_follow_the_legacy_threshold_mapping() { - let revision = ConfigurationRevisionId::new("configuration.proximity-policy").unwrap(); - let digest = ManifestDigest::new(format!("sha256:{}", "a".repeat(64))).unwrap(); - for value in 0..=10_000_u16 { - let pin = - ProximityThresholdPinV1::new(revision.clone(), digest.clone(), value).expect("pin"); - let legacy_hint_score = 7_500_u16; - assert_eq!( - pin.admits_relationship_hints(), - legacy_hint_score >= value, - "threshold {value}" - ); - } - } - fn encounter_evidence(scope: &FeedbackScopeV1) -> CanonicalProximityEvidenceV1 { let provider = ProviderId::new("provider.cursor").unwrap(); let address = ProximityAddressV1 { @@ -937,9 +933,10 @@ mod tests { retrieval_anchor_id: Some(hint.retrieval_anchor_ids[0].clone()), }); let mut exact_identity = None; - for value in [0, 7_500, 7_501, 10_000] { + for relationship_hints in [true, false] { let pin = - ProximityThresholdPinV1::new(revision.clone(), digest.clone(), value).unwrap(); + ProximityPolicyPinV1::new(revision.clone(), digest.clone(), relationship_hints) + .unwrap(); let exact = build_proximity_contribution(&request, &pin, evidence.clone()).unwrap(); assert_eq!(exact.inclusion, ProximityInclusionV1::Included); assert_eq!(exact.address.as_ref(), Some(&evidence.address)); @@ -950,7 +947,7 @@ mod tests { let related = build_proximity_contribution(&request, &pin, hint.clone()).unwrap(); assert_eq!( related.inclusion, - if value <= 7_500 { + if relationship_hints { ProximityInclusionV1::Included } else { ProximityInclusionV1::BelowThreshold @@ -963,7 +960,7 @@ mod tests { }) .unwrap() .findings; - if value <= 7_500 { + if relationship_hints { assert_eq!(findings.len(), 1); assert_eq!( findings[0] @@ -976,7 +973,7 @@ mod tests { assert!(findings.is_empty()); } } - let pin = ProximityThresholdPinV1::new(revision, digest, 0).unwrap(); + let pin = ProximityPolicyPinV1::new(revision, digest, true).unwrap(); let stale_request = ProximityEvaluationRequestV1 { observed_at: UtcMicros(4), ..request @@ -986,6 +983,35 @@ mod tests { assert_eq!(stale.coverage, ProximityCoverageV1::Stale); } + #[tokio::test] + async fn read_page_preserves_encounter_intervals_and_relation_evidence() { + let (scope, context) = scope_and_context(); + let evidence = encounter_evidence(&scope); + let expected = evidence.encounter.clone(); + let authority: SharedCanonicalProximityEvidenceAuthorityV1 = + Arc::new(StaticEvidence(CanonicalProximityEvidenceBatchV1 { + evidence: vec![evidence], + coverage: ProximityCoverageV1::Complete, + source_generation: CodeGenerationId::new("generation.proximity-read").unwrap(), + observed_at: UtcMicros(1), + expires_at: UtcMicros(4), + omissions: Vec::new(), + })); + let runtime = FeedbackProximityReadRuntimeV1::new(scope, authority).unwrap(); + let result = runtime + .read( + &context, + &FeedbackProximityReadRequestV1 { + observed_at: UtcMicros(2), + }, + ) + .await; + let FeedbackProximityReadResultV1::Complete { page } = result else { + panic!("expected a complete read: {result:?}"); + }; + assert_eq!(page.encounters, vec![expected]); + } + #[tokio::test] async fn expired_evidence_returns_typed_stale_result() { let (scope, context) = scope_and_context(); diff --git a/crates/tracedecay-application/src/feedback/cycle_production.rs b/crates/tracedecay-application/src/feedback/cycle_production.rs index 59618059b54..339cb71fa14 100644 --- a/crates/tracedecay-application/src/feedback/cycle_production.rs +++ b/crates/tracedecay-application/src/feedback/cycle_production.rs @@ -56,7 +56,7 @@ use tracedecay_tool_catalog::CapabilityId; use super::cycle_runtime::FeedbackCycleRuntime; use super::cycle_runtime::{FeedbackCycleInvocation, FeedbackCycleLspInput}; use crate::advisory::{ - ConcreteProximityRuntimeOwnerV1, ProximityRuntimeOutcomeV1, ProximityThresholdPinV1, + ConcreteProximityRuntimeOwnerV1, ProximityPolicyPinV1, ProximityRuntimeOutcomeV1, SharedCanonicalProximityEvidenceAuthorityV1, open_proximity_runtime, }; use crate::diagnostics_publication::{ @@ -194,7 +194,7 @@ struct ProductionFeedbackCycleProximityV1 { project_root: PathBuf, document_identity: Arc, owner: ProductionProximityOwnerV1, - threshold_pin: ProximityThresholdPinV1, + policy_pin: ProximityPolicyPinV1, } impl ProductionFeedbackCycleProximityPortV1 for ProductionFeedbackCycleProximityV1 { @@ -216,7 +216,7 @@ impl ProductionFeedbackCycleProximityPortV1 for ProductionFeedbackCycleProximity }; match self .owner - .evaluate_with_threshold_pin(context, &request, &self.threshold_pin) + .evaluate_with_policy_pin(context, &request, &self.policy_pin) .await { ProximityRuntimeOutcomeV1::Completed(contributor) => { @@ -372,11 +372,11 @@ pub async fn resolve_production_feedback_cycle_parts( input: ProductionFeedbackCycleOpenV1, ) -> Result { let feedback_scope = resolve_project_feedback_scope_v1(&input.project_root, &input.scope)?; - let proximity_threshold_pin = ProximityThresholdPinV1::from_current_configuration( + let proximity_policy_pin = ProximityPolicyPinV1::from_current_configuration( &input.access_configuration, ) .ok_or(ApplicationContractError::Inconsistent { - field: "project-open proximity threshold", + field: "project-open proximity policy", })?; let proximity_evidence = crate::advisory::proximity_runtime::production_proximity_evidence_authority_v1( @@ -404,7 +404,7 @@ pub async fn resolve_production_feedback_cycle_parts( project_root: input.project_root.clone(), document_identity: Arc::clone(&input.document_identity), owner: proximity_owner, - threshold_pin: proximity_threshold_pin.clone(), + policy_pin: proximity_policy_pin.clone(), }); let access_configuration_digest = input .access_configuration @@ -506,7 +506,7 @@ pub async fn resolve_production_feedback_cycle_parts( scope: input.scope.clone(), requester: input.requester.clone(), authorization: input.authorization, - threshold_pin: proximity_threshold_pin, + policy_pin: proximity_policy_pin, policy_digest: policy_digest.clone(), providers: provider_candidates .iter() @@ -862,7 +862,7 @@ struct ProductionLspInputContext { scope: ResolvedScope, requester: ActorId, authorization: Arc, - threshold_pin: ProximityThresholdPinV1, + policy_pin: ProximityPolicyPinV1, policy_digest: ManifestDigest, providers: Vec, project_root: PathBuf, @@ -877,7 +877,7 @@ fn production_lsp_input( scope, requester, authorization, - threshold_pin, + policy_pin, policy_digest, providers, project_root, @@ -902,7 +902,7 @@ fn production_lsp_input( let scope = scope.clone(); let requester = requester.clone(); let authorization = Arc::clone(&authorization); - let threshold_pin = threshold_pin.clone(); + let policy_pin = policy_pin.clone(); let policy_digest = policy_digest.clone(); let providers = providers.clone(); let project_root = project_root.clone(); @@ -926,8 +926,8 @@ fn production_lsp_input( }; let observed_at = now_micros(); let access = authorization.authorize(observed_at).await?; - if access.configuration_revision != threshold_pin.configuration_revision - || access.configuration_digest != threshold_pin.configuration_digest + if access.configuration_revision != policy_pin.configuration_revision + || access.configuration_digest != policy_pin.configuration_digest { return Err(LspRuntimeFailure::new("feedback-cycle-configuration-drift")); } @@ -966,7 +966,7 @@ fn production_lsp_input( }, trigger, policy_digest, - threshold_pin.configuration_digest, + policy_pin.configuration_digest, FeedbackBudgetV1::bounded(1_000, 1_000, 10_000, 10_000), ) .map_err(|_| LspRuntimeFailure::new("feedback-cycle-request"))?; @@ -1384,16 +1384,16 @@ mod tests { ) } - fn threshold_pin( + fn policy_pin( configuration_revision: &ConfigurationRevisionId, configuration_digest: &ManifestDigest, - ) -> ProximityThresholdPinV1 { - ProximityThresholdPinV1::new( + ) -> ProximityPolicyPinV1 { + ProximityPolicyPinV1::new( configuration_revision.clone(), configuration_digest.clone(), - 5_000, + true, ) - .expect("threshold pin") + .expect("policy pin") } #[test] @@ -1478,7 +1478,7 @@ mod tests { scope: scope.clone(), requester: ActorId::new("actor.cycle-production").expect("actor"), authorization: current, - threshold_pin: threshold_pin(&configuration_revision, &configuration), + policy_pin: policy_pin(&configuration_revision, &configuration), policy_digest: policy.clone(), providers: vec![provider.clone()], project_root: PathBuf::from(WORKSPACE_ROOT), @@ -1497,7 +1497,7 @@ mod tests { scope, requester: ActorId::new("actor.cycle-production").expect("actor"), authorization: expired, - threshold_pin: threshold_pin(&configuration_revision, &configuration), + policy_pin: policy_pin(&configuration_revision, &configuration), policy_digest: policy, providers: vec![provider], project_root: PathBuf::from(WORKSPACE_ROOT), @@ -1540,7 +1540,7 @@ mod tests { scope, requester: ActorId::new("actor.cycle-production").expect("actor"), authorization, - threshold_pin: threshold_pin(&configuration_revision, &authorized_configuration), + policy_pin: policy_pin(&configuration_revision, &authorized_configuration), policy_digest: policy, providers: vec![provider], project_root: PathBuf::from(WORKSPACE_ROOT), @@ -1684,7 +1684,7 @@ mod tests { scope, requester: ActorId::new("actor.cycle-production").expect("actor"), authorization, - threshold_pin: threshold_pin(&configuration_revision, &configuration), + policy_pin: policy_pin(&configuration_revision, &configuration), policy_digest: policy, providers: vec![provider], project_root: PathBuf::from(WORKSPACE_ROOT), @@ -1733,7 +1733,7 @@ mod tests { scope, requester: ActorId::new("actor.cycle-production").expect("actor"), authorization, - threshold_pin: threshold_pin(&configuration_revision, &configuration), + policy_pin: policy_pin(&configuration_revision, &configuration), policy_digest: policy, providers: vec![provider], project_root: PathBuf::from(WORKSPACE_ROOT), diff --git a/crates/tracedecay-configuration/src/configuration/operations.rs b/crates/tracedecay-configuration/src/configuration/operations.rs index 7b47b96d12f..65c9e5ae404 100644 --- a/crates/tracedecay-configuration/src/configuration/operations.rs +++ b/crates/tracedecay-configuration/src/configuration/operations.rs @@ -947,9 +947,10 @@ mod tests { clock, ); - let key = - SettingKey::new(tracedecay_domain::feedback::PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1) - .unwrap(); + let key = SettingKey::new( + tracedecay_domain::feedback::PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1, + ) + .unwrap(); let expected = registry.definition(&key).unwrap().default_value.clone(); let actor = AuthorizedActor { actor_id: id::("actor.configuration.default-fallback"), @@ -961,7 +962,7 @@ mod tests { assert_eq!(resolved.effective_value, expected); assert_eq!( resolved.effective_value, - ConfigurationValueV1::Unsigned(7_000) + ConfigurationValueV1::Boolean(true) ); assert!( resolved.candidates.is_empty(), diff --git a/crates/tracedecay-contracts/src/advisory.rs b/crates/tracedecay-contracts/src/advisory.rs index ac0efe7bf81..ae6f0aca6f8 100644 --- a/crates/tracedecay-contracts/src/advisory.rs +++ b/crates/tracedecay-contracts/src/advisory.rs @@ -25,10 +25,10 @@ pub use tracedecay_domain::feedback::{ GitHubReviewLifecycleV1, GitHubReviewRateLimitCheckpointV1, GitHubReviewReadCheckpointV1, GitHubReviewReadOperationV1, GitHubReviewRemapStateV1, GitHubReviewStateV1, GitHubReviewThreadIdV1, MAX_CI_FAILURE_CALLER_EVIDENCE_V1, MAX_CI_FAILURE_RERUN_HINTS_V1, - MAX_CI_FAILURE_TEST_EVIDENCE_V1, PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1, ProximityAddressV1, - ProximityContributionIdV1, ProximityContributionV1, ProximityCoverageV1, ProximityInclusionV1, - ProximityObservationIdV1, ProximityRelationPathKindV1, ProximityRelationPathV1, - ProximityWarningClassV1, + MAX_CI_FAILURE_TEST_EVIDENCE_V1, PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1, + ProximityAddressV1, ProximityContributionIdV1, ProximityContributionV1, ProximityCoverageV1, + ProximityInclusionV1, ProximityObservationIdV1, ProximityRelationPathKindV1, + ProximityRelationPathV1, ProximityWarningClassV1, }; /// The window of one advisory cycle. It opens when the cycle starts and diff --git a/crates/tracedecay-contracts/src/lib.rs b/crates/tracedecay-contracts/src/lib.rs index 610b8ad95e4..45413a71cfb 100644 --- a/crates/tracedecay-contracts/src/lib.rs +++ b/crates/tracedecay-contracts/src/lib.rs @@ -113,10 +113,10 @@ pub use advisory::{ GitHubReviewLifecycleV1, GitHubReviewRateLimitCheckpointV1, GitHubReviewReadCheckpointV1, GitHubReviewReadOperationV1, GitHubReviewRemapStateV1, GitHubReviewStateV1, GitHubReviewThreadIdV1, MAX_CI_FAILURE_CALLER_EVIDENCE_V1, MAX_CI_FAILURE_RERUN_HINTS_V1, - MAX_CI_FAILURE_TEST_EVIDENCE_V1, PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1, ProximityAddressV1, - ProximityContributionIdV1, ProximityContributionV1, ProximityCoverageV1, ProximityInclusionV1, - ProximityObservationIdV1, ProximityRelationPathKindV1, ProximityRelationPathV1, - ProximityWarningClassV1, + MAX_CI_FAILURE_TEST_EVIDENCE_V1, PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1, + ProximityAddressV1, ProximityContributionIdV1, ProximityContributionV1, ProximityCoverageV1, + ProximityInclusionV1, ProximityObservationIdV1, ProximityRelationPathKindV1, + ProximityRelationPathV1, ProximityWarningClassV1, }; pub use authorization::AuthorizationRequest; pub use clock::{ClockError, now_micros, try_now_micros}; diff --git a/crates/tracedecay-domain/src/configuration.rs b/crates/tracedecay-domain/src/configuration.rs index 35d41cb26cd..2faae480b0f 100644 --- a/crates/tracedecay-domain/src/configuration.rs +++ b/crates/tracedecay-domain/src/configuration.rs @@ -103,7 +103,7 @@ pub const CONFIGURATION_SETTING_KEYS_V1: &[&str] = &[ CONTEXT_SCOUT_SETTINGS_SETTING_KEY, AUTOMATION_SETTINGS_SETTING_KEY, LCM_SUMMARIZER_EXECUTABLES_SETTING_KEY, - crate::feedback::PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1, + crate::feedback::PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1, USER_REPEATED_QUERY_HINTS_SETTING_KEY, USER_CODE_INDEX_WORKERS_SETTING_KEY, USER_WATCHER_DEBOUNCE_MS_SETTING_KEY, diff --git a/crates/tracedecay-domain/src/feedback/proximity.rs b/crates/tracedecay-domain/src/feedback/proximity.rs index a9b90ff56b4..3d7bf918c3b 100644 --- a/crates/tracedecay-domain/src/feedback/proximity.rs +++ b/crates/tracedecay-domain/src/feedback/proximity.rs @@ -13,7 +13,8 @@ use crate::research::{DomainError, RetrievalAnchorId, UtcMicros}; use super::FeedbackScopeV1; -pub const PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1: &str = "feedback.proximity.risk_threshold"; +pub const PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1: &str = + "feedback.proximity.relationship_hints.v1"; crate::canonical_text::validated_string_newtype!( plain, diff --git a/crates/tracedecay-domain/src/lib.rs b/crates/tracedecay-domain/src/lib.rs index 764d8cd2317..f50314e3c9e 100644 --- a/crates/tracedecay-domain/src/lib.rs +++ b/crates/tracedecay-domain/src/lib.rs @@ -183,7 +183,7 @@ pub use feedback::{ GitHubReviewReadOperationV1, GitHubReviewRemapStateV1, GitHubReviewStateV1, GitHubReviewThreadIdV1, MAX_CI_FAILURE_CALLER_EVIDENCE_V1, MAX_CI_FAILURE_RERUN_HINTS_V1, MAX_CI_FAILURE_TEST_EVIDENCE_V1, MAX_GITHUB_PULL_REQUEST_TITLE_BYTES_V1, - MAX_GITHUB_REVIEW_THREAD_PATH_BYTES_V1, PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1, + MAX_GITHUB_REVIEW_THREAD_PATH_BYTES_V1, PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1, ProviderEvaluationStateV1, ProximityAddressV1, ProximityContributionIdV1, ProximityContributionV1, ProximityCoverageV1, ProximityInclusionV1, ProximityObservationIdV1, ProximityRelationPathKindV1, ProximityRelationPathV1, ProximityWarningClassV1, diff --git a/crates/tracedecay-global-db/src/configuration/registry.rs b/crates/tracedecay-global-db/src/configuration/registry.rs index 02c3b283cb9..252a6e2416a 100644 --- a/crates/tracedecay-global-db/src/configuration/registry.rs +++ b/crates/tracedecay-global-db/src/configuration/registry.rs @@ -26,17 +26,13 @@ use tracedecay_domain::configuration::{ USER_WORK_EXPERTISE_CONSENT_SETTING_KEY, WORK_EXECUTABLE_BINDINGS_SETTING_KEY, WORK_TOPOLOGY_POLICY_SETTING_KEY, WorkExpertiseConsentV1, safe_work_topology_policy_v1, }; -use tracedecay_domain::feedback::PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1; +use tracedecay_domain::feedback::PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1; use tracedecay_domain::source_path_policy::GENERATED_DIR_SEGMENTS; use tracedecay_domain::{DomainError, validate_index_path_patterns}; -/// Canonical default for configured-tier proximity warnings. -pub const DEFAULT_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1: u64 = 7_000; -pub const MAX_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1: u64 = 10_000; - /// Registry schema revision. Increment only when setting-definition semantics /// change, not when a setting value changes. -pub const CONFIGURATION_REGISTRY_SCHEMA_REVISION: u16 = 9; +pub const CONFIGURATION_REGISTRY_SCHEMA_REVISION: u16 = 10; #[derive(Debug, Error)] pub enum ConfigurationRegistryError { @@ -180,12 +176,10 @@ impl ConfigurationRegistry { restart_requirement: RestartRequirementV1::None, })?; registry.register(SettingDefinitionV1 { - key: setting_key(PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1)?, + key: setting_key(PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1)?, schema_revision: CONFIGURATION_REGISTRY_SCHEMA_REVISION, - value_kind: ConfigurationValueKindV1::Unsigned, - default_value: ConfigurationValueV1::Unsigned( - DEFAULT_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1, - ), + value_kind: ConfigurationValueKindV1::Boolean, + default_value: ConfigurationValueV1::Boolean(true), sensitivity: SettingSensitivityV1::Public, scope: SettingScopeV1::Project, restart_requirement: RestartRequirementV1::None, @@ -278,23 +272,6 @@ impl ConfigurationRegistry { }); } value.validate()?; - if key.as_str() == PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1 { - let ConfigurationValueV1::Unsigned(actual) = value else { - return Err(ConfigurationRegistryError::ValueKindMismatch { - key: key.clone(), - expected: ConfigurationValueKindV1::Unsigned, - actual: value.kind(), - }); - }; - if *actual > MAX_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1 { - return Err(ConfigurationRegistryError::UnsignedValueOutOfRange { - key: key.clone(), - minimum: 0, - maximum: MAX_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1, - actual: *actual, - }); - } - } if matches!( key.as_str(), USER_WATCHER_DEBOUNCE_MS_SETTING_KEY | USER_EXTRACTION_TIMEOUT_SECS_SETTING_KEY @@ -668,43 +645,26 @@ fn setting_key(value: &str) -> Result { } #[cfg(test)] -mod proximity_threshold_tests { +mod proximity_relationship_hints_tests { use super::*; #[test] - fn proximity_threshold_has_one_bounded_project_default() { + fn proximity_relationship_hints_is_one_boolean_project_default() { + assert_eq!(CONFIGURATION_REGISTRY_SCHEMA_REVISION, 10); let registry = ConfigurationRegistry::core().expect("registry"); - let key = SettingKey::new(PROXIMITY_RISK_THRESHOLD_SETTING_KEY_V1).expect("key"); + let key = SettingKey::new(PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1).expect("key"); let definition = registry.definition(&key).expect("definition"); - - assert_eq!(definition.value_kind, ConfigurationValueKindV1::Unsigned); + assert_eq!(definition.value_kind, ConfigurationValueKindV1::Boolean); assert_eq!( definition.default_value, - ConfigurationValueV1::Unsigned(DEFAULT_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1) + ConfigurationValueV1::Boolean(true) ); assert_eq!(definition.scope, SettingScopeV1::Project); - assert_eq!(definition.sensitivity, SettingSensitivityV1::Public); - assert_eq!(definition.restart_requirement, RestartRequirementV1::None); + let retired = SettingKey::new("feedback.proximity.risk_threshold").expect("key"); assert!( - registry - .validate_value(&key, &ConfigurationValueV1::Unsigned(0)) - .is_ok() + registry.definition(&retired).is_err(), + "the numeric threshold is retired" ); - assert!( - registry - .validate_value( - &key, - &ConfigurationValueV1::Unsigned(MAX_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1), - ) - .is_ok() - ); - assert!(matches!( - registry.validate_value( - &key, - &ConfigurationValueV1::Unsigned(MAX_PROXIMITY_RISK_THRESHOLD_BASIS_POINTS_V1 + 1), - ), - Err(ConfigurationRegistryError::UnsignedValueOutOfRange { .. }) - )); } } diff --git a/crates/tracedecay-global-db/src/configuration/store/tests/fixtures/configuration-registry-revision9.sql b/crates/tracedecay-global-db/src/configuration/store/tests/fixtures/configuration-registry-revision9.sql new file mode 100644 index 00000000000..4e362414269 --- /dev/null +++ b/crates/tracedecay-global-db/src/configuration/store/tests/fixtures/configuration-registry-revision9.sql @@ -0,0 +1,41 @@ +INSERT INTO "configuration_format" VALUES(1,1); +INSERT INTO "configuration_revisions" VALUES('configuration.revision.root',NULL,'tracedecay.configuration.snapshot.v1.e4e16ae48fa864f997a4151ca35d66319b796f53f25d1c6a9e32657c467cab35','sha256:5d59396db8b24fb8b0ad0309dc8df48e0ad104917006792066f95297cdb9cf31','sha256:f6234e098ad2b851ddb6727f1c2a74648ea974c31bdebe21ecb5c6b0a2a3d272','actor.configuration.fixture','canonical_initialization',1); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','analyzer.settings.v1','default','',1,'{"schema_version":1,"value":{"kind":"analyzer_settings","value":{"schema_version":1,"selections":[]}},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','automation.settings.v1','default','',1,'{"schema_version":1,"value":{"kind":"automation_settings","value":{"schema_version":1,"enabled":true,"backend":"codex_app_server","host_mode":"standalone","model_id":"gpt-5.6-sol","timeout_secs":60,"scheduler_tick_secs":60,"combine_due_tasks":true,"allow_job_commands":false,"tasks":{"memory_curator":{"enabled":true,"schedule":"interval","interval_secs":900,"cooldown_secs":300,"min_idle_secs":null},"session_reflector":{"enabled":true,"schedule":"interval","interval_secs":900,"cooldown_secs":300,"min_idle_secs":null},"skill_writer":{"enabled":true,"schedule":"interval","interval_secs":3600,"cooldown_secs":300,"min_idle_secs":900}}}},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','context_scout.settings.v1','default','',1,'{"schema_version":1,"value":{"kind":"context_scout_settings","value":{"schema_version":1,"state":"disabled","mode":"deterministic","limits":{"max_candidates":32,"max_evidence":16,"max_text_bytes":4096,"max_model_input_tokens":2048,"max_model_output_tokens":256},"model_path":null,"model_id":null,"model_timeout_secs":null}},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','feedback.proximity.risk_threshold','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":7000},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','index.exclude.v1','default','',1,'{"schema_version":1,"value":{"kind":"string_list","value":[".git/**",".tracedecay/**","**/*.min.*",".cache/**","**/.cache/**",".gradle/**","**/.gradle/**",".next/**","**/.next/**",".turbo/**","**/.turbo/**",".venv/**","**/.venv/**",".worktrees/**","**/.worktrees/**","__pycache__/**","**/__pycache__/**","build/**","**/build/**","coverage/**","**/coverage/**","dist/**","**/dist/**","node_modules/**","**/node_modules/**","out/**","**/out/**","target/**","**/target/**","vendor/**","**/vendor/**","venv/**","**/venv/**"]},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','index.extract_docstrings.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":true},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','index.include.v1','default','',1,'{"schema_version":1,"value":{"kind":"string_list","value":[]},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','index.include_submodules.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":false},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','index.max_file_size.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":1048576},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','index.native_graph_activation.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":true},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','index.track_call_sites.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":true},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','lcm.summarizer_executables.v1','default','',1,'{"schema_version":1,"value":{"kind":"lcm_summarizer_executables","value":{"cursor_agent":{"state":"unconfigured"},"codex":{"state":"unconfigured"}}},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','scope.access_rules.v1','default','',1,'{"schema_version":1,"value":{"kind":"access_rules","value":[]},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','scope.source_bindings.v1','default','',1,'{"schema_version":1,"value":{"kind":"source_bindings","value":[]},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.auto_init.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":true},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.auto_track_pr_branches.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":false},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.auto_track_pr_poll_secs.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":300},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.auto_watch.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":false},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.backstop_interval_mins.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":15},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.branch_gc_days.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":14},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.read_cooldown_secs.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":30},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.read_refresh.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":true},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.session_start_stale_threshold_secs.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":600},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.session_start_sync.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":true},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.watch_debounce_ms.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":2000},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.watch_linked_worktrees.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":false},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.watch_max_delay_ms.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":30000},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','sync.watch_max_projects.v1','default','',1,'{"schema_version":1,"value":{"kind":"unsigned","value":32},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','telemetry.timings.v1','default','',1,'{"schema_version":1,"value":{"kind":"boolean","value":true},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','user.work_expertise_consent.v1','default','',1,'{"schema_version":1,"value":{"kind":"work_expertise_consent","value":{"schema_version":1,"enabled":false,"granted_at":null,"expires_at":null,"allowed_categories":[]}},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','work.executable_bindings.v1','default','',1,'{"schema_version":1,"value":{"kind":"work_executable_bindings","value":[]},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','work.expertise_consent.v1','default','',1,'{"schema_version":1,"value":{"kind":"work_expertise_consent","value":{"schema_version":1,"enabled":false,"granted_at":null,"expires_at":null,"allowed_categories":[]}},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_entries" VALUES('configuration.revision.root','work.topology_policy.v1','default','',1,'{"schema_version":1,"value":{"kind":"work_topology_policy","value":{"schema_version":1,"placement":{"kind":"existing_worktree_only"},"roots":[],"branch_topology":{"allowed":["no_branches","unbranched","independent_branches"]},"review_topology":{"allowed":["no_review","independent_review","standard_pull_requests"],"github_stacked_prs":"disabled"},"branch_naming":{"prefix":"tracedecay/","components":[{"kind":"task_id_digest_prefix","bytes":10},{"kind":"work_class"},{"kind":"monotonic_collision_ordinal"}],"separator":"slash","maximum_bytes":200,"collision":{"kind":"append_monotonic_ordinal","maximum_attempts":32}},"concurrency":{"maximum_active_per_repository":1,"maximum_parallel_per_task":1,"maximum_global_active":1,"maximum_stack_depth":1},"cross_merge":{"allowed_modes":["disabled"],"default_mode":"disabled","allow_cross_repository":false},"gates":{"cleanliness":"require_clean","tests":[],"review":{"kind":"independent_review_count","count":1},"require_fresh_preflight":true,"maximum_preflight_age_seconds":300},"protected_refs":[{"selector":{"kind":"native_default_branch"},"disposition":"reject"},{"selector":{"kind":"exact","value":"refs/heads/main"},"disposition":"reject"},{"selector":{"kind":"exact","value":"refs/heads/master"},"disposition":"reject"},{"selector":{"kind":"prefix","value":"refs/tags/"},"disposition":"reject"},{"selector":{"kind":"prefix","value":"refs/remotes/"},"disposition":"reject"}],"history_rewrite":"forbid_force_and_rebase","escalation":"reject","retention":{"terminal_retention_seconds":null,"abandoned_retention_seconds":null,"maximum_retained_per_repository":null,"automatic_gc":{"kind":"disabled"}},"notifications":"critical_only"}},"provenance":[{"layer":{"kind":"default"},"revision_id":"configuration.registry.default.v1","disposition":"defaulted","safe_reason":"registry_default"}]}'); +INSERT INTO "configuration_topology_policies" VALUES('configuration.revision.root',1,'sha256:d27b56e55ddd25797af2a8645a2d312424b2a97a16eb52d50b84058af0c0faab','existing_worktree_only','disabled',0,'require_clean','{"allowed":["no_review","independent_review","standard_pull_requests"],"github_stacked_prs":"disabled"}',1,300,'forbid_force_and_rebase','reject','{"kind":"disabled"}','critical_only',X'7b22736368656d615f76657273696f6e223a312c22706c6163656d656e74223a7b226b696e64223a226578697374696e675f776f726b747265655f6f6e6c79227d2c22726f6f7473223a5b5d2c226272616e63685f746f706f6c6f6779223a7b22616c6c6f776564223a5b226e6f5f6272616e63686573222c22756e6272616e63686564222c22696e646570656e64656e745f6272616e63686573225d7d2c227265766965775f746f706f6c6f6779223a7b22616c6c6f776564223a5b226e6f5f726576696577222c22696e646570656e64656e745f726576696577222c227374616e646172645f70756c6c5f7265717565737473225d2c226769746875625f737461636b65645f707273223a2264697361626c6564227d2c226272616e63685f6e616d696e67223a7b22707265666978223a22747261636564656361792f222c22636f6d706f6e656e7473223a5b7b226b696e64223a227461736b5f69645f6469676573745f707265666978222c226279746573223a31307d2c7b226b696e64223a22776f726b5f636c617373227d2c7b226b696e64223a226d6f6e6f746f6e69635f636f6c6c6973696f6e5f6f7264696e616c227d5d2c22736570617261746f72223a22736c617368222c226d6178696d756d5f6279746573223a3230302c22636f6c6c6973696f6e223a7b226b696e64223a22617070656e645f6d6f6e6f746f6e69635f6f7264696e616c222c226d6178696d756d5f617474656d707473223a33327d7d2c22636f6e63757272656e6379223a7b226d6178696d756d5f6163746976655f7065725f7265706f7369746f7279223a312c226d6178696d756d5f706172616c6c656c5f7065725f7461736b223a312c226d6178696d756d5f676c6f62616c5f616374697665223a312c226d6178696d756d5f737461636b5f6465707468223a317d2c2263726f73735f6d65726765223a7b22616c6c6f7765645f6d6f646573223a5b2264697361626c6564225d2c2264656661756c745f6d6f6465223a2264697361626c6564222c22616c6c6f775f63726f73735f7265706f7369746f7279223a66616c73657d2c226761746573223a7b22636c65616e6c696e657373223a22726571756972655f636c65616e222c227465737473223a5b5d2c22726576696577223a7b226b696e64223a22696e646570656e64656e745f7265766965775f636f756e74222c22636f756e74223a317d2c22726571756972655f66726573685f707265666c69676874223a747275652c226d6178696d756d5f707265666c696768745f6167655f7365636f6e6473223a3330307d2c2270726f7465637465645f72656673223a5b7b2273656c6563746f72223a7b226b696e64223a226e61746976655f64656661756c745f6272616e6368227d2c22646973706f736974696f6e223a2272656a656374227d2c7b2273656c6563746f72223a7b226b696e64223a226578616374222c2276616c7565223a22726566732f68656164732f6d61696e227d2c22646973706f736974696f6e223a2272656a656374227d2c7b2273656c6563746f72223a7b226b696e64223a226578616374222c2276616c7565223a22726566732f68656164732f6d6173746572227d2c22646973706f736974696f6e223a2272656a656374227d2c7b2273656c6563746f72223a7b226b696e64223a22707265666978222c2276616c7565223a22726566732f746167732f227d2c22646973706f736974696f6e223a2272656a656374227d2c7b2273656c6563746f72223a7b226b696e64223a22707265666978222c2276616c7565223a22726566732f72656d6f7465732f227d2c22646973706f736974696f6e223a2272656a656374227d5d2c22686973746f72795f72657772697465223a22666f726269645f666f7263655f616e645f726562617365222c22657363616c6174696f6e223a2272656a656374222c22726574656e74696f6e223a7b227465726d696e616c5f726574656e74696f6e5f7365636f6e6473223a6e756c6c2c226162616e646f6e65645f726574656e74696f6e5f7365636f6e6473223a6e756c6c2c226d6178696d756d5f72657461696e65645f7065725f7265706f7369746f7279223a6e756c6c2c226175746f6d617469635f6763223a7b226b696e64223a2264697361626c6564227d7d2c226e6f74696669636174696f6e73223a22637269746963616c5f6f6e6c79227d'); +INSERT INTO "configuration_topology_protected_refs" VALUES('configuration.revision.root',0,'native_default_branch','sha256:56e81e607fe237229fd1498bc34aaf7d25200483edf221fc5ad9130b046f8ad0','reject'); +INSERT INTO "configuration_topology_protected_refs" VALUES('configuration.revision.root',1,'exact','sha256:bbd38a5d10ad265a2c07c1dfbe6d9891ed111c40fdadf743cede6dfb055b05e7','reject'); +INSERT INTO "configuration_topology_protected_refs" VALUES('configuration.revision.root',2,'exact','sha256:1efd7aa986ff318fd533e92fba9cf42fba371891d03b0d328124046f4d4a7ee8','reject'); +INSERT INTO "configuration_topology_protected_refs" VALUES('configuration.revision.root',3,'prefix','sha256:048b859662196a287ab1796dee38d4284cc8b8bb74661c2979fbf65d40dbf7f0','reject'); +INSERT INTO "configuration_topology_protected_refs" VALUES('configuration.revision.root',4,'prefix','sha256:bc52254d2bcb530eba5139003761a4415bcbed291bde713212fd08c14219a961','reject'); diff --git a/crates/tracedecay-global-db/src/configuration/store/tests/mod.rs b/crates/tracedecay-global-db/src/configuration/store/tests/mod.rs index ef11d2128cd..fb16817bcec 100644 --- a/crates/tracedecay-global-db/src/configuration/store/tests/mod.rs +++ b/crates/tracedecay-global-db/src/configuration/store/tests/mod.rs @@ -513,3 +513,4 @@ fn evidence_for(plan: &ProtectedChangePlan) -> ScopeRevalidationEvidenceV1 { mod control; mod persistence; mod receipt_writer; +mod retired_proximity_threshold; diff --git a/crates/tracedecay-global-db/src/configuration/store/tests/retired_proximity_threshold.rs b/crates/tracedecay-global-db/src/configuration/store/tests/retired_proximity_threshold.rs new file mode 100644 index 00000000000..568753db9bc --- /dev/null +++ b/crates/tracedecay-global-db/src/configuration/store/tests/retired_proximity_threshold.rs @@ -0,0 +1,285 @@ +use super::{control_authority_with_key_for_layer, global_setup, point_revision_at_snapshot}; +use crate::configuration::contracts::DirectConfigurationMutation; +use crate::configuration::contracts::ports::ConfigurationControlStore; +use crate::configuration::store::GlobalDbConfigurationControlStore; +use crate::tests::harness::HostAdmissionScope; +use tracedecay_domain::configuration::{ + ConfigurationIdempotencyKey, ConfigurationLayerIdV1, ConfigurationMutationOperationV1, + ConfigurationSnapshotV1, ConfigurationValueV1, SettingKey, +}; +use tracedecay_domain::feedback::PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1; +use tracedecay_domain::{ProjectId, UtcMicros}; + +const REGISTRY_REVISION_9_STORE_FIXTURE: &str = + include_str!("fixtures/configuration-registry-revision9.sql"); + +const RETIRED_PROXIMITY_THRESHOLD_SETTING_KEY: &str = "feedback.proximity.risk_threshold"; + +const PROJECT_ID: &str = "project.configuration-store.fixture"; + +const REPLACED_TABLES: &str = "'configuration_format', 'configuration_revisions', \ + 'configuration_entries', 'configuration_topology_policies', \ + 'configuration_topology_protected_refs'"; + +async fn replaced_table_triggers( + transaction: &crate::registered::RegisteredGlobalDbWriteTransaction<'_>, +) -> Result, tracedecay_runtime_core::db::engine::Error> { + let sql = format!( + "SELECT name, sql FROM sqlite_master + WHERE type = 'trigger' AND tbl_name IN ({REPLACED_TABLES}) + ORDER BY name" + ); + let mut rows = transaction.query(&sql, ()).await?; + let mut triggers = Vec::new(); + while let Some(row) = rows.next().await? { + triggers.push((row.get::(0)?, row.get::(1)?)); + } + Ok(triggers) +} + +async fn trigger_names( + db: &crate::registered::RegisteredGlobalDb, +) -> Result, Box> { + let read = db.read_snapshot().await?; + let mut rows = read + .query( + "SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name", + (), + ) + .await?; + let mut names = Vec::new(); + while let Some(row) = rows.next().await? { + names.push(row.get::(0)?); + } + Ok(names) +} + +async fn seed_released_registry_key_set( + transaction: &crate::registered::RegisteredGlobalDbWriteTransaction<'_>, +) -> Result<(), tracedecay_runtime_core::db::engine::Error> { + let triggers = replaced_table_triggers(transaction).await?; + let mut replace_rows = String::new(); + for (name, _) in &triggers { + replace_rows.push_str(&format!( + "DROP TRIGGER \"{}\";\n", + name.replace('"', "\"\"") + )); + } + replace_rows.push_str( + "DELETE FROM configuration_topology_protected_refs; + DELETE FROM configuration_entries; + DELETE FROM configuration_topology_policies; + DELETE FROM configuration_revisions; + DELETE FROM configuration_format;", + ); + transaction.execute_batch(&replace_rows).await?; + transaction + .execute_batch(REGISTRY_REVISION_9_STORE_FIXTURE) + .await?; + for (_, definition) in triggers { + transaction.execute_batch(&definition).await?; + } + Ok(()) +} + +#[tokio::test] +async fn snapshot_holding_the_retired_proximity_threshold_is_reset_required() { + let (_directory, runtime, root) = global_setup().await; + let db = runtime + .registered_database(HostAdmissionScope::Project) + .expect("registered project database"); + let triggers_before = trigger_names(db).await.unwrap(); + let transaction = db.begin_write_transaction().await.unwrap(); + seed_released_registry_key_set(&transaction).await.unwrap(); + transaction.commit().await.unwrap(); + assert_eq!( + trigger_names(db).await.unwrap(), + triggers_before, + "seeding restores every immutability trigger it stepped around" + ); + let store = GlobalDbConfigurationControlStore::new_registered(db); + + let error = store + .converge_registered_registry_shape(&root.revision_id, UtcMicros(2)) + .await + .expect_err( + "a snapshot holding feedback.proximity.risk_threshold must return configuration ResetRequired", + ); + + assert!( + matches!( + error, + crate::configuration::contracts::ConfigurationError::ResetRequired { .. } + ), + "the retired entry must surface the typed reset state: {error:?}" + ); + + let read = db.read_snapshot().await.unwrap(); + let mut rows = read + .query( + "SELECT COUNT(*) FROM configuration_entries WHERE key = ?1", + tracedecay_runtime_core::db::engine::params![RETIRED_PROXIMITY_THRESHOLD_SETTING_KEY], + ) + .await + .unwrap(); + assert_eq!( + rows.next().await.unwrap().unwrap().get::(0).unwrap(), + 1, + "the refused convergence must leave the retired entry untouched" + ); + let mut rows = read + .query("SELECT COUNT(*) FROM configuration_entries", ()) + .await + .unwrap(); + assert_eq!( + rows.next().await.unwrap().unwrap().get::(0).unwrap(), + 33, + "no entry is added, removed, or rewritten by the refused convergence" + ); + let mut rows = read + .query( + "SELECT typeof(sealed_policy_value), length(sealed_policy_value) + FROM configuration_topology_policies", + (), + ) + .await + .unwrap(); + let row = rows.next().await.unwrap().unwrap(); + assert_eq!( + row.get::(0).unwrap(), + "blob", + "production seals the topology policy as a JSON BLOB" + ); + assert!(row.get::(1).unwrap() > 0); + + let layer = ConfigurationLayerIdV1::Project { + project_id: ProjectId::new(PROJECT_ID).expect("project"), + }; + let authority = control_authority_with_key_for_layer( + ConfigurationMutationOperationV1::DirectMutation, + &root.revision_id, + Some( + ConfigurationIdempotencyKey::new("configuration.idempotency.retired-proximity") + .expect("idempotency key"), + ), + layer.clone(), + ); + let mutation = DirectConfigurationMutation::Set { + layer, + key: SettingKey::new(RETIRED_PROXIMITY_THRESHOLD_SETTING_KEY).expect("key"), + value: Box::new(ConfigurationValueV1::Unsigned(7_000)), + }; + let error = store + .commit_direct(&authority, &mutation, &root.revision_id) + .await + .expect_err("a setter for the retired threshold must be refused as unknown"); + match error { + crate::configuration::contracts::ConfigurationError::Validation(message) => assert!( + message.contains("is not registered"), + "the retired setter must be refused as an unknown setting: {message}" + ), + other => panic!("unexpected setter refusal: {other:?}"), + } +} + +#[tokio::test] +async fn snapshot_holding_both_proximity_keys_is_reset_required() { + let (_directory, runtime, root) = global_setup().await; + let current_key = SettingKey::new(PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1).unwrap(); + let retired_key = SettingKey::new(RETIRED_PROXIMITY_THRESHOLD_SETTING_KEY).unwrap(); + assert_eq!( + root.snapshot.effective_values.get(¤t_key), + Some(&ConfigurationValueV1::Boolean(true)) + ); + assert!(!root.snapshot.effective_values.contains_key(&retired_key)); + + let mut effective_values = root.snapshot.effective_values.clone(); + effective_values.insert(retired_key.clone(), ConfigurationValueV1::Unsigned(7_000)); + let mut provenance = root.snapshot.provenance.clone(); + provenance.insert( + retired_key.clone(), + root.snapshot.provenance[¤t_key].clone(), + ); + let legacy_snapshot = ConfigurationSnapshotV1::new(effective_values, provenance).unwrap(); + + let db = runtime + .registered_database(HostAdmissionScope::Project) + .expect("registered project database"); + let transaction = db.begin_write_transaction().await.unwrap(); + transaction + .execute_batch("DROP TRIGGER configuration_revisions_immutable_update;") + .await + .unwrap(); + transaction + .execute( + "INSERT INTO configuration_entries ( + revision_id, key, layer_kind, layer_id, schema_revision, typed_value + ) VALUES (?1, ?2, 'default', '', 1, ?3)", + tracedecay_runtime_core::db::engine::params![ + root.revision_id.as_str(), + retired_key.as_str(), + serde_json::json!({ + "schema_version": 1, + "value": ConfigurationValueV1::Unsigned(7_000), + "provenance": legacy_snapshot.provenance[&retired_key], + }) + .to_string(), + ], + ) + .await + .unwrap(); + point_revision_at_snapshot(&transaction, &root.revision_id, &legacy_snapshot).await; + transaction.commit().await.unwrap(); + let store = GlobalDbConfigurationControlStore::new_registered(db); + + let error = store + .converge_registered_registry_shape(&root.revision_id, UtcMicros(2)) + .await + .expect_err( + "a snapshot holding both proximity keys must return configuration ResetRequired", + ); + assert!( + matches!( + error, + crate::configuration::contracts::ConfigurationError::ResetRequired { .. } + ), + "the legacy numeric entry must surface the typed reset state: {error:?}" + ); + + let read = db.read_snapshot().await.unwrap(); + let mut rows = read + .query( + "SELECT COUNT(*) FROM configuration_entries WHERE key = ?1", + tracedecay_runtime_core::db::engine::params![RETIRED_PROXIMITY_THRESHOLD_SETTING_KEY], + ) + .await + .unwrap(); + assert_eq!( + rows.next().await.unwrap().unwrap().get::(0).unwrap(), + 1, + "the refused convergence must leave the legacy numeric entry untouched" + ); + let mut rows = read + .query( + "SELECT COUNT(*) FROM configuration_entries WHERE key = ?1", + tracedecay_runtime_core::db::engine::params![ + PROXIMITY_RELATIONSHIP_HINTS_SETTING_KEY_V1 + ], + ) + .await + .unwrap(); + assert_eq!( + rows.next().await.unwrap().unwrap().get::(0).unwrap(), + 1, + "the refused convergence must leave the relationship-hint entry untouched" + ); + let mut rows = read + .query("SELECT COUNT(*) FROM configuration_revisions", ()) + .await + .unwrap(); + assert_eq!( + rows.next().await.unwrap().unwrap().get::(0).unwrap(), + 1, + "the refused convergence must not write a revision" + ); +} diff --git a/crates/tracedecay/src/mcp/tools/handlers/configuration_batch_behavior_tests.rs b/crates/tracedecay/src/mcp/tools/handlers/configuration_batch_behavior_tests.rs index 40ac7b4b501..e2cf8b9f6d9 100644 --- a/crates/tracedecay/src/mcp/tools/handlers/configuration_batch_behavior_tests.rs +++ b/crates/tracedecay/src/mcp/tools/handlers/configuration_batch_behavior_tests.rs @@ -12,9 +12,10 @@ use tracedecay_mcp::JsonRpcResponse; use crate::daemon::ProductionProjectCompositionHarnessV1; -const THRESHOLD_KEY: &str = "feedback.proximity.risk_threshold"; -const DEFAULT_THRESHOLD: u64 = 7_000; -const OVERRIDE_THRESHOLD: u64 = 6_000; +const DAEMON_RESTART_UNSIGNED_KEY: &str = "sync.read_cooldown_secs.v1"; +const DAEMON_RESTART_DEFAULT: u64 = 30; +const DAEMON_RESTART_OVERRIDE: u64 = 45; +const RELATIONSHIP_HINTS_KEY: &str = "feedback.proximity.relationship_hints.v1"; const TIMINGS_KEY: &str = "telemetry.timings.v1"; const BATCH_KEY: &str = "configuration.idempotency.mcp-batch-proof"; const RESTORE_KEY: &str = "configuration.idempotency.mcp-batch-restore"; @@ -222,34 +223,31 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( &harness, &project, "tracedecay_configuration_get", - json!({"key": THRESHOLD_KEY, "format": "json"}), + json!({"key": DAEMON_RESTART_UNSIGNED_KEY, "format": "json"}), ) .await; let (refused, enrolled_payload) = tool_text(&enrolled); - assert!( - !refused, - "initial threshold read refused: {enrolled_payload}" - ); + assert!(!refused, "initial setting read refused: {enrolled_payload}"); let project_id = enrolled_payload["scope"]["project_id"] .as_str() .expect("enrolled project id") .to_owned(); - let threshold = enrolled_payload["outcome"]["value"]["payload"].clone(); + let restart_setting = enrolled_payload["outcome"]["value"]["payload"].clone(); let timings = read_setting(&harness, &project, TIMINGS_KEY).await; - let initial_revision = threshold["revision_id"] + let initial_revision = restart_setting["revision_id"] .as_str() .expect("initial revision") .to_owned(); assert_eq!(initial_revision, "configuration.initial.canonical.v1"); assert_eq!(timings["revision_id"], initial_revision); - assert_eq!(threshold["key"], THRESHOLD_KEY); + assert_eq!(restart_setting["key"], DAEMON_RESTART_UNSIGNED_KEY); assert_eq!(timings["key"], TIMINGS_KEY); assert_eq!( - threshold["effective_value"], - unsigned_value(DEFAULT_THRESHOLD) + restart_setting["effective_value"], + unsigned_value(DAEMON_RESTART_DEFAULT) ); assert_eq!(timings["effective_value"], boolean_value(true)); - assert_default_candidate(&threshold); + assert_default_candidate(&restart_setting); assert_default_candidate(&timings); let layer = project_layer(&project_id); @@ -260,8 +258,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([ set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(OVERRIDE_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_OVERRIDE) ), set_mutation(layer.clone(), TIMINGS_KEY, boolean_value(false)) ]), @@ -309,16 +307,16 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( .to_owned(); assert_ne!(committed_revision, initial_revision); - let committed_threshold = read_setting(&harness, &project, THRESHOLD_KEY).await; + let committed_restart = read_setting(&harness, &project, DAEMON_RESTART_UNSIGNED_KEY).await; let committed_timings = read_setting(&harness, &project, TIMINGS_KEY).await; assert_eq!( - committed_threshold["effective_value"], - unsigned_value(OVERRIDE_THRESHOLD) + committed_restart["effective_value"], + unsigned_value(DAEMON_RESTART_OVERRIDE) ); assert_eq!(committed_timings["effective_value"], boolean_value(false)); - assert_eq!(committed_threshold["revision_id"], committed_revision); + assert_eq!(committed_restart["revision_id"], committed_revision); assert_eq!(committed_timings["revision_id"], committed_revision); - assert_winning_candidate(&committed_threshold, &project_id, &committed_revision); + assert_winning_candidate(&committed_restart, &project_id, &committed_revision); assert_winning_candidate(&committed_timings, &project_id, &committed_revision); let observed = call_tool( @@ -335,11 +333,11 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([{ "component": "configuration.runtime-cache", "desired_revision_id": committed_revision, - "observed_revision_id": committed_revision, - "last_working_revision_id": committed_revision, - "restart_required": false, + "observed_revision_id": "configuration.initial.canonical.v1", + "last_working_revision_id": "configuration.initial.canonical.v1", + "restart_required": true, "activation_error_code": null, - "drift": "current" + "drift": "pending_restart" }]) ); @@ -350,8 +348,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([ set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(OVERRIDE_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_OVERRIDE) ), set_mutation(layer.clone(), TIMINGS_KEY, boolean_value(false)) ]), @@ -369,7 +367,7 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( applied_payload["outcome"]["value"] ); assert_eq!( - read_setting(&harness, &project, THRESHOLD_KEY).await["revision_id"], + read_setting(&harness, &project, DAEMON_RESTART_UNSIGNED_KEY).await["revision_id"], committed_revision ); @@ -380,8 +378,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([ set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(DEFAULT_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_DEFAULT) ), set_mutation(layer.clone(), TIMINGS_KEY, boolean_value(false)) ]), @@ -406,8 +404,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([ set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(OVERRIDE_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_OVERRIDE) ), set_mutation(layer.clone(), TIMINGS_KEY, boolean_value(true)) ]), @@ -453,13 +451,13 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([ set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(DEFAULT_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_DEFAULT) ), set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(OVERRIDE_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_OVERRIDE) ) ]), &committed_revision, @@ -483,8 +481,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([ set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(DEFAULT_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_DEFAULT) ), set_mutation(json!({"kind": "default"}), TIMINGS_KEY, boolean_value(true)) ]), @@ -532,8 +530,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( json!([ set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(DEFAULT_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_DEFAULT) ), set_mutation( layer.clone(), @@ -561,8 +559,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( batch_arguments( json!([set_mutation( project_layer("project.configuration-batch.foreign"), - THRESHOLD_KEY, - unsigned_value(DEFAULT_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_DEFAULT) )]), &committed_revision, "configuration.idempotency.mcp-batch-foreign", @@ -604,8 +602,8 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( let mut unknown_field = batch_arguments( json!([set_mutation( layer.clone(), - THRESHOLD_KEY, - unsigned_value(DEFAULT_THRESHOLD) + DAEMON_RESTART_UNSIGNED_KEY, + unsigned_value(DAEMON_RESTART_DEFAULT) )]), &committed_revision, "configuration.idempotency.mcp-batch-unknown-field", @@ -614,14 +612,14 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( let schema = call_batch(&harness, &project, unknown_field).await; assert_schema_refusal(&schema); - let unchanged_threshold = read_setting(&harness, &project, THRESHOLD_KEY).await; + let unchanged_restart = read_setting(&harness, &project, DAEMON_RESTART_UNSIGNED_KEY).await; let unchanged_timings = read_setting(&harness, &project, TIMINGS_KEY).await; assert_eq!( - unchanged_threshold["effective_value"], - unsigned_value(OVERRIDE_THRESHOLD) + unchanged_restart["effective_value"], + unsigned_value(DAEMON_RESTART_OVERRIDE) ); assert_eq!(unchanged_timings["effective_value"], boolean_value(false)); - assert_eq!(unchanged_threshold["revision_id"], committed_revision); + assert_eq!(unchanged_restart["revision_id"], committed_revision); assert_eq!(unchanged_timings["revision_id"], committed_revision); let restored = call_batch( @@ -629,7 +627,7 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( &project, batch_arguments( json!([ - unset_mutation(layer.clone(), THRESHOLD_KEY), + unset_mutation(layer.clone(), DAEMON_RESTART_UNSIGNED_KEY), unset_mutation(layer, TIMINGS_KEY) ]), &committed_revision, @@ -648,17 +646,97 @@ async fn configuration_batch_applies_both_settings_and_refuses_the_other_inputs( .expect("restored revision") .to_owned(); assert_ne!(restored_revision, committed_revision); - let restored_threshold = read_setting(&harness, &project, THRESHOLD_KEY).await; + let restored_restart = read_setting(&harness, &project, DAEMON_RESTART_UNSIGNED_KEY).await; let restored_timings = read_setting(&harness, &project, TIMINGS_KEY).await; assert_eq!( - restored_threshold["effective_value"], - unsigned_value(DEFAULT_THRESHOLD) + restored_restart["effective_value"], + unsigned_value(DAEMON_RESTART_DEFAULT) ); assert_eq!(restored_timings["effective_value"], boolean_value(true)); - assert_eq!(restored_threshold["revision_id"], restored_revision); + assert_eq!(restored_restart["revision_id"], restored_revision); assert_eq!(restored_timings["revision_id"], restored_revision); - assert_default_candidate(&restored_threshold); + assert_default_candidate(&restored_restart); assert_default_candidate(&restored_timings); harness.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn configuration_batch_activates_a_no_restart_setting_in_the_live_runtime() { + let isolation = TempDir::new().expect("journey isolation"); + let project = isolation.path().join("project"); + initialize_project(&project); + let harness = ProductionProjectCompositionHarnessV1::open(isolation.path(), [project.clone()]) + .await + .expect("production composition"); + + let enrolled = call_tool( + &harness, + &project, + "tracedecay_configuration_get", + json!({"key": RELATIONSHIP_HINTS_KEY, "format": "json"}), + ) + .await; + let (refused, enrolled_payload) = tool_text(&enrolled); + assert!(!refused, "initial setting read refused: {enrolled_payload}"); + let project_id = enrolled_payload["scope"]["project_id"] + .as_str() + .expect("enrolled project id") + .to_owned(); + let initial = enrolled_payload["outcome"]["value"]["payload"].clone(); + let initial_revision = initial["revision_id"] + .as_str() + .expect("initial revision") + .to_owned(); + assert_eq!(initial["effective_value"], boolean_value(true)); + + let applied = call_batch( + &harness, + &project, + batch_arguments( + json!([set_mutation( + project_layer(&project_id), + RELATIONSHIP_HINTS_KEY, + boolean_value(false) + )]), + &initial_revision, + "configuration.idempotency.mcp-activation-proof", + ), + ) + .await; + let (refused, applied_payload) = tool_text(&applied); + assert!(!refused, "activation batch refused: {applied_payload}"); + let committed_revision = applied_payload["outcome"]["value"]["payload"]["result_revision_id"] + .as_str() + .expect("committed revision") + .to_owned(); + assert_ne!(committed_revision, initial_revision); + + let committed = read_setting(&harness, &project, RELATIONSHIP_HINTS_KEY).await; + assert_eq!(committed["effective_value"], boolean_value(false)); + assert_eq!(committed["revision_id"], committed_revision); + + let observed = call_tool( + &harness, + &project, + "tracedecay_configuration_observed_state", + json!({"format": "json"}), + ) + .await; + let (refused, observed_payload) = tool_text(&observed); + assert!(!refused, "observed state refused: {observed_payload}"); + assert_eq!( + observed_payload["outcome"]["value"]["payload"], + json!([{ + "component": "configuration.runtime-cache", + "desired_revision_id": committed_revision, + "observed_revision_id": committed_revision, + "last_working_revision_id": committed_revision, + "restart_required": false, + "activation_error_code": null, + "drift": "current" + }]) + ); + + harness.shutdown().await; +} diff --git a/crates/tracedecay/tests/runtime_acceptance_suite/advisory_runtime_acceptance.rs b/crates/tracedecay/tests/runtime_acceptance_suite/advisory_runtime_acceptance.rs index 4a5d8ff88d6..f7e245a1bc0 100644 --- a/crates/tracedecay/tests/runtime_acceptance_suite/advisory_runtime_acceptance.rs +++ b/crates/tracedecay/tests/runtime_acceptance_suite/advisory_runtime_acceptance.rs @@ -64,8 +64,8 @@ use tracedecay_application::ProjectSourceAccessSnapshot; use tracedecay_application::advisory::fixtures::AdvisoryProximityFixtureEvidenceV1; #[cfg(feature = "test-transport")] use tracedecay_application::advisory::proximity_runtime::{ - CanonicalProximityEvidenceAuthorityV1, CanonicalProximityEvidenceBatchV1, - ProximityRuntimeOutcomeV1, ProximityRuntimeOwnerV1, ProximityThresholdPinV1, + CanonicalProximityEvidenceAuthorityV1, CanonicalProximityEvidenceBatchV1, ProximityPolicyPinV1, + ProximityRuntimeOutcomeV1, ProximityRuntimeOwnerV1, }; #[cfg(feature = "test-transport")] use tracedecay_application::feedback::concrete::open_feedback_runtime; @@ -1962,8 +1962,6 @@ async fn one_saved_edit_cycle_returns_all_four_advisory_pillars_together() { symbol: Some(ci_symbol.symbol.clone()), }, relation_paths: Vec::new(), - // Same file as the saved edit: the shipped owner classifies that as - // an exact overlap, so inclusion never depends on the threshold. warning_class: ProximityWarningClassV1::SameFile, observed_at: UtcMicros(now.0.saturating_sub(1_000_000)), expires_at: UtcMicros(now.0.saturating_add(600_000_000)), @@ -1990,17 +1988,17 @@ async fn one_saved_edit_cycle_returns_all_four_advisory_pillars_together() { (), ) .expect("proximity runtime owner"); - let threshold = ProximityThresholdPinV1::new( + let policy = ProximityPolicyPinV1::new( tracedecay_domain::configuration::ConfigurationRevisionId::new( "configuration.advisory.four-pillar", ) .unwrap(), four_pillar_digest('2'), - 5_000, + true, ) - .expect("effective Plan 20 threshold pin"); + .expect("effective proximity policy pin"); let ProximityRuntimeOutcomeV1::Completed(proximity) = proximity_owner - .evaluate_with_threshold_pin(&context, &proximity_request, &threshold) + .evaluate_with_policy_pin(&context, &proximity_request, &policy) .await else { panic!("recorded concurrent-agent evidence must complete the proximity provider"); diff --git a/dashboard/src/viz/proximity/ProximityPanel.dom.test.tsx b/dashboard/src/viz/proximity/ProximityPanel.dom.test.tsx new file mode 100644 index 00000000000..8384603fa7a --- /dev/null +++ b/dashboard/src/viz/proximity/ProximityPanel.dom.test.tsx @@ -0,0 +1,90 @@ +import { describe, it, expect } from 'vitest'; +import { render } from '@testing-library/react'; +import type { + FeedbackProximityEncounterV1, + FeedbackProximityReadResultV1, +} from '../../contracts/generated.ts'; +import { formatMicrosUtc } from '../../ui/format.ts'; +import type { WorkResult } from '../../workspaces/work/workApi.ts'; +import { ProximityPanel } from './ProximityPanel.tsx'; +import { proximityLabel } from './proximity.ts'; + +const scope = { + project_id: 'project.proximity-panel', + repository_id: 'repository.proximity-panel', + worktree_id: 'worktree.proximity-panel', + branch_ref: 'refs/heads/proximity-panel', + head_commit_id: 'commit.proximity-panel', +}; + +const encounter: FeedbackProximityEncounterV1 = { + encounter_id: `sha256:${'b'.repeat(64)}`, + scope, + interval: { start: 1_700_000_000_000_000, end: 1_700_000_060_000_000 }, + participants: [ + { + source: { provider: 'provider.cursor', session_id: 'session.proximity-panel' }, + agent_id: 'agent.proximity-panel', + worktree_id: 'worktree.proximity-panel', + worktree_root: '/workspace', + branch_ref: 'refs/heads/proximity-panel', + head_revision: 'commit.proximity-panel', + access: 'write', + activity: { start: 1_700_000_000_000_000, end: 1_700_000_060_000_000 }, + address: { + scope, + file: 'file.proximity-panel', + span: { start_byte: 0, end_byte: 5 }, + symbol: null, + }, + }, + ], + relation: { relation_kind: 'overlapping_edit', warning_class: 'same_file' }, + observed_at: 1_700_000_000_000_000, + expires_at: 1_700_000_600_000_000, + coverage: 'complete', +}; + +const complete: WorkResult = { + outcome: 'value', + value: { + state: 'complete', + page: { + scope, + source_generation: 'generation.proximity-panel', + observed_at: encounter.observed_at, + expires_at: encounter.expires_at, + encounters: [encounter], + }, + }, +}; + +function renderPanel(result: WorkResult) { + return render( + undefined} />, + ); +} + +describe('ProximityPanel', () => { + it('renders the encounter interval and relation label without a score', () => { + const { container } = renderPanel(complete); + const text = container.textContent ?? ''; + + expect(text).toContain(formatMicrosUtc(encounter.interval.start)); + expect(text).toContain(formatMicrosUtc(encounter.interval.end)); + expect(text).toContain(proximityLabel(encounter.relation)); + + const scored = [...container.querySelectorAll('*')].filter((element) => + /risk|score|threshold/i.test( + [...element.childNodes] + .filter((node) => node.nodeType === Node.TEXT_NODE) + .map((node) => node.textContent ?? '') + .join(' '), + ), + ); + expect( + scored.map((element) => element.textContent), + 'proximity is evidence, not a risk score', + ).toEqual([]); + }); +});