//! ATDD (RED) Story 3.13 — публикация immutable Published Prompt Version, exact //! чтение версии, archive lifecycle и exact typed binding Prompt → Agent. //! //! Источники: BODY t_a8f885f9 (Epic3/Story3.13/FR17), TL решения //! `.tmp/t_bcada2cc/tl347-review.md` п.3, QA design //! `.tmp/t_bcada2cc/story313-test-design.md`, `.tmp/t_c9d239b4/epics-source.md:618–654`, //! `docs/acceptance-test-plan.md:1119–1131` (AT-3.13-01..04). //! //! Тесты поведенческие: реальный `build_app` router и PostgreSQL через `common`. //! RED здесь — отсутствующее продуктовое поведение (405 на выбранном item POST, //! отсутствие exact-полей опубликованной версии и typed prompt bindings), а не //! compile failure и не assertions по тексту исходников. Положительный контроль — //! обычный Draft create/get/preview/list (`story313_positive_control_*`), //! он обязан быть зелёным уже до реализации. //! //! Запуск: //! `cargo test -p admin-api --test integration prompt_publication` use reqwest::StatusCode; use serde_json::{Value, json}; use serial_test::serial; use time::OffsetDateTime; use crank_core::{ Workspace, WorkspaceId, WorkspaceStatus, ids::PromptId, prompt::{PromptDefinition, PromptSensitivity}, }; use crank_registry::{ CreateWorkspaceRequest, model::{CreatePromptDraftRequest, PublishPromptRequest}, }; use super::common::{ authorized_client, build_test_app, spawn_admin_api, test_registry, test_storage_root, }; /// Definition с двумя аргументами и двумя сообщениями: проверяются порядок, /// точное значение и неизменность опубликованной версии. fn prompt_body(name: &str) -> Value { json!({ "name": name, "description": "Story 3.13 immutable publication fixture", "sensitivity": "internal", "arguments": [ {"name":"count","schema":{"type":"integer"},"required":true}, {"name":"tone","schema":{"type":"string","enum":["warm","plain"]},"required":false,"default":"warm"} ], "messages": [ {"role":"system","content":"Be {{tone}}."}, {"role":"user","content":"Count {{count}}."} ] }) } async fn read(response: reqwest::Response) -> (StatusCode, Value) { let status = response.status(); let text = response.text().await.unwrap_or_default(); (status, serde_json::from_str(&text).unwrap_or(Value::Null)) } /// Shape-проверка nullable-поля: `Value::Null` сам по себе не отличает /// отсутствующий ключ от явного `null`, поэтому наличие ключа проверяется отдельно. fn assert_nullable_field_is_present(view: &Value, field: &str, context: &str) { let object = view .as_object() .unwrap_or_else(|| panic!("{context}: the item view must be a JSON object: {view}")); assert!( object.contains_key(field), "{context}: the item view must expose `{field}` explicitly even when it is null: {view}" ); assert_eq!(object[field], Value::Null, "{context}: {view}"); } fn foreign_definition() -> PromptDefinition { let mut body = prompt_body("Story 3.13 foreign secret"); body.as_object_mut() .expect("fixture body is an object") .remove("sensitivity"); PromptDefinition::parse(&body).expect("fixture definition parses") } /// Опубликованный Prompt в другом workspace: нужен, чтобы проверить, что binding /// чужой публикации отклоняется санитизированно и не оставляет следов. async fn publish_prompt_in_foreign_workspace( registry: &crank_registry::PostgresRegistry, workspace_id: &str, ) -> String { let now = OffsetDateTime::now_utc(); let workspace = WorkspaceId::new(workspace_id); registry .create_workspace(CreateWorkspaceRequest { workspace: &Workspace { id: workspace.clone(), slug: "story313-foreign".to_owned(), display_name: "Story 3.13 foreign".to_owned(), status: WorkspaceStatus::Active, settings: json!({}), created_at: now, updated_at: now, }, }) .await .expect("the foreign workspace fixture is created"); let prompt_id = PromptId::new("prm_story313_foreign"); let created = registry .create_prompt_draft(CreatePromptDraftRequest { workspace_id: workspace.clone(), prompt_id: prompt_id.clone(), sensitivity: PromptSensitivity::Internal, definition: foreign_definition(), created_at: now, }) .await .expect("the foreign Draft fixture is created"); registry .publish_prompt_draft(PublishPromptRequest { workspace_id: workspace, prompt_id: prompt_id.clone(), expected_updated_at: created.updated_at, published_at: OffsetDateTime::now_utc(), }) .await .expect("the foreign publication fixture is pinned"); prompt_id.as_str().to_owned() } async fn create_prompt(client: &reqwest::Client, base: &str, body: &Value) -> Value { let response = client .post(format!("{base}/prompts")) .json(body) .send() .await .expect("create request completes"); let status = response.status(); let text = response.text().await.unwrap_or_default(); assert_eq!( status, StatusCode::CREATED, "the ordinary Draft create baseline must stay green: {text}" ); serde_json::from_str(&text).expect("created prompt is JSON") } async fn create_agent(client: &reqwest::Client, base: &str, slug: &str) -> String { let (status, agent) = read( client .post(format!("{base}/agents")) .json(&json!({ "slug": slug, "display_name": "Story 3.13 prompt binding", "description": "Story 3.13 exact Prompt binding fixture", "instructions": {}, "tool_selection_policy": {} })) .send() .await .expect("agent create completes"), ) .await; assert_eq!( status, StatusCode::OK, "the ordinary Agent create baseline must stay green: {agent}" ); agent["agent_id"] .as_str() .expect("created agent id") .to_owned() } #[tokio::test(flavor = "multi_thread")] #[serial] async fn story313_positive_control_draft_create_get_preview_and_list_stay_green() { let registry = test_registry().await; let server = spawn_admin_api(build_test_app( registry, test_storage_root("story313_positive_control"), )) .await; let client = authorized_client(&server).await; let base = server.as_ref(); let created = create_prompt(&client, base, &prompt_body("Story 3.13 control")).await; let prompt_id = created["prompt_id"] .as_str() .expect("created prompt id") .to_owned(); assert_eq!(created["version"], 1); assert_eq!(created["status"], "draft"); assert_eq!( created["definition"]["messages"][1]["content"], "Count {{count}}." ); let (status, stored) = read( client .get(format!("{base}/prompts/{prompt_id}")) .send() .await .expect("read request completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(stored["definition"], created["definition"]); let (status, preview) = read( client .post(format!("{base}/prompts/{prompt_id}/preview")) .json(&json!({"arguments":{"count":7}})) .send() .await .expect("preview request completes"), ) .await; assert_eq!(status, StatusCode::OK, "preview baseline: {preview}"); assert_eq!(preview["status"], "draft"); assert_eq!(preview["messages"][0]["content"], "Be warm."); assert_eq!(preview["messages"][1]["content"], "Count 7."); let (status, listed) = read( client .get(format!("{base}/prompts")) .send() .await .expect("list request completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(listed["items"].as_array().map(Vec::len), Some(1)); assert_eq!(listed["items"][0]["prompt_id"], prompt_id); } #[tokio::test(flavor = "multi_thread")] #[serial] async fn story313_ac1_publish_pins_immutable_published_version_and_edit_opens_new_draft() { let registry = test_registry().await; let server = spawn_admin_api(build_test_app( registry, test_storage_root("story313_publish"), )) .await; let client = authorized_client(&server).await; let base = server.as_ref(); let created = create_prompt(&client, base, &prompt_body("Story 3.13 published")).await; let prompt_id = created["prompt_id"] .as_str() .expect("created prompt id") .to_owned(); let item = format!("{base}/prompts/{prompt_id}"); let (status, published) = read( client .post(&item) .json(&json!({ "action": "publish", "expected_updated_at": created["updated_at"] })) .send() .await .expect("publish request completes"), ) .await; assert_eq!( status, StatusCode::OK, "publish must be served by the existing item route and pin the Draft as an immutable \ Published Prompt Version: {status}: {published}" ); assert_eq!( published["version"], 1, "publish must expose the exact published version number: {published}" ); assert_eq!( published["status"], "published", "publish must report the published lifecycle status: {published}" ); assert_eq!( published["latest_published_version"], 1, "publish must raise latest_published_version: {published}" ); assert_eq!( published["definition"], created["definition"], "the Published Prompt Version must pin the exact validated Draft definition: {published}" ); let (status, exact) = read( client .get(&item) .query(&[("version", "1")]) .send() .await .expect("exact version read completes"), ) .await; assert_eq!( status, StatusCode::OK, "GET item ?version=1 must return the exact Published definition: {status}: {exact}" ); assert_eq!(exact["version"], 1); assert_eq!(exact["definition"], created["definition"]); let mut edit = prompt_body("Story 3.13 edited"); edit["description"] = json!("edited after publication"); edit["expected_updated_at"] = published["updated_at"].clone(); let (status, draft_v2) = read( client .put(&item) .json(&edit) .send() .await .expect("draft edit completes"), ) .await; assert_eq!( status, StatusCode::OK, "editing a published prompt must open a new Draft instead of mutating the published \ version: {status}: {draft_v2}" ); assert_eq!(draft_v2["version"], 2, "{draft_v2}"); assert_eq!( draft_v2["current_draft_version"], 2, "the item view must expose the new Draft version: {draft_v2}" ); assert_eq!( draft_v2["latest_published_version"], 1, "the published version must stay pinned while the Draft moves on: {draft_v2}" ); assert_eq!(draft_v2["name"], "Story 3.13 edited"); let (status, preserved) = read( client .get(&item) .query(&[("version", "1")]) .send() .await .expect("published version re-read completes"), ) .await; assert_eq!( status, StatusCode::OK, "the pinned publication must survive a Draft edit: {status}: {preserved}" ); assert_eq!( preserved["definition"], created["definition"], "published arguments/messages must not change in place: {preserved}" ); assert_eq!(preserved["name"], "Story 3.13 published"); let (status, archived) = read( client .post(&item) .json(&json!({ "action": "archive", "expected_updated_at": draft_v2["updated_at"] })) .send() .await .expect("archive request completes"), ) .await; assert_eq!( status, StatusCode::OK, "archive must be served by the same item route: {status}: {archived}" ); assert_eq!( archived["status"], "archived", "archive must report the archived lifecycle status: {archived}" ); let (status, refused) = read( client .post(&item) .json(&json!({ "action": "publish", "expected_updated_at": archived["updated_at"] })) .send() .await .expect("publish after archive completes"), ) .await; assert_eq!( status, StatusCode::CONFLICT, "an archived prompt must refuse a new publication: {status}: {refused}" ); let (status, after_archive) = read( client .get(&item) .query(&[("version", "1")]) .send() .await .expect("read after archive completes"), ) .await; assert_eq!( status, StatusCode::OK, "archive is not a security revoke and must keep the immutable publication: \ {status}: {after_archive}" ); assert_eq!(after_archive["definition"], created["definition"]); } #[tokio::test(flavor = "multi_thread")] #[serial] async fn story313_ac1_publish_refuses_missing_precondition_stale_revision_and_invalid_action() { let registry = test_registry().await; let server = spawn_admin_api(build_test_app( registry, test_storage_root("story313_publish_negatives"), )) .await; let client = authorized_client(&server).await; let base = server.as_ref(); let created = create_prompt(&client, base, &prompt_body("Story 3.13 negatives")).await; let prompt_id = created["prompt_id"] .as_str() .expect("created prompt id") .to_owned(); let item = format!("{base}/prompts/{prompt_id}"); let (status, missing) = read( client .post(&item) .json(&json!({"action": "publish"})) .send() .await .expect("publish without precondition completes"), ) .await; assert_eq!( status, StatusCode::PRECONDITION_REQUIRED, "publish without expected_updated_at must be refused as a missing precondition, \ separately from a stale revision: {status}: {missing}" ); let (status, invalid) = read( client .post(&item) .json(&json!({ "action": "destroy", "expected_updated_at": created["updated_at"] })) .send() .await .expect("publish with unknown action completes"), ) .await; assert_eq!( status, StatusCode::BAD_REQUEST, "an unknown action must be rejected as an invalid request: {status}: {invalid}" ); let mut edit = prompt_body("Story 3.13 stale fixture"); edit["expected_updated_at"] = created["updated_at"].clone(); let (status, draft_v2) = read( client .put(&item) .json(&edit) .send() .await .expect("draft update completes"), ) .await; assert_eq!( status, StatusCode::OK, "the ordinary Draft update baseline must stay green: {status}: {draft_v2}" ); let (status, stale) = read( client .post(&item) .json(&json!({ "action": "publish", "expected_updated_at": created["updated_at"] })) .send() .await .expect("stale publish completes"), ) .await; assert_eq!( status, StatusCode::CONFLICT, "publish with a stale expected_updated_at must conflict instead of publishing: \ {status}: {stale}" ); let (status, item_view) = read( client .get(&item) .send() .await .expect("item read after refusals completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( item_view["current_draft_version"], 2, "refused publications must not create a Draft revision: {item_view}" ); assert_nullable_field_is_present( &item_view, "latest_published_version", "refused publications must not leave a publication behind", ); } #[tokio::test(flavor = "multi_thread")] #[serial] async fn story313_ac1_item_distinguishes_current_draft_from_latest_published_version() { let registry = test_registry().await; let server = spawn_admin_api(build_test_app( registry, test_storage_root("story313_item_view"), )) .await; let client = authorized_client(&server).await; let base = server.as_ref(); let created = create_prompt(&client, base, &prompt_body("Story 3.13 item view")).await; let prompt_id = created["prompt_id"] .as_str() .expect("created prompt id") .to_owned(); let item = format!("{base}/prompts/{prompt_id}"); let (status, fresh) = read( client .get(&item) .send() .await .expect("fresh item read completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( fresh["current_draft_version"], 1, "the item view must expose the current Draft version independently of `version`: {fresh}" ); assert_nullable_field_is_present( &fresh, "latest_published_version", "a never published prompt must not report a published version", ); let mut edit = prompt_body("Story 3.13 item view edited"); edit["expected_updated_at"] = created["updated_at"].clone(); let (status, _updated) = read( client .put(&item) .json(&edit) .send() .await .expect("draft update completes"), ) .await; assert_eq!(status, StatusCode::OK); let (status, edited) = read( client .get(&item) .send() .await .expect("edited item read completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( edited["current_draft_version"], 2, "the item view must follow the current Draft after an edit: {edited}" ); assert_eq!( edited["version"], 2, "the item view keeps the current Draft version in `version`: {edited}" ); assert_nullable_field_is_present( &edited, "latest_published_version", "editing a Draft must not report a published version", ); } #[tokio::test(flavor = "multi_thread")] #[serial] async fn story313_ac2_exact_prompt_binding_survives_draft_edit_and_refuses_unpublished() { let registry = test_registry().await; let server = spawn_admin_api(build_test_app( registry, test_storage_root("story313_exact_prompt_binding"), )) .await; let client = authorized_client(&server).await; let base = server.as_ref(); let created = create_prompt(&client, base, &prompt_body("Story 3.13 bound")).await; let prompt_id = created["prompt_id"] .as_str() .expect("created prompt id") .to_owned(); let item = format!("{base}/prompts/{prompt_id}"); let (status, published) = read( client .post(&item) .json(&json!({ "action": "publish", "expected_updated_at": created["updated_at"] })) .send() .await .expect("publish request completes"), ) .await; assert_eq!(status, StatusCode::OK, "publish must succeed: {published}"); let agent_id = create_agent(&client, base, "story313-exact-prompt-binding").await; let detail = client .get(format!("{base}/agents/{agent_id}")) .send() .await .expect("agent detail completes"); let etag = detail .headers() .get(reqwest::header::ETAG) .expect("agent detail exposes an ETag") .to_str() .expect("Agent ETag is ASCII") .to_owned(); let bindings_url = format!("{base}/agents/{agent_id}/bindings"); let (status, saved) = read( client .post(&bindings_url) .header(reqwest::header::IF_MATCH, &etag) .json(&json!({ "bindings": [], "tool_selection_policy": {}, "prompt_bindings": [{"prompt_id": prompt_id, "prompt_version": 1}] })) .send() .await .expect("bindings request completes"), ) .await; assert_eq!(status, StatusCode::OK, "exact binding must save: {saved}"); assert_eq!( saved["prompt_bindings"], json!([{"prompt_id": prompt_id, "prompt_version": 1}]), "the response must expose the exact typed Prompt binding: {saved}" ); // Tri-state: отсутствие `prompt_bindings` сохраняет прежнюю привязку. let refreshed_etag = client .get(format!("{base}/agents/{agent_id}")) .send() .await .expect("agent detail completes") .headers() .get(reqwest::header::ETAG) .expect("agent detail exposes an ETag") .to_str() .expect("Agent ETag is ASCII") .to_owned(); let (status, preserved) = read( client .post(&bindings_url) .header(reqwest::header::IF_MATCH, refreshed_etag) .json(&json!({"bindings": [], "tool_selection_policy": {}})) .send() .await .expect("bindings request completes"), ) .await; assert_eq!(status, StatusCode::OK, "{preserved}"); assert_eq!( preserved["prompt_bindings"], json!([{"prompt_id": prompt_id, "prompt_version": 1}]), "an absent prompt_bindings field must preserve the binding: {preserved}" ); // Правка Draft не переписывает закреплённую публикацию. let mut edit = prompt_body("Story 3.13 bound edited"); edit["expected_updated_at"] = published["updated_at"].clone(); let (status, _draft_v2) = read( client .put(&item) .json(&edit) .send() .await .expect("draft edit completes"), ) .await; assert_eq!(status, StatusCode::OK); let (status, exact) = read( client .get(&item) .query(&[("version", "1")]) .send() .await .expect("exact read completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(exact["definition"], created["definition"]); assert_eq!(exact["name"], "Story 3.13 bound"); // Bind неопубликованной версии: sanitized 404, binding не меняется. let (status, refused) = read( client .post(&bindings_url) .header( reqwest::header::IF_MATCH, client .get(format!("{base}/agents/{agent_id}")) .send() .await .expect("agent detail completes") .headers() .get(reqwest::header::ETAG) .expect("agent detail exposes an ETag") .to_str() .expect("Agent ETag is ASCII") .to_owned(), ) .json(&json!({ "bindings": [], "tool_selection_policy": {}, "prompt_bindings": [{"prompt_id": prompt_id, "prompt_version": 2}] })) .send() .await .expect("bindings request completes"), ) .await; assert_eq!( status, StatusCode::NOT_FOUND, "an unpublished version must be refused without leaking existence: {refused}" ); let (status, unchanged) = read( client .get(format!("{base}/agents/{agent_id}/versions/1")) .send() .await .expect("agent version read completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( unchanged["prompt_bindings"], json!([{"prompt_id": prompt_id, "prompt_version": 1}]), "a refused binding must not change stored bindings: {unchanged}" ); } #[tokio::test(flavor = "multi_thread")] #[serial] async fn story313_ac2_agent_binding_response_exposes_exact_prompt_bindings() { let registry = test_registry().await; let server = spawn_admin_api(build_test_app( registry, test_storage_root("story313_prompt_binding"), )) .await; let client = authorized_client(&server).await; let base = server.as_ref(); let agent_id = create_agent(&client, base, "story313-prompt-binding").await; let detail = client .get(format!("{base}/agents/{agent_id}")) .send() .await .expect("agent detail completes"); assert_eq!( detail.status(), StatusCode::OK, "agent detail must expose the current Agent ETag" ); let etag = detail .headers() .get(reqwest::header::ETAG) .expect("agent detail must expose an ETag") .to_str() .expect("Agent ETag is ASCII") .to_owned(); let (status, saved) = read( client .post(format!("{base}/agents/{agent_id}/bindings")) .header(reqwest::header::IF_MATCH, etag) .json(&json!({ "bindings": [], "tool_selection_policy": {}, "prompt_bindings": [] })) .send() .await .expect("bindings request completes"), ) .await; assert_eq!( status, StatusCode::OK, "the existing bindings endpoint must accept the tri-state prompt_bindings field: \ {status}: {saved}" ); assert_eq!( saved["prompt_bindings"], json!([]), "the bindings response must expose the exact typed Prompt bindings (`[]` clears them \ here): {saved}" ); let (status, version) = read( client .get(format!("{base}/agents/{agent_id}/versions/1")) .send() .await .expect("agent version read completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( version["prompt_bindings"], json!([]), "GET versions/1 must return the same exact typed Prompt bindings: {version}" ); } #[tokio::test(flavor = "multi_thread")] #[serial] async fn story313_ac2_foreign_workspace_prompt_binding_is_sanitized_404_without_effects() { let registry = test_registry().await; let foreign_prompt_id = publish_prompt_in_foreign_workspace(®istry, "ws_story313_foreign").await; let server = spawn_admin_api(build_test_app( registry, test_storage_root("story313_foreign_binding"), )) .await; let client = authorized_client(&server).await; let base = server.as_ref(); let agent_id = create_agent(&client, base, "story313-foreign-binding").await; let agent_url = format!("{base}/agents/{agent_id}"); let etag = client .get(&agent_url) .send() .await .expect("agent detail completes") .headers() .get(reqwest::header::ETAG) .expect("agent detail exposes an ETag") .to_str() .expect("Agent ETag is ASCII") .to_owned(); let (status, refused) = read( client .post(format!("{agent_url}/bindings")) .header(reqwest::header::IF_MATCH, etag) .json(&json!({ "bindings": [], "tool_selection_policy": {}, "prompt_bindings": [{"prompt_id": foreign_prompt_id, "prompt_version": 1}] })) .send() .await .expect("foreign binding request completes"), ) .await; assert_eq!( status, StatusCode::NOT_FOUND, "a Prompt published in another workspace must be refused as sanitized 404: {refused}" ); assert_eq!( refused["error"]["code"], "agent_prompt_binding_not_found", "the refusal must use the binding-specific sanitized error code: {refused}" ); assert!( !refused.to_string().contains("foreign secret"), "the refusal must not leak the foreign Prompt definition: {refused}" ); let (status, version) = read( client .get(format!("{agent_url}/versions/1")) .send() .await .expect("agent version read completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( version["prompt_bindings"], json!([]), "a refused foreign binding must not leave a row in agent_prompt_bindings: {version}" ); let (status, agent) = read( client .get(&agent_url) .send() .await .expect("agent detail read completes"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( agent["catalog_revision"], 0, "a refused foreign binding must not bump the catalog revision: {agent}" ); let (status, hidden) = read( client .get(format!("{base}/prompts/{foreign_prompt_id}")) .query(&[("version", "1")]) .send() .await .expect("foreign exact read completes"), ) .await; assert_eq!( status, StatusCode::NOT_FOUND, "the foreign publication must stay invisible in this workspace: {hidden}" ); }