[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.
This commit is contained in:
1 parent
1b6db09bd1
commit
301dce301a
357 files changed
+118831
-5113
No files matched your search
@@ -0,0 +1,590 @@
|
||||
//! Story 3.16 / FR-18 на границе MCP `prompts/get`: составной Prompt из опубликованных Resource.
|
||||
//!
|
||||
//! Всё идёт production-путём: реальный registry (create/publish Prompt, exact bindings, publish
|
||||
//! Agent), реальный artifact root для опубликованного Resource и настоящий MCP endpoint.
|
||||
//!
|
||||
//! Проверяется:
|
||||
//! - точный pinned-текст вставляется дословно внутрь объявленного сообщения, роли и число
|
||||
//! сообщений не меняются (AC4/AC5);
|
||||
//! - новая опубликованная версия Resource не меняет то, что получает агент (AC8);
|
||||
//! - недоступная (отозванная) зависимость — структурированный отказ без `messages` (AC6).
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, HttpMethod, OperationSafetyClass,
|
||||
OperationSafetyPolicy, PlatformApiKeyScope, RestTarget, Target, ToolSelectionPolicy,
|
||||
ids::{PromptId, ResourceId},
|
||||
prompt::{PromptDefinition, PromptSensitivity},
|
||||
resource::template::TemplateSource,
|
||||
};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::{
|
||||
PostgresRegistry, PublishRequest,
|
||||
model::{
|
||||
AgentPromptBinding, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
resource::{
|
||||
CreateResourceDraftRequest, CreateResourceTemplateDraftRequest,
|
||||
PublishResourceTemplateVersionRequest, PublishResourceVersionRequest,
|
||||
},
|
||||
},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::super::common::{
|
||||
agent_mcp_url, build_test_app_with_artifacts, create_platform_api_key, object_schema,
|
||||
spawn_mcp_server, test_operation, test_registry, test_workspace_id,
|
||||
};
|
||||
use super::fixtures::{
|
||||
META_CLIENT_CAPABILITIES, META_CLIENT_INFO, META_PROTOCOL_VERSION, MODERN_REVISION,
|
||||
PromptEndpoint,
|
||||
};
|
||||
|
||||
const AGENT_SLUG: &str = "composed-prompts";
|
||||
const PINNED_V1: &str = "PINNED CHANGELOG v1";
|
||||
const PINNED_V2: &str = "PINNED CHANGELOG v2";
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-mcp-prompt-composition-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&path).expect("artifact root must be creatable");
|
||||
// Тот же контракт приватности, что у production root: 0700.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("artifact root must be 0700");
|
||||
}
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Публикует static Resource через production-путь 3.6/3.7 в реальном artifact root.
|
||||
async fn publish_resource(
|
||||
registry: &PostgresRegistry,
|
||||
store: &ArtifactStore,
|
||||
resource_id: &str,
|
||||
bytes: &[u8],
|
||||
) -> u32 {
|
||||
let id = ResourceId::new(resource_id);
|
||||
let artifact = store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes are registered durably");
|
||||
if registry
|
||||
.get_resource_draft(test_workspace_id().as_str(), &id)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
let current = registry
|
||||
.get_resource_draft(test_workspace_id().as_str(), &id)
|
||||
.await
|
||||
.expect("current draft reads");
|
||||
registry
|
||||
.update_resource_draft(
|
||||
crank_registry::model::resource::UpdateResourceDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: id.clone(),
|
||||
description: "next version".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
artifact,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("next draft version is created");
|
||||
} else {
|
||||
registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
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: "internal".to_owned(),
|
||||
artifact,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("resource draft is created");
|
||||
}
|
||||
let current = registry
|
||||
.get_resource_draft(test_workspace_id().as_str(), &id)
|
||||
.await
|
||||
.expect("draft reads");
|
||||
registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: id,
|
||||
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: store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes are registered durably"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("resource version publishes")
|
||||
.version
|
||||
}
|
||||
|
||||
fn composed_definition(resource_id: &str, version: u32) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "release-notes",
|
||||
"description": "Composed release notes",
|
||||
"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": [{"resource_id": resource_id, "version": version}]
|
||||
}))
|
||||
.expect("composed definition is valid")
|
||||
}
|
||||
|
||||
/// Стенд: опубликованный Resource v1, составной Prompt, exact binding и опубликованный Agent.
|
||||
///
|
||||
/// Возвращает endpoint, store и корень артефактов: `ArtifactStore` клонируется в приложение, поэтому
|
||||
/// последующая публикация новой версии Resource идёт в тот же immutable root.
|
||||
async fn composed_endpoint() -> (PromptEndpoint, ArtifactStore, TestRoot) {
|
||||
let root = TestRoot::new();
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("artifact store opens");
|
||||
let registry = test_registry().await;
|
||||
let resource_id = "res_story316_mcp_composed";
|
||||
let version = publish_resource(®istry, &store, resource_id, PINNED_V1.as_bytes()).await;
|
||||
let endpoint = bound_prompt_endpoint(
|
||||
registry,
|
||||
store.clone(),
|
||||
PromptId::new("prm_story316_mcp_composed"),
|
||||
composed_definition(resource_id, version),
|
||||
)
|
||||
.await;
|
||||
(endpoint, store, root)
|
||||
}
|
||||
|
||||
/// Опубликованный Prompt + exact binding в опубликованном Agent и живой MCP endpoint.
|
||||
async fn bound_prompt_endpoint(
|
||||
registry: PostgresRegistry,
|
||||
store: ArtifactStore,
|
||||
prompt_id: PromptId,
|
||||
definition: PromptDefinition,
|
||||
) -> PromptEndpoint {
|
||||
let created = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("composed prompt draft is created");
|
||||
registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: created.updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("composed prompt publishes");
|
||||
|
||||
let agent_id = AgentId::new(format!("agent_{AGENT_SLUG}"));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_agent(crank_registry::CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: agent_id.clone(),
|
||||
workspace_id: test_workspace_id(),
|
||||
slug: AGENT_SLUG.to_owned(),
|
||||
display_name: AGENT_SLUG.to_owned(),
|
||||
description: "Story 3.16 composed Prompt fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: agent_id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.expect("draft Agent is created");
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
crank_registry::model::SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("exact published Prompt binding is accepted");
|
||||
registry
|
||||
.publish_agent(crank_registry::PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("bound Agent publishes");
|
||||
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
AGENT_SLUG,
|
||||
"mcp-prompts-composed",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
|
||||
registry.clone(),
|
||||
Duration::from_millis(0),
|
||||
Some("https://crank.example.com".to_owned()),
|
||||
store,
|
||||
))
|
||||
.await;
|
||||
PromptEndpoint {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
|
||||
base_url,
|
||||
api_key,
|
||||
registry,
|
||||
greeting_id: prompt_id,
|
||||
archived_id: PromptId::new("prm_story316_unused_archived"),
|
||||
archived_updated_at: now,
|
||||
}
|
||||
}
|
||||
|
||||
/// Один modern `prompts/get` запрос через тот же adapter, что у остальных Prompt-тестов.
|
||||
async fn get(endpoint: &PromptEndpoint, channel: &str) -> Value {
|
||||
let headers = [
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "prompts/get"),
|
||||
("Mcp-Name", "release-notes"),
|
||||
];
|
||||
let params = json!({
|
||||
"name": "release-notes",
|
||||
"arguments": {"channel": channel},
|
||||
"_meta": {
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-prompts-story316", "version": "0.1.0"}
|
||||
}
|
||||
});
|
||||
let response = super::super::common::post_jsonrpc_with_headers(
|
||||
&endpoint.client,
|
||||
&agent_mcp_url(&endpoint.base_url, AGENT_SLUG),
|
||||
&endpoint.api_key,
|
||||
&headers,
|
||||
json!({"jsonrpc": "2.0", "id": 7, "method": "prompts/get", "params": params}),
|
||||
)
|
||||
.await;
|
||||
super::fixtures::json_body(response).await
|
||||
}
|
||||
|
||||
fn message_texts(body: &Value) -> Vec<(String, String)> {
|
||||
body["result"]["messages"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("prompts/get must carry messages: {body}"))
|
||||
.iter()
|
||||
.map(|message| {
|
||||
(
|
||||
message["role"].as_str().unwrap_or_default().to_owned(),
|
||||
message["content"]["text"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_inserts_pinned_text_inside_the_declared_message() {
|
||||
let (endpoint, _store, _root) = composed_endpoint().await;
|
||||
let body = get(&endpoint, "ops").await;
|
||||
let messages = message_texts(&body);
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
2,
|
||||
"the declared message count is unchanged: {body}"
|
||||
);
|
||||
assert_eq!(messages[0].0, "system");
|
||||
assert_eq!(
|
||||
messages[0].1, "Summarise only the attached document.",
|
||||
"the system message never receives document text: {body}"
|
||||
);
|
||||
assert_eq!(messages[1].0, "user");
|
||||
assert_eq!(
|
||||
messages[1].1,
|
||||
format!("Channel: ops\n\n{PINNED_V1}"),
|
||||
"the pinned text is inserted verbatim after the rendered template: {body}"
|
||||
);
|
||||
assert!(
|
||||
body["result"]["messages"][1].get("tool_calls").is_none(),
|
||||
"content never becomes a tool call: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_keeps_the_pinned_version_after_a_new_resource_version() {
|
||||
let (endpoint, store, _root) = composed_endpoint().await;
|
||||
// Новая опубликованная версия того же Resource не переписывает пин.
|
||||
publish_resource(
|
||||
&endpoint.registry,
|
||||
&store,
|
||||
"res_story316_mcp_composed",
|
||||
PINNED_V2.as_bytes(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let body = get(&endpoint, "ops").await;
|
||||
let messages = message_texts(&body);
|
||||
assert!(
|
||||
messages[1].1.contains(PINNED_V1),
|
||||
"the agent keeps receiving the pinned version: {body}"
|
||||
);
|
||||
assert!(
|
||||
!messages[1].1.contains(PINNED_V2),
|
||||
"a newer Resource version requires a new Prompt publication: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_unavailable_dependency_is_structured_without_messages() {
|
||||
let (endpoint, _store, _root) = composed_endpoint().await;
|
||||
endpoint
|
||||
.registry
|
||||
.revoke_resource(crank_registry::model::resource::RevokeResourceRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: ResourceId::new("res_story316_mcp_composed"),
|
||||
actor_user_id: "user_default_owner".to_owned(),
|
||||
request_id: "story316-mcp".to_owned(),
|
||||
trace_id: "story316-mcp".to_owned(),
|
||||
revoked_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("revocation is the accepted 3.8 path");
|
||||
|
||||
let body = get(&endpoint, "ops").await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"no partial prompt is returned: {body}"
|
||||
);
|
||||
let message = body["error"]["message"].as_str().unwrap_or_default();
|
||||
assert!(
|
||||
message.contains("dependencies[0]"),
|
||||
"the failure names the declaration position: {body}"
|
||||
);
|
||||
assert!(
|
||||
!serde_json::to_string(&body)
|
||||
.unwrap_or_default()
|
||||
.contains(PINNED_V1),
|
||||
"no dependency content appears in the failure: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AC6 (§4): dynamic (template) dependency читается runtime 3.11 через prompts/get
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const DYNAMIC_RESOURCE_ID: &str = "res_story316_mcp_dynamic";
|
||||
const DYNAMIC_DEFAULT_ID: &str = "order-42";
|
||||
|
||||
/// Upstream шаблона: `GET /orders/{order_id}` → `{"id": "<order_id>"}`.
|
||||
async fn spawn_orders_upstream() -> String {
|
||||
use axum::{Router, extract::Path, routing::get};
|
||||
let app = Router::new().route(
|
||||
"/orders/{order_id}",
|
||||
get(|Path(order_id): Path<String>| async move { axum::Json(json!({ "id": order_id })) }),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("upstream must bind a loopback port");
|
||||
let address = listener.local_addr().expect("upstream address");
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.expect("upstream serves");
|
||||
});
|
||||
format!("http://{address}")
|
||||
}
|
||||
|
||||
/// Стенд динамической зависимости: опубликованная read Operation, опубликованный template
|
||||
/// Resource с параметром по умолчанию, составной Prompt и опубликованный Agent.
|
||||
async fn dynamic_endpoint() -> (PromptEndpoint, TestRoot) {
|
||||
let root = TestRoot::new();
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("artifact store opens");
|
||||
let registry = test_registry().await;
|
||||
let upstream = spawn_orders_upstream().await;
|
||||
|
||||
let mut operation = test_operation(&upstream, "story316_prompt_dynamic");
|
||||
operation.id = crank_core::OperationId::new("op_story316_prompt_dynamic");
|
||||
operation.target = Target::Rest(RestTarget {
|
||||
base_url: upstream,
|
||||
method: HttpMethod::Get,
|
||||
path_template: "/orders/{order_id}".to_owned(),
|
||||
static_headers: Default::default(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: Default::default(),
|
||||
});
|
||||
operation.input_schema = object_schema("order_id");
|
||||
operation.execution_config.timeout_ms = 1_000;
|
||||
operation.execution_config.safety = Some(OperationSafetyPolicy {
|
||||
class: OperationSafetyClass::Read,
|
||||
confirmation: None,
|
||||
});
|
||||
operation.input_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.order_id".to_owned(),
|
||||
target: "$.request.path.order_id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.expect("GET Read operation is created through the registry API");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("GET Read operation exact version publishes");
|
||||
|
||||
let resource_id = ResourceId::new(DYNAMIC_RESOURCE_ID);
|
||||
let definition_value = json!({
|
||||
"operation_id": operation.id.to_string(),
|
||||
"operation_version": 1,
|
||||
"uri_template": "crank://orders/{order_id}",
|
||||
"parameters": [{
|
||||
"name": "order_id",
|
||||
"input_path": "input.order_id",
|
||||
"schema": { "type": "string", "required": true, "default_value": DYNAMIC_DEFAULT_ID }
|
||||
}],
|
||||
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
|
||||
"failure": { "outcome": "error" }
|
||||
});
|
||||
let definition = serde_json::to_string(
|
||||
&TemplateSource::parse(&definition_value).expect("template source is valid"),
|
||||
)
|
||||
.expect("normalized definition serializes canonically");
|
||||
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
|
||||
let draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: "crank://templates/story316-order".to_owned(),
|
||||
name: "story316_order".to_owned(),
|
||||
description: "Story 3.16 dynamic dependency".to_owned(),
|
||||
kind: "json".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition,
|
||||
definition_digest: digest.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template Draft is created through the registry API");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: draft.snapshot.resource.updated_at,
|
||||
expected_version: draft.snapshot.version.version,
|
||||
expected_digest: digest,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template exact version publishes");
|
||||
|
||||
let endpoint = bound_prompt_endpoint(
|
||||
registry,
|
||||
store,
|
||||
PromptId::new("prm_story316_mcp_dynamic"),
|
||||
composed_definition(DYNAMIC_RESOURCE_ID, 1),
|
||||
)
|
||||
.await;
|
||||
(endpoint, root)
|
||||
}
|
||||
|
||||
/// AT-3.16-06 (§4): `prompts/get` читает «живой» документ через Resource runtime; вывод вставлен
|
||||
/// дословно внутри объявленного сообщения, роли и число сообщений не меняются.
|
||||
#[tokio::test]
|
||||
async fn get_reads_a_dynamic_dependency_through_the_resource_runtime() {
|
||||
let (endpoint, _root) = dynamic_endpoint().await;
|
||||
let body = get(&endpoint, "ops").await;
|
||||
let messages = message_texts(&body);
|
||||
assert_eq!(
|
||||
messages.len(),
|
||||
2,
|
||||
"a dependency cannot add or remove a declared message: {body}"
|
||||
);
|
||||
assert_eq!(messages[0].0, "system");
|
||||
assert_eq!(
|
||||
messages[0].1, "Summarise only the attached document.",
|
||||
"the system message never receives document text: {body}"
|
||||
);
|
||||
assert_eq!(messages[1].0, "user");
|
||||
assert_eq!(
|
||||
messages[1].1,
|
||||
format!("Channel: ops\n\n{{\"id\":\"{DYNAMIC_DEFAULT_ID}\"}}"),
|
||||
"the pinned template output is inserted verbatim after one blank line: {body}"
|
||||
);
|
||||
assert!(
|
||||
body["result"]["messages"][1].get("tool_calls").is_none(),
|
||||
"content never becomes a tool call: {body}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
//! Story 3.14 acceptance fixtures: a real MCP endpoint over a real PostgreSQL registry.
|
||||
//!
|
||||
//! Everything here is the production path: `build_test_app` + the real
|
||||
//! `CommunityMachineCredentialVerifier`, published Prompt versions created through the registry
|
||||
//! (`create_prompt_draft` → `publish_prompt_draft`), exact bindings written through
|
||||
//! `save_agent_catalog_config_editable_with_prompts`, and an Agent published with `publish_agent`.
|
||||
//! No route stub, no fake service, no seeded Prompt rows behind the registry's back.
|
||||
//!
|
||||
//! Bounded fixture set (names chosen so the bound snapshot order is explicit):
|
||||
//! - `prm_a_greeting` — typed arguments (`name` required string, `tone` optional enum with default)
|
||||
//! and a system + user message;
|
||||
//! - `prm_b_review` — no arguments;
|
||||
//! - `prm_c_archived` — bound, published, then archived (AT-3.14-03);
|
||||
//! - `prm_d_unbound` — published but not bound to the Agent;
|
||||
//! - `prm_e_draft` — Draft only;
|
||||
//! - `prm_f_other` — bound to another Agent of the same workspace (scope isolation).
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolSelectionPolicy,
|
||||
ids::PromptId,
|
||||
prompt::{PromptDefinition, PromptSensitivity},
|
||||
};
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||||
};
|
||||
use crank_registry::{CreateAgentRequest, PostgresRegistry, PublishAgentRequest};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::super::common::{
|
||||
agent_mcp_url, build_test_app, create_platform_api_key, initialize_session,
|
||||
post_jsonrpc_with_headers, spawn_mcp_server, test_registry, test_workspace_id,
|
||||
};
|
||||
|
||||
pub(super) const MODERN_REVISION: &str = "2026-07-28";
|
||||
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
|
||||
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
pub(super) const SALES_AGENT_SLUG: &str = "sales-prompts";
|
||||
pub(super) const OTHER_AGENT_SLUG: &str = "other-prompts";
|
||||
|
||||
/// The exact bound Prompt names of `sales-prompts`, in the deterministic snapshot order
|
||||
/// (`prompt_id` ascending) the service pages over.
|
||||
pub(super) const BOUND_PROMPT_NAMES: [&str; 3] = ["greeting", "review", "archived-prompt"];
|
||||
|
||||
pub(super) fn greeting_definition(content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "greeting",
|
||||
"description": "Greets the customer",
|
||||
"arguments": [
|
||||
{"name": "name", "schema": {"type": "string"}, "required": true},
|
||||
{
|
||||
"name": "tone",
|
||||
"schema": {"type": "string", "enum": ["warm", "dry"]},
|
||||
"required": false,
|
||||
"default": "warm"
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{"role": "system", "content": "Be brief."},
|
||||
{"role": "user", "content": content}
|
||||
]
|
||||
}))
|
||||
.expect("greeting definition is valid")
|
||||
}
|
||||
|
||||
fn review_definition() -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "review",
|
||||
"description": "Reviews a change",
|
||||
"arguments": [],
|
||||
"messages": [{"role": "user", "content": "Review the change."}]
|
||||
}))
|
||||
.expect("review definition is valid")
|
||||
}
|
||||
|
||||
fn archived_definition() -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "archived-prompt",
|
||||
"description": "Still bound after archive",
|
||||
"arguments": [],
|
||||
"messages": [{"role": "user", "content": "Archived but bound."}]
|
||||
}))
|
||||
.expect("archived definition is valid")
|
||||
}
|
||||
|
||||
fn other_definition() -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "other-agent-prompt",
|
||||
"description": "Bound to another Agent",
|
||||
"arguments": [],
|
||||
"messages": [{"role": "user", "content": "Other agent secret."}]
|
||||
}))
|
||||
.expect("other definition is valid")
|
||||
}
|
||||
|
||||
fn draft_definition() -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "draft-prompt",
|
||||
"description": "Never published",
|
||||
"arguments": [],
|
||||
"messages": [{"role": "user", "content": "Draft content."}]
|
||||
}))
|
||||
.expect("draft definition is valid")
|
||||
}
|
||||
|
||||
pub(super) struct PromptEndpoint {
|
||||
pub(super) client: reqwest::Client,
|
||||
pub(super) base_url: String,
|
||||
pub(super) mcp_url: String,
|
||||
pub(super) api_key: String,
|
||||
pub(super) registry: PostgresRegistry,
|
||||
pub(super) greeting_id: PromptId,
|
||||
pub(super) archived_id: PromptId,
|
||||
pub(super) archived_updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
impl PromptEndpoint {
|
||||
/// One modern `prompts/*` request with the required per-request identity.
|
||||
pub(super) async fn modern(&self, method: &str, params: Value, name: Option<&str>) -> Value {
|
||||
self.modern_for(SALES_AGENT_SLUG, &self.api_key, method, params, name)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The same request for an explicitly chosen Agent route and credential.
|
||||
pub(super) async fn modern_for(
|
||||
&self,
|
||||
agent_slug: &str,
|
||||
api_key: &str,
|
||||
method: &str,
|
||||
params: Value,
|
||||
name: Option<&str>,
|
||||
) -> Value {
|
||||
let headers = match name {
|
||||
Some(name) => vec![
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", method),
|
||||
("Mcp-Name", name),
|
||||
],
|
||||
None => vec![
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", method),
|
||||
],
|
||||
};
|
||||
let mut params = params;
|
||||
params["_meta"] = json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-prompts-atdd", "version": "0.1.0"}
|
||||
});
|
||||
let response = post_jsonrpc_with_headers(
|
||||
&self.client,
|
||||
&agent_mcp_url(&self.base_url, agent_slug),
|
||||
api_key,
|
||||
&headers,
|
||||
json!({"jsonrpc": "2.0", "id": 7, "method": method, "params": params}),
|
||||
)
|
||||
.await;
|
||||
json_body(response).await
|
||||
}
|
||||
|
||||
/// One legacy `prompts/*` request inside the sales Agent's initialized session.
|
||||
pub(super) async fn legacy(&self, session: &str, method: &str, params: Value) -> Value {
|
||||
self.legacy_for(SALES_AGENT_SLUG, &self.api_key, session, method, params)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The legacy era resolves workspace and Agent from the initialized *session*, so an explicit
|
||||
/// Agent route and credential select the snapshot the request is served from.
|
||||
pub(super) async fn legacy_for(
|
||||
&self,
|
||||
agent_slug: &str,
|
||||
api_key: &str,
|
||||
session: &str,
|
||||
method: &str,
|
||||
params: Value,
|
||||
) -> Value {
|
||||
let response = self
|
||||
.client
|
||||
.post(agent_mcp_url(&self.base_url, agent_slug))
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 8, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
json_body(response).await
|
||||
}
|
||||
|
||||
pub(super) async fn legacy_session(&self) -> String {
|
||||
initialize_session(&self.client, &self.mcp_url, &self.api_key).await
|
||||
}
|
||||
|
||||
/// An initialized legacy session of an explicitly chosen Agent (its route and credential).
|
||||
pub(super) async fn legacy_session_for(&self, agent_slug: &str, api_key: &str) -> String {
|
||||
initialize_session(
|
||||
&self.client,
|
||||
&agent_mcp_url(&self.base_url, agent_slug),
|
||||
api_key,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// One `prompts/*` request on the sales Agent of the explicitly chosen supported revision.
|
||||
pub(super) async fn on_revision(
|
||||
&self,
|
||||
revision: &str,
|
||||
method: &str,
|
||||
params: Value,
|
||||
name: Option<&str>,
|
||||
) -> Value {
|
||||
self.on_revision_for(
|
||||
SALES_AGENT_SLUG,
|
||||
&self.api_key,
|
||||
revision,
|
||||
method,
|
||||
params,
|
||||
name,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The same request on an explicitly chosen Agent, revision and credential.
|
||||
pub(super) async fn on_revision_for(
|
||||
&self,
|
||||
agent_slug: &str,
|
||||
api_key: &str,
|
||||
revision: &str,
|
||||
method: &str,
|
||||
params: Value,
|
||||
name: Option<&str>,
|
||||
) -> Value {
|
||||
match revision {
|
||||
MODERN_REVISION => {
|
||||
self.modern_for(agent_slug, api_key, method, params, name)
|
||||
.await
|
||||
}
|
||||
LEGACY_REVISION => {
|
||||
let session = self.legacy_session_for(agent_slug, api_key).await;
|
||||
self.legacy_for(agent_slug, api_key, &session, method, params)
|
||||
.await
|
||||
}
|
||||
other => panic!("{other} is not a supported protocol revision"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only credential of the other Agent of the same workspace.
|
||||
pub(super) async fn other_agent_key(&self) -> String {
|
||||
create_platform_api_key(
|
||||
&self.registry,
|
||||
OTHER_AGENT_SLUG,
|
||||
"mcp-prompts-other",
|
||||
&[crank_core::PlatformApiKeyScope::Read],
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn json_body(response: reqwest::Response) -> Value {
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body)
|
||||
.unwrap_or_else(|error| panic!("expected a JSON-RPC body, got {status} {body:?}: {error}"))
|
||||
}
|
||||
|
||||
async fn create_prompt(
|
||||
registry: &PostgresRegistry,
|
||||
prompt_id: &PromptId,
|
||||
definition: PromptDefinition,
|
||||
) -> OffsetDateTime {
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("Prompt Draft is created")
|
||||
.updated_at
|
||||
}
|
||||
|
||||
async fn publish_prompt(
|
||||
registry: &PostgresRegistry,
|
||||
prompt_id: &PromptId,
|
||||
expected_updated_at: OffsetDateTime,
|
||||
) -> OffsetDateTime {
|
||||
registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("prompt publishes as an immutable version")
|
||||
.updated_at
|
||||
}
|
||||
|
||||
async fn create_agent(registry: &PostgresRegistry, agent_slug: &str) -> AgentId {
|
||||
let agent_id = AgentId::new(format!("agent_{agent_slug}"));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: agent_id.clone(),
|
||||
workspace_id: test_workspace_id(),
|
||||
slug: agent_slug.to_owned(),
|
||||
display_name: agent_slug.to_owned(),
|
||||
description: "Story 3.14 Prompt fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: agent_id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.expect("draft Agent is created");
|
||||
agent_id
|
||||
}
|
||||
|
||||
pub(super) async fn bind_prompts(
|
||||
registry: &PostgresRegistry,
|
||||
agent_id: &AgentId,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<u32, crank_registry::RegistryError> {
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
bindings,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn publish_agent(registry: &PostgresRegistry, agent_id: &AgentId) {
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("bound Agent publishes");
|
||||
}
|
||||
|
||||
/// Publish the whole fixture set and start the real MCP server.
|
||||
pub(super) async fn prompt_endpoint() -> PromptEndpoint {
|
||||
let registry = test_registry().await;
|
||||
let greeting_id = PromptId::new("prm_a_greeting");
|
||||
let review_id = PromptId::new("prm_b_review");
|
||||
let archived_id = PromptId::new("prm_c_archived");
|
||||
let unbound_id = PromptId::new("prm_d_unbound");
|
||||
let draft_id = PromptId::new("prm_e_draft");
|
||||
let other_id = PromptId::new("prm_f_other");
|
||||
|
||||
let greeting_at = create_prompt(
|
||||
®istry,
|
||||
&greeting_id,
|
||||
greeting_definition("Hello {{name}}"),
|
||||
)
|
||||
.await;
|
||||
publish_prompt(®istry, &greeting_id, greeting_at).await;
|
||||
let review_at = create_prompt(®istry, &review_id, review_definition()).await;
|
||||
publish_prompt(®istry, &review_id, review_at).await;
|
||||
let archived_created = create_prompt(®istry, &archived_id, archived_definition()).await;
|
||||
let archived_at = publish_prompt(®istry, &archived_id, archived_created).await;
|
||||
let unbound_at = create_prompt(®istry, &unbound_id, review_definition()).await;
|
||||
publish_prompt(®istry, &unbound_id, unbound_at).await;
|
||||
create_prompt(®istry, &draft_id, draft_definition()).await;
|
||||
let other_at = create_prompt(®istry, &other_id, other_definition()).await;
|
||||
publish_prompt(®istry, &other_id, other_at).await;
|
||||
|
||||
let agent_id = create_agent(®istry, SALES_AGENT_SLUG).await;
|
||||
bind_prompts(
|
||||
®istry,
|
||||
&agent_id,
|
||||
&[
|
||||
AgentPromptBinding {
|
||||
prompt_id: greeting_id.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: review_id.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
AgentPromptBinding {
|
||||
prompt_id: archived_id.clone(),
|
||||
prompt_version: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect("exact published Prompt bindings are accepted");
|
||||
publish_agent(®istry, &agent_id).await;
|
||||
|
||||
// AT-3.14-03: archive *after* the binding is fixed in the published Agent snapshot.
|
||||
let archived_updated_at = registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: archived_id.clone(),
|
||||
expected_updated_at: archived_at,
|
||||
archived_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the bound Prompt is archived after the snapshot")
|
||||
.updated_at;
|
||||
|
||||
let other_agent_id = create_agent(®istry, OTHER_AGENT_SLUG).await;
|
||||
bind_prompts(
|
||||
®istry,
|
||||
&other_agent_id,
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: other_id,
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("another Agent binds its own Prompt");
|
||||
publish_agent(®istry, &other_agent_id).await;
|
||||
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
SALES_AGENT_SLUG,
|
||||
"mcp-prompts",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app(
|
||||
registry.clone(),
|
||||
Duration::from_millis(0),
|
||||
Some("https://crank.example.com".to_owned()),
|
||||
))
|
||||
.await;
|
||||
|
||||
PromptEndpoint {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: agent_mcp_url(&base_url, SALES_AGENT_SLUG),
|
||||
base_url,
|
||||
api_key,
|
||||
registry,
|
||||
greeting_id,
|
||||
archived_id,
|
||||
archived_updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a bound greeting Draft edit into a new Draft version (v2) without touching v1.
|
||||
pub(super) async fn edit_greeting_draft(endpoint: &PromptEndpoint) -> OffsetDateTime {
|
||||
let draft = endpoint
|
||||
.registry
|
||||
.get_prompt_draft(&test_workspace_id(), &endpoint.greeting_id)
|
||||
.await
|
||||
.expect("greeting Draft reads");
|
||||
endpoint
|
||||
.registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: endpoint.greeting_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: greeting_definition("Changed {{name}}"),
|
||||
expected_updated_at: draft.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("editing a published Prompt opens a new Draft")
|
||||
.updated_at
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! AT-3.14-02 / AT-3.14-03 / AT-3.14-04: `prompts/get` renders one exact bound Published Prompt
|
||||
//! Version deterministically, rejects every invalid argument before rendering, keeps an archived
|
||||
//! bound version readable, and never serves another Agent's snapshot. Every case runs on both
|
||||
//! supported protocol revisions: the legacy era resolves workspace and Agent from the initialized
|
||||
//! session, so its snapshot selection is proven separately below.
|
||||
|
||||
use crank_core::prompt::MAX_TEXT_BYTES;
|
||||
use crank_registry::RegistryError;
|
||||
use crank_registry::model::AgentPromptBinding;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::fixtures::*;
|
||||
|
||||
fn messages(body: &Value) -> &Vec<Value> {
|
||||
body["result"]["messages"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("prompts/get must carry messages: {body}"))
|
||||
}
|
||||
|
||||
fn greeting_messages() -> Vec<Value> {
|
||||
vec![
|
||||
json!({"role": "system", "content": {"type": "text", "text": "Be brief."}}),
|
||||
json!({"role": "user", "content": {"type": "text", "text": "Hello Ada"}}),
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_renders_typed_arguments_deterministically_on_both_revisions() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
let body = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name": "greeting", "arguments": {"name": "Ada"}}),
|
||||
Some("greeting"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
body["result"]["description"],
|
||||
json!("Greets the customer"),
|
||||
"the bound description is served on {revision}: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
messages(&body),
|
||||
&greeting_messages(),
|
||||
"the typed renderer output is served unchanged on {revision}: {body}"
|
||||
);
|
||||
|
||||
let repeated = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name": "greeting", "arguments": {"name": "Ada"}}),
|
||||
Some("greeting"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
body, repeated,
|
||||
"rendering is deterministic on {revision}: {repeated}"
|
||||
);
|
||||
|
||||
// The rendered enum/default argument path is accepted too.
|
||||
let with_tone = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name": "greeting", "arguments": {"name": "Ada", "tone": "dry"}}),
|
||||
Some("greeting"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
messages(&with_tone)[1]["content"],
|
||||
json!({"type": "text", "text": "Hello Ada"}),
|
||||
"an explicit enum value still renders the bound template on {revision}: {with_tone}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_rejects_each_invalid_argument_before_rendering_without_disclosure() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
|
||||
let oversized = "x".repeat(MAX_TEXT_BYTES + 1);
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
for (arguments, reason, argument) in [
|
||||
(json!({}), "missing_argument", "name"),
|
||||
(
|
||||
json!({"name": "Ada", "extra": "x"}),
|
||||
"unknown_argument",
|
||||
"extra",
|
||||
),
|
||||
(json!({"name": 5}), "argument_invalid", "name"),
|
||||
(
|
||||
json!({"name": "Ada", "tone": "loud"}),
|
||||
"argument_invalid",
|
||||
"tone",
|
||||
),
|
||||
(json!({"name": oversized}), "argument_too_large", "name"),
|
||||
] {
|
||||
let body = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name": "greeting", "arguments": arguments}),
|
||||
Some("greeting"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
body["error"]["code"],
|
||||
json!(-32602),
|
||||
"{reason} on {revision}: a typed argument rejection is invalid params: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
body["error"]["data"]["reason"],
|
||||
json!(reason),
|
||||
"{reason} on {revision}: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
body["error"]["data"]["argument"],
|
||||
json!(argument),
|
||||
"{reason} on {revision}: {body}"
|
||||
);
|
||||
|
||||
// No partial rendering and no foreign metadata: neither bound content nor any prompt
|
||||
// message may appear anywhere in the error envelope.
|
||||
let serialized = body.to_string();
|
||||
for leaked in [
|
||||
"Be brief.",
|
||||
"Hello ",
|
||||
"Archived but bound.",
|
||||
"Draft content.",
|
||||
] {
|
||||
assert!(
|
||||
!serialized.contains(leaked),
|
||||
"{reason} on {revision}: the rejection must not disclose {leaked:?}: {serialized}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"{reason} on {revision}: a rejected request carries no result: {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_serves_the_archived_bound_version_and_archive_blocks_new_bindings() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
|
||||
// AT-3.14-03: the immutable snapshot behaviour survives the archive, on every revision.
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
let serving = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name": "archived-prompt"}),
|
||||
Some("archived-prompt"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
messages(&serving),
|
||||
&vec![
|
||||
json!({"role": "user", "content": {"type": "text", "text": "Archived but bound."}})
|
||||
],
|
||||
"an archived Prompt Version bound before the archive keeps serving on {revision}: {serving}"
|
||||
);
|
||||
}
|
||||
|
||||
// Archive forbids new bindings: the exact version may not be attached to another Agent.
|
||||
let other_agent = crank_core::AgentId::new(format!("agent_{OTHER_AGENT_SLUG}"));
|
||||
let rebind = bind_prompts(
|
||||
&endpoint.registry,
|
||||
&other_agent,
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: endpoint.archived_id.clone(),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(rebind, Err(RegistryError::PromptArchived { .. })),
|
||||
"archive must refuse new bindings, got {rebind:?}"
|
||||
);
|
||||
|
||||
// Archive forbids new publications of the same Prompt (archived is terminal lifecycle).
|
||||
let publication = endpoint
|
||||
.registry
|
||||
.publish_prompt_draft(crank_registry::model::PublishPromptRequest {
|
||||
workspace_id: crank_core::WorkspaceId::new("ws_default"),
|
||||
prompt_id: endpoint.archived_id.clone(),
|
||||
expected_updated_at: endpoint.archived_updated_at,
|
||||
published_at: time::OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
matches!(publication, Err(RegistryError::PromptNotDraft { .. })),
|
||||
"archive must refuse new publications, got {publication:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_of_an_unknown_unbound_or_foreign_prompt_is_indistinguishable() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
for name in [
|
||||
"draft-prompt",
|
||||
"other-agent-prompt",
|
||||
"prm_a_greeting",
|
||||
"never-existed",
|
||||
] {
|
||||
let body = endpoint
|
||||
.on_revision(revision, "prompts/get", json!({"name": name}), Some(name))
|
||||
.await;
|
||||
assert_eq!(
|
||||
body["error"]["code"],
|
||||
json!(-32602),
|
||||
"{name} on {revision}: an unaddressable Prompt is invalid params: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
json!("the requested prompt is not available"),
|
||||
"Draft, unbound, foreign and unknown names share one safe answer on {revision}: {body}"
|
||||
);
|
||||
let serialized = body.to_string();
|
||||
for leaked in ["Other agent secret.", "Draft content.", "Be brief."] {
|
||||
assert!(
|
||||
!serialized.contains(leaked),
|
||||
"{name} on {revision}: leaked {leaked:?}: {serialized}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_serves_the_exact_bound_version_after_a_draft_edit() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
edit_greeting_draft(&endpoint).await;
|
||||
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
let body = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/get",
|
||||
json!({"name": "greeting", "arguments": {"name": "Ada"}}),
|
||||
Some("greeting"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
messages(&body)[1]["content"],
|
||||
json!({"type": "text", "text": "Hello Ada"}),
|
||||
"the bound v1 snapshot stays immutable after a Draft edit on {revision}: {body}"
|
||||
);
|
||||
|
||||
let listed = endpoint
|
||||
.on_revision(revision, "prompts/list", json!({}), None)
|
||||
.await;
|
||||
assert_eq!(
|
||||
listed["result"]["prompts"][0]["description"],
|
||||
json!("Greets the customer"),
|
||||
"discovery still describes the bound version, not the new Draft, on {revision}: {listed}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The legacy era takes workspace and Agent from the *initialized session*, not from the request
|
||||
/// body. A session of the other Agent therefore serves that Agent's snapshot, and a Prompt bound to
|
||||
/// the sales Agent is indistinguishable from an unknown name on it.
|
||||
#[tokio::test]
|
||||
async fn legacy_session_serves_only_its_own_agent_snapshot() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
let other_key = endpoint.other_agent_key().await;
|
||||
let session = endpoint
|
||||
.legacy_session_for(OTHER_AGENT_SLUG, &other_key)
|
||||
.await;
|
||||
|
||||
let own = endpoint
|
||||
.legacy_for(
|
||||
OTHER_AGENT_SLUG,
|
||||
&other_key,
|
||||
&session,
|
||||
"prompts/get",
|
||||
json!({"name": "other-agent-prompt"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
messages(&own),
|
||||
&vec![json!({"role": "user", "content": {"type": "text", "text": "Other agent secret."}})],
|
||||
"the session's own bound snapshot is served: {own}"
|
||||
);
|
||||
|
||||
let listed = endpoint
|
||||
.legacy_for(
|
||||
OTHER_AGENT_SLUG,
|
||||
&other_key,
|
||||
&session,
|
||||
"prompts/list",
|
||||
json!({}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
listed["result"]["prompts"]
|
||||
.as_array()
|
||||
.expect("the session lists its own prompts")
|
||||
.iter()
|
||||
.map(|prompt| prompt["name"].as_str().unwrap_or_default().to_owned())
|
||||
.collect::<Vec<String>>(),
|
||||
vec!["other-agent-prompt"],
|
||||
"the legacy session lists only its own bound Prompt: {listed}"
|
||||
);
|
||||
|
||||
// Every Prompt bound to the sales Agent is foreign to this session.
|
||||
for name in ["greeting", "review", "archived-prompt"] {
|
||||
let body = endpoint
|
||||
.legacy_for(
|
||||
OTHER_AGENT_SLUG,
|
||||
&other_key,
|
||||
&session,
|
||||
"prompts/get",
|
||||
json!({"name": name}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
body["error"]["code"],
|
||||
json!(-32602),
|
||||
"{name}: a foreign bound Prompt is invalid params on the legacy era: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
body["error"]["message"],
|
||||
json!("the requested prompt is not available"),
|
||||
"{name}: a foreign bound Prompt shares the safe answer: {body}"
|
||||
);
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"{name}: a foreign bound Prompt carries no result: {body}"
|
||||
);
|
||||
let serialized = body.to_string();
|
||||
for leaked in ["Be brief.", "Hello ", "Archived but bound."] {
|
||||
assert!(
|
||||
!serialized.contains(leaked),
|
||||
"{name}: the foreign rejection must not disclose {leaked:?}: {serialized}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! AT-3.14-04: the accepted discovery budget (≤150 ms p95) measured on the real endpoint.
|
||||
//!
|
||||
//! The measurement is a real one: sequential HTTP `prompts/list` requests against the task-owned
|
||||
//! loopback MCP server, the real PostgreSQL registry and the fixture's three bound Published Prompt
|
||||
//! Versions in a debug build. It is recorded as evidence with workload/revision/environment/sample
|
||||
//! count instead of being replaced by an assertion about speed. A future release benchmark is not
|
||||
//! part of this story.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::fixtures::*;
|
||||
|
||||
const SAMPLES: usize = 30;
|
||||
const WARMUP: usize = 3;
|
||||
const BUDGET: Duration = Duration::from_millis(150);
|
||||
|
||||
fn percentile(sorted: &[Duration], percentile: f64) -> Duration {
|
||||
let rank = ((percentile / 100.0) * sorted.len() as f64).ceil() as usize;
|
||||
sorted[rank.saturating_sub(1).min(sorted.len() - 1)]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prompts_list_discovery_p95_stays_within_the_accepted_budget() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
|
||||
for _ in 0..WARMUP {
|
||||
let body = endpoint.modern("prompts/list", json!({}), None).await;
|
||||
assert!(
|
||||
body["result"].is_object(),
|
||||
"warmup list must succeed: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut samples = Vec::with_capacity(SAMPLES);
|
||||
for _ in 0..SAMPLES {
|
||||
let started = Instant::now();
|
||||
let body = endpoint.modern("prompts/list", json!({}), None).await;
|
||||
samples.push(started.elapsed());
|
||||
assert!(
|
||||
body["result"]["prompts"].is_array(),
|
||||
"every measured list must serve the bound page: {body}"
|
||||
);
|
||||
}
|
||||
samples.sort_unstable();
|
||||
|
||||
let p50 = percentile(&samples, 50.0);
|
||||
let p95 = percentile(&samples, 95.0);
|
||||
let max = *samples.last().unwrap();
|
||||
let report = json!({
|
||||
"case": "AT-3.14-04",
|
||||
"surface": "prompts/list",
|
||||
"revision": MODERN_REVISION,
|
||||
"workload": "one bound Published Prompt snapshot of 3 versions (typed arguments), no pagination",
|
||||
"environment": "debug build, task-owned loopback MCP server, PostgreSQL test container, 4 vCPU",
|
||||
"samples": SAMPLES,
|
||||
"warmup_samples": WARMUP,
|
||||
"p50_ms": p50.as_secs_f64() * 1_000.0,
|
||||
"p95_ms": p95.as_secs_f64() * 1_000.0,
|
||||
"max_ms": max.as_secs_f64() * 1_000.0,
|
||||
"budget_ms": BUDGET.as_millis(),
|
||||
});
|
||||
println!("AT-3.14-04 discovery latency evidence: {report}");
|
||||
|
||||
if let Ok(path) = std::env::var("CRANK_PROMPTS_P95_REPORT") {
|
||||
std::fs::write(&path, serde_json::to_vec_pretty(&report).unwrap())
|
||||
.unwrap_or_else(|error| panic!("latency evidence must be writable at {path}: {error}"));
|
||||
}
|
||||
|
||||
assert!(
|
||||
p95 <= BUDGET,
|
||||
"prompts/list discovery p95 {p95:?} must stay within {BUDGET:?} ({report})"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! AT-3.14-01 / AT-3.14-04: `prompts/list` serves exactly the bound Published Prompt Versions with
|
||||
//! revision-scoped pagination and typed argument metadata; Draft, unbound and foreign Prompts of
|
||||
//! another Agent are never disclosed. Every case runs on both supported protocol revisions, because
|
||||
//! AC-4 requires the behaviour to be proven per revision and the legacy era resolves workspace and
|
||||
//! Agent from the initialized session instead of the request body.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::fixtures::*;
|
||||
|
||||
fn names(page: &Value) -> Vec<String> {
|
||||
page["result"]["prompts"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("prompts/list must carry a prompts array: {page}"))
|
||||
.iter()
|
||||
.map(|prompt| prompt["name"].as_str().unwrap_or_default().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_serves_only_bound_published_prompts_with_typed_arguments() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
let body = endpoint
|
||||
.on_revision(revision, "prompts/list", json!({}), None)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
body.get("error").is_none(),
|
||||
"prompts/list must succeed on {revision}: {body}"
|
||||
);
|
||||
let listed = names(&body);
|
||||
assert_eq!(
|
||||
listed, BOUND_PROMPT_NAMES,
|
||||
"only the bound Published Prompt Versions may be listed on {revision}: {body}"
|
||||
);
|
||||
for excluded in ["draft-prompt", "other-agent-prompt"] {
|
||||
assert!(
|
||||
!listed.contains(&excluded.to_owned()),
|
||||
"{excluded} must not be discoverable on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
let greeting = body["result"]["prompts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|prompt| prompt["name"] == json!("greeting"))
|
||||
.expect("the bound greeting is listed");
|
||||
assert_eq!(greeting["description"], json!("Greets the customer"));
|
||||
let arguments = greeting["arguments"]
|
||||
.as_array()
|
||||
.expect("the listed Prompt must carry argument metadata");
|
||||
assert_eq!(
|
||||
arguments.len(),
|
||||
2,
|
||||
"both arguments are advertised on {revision}: {greeting}"
|
||||
);
|
||||
assert_eq!(arguments[0]["name"], json!("name"));
|
||||
assert_eq!(arguments[0]["required"], json!(true));
|
||||
assert_eq!(arguments[0]["schema"]["type"], json!("string"));
|
||||
assert_eq!(arguments[1]["name"], json!("tone"));
|
||||
assert_eq!(arguments[1]["required"], json!(false));
|
||||
assert_eq!(arguments[1]["schema"]["enum"], json!(["warm", "dry"]));
|
||||
assert_eq!(arguments[1]["default"], json!("warm"));
|
||||
assert!(
|
||||
greeting.get("messages").is_none(),
|
||||
"discovery must not disclose message content on {revision}: {greeting}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_paginates_deterministically_and_binds_the_cursor_to_the_revision() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
let first = endpoint
|
||||
.on_revision(revision, "prompts/list", json!({"limit": 2}), None)
|
||||
.await;
|
||||
let cursor = first["result"]["nextCursor"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| {
|
||||
panic!("a bounded first page must carry a continuation on {revision}: {first}")
|
||||
})
|
||||
.to_owned();
|
||||
assert_eq!(
|
||||
names(&first),
|
||||
vec!["greeting", "review"],
|
||||
"the first page is deterministic on {revision}: {first}"
|
||||
);
|
||||
|
||||
let second = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/list",
|
||||
json!({"cursor": cursor.clone(), "limit": 2}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&second),
|
||||
vec!["archived-prompt"],
|
||||
"the continuation serves the next bound slice and nothing else on {revision}: {second}"
|
||||
);
|
||||
assert!(
|
||||
second["result"].get("nextCursor").is_none(),
|
||||
"the last page carries no continuation on {revision}: {second}"
|
||||
);
|
||||
|
||||
// A page is never mixed across protocol revisions: the other era refuses this cursor.
|
||||
let other_revision = match revision {
|
||||
MODERN_REVISION => LEGACY_REVISION,
|
||||
_ => MODERN_REVISION,
|
||||
};
|
||||
let cross_revision = endpoint
|
||||
.on_revision(
|
||||
other_revision,
|
||||
"prompts/list",
|
||||
json!({"cursor": cursor.clone()}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
cross_revision["error"]["code"],
|
||||
json!(-32602),
|
||||
"a {revision} cursor must be refused as invalid params on {other_revision}: {cross_revision}"
|
||||
);
|
||||
|
||||
// A malformed token is invalid params, never the first page.
|
||||
let malformed = endpoint
|
||||
.on_revision(
|
||||
revision,
|
||||
"prompts/list",
|
||||
json!({"cursor": "not-a-cursor"}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
malformed["error"]["code"],
|
||||
json!(-32602),
|
||||
"a malformed cursor is invalid params on {revision}: {malformed}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_of_an_agent_shows_only_its_own_bound_snapshot() {
|
||||
let endpoint = prompt_endpoint().await;
|
||||
// The other Agent binds exactly one Prompt; it must not see the sales Agent's snapshot.
|
||||
let other_key = endpoint.other_agent_key().await;
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
let body = endpoint
|
||||
.on_revision_for(
|
||||
OTHER_AGENT_SLUG,
|
||||
&other_key,
|
||||
revision,
|
||||
"prompts/list",
|
||||
json!({}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&body),
|
||||
vec!["other-agent-prompt"],
|
||||
"an Agent sees only its own bound snapshot on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user