[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:
Hermes DevOps committed 2026-10-25 08:05:37 +00:00
1 parent 1b6db09bd1
commit 301dce301a
357 files changed
+118831 -5113

No files matched your search

@@ -0,0 +1,939 @@
use super::*;
use base64::Engine as _;
use std::sync::Arc;
#[path = "template_discovery_binary.rs"]
mod binary_fixture;
use binary_fixture::{TestValkey, publish_binary_template};
async fn template_order_lookup(
State(calls): State<Arc<AtomicUsize>>,
Path(order_id): Path<String>,
) -> AxumJson<Value> {
calls.fetch_add(1, Ordering::SeqCst);
if order_id == "00000000-0000-4000-8000-000000000001" {
tokio::time::sleep(std::time::Duration::from_millis(600)).await;
}
AxumJson(json!({ "id": order_id, "order_id": order_id, "status": "found" }))
}
async fn template_binary_lookup(
State(calls): State<Arc<AtomicUsize>>,
Path(order_id): Path<String>,
headers: axum::http::HeaderMap,
) -> Response<Body> {
use base64::Engine as _;
calls.fetch_add(1, Ordering::SeqCst);
if headers
.get("authorization")
.and_then(|value| value.to_str().ok())
!= Some("Bearer story311-test-token")
{
return Response::builder()
.status(401)
.header("content-type", "application/json")
.body(Body::from(r#"{"error":"unauthorized"}"#))
.unwrap();
}
let payload = if order_id.ends_with("d481") {
json!({ "data_base64": "not-base64" })
} else if order_id.ends_with("d482") {
json!({ "data_base64": "AA==", "extra": "not-allowed" })
} else if order_id.ends_with("d484") {
json!({
"data_base64": base64::engine::general_purpose::STANDARD.encode(vec![0_u8; 65_537])
})
} else if order_id.ends_with("d485") {
json!({
"data_base64": base64::engine::general_purpose::STANDARD.encode(vec![0_u8; 65_536])
})
} else {
json!({
"data_base64": base64::engine::general_purpose::STANDARD.encode([0_u8, 255, 1, 253, 254, 255])
})
};
let mime = if order_id.ends_with("d483") {
"text/plain"
} else {
"application/json"
};
Response::builder()
.status(200)
.header("content-type", mime)
.body(Body::from(serde_json::to_vec(&payload).unwrap()))
.unwrap()
}
async fn template_order_head(
State(calls): State<Arc<AtomicUsize>>,
Path(order_id): Path<String>,
) -> Response<Body> {
calls.fetch_add(1, Ordering::SeqCst);
Response::builder()
.status(200)
.header("x_order_id", order_id)
.body(Body::empty())
.unwrap()
}
#[path = "template_discovery_cache_loss.rs"]
mod cache_loss;
/// Regression oracle for Story 3.11: a real, exact-version template bound to the published Agent
/// must be discoverable, rather than being confused with the empty-template positive control.
#[tokio::test]
async fn published_agent_discovers_its_bound_template_on_supported_revisions() {
let (valkey, port) = TestValkey::start();
let cache = Arc::new(
crank_runtime::RedisCacheStore::connect(
crank_core::CacheBackend::Valkey,
&format!("redis://127.0.0.1:{port}/0"),
)
.await
.expect("runtime must connect to test-owned Valkey"),
);
let endpoint = standard_endpoint_with_cache("bound_template_discovery", Some(cache)).await;
let registry: &PostgresRegistry = &endpoint.registry;
let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("test upstream must bind a loopback port");
let upstream_address = upstream_listener.local_addr().unwrap();
let upstream_calls = Arc::new(AtomicUsize::new(0));
let upstream = axum::Router::new()
.route("/orders/{order_id}", get(template_order_lookup))
.route("/orders-binary/{order_id}", get(template_binary_lookup))
.route("/order-metadata/{order_id}", head(template_order_head))
.with_state(Arc::clone(&upstream_calls));
tokio::spawn(async move {
axum::serve(upstream_listener, upstream)
.await
.expect("test upstream must serve");
});
let mut operation = test_operation(&format!("http://{upstream_address}"), "bound_order_lookup");
operation.target = Target::Rest(RestTarget {
base_url: format!("http://{upstream_address}"),
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
.input_schema
.fields
.get_mut("order_id")
.unwrap()
.format = Some("uuid".to_owned());
operation.execution_config.timeout_ms = 300;
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 must be created through 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 must publish");
let published = registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
.await
.expect("published Agent snapshot must be readable")
.expect("published Agent version 1 must exist");
let operation_id = operation.id.to_string();
let resource_id = ResourceId::new("res_bound_template_discovery");
let uri = "crank://orders/{order_id}";
let head_uri = "crank://orders-metadata/{order_id}";
let definition_value = json!({
"operation_id": operation_id,
"operation_version": 1,
"uri_template": uri,
"parameters": [{
"name": "order_id",
"input_path": "input.order_id",
"schema": { "type": "string", "required": true, "format": "uuid" }
}],
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
"failure": { "outcome": "error" }
});
let normalized_source = TemplateSource::parse(&definition_value)
.expect("template fixture must satisfy the Story 3.10 source contract");
let definition = serde_json::to_string(&normalized_source)
.expect("normalized definition must serialize 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/order-lookup".to_owned(),
name: "order_lookup".to_owned(),
description: "Published order lookup template".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition.clone(),
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("template Draft must be 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.clone(),
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("template exact version must publish");
let mut head_operation = test_operation(
&format!("http://{upstream_address}"),
"bound_order_metadata",
);
head_operation.id = OperationId::new("op_bound_order_metadata");
head_operation.target = Target::Rest(RestTarget {
base_url: format!("http://{upstream_address}"),
method: HttpMethod::Head,
path_template: "/order-metadata/{order_id}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: vec![RestResponseDescriptor {
status_code: 200,
media_type: None,
schema_variant: 0,
}],
multipart_field_mime_types: Default::default(),
});
head_operation.input_schema = object_schema("order_id");
head_operation
.input_schema
.fields
.get_mut("order_id")
.unwrap()
.format = Some("uuid".to_owned());
head_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,
}],
};
head_operation
.output_schema
.fields
.get_mut("id")
.unwrap()
.kind = SchemaKind::Number;
head_operation.output_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.response.data.status".to_owned(),
target: "$.output.id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
head_operation.execution_config.timeout_ms = 300;
head_operation.execution_config.safety = Some(OperationSafetyPolicy {
class: OperationSafetyClass::Read,
confirmation: None,
});
registry
.create_operation(&test_workspace_id(), &head_operation, Some("alice"))
.await
.expect("HEAD Read operation must be created");
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &head_operation.id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
})
.await
.expect("HEAD Read operation must publish");
let head_resource_id = ResourceId::new("res_bound_template_head");
let head_definition_value = json!({
"operation_id": head_operation.id.as_str(), "operation_version": 1,
"uri_template": head_uri,
"parameters": [{"name":"order_id","input_path":"input.order_id","schema":{"type":"string","required":true,"format":"uuid"}}],
"cache": {"ttl_ms":60000,"vary":["order_id"],"max_bytes":65536}, "failure":{"outcome":"error"}
});
let head_source = TemplateSource::parse(&head_definition_value)
.expect("HEAD metadata definition must be valid");
let head_definition = serde_json::to_string(&head_source).unwrap();
let head_digest = format!("{:x}", Sha256::digest(head_definition.as_bytes()));
let head_draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: head_resource_id.clone(),
uri: "crank://templates/order-metadata".to_owned(),
name: "order_metadata".to_owned(),
description: "Published order metadata template".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: head_definition,
definition_digest: head_digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("HEAD template Draft must be created");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: head_resource_id.clone(),
expected_updated_at: head_draft.snapshot.resource.updated_at,
expected_version: head_draft.snapshot.version.version,
expected_digest: head_digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("HEAD template must be published");
let now = OffsetDateTime::now_utc();
let mut agent_draft = published.snapshot.clone();
agent_draft.version = 2;
agent_draft.status = AgentStatus::Draft;
agent_draft.created_at = now;
registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: &agent_draft,
bindings: &published.bindings,
updated_at: &now,
})
.await
.expect("a new Agent Draft must be created for the exact template binding");
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
agent_version: 2,
bindings: &published.bindings,
tool_selection_policy: &published.snapshot.tool_selection_policy,
resource_bindings: &[
AgentResourceBinding {
resource_id: resource_id.clone(),
resource_version: 1,
},
AgentResourceBinding {
resource_id: head_resource_id.clone(),
resource_version: 1,
},
],
expected_state: None,
})
.await
.expect("exact template version must be bound to the Agent Draft");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: 2,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("Agent snapshot with the exact template binding must publish");
let unbound_id = ResourceId::new("res_unbound_template");
let mut unbound_json = definition_value.clone();
unbound_json["uri_template"] = json!("crank://other-orders/{order_id}");
let unbound_source =
TemplateSource::parse(&unbound_json).expect("unbound template definition remains valid");
let unbound_definition = serde_json::to_string(&unbound_source).unwrap();
let unbound_digest = format!("{:x}", Sha256::digest(unbound_definition.as_bytes()));
let unbound_draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: unbound_id.clone(),
uri: "crank://templates/unbound-order".to_owned(),
name: "unbound_order".to_owned(),
description: "Published but not bound".to_owned(),
kind: "text".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: unbound_definition.clone(),
definition_digest: unbound_digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("unbound template Draft must be created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: unbound_id,
expected_updated_at: unbound_draft.snapshot.resource.updated_at,
expected_version: unbound_draft.snapshot.version.version,
expected_digest: unbound_digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("unbound template must be published without an Agent binding");
// Prove the fixture is a real exact-version Published template binding before MCP is called.
let (publication, stored_definition) = registry
.resolve_resource_template_publication(test_workspace_id().as_str(), &resource_id, 1)
.await
.expect("the exact Published template source must resolve");
assert_eq!(publication.source_kind, "template");
assert_eq!(publication.version, 1);
assert_eq!(stored_definition.definition_json, definition);
assert_eq!(stored_definition.definition_digest, digest);
assert_eq!(
TemplateSource::parse(
&serde_json::from_str(&stored_definition.definition_json)
.expect("stored definition must remain JSON")
)
.expect("stored definition must remain normalized and valid"),
normalized_source
);
let published_operation = registry
.get_operation_version(&test_workspace_id(), &operation.id, 1)
.await
.expect("the exact Published Read Operation must be readable")
.expect("the exact operation version must exist");
assert_eq!(
published_operation.status,
crank_core::OperationStatus::Published
);
assert_eq!(published_operation.version, 1);
assert!(matches!(
&published_operation.snapshot.target,
Target::Rest(target)
if target.method == HttpMethod::Get
&& target.path_template == "/orders/{order_id}"
));
assert_eq!(
published_operation
.snapshot
.execution_config
.safety
.as_ref()
.map(|policy| policy.class),
Some(OperationSafetyClass::Read),
"the pinned operation must be explicitly classified as Read"
);
assert!(
published_operation
.snapshot
.execution_config
.approval_policy
.is_none(),
"the pinned Read operation must not require approval"
);
assert_eq!(
published_operation.snapshot.input_schema.fields["order_id"]
.format
.as_deref(),
Some("uuid"),
"the published input schema must match the template parameter"
);
let exact_published_agent = registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 2)
.await
.expect("published Agent snapshot must be readable")
.expect("the bound Agent version must exist");
assert_eq!(
exact_published_agent.snapshot.status,
AgentStatus::Published,
"the binding must belong to a Published Agent snapshot"
);
assert_eq!(exact_published_agent.snapshot.version, 2);
assert_eq!(
exact_published_agent.resource_bindings,
vec![
AgentResourceBinding {
resource_id: resource_id.clone(),
resource_version: 1
},
AgentResourceBinding {
resource_id: head_resource_id.clone(),
resource_version: 1
},
],
"the fixture must bind the exact template version"
);
let mut checks = RevisionChecks::default();
for revision in supported_revisions() {
let response = list_resource_templates(&endpoint, &revision).await;
let status = response.status();
let body = json_body(response).await;
println!("template discovery {revision}: HTTP {status} {body}");
checks.require(status == reqwest::StatusCode::OK, || {
format!("template discovery HTTP status on {revision}: HTTP {status} {body}")
});
let Some(result) = checks.result(&body, &revision, "resources/templates/list") else {
continue;
};
require_list_result_shape(&mut checks, &body, &revision, "resources/templates/list");
let Some(templates) = result.get("resourceTemplates").and_then(Value::as_array) else {
checks.require(false, || {
format!(
"resources/templates/list must return resourceTemplates on {revision}: {body}"
)
});
continue;
};
checks.require(templates.len() == 2, || {
format!("the exact bound Published templates must be listed on {revision}: {body}")
});
checks.require(
templates
.iter()
.any(|template| template["uriTemplate"] == head_uri),
|| format!("the bound HEAD metadata template must be listed on {revision}: {body}"),
);
checks.require(result.get("nextCursor").is_none(), || {
format!("a complete template page must not advertise nextCursor on {revision}: {body}")
});
if let Some(template) = templates.first() {
for (field, expected) in [
("uriTemplate", json!(uri)),
("name", json!("order_lookup")),
("mimeType", json!("application/json")),
("description", json!("Published order lookup template")),
] {
checks.require(template.get(field) == Some(&expected), || {
format!(
"template {field} must match the published definition on {revision}: {body}"
)
});
}
}
let mut cursor: Option<String> = None;
let mut paged_templates = Vec::new();
for _ in 0..10 {
let params = cursor.as_ref().map_or_else(
|| json!({ "limit": 1 }),
|cursor| json!({ "limit": 1, "cursor": cursor }),
);
let body =
json_body(list_resource_templates_with_params(&endpoint, &revision, params).await)
.await;
let Some(result) = body.get("result") else {
panic!("template page failed on {revision}: {body}");
};
paged_templates.extend(result["resourceTemplates"].as_array().unwrap().clone());
cursor = result
.get("nextCursor")
.and_then(Value::as_str)
.map(str::to_owned);
if cursor.is_none() {
break;
}
}
assert_eq!(
paged_templates.len(),
2,
"pagination must eventually yield both bound templates on {revision}: {paged_templates:?}"
);
let paged_uris: BTreeSet<String> = paged_templates
.iter()
.filter_map(|item| item["uriTemplate"].as_str().map(str::to_owned))
.collect();
assert_eq!(
paged_uris,
BTreeSet::from([uri.to_owned(), head_uri.to_owned()])
);
let invalid_cursor = json_body(
list_resource_templates_with_params(
&endpoint,
&revision,
json!({"cursor":"not-a-valid-cursor"}),
)
.await,
)
.await;
checks.require(invalid_cursor.get("result").is_none() && invalid_cursor["error"]["code"].as_i64() == Some(-32602), || {
format!("template list must reject a malformed scoped cursor on {revision}: {invalid_cursor}")
});
}
let (binary_template, auth_profile_id) = publish_binary_template(
registry,
&endpoint.agent_id,
&format!("http://{upstream_address}"),
)
.await;
let binary_bytes = [0_u8, 255, 1, 253, 254, 255];
let mut binary_cache_warmed = false;
for revision in supported_revisions() {
let exact_uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480";
let binary_calls_before = upstream_calls.load(Ordering::SeqCst);
let body = json_body(read_resource(&endpoint, &revision, exact_uri, None).await).await;
assert!(
body.get("error").is_none(),
"declared binary runtime read failed on {revision}: {body}"
);
let content = &body["result"]["contents"][0];
assert_eq!(content["uri"], exact_uri);
assert_eq!(content["mimeType"], "application/pdf");
assert_eq!(
base64::engine::general_purpose::STANDARD
.decode(content["blob"].as_str().unwrap())
.unwrap(),
binary_bytes,
"binary Resource wire bytes must exactly match the REST output on {revision}"
);
assert!(
content.get("text").is_none(),
"binary content must not be represented as text"
);
let expected_calls = binary_calls_before + usize::from(!binary_cache_warmed);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
expected_calls,
"the binary read must be fetched once, then served from cache across revisions"
);
binary_cache_warmed = true;
let cached = json_body(read_resource(&endpoint, &revision, exact_uri, None).await).await;
assert_eq!(cached["result"]["contents"][0]["blob"], content["blob"]);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
expected_calls,
"the authenticated binary read must hit its own cache on {revision}"
);
let boundary_uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d485";
let boundary =
json_body(read_resource(&endpoint, &revision, boundary_uri, None).await).await;
let boundary_bytes = base64::engine::general_purpose::STANDARD
.decode(boundary["result"]["contents"][0]["blob"].as_str().unwrap())
.unwrap();
assert_eq!(
boundary_bytes.len(),
65_536,
"max_bytes boundary is inclusive on {revision}"
);
for (case, uri) in [
(
"malformed base64",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d481",
),
(
"unexpected field",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d482",
),
(
"wrong MIME",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d483",
),
(
"oversize body",
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d484",
),
] {
let uri = if revision == MODERN_REVISION {
uri.to_owned()
} else {
uri.replace("4372", "4373")
};
let calls_before_negative = upstream_calls.load(Ordering::SeqCst);
let rejected = json_body(read_resource(&endpoint, &revision, &uri, None).await).await;
assert!(
rejected.get("result").is_none() && rejected.get("error").is_some(),
"{case} binary result must fail closed on {revision}: {rejected}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_negative + 1,
"{case} case must reach the REST response mapper on {revision}: {uri}"
);
}
}
let calls_before_auth_profile_cache_confirmation = upstream_calls.load(Ordering::SeqCst);
for revision in supported_revisions() {
let cached = json_body(
read_resource(
&endpoint,
&revision,
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480",
None,
)
.await,
)
.await;
assert!(
cached.get("result").is_some(),
"the exact AuthProfile-backed response must be cached before revoke on {revision}: {cached}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_auth_profile_cache_confirmation,
"the pre-revoke control must hit the live AuthProfile-backed cache on {revision}"
);
}
let calls_before_auth_profile_revoke = upstream_calls.load(Ordering::SeqCst);
sqlx::query("delete from auth_profiles where id = $1")
.bind(auth_profile_id.as_str())
.execute(registry.pool())
.await
.expect("the test-owned pinned AuthProfile is revoked");
for revision in supported_revisions() {
let uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480";
let revoked = json_body(read_resource(&endpoint, &revision, uri, None).await).await;
assert!(
revoked.get("result").is_none(),
"a missing pinned AuthProfile must fail closed before returning cache on {revision}: {revoked}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_auth_profile_revoke,
"revoking the pinned AuthProfile must prevent both cached return and REST dispatch"
);
}
assert_eq!(binary_template, "crank://orders-binary/{order_id}");
let order_id = "f47ac10b-58cc-4372-a567-0e02b2c3d479";
let expanded_uri = format!("crank://orders/{order_id}");
let mut successful_reads = upstream_calls.load(Ordering::SeqCst);
let mut text_cache_filled = false;
for revision in supported_revisions() {
let response = read_resource(&endpoint, &revision, &expanded_uri, None).await;
let status = response.status();
let body = json_body(response).await;
assert_eq!(
status,
reqwest::StatusCode::OK,
"dynamic template read failed on {revision}: {body}"
);
let contents = body["result"]["contents"][0]["text"]
.as_str()
.expect("JSON result must be returned as text content");
let output: Value =
serde_json::from_str(contents).expect("the upstream JSON must remain JSON content");
assert_eq!(output["id"], order_id);
assert_eq!(body["result"]["contents"][0]["uri"], expanded_uri);
if !text_cache_filled {
successful_reads += 1;
text_cache_filled = true;
}
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
successful_reads,
"the second protocol revision must return the populated cache entry without another REST call"
);
let expanded_head_uri = format!("crank://orders-metadata/{order_id}");
let response = read_resource(&endpoint, &revision, &expanded_head_uri, None).await;
let status = response.status();
let body = json_body(response).await;
assert_eq!(
status,
reqwest::StatusCode::OK,
"HEAD metadata mapping failed on {revision}: {body}"
);
let contents = body["result"]["contents"][0]["text"]
.as_str()
.unwrap_or_else(|| {
panic!("explicit HEAD metadata response must contain JSON text: {body}")
});
let metadata: Value =
serde_json::from_str(contents).expect("the explicit metadata mapping remains JSON");
assert_eq!(metadata["id"], 200);
successful_reads += 1;
assert_eq!(upstream_calls.load(Ordering::SeqCst), successful_reads);
let traversal = "crank://orders/%2e%2e";
let body = json_body(read_resource(&endpoint, &revision, traversal, None).await).await;
assert!(
body.get("result").is_none(),
"traversal-shaped template URI must not be served on {revision}: {body}"
);
let host_injection = format!("crank://127.0.0.1/orders/{order_id}");
let body =
json_body(read_resource(&endpoint, &revision, &host_injection, None).await).await;
assert!(
body.get("result").is_none(),
"URI authority must remain fixed on {revision}: {body}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
successful_reads,
"host injection must be rejected before REST dispatch"
);
let invalid_uuid = "crank://orders/not-a-uuid";
let body = json_body(read_resource(&endpoint, &revision, invalid_uuid, None).await).await;
assert!(
body.get("result").is_none(),
"URI parameters must satisfy the exact published input schema on {revision}: {body}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
successful_reads,
"invalid URI values must be rejected before REST dispatch"
);
}
let timeout_uuid = "00000000-0000-4000-8000-000000000001";
let timeout_uri = format!("crank://orders/{timeout_uuid}");
let response = read_resource(&endpoint, MODERN_REVISION, &timeout_uri, None).await;
let status = response.status();
let body = json_body(response).await;
assert_eq!(
status,
reqwest::StatusCode::OK,
"runtime failures must use an MCP error response: {body}"
);
assert!(body.get("result").is_none());
assert!(
body["error"]["data"]["request_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
assert!(
body["error"]["data"]["trace_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
for field in ["error_code", "stage", "retryability", "outcome_certainty"] {
assert!(
body["error"]["data"][field]
.as_str()
.is_some_and(|value| !value.is_empty()),
"structured runtime error must include {field}: {body}"
);
}
assert_eq!(upstream_calls.load(Ordering::SeqCst), successful_reads + 1);
assert!(!body.to_string().contains(timeout_uuid));
assert!(!body.to_string().contains("127.0.0.1"));
let calls_before_operation_cache_confirmation = upstream_calls.load(Ordering::SeqCst);
for revision in supported_revisions() {
let cached =
json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
assert!(
cached.get("result").is_some(),
"the exact Operation response must be available from cache before archive on {revision}: {cached}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_operation_cache_confirmation,
"the pre-archive control must hit the existing cache on {revision}"
);
}
let calls_before_operation_archive = upstream_calls.load(Ordering::SeqCst);
registry
.archive_operation(
&test_workspace_id(),
&operation.id,
&OffsetDateTime::now_utc(),
)
.await
.expect("the exact pinned Operation must be archivable for the stale-snapshot regression");
for revision in supported_revisions() {
let body = json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
assert!(
body.get("result").is_none(),
"an archived source Operation must fail closed on {revision}: {body}"
);
assert!(
body["error"]["data"]["request_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
assert!(
body["error"]["data"]["trace_id"]
.as_str()
.is_some_and(|id| !id.is_empty())
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_operation_archive,
"an archived Operation must not return its live Valkey cache entry or dispatch"
);
}
// Keep an independent published HEAD Operation eligible to verify real Valkey-loss fallback.
let calls_before_valkey_loss = upstream_calls.load(Ordering::SeqCst);
valkey.stop();
let fallback_uri = format!("crank://orders-metadata/{order_id}");
let fallback =
json_body(read_resource(&endpoint, MODERN_REVISION, &fallback_uri, None).await).await;
let fallback_text = fallback["result"]["contents"][0]["text"]
.as_str()
.expect("cache-loss fallback must preserve the declared HEAD metadata representation");
let fallback_output: Value = serde_json::from_str(fallback_text).unwrap();
assert_eq!(fallback_output["id"], 200);
assert_eq!(fallback["result"]["contents"][0]["uri"], fallback_uri);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_before_valkey_loss + 1,
"Valkey loss must use the eligible HEAD Operation's uncached REST path"
);
checks.finish();
// A live revoke must remove the exact template binding from future discovery.
sqlx::query("insert into resource_security_revocations (workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id) values ('ws_default', $1, now(), 'user_default_owner', 'story311-list', 'story311-list')")
.bind(resource_id.as_str()).execute(registry.pool()).await
.expect("the fixture revoke must be persisted");
sqlx::query("insert into resource_security_revocations (workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id) values ('ws_default', $1, now(), 'user_default_owner', 'story311-head-list', 'story311-head-list')")
.bind(head_resource_id.as_str()).execute(registry.pool()).await
.expect("the HEAD template revoke must be persisted");
let calls_after_revoke = upstream_calls.load(Ordering::SeqCst);
for revision in supported_revisions() {
let body = json_body(list_resource_templates(&endpoint, &revision).await).await;
assert!(
body["result"]["resourceTemplates"]
.as_array()
.is_some_and(|items| {
items.len() == 1 && items[0]["uriTemplate"] == binary_template
}),
"revoked text templates must disappear while the independent binary template remains on {revision}: {body}"
);
let body = json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
assert!(
body.get("result").is_none(),
"a revoked template must not be read on {revision}: {body}"
);
let revoked_head_uri = format!("crank://orders-metadata/{order_id}");
let body =
json_body(read_resource(&endpoint, &revision, &revoked_head_uri, None).await).await;
assert!(
body.get("result").is_none(),
"revoked HEAD metadata must not be read on {revision}: {body}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
calls_after_revoke,
"revoked template read must not dispatch"
);
}
}
@@ -0,0 +1,308 @@
use super::*;
use std::process::Command;
pub(super) struct TestValkey(String);
impl TestValkey {
pub(super) fn start() -> (Self, u16) {
let output = Command::new("docker")
.args([
"run",
"--detach",
"--publish",
"127.0.0.1::6379",
"valkey/valkey:8-alpine",
])
.output()
.expect("Docker CLI must start the test-owned Valkey container");
assert!(
output.status.success(),
"test-owned Valkey must start: {}",
String::from_utf8_lossy(&output.stderr)
);
let id = String::from_utf8(output.stdout)
.expect("Docker container id must be UTF-8")
.trim()
.to_owned();
let valkey = Self(id);
let port_output = Command::new("docker")
.args(["port", &valkey.0, "6379/tcp"])
.output()
.expect("Docker CLI must report the test-owned port");
assert!(
port_output.status.success(),
"test-owned Valkey port must be available"
);
let address = String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
let port = address
.trim()
.rsplit(':')
.next()
.unwrap()
.parse()
.expect("Docker mapped port must be numeric");
(valkey, port)
}
pub(super) fn stop(&self) {
let output = Command::new("docker")
.args(["stop", &self.0])
.output()
.expect("Docker CLI must stop the test-owned Valkey");
assert!(output.status.success(), "test-owned Valkey must stop");
}
}
impl Drop for TestValkey {
fn drop(&mut self) {
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
}
}
pub(super) async fn publish_binary_template(
registry: &PostgresRegistry,
agent_id: &crank_core::AgentId,
base_url: &str,
) -> (String, crank_core::AuthProfileId) {
let now = OffsetDateTime::now_utc();
let secret_id = crank_core::SecretId::new("secret_story311_binary_test");
let secret = crank_core::Secret {
id: secret_id.clone(),
workspace_id: test_workspace_id(),
name: "story311 binary test credential".to_owned(),
kind: crank_core::SecretKind::Token,
status: crank_core::SecretStatus::Active,
current_version: 1,
created_at: now,
updated_at: now,
last_used_at: None,
};
let crypto =
crank_runtime::SecretCrypto::new("test-master-key-00000000000000000000000000000000")
.unwrap();
registry
.verify_or_register_master_key_identity(crank_registry::MasterKeyIdentityCandidate {
epoch: crypto.master_key_epoch(),
fingerprint: crypto.master_key_fingerprint(),
cipher_contract: crank_registry::MASTER_KEY_CIPHER_CONTRACT,
observed_at: &now,
})
.await
.expect("the test runtime master-key identity must be registered");
let ciphertext = crypto
.encrypt(&json!({"token":"story311-test-token"}))
.unwrap();
registry
.create_secret(crank_registry::CreateSecretRequest {
secret: &secret,
ciphertext: &ciphertext,
key_version: crypto.key_version(),
master_key_epoch: crypto.master_key_epoch(),
created_by: None,
})
.await
.expect("test-owned binary auth secret must be persisted encrypted");
let auth_profile_id = crank_core::AuthProfileId::new("auth_story311_binary_test");
let auth_profile = crank_core::AuthProfile {
id: auth_profile_id.clone(),
workspace_id: test_workspace_id(),
name: "story311 binary test auth".to_owned(),
kind: crank_core::AuthKind::Bearer,
config: crank_core::AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id,
}),
created_at: now,
updated_at: now,
};
registry
.save_auth_profile(crank_registry::SaveAuthProfileRequest {
workspace_id: &test_workspace_id(),
profile: &auth_profile,
})
.await
.expect("test auth profile must be saved in its workspace");
let mut operation = test_operation(base_url, "bound_order_binary");
operation.id = OperationId::new("op_bound_order_binary");
operation.target = Target::Rest(RestTarget {
base_url: base_url.to_owned(),
method: HttpMethod::Get,
path_template: "/orders-binary/{order_id}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: vec![RestResponseDescriptor {
status_code: 200,
media_type: Some("application/json".to_owned()),
schema_variant: 0,
}],
multipart_field_mime_types: Default::default(),
});
operation.input_schema = object_schema("order_id");
operation
.input_schema
.fields
.get_mut("order_id")
.unwrap()
.format = Some("uuid".to_owned());
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,
}],
};
let mut output_schema = object_schema("data_base64");
output_schema.fields.insert(
"extra".to_owned(),
output_schema.fields["data_base64"].clone(),
);
output_schema.fields.get_mut("extra").unwrap().required = false;
operation.output_schema = output_schema;
operation.output_mapping = MappingSet {
rules: vec![
MappingRule {
source: "$.response.body.data_base64".to_owned(),
target: "$.output.data_base64".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
},
MappingRule {
source: "$.response.body.extra".to_owned(),
target: "$.output.extra".to_owned(),
required: false,
default_value: None,
transform: None,
condition: None,
notes: None,
},
],
};
operation.execution_config.timeout_ms = 1_000;
operation.execution_config.auth_profile_ref = Some(auth_profile_id.clone());
operation.execution_config.safety = Some(OperationSafetyPolicy {
class: OperationSafetyClass::Read,
confirmation: None,
});
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.expect("binary GET Read operation must be created");
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("binary operation must publish");
let uri_template = "crank://orders-binary/{order_id}";
let definition_value = json!({
"operation_id": operation.id.as_str(),
"operation_version": 1,
"uri_template": uri_template,
"parameters": [{"name":"order_id","input_path":"input.order_id","schema":{"type":"string","required":true,"format":"uuid"}}],
"cache": {"ttl_ms":60000,"vary":["order_id"],"max_bytes":65536},
"failure": {"outcome":"error"}
});
let source = TemplateSource::parse(&definition_value).expect("binary template source is valid");
let definition = serde_json::to_string(&source).unwrap();
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
let resource_id = ResourceId::new("res_bound_template_binary");
let draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
uri: "crank://templates/order-binary".to_owned(),
name: "order_binary".to_owned(),
description: "Published binary order representation".to_owned(),
kind: "binary".to_owned(),
mime_type: "application/pdf".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition,
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("binary template Draft must be created");
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("binary template must publish");
let published = registry
.get_agent_version(&test_workspace_id(), agent_id, 2)
.await
.expect("version two agent must remain readable")
.expect("version two agent must be published");
let now = OffsetDateTime::now_utc();
let mut agent_draft = published.snapshot.clone();
agent_draft.version = 3;
agent_draft.status = AgentStatus::Draft;
agent_draft.created_at = now;
registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id: &test_workspace_id(),
agent_id,
version: &agent_draft,
bindings: &published.bindings,
updated_at: &now,
})
.await
.expect("binary binding draft version must create");
let existing_publications: Vec<(String, i32)> = sqlx::query_as(
"select resource_id, version from resource_publications where workspace_id = $1 and resource_id in ('res_bound_template_discovery', 'res_bound_template_head', 'res_bound_template_binary')",
)
.bind(test_workspace_id().as_str())
.fetch_all(registry.pool())
.await
.expect("published Resource versions must be discoverable for the Agent fixture");
let resource_bindings: Vec<AgentResourceBinding> = existing_publications
.into_iter()
.map(|(resource_id, resource_version)| AgentResourceBinding {
resource_id: ResourceId::new(resource_id),
resource_version: resource_version as u32,
})
.collect();
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id,
agent_version: 3,
bindings: &published.bindings,
tool_selection_policy: &published.snapshot.tool_selection_policy,
resource_bindings: &resource_bindings,
expected_state: None,
})
.await
.expect("exact binary template version must bind to the Agent draft");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id,
version: 3,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("Agent snapshot with binary binding must publish");
(uri_template.to_owned(), auth_profile_id)
}
@@ -0,0 +1,150 @@
use super::*;
/// A live cache hit must fall back to the exact REST read when the test-owned Valkey is lost.
#[tokio::test]
async fn eligible_get_resource_reads_uncached_after_valkey_loss() {
let (valkey, port) = TestValkey::start();
let cache = Arc::new(
crank_runtime::RedisCacheStore::connect(
crank_core::CacheBackend::Valkey,
&format!("redis://127.0.0.1:{port}/0"),
)
.await
.expect("runtime must connect to test-owned Valkey"),
);
let endpoint = standard_endpoint_with_cache("uncached_after_valkey_loss", Some(cache)).await;
let registry = &endpoint.registry;
let published = registry
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
.await
.expect("published Agent snapshot must be readable")
.expect("published Agent version 1 must exist");
let now = OffsetDateTime::now_utc();
let mut agent_draft = published.snapshot.clone();
agent_draft.version = 2;
agent_draft.status = AgentStatus::Draft;
agent_draft.created_at = now;
registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: &agent_draft,
bindings: &published.bindings,
updated_at: &now,
})
.await
.expect("Agent version two Draft must be created for the template fixture");
registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
agent_version: 2,
bindings: &published.bindings,
tool_selection_policy: &published.snapshot.tool_selection_policy,
resource_bindings: &[],
expected_state: None,
})
.await
.expect("Agent version two catalog must be saved");
registry
.publish_agent(PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id: &endpoint.agent_id,
version: 2,
published_at: &now,
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("Agent version two must be published for the template fixture");
let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("test upstream must bind a loopback port");
let upstream_address = upstream_listener.local_addr().unwrap();
let upstream_calls = Arc::new(AtomicUsize::new(0));
let upstream = axum::Router::new()
.route("/orders-binary/{order_id}", get(template_binary_lookup))
.with_state(Arc::clone(&upstream_calls));
tokio::spawn(async move {
axum::serve(upstream_listener, upstream)
.await
.expect("test upstream must serve");
});
let (template, _auth_profile_id) = publish_binary_template(
&endpoint.registry,
&endpoint.agent_id,
&format!("http://{upstream_address}"),
)
.await;
assert_eq!(template, "crank://orders-binary/{order_id}");
let expected_bytes = [0_u8, 255, 1, 253, 254, 255];
let revision_uris = [
(
MODERN_REVISION,
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480",
),
(
LEGACY_REVISION,
"crank://orders-binary/f47ac10b-58cc-4373-a567-0e02b2c3d480",
),
];
for (revision, uri) in revision_uris {
let before_first_read = upstream_calls.load(Ordering::SeqCst);
for expected_calls in [before_first_read + 1, before_first_read + 1] {
let body = json_body(read_resource(&endpoint, revision, uri, None).await).await;
assert!(
body.get("error").is_none(),
"eligible GET failed on {revision}: {body}"
);
let content = &body["result"]["contents"][0];
assert_eq!(content["uri"], uri);
assert_eq!(content["mimeType"], "application/pdf");
assert_eq!(
base64::engine::general_purpose::STANDARD
.decode(
content["blob"]
.as_str()
.expect("binary response must carry a blob")
)
.expect("binary response must be valid base64"),
expected_bytes,
"REST bytes must remain exact on {revision}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
expected_calls,
"the initial REST read increments once and its live-Valkey repeat is a hit on {revision}"
);
}
}
valkey.stop();
for (revision, uri) in revision_uris {
let before_read = upstream_calls.load(Ordering::SeqCst);
let body = json_body(read_resource(&endpoint, revision, uri, None).await).await;
assert!(
body.get("error").is_none(),
"eligible uncached GET failed on {revision}: {body}"
);
let content = &body["result"]["contents"][0];
assert_eq!(content["uri"], uri);
assert_eq!(content["mimeType"], "application/pdf");
assert_eq!(
base64::engine::general_purpose::STANDARD
.decode(
content["blob"]
.as_str()
.expect("binary response must carry a blob")
)
.expect("binary response must be valid base64"),
expected_bytes,
"REST bytes must remain exact after Valkey loss on {revision}"
);
assert_eq!(
upstream_calls.load(Ordering::SeqCst),
before_read + 1,
"the exact eligible URI must use REST when Valkey is unavailable on {revision}"
);
}
}