Files
crank/crates/crank-registry/src/postgres/agent_prompt_bindings.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

185 lines
6.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Typed exact Prompt bindings Agent (Story 3.13, V22).
//!
//! `agent_prompt_bindings` — отдельная typed-таблица: строка адресует точную
//! Published Prompt Version (`prompt_publications`) для точной версии Agent
//! (`agent_versions`). Composite FK на обоих концах фиксирует workspace, поэтому
//! ни чужой Agent, ни чужая/неопубликованная Prompt Version не могут стать частью
//! binding, а floating `latest` невозможен.
//!
//! Archive — lifecycle-состояние, а не удаление immutable снимка: строка
//! публикации остаётся, поэтому новый binding на archived Prompt обязан
//! отклоняться проверкой состояния в той же транзакции, что и запись.
use super::*;
use crank_core::ids::PromptId;
use sqlx::{PgConnection, Row};
impl PostgresRegistry {
/// Точные Prompt bindings версии Agent (публичный read path).
pub async fn list_agent_prompt_bindings(
&self,
agent_id: &AgentId,
version: u32,
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
let mut connection = self.pool.acquire().await?;
read_agent_prompt_bindings(&mut connection, agent_id, version).await
}
/// Возвращает bindings, для которых в **этом** workspace нет точной строки
/// `prompt_publications`. Пустой результат — все версии опубликованы.
pub async fn unresolved_published_prompt_versions(
&self,
workspace_id: &WorkspaceId,
bindings: &[AgentPromptBinding],
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
let mut unresolved = Vec::new();
for binding in bindings {
let version = i32::try_from(binding.prompt_version).map_err(|_| {
RegistryError::InvalidNumericValue {
field: "prompt_version",
value: i64::from(binding.prompt_version),
}
})?;
let exists = sqlx::query_scalar::<_, bool>(
"select exists (
select 1 from prompt_publications
where workspace_id = $1 and prompt_id = $2 and version = $3
)",
)
.bind(workspace_id.as_str())
.bind(binding.prompt_id.as_str())
.bind(version)
.fetch_one(&self.pool)
.await?;
if !exists {
unresolved.push(binding.clone());
}
}
Ok(unresolved)
}
}
/// Полная замена Prompt bindings конкретной версии Agent внутри открытой
/// транзакции save/publish/fork. FK-нарушение откатывает всю транзакцию целиком.
pub(super) async fn replace_agent_prompt_bindings_rows(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
version: u32,
bindings: &[AgentPromptBinding],
) -> Result<(), RegistryError> {
if let Some(archived) = first_archived_prompt(tx, workspace_id, bindings).await? {
return Err(RegistryError::PromptArchived {
prompt_id: archived,
});
}
sqlx::query(
"delete from agent_prompt_bindings
where agent_id = $1 and agent_version = $2",
)
.bind(agent_id.as_str())
.bind(to_db_version(version))
.execute(&mut **tx)
.await?;
for binding in bindings {
sqlx::query(
"insert into agent_prompt_bindings (
workspace_id,
agent_id,
agent_version,
prompt_id,
prompt_version
) values ($1, $2, $3, $4, $5)",
)
.bind(workspace_id.as_str())
.bind(agent_id.as_str())
.bind(to_db_version(version))
.bind(binding.prompt_id.as_str())
.bind(to_db_version(binding.prompt_version))
.execute(&mut **tx)
.await?;
}
Ok(())
}
/// Archive блокирует только *новые* binding: immutable publication уже созданной
/// версии не удаляется. Кандидаты блокируются в детерминированном порядке, чтобы
/// concurrent archive либо успел раньше (отказ), либо ждал commit транзакции.
async fn first_archived_prompt(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &WorkspaceId,
bindings: &[AgentPromptBinding],
) -> Result<Option<String>, RegistryError> {
let prompt_ids: Vec<String> = bindings
.iter()
.map(|binding| binding.prompt_id.as_str().to_owned())
.collect();
if prompt_ids.is_empty() {
return Ok(None);
}
let rows = sqlx::query(
"select prompt_id, status
from prompts
where workspace_id = $1
and prompt_id = any($2::text[])
order by prompt_id asc
for update",
)
.bind(workspace_id.as_str())
.bind(&prompt_ids)
.fetch_all(&mut **tx)
.await?;
for row in rows {
if row.try_get::<String, _>("status")? == "archived" {
return Ok(Some(row.try_get("prompt_id")?));
}
}
Ok(None)
}
/// Fail-closed проверка перед публикацией Agent: ни один binding не должен
/// указывать на archived Prompt. Отказ не меняет ни snapshot, ни catalog_revision.
pub(super) async fn ensure_agent_prompt_bindings_not_archived(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
version: u32,
) -> Result<(), RegistryError> {
let bindings = read_agent_prompt_bindings(tx, agent_id, version).await?;
if let Some(archived) = first_archived_prompt(tx, workspace_id, &bindings).await? {
return Err(RegistryError::PromptArchived {
prompt_id: archived,
});
}
Ok(())
}
pub(super) async fn read_agent_prompt_bindings(
connection: &mut PgConnection,
agent_id: &AgentId,
version: u32,
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
let rows = sqlx::query(
"select prompt_id, prompt_version
from agent_prompt_bindings
where agent_id = $1 and agent_version = $2
order by prompt_id asc",
)
.bind(agent_id.as_str())
.bind(to_db_version(version))
.fetch_all(&mut *connection)
.await?;
rows.into_iter()
.map(|row| {
Ok(AgentPromptBinding {
prompt_id: PromptId::new(row.try_get::<String, _>("prompt_id")?),
prompt_version: from_db_version(row.try_get("prompt_version")?, "prompt_version")?,
})
})
.collect()
}