Files
crank/apps/admin-api/src/service/prompts/portability.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

204 lines
7.9 KiB
Rust

//! Story 3.15: bounded portability envelope шаблона сообщений (Prompt) — экспорт
//! текущего Draft / точной Published Version и импорт как **нового** Draft
//! текущего владельца.
//!
//! Транспортный контракт (строгий allowlist ключей, формат/версия, `source` как
//! только provenance) живёт здесь, в admin-api; домен `crank-core` не меняется:
//! `arguments`/`messages` передаются **тем же** JSON, который принимает
//! `PromptDefinition::parse`/`as_json`, поэтому роли, типы, `enum`, `required` и
//! `default` переносятся без преобразований. Импорт не восстанавливает
//! идентичность: новый `prompt_id`, `current_draft_version = 1`, `status = draft`,
//! публикации нет. Владелец берётся из authenticated session, target workspace —
//! из URL, никогда из envelope.
use crank_core::{
WorkspaceId,
ids::PromptId,
prompt::{PromptDefinition, PromptSensitivity},
};
use serde_json::{Map, Value, json};
use crate::{error::ApiError, service::AdminService};
/// Единственный поддерживаемый формат переносимого документа.
pub(crate) const ENVELOPE_FORMAT: &str = "crank-prompt-portability";
pub(crate) const ENVELOPE_VERSION: u64 = 1;
const ROOT_KEYS: [&str; 4] = ["format", "version", "prompt", "source"];
const PROMPT_KEYS: [&str; 5] = [
"name",
"description",
"sensitivity",
"arguments",
"messages",
];
const SOURCE_KEYS: [&str; 2] = ["kind", "version"];
impl AdminService {
/// Экспорт текущего Draft: definition и его ревизия читаются одним exact-геттером.
pub(crate) async fn export_prompt_draft_envelope(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
) -> Result<(Value, String), ApiError> {
let record = self
.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?;
Ok(portable_document(
record.prompt.definition(),
record.prompt.sensitivity(),
"draft",
record.prompt.version(),
))
}
/// Экспорт **точной** Published Version: immutable snapshot этой ревизии.
pub(crate) async fn export_published_prompt_envelope(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
version: u32,
) -> Result<(Value, String), ApiError> {
let record = self
.registry
.get_published_prompt_version(workspace_id, prompt_id, version)
.await?;
Ok(portable_document(
&record.definition,
record.sensitivity,
"published",
record.version,
))
}
/// Импорт envelope: строгая форма → принятый `create_prompt_draft` (новый Draft).
/// Никакого upsert существующего Prompt этот путь не открывает.
pub(crate) async fn import_prompt_envelope(
&self,
workspace_id: &WorkspaceId,
body: Value,
) -> Result<Value, ApiError> {
let body = parse_envelope(&body)?;
// В контексте переноса любой отказ принятого парсера — стабильный
// `prompt_invalid_definition` (типы, лимиты, роли, плейсхолдеры, дубли имён);
// сообщение фиксированное, definition не эхо.
super::parse_definition_body(&body).map_err(|_| invalid_definition())?;
self.create_prompt_draft(workspace_id, body).await
}
}
fn portable_document(
definition: &PromptDefinition,
sensitivity: PromptSensitivity,
kind: &str,
version: u32,
) -> (Value, String) {
let definition = definition.as_json();
let name = definition["name"].as_str().unwrap_or_default();
let envelope = json!({
"format": ENVELOPE_FORMAT,
"version": ENVELOPE_VERSION,
"prompt": {
"name": definition["name"],
"description": definition["description"],
"sensitivity": sensitivity,
"arguments": definition["arguments"],
"messages": definition["messages"],
},
"source": { "kind": kind, "version": version },
});
(envelope, export_filename(name))
}
/// Разбор envelope со **строгим** allowlist: любой неизвестный ключ (в том числе
/// `prompt_id`, `workspace_id`, `owner`, `status`, `path`) — отказ формы.
///
/// Содержимое definition здесь не оценивается: невалидные роли/типы/лимиты/
/// плейсхолдеры отклоняет принятый парсер в `import_prompt_envelope`
/// (стабильный код `prompt_invalid_definition`).
fn parse_envelope(body: &Value) -> Result<Value, ApiError> {
let root = block(body, &ROOT_KEYS)?;
if root["format"].as_str() != Some(ENVELOPE_FORMAT) {
return Err(envelope_invalid());
}
if root["version"].as_u64() != Some(ENVELOPE_VERSION) {
return Err(envelope_invalid());
}
let prompt = block(&root["prompt"], &PROMPT_KEYS)?;
let name = text(prompt, "name")?;
let description = text(prompt, "description")?;
let sensitivity = match prompt["sensitivity"].as_str() {
Some("public") => json!("public"),
Some("internal") => json!("internal"),
Some("secret") => json!("secret"),
_ => return Err(envelope_invalid()),
};
let source = block(&root["source"], &SOURCE_KEYS)?;
match source["kind"].as_str() {
Some("draft") | Some("published") => {}
_ => return Err(envelope_invalid()),
}
// `source.version` — только provenance: проверяется по форме (целое ≥ 1) и
// ничего не восстанавливает.
source["version"]
.as_u64()
.filter(|value| (1..=u32::MAX as u64).contains(value))
.ok_or_else(envelope_invalid)?;
Ok(json!({
"name": name,
"description": description,
"sensitivity": sensitivity,
"arguments": prompt["arguments"],
"messages": prompt["messages"],
}))
}
/// `<sanitized name>.crank-prompt.json` — только ASCII, без CR/LF и traversal.
pub(crate) fn export_filename(name: &str) -> String {
let stem: String = name
.chars()
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
.take(64)
.collect();
let stem = if stem.is_empty() {
"prompt"
} else {
stem.as_str()
};
format!("{stem}.crank-prompt.json")
}
/// Ровно объявленный набор ключей: объект, ни одного лишнего, ни одного недостающего.
fn block<'a>(value: &'a Value, keys: &[&str]) -> Result<&'a Map<String, Value>, ApiError> {
let object = value.as_object().ok_or_else(envelope_invalid)?;
if object.len() != keys.len() || object.keys().any(|key| !keys.contains(&key.as_str())) {
return Err(envelope_invalid());
}
Ok(object)
}
fn text(object: &Map<String, Value>, key: &str) -> Result<String, ApiError> {
object[key]
.as_str()
.map(str::to_owned)
.ok_or_else(envelope_invalid)
}
fn envelope_invalid() -> ApiError {
ApiError::validation_with_context(
"prompt portability envelope is invalid",
json!({ "error_code": "prompt_portability_envelope_invalid" }),
)
}
fn invalid_definition() -> ApiError {
ApiError::validation_with_context(
"prompt definition is invalid",
json!({ "field": "definition", "error_code": "prompt_invalid_definition" }),
)
}