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
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.
757 lines
30 KiB
Rust
757 lines
30 KiB
Rust
//! Story 3.13 / FR-17: immutable Published Prompt Versions и exact typed Prompt
|
||
//! bindings Agent (V22).
|
||
//!
|
||
//! Проверяется на реальном PostgreSQL, что контракт держится схемой и
|
||
//! транзакциями, а не только JSON-ответом API:
|
||
//! - publish фиксирует точную версию, последующая правка открывает новый Draft,
|
||
//! exact v1 не меняется после edit/publish/archive;
|
||
//! - concurrent publish с одинаковым `expected_updated_at` даёт ровно одну
|
||
//! публикацию, проигравший получает stale;
|
||
//! - guard-триггеры запрещают менять definition опубликованной версии и строку
|
||
//! публикации напрямую через SQL;
|
||
//! - binding адресует exact published версию, archived/unpublished отклоняются,
|
||
//! published Agent bindings иммутабельны, повтор Agent publish не даёт двойной
|
||
//! bump, scope другого workspace не раскрывается.
|
||
|
||
use crank_core::{
|
||
Agent, AgentId, AgentStatus, AgentVersion, Workspace, WorkspaceId, WorkspaceStatus,
|
||
ids::PromptId,
|
||
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
|
||
};
|
||
use crank_registry::{
|
||
CreateAgentRequest, CreateWorkspaceRequest, MigrationAuthority, PostgresRegistry,
|
||
PublishAgentRequest, RegistryError,
|
||
model::{
|
||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||
},
|
||
};
|
||
use serde_json::json;
|
||
use time::OffsetDateTime;
|
||
|
||
const WS: &str = "ws_default";
|
||
|
||
fn prompt(content: &str) -> PromptDefinition {
|
||
PromptDefinition::parse(&json!({
|
||
"name":"welcome", "description":"Greeting",
|
||
"arguments":[{"name":"name","schema":{"type":"string"},"required":true}],
|
||
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
|
||
}))
|
||
.expect("valid typed definition")
|
||
}
|
||
|
||
async fn registry_pool(label: &str) -> (PostgresRegistry, sqlx::PgPool) {
|
||
let url = crank_test_support::postgres_schema_url(&format!("story313_{label}")).await;
|
||
let pool = sqlx::PgPool::connect(&url)
|
||
.await
|
||
.expect("test postgres schema connects");
|
||
MigrationAuthority::apply(&pool)
|
||
.await
|
||
.expect("migration sequence applies");
|
||
let registry = PostgresRegistry::connect(&url)
|
||
.await
|
||
.expect("registry connects");
|
||
(registry, pool)
|
||
}
|
||
|
||
async fn registry(label: &str) -> PostgresRegistry {
|
||
registry_pool(label).await.0
|
||
}
|
||
|
||
async fn create_prompt(
|
||
registry: &PostgresRegistry,
|
||
workspace_id: &WorkspaceId,
|
||
prompt_id: &PromptId,
|
||
) -> crank_registry::model::PromptDraftRecord {
|
||
registry
|
||
.create_prompt_draft(CreatePromptDraftRequest {
|
||
workspace_id: workspace_id.clone(),
|
||
prompt_id: prompt_id.clone(),
|
||
sensitivity: PromptSensitivity::Internal,
|
||
definition: prompt("Hello {{name}}"),
|
||
created_at: OffsetDateTime::now_utc(),
|
||
})
|
||
.await
|
||
.expect("draft creates")
|
||
}
|
||
|
||
async fn publish(
|
||
registry: &PostgresRegistry,
|
||
workspace_id: &WorkspaceId,
|
||
prompt_id: &PromptId,
|
||
expected_updated_at: OffsetDateTime,
|
||
) -> Result<crank_registry::model::PromptDraftRecord, RegistryError> {
|
||
registry
|
||
.publish_prompt_draft(PublishPromptRequest {
|
||
workspace_id: workspace_id.clone(),
|
||
prompt_id: prompt_id.clone(),
|
||
expected_updated_at,
|
||
published_at: OffsetDateTime::now_utc(),
|
||
})
|
||
.await
|
||
}
|
||
|
||
/// NEW-side проверки guard-триггеров обязаны падать именно на защите
|
||
/// опубликованной версии, а не на случайном ограничении схемы.
|
||
fn assert_immutable_guard_rejected(
|
||
result: Result<sqlx::postgres::PgQueryResult, sqlx::Error>,
|
||
expected_message: &str,
|
||
) {
|
||
let error = match result {
|
||
Ok(_) => panic!("raw SQL must be rejected by `{expected_message}`"),
|
||
Err(error) => error,
|
||
};
|
||
let message = match &error {
|
||
sqlx::Error::Database(database) => database.message().to_owned(),
|
||
other => panic!("expected the `{expected_message}` guard rejection, got: {other}"),
|
||
};
|
||
assert!(
|
||
message.contains(expected_message),
|
||
"the guard must reject the write with `{expected_message}`, got: {message}"
|
||
);
|
||
}
|
||
|
||
async fn create_draft_agent(
|
||
registry: &PostgresRegistry,
|
||
workspace_id: &WorkspaceId,
|
||
agent_id: &str,
|
||
slug: &str,
|
||
) -> AgentId {
|
||
let id = AgentId::new(agent_id);
|
||
let now = OffsetDateTime::now_utc();
|
||
registry
|
||
.create_agent(CreateAgentRequest {
|
||
agent: &Agent {
|
||
id: id.clone(),
|
||
workspace_id: workspace_id.clone(),
|
||
slug: slug.to_owned(),
|
||
display_name: slug.to_owned(),
|
||
description: "Story 3.13 prompt binding 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: id.clone(),
|
||
version: 1,
|
||
status: AgentStatus::Draft,
|
||
instructions: json!({}),
|
||
tool_selection_policy: Default::default(),
|
||
created_at: now,
|
||
},
|
||
bindings: &[],
|
||
})
|
||
.await
|
||
.expect("draft Agent is created");
|
||
id
|
||
}
|
||
|
||
async fn save_prompt_bindings(
|
||
registry: &PostgresRegistry,
|
||
workspace_id: &WorkspaceId,
|
||
agent_id: &AgentId,
|
||
agent_version: u32,
|
||
prompt_id: &PromptId,
|
||
prompt_version: u32,
|
||
) -> Result<u32, RegistryError> {
|
||
registry
|
||
.save_agent_catalog_config_editable_with_prompts(
|
||
SaveAgentCatalogConfigRequest {
|
||
workspace_id,
|
||
agent_id,
|
||
agent_version,
|
||
bindings: &[],
|
||
tool_selection_policy: &Default::default(),
|
||
resource_bindings: &[],
|
||
expected_state: None,
|
||
},
|
||
&[AgentPromptBinding {
|
||
prompt_id: prompt_id.clone(),
|
||
prompt_version,
|
||
}],
|
||
)
|
||
.await
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn story313_publish_pins_immutable_version_and_edit_opens_new_draft() {
|
||
let registry = registry("publish_lifecycle").await;
|
||
let workspace_id = WorkspaceId::new(WS);
|
||
let prompt_id = PromptId::new("prm_story313_lifecycle");
|
||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||
.await
|
||
.expect("valid Draft publishes");
|
||
assert_eq!(published.prompt.status(), PromptStatus::Published);
|
||
assert_eq!(published.prompt.version(), 1);
|
||
assert_eq!(published.latest_published_version, Some(1));
|
||
assert_eq!(published.prompt.definition(), created.prompt.definition());
|
||
|
||
let exact = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||
.await
|
||
.expect("exact published version reads");
|
||
assert_eq!(exact.name, "welcome");
|
||
assert_eq!(&exact.definition, created.prompt.definition());
|
||
|
||
let edited_definition = prompt("Edited {{name}}");
|
||
let edited = registry
|
||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||
workspace_id: workspace_id.clone(),
|
||
prompt_id: prompt_id.clone(),
|
||
sensitivity: PromptSensitivity::Internal,
|
||
definition: edited_definition.clone(),
|
||
expected_updated_at: published.updated_at,
|
||
updated_at: OffsetDateTime::now_utc(),
|
||
})
|
||
.await
|
||
.expect("editing a published Prompt opens a new Draft");
|
||
assert_eq!(edited.prompt.status(), PromptStatus::Draft);
|
||
assert_eq!(edited.prompt.version(), 2);
|
||
assert_eq!(edited.latest_published_version, Some(1));
|
||
assert_eq!(edited.prompt.definition(), &edited_definition);
|
||
|
||
let preserved = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||
.await
|
||
.expect("the pinned publication survives a Draft edit");
|
||
assert_eq!(&preserved.definition, created.prompt.definition());
|
||
assert_eq!(preserved.name, "welcome");
|
||
|
||
// Вторая публикация: publish v2 создаёт отдельный immutable snapshot, при этом
|
||
// exact v1 остаётся читаемой и latest_published_version поднимается до 2.
|
||
let published_v2 = publish(®istry, &workspace_id, &prompt_id, edited.updated_at)
|
||
.await
|
||
.expect("the edited Draft publishes as v2");
|
||
assert_eq!(published_v2.prompt.status(), PromptStatus::Published);
|
||
assert_eq!(published_v2.prompt.version(), 2);
|
||
assert_eq!(published_v2.latest_published_version, Some(2));
|
||
assert_eq!(published_v2.prompt.definition(), &edited_definition);
|
||
|
||
let exact_v1_after_v2 = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||
.await
|
||
.expect("exact v1 stays readable after publishing v2");
|
||
assert_eq!(&exact_v1_after_v2.definition, created.prompt.definition());
|
||
assert_eq!(exact_v1_after_v2.version, 1);
|
||
let exact_v2 = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 2)
|
||
.await
|
||
.expect("exact v2 is readable by its own number");
|
||
assert_eq!(exact_v2.version, 2);
|
||
assert_eq!(&exact_v2.definition, &edited_definition);
|
||
|
||
let archived = registry
|
||
.archive_prompt_draft(ArchivePromptRequest {
|
||
workspace_id: workspace_id.clone(),
|
||
prompt_id: prompt_id.clone(),
|
||
expected_updated_at: published_v2.updated_at,
|
||
archived_at: OffsetDateTime::now_utc(),
|
||
})
|
||
.await
|
||
.expect("archive is a lifecycle action");
|
||
assert_eq!(archived.prompt.status(), PromptStatus::Archived);
|
||
|
||
let refused = publish(®istry, &workspace_id, &prompt_id, archived.updated_at).await;
|
||
assert!(matches!(refused, Err(RegistryError::PromptNotDraft { .. })));
|
||
|
||
let after_archive = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||
.await
|
||
.expect("archive is not a security revoke");
|
||
assert_eq!(&after_archive.definition, created.prompt.definition());
|
||
let v2_after_archive = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 2)
|
||
.await
|
||
.expect("the second publication survives archive");
|
||
assert_eq!(&v2_after_archive.definition, &edited_definition);
|
||
|
||
// Повторная публикация той же версии не создаёт вторую строку публикации.
|
||
let repeat = publish(®istry, &workspace_id, &prompt_id, archived.updated_at).await;
|
||
assert!(matches!(repeat, Err(RegistryError::PromptNotDraft { .. })));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn story313_repeated_publish_of_the_same_version_conflicts_without_mutation() {
|
||
let (registry, pool) = registry_pool("repeated_publish").await;
|
||
let workspace_id = WorkspaceId::new(WS);
|
||
let prompt_id = PromptId::new("prm_story313_repeat");
|
||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||
.await
|
||
.expect("first publish succeeds");
|
||
let repeat = publish(®istry, &workspace_id, &prompt_id, published.updated_at).await;
|
||
assert!(matches!(
|
||
repeat,
|
||
Err(RegistryError::PromptPublicationConflict { .. })
|
||
));
|
||
let rows: i64 = sqlx::query_scalar(
|
||
"select count(*) from prompt_publications where prompt_id = $1 and version = 1",
|
||
)
|
||
.bind(prompt_id.as_str())
|
||
.fetch_one(&pool)
|
||
.await
|
||
.expect("publication rows are readable");
|
||
assert_eq!(rows, 1);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn story313_concurrent_publish_with_same_precondition_yields_one_publication() {
|
||
let (registry, pool) = registry_pool("concurrent_publish").await;
|
||
let workspace_id = WorkspaceId::new(WS);
|
||
let prompt_id = PromptId::new("prm_story313_concurrent");
|
||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||
let (first, second) = tokio::join!(
|
||
publish(®istry, &workspace_id, &prompt_id, created.updated_at),
|
||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||
);
|
||
let successes = usize::from(first.is_ok()) + usize::from(second.is_ok());
|
||
assert_eq!(successes, 1, "exactly one publish may win the CAS race");
|
||
let loser = if first.is_err() { first } else { second };
|
||
assert!(matches!(
|
||
loser,
|
||
Err(RegistryError::PromptStaleRevision { .. })
|
||
));
|
||
let rows: i64 = sqlx::query_scalar(
|
||
"select count(*) from prompt_publications where prompt_id = $1 and version = 1",
|
||
)
|
||
.bind(prompt_id.as_str())
|
||
.fetch_one(&pool)
|
||
.await
|
||
.expect("publication rows are readable");
|
||
assert_eq!(rows, 1);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn story313_database_guard_protects_published_definition_and_publication() {
|
||
let (registry, pool) = registry_pool("definition_guard").await;
|
||
let workspace_id = WorkspaceId::new(WS);
|
||
let prompt_id = PromptId::new("prm_story313_guard");
|
||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||
.await
|
||
.expect("publish succeeds");
|
||
|
||
let mutated = sqlx::query(
|
||
"update prompt_messages set content = 'tampered'
|
||
where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||
)
|
||
.bind(WS)
|
||
.bind(prompt_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert!(mutated.is_err(), "published messages must be immutable");
|
||
let removed = sqlx::query(
|
||
"delete from prompt_arguments where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||
)
|
||
.bind(WS)
|
||
.bind(prompt_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert!(removed.is_err(), "published arguments must be immutable");
|
||
let rewritten = sqlx::query(
|
||
"update prompt_publications set name = 'tampered'
|
||
where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||
)
|
||
.bind(WS)
|
||
.bind(prompt_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert!(rewritten.is_err(), "publication rows must be immutable");
|
||
|
||
// NEW-сторона guard: в опубликованную версию нельзя добавить новую строку
|
||
// definition напрямую через SQL.
|
||
let inserted_argument = sqlx::query(
|
||
"insert into prompt_arguments
|
||
(workspace_id, prompt_id, version, argument_name, argument_type, required,
|
||
default_value, enumeration, position)
|
||
values ($1, $2, 1, 'injected', 'string', false, null, null, 3)",
|
||
)
|
||
.bind(WS)
|
||
.bind(prompt_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert_immutable_guard_rejected(inserted_argument, "published Prompt version is immutable");
|
||
let inserted_message = sqlx::query(
|
||
"insert into prompt_messages (workspace_id, prompt_id, version, position, role, content)
|
||
values ($1, $2, 1, 2, 'assistant', 'injected')",
|
||
)
|
||
.bind(WS)
|
||
.bind(prompt_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert_immutable_guard_rejected(inserted_message, "published Prompt version is immutable");
|
||
|
||
let exact = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||
.await
|
||
.expect("exact read still works");
|
||
assert_eq!(&exact.definition, created.prompt.definition());
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn story313_exact_read_and_publish_are_workspace_scoped() {
|
||
let (registry, pool) = registry_pool("scope").await;
|
||
let own = WorkspaceId::new(WS);
|
||
let other = WorkspaceId::new("ws_story313_other");
|
||
let now = OffsetDateTime::now_utc();
|
||
registry
|
||
.create_workspace(CreateWorkspaceRequest {
|
||
workspace: &Workspace {
|
||
id: other.clone(),
|
||
slug: "story313-other".to_owned(),
|
||
display_name: "Story 3.13 other".to_owned(),
|
||
status: WorkspaceStatus::Active,
|
||
settings: json!({}),
|
||
created_at: now,
|
||
updated_at: now,
|
||
},
|
||
})
|
||
.await
|
||
.expect("second workspace is created");
|
||
let prompt_id = PromptId::new("prm_story313_scope");
|
||
let created = create_prompt(®istry, &own, &prompt_id).await;
|
||
publish(®istry, &own, &prompt_id, created.updated_at)
|
||
.await
|
||
.expect("publish succeeds");
|
||
|
||
let hidden = registry
|
||
.get_published_prompt_version(&other, &prompt_id, 1)
|
||
.await;
|
||
assert!(matches!(
|
||
hidden,
|
||
Err(RegistryError::PromptPublicationNotFound { .. })
|
||
));
|
||
let foreign_publish = publish(®istry, &other, &prompt_id, created.updated_at).await;
|
||
assert!(matches!(
|
||
foreign_publish,
|
||
Err(RegistryError::PromptNotFound { .. })
|
||
));
|
||
let publications: i64 =
|
||
sqlx::query_scalar("select count(*) from prompt_publications where prompt_id = $1")
|
||
.bind(prompt_id.as_str())
|
||
.fetch_one(&pool)
|
||
.await
|
||
.expect("publication rows are readable");
|
||
assert_eq!(publications, 1);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn story313_agent_binding_is_exact_typed_and_published_snapshot_is_stable() {
|
||
let (registry, pool) = registry_pool("agent_binding").await;
|
||
let workspace_id = WorkspaceId::new(WS);
|
||
let prompt_id = PromptId::new("prm_story313_binding");
|
||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||
.await
|
||
.expect("publish succeeds");
|
||
let agent_id = create_draft_agent(®istry, &workspace_id, "agent_story313", "agent313").await;
|
||
|
||
let saved = save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1)
|
||
.await
|
||
.expect("exact published Prompt binding is accepted");
|
||
assert_eq!(saved, 1);
|
||
let version = registry
|
||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||
.await
|
||
.expect("agent version reads")
|
||
.expect("agent version exists");
|
||
assert_eq!(
|
||
version.prompt_bindings,
|
||
vec![AgentPromptBinding {
|
||
prompt_id: prompt_id.clone(),
|
||
prompt_version: 1,
|
||
}]
|
||
);
|
||
|
||
// Draft edit после binding не меняет закреплённую версию.
|
||
registry
|
||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||
workspace_id: workspace_id.clone(),
|
||
prompt_id: prompt_id.clone(),
|
||
sensitivity: PromptSensitivity::Internal,
|
||
definition: prompt("Changed {{name}}"),
|
||
expected_updated_at: published.updated_at,
|
||
updated_at: OffsetDateTime::now_utc(),
|
||
})
|
||
.await
|
||
.expect("draft edit after binding succeeds");
|
||
let exact = registry
|
||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||
.await
|
||
.expect("binding keeps the exact published definition");
|
||
assert_eq!(&exact.definition, created.prompt.definition());
|
||
|
||
// Agent publication атомарно включает binding и bump catalog_revision; повтор
|
||
// уже опубликованной версии идемпотентен.
|
||
registry
|
||
.publish_agent(PublishAgentRequest {
|
||
workspace_id: &workspace_id,
|
||
agent_id: &agent_id,
|
||
version: 1,
|
||
published_at: &OffsetDateTime::now_utc(),
|
||
published_by: None,
|
||
expected_state: None,
|
||
})
|
||
.await
|
||
.expect("agent publishes with the exact Prompt snapshot");
|
||
let summary = registry
|
||
.get_agent_summary(&workspace_id, &agent_id)
|
||
.await
|
||
.expect("agent summary reads")
|
||
.expect("agent exists");
|
||
assert_eq!(summary.latest_published_version, Some(1));
|
||
assert_eq!(summary.catalog_revision, 1);
|
||
registry
|
||
.publish_agent(PublishAgentRequest {
|
||
workspace_id: &workspace_id,
|
||
agent_id: &agent_id,
|
||
version: 1,
|
||
published_at: &OffsetDateTime::now_utc(),
|
||
published_by: None,
|
||
expected_state: None,
|
||
})
|
||
.await
|
||
.expect("repeated publish is idempotent");
|
||
let repeated = registry
|
||
.get_agent_summary(&workspace_id, &agent_id)
|
||
.await
|
||
.expect("agent summary reads")
|
||
.expect("agent exists");
|
||
assert_eq!(repeated.catalog_revision, 1, "no double catalog bump");
|
||
|
||
// После unpublish та же версия публикуется обычным путём: Agent снова
|
||
// Published, revision растёт один раз, exact Prompt binding сохраняется.
|
||
registry
|
||
.unpublish_agent(&workspace_id, &agent_id, &OffsetDateTime::now_utc(), None)
|
||
.await
|
||
.expect("agent unpublishes");
|
||
registry
|
||
.publish_agent(PublishAgentRequest {
|
||
workspace_id: &workspace_id,
|
||
agent_id: &agent_id,
|
||
version: 1,
|
||
published_at: &OffsetDateTime::now_utc(),
|
||
published_by: None,
|
||
expected_state: None,
|
||
})
|
||
.await
|
||
.expect("republishing the same version after unpublish succeeds");
|
||
let republished = registry
|
||
.get_agent_summary(&workspace_id, &agent_id)
|
||
.await
|
||
.expect("agent summary reads")
|
||
.expect("agent exists");
|
||
assert_eq!(republished.catalog_revision, 3);
|
||
let still_bound = registry
|
||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||
.await
|
||
.expect("agent version reads")
|
||
.expect("agent version exists");
|
||
assert_eq!(still_bound.prompt_bindings.len(), 1);
|
||
|
||
// Published Agent bindings иммутабельны и через прямой SQL.
|
||
let rewritten = sqlx::query(
|
||
"update agent_prompt_bindings set prompt_version = 2
|
||
where agent_id = $1 and agent_version = 1",
|
||
)
|
||
.bind(agent_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert!(rewritten.is_err(), "published Agent bindings are immutable");
|
||
|
||
// NEW-сторона guard: в опубликованную версию Agent нельзя добавить новую
|
||
// привязку к другой опубликованной версии Prompt.
|
||
let second_prompt_id = PromptId::new("prm_story313_binding_second");
|
||
let second = create_prompt(®istry, &workspace_id, &second_prompt_id).await;
|
||
publish(
|
||
®istry,
|
||
&workspace_id,
|
||
&second_prompt_id,
|
||
second.updated_at,
|
||
)
|
||
.await
|
||
.expect("the second Prompt fixture publishes");
|
||
let inserted = sqlx::query(
|
||
"insert into agent_prompt_bindings
|
||
(workspace_id, agent_id, agent_version, prompt_id, prompt_version)
|
||
values ($1, $2, 1, $3, 1)",
|
||
)
|
||
.bind(WS)
|
||
.bind(agent_id.as_str())
|
||
.bind(second_prompt_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert_immutable_guard_rejected(inserted, "published Agent Prompt bindings are immutable");
|
||
|
||
let removed =
|
||
sqlx::query("delete from agent_prompt_bindings where agent_id = $1 and agent_version = 1")
|
||
.bind(agent_id.as_str())
|
||
.execute(&pool)
|
||
.await;
|
||
assert_immutable_guard_rejected(removed, "published Agent Prompt bindings are immutable");
|
||
|
||
let still_bound = registry
|
||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||
.await
|
||
.expect("agent version reads")
|
||
.expect("agent version exists");
|
||
assert_eq!(
|
||
still_bound.prompt_bindings,
|
||
vec![AgentPromptBinding {
|
||
prompt_id: prompt_id.clone(),
|
||
prompt_version: 1,
|
||
}],
|
||
"raw SQL must not change the published Agent snapshot"
|
||
);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn story313_binding_to_unpublished_or_archived_prompt_is_refused() {
|
||
let registry = registry("binding_refusals").await;
|
||
let workspace_id = WorkspaceId::new(WS);
|
||
let prompt_id = PromptId::new("prm_story313_refusals");
|
||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||
|
||
// Ещё не опубликованный Prompt: exact версии 1 нет в prompt_publications.
|
||
let unpublished = save_prompt_bindings(
|
||
®istry,
|
||
&workspace_id,
|
||
&create_draft_agent(®istry, &workspace_id, "agent_313_a", "agent313a").await,
|
||
1,
|
||
&prompt_id,
|
||
1,
|
||
)
|
||
.await;
|
||
assert!(unpublished.is_err(), "unpublished version cannot be bound");
|
||
|
||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||
.await
|
||
.expect("publish succeeds");
|
||
let agent_id = create_draft_agent(®istry, &workspace_id, "agent_313_b", "agent313b").await;
|
||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1)
|
||
.await
|
||
.expect("published version binds");
|
||
|
||
registry
|
||
.archive_prompt_draft(ArchivePromptRequest {
|
||
workspace_id: workspace_id.clone(),
|
||
prompt_id: prompt_id.clone(),
|
||
expected_updated_at: published.updated_at,
|
||
archived_at: OffsetDateTime::now_utc(),
|
||
})
|
||
.await
|
||
.expect("archive succeeds");
|
||
|
||
let archived =
|
||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1).await;
|
||
assert!(
|
||
matches!(archived, Err(RegistryError::PromptArchived { .. })),
|
||
"archived Prompt must refuse new bindings: {archived:?}"
|
||
);
|
||
let version = registry
|
||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||
.await
|
||
.expect("agent version reads")
|
||
.expect("agent version exists");
|
||
assert_eq!(
|
||
version.prompt_bindings.len(),
|
||
1,
|
||
"a refused binding must not clear existing bindings"
|
||
);
|
||
}
|
||
|
||
/// Гонка «bind в Draft-версию Agent» ↔ «publish этой версии»: обе операции
|
||
/// сериализуются на строке Agent, и опубликованный снимок не мутирует ни в одном
|
||
/// из порядков — bind либо успевает до publish, либо уезжает в новую Draft.
|
||
#[tokio::test]
|
||
async fn story313_concurrent_bind_and_agent_publish_keep_the_publication_stable() {
|
||
let (registry, pool) = registry_pool("bind_publish_race").await;
|
||
let workspace_id = WorkspaceId::new(WS);
|
||
let prompt_id = PromptId::new("prm_story313_race");
|
||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||
.await
|
||
.expect("the Prompt fixture publishes");
|
||
let agent_id =
|
||
create_draft_agent(®istry, &workspace_id, "agent_313_race", "agent313race").await;
|
||
let binding = AgentPromptBinding {
|
||
prompt_id: prompt_id.clone(),
|
||
prompt_version: 1,
|
||
};
|
||
|
||
let publish_at = OffsetDateTime::now_utc();
|
||
let (bound, published) = tokio::join!(
|
||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1),
|
||
registry.publish_agent(PublishAgentRequest {
|
||
workspace_id: &workspace_id,
|
||
agent_id: &agent_id,
|
||
version: 1,
|
||
published_at: &publish_at,
|
||
published_by: None,
|
||
expected_state: None,
|
||
})
|
||
);
|
||
published.expect("Agent publish serializes against the concurrent binding save");
|
||
|
||
let summary = registry
|
||
.get_agent_summary(&workspace_id, &agent_id)
|
||
.await
|
||
.expect("agent summary reads")
|
||
.expect("agent exists");
|
||
assert_eq!(summary.latest_published_version, Some(1));
|
||
|
||
let published_v1 = registry
|
||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||
.await
|
||
.expect("agent version reads")
|
||
.expect("version 1 exists");
|
||
assert_eq!(published_v1.status, AgentStatus::Published);
|
||
|
||
match bound {
|
||
// Bind ушёл первым: опубликованный снимок содержит эту привязку.
|
||
Ok(1) => {
|
||
assert_eq!(published_v1.prompt_bindings, vec![binding.clone()]);
|
||
assert_eq!(summary.current_draft_version, 1);
|
||
}
|
||
// Publish ушёл первым: bind форкнут в новую Draft, published v1 не изменился.
|
||
Ok(2) => {
|
||
assert!(
|
||
published_v1.prompt_bindings.is_empty(),
|
||
"publish won the race, so the published v1 must stay empty: {published_v1:?}"
|
||
);
|
||
let draft_v2 = registry
|
||
.get_agent_version(&workspace_id, &agent_id, 2)
|
||
.await
|
||
.expect("agent version reads")
|
||
.expect("the forked Draft version exists");
|
||
assert_eq!(draft_v2.status, AgentStatus::Draft);
|
||
assert_eq!(draft_v2.prompt_bindings, vec![binding.clone()]);
|
||
}
|
||
other => panic!("unexpected concurrent binding outcome: {other:?}"),
|
||
}
|
||
|
||
// Повторное чтение: опубликованный снимок не изменился после гонки.
|
||
let replayed = registry
|
||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||
.await
|
||
.expect("agent version reads")
|
||
.expect("version 1 exists");
|
||
assert_eq!(replayed.prompt_bindings, published_v1.prompt_bindings);
|
||
let rows: i64 = sqlx::query_scalar(
|
||
"select count(*) from agent_prompt_bindings where agent_id = $1 and agent_version = 1",
|
||
)
|
||
.bind(agent_id.as_str())
|
||
.fetch_one(&pool)
|
||
.await
|
||
.expect("binding rows are readable");
|
||
assert_eq!(
|
||
rows,
|
||
published_v1.prompt_bindings.len() as i64,
|
||
"the published Agent snapshot must not gain or lose binding rows"
|
||
);
|
||
}
|