Files
crank/apps/admin-api/tests/integration/prompt_composition/mod.rs
T
Hermes DevOps 75fe5a123c [skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
2026-10-25 10:00:22 +00:00

359 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! ATDD (RED) для Story 3.16 — composition of Prompts with Published Resources (FR-18).
//!
//! Источники: `_bmad-output/initiative-crank/epic-mcp-capabilities/spec-prompt-composition/contract.md`
//! (§1–§8 — wire shape, resolution, effective policy, render, findings, immutability),
//! `epics.md`:2920–2986 (AC группы 1–10), `docs/acceptance-test-plan.md` AT-3.16-01…10,
//! `test-design-epic-3.md` строки 3.16 / 3.16-INT-A,B / E3-R2,R3.
//!
//! Состояние на момент написания: `PromptDefinition` не знает `dependencies`, а preview не
//! разрешает Resource. Поэтому каждый RED ниже — поведенческое расхождение на реальном HTTP
//! (400 `prompt_invalid_definition` там, где контракт требует 201/200/409/400 с точным кодом),
//! а не ошибка компиляции или setup. Позитивные контроли (создание/publish/preview обычного
//! Prompt и публикация Resource) исполняются в том же файле и доказывают работоспособность
//! харнесса.
//!
//! Фильтр запуска:
//! `cargo test -p admin-api --test integration prompt_composition -- --test-threads=1`.
use super::common::{
TestServer, authorized_client, build_test_app, spawn_admin_api, test_auth_settings,
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 serial_test::serial;
use std::sync::atomic::{AtomicU32, Ordering};
use time::OffsetDateTime;
const DEFAULT_WORKSPACE_ID: &str = "ws_default";
const TEST_AUTH_EMAIL: &str = "owner@crank.local";
const TEST_AUTH_PASSWORD: &str = "test-password";
static SEQ: AtomicU32 = AtomicU32::new(0);
struct Stand {
/// Держит сервер живым на всё время теста: Drop останавливает его.
_server: TestServer,
client: reqwest::Client,
base: String,
}
/// Свежий Admin API на собственном PostgreSQL-схеме и с авторизованной сессией владельца.
async fn stand(prefix: &str) -> Stand {
let registry = test_registry().await;
let server = spawn_admin_api(build_test_app(registry, test_storage_root(prefix))).await;
let client = authorized_client(&server).await;
let base = server.as_ref().to_owned();
Stand {
_server: server,
client,
base,
}
}
fn unique(prefix: &str) -> String {
let n = SEQ.fetch_add(1, Ordering::Relaxed);
format!("{prefix}_{n}")
}
// ---------------------------------------------------------------------------
// Fixtures: published Resources через production multipart/publish path
// ---------------------------------------------------------------------------
struct ResourceFixture {
id: String,
version: u32,
digest: String,
}
async fn create_and_publish_resource(
stand: &Stand,
base: &str,
kind: &str,
mime: &str,
sensitivity: &str,
content: &[u8],
) -> ResourceFixture {
let name = unique("story316");
let uri = format!("crank://resources/{name}");
let metadata = json!({
"uri": uri,
"name": name,
"description": "",
"kind": kind,
"mime_type": mime,
"sensitivity": sensitivity,
});
let form = Form::new()
.part(
"metadata",
Part::bytes(serde_json::to_vec(&metadata).expect("metadata json"))
.file_name("metadata.json".to_owned())
.mime_str("application/json")
.expect("metadata mime"),
)
.part(
"content",
Part::bytes(content.to_vec())
.file_name("content.bin".to_owned())
.mime_str(mime)
.expect("content mime"),
);
let response = stand
.client
.post(format!("{base}/resources"))
.multipart(form)
.send()
.await
.expect("resource create request");
let status = response.status();
let body: Value = response.json().await.unwrap_or(Value::Null);
assert_eq!(
status,
StatusCode::CREATED,
"resource Draft creation is the existing 3.6 path: {body}"
);
let id = body["resource"]["resource_id"]
.as_str()
.expect("resource card carries the id")
.to_owned();
let updated_at = body["resource"]["updated_at"]
.as_str()
.expect("resource card carries updated_at")
.to_owned();
let published = stand
.client
.post(format!("{base}/resources/{id}/publish"))
.json(&json!({ "expected_updated_at": updated_at }))
.send()
.await
.expect("resource publish request");
let status = published.status();
let body: Value = published.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::OK, "resource publish: {body}");
ResourceFixture {
id,
version: body["published_version"]["version"]
.as_u64()
.expect("published_version.version") as u32,
digest: body["published_version"]["digest"]
.as_str()
.expect("published_version.digest")
.to_owned(),
}
}
/// Новая Draft-версия того же Resource (immutable fields не передаются) + её публикация.
async fn publish_next_resource_version(
stand: &Stand,
base: &str,
resource_id: &str,
kind_mime_sensitivity: (&str, &str),
content: &[u8],
) -> ResourceFixture {
let (mime, sensitivity) = kind_mime_sensitivity;
// PUT требует precondition по текущей карточке Resource (Story 3.6 CAS).
let current: Value = stand
.client
.get(format!("{base}/resources/{resource_id}"))
.send()
.await
.expect("resource card request")
.json()
.await
.unwrap_or(Value::Null);
let expected_updated_at = current["resource"]["updated_at"]
.as_str()
.expect("current resource card carries updated_at")
.to_owned();
let metadata = json!({
"description": "",
"mime_type": mime,
"sensitivity": sensitivity,
"expected_updated_at": expected_updated_at,
});
let form = Form::new()
.part(
"metadata",
Part::bytes(serde_json::to_vec(&metadata).expect("metadata json"))
.file_name("metadata.json".to_owned())
.mime_str("application/json")
.expect("metadata mime"),
)
.part(
"content",
Part::bytes(content.to_vec())
.file_name("content.bin".to_owned())
.mime_str(mime)
.expect("content mime"),
);
let response = stand
.client
.put(format!("{base}/resources/{resource_id}"))
.multipart(form)
.send()
.await
.expect("resource update request");
let status = response.status();
let body: Value = response.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::OK, "resource new Draft version: {body}");
let updated_at = body["resource"]["updated_at"]
.as_str()
.expect("updated card carries updated_at")
.to_owned();
let published = stand
.client
.post(format!("{base}/resources/{resource_id}/publish"))
.json(&json!({ "expected_updated_at": updated_at }))
.send()
.await
.expect("resource publish request");
let status = published.status();
let body: Value = published.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::OK, "resource publish v2: {body}");
ResourceFixture {
id: resource_id.to_owned(),
version: body["published_version"]["version"]
.as_u64()
.expect("published_version.version") as u32,
digest: body["published_version"]["digest"]
.as_str()
.expect("published_version.digest")
.to_owned(),
}
}
fn dependency(resource: &ResourceFixture) -> Value {
json!([{ "resource_id": resource.id, "version": resource.version }])
}
/// Определение с одной pinned-зависимостью и точкой вставки в user-сообщении.
fn composed_prompt(name: &str, sensitivity: &str, dependencies: Value) -> Value {
json!({
"name": name,
"description": "composed prompt",
"sensitivity": sensitivity,
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
"messages": [
{"role": "system", "content": "Summarise only the attached document."},
{"role": "user", "content": "Channel: {{channel}}", "resource_refs": [0]}
],
"dependencies": dependencies
})
}
// ---------------------------------------------------------------------------
// HTTP helpers
// ---------------------------------------------------------------------------
async fn create_prompt(stand: &Stand, base: &str, body: &Value) -> (StatusCode, Value) {
let response = stand
.client
.post(format!("{base}/prompts"))
.json(body)
.send()
.await
.expect("create prompt request");
let status = response.status();
(status, response.json().await.unwrap_or(Value::Null))
}
async fn publish_prompt(
stand: &Stand,
base: &str,
prompt_id: &str,
extra: Option<Value>,
) -> (StatusCode, Value) {
let mut body = json!({ "action": "publish" });
if let Some(expected) = extra {
body["expected_updated_at"] = expected;
}
let response = stand
.client
.post(format!("{base}/prompts/{prompt_id}"))
.json(&body)
.send()
.await
.expect("publish prompt request");
let status = response.status();
(status, response.json().await.unwrap_or(Value::Null))
}
async fn preview_prompt(
stand: &Stand,
base: &str,
prompt_id: &str,
arguments: Value,
) -> (StatusCode, Value) {
let response = stand
.client
.post(format!("{base}/prompts/{prompt_id}/preview"))
.json(&json!({ "arguments": arguments }))
.send()
.await
.expect("preview prompt request");
let status = response.status();
(status, response.json().await.unwrap_or(Value::Null))
}
async fn workspace_with_membership(registry: &PostgresRegistry, suffix: &str) -> WorkspaceId {
let now = OffsetDateTime::now_utc();
let workspace_id = WorkspaceId::new(format!("ws_story316_{suffix}"));
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: format!("story316-{suffix}"),
display_name: format!("Story 3.16 {suffix}"),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("synthetic workspace creates");
let password_hash =
admin_api::auth::hash_password(TEST_AUTH_PASSWORD, &test_auth_settings().password_pepper)
.expect("owner password hash");
let owner_id = registry
.upsert_bootstrap_user(TEST_AUTH_EMAIL, "Test Owner", &password_hash)
.await
.expect("owner account");
registry
.ensure_membership(&workspace_id, &owner_id, MembershipRole::Owner)
.await
.expect("owner membership");
workspace_id
}
fn error_code(body: &Value) -> String {
body["error"]["code"]
.as_str()
.unwrap_or("<absent>")
.to_owned()
}
fn error_context(body: &Value) -> &Value {
&body["error"]["context"]
}
fn message_text(body: &Value, index: usize) -> String {
body["messages"][index]["content"]
.as_str()
.unwrap_or("<absent>")
.to_owned()
}
// Группы оракулов разнесены по файлам, чтобы каждый из них оставался в пределах
// rust-code-health; харнесс и фикстуры живут здесь, в `mod.rs`.
mod ac;
mod ac_render;
mod ac_scan;
mod oracles;