Files
crank/crates/crank-registry/tests/integration/prompt_composition.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

485 lines
16 KiB
Rust

//! Story 3.16 / FR-18 на уровне реестра: version-keyed пины зависимостей Prompt.
//!
//! Проверяется на реальном PostgreSQL и реальном artifact store, что контракт держится схемой и
//! транзакциями, а не только JSON-ответом admin-api:
//! - публикация Prompt сохраняет точную опубликованную версию Resource (resource_id, version,
//! digest, kind, source_class, sensitivity) и объявленные точки вставки;
//! - новая версия Resource не переписывает пины уже опубликованного Prompt;
//! - guard-триггер запрещает менять строки пинов опубликованной версии напрямую через SQL;
//! - dependency другого workspace неотличима от отсутствующей (`prompt_dependency_unresolved`);
//! - dependency, на которую не ссылается ни одно сообщение, отклоняется до любого чтения
//! (`prompt_dependency_unused`);
//! - публикация хранит строгую (effective) sensitivity.
use std::{
fs,
os::unix::fs::PermissionsExt,
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
};
use crank_artifacts::{ArtifactStore, RegisteredArtifact};
use crank_core::{
Workspace, WorkspaceId, WorkspaceStatus,
ids::{PromptId, ResourceId},
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
};
use crank_registry::{
CreateWorkspaceRequest, MigrationAuthority, PostgresRegistry, RegistryError,
model::{
CreatePromptDraftRequest, PublishPromptRequest,
resource::{CreateResourceDraftRequest, PublishResourceVersionRequest},
},
};
use serde_json::json;
use time::OffsetDateTime;
const WORKSPACE_ID: &str = "ws_default";
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
struct TestRoot(PathBuf);
impl TestRoot {
fn new(name: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"crank-registry-prompt-composition-{name}-{}-{}",
std::process::id(),
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&path).expect("private artifact root must be creatable");
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
.expect("private artifact root must be 0700");
Self(path)
}
}
impl Drop for TestRoot {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
struct Sandbox {
registry: PostgresRegistry,
store: ArtifactStore,
_root: TestRoot,
}
async fn sandbox(name: &str) -> Sandbox {
let database_url = crank_test_support::postgres_schema_url(&format!("story316_{name}")).await;
let pool = sqlx::PgPool::connect(&database_url)
.await
.expect("test schema must accept connections");
MigrationAuthority::apply(&pool)
.await
.expect("migration sequence applies");
let registry = PostgresRegistry::connect(&database_url)
.await
.expect("registry must connect");
let root = TestRoot::new(name);
let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open");
Sandbox {
registry,
store,
_root: root,
}
}
/// Второй workspace того же реестра: dependency из него не адресуема.
async fn create_foreign_workspace(registry: &PostgresRegistry) -> WorkspaceId {
let workspace_id = WorkspaceId::new("ws_story316_foreign");
let now = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: "story316-foreign".to_owned(),
display_name: "Story 3.16 foreign".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("foreign workspace must be created");
workspace_id
}
fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact {
sandbox
.store
.put_registered(bytes)
.expect("fixture bytes must be registered durably")
}
/// Публикует static Resource в заданном workspace и возвращает точную опубликованную версию.
async fn published_resource(
sandbox: &Sandbox,
workspace: &WorkspaceId,
resource_id: &str,
sensitivity: &str,
bytes: &[u8],
) -> (ResourceId, u32, String) {
let id = ResourceId::new(resource_id);
let registry = &sandbox.registry;
if registry
.get_resource_draft(workspace.as_str(), &id)
.await
.is_ok()
{
// Новая опубликованная версия существующего Resource (Story 3.7 path).
let current = registry
.get_resource_draft(workspace.as_str(), &id)
.await
.expect("current draft readable");
registry
.update_resource_draft(
crank_registry::model::resource::UpdateResourceDraftRequest {
workspace_id: workspace.clone(),
resource_id: id.clone(),
description: "second version".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: sensitivity.to_owned(),
expected_updated_at: current.resource.updated_at,
artifact: registered(sandbox, bytes),
},
)
.await
.expect("second draft version must be creatable");
} else {
registry
.create_resource_draft(CreateResourceDraftRequest {
workspace_id: workspace.clone(),
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: sensitivity.to_owned(),
artifact: registered(sandbox, bytes),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("resource draft must be created");
}
let current = registry
.get_resource_draft(workspace.as_str(), &id)
.await
.expect("draft must be readable");
let publication = registry
.publish_resource_version(PublishResourceVersionRequest {
workspace_id: workspace.clone(),
resource_id: id.clone(),
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: registered(sandbox, bytes),
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("published Resource version");
(id, publication.version, publication.digest)
}
fn composed_definition(
dependencies: serde_json::Value,
refs: serde_json::Value,
) -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "release-notes",
"description": "Composed prompt",
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
"messages": [
{"role": "system", "content": "Summarise only the attached document."},
{"role": "user", "content": "Channel: {{channel}}", "resource_refs": refs}
],
"dependencies": dependencies
}))
.expect("composed definition parses")
}
async fn create_draft(
sandbox: &Sandbox,
workspace: &WorkspaceId,
prompt_id: &str,
sensitivity: PromptSensitivity,
definition: PromptDefinition,
) -> crank_registry::model::PromptDraftRecord {
sandbox
.registry
.create_prompt_draft(CreatePromptDraftRequest {
workspace_id: workspace.clone(),
prompt_id: PromptId::new(prompt_id),
sensitivity,
definition,
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("composed prompt draft creates")
}
async fn publish_draft(
sandbox: &Sandbox,
workspace: &WorkspaceId,
prompt_id: &str,
expected_updated_at: time::OffsetDateTime,
) -> crank_registry::model::PromptDraftRecord {
sandbox
.registry
.publish_prompt_draft(PublishPromptRequest {
workspace_id: workspace.clone(),
prompt_id: PromptId::new(prompt_id),
expected_updated_at,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("composed prompt publishes")
}
#[tokio::test]
async fn story316_registry_stores_version_keyed_pins_and_insertion_points() {
let sandbox = sandbox("pins").await;
let workspace = WorkspaceId::new(WORKSPACE_ID);
let (resource, version, digest) = published_resource(
&sandbox,
&workspace,
"res_story316_pins",
"internal",
b"pinned body",
)
.await;
let definition = composed_definition(
json!([{"resource_id": resource.as_str(), "version": version}]),
json!([0]),
);
let created = create_draft(
&sandbox,
&workspace,
"prm_story316_pins",
PromptSensitivity::Public,
definition,
)
.await;
assert_eq!(created.dependencies.len(), 1);
assert_eq!(created.dependencies[0].resource_id, resource.as_str());
assert_eq!(created.dependencies[0].version, version);
assert_eq!(created.dependencies[0].digest, digest);
assert_eq!(created.dependencies[0].kind.as_str(), "text");
assert_eq!(created.dependencies[0].source_class.as_str(), "static");
assert_eq!(
created.dependencies[0].sensitivity,
PromptSensitivity::Internal
);
let stored_version: i32 =
sqlx::query_scalar("select resource_version from prompt_dependencies where prompt_id = $1")
.bind("prm_story316_pins")
.fetch_one(sandbox.registry.pool())
.await
.expect("pins are queryable");
assert_eq!(stored_version, i32::try_from(version).unwrap());
let refs: i32 = sqlx::query_scalar(
"select dependency_position from prompt_message_resource_refs where prompt_id = $1",
)
.bind("prm_story316_pins")
.fetch_one(sandbox.registry.pool())
.await
.expect("insertion points are queryable");
assert_eq!(refs, 0);
// AC3: публикация хранит строгую политику, локальное значение остаётся в prompts.
let published = publish_draft(
&sandbox,
&workspace,
"prm_story316_pins",
created.updated_at,
)
.await;
assert_eq!(published.prompt.status(), PromptStatus::Published);
let publication_sensitivity: String = sqlx::query_scalar(
"select sensitivity from prompt_publications where prompt_id = $1 and version = 1",
)
.bind("prm_story316_pins")
.fetch_one(sandbox.registry.pool())
.await
.expect("publication is queryable");
assert_eq!(publication_sensitivity, "internal");
let local_sensitivity: String =
sqlx::query_scalar("select sensitivity from prompts where prompt_id = $1")
.bind("prm_story316_pins")
.fetch_one(sandbox.registry.pool())
.await
.expect("local value is queryable");
assert_eq!(
local_sensitivity, "public",
"the local value is not rewritten"
);
}
#[tokio::test]
async fn story316_registry_pins_stay_immutable_after_a_new_resource_version() {
let sandbox = sandbox("immutable").await;
let workspace = WorkspaceId::new(WORKSPACE_ID);
let (resource, version, digest) = published_resource(
&sandbox,
&workspace,
"res_story316_immutable",
"internal",
b"CHANGELOG v1",
)
.await;
let definition = composed_definition(
json!([{"resource_id": resource.as_str(), "version": version}]),
json!([0]),
);
let created = create_draft(
&sandbox,
&workspace,
"prm_story316_immutable",
PromptSensitivity::Internal,
definition,
)
.await;
publish_draft(
&sandbox,
&workspace,
"prm_story316_immutable",
created.updated_at,
)
.await;
// Новая опубликованная версия того же Resource.
let (_, second_version, second_digest) = published_resource(
&sandbox,
&workspace,
"res_story316_immutable",
"internal",
b"CHANGELOG v2",
)
.await;
assert_eq!(second_version, version + 1);
assert_ne!(second_digest, digest);
let publication = sandbox
.registry
.get_published_prompt_version(
&workspace,
&PromptId::new("prm_story316_immutable"),
version,
)
.await
.expect("published prompt version is readable");
assert_eq!(
publication.dependencies[0].version, version,
"the publication keeps the exact pinned version"
);
assert_eq!(publication.dependencies[0].digest, digest);
// Guard опубликованной версии: прямая правка пина через SQL отклоняется.
let update = sqlx::query(
"update prompt_dependencies set resource_version = resource_version + 1 where prompt_id = $1",
)
.bind("prm_story316_immutable")
.execute(sandbox.registry.pool())
.await;
assert!(
update.is_err(),
"a published pin must be immutable through SQL as well"
);
}
#[tokio::test]
async fn story316_registry_cross_workspace_dependency_is_unresolved() {
let sandbox = sandbox("foreign").await;
let workspace = WorkspaceId::new(WORKSPACE_ID);
let foreign = create_foreign_workspace(&sandbox.registry).await;
let (resource, version, _digest) = published_resource(
&sandbox,
&foreign,
"res_story316_foreign",
"internal",
b"foreign body",
)
.await;
let definition = composed_definition(
json!([{"resource_id": resource.as_str(), "version": version}]),
json!([0]),
);
let error = sandbox
.registry
.create_prompt_draft(CreatePromptDraftRequest {
workspace_id: workspace.clone(),
prompt_id: PromptId::new("prm_story316_foreign"),
sensitivity: PromptSensitivity::Internal,
definition,
created_at: OffsetDateTime::now_utc(),
})
.await
.expect_err("a foreign dependency is not addressable");
assert!(matches!(
error,
RegistryError::PromptDependencyUnresolved { position: 0, .. }
));
}
#[tokio::test]
async fn story316_registry_unused_dependency_is_refused() {
let sandbox = sandbox("unused").await;
let workspace = WorkspaceId::new(WORKSPACE_ID);
let (first, first_version, _) = published_resource(
&sandbox,
&workspace,
"res_story316_unused_a",
"internal",
b"first",
)
.await;
let (second, second_version, _) = published_resource(
&sandbox,
&workspace,
"res_story316_unused_b",
"internal",
b"second",
)
.await;
let definition = composed_definition(
json!([
{"resource_id": first.as_str(), "version": first_version},
{"resource_id": second.as_str(), "version": second_version}
]),
json!([0]),
);
let error = sandbox
.registry
.create_prompt_draft(CreatePromptDraftRequest {
workspace_id: workspace.clone(),
prompt_id: PromptId::new("prm_story316_unused"),
sensitivity: PromptSensitivity::Internal,
definition,
created_at: OffsetDateTime::now_utc(),
})
.await
.expect_err("a dependency that no message references is refused");
match error {
RegistryError::PromptDependencyUnused {
position,
resource_id,
version,
..
} => {
assert_eq!(position, 1);
assert_eq!(resource_id, second.as_str());
assert_eq!(version, second_version);
}
other => panic!("expected prompt_dependency_unused, got {other:?}"),
}
}