//! HTTP/artifact fixtures Story 3.7 exact Resource binding (вынесены из //! `agent_resource_bindings.rs`, чтобы файл оставался в пределах //! rust-code-health); assertions и поведение тестов не меняются. use super::super::common::{ TestServer, agent_etag, assert_success_json, authorized_client, build_test_app, operation_etag, spawn_admin_api, test_auth_settings, test_operation_payload, test_registry, test_storage_root, }; use crank_core::{MembershipRole, Workspace, WorkspaceId, WorkspaceStatus}; use crank_registry::{CreateWorkspaceRequest, PostgresRegistry}; use reqwest::StatusCode; use reqwest::multipart::{Form, Part}; use serde_json::{Value, json}; use time::OffsetDateTime; pub(super) const OWNER_EMAIL: &str = "owner@crank.local"; pub(super) const OWNER_PASSWORD: &str = "test-password"; // --------------------------------------------------------------------------- // Стенд // --------------------------------------------------------------------------- pub(super) async fn spawn_workspace(name: &str) -> (PostgresRegistry, TestServer, reqwest::Client) { let registry = test_registry().await; let app = build_test_app(registry.clone(), test_storage_root(name)); let server = spawn_admin_api(app).await; let client = authorized_client(&server).await; (registry, server, client) } /// Базовый URL другого workspace на том же сервере: нужен для чужого опубликованного /// Resource Version (изоляция workspace). pub(super) fn workspace_url(server: &TestServer, workspace_id: &str) -> String { let base = server.as_ref(); let root = base .split("/api/admin/workspaces/") .next() .expect("workspace base url must contain the admin workspace prefix"); format!("{root}/api/admin/workspaces/{workspace_id}") } /// WorkspaceB с Owner-membership вызывающего аккаунта: workspace доступен, а принадлежащий /// ему Resource Version — чужая сущность для `ws_default`. pub(super) async fn create_owned_workspace( registry: &PostgresRegistry, id: &str, slug: &str, ) -> WorkspaceId { let now = OffsetDateTime::now_utc(); let workspace_id = WorkspaceId::new(id); registry .create_workspace(CreateWorkspaceRequest { workspace: &Workspace { id: workspace_id.clone(), 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"); let password_hash = admin_api::auth::hash_password(OWNER_PASSWORD, &test_auth_settings().password_pepper) .expect("owner password hash"); let owner_id = registry .upsert_bootstrap_user(OWNER_EMAIL, "Test Owner", &password_hash) .await .expect("owner account"); registry .ensure_membership(&workspace_id, &owner_id, MembershipRole::Owner) .await .expect("owner membership in WorkspaceB"); workspace_id } // --------------------------------------------------------------------------- // Resource fixtures (существующий принятый контракт Story 3.6/3.7) // --------------------------------------------------------------------------- pub(super) fn draft_metadata( uri: &str, name: &str, kind: &str, mime: &str, sensitivity: &str, ) -> Value { json!({ "uri": uri, "name": name, "description": "", "kind": kind, "mime_type": mime, "sensitivity": sensitivity, }) } pub(super) fn json_part(metadata: &Value) -> Part { Part::bytes(serde_json::to_vec(metadata).expect("metadata must serialize")) .file_name("metadata.json".to_owned()) .mime_str("application/json") .expect("json part mime") } pub(super) fn content_part(content: &[u8], filename: &str, mime: &str) -> Part { Part::bytes(content.to_vec()) .file_name(filename.to_owned()) .mime_str(mime) .expect("content part mime") } pub(super) fn draft_form(metadata: &Value, content: &[u8], filename: &str, mime: &str) -> Form { Form::new() .part("metadata", json_part(metadata)) .part("content", content_part(content, filename, mime)) } pub(super) async fn read_response(response: reqwest::Response) -> (StatusCode, String, Value) { let status = response.status(); let text = response.text().await.unwrap_or_default(); let json = serde_json::from_str::(&text).unwrap_or(Value::Null); (status, text, json) } pub(super) async fn create_draft( client: &reqwest::Client, server: &str, metadata: &Value, content: &[u8], filename: &str, mime: &str, ) -> (String, Value) { let (status, text, body) = read_response( client .post(format!("{server}/resources")) .multipart(draft_form(metadata, content, filename, mime)) .send() .await .expect("draft request must complete"), ) .await; assert_eq!( status, StatusCode::CREATED, "positive control: POST /resources must create a Draft (AT-3.6-02); observed {status} body={text}" ); let resource_id = body["resource"]["resource_id"] .as_str() .or_else(|| body["resource"]["id"].as_str()) .unwrap_or_else(|| panic!("201 response must carry the Resource identifier: {body}")) .to_owned(); (resource_id, body) } pub(super) fn draft_updated_at(body: &Value) -> String { for pointer in ["/resource/updated_at", "/version/updated_at", "/updated_at"] { if let Some(value) = body.pointer(pointer).and_then(Value::as_str) { return value.to_owned(); } } panic!("Draft card must expose `updated_at` as the publication precondition: {body}"); } pub(super) async fn get_card(client: &reqwest::Client, server: &str, resource_id: &str) -> Value { let (status, text, body) = read_response( client .get(format!("{server}/resources/{resource_id}")) .send() .await .expect("card request must complete"), ) .await; assert_eq!( status, StatusCode::OK, "positive control: GET /resources/{{id}} must return the card; observed {status} body={text}" ); body } /// Публикует текущий Draft существующим контрактом Story 3.7 и возвращает immutable /// `published_version` object. pub(super) async fn publish_current_draft( client: &reqwest::Client, server: &str, resource_id: &str, context: &str, ) -> Value { let card = get_card(client, server, resource_id).await; let updated_at = draft_updated_at(&card); let (status, text, body) = read_response( client .post(format!("{server}/resources/{resource_id}/publish")) .json(&json!({ "expected_updated_at": updated_at })) .send() .await .expect("publish request must complete"), ) .await; assert_eq!( status, StatusCode::OK, "{context}: positive control requires a successful Resource publication (AT-3.7-03); \ observed {status} body={text}" ); body["published_version"] .as_object() .map(|_| body["published_version"].clone()) .unwrap_or_else(|| panic!("{context}: publish must return `published_version`: {body}")) } /// Draft → Published Version через существующий HTTP-контракт. pub(super) async fn create_published_resource( client: &reqwest::Client, server: &str, uri: &str, name: &str, content: &[u8], ) -> (String, Value) { let metadata = draft_metadata(uri, name, "text", "text/plain", "internal"); let (resource_id, _) = create_draft( client, server, &metadata, content, "story37-agent-binding.txt", "text/plain", ) .await; let published = publish_current_draft(client, server, &resource_id, "resource v1").await; assert_eq!( published["version"], json!(1), "the first publication must be exact version 1: {published}" ); (resource_id, published) } /// Редактирует Draft и публикует новую immutable версию (ожидается v2). pub(super) async fn edit_and_publish_second_version( client: &reqwest::Client, server: &str, resource_id: &str, content: &[u8], context: &str, ) -> Value { let card = get_card(client, server, resource_id).await; let (status, text, _) = read_response( client .put(format!("{server}/resources/{resource_id}")) .multipart(draft_form( &json!({ "description": "правка черновика перед второй публикацией", "mime_type": "text/plain", "sensitivity": "internal", "expected_updated_at": draft_updated_at(&card), }), content, "story37-agent-binding-v2.txt", "text/plain", )) .send() .await .expect("draft update request must complete"), ) .await; assert!( status.is_success(), "{context}: positive control requires the Draft update to stay accepted (Story 3.6); \ observed {status} body={text}" ); let published = publish_current_draft(client, server, resource_id, context).await; assert_eq!( published["version"], json!(2), "{context}: the edited Draft must publish as exact version 2: {published}" ); published } // --------------------------------------------------------------------------- // Agent fixtures // --------------------------------------------------------------------------- pub(super) fn operation_binding(operation_id: &str, tool_name: &str) -> Value { json!({ "operation_id": operation_id, "operation_version": 1, "tool_name": tool_name, "tool_title": tool_name, "tool_description_override": null, "enabled": true }) } pub(super) fn resource_binding(resource_id: &str, resource_version: u32) -> Value { json!({ "resource_id": resource_id, "resource_version": resource_version }) } pub(super) fn expected_resource_bindings(resource_id: &str, resource_version: u32) -> Value { json!([{ "resource_id": resource_id, "resource_version": resource_version }]) } /// Config-форма существующего `POST .../bindings` (TL interface decision 1): Operation /// bindings и `tool_selection_policy` сохраняют прежний смысл, `resource_bindings` — /// additive-поле точных Published Resource Versions. pub(super) fn catalog_config(operation_bindings: Value, resource_bindings: Value) -> Value { json!({ "bindings": operation_bindings, "tool_selection_policy": {}, "resource_bindings": resource_bindings, }) } pub(super) async fn create_published_operation( client: &reqwest::Client, server: &str, upstream: &str, name: &str, ) -> String { let operation = assert_success_json( client .post(format!("{server}/operations")) .json(&test_operation_payload(upstream, name)) .send() .await .unwrap(), ) .await; let operation_id = operation["operation_id"].as_str().unwrap().to_owned(); let etag = operation_etag(client, server, &operation_id).await; assert_success_json( client .post(format!("{server}/operations/{operation_id}/publish")) .header(reqwest::header::IF_MATCH, etag) .json(&json!({ "version": 1 })) .send() .await .unwrap(), ) .await; operation_id } pub(super) async fn create_agent(client: &reqwest::Client, server: &str, slug: &str) -> String { let agent = assert_success_json( client .post(format!("{server}/agents")) .json(&json!({ "slug": slug, "display_name": slug, "description": "Story 3.7 exact Resource binding fixture", "instructions": {}, "tool_selection_policy": {} })) .send() .await .unwrap(), ) .await; agent["agent_id"].as_str().unwrap().to_owned() } pub(super) async fn get_agent(client: &reqwest::Client, server: &str, agent_id: &str) -> Value { assert_success_json( client .get(format!("{server}/agents/{agent_id}")) .send() .await .unwrap(), ) .await } pub(super) async fn get_agent_version( client: &reqwest::Client, server: &str, agent_id: &str, version: u32, ) -> Value { assert_success_json( client .get(format!("{server}/agents/{agent_id}/versions/{version}")) .send() .await .unwrap(), ) .await } pub(super) async fn save_bindings_raw( client: &reqwest::Client, server: &str, agent_id: &str, etag: &str, payload: &Value, ) -> (StatusCode, String, Value) { read_response( client .post(format!("{server}/agents/{agent_id}/bindings")) .header(reqwest::header::IF_MATCH, etag) .json(payload) .send() .await .expect("bindings request must complete"), ) .await } /// Успешное сохранение Config-формы с Resource binding: возвращает AgentVersionRecord. pub(super) async fn save_bindings_expect_success( client: &reqwest::Client, server: &str, agent_id: &str, payload: &Value, context: &str, ) -> Value { let etag = agent_etag(client, server, agent_id).await; let (status, text, body) = save_bindings_raw(client, server, agent_id, &etag, payload).await; assert_eq!( status, StatusCode::OK, "{context}: the additive Config form must save exact Resource bindings; \ observed {status} body={text}" ); body } pub(super) async fn publish_agent_raw( client: &reqwest::Client, server: &str, agent_id: &str, etag: &str, version: u32, ) -> (StatusCode, String, Value) { read_response( client .post(format!("{server}/agents/{agent_id}/publish")) .header(reqwest::header::IF_MATCH, etag) .json(&json!({ "version": version })) .send() .await .expect("agent publish request must complete"), ) .await } pub(super) async fn publish_agent_expect_success( client: &reqwest::Client, server: &str, agent_id: &str, version: u32, context: &str, ) -> Value { let etag = agent_etag(client, server, agent_id).await; let (status, text, body) = publish_agent_raw(client, server, agent_id, &etag, version).await; assert_eq!( status, StatusCode::OK, "{context}: Agent publication must succeed and include the exact Resource snapshot; \ observed {status} body={text}" ); body } pub(super) async fn agent_version_count(registry: &PostgresRegistry, agent_id: &str) -> i64 { sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1") .bind(agent_id) .fetch_one(registry.pool()) .await .expect("agent_versions count") } // --------------------------------------------------------------------------- // AC04: exact Published Resource Version binding // ---------------------------------------------------------------------------