//! Story 3.16 / FR-18 на уровне реестра: version-keyed пины зависимостей Prompt. //! //! Проверяется на реальном PostgreSQL и реальном artifact store, что контракт держится схемой и //! транзакциями, а не только JSON-ответом admin-api: //! - публикация Prompt сохраняет точную опубликованную версию Resource (resource_id, version, //! digest, kind, source_class, sensitivity) и объявленные точки вставки; //! - новая версия Resource не переписывает пины уже опубликованного Prompt; //! - guard-триггер запрещает менять строки пинов опубликованной версии напрямую через SQL; //! - dependency другого workspace неотличима от отсутствующей (`prompt_dependency_unresolved`); //! - dependency, на которую не ссылается ни одно сообщение, отклоняется до любого чтения //! (`prompt_dependency_unused`); //! - публикация хранит строгую (effective) sensitivity. use std::{ fs, os::unix::fs::PermissionsExt, path::PathBuf, sync::atomic::{AtomicU64, Ordering}, }; use crank_artifacts::{ArtifactStore, RegisteredArtifact}; use crank_core::{ Workspace, WorkspaceId, WorkspaceStatus, ids::{PromptId, ResourceId}, prompt::{PromptDefinition, PromptSensitivity, PromptStatus}, }; use crank_registry::{ CreateWorkspaceRequest, MigrationAuthority, PostgresRegistry, RegistryError, model::{ CreatePromptDraftRequest, PublishPromptRequest, resource::{CreateResourceDraftRequest, PublishResourceVersionRequest}, }, }; use serde_json::json; use time::OffsetDateTime; const WORKSPACE_ID: &str = "ws_default"; 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-prompt-composition-{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::remove_dir_all(&self.0); } } struct Sandbox { registry: PostgresRegistry, store: ArtifactStore, _root: TestRoot, } async fn sandbox(name: &str) -> Sandbox { let database_url = crank_test_support::postgres_schema_url(&format!("story316_{name}")).await; let pool = sqlx::PgPool::connect(&database_url) .await .expect("test schema must accept connections"); MigrationAuthority::apply(&pool) .await .expect("migration sequence applies"); let registry = PostgresRegistry::connect(&database_url) .await .expect("registry must connect"); let root = TestRoot::new(name); let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open"); Sandbox { registry, store, _root: root, } } /// Второй workspace того же реестра: dependency из него не адресуема. async fn create_foreign_workspace(registry: &PostgresRegistry) -> WorkspaceId { let workspace_id = WorkspaceId::new("ws_story316_foreign"); let now = OffsetDateTime::now_utc(); registry .create_workspace(CreateWorkspaceRequest { workspace: &Workspace { id: workspace_id.clone(), slug: "story316-foreign".to_owned(), display_name: "Story 3.16 foreign".to_owned(), status: WorkspaceStatus::Active, settings: json!({}), created_at: now, updated_at: now, }, }) .await .expect("foreign workspace must be created"); workspace_id } fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact { sandbox .store .put_registered(bytes) .expect("fixture bytes must be registered durably") } /// Публикует static Resource в заданном workspace и возвращает точную опубликованную версию. async fn published_resource( sandbox: &Sandbox, workspace: &WorkspaceId, resource_id: &str, sensitivity: &str, bytes: &[u8], ) -> (ResourceId, u32, String) { let id = ResourceId::new(resource_id); let registry = &sandbox.registry; if registry .get_resource_draft(workspace.as_str(), &id) .await .is_ok() { // Новая опубликованная версия существующего Resource (Story 3.7 path). let current = registry .get_resource_draft(workspace.as_str(), &id) .await .expect("current draft readable"); registry .update_resource_draft( crank_registry::model::resource::UpdateResourceDraftRequest { workspace_id: workspace.clone(), resource_id: id.clone(), description: "second version".to_owned(), mime_type: "text/plain".to_owned(), sensitivity: sensitivity.to_owned(), expected_updated_at: current.resource.updated_at, artifact: registered(sandbox, bytes), }, ) .await .expect("second draft version must be creatable"); } else { registry .create_resource_draft(CreateResourceDraftRequest { workspace_id: workspace.clone(), resource_id: id.clone(), uri: format!("crank://resources/{resource_id}"), name: resource_id.to_owned(), description: String::new(), kind: "text".to_owned(), mime_type: "text/plain".to_owned(), sensitivity: sensitivity.to_owned(), artifact: registered(sandbox, bytes), created_at: OffsetDateTime::now_utc(), }) .await .expect("resource draft must be created"); } let current = registry .get_resource_draft(workspace.as_str(), &id) .await .expect("draft must be readable"); let publication = registry .publish_resource_version(PublishResourceVersionRequest { workspace_id: workspace.clone(), resource_id: 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("published Resource version"); (id, publication.version, publication.digest) } fn composed_definition( dependencies: serde_json::Value, refs: serde_json::Value, ) -> PromptDefinition { PromptDefinition::parse(&json!({ "name": "release-notes", "description": "Composed prompt", "arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}], "messages": [ {"role": "system", "content": "Summarise only the attached document."}, {"role": "user", "content": "Channel: {{channel}}", "resource_refs": refs} ], "dependencies": dependencies })) .expect("composed definition parses") } async fn create_draft( sandbox: &Sandbox, workspace: &WorkspaceId, prompt_id: &str, sensitivity: PromptSensitivity, definition: PromptDefinition, ) -> crank_registry::model::PromptDraftRecord { sandbox .registry .create_prompt_draft(CreatePromptDraftRequest { workspace_id: workspace.clone(), prompt_id: PromptId::new(prompt_id), sensitivity, definition, created_at: OffsetDateTime::now_utc(), }) .await .expect("composed prompt draft creates") } async fn publish_draft( sandbox: &Sandbox, workspace: &WorkspaceId, prompt_id: &str, expected_updated_at: time::OffsetDateTime, ) -> crank_registry::model::PromptDraftRecord { sandbox .registry .publish_prompt_draft(PublishPromptRequest { workspace_id: workspace.clone(), prompt_id: PromptId::new(prompt_id), expected_updated_at, published_at: OffsetDateTime::now_utc(), }) .await .expect("composed prompt publishes") } #[tokio::test] async fn story316_registry_stores_version_keyed_pins_and_insertion_points() { let sandbox = sandbox("pins").await; let workspace = WorkspaceId::new(WORKSPACE_ID); let (resource, version, digest) = published_resource( &sandbox, &workspace, "res_story316_pins", "internal", b"pinned body", ) .await; let definition = composed_definition( json!([{"resource_id": resource.as_str(), "version": version}]), json!([0]), ); let created = create_draft( &sandbox, &workspace, "prm_story316_pins", PromptSensitivity::Public, definition, ) .await; assert_eq!(created.dependencies.len(), 1); assert_eq!(created.dependencies[0].resource_id, resource.as_str()); assert_eq!(created.dependencies[0].version, version); assert_eq!(created.dependencies[0].digest, digest); assert_eq!(created.dependencies[0].kind.as_str(), "text"); assert_eq!(created.dependencies[0].source_class.as_str(), "static"); assert_eq!( created.dependencies[0].sensitivity, PromptSensitivity::Internal ); let stored_version: i32 = sqlx::query_scalar("select resource_version from prompt_dependencies where prompt_id = $1") .bind("prm_story316_pins") .fetch_one(sandbox.registry.pool()) .await .expect("pins are queryable"); assert_eq!(stored_version, i32::try_from(version).unwrap()); let refs: i32 = sqlx::query_scalar( "select dependency_position from prompt_message_resource_refs where prompt_id = $1", ) .bind("prm_story316_pins") .fetch_one(sandbox.registry.pool()) .await .expect("insertion points are queryable"); assert_eq!(refs, 0); // AC3: публикация хранит строгую политику, локальное значение остаётся в prompts. let published = publish_draft( &sandbox, &workspace, "prm_story316_pins", created.updated_at, ) .await; assert_eq!(published.prompt.status(), PromptStatus::Published); let publication_sensitivity: String = sqlx::query_scalar( "select sensitivity from prompt_publications where prompt_id = $1 and version = 1", ) .bind("prm_story316_pins") .fetch_one(sandbox.registry.pool()) .await .expect("publication is queryable"); assert_eq!(publication_sensitivity, "internal"); let local_sensitivity: String = sqlx::query_scalar("select sensitivity from prompts where prompt_id = $1") .bind("prm_story316_pins") .fetch_one(sandbox.registry.pool()) .await .expect("local value is queryable"); assert_eq!( local_sensitivity, "public", "the local value is not rewritten" ); } #[tokio::test] async fn story316_registry_pins_stay_immutable_after_a_new_resource_version() { let sandbox = sandbox("immutable").await; let workspace = WorkspaceId::new(WORKSPACE_ID); let (resource, version, digest) = published_resource( &sandbox, &workspace, "res_story316_immutable", "internal", b"CHANGELOG v1", ) .await; let definition = composed_definition( json!([{"resource_id": resource.as_str(), "version": version}]), json!([0]), ); let created = create_draft( &sandbox, &workspace, "prm_story316_immutable", PromptSensitivity::Internal, definition, ) .await; publish_draft( &sandbox, &workspace, "prm_story316_immutable", created.updated_at, ) .await; // Новая опубликованная версия того же Resource. let (_, second_version, second_digest) = published_resource( &sandbox, &workspace, "res_story316_immutable", "internal", b"CHANGELOG v2", ) .await; assert_eq!(second_version, version + 1); assert_ne!(second_digest, digest); let publication = sandbox .registry .get_published_prompt_version( &workspace, &PromptId::new("prm_story316_immutable"), version, ) .await .expect("published prompt version is readable"); assert_eq!( publication.dependencies[0].version, version, "the publication keeps the exact pinned version" ); assert_eq!(publication.dependencies[0].digest, digest); // Guard опубликованной версии: прямая правка пина через SQL отклоняется. let update = sqlx::query( "update prompt_dependencies set resource_version = resource_version + 1 where prompt_id = $1", ) .bind("prm_story316_immutable") .execute(sandbox.registry.pool()) .await; assert!( update.is_err(), "a published pin must be immutable through SQL as well" ); } #[tokio::test] async fn story316_registry_cross_workspace_dependency_is_unresolved() { let sandbox = sandbox("foreign").await; let workspace = WorkspaceId::new(WORKSPACE_ID); let foreign = create_foreign_workspace(&sandbox.registry).await; let (resource, version, _digest) = published_resource( &sandbox, &foreign, "res_story316_foreign", "internal", b"foreign body", ) .await; let definition = composed_definition( json!([{"resource_id": resource.as_str(), "version": version}]), json!([0]), ); let error = sandbox .registry .create_prompt_draft(CreatePromptDraftRequest { workspace_id: workspace.clone(), prompt_id: PromptId::new("prm_story316_foreign"), sensitivity: PromptSensitivity::Internal, definition, created_at: OffsetDateTime::now_utc(), }) .await .expect_err("a foreign dependency is not addressable"); assert!(matches!( error, RegistryError::PromptDependencyUnresolved { position: 0, .. } )); } #[tokio::test] async fn story316_registry_unused_dependency_is_refused() { let sandbox = sandbox("unused").await; let workspace = WorkspaceId::new(WORKSPACE_ID); let (first, first_version, _) = published_resource( &sandbox, &workspace, "res_story316_unused_a", "internal", b"first", ) .await; let (second, second_version, _) = published_resource( &sandbox, &workspace, "res_story316_unused_b", "internal", b"second", ) .await; let definition = composed_definition( json!([ {"resource_id": first.as_str(), "version": first_version}, {"resource_id": second.as_str(), "version": second_version} ]), json!([0]), ); let error = sandbox .registry .create_prompt_draft(CreatePromptDraftRequest { workspace_id: workspace.clone(), prompt_id: PromptId::new("prm_story316_unused"), sensitivity: PromptSensitivity::Internal, definition, created_at: OffsetDateTime::now_utc(), }) .await .expect_err("a dependency that no message references is refused"); match error { RegistryError::PromptDependencyUnused { position, resource_id, version, .. } => { assert_eq!(position, 1); assert_eq!(resource_id, second.as_str()); assert_eq!(version, second_version); } other => panic!("expected prompt_dependency_unused, got {other:?}"), } }