//! Story 3.7 / AC04 regression: typed exact Resource bindings Agent (V18). //! //! Проверяется на реальном PostgreSQL, что integrity держится **схемой**, а не только //! JSON-ответом API: //! - workspace-равенство на обоих концах composite FK (Agent и Resource publication); //! - published Agent Version bindings иммутабельны (V9 guard function); //! - закреплённая exact v1 не меняется после публикации Resource v2; //! - failed save/publish откатываются без partial rows/pointer/revision; //! - published catalog reader отдаёт resources из того же снимка, что //! agent_version/catalog_revision/tools. use std::{ fs, os::unix::fs::PermissionsExt, path::PathBuf, sync::atomic::{AtomicU64, Ordering}, }; use super::common::*; mod archive_race; mod revocation_race; mod revocation_write_race; mod rollback; use crank_artifacts::{ArtifactStore, RegisteredArtifact}; use crank_core::ids::ResourceId; use crank_core::{Agent, AgentStatus, AgentVersion, Workspace, WorkspaceId, WorkspaceStatus}; use crank_registry::model::resource::{ CreateResourceDraftRequest, PublishResourceVersionRequest, UpdateResourceDraftRequest, }; use crank_registry::{ AgentResourceBinding, CreateAgentRequest, CreateWorkspaceRequest, PostgresRegistry, PublishAgentRequest, SaveAgentCatalogConfigRequest, }; use serde_json::json; use time::OffsetDateTime; static NEXT_ROOT: AtomicU64 = AtomicU64::new(0); struct TestRoot(PathBuf); impl TestRoot { fn new(name: &str) -> Self { let path = std::env::temp_dir().join(format!( "crank-registry-agent-resource-bindings-{name}-{}-{}", std::process::id(), NEXT_ROOT.fetch_add(1, Ordering::Relaxed) )); fs::create_dir(&path).expect("private artifact root must be creatable"); fs::set_permissions(&path, fs::Permissions::from_mode(0o700)) .expect("private artifact root must be 0700"); Self(path) } } impl Drop for TestRoot { fn drop(&mut self) { let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700)); let _ = fs::remove_dir_all(&self.0); } } struct Sandbox { registry: PostgresRegistry, pool: sqlx::PgPool, store: ArtifactStore, _root: TestRoot, database: TestDatabase, } async fn sandbox(name: &str) -> Sandbox { let database = TestDatabase::new().await; let registry = database.registry().await; let pool = database.raw_pool().await; let root = TestRoot::new(name); let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open"); Sandbox { registry, pool, store, _root: root, database, } } impl Sandbox { async fn cleanup(&self) { self.database.cleanup().await; } } fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact { sandbox .store .put_registered(bytes) .expect("fixture bytes must be registered durably") } async fn seed_workspace(sandbox: &Sandbox, workspace_id: &str, slug: &str) { let now = OffsetDateTime::now_utc(); sandbox .registry .create_workspace(CreateWorkspaceRequest { workspace: &Workspace { id: WorkspaceId::new(workspace_id), slug: slug.to_owned(), display_name: slug.to_owned(), status: WorkspaceStatus::Active, settings: json!({}), created_at: now, updated_at: now, }, }) .await .expect("synthetic workspace must be created"); } /// Draft → Published Resource v1 через принятый Story 3.6/3.7 registry-контракт. async fn published_resource( sandbox: &Sandbox, workspace_id: &str, resource_id: &str, uri: &str, bytes: &[u8], ) -> ResourceId { let id = ResourceId::new(resource_id); sandbox .registry .create_resource_draft(CreateResourceDraftRequest { workspace_id: WorkspaceId::new(workspace_id), resource_id: id.clone(), uri: uri.to_owned(), name: "binding_doc".to_owned(), description: String::new(), kind: "text".to_owned(), mime_type: "text/plain".to_owned(), sensitivity: "internal".to_owned(), artifact: registered(sandbox, bytes), created_at: OffsetDateTime::now_utc(), }) .await .expect("resource draft must be created"); publish_current_resource(sandbox, workspace_id, &id, bytes).await; id } async fn publish_current_resource( sandbox: &Sandbox, workspace_id: &str, resource_id: &ResourceId, bytes: &[u8], ) -> u32 { let current = sandbox .registry .get_resource_draft(workspace_id, resource_id) .await .expect("draft must be readable"); let publication = sandbox .registry .publish_resource_version(PublishResourceVersionRequest { workspace_id: WorkspaceId::new(workspace_id), resource_id: resource_id.clone(), expected_updated_at: current.resource.updated_at, expected_version: current.version.version, expected_digest: current.version.digest.clone(), expected_size_bytes: current.version.size_bytes, artifact: registered(sandbox, bytes), published_at: OffsetDateTime::now_utc(), }) .await .expect("valid current draft must publish"); publication.version } async fn draft_next_resource_version( sandbox: &Sandbox, workspace_id: &str, resource_id: &ResourceId, bytes: &[u8], ) { let current = sandbox .registry .get_resource_draft(workspace_id, resource_id) .await .expect("draft must be readable"); sandbox .registry .update_resource_draft(UpdateResourceDraftRequest { workspace_id: WorkspaceId::new(workspace_id), resource_id: resource_id.clone(), description: "edited after publication".to_owned(), mime_type: "text/plain".to_owned(), sensitivity: "internal".to_owned(), expected_updated_at: current.resource.updated_at, artifact: registered(sandbox, bytes), }) .await .expect("draft edit after publication must succeed"); } async fn create_draft_agent( sandbox: &Sandbox, workspace_id: &str, agent_id: &str, slug: &str, ) -> crank_core::AgentId { let id = crank_core::AgentId::new(agent_id); let now = OffsetDateTime::now_utc(); let agent = Agent { id: id.clone(), workspace_id: WorkspaceId::new(workspace_id), slug: slug.to_owned(), display_name: slug.to_owned(), description: "Story 3.7 typed binding fixture".to_owned(), status: AgentStatus::Draft, current_draft_version: 1, latest_published_version: None, created_at: now, updated_at: now, published_at: None, }; let version = AgentVersion { agent_id: id.clone(), version: 1, status: AgentStatus::Draft, instructions: json!({}), tool_selection_policy: Default::default(), created_at: now, }; sandbox .registry .create_agent(CreateAgentRequest { agent: &agent, version: &version, bindings: &[], }) .await .expect("draft Agent must be created"); id } async fn save_resource_bindings( sandbox: &Sandbox, workspace_id: &str, agent_id: &crank_core::AgentId, bindings: &[AgentResourceBinding], ) -> Result<(), crank_registry::RegistryError> { sandbox .registry .save_agent_catalog_config(SaveAgentCatalogConfigRequest { workspace_id: &WorkspaceId::new(workspace_id), agent_id, agent_version: 1, bindings: &[], tool_selection_policy: &Default::default(), resource_bindings: bindings, expected_state: None, }) .await } async fn binding_rows(sandbox: &Sandbox, agent_id: &str) -> i64 { sqlx::query_scalar("select count(*) from agent_resource_bindings where agent_id = $1") .bind(agent_id) .fetch_one(&sandbox.pool) .await .expect("binding rows must be queryable") } #[tokio::test] async fn story37_v18_typed_fk_enforces_workspace_on_both_ends() { let sandbox = sandbox("v18_fk_scope").await; seed_workspace(&sandbox, "ws_other", "other").await; let own = published_resource( &sandbox, "ws_default", "res_v18_default", "crank://v18/default", b"default v1", ) .await; let foreign = published_resource( &sandbox, "ws_other", "res_v18_foreign", "crank://v18/foreign", b"foreign v1", ) .await; let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_fk", "v18-fk").await; let other_agent = create_draft_agent(&sandbox, "ws_other", "agent_v18_other", "v18-other").await; let foreign_binding = AgentResourceBinding { resource_id: foreign.clone(), resource_version: 1, }; // Чужой Agent в binding.workspace_id отвергается composite FK на Agent-конце. let agent_scope = sqlx::query( "insert into agent_resource_bindings (workspace_id, agent_id, agent_version, resource_id, resource_version) values ('ws_default', $1, 1, $2, 1)", ) .bind(other_agent.as_str()) .bind(own.as_str()) .execute(&sandbox.pool) .await .expect_err("a foreign-workspace Agent must be rejected by the Agent-side FK"); assert_eq!( database_error_code(&agent_scope), "23503", "Agent workspace mismatch must be a foreign-key violation: {agent_scope}" ); // Чужая Resource publication отвергается composite FK на Resource-конце. let resource_scope = sqlx::query( "insert into agent_resource_bindings (workspace_id, agent_id, agent_version, resource_id, resource_version) values ('ws_default', $1, 1, $2, 1)", ) .bind(agent.as_str()) .bind(foreign_binding.resource_id.as_str()) .execute(&sandbox.pool) .await .expect_err("a foreign-workspace Resource publication must be rejected"); assert_eq!( database_error_code(&resource_scope), "23503", "Resource workspace mismatch must be a foreign-key violation: {resource_scope}" ); // Positive control: та же вставка в своём workspace проходит и видна читателю. save_resource_bindings( &sandbox, "ws_default", &agent, &[AgentResourceBinding { resource_id: own.clone(), resource_version: 1, }], ) .await .expect("a same-workspace exact binding must be accepted"); let record = sandbox .registry .get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1) .await .expect("agent version must be readable") .expect("agent version must exist"); assert_eq!( record.resource_bindings, vec![AgentResourceBinding { resource_id: own, resource_version: 1 }] ); assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 1); sandbox.cleanup().await; } fn database_error_code(error: &sqlx::Error) -> String { match error { sqlx::Error::Database(database) => database.code().unwrap_or_default().to_string(), other => panic!("expected a database error, got {other}"), } } #[tokio::test] async fn story37_v18_published_agent_resource_bindings_are_immutable() { let sandbox = sandbox("v18_immutable").await; let resource = published_resource( &sandbox, "ws_default", "res_v18_immutable", "crank://v18/immutable", b"immutable v1", ) .await; let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_immutable", "v18-imm").await; save_resource_bindings( &sandbox, "ws_default", &agent, &[AgentResourceBinding { resource_id: resource.clone(), resource_version: 1, }], ) .await .expect("draft binding must be saved"); sandbox .registry .publish_agent(PublishAgentRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &agent, version: 1, published_at: &OffsetDateTime::now_utc(), published_by: None, expected_state: None, }) .await .expect("resource-only Agent must publish at registry level"); let update = sqlx::query( "update agent_resource_bindings set resource_version = 2 where agent_id = $1 and agent_version = 1", ) .bind(agent.as_str()) .execute(&sandbox.pool) .await .expect_err("a published Agent binding must not be updated"); assert_eq!( database_error_code(&update), "23514", "immutability guard must raise a check violation: {update}" ); let delete = sqlx::query("delete from agent_resource_bindings where agent_id = $1") .bind(agent.as_str()) .execute(&sandbox.pool) .await .expect_err("a published Agent binding must not be deleted"); assert_eq!( database_error_code(&delete), "23514", "immutability guard must reject deletes: {delete}" ); assert_eq!( binding_rows(&sandbox, agent.as_str()).await, 1, "refused mutations must keep the published snapshot" ); sandbox.cleanup().await; } #[tokio::test] async fn story37_v18_published_binding_cannot_move_to_a_draft_agent_or_version() { let sandbox = sandbox("v18_immutable_move").await; let resource = published_resource( &sandbox, "ws_default", "res_v18_move", "crank://v18/move", b"move v1", ) .await; let published_agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_move_pub", "v18-move-pub").await; let draft_agent = create_draft_agent( &sandbox, "ws_default", "agent_v18_move_draft", "v18-move-draft", ) .await; save_resource_bindings( &sandbox, "ws_default", &published_agent, &[AgentResourceBinding { resource_id: resource.clone(), resource_version: 1, }], ) .await .expect("draft binding must be saved"); sandbox .registry .publish_agent(PublishAgentRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &published_agent, version: 1, published_at: &OffsetDateTime::now_utc(), published_by: None, expected_state: None, }) .await .expect("resource-only Agent must publish"); // Перенос Published snapshot -> Draft Agent другого id: оба composite FK остаются // валидными (тот же workspace), поэтому отказать обязан immutable guard по OLD-ключу. let to_draft_agent = sqlx::query( "update agent_resource_bindings set agent_id = $1 where agent_id = $2 and agent_version = 1", ) .bind(draft_agent.as_str()) .bind(published_agent.as_str()) .execute(&sandbox.pool) .await .expect_err("moving a published binding to a Draft Agent must be rejected"); assert_eq!( database_error_code(&to_draft_agent), "23514", "V18 guard must reject relocation away from the published source: {to_draft_agent}" ); // Draft-версия того же Agent создаётся штатным editable fork (v2 без bindings). let forked = sandbox .registry .save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &published_agent, agent_version: 1, bindings: &[], tool_selection_policy: &Default::default(), resource_bindings: &[], expected_state: None, }) .await .expect("editing a published Agent must fork a Draft version"); assert_eq!(forked, 2, "editable fork must create Agent version 2"); let to_draft_version = sqlx::query( "update agent_resource_bindings set agent_version = $1 where agent_id = $2 and agent_version = 1", ) .bind(i32::try_from(forked).expect("forked version must fit the DB integer domain")) .bind(published_agent.as_str()) .execute(&sandbox.pool) .await .expect_err("moving a published binding to a Draft version must be rejected"); assert_eq!( database_error_code(&to_draft_version), "23514", "V18 guard must reject relocation to a Draft version: {to_draft_version}" ); draft_next_resource_version(&sandbox, "ws_default", &resource, b"move v2").await; assert_eq!( publish_current_resource(&sandbox, "ws_default", &resource, b"move v2").await, 2 ); // NEW-конец тоже защищён: нельзя добавить binding в уже опубликованный snapshot. let insert_into_published = sqlx::query( "insert into agent_resource_bindings (workspace_id, agent_id, agent_version, resource_id, resource_version) values ('ws_default', $1, 1, $2, 2)", ) .bind(published_agent.as_str()) .bind(resource.as_str()) .execute(&sandbox.pool) .await .expect_err("inserting a binding into a published Agent version must be rejected"); assert_eq!( database_error_code(&insert_into_published), "23514", "V18 guard must reject new rows for a published version: {insert_into_published}" ); // Positive control: Draft binding по-прежнему изменяем (обычный UPDATE). save_resource_bindings( &sandbox, "ws_default", &draft_agent, &[AgentResourceBinding { resource_id: resource.clone(), resource_version: 1, }], ) .await .expect("a Draft Agent binding must be accepted"); let draft_move = sqlx::query( "update agent_resource_bindings set resource_version = 2 where agent_id = $1 and agent_version = 1", ) .bind(draft_agent.as_str()) .execute(&sandbox.pool) .await .expect("a Draft binding must remain mutable"); assert_eq!(draft_move.rows_affected(), 1); // Отказы не тронули published snapshot и каталог. assert_eq!(binding_rows(&sandbox, published_agent.as_str()).await, 1); let pinned = sandbox .registry .get_agent_version(&WorkspaceId::new("ws_default"), &published_agent, 1) .await .expect("agent version must be readable") .expect("agent version must exist"); assert_eq!( pinned.resource_bindings, vec![AgentResourceBinding { resource_id: resource.clone(), resource_version: 1 }], "refused relocations must keep the published exact v1" ); let catalog = sandbox .registry .get_published_agent_catalog_by_slug("default", "v18-move-pub") .await .expect("published catalog must be readable"); assert_eq!(catalog.agent_version, 1); assert_eq!( catalog.resources, vec![AgentResourceBinding { resource_id: resource, resource_version: 1 }], "the published catalog must keep the original exact snapshot" ); sandbox.cleanup().await; } #[tokio::test] async fn story37_v18_exact_v1_survives_resource_v2_and_catalog_reader_is_coherent() { let sandbox = sandbox("v18_exact_v1").await; let resource = published_resource( &sandbox, "ws_default", "res_v18_exact", "crank://v18/exact", b"exact v1", ) .await; let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_exact", "v18-exact").await; save_resource_bindings( &sandbox, "ws_default", &agent, &[AgentResourceBinding { resource_id: resource.clone(), resource_version: 1, }], ) .await .expect("draft exact v1 must be saved"); sandbox .registry .publish_agent(PublishAgentRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &agent, version: 1, published_at: &OffsetDateTime::now_utc(), published_by: None, expected_state: None, }) .await .expect("Agent must publish"); let summary_before = sandbox .registry .get_agent_summary(&WorkspaceId::new("ws_default"), &agent) .await .expect("summary must be readable") .expect("summary must exist"); draft_next_resource_version(&sandbox, "ws_default", &resource, b"exact v2").await; assert_eq!( publish_current_resource(&sandbox, "ws_default", &resource, b"exact v2").await, 2, "the edited Draft must publish as exact v2" ); let pinned = sandbox .registry .get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1) .await .expect("agent version must be readable") .expect("agent version must exist"); assert_eq!( pinned.resource_bindings, vec![AgentResourceBinding { resource_id: resource.clone(), resource_version: 1 }], "Resource v2 must not replace the pinned exact v1" ); let summary_after = sandbox .registry .get_agent_summary(&WorkspaceId::new("ws_default"), &agent) .await .expect("summary must be readable") .expect("summary must exist"); assert_eq!( summary_after.catalog_revision, summary_before.catalog_revision, "a Resource publication must not bump the Agent catalog_revision" ); let catalog = sandbox .registry .get_published_agent_catalog_by_slug("default", "v18-exact") .await .expect("published catalog must be readable"); assert_eq!( catalog.agent_version, 1, "catalog must keep the published Agent version" ); assert_eq!( catalog.catalog_revision, format!( "agent-version-1-catalog-revision-{}", summary_after.catalog_revision ), "resources and revision must come from the same published snapshot" ); assert_eq!( catalog.resources, vec![AgentResourceBinding { resource_id: resource, resource_version: 1 }], "catalog reader must expose the exact pinned Resource Version" ); // Явный republish Agent фиксирует новый snapshot, старый остаётся exact v1. sandbox .registry .save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &agent, agent_version: 1, bindings: &[], tool_selection_policy: &Default::default(), resource_bindings: &[AgentResourceBinding { resource_id: ResourceId::new("res_v18_exact"), resource_version: 2, }], expected_state: None, }) .await .expect("editing a published Agent must fork a new Draft with v2"); sandbox .registry .publish_agent(PublishAgentRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &agent, version: 2, published_at: &OffsetDateTime::now_utc(), published_by: None, expected_state: None, }) .await .expect("republished Agent version 2 must publish"); let catalog_v2 = sandbox .registry .get_published_agent_catalog_by_slug("default", "v18-exact") .await .expect("published catalog must be readable"); assert_eq!(catalog_v2.agent_version, 2); assert_eq!( catalog_v2.resources, vec![AgentResourceBinding { resource_id: ResourceId::new("res_v18_exact"), resource_version: 2 }], "an explicit republish must switch the catalog to the new exact snapshot" ); let still_v1 = sandbox .registry .get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1) .await .expect("agent version must be readable") .expect("agent version must exist"); assert_eq!( still_v1.resource_bindings, vec![AgentResourceBinding { resource_id: ResourceId::new("res_v18_exact"), resource_version: 1 }], "the earlier published snapshot must stay exact v1" ); sandbox.cleanup().await; } #[tokio::test] async fn story37_v18_failed_write_and_publication_leave_no_partial_state() { let sandbox = sandbox("v18_rollback").await; let resource = published_resource( &sandbox, "ws_default", "res_v18_rollback", "crank://v18/rollback", b"rollback v1", ) .await; // Draft v2 существует, но не опубликован: exact version недоступна для binding. draft_next_resource_version(&sandbox, "ws_default", &resource, b"rollback v2").await; let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_rollback", "v18-rb").await; let failed_save = save_resource_bindings( &sandbox, "ws_default", &agent, &[AgentResourceBinding { resource_id: resource.clone(), resource_version: 2, }], ) .await .expect_err("an unpublished Resource version must fail the write"); assert!( matches!(failed_save, crank_registry::RegistryError::Storage(_)), "the FK refusal must surface as a storage error: {failed_save}" ); assert_eq!( binding_rows(&sandbox, agent.as_str()).await, 0, "a failed save must not leave partial binding rows" ); let versions: i64 = sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1") .bind(agent.as_str()) .fetch_one(&sandbox.pool) .await .expect("agent versions must be queryable"); assert_eq!(versions, 1, "a failed save must not add a version row"); let summary = sandbox .registry .get_agent_summary(&WorkspaceId::new("ws_default"), &agent) .await .expect("summary must be readable") .expect("summary must exist"); assert_eq!( summary.current_draft_version, 1, "a failed save must not move the Draft pointer" ); // Stale publication: отказ до записи, pointer/revision/rows не меняются. save_resource_bindings( &sandbox, "ws_default", &agent, &[AgentResourceBinding { resource_id: resource.clone(), resource_version: 1, }], ) .await .expect("a published exact v1 must be accepted"); let stale_state = crank_registry::AgentStateExpectation { status: AgentStatus::Draft, current_draft_version: 1, latest_published_version: None, catalog_revision: summary.catalog_revision, updated_at: summary.updated_at, }; let failed_publish = sandbox .registry .publish_agent(PublishAgentRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &agent, version: 1, published_at: &OffsetDateTime::now_utc(), published_by: None, expected_state: Some(&stale_state), }) .await .expect_err("a stale publication precondition must fail"); assert!( matches!( failed_publish, crank_registry::RegistryError::AgentStaleRevision { .. } ), "stale publication must keep the Agent taxonomy: {failed_publish}" ); let published_rows: i64 = sqlx::query_scalar("select count(*) from published_agents where agent_id = $1") .bind(agent.as_str()) .fetch_one(&sandbox.pool) .await .expect("published pointer must be queryable"); assert_eq!( published_rows, 0, "a failed publish must not write a pointer" ); let after = sandbox .registry .get_agent_summary(&WorkspaceId::new("ws_default"), &agent) .await .expect("summary must be readable") .expect("summary must exist"); assert_eq!(after.catalog_revision, summary.catalog_revision); assert_eq!(after.latest_published_version, None); assert_eq!( binding_rows(&sandbox, agent.as_str()).await, 1, "a failed publish must not drop the draft binding" ); // Positive control: корректная публикация атомарно двигает pointer и revision. sandbox .registry .publish_agent(PublishAgentRequest { workspace_id: &WorkspaceId::new("ws_default"), agent_id: &agent, version: 1, published_at: &OffsetDateTime::now_utc(), published_by: None, expected_state: Some(&crank_registry::AgentStateExpectation { status: after.status, current_draft_version: after.current_draft_version, latest_published_version: after.latest_published_version, catalog_revision: after.catalog_revision, updated_at: after.updated_at, }), }) .await .expect("a fresh precondition must publish"); let published = sandbox .registry .get_agent_summary(&WorkspaceId::new("ws_default"), &agent) .await .expect("summary must be readable") .expect("summary must exist"); assert_eq!(published.latest_published_version, Some(1)); assert_eq!( published.catalog_revision, after.catalog_revision + 1, "publication must raise catalog_revision by exactly one" ); assert_eq!( published.status, AgentStatus::Published, "publication must atomically switch the Agent pointer" ); sandbox.cleanup().await; }