use super::*; use serde_json::{Value, json}; #[tokio::test] async fn import_context_registration_is_revision_guarded_pending_and_recovers_report() { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let workspace_id = WorkspaceId::new("ws_default"); let operation = test_operation("op_import_pending", 1, OperationStatus::Draft); registry .create_operation(&workspace_id, &operation, None) .await .unwrap(); insert_import_application( &pool, "ws_default", "idem_pending", &[ ( "candidate_create", "createLead", "created", "op_import_pending", Some(1), ), ("candidate_skip", "skipMe", "skipped", "", None), ], ) .await; let initial = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); assert_eq!( initial.operation_id, Some(operation.id.clone()), "without an import context the generic projection auto-selects the draft" ); // A forged application identity has no committed immutable apply report. assert!(matches!( registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_missing", plan_digest: &"b".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap_err(), RegistryError::OnboardingImportApplicationUnavailable )); assert_eq!(context_count(&pool).await, 0); // A mismatched plan digest is rejected without mutation. assert!(matches!( registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_pending", plan_digest: &"d".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap_err(), RegistryError::OnboardingImportApplicationUnavailable )); assert_eq!(context_count(&pool).await, 0); // Stale revision cannot register a context. assert!(matches!( registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_pending", plan_digest: &"b".repeat(64), expected_revision: initial.revision + 1, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap_err(), RegistryError::OnboardingStaleRevision )); assert_eq!(context_count(&pool).await, 0); // A valid registration stores a pending context and suppresses the // generic automatic Operation selection. let registered = registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_pending", plan_digest: &"b".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); assert_eq!(registered.operation_id, None); assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1); // Recovery re-reads the immutable report and all outcome choices. let context = registry .get_onboarding_import_context(&workspace_id) .await .unwrap() .expect("pending import context must be recoverable"); assert!(context.selected_operation_id.is_none()); assert_eq!(context.plan_digest, "b".repeat(64)); assert_eq!( context.report.get("schema_version").and_then(Value::as_str), Some("import-plan-apply-report-v1") ); let created = context .choices .iter() .find(|choice| choice.outcome == "created") .expect("created choice"); assert!(created.selectable); assert_eq!(created.operation_id.as_deref(), Some("op_import_pending")); let skipped = context .choices .iter() .find(|choice| choice.outcome == "skipped") .expect("skipped choice"); assert!( !skipped.selectable, "blocked outcomes stay visible but not selectable" ); // Exact re-registration is idempotent and keeps the single durable row. let again = registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_pending", plan_digest: &"b".repeat(64), expected_revision: registered.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); assert_eq!(again.operation_id, None); assert_eq!(context_count(&pool).await, 1); assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1); database.cleanup().await; } #[tokio::test] async fn import_selection_requires_exact_successful_outcome_and_live_draft() { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let workspace_id = WorkspaceId::new("ws_default"); let anchor = test_operation("op_import_anchor", 1, OperationStatus::Draft); registry .create_operation(&workspace_id, &anchor, None) .await .unwrap(); let later = test_operation("op_import_later", 1, OperationStatus::Draft); registry .create_operation(&workspace_id, &later, None) .await .unwrap(); insert_import_application( &pool, "ws_default", "idem_select", &[ ( "candidate_anchor", "createLead", "created", "op_import_anchor", Some(1), ), ( "candidate_later", "createTask", "created", "op_import_later", Some(1), ), ], ) .await; let initial = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_select", plan_digest: &"b".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); let pending = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); // Wrong application identity cannot select against this context. assert!(matches!( registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_other", plan_digest: &"b".repeat(64), operation_id: &anchor.id, operation_version: 1, expected_revision: pending.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap_err(), RegistryError::OnboardingImportContextUnavailable )); // A forged operation that is not a successful outcome of the report. assert!(matches!( registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_select", plan_digest: &"b".repeat(64), operation_id: &crank_core::OperationId::new("op_forged"), operation_version: 1, expected_revision: pending.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap_err(), RegistryError::OnboardingImportDraftUnavailable )); // A version drift from the exact successful outcome is rejected. assert!(matches!( registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_select", plan_digest: &"b".repeat(64), operation_id: &anchor.id, operation_version: 7, expected_revision: pending.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap_err(), RegistryError::OnboardingImportDraftUnavailable )); assert_eq!(selected_version(&pool).await, None); // A foreign workspace with no registered context cannot claim it. create_workspace(®istry, "ws_import_other", "import-other").await; let other = WorkspaceId::new("ws_import_other"); let other_revision = registry .get_onboarding_projection(&other) .await .unwrap() .revision; assert!(matches!( registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &other, application_idempotency_key: "idem_select", plan_digest: &"b".repeat(64), operation_id: &anchor.id, operation_version: 1, expected_revision: other_revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap_err(), RegistryError::OnboardingImportContextUnavailable )); assert_eq!(selected_version(&pool).await, None); // A valid selection anchors the exact Draft version. let selected = registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_select", plan_digest: &"b".repeat(64), operation_id: &anchor.id, operation_version: 1, expected_revision: pending.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); assert_eq!(selected.operation_id, Some(anchor.id.clone())); assert_eq!(selected_version(&pool).await, Some(1)); // A second, otherwise eligible import Draft must not replace the explicit // target. let anchored = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); assert_eq!(anchored.operation_id, Some(anchor.id.clone())); // A new Draft version of the selected operation is surfaced as drift, not // silently rebound. let snapshot = test_operation("op_import_anchor", 2, OperationStatus::Draft); registry .create_version(CreateVersionRequest { workspace_id: &workspace_id, snapshot: &snapshot, change_note: None, created_by: None, }) .await .unwrap(); let drifted = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); assert_eq!(drifted.operation_id, Some(anchor.id.clone())); assert_eq!( selected_version(&pool).await, Some(1), "the anchored import version must not drift with a new Draft" ); let context = registry .get_onboarding_import_context(&workspace_id) .await .unwrap() .unwrap(); assert_eq!( context.drift.as_ref().map(|drift| drift.reason.as_str()), Some("selected_operation_version_drift") ); // Reset clears the durable import context but keeps the evidence boundary. let _ = registry .reset_onboarding_selection(&workspace_id, drifted.revision, OffsetDateTime::now_utc()) .await .unwrap(); assert_eq!(context_count(&pool).await, 0); database.cleanup().await; } #[tokio::test] async fn import_funnel_milestones_require_exact_public_call() { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let workspace_id = WorkspaceId::new("ws_default"); let operation = test_operation("op_import_funnel", 1, OperationStatus::Draft); registry .create_operation(&workspace_id, &operation, None) .await .unwrap(); insert_import_application( &pool, "ws_default", "idem_funnel", &[( "candidate", "createLead", "created", "op_import_funnel", Some(1), )], ) .await; let initial = registry .get_onboarding_projection(&workspace_id) .await .unwrap(); let registered = registry .register_onboarding_import_context(RegisterOnboardingImportContextRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_funnel", plan_digest: &"b".repeat(64), expected_revision: initial.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1); assert_eq!(event_count(&pool, "onboarding_import_published").await, 0); assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 0); let selected = registry .select_onboarding_import_draft(SelectOnboardingImportDraftRequest { workspace_id: &workspace_id, application_idempotency_key: "idem_funnel", plan_digest: &"b".repeat(64), operation_id: &operation.id, operation_version: 1, expected_revision: registered.revision, occurred_at: OffsetDateTime::now_utc(), }) .await .unwrap(); assert_eq!(selected.operation_id, Some(operation.id.clone())); // Publish the exact selected operation/version. let published_at = OffsetDateTime::now_utc(); registry .publish_operation(PublishRequest { workspace_id: &workspace_id, operation_id: &operation.id, version: 1, published_at: &published_at, published_by: Some("onboarding-funnel-test"), }) .await .unwrap(); assert_eq!( event_count(&pool, "onboarding_import_published").await, 1, "publishing the explicitly selected version materializes its funnel event immediately" ); let (agent_id, key_id) = attach_published_agent_and_key( ®istry, &operation.id, "agent_import_funnel", "pk_import_funnel", ) .await; // Agent publication alone must not activate the funnel milestone. registry .ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc()) .await .unwrap(); assert_eq!(event_count(&pool, "onboarding_import_published").await, 1); assert_eq!( event_count(&pool, "onboarding_agent_activated").await, 0, "Agent publication without a public call is not activation" ); // The authoritative successful public first call on the exact selected // operation/version with its Agent/key binding activates the milestone. record_onboarding_test_and_call( ®istry, &operation.id, &agent_id, &key_id, "import_funnel", OffsetDateTime::now_utc(), ) .await; let projection = registry .ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc()) .await .unwrap(); assert!( projection.completed, "the selected import path must reach the authoritative terminal tuple" ); assert_eq!(event_count(&pool, "onboarding_import_published").await, 1); assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 1); // The conversion milestones are anchored to authoritative evidence, not to // the observation time: publication uses the exact selected version's // `published_at`, activation uses the exact successful public first call. let published_event_at: OffsetDateTime = sqlx::query_scalar( "select occurred_at from product_events where workspace_id = 'ws_default' and event_name = 'onboarding_import_published'", ) .fetch_one(&pool) .await .unwrap(); assert_eq!( published_event_at, super::truncate_to_micros(published_at), "import-published must inherit the exact selected version published_at" ); let first_call_at = projection .first_call_at .expect("the completed projection carries the authoritative first call"); let activated_event_at: OffsetDateTime = sqlx::query_scalar( "select occurred_at from product_events where workspace_id = 'ws_default' and event_name = 'onboarding_agent_activated'", ) .fetch_one(&pool) .await .unwrap(); assert_eq!( activated_event_at, first_call_at, "agent-activated must inherit the exact successful public first_call_at" ); let properties: Vec = sqlx::query_scalar( "select properties_json::text from product_events where workspace_id = $1 and event_name in ( 'onboarding_import_eligible', 'onboarding_import_published', 'onboarding_agent_activated')", ) .bind("ws_default") .fetch_all(&pool) .await .unwrap(); assert_eq!(properties.len(), 3); for value in properties { let stored: Value = serde_json::from_str(&value).unwrap(); let object = stored .as_object() .expect("server event properties are bounded objects"); let mut keys: Vec<&str> = object.keys().map(String::as_str).collect(); keys.sort_unstable(); assert_eq!( keys, ["eligible", "eligible_since", "milestone"], "server-owned properties must never carry source bytes, credentials or actor IDs" ); assert!(!value.contains("ws_default")); assert!(!value.contains("openapi:")); assert!(!value.contains("secret")); } // Every funnel milestone inherits the authoritative eligible cohort; none // is appended with `eligible=null/false`. let cohort: Vec<(String, bool, Option)> = sqlx::query_as( "select event_name, (properties_json ->> 'eligible')::boolean, properties_json ->> 'eligible_since' from product_events where workspace_id = $1 and event_name in ( 'onboarding_import_eligible', 'onboarding_import_published', 'onboarding_agent_activated') order by event_name", ) .bind("ws_default") .fetch_all(&pool) .await .unwrap(); assert_eq!(cohort.len(), 3); let eligible_since = cohort .iter() .find(|(name, _, _)| name == "onboarding_import_eligible") .and_then(|(_, _, since)| since.clone()) .expect("eligibility denominator has eligible_since"); for (name, eligible, since) in &cohort { assert!(*eligible, "{name} must inherit eligible=true"); assert_eq!( since.as_deref(), Some(eligible_since.as_str()), "{name} must inherit the authoritative eligible_since" ); } let rolled_up: i64 = sqlx::query_scalar( "select events_total from product_event_daily_rollups where workspace_id = $1 and event_name = 'onboarding_import_published'", ) .bind("ws_default") .fetch_one(&pool) .await .unwrap(); assert_eq!(rolled_up, 1); // The rollup day follows the authoritative evidence day, so a publication // observed later still rolls up on its exact published_at date. let rollup_day: String = sqlx::query_scalar( "select day::text from product_event_daily_rollups where workspace_id = $1 and event_name = 'onboarding_import_published'", ) .bind("ws_default") .fetch_one(&pool) .await .unwrap(); assert_eq!(rollup_day, published_at.date().to_string()); // Re-observing the projection is idempotent: milestones stay single. registry .ensure_onboarding_eligibility(&workspace_id, OffsetDateTime::now_utc()) .await .unwrap(); assert_eq!(event_count(&pool, "onboarding_import_eligible").await, 1); assert_eq!(event_count(&pool, "onboarding_import_published").await, 1); assert_eq!(event_count(&pool, "onboarding_agent_activated").await, 1); database.cleanup().await; } pub(super) async fn attach_published_agent_and_key( registry: &crank_registry::PostgresRegistry, operation_id: &crank_core::OperationId, agent_id: &str, key_id: &str, ) -> (crank_core::AgentId, PlatformApiKeyId) { let workspace_id = WorkspaceId::new("ws_default"); let agent = test_agent(agent_id, AgentStatus::Draft); let version = test_agent_version(&agent.id, 1, AgentStatus::Draft); let bindings = vec![AgentOperationBinding { operation_id: operation_id.clone(), operation_version: 1, tool_name: "create_lead".to_owned(), tool_title: "Create lead".to_owned(), tool_description_override: None, enabled: true, }]; registry .create_agent(CreateAgentRequest { agent: &agent, version: &version, bindings: &bindings, }) .await .unwrap(); registry .publish_agent(PublishAgentRequest { workspace_id: &workspace_id, agent_id: &agent.id, version: 1, published_at: &OffsetDateTime::now_utc(), published_by: Some("onboarding-funnel-test"), expected_state: None, }) .await .unwrap(); let key_id = PlatformApiKeyId::new(key_id); let key = PlatformApiKey { id: key_id.clone(), workspace_id, agent_id: Some(agent.id.clone()), key_kind: PlatformApiKeyKind::McpClient, name: format!("onboarding-{key_id}-key"), prefix: format!("crk_{}", key_id.as_str()), scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], status: PlatformApiKeyStatus::Active, created_at: OffsetDateTime::now_utc(), last_used_at: None, expires_at: None, allowed_origins: Vec::new(), }; registry .create_platform_api_key(CreatePlatformApiKeyRequest { api_key: &key, secret_hash: "funnel-secret-hash", }) .await .unwrap(); (agent.id, key_id) } async fn context_count(pool: &sqlx::PgPool) -> i64 { context_count_for(pool, "ws_default").await } pub(super) async fn context_count_for(pool: &sqlx::PgPool, workspace_id: &str) -> i64 { sqlx::query_scalar("select count(*) from onboarding_import_selections where workspace_id = $1") .bind(workspace_id) .fetch_one(pool) .await .unwrap() } pub(super) async fn selected_version(pool: &sqlx::PgPool) -> Option { sqlx::query_scalar( "select selected_operation_version from onboarding_import_selections where workspace_id = 'ws_default'", ) .fetch_optional(pool) .await .unwrap() .flatten() } pub(super) async fn event_count(pool: &sqlx::PgPool, event_name: &str) -> i64 { sqlx::query_scalar( "select count(*) from product_events where workspace_id = 'ws_default' and event_name = $1", ) .bind(event_name) .fetch_one(pool) .await .unwrap() } pub(super) type OutcomeSpec<'a> = (&'a str, &'a str, &'a str, &'a str, Option); pub(super) async fn insert_import_application( pool: &sqlx::PgPool, workspace_id: &str, idempotency_key: &str, outcomes: &[OutcomeSpec<'_>], ) { let outcomes = outcomes .iter() .map(|(key, name, outcome, operation_id, version)| { json!({ "key": key, "name": name, "outcome": outcome, "operation_id": if operation_id.is_empty() { Value::Null } else { Value::String((*operation_id).to_owned()) }, "version": version, }) }) .collect::>(); let report = json!({ "schema_version": "import-plan-apply-report-v1", "status": "applied", "plan_id": "plan_import", "plan_digest": "b".repeat(64), "job_id": "job_import", "idempotency_key": idempotency_key, "source_id": "source_import", "source_digest": "c".repeat(64), "dependencies": [], "counts": {"created": 1, "versioned": 0, "renamed": 0, "skipped": 0, "excluded": 0, "rejected": 0}, "outcomes": outcomes, "summary": "import applied", "recovery": "none", "applied_at": "2026-10-03T00:00:00Z", }); sqlx::query( "insert into import_plan_applications ( workspace_id, idempotency_key, plan_id, plan_digest, report, created_at ) values ($1, $2, 'plan_import', $3, $4, now())", ) .bind(workspace_id) .bind(idempotency_key) .bind("b".repeat(64)) .bind(report) .execute(pool) .await .unwrap(); }