Files
crank/crates/crank-registry/tests/integration/common.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

332 lines
12 KiB
Rust

#![allow(dead_code, unused_imports)]
use std::collections::BTreeMap;
use std::str::FromStr;
use crank_core::{
AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApiKeyHeaderAuthConfig, AuthConfig,
AuthKind, AuthProfile, ConfigExport, ExecutionConfig, ExportMode, GeneratedDraft,
GeneratedDraftStatus, HttpMethod, InvocationLog, MembershipRole, OperationId,
OperationSecurityLevel, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, RetryPolicy, Samples, SecretId, Target,
ToolDescription, ToolExample, User, UserId, UserSessionId, WizardState, Workspace, WorkspaceId,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_schema::{Schema, SchemaKind};
use serde_json::json;
use sqlx::{Executor, PgPool, postgres::PgPoolOptions};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use crank_registry::{
CreateAgentRequest, CreateInvocationLogRequest, CreatePlatformApiKeyRequest,
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest, DescriptorKind,
DescriptorMetadata, OperationSampleMetadata, PlatformApiKeyRecord, PostgresRegistry,
PublishAgentRequest, PublishRequest, RegistryError, RegistryOperation, SampleKind,
SaveAgentCatalogConfigRequest, SaveAuthProfileRequest, SaveDescriptorMetadataRequest,
SaveSampleMetadataRequest, WorkspaceRecord, YamlImportJobCompletion, YamlImportJobId,
YamlImportJobStatus,
};
pub(super) fn test_workspace_id() -> WorkspaceId {
WorkspaceId::new("ws_default")
}
fn timestamp(value: &str) -> OffsetDateTime {
OffsetDateTime::parse(value, &Rfc3339).unwrap()
}
pub(super) fn test_operation(id: &str, version: u32, status: OperationStatus) -> RegistryOperation {
RegistryOperation {
id: OperationId::new(id),
name: format!("{id}_tool"),
display_name: format!("Display {id}"),
category: "general".to_owned(),
protocol: Protocol::Rest,
security_level: OperationSecurityLevel::Standard,
status,
version,
target: Target::Rest(RestTarget {
base_url: "https://api.example.com".to_owned(),
method: HttpMethod::Post,
path_template: "/v1/leads".to_owned(),
static_headers: BTreeMap::from([("X-Static".to_owned(), "true".to_owned())]),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: Schema {
kind: SchemaKind::Object,
format: None,
description: Some("input".to_owned()),
required: true,
nullable: false,
default_value: None,
fields: BTreeMap::from([(
"email".to_owned(),
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
)]),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
output_schema: Schema {
kind: SchemaKind::Object,
format: None,
description: Some("output".to_owned()),
required: true,
nullable: false,
default_value: None,
fields: BTreeMap::from([(
"id".to_owned(),
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
)]),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
input_mapping: MappingSet {
rules: vec![MappingRule {
source: "$.mcp.email".to_owned(),
target: "$.request.body.email".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
},
output_mapping: MappingSet {
rules: vec![MappingRule {
source: "$.response.body.id".to_owned(),
target: "$.output.id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
},
execution_config: ExecutionConfig {
timeout_ms: 10_000,
retry_policy: Some(RetryPolicy { max_attempts: 3 }),
auth_profile_ref: Some("auth_crank".into()),
headers: BTreeMap::from([("X-Request-Id".to_owned(), "static".to_owned())]),
..ExecutionConfig::default()
},
tool_description: ToolDescription {
title: "Create lead".to_owned(),
description: "Creates CRM lead".to_owned(),
tags: vec!["crm".to_owned()],
examples: vec![ToolExample {
input: json!({ "email": "a@example.com" }),
}],
},
samples: Some(Samples {
input_json_sample_ref: Some("sample_input".into()),
output_json_sample_ref: Some("sample_output".into()),
}),
generated_draft: Some(GeneratedDraft {
status: GeneratedDraftStatus::Available,
source_types: vec!["input_json".to_owned(), "output_json".to_owned()],
generated_at: Some("2026-03-25T11:59:00Z".to_owned()),
input_schema_generated: true,
output_schema_generated: true,
input_mapping_generated: true,
output_mapping_generated: true,
warnings: Vec::new(),
}),
config_export: Some(ConfigExport {
format_version: "v1".to_owned(),
export_mode: ExportMode::Portable,
}),
wizard_state: Some(WizardState {
input_sample: Some(json!({ "email": format!("lead-{version}@example.com") })),
output_sample: Some(json!({ "id": format!("lead_{version}") })),
test_input: Some(json!({ "email": format!("test-v{version}@example.com") })),
import_findings: Vec::new(),
}),
created_at: timestamp("2026-03-25T11:58:00Z"),
updated_at: timestamp(&format!("2026-03-25T12:{version:02}:00Z")),
published_at: None,
}
}
pub(super) fn test_agent(id: &str, status: AgentStatus) -> crank_core::Agent {
crank_core::Agent {
id: AgentId::new(id),
workspace_id: test_workspace_id(),
slug: format!("{id}_slug"),
display_name: format!("Display {id}"),
description: format!("Description {id}"),
status,
current_draft_version: 1,
latest_published_version: None,
created_at: timestamp("2026-03-25T11:58:00Z"),
updated_at: timestamp("2026-03-25T12:00:00Z"),
published_at: None,
}
}
pub(super) fn test_agent_version(
agent_id: &AgentId,
version: u32,
status: AgentStatus,
) -> AgentVersion {
AgentVersion {
agent_id: agent_id.clone(),
version,
status,
instructions: json!({
"system": "triage tickets",
"guardrails": ["don't mutate state"]
}),
tool_selection_policy: Default::default(),
created_at: timestamp("2026-03-25T12:00:00Z"),
}
}
pub(super) fn test_invocation_log(
id: &str,
operation_id: &OperationId,
agent_id: Option<AgentId>,
status: crank_core::InvocationStatus,
duration_ms: u64,
created_at: &str,
) -> InvocationLog {
InvocationLog {
id: crank_core::InvocationLogId::new(id),
workspace_id: test_workspace_id(),
agent_id,
platform_api_key_id: None,
operation_id: operation_id.clone(),
operation_version: Some(1),
source: crank_core::InvocationSource::AgentToolCall,
level: crank_core::InvocationLevel::Info,
status,
tool_name: "create_lead".to_owned(),
message: "invocation".to_owned(),
request_id: Some(format!("req_{id}")),
trace_id: Some("0af7651916cd43dd8448eb211c80319c".to_owned()),
status_code: Some(200),
duration_ms,
error_kind: None,
execution_stage: Some(crank_core::ExecutionStage::Runtime),
execution_error_code: (status == crank_core::InvocationStatus::Error)
.then_some(crank_core::ExecutionErrorCode::RuntimeInternal),
retryability: Some(crank_core::Retryability::Never),
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
request_preview: json!({"input":"value"}),
response_preview: json!({"ok":true}),
created_at: timestamp(created_at),
}
}
pub(super) struct TestDatabase {
admin_pool: PgPool,
database_url: String,
schema: String,
}
impl TestDatabase {
pub(super) async fn new() -> Self {
let database_url = crank_test_support::postgres_database_url().await.to_owned();
let admin_pool = PgPoolOptions::new()
.max_connections(1)
.connect(&database_url)
.await
.unwrap();
let schema = crank_test_support::unique_schema_name("test_registry");
admin_pool
.execute(sqlx::query(sqlx::AssertSqlSafe(format!(
"create schema {schema}"
))))
.await
.unwrap();
Self {
admin_pool,
database_url,
schema,
}
}
pub(super) async fn registry(&self) -> PostgresRegistry {
let database_url = format!(
"{}?options=-csearch_path%3D{}",
self.database_url, self.schema
);
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
crank_registry::MigrationAuthority::apply(&pool)
.await
.unwrap();
PostgresRegistry::connect(&database_url).await.unwrap()
}
pub(super) async fn raw_pool(&self) -> PgPool {
let database_url = format!(
"{}?options=-csearch_path%3D{}",
self.database_url, self.schema
);
PgPoolOptions::new()
.max_connections(1)
.connect(&database_url)
.await
.unwrap()
}
/// Registry over a multi-connection pool in this test schema: concurrency regressions need
/// sessions that can genuinely block on each other's row locks.
pub(super) async fn concurrent_registry(&self, max_connections: u32) -> PostgresRegistry {
let database_url = format!(
"{}?options=-csearch_path%3D{}",
self.database_url, self.schema
);
let options = sqlx::postgres::PgConnectOptions::from_str(&database_url)
.expect("the test database url must parse into connect options");
PostgresRegistry::connect_with_options_and_pool_config(
options,
crank_registry::PostgresPoolConfig {
max_connections,
min_connections: 0,
acquire_timeout_ms: 10_000,
idle_timeout_ms: 600_000,
max_lifetime_ms: 1_800_000,
},
)
.await
.expect("the concurrent test registry must connect")
}
pub(super) async fn cleanup(&self) {
self.admin_pool
.execute(sqlx::query(sqlx::AssertSqlSafe(format!(
"drop schema if exists {} cascade",
self.schema
))))
.await
.unwrap();
}
}