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

403 lines
16 KiB
Rust

use crank_core::{
WorkspaceId,
ids::{PromptId, ResourceId},
prompt::{PromptDefinition, PromptError, PromptSensitivity, PromptStatus},
prompt_composition::{
self, PromptCompositionError, PromptDependencyPin, PromptDependencySourceClass,
effective_sensitivity, provenance_json,
},
};
use crank_registry::model::{
ArchivePromptRequest, CreatePromptDraftRequest, PromptDraftRecord, PromptPublicationRecord,
PublishPromptRequest, UpdatePromptDraftRequest,
};
use serde_json::{Value, json};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use uuid::Uuid;
use crate::{error::ApiError, service::AdminService};
pub(crate) mod portability;
const CREDENTIAL_FINDING: &str = "prompt_credential_finding";
const ACCESS_BYPASS_FINDING: &str = "prompt_access_bypass_finding";
const DEPENDENCY_CREDENTIAL_FINDING: &str = "prompt_dependency_credential_finding";
const DEPENDENCY_ACCESS_BYPASS_FINDING: &str = "prompt_dependency_access_bypass_finding";
impl AdminService {
pub(crate) async fn list_prompt_drafts(
&self,
workspace_id: &WorkspaceId,
) -> Result<Value, ApiError> {
let prompts = self.registry.list_prompt_drafts(workspace_id).await?;
Ok(json!({ "items": prompts.into_iter().map(prompt_view).collect::<Vec<_>>() }))
}
pub(crate) async fn get_prompt_draft(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
version: Option<u32>,
) -> Result<Value, ApiError> {
match version {
Some(version) => Ok(json!(publication_view(
self.registry
.get_published_prompt_version(workspace_id, prompt_id, version)
.await?
))),
None => Ok(json!(prompt_view(
self.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?
))),
}
}
/// `action: publish|archive` на существующем item route.
pub(crate) async fn prompt_action(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
body: Value,
) -> Result<Value, ApiError> {
let object = body.as_object().ok_or_else(invalid_body)?;
let action = object
.get("action")
.and_then(Value::as_str)
.ok_or_else(invalid_body)?;
if action != "publish" && action != "archive" {
return Err(invalid_body());
}
let expected_updated_at = object
.get("expected_updated_at")
.and_then(Value::as_str)
.ok_or_else(|| {
ApiError::precondition_required_with_context(
"expected_updated_at is required for a prompt lifecycle action",
json!({
"error_code": "prompt_precondition_required",
"recovery": "reload"
}),
)
})?
.parse_timestamp()?;
let now = truncate_to_micros(OffsetDateTime::now_utc());
let record = match action {
"publish" => {
// Шаблон не проходит Resource-публикацию, поэтому bounded scan стоит до
// публикации: непригодный текст не должен стать Published Prompt (AC7).
let draft = self
.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?;
scan_prompt_template(draft.prompt.definition())?;
self.registry
.publish_prompt_draft(PublishPromptRequest {
workspace_id: workspace_id.clone(),
prompt_id: prompt_id.clone(),
expected_updated_at,
published_at: now,
})
.await?
}
_ => {
self.registry
.archive_prompt_draft(ArchivePromptRequest {
workspace_id: workspace_id.clone(),
prompt_id: prompt_id.clone(),
expected_updated_at,
archived_at: now,
})
.await?
}
};
Ok(json!(prompt_view(record)))
}
pub(crate) async fn create_prompt_draft(
&self,
workspace_id: &WorkspaceId,
body: Value,
) -> Result<Value, ApiError> {
let object = body.as_object().ok_or_else(invalid_body)?;
let definition = parse_definition_body(&body)?;
let sensitivity = parse_sensitivity(object.get("sensitivity").and_then(Value::as_str))?;
let request = CreatePromptDraftRequest {
workspace_id: workspace_id.clone(),
prompt_id: PromptId::new(format!("prm_{}", Uuid::now_v7().simple())),
sensitivity,
definition,
created_at: truncate_to_micros(OffsetDateTime::now_utc()),
};
Ok(json!(prompt_view(
self.registry.create_prompt_draft(request).await?
)))
}
pub(crate) async fn update_prompt_draft(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
body: Value,
) -> Result<Value, ApiError> {
let object = body.as_object().ok_or_else(invalid_body)?;
let expected_updated_at = object
.get("expected_updated_at")
.and_then(Value::as_str)
.ok_or_else(invalid_body)?
.parse_timestamp()?;
let sensitivity = parse_sensitivity(object.get("sensitivity").and_then(Value::as_str))?;
let definition = parse_definition_body(&body)?;
let updated_at = truncate_to_micros(OffsetDateTime::now_utc());
let record = self
.registry
.update_prompt_draft(UpdatePromptDraftRequest {
workspace_id: workspace_id.clone(),
prompt_id: prompt_id.clone(),
sensitivity,
definition,
expected_updated_at,
updated_at,
})
.await?;
Ok(json!(prompt_view(record)))
}
/// Preview одного Draft: рендер шаблона + вставка точных pinned-версий (contract §7).
pub(crate) async fn preview_prompt_draft(
&self,
workspace_id: &WorkspaceId,
prompt_id: &PromptId,
body: Value,
correlation: &crank_core::CorrelationContext,
) -> Result<Value, ApiError> {
let arguments = body
.as_object()
.and_then(|object| object.get("arguments"))
.and_then(Value::as_object)
.cloned()
.ok_or_else(invalid_body)?;
let record = self
.registry
.get_prompt_draft(workspace_id, prompt_id)
.await?;
let definition = record.prompt.definition();
scan_prompt_template(definition)?;
let contents = self
.prompt_dependency_contents(workspace_id, &record.dependencies, correlation)
.await;
let messages =
prompt_composition::render(definition, &record.dependencies, &arguments, &contents)
.map_err(map_composition_error)?;
Ok(json!({
"status": "draft",
"version": record.prompt.version(),
"effective_sensitivity": effective_sensitivity(
record.prompt.sensitivity(),
&record.dependencies,
),
"messages": messages,
"dependencies": provenance_json(&record.dependencies),
}))
}
/// Content of every pinned dependency by declaration position; `None` = not readable now.
///
/// The pinned version is re-checked at read time (AC6/AC8): a revoked Resource never falls
/// back to stale content, and a static version is read through the single digest-verified
/// artifact path. A dynamic (template) dependency is read by the Story 3.11 runtime contract.
async fn prompt_dependency_contents(
&self,
workspace_id: &WorkspaceId,
pins: &[PromptDependencyPin],
correlation: &crank_core::CorrelationContext,
) -> Vec<Option<Vec<u8>>> {
let mut contents = Vec::with_capacity(pins.len());
for pin in pins {
let resource_id = ResourceId::new(pin.resource_id.clone());
let readable = match self
.registry
.resource_is_revoked(workspace_id, &resource_id)
.await
{
Ok(false) => match pin.source_class {
PromptDependencySourceClass::Static => self
.resources
.load_published_content(workspace_id, &resource_id, pin.version)
.await
.map(|(bytes, _)| bytes)
.ok(),
// Динамическая (template) зависимость читается контрактом Resource 3.11:
// определение не содержит bytes, поэтому исполняется объявленная read
// Operation с параметрами самого шаблона (значения по умолчанию).
PromptDependencySourceClass::Dynamic => {
self.resources
.read_pinned_template_content(
self,
workspace_id,
&resource_id,
pin.version,
correlation,
)
.await
}
},
Ok(true) | Err(_) => None,
};
contents.push(readable);
}
contents
}
}
/// Bounded scan of the Prompt template text: a raw credential or an explicit `include:`
/// directive blocks preview and publication with the exact `messages[i].content` path.
fn scan_prompt_template(definition: &PromptDefinition) -> Result<(), ApiError> {
prompt_composition::scan_template(definition).map_err(map_composition_error)
}
fn map_composition_error(error: PromptCompositionError) -> ApiError {
use crate::error as api_error;
match error {
PromptCompositionError::DependencyUnavailable { position } => {
api_error::unavailable(position)
}
PromptCompositionError::DependencyUnused {
position,
resource_id,
version,
} => api_error::unused(resource_id, version, position),
PromptCompositionError::DependencyRepresentationUnsupported { position } => {
api_error::representation_unsupported(String::new(), 0, position)
}
PromptCompositionError::CredentialFinding { source_path } => {
api_error::template_finding(CREDENTIAL_FINDING, source_path)
}
PromptCompositionError::AccessBypassFinding { source_path } => {
api_error::template_finding(ACCESS_BYPASS_FINDING, source_path)
}
PromptCompositionError::DependencyCredentialFinding { position } => {
api_error::dependency_finding(DEPENDENCY_CREDENTIAL_FINDING, position)
}
PromptCompositionError::DependencyAccessBypassFinding { position } => {
api_error::dependency_finding(DEPENDENCY_ACCESS_BYPASS_FINDING, position)
}
PromptCompositionError::Template(error) => map_prompt_error(error),
}
}
trait ParseTimestamp {
fn parse_timestamp(&self) -> Result<OffsetDateTime, ApiError>;
}
impl ParseTimestamp for str {
fn parse_timestamp(&self) -> Result<OffsetDateTime, ApiError> {
OffsetDateTime::parse(self, &Rfc3339)
.map(truncate_to_micros)
.map_err(|_| invalid_body())
}
}
fn prompt_view(record: PromptDraftRecord) -> Value {
let effective = effective_sensitivity(record.prompt.sensitivity(), &record.dependencies);
// Публикация показывает действующую политику; Draft — локальное редактируемое значение.
let sensitivity = match record.prompt.status() {
PromptStatus::Published => effective,
PromptStatus::Draft | PromptStatus::Archived => record.prompt.sensitivity(),
};
let prompt = record.prompt;
json!({
"prompt_id": prompt.prompt_id().as_str(),
"name": prompt.definition().name(),
"description": prompt.definition().description(),
"version": prompt.version(),
"current_draft_version": prompt.version(),
"latest_published_version": record.latest_published_version,
"status": prompt.status(),
"sensitivity": sensitivity,
"effective_sensitivity": effective,
"updated_at": record.updated_at.format(&Rfc3339).unwrap_or_default(),
"created_at": record.created_at.format(&Rfc3339).unwrap_or_default(),
"definition": prompt.definition().as_json(),
})
}
fn publication_view(record: PromptPublicationRecord) -> Value {
let published_at = record.published_at.format(&Rfc3339).unwrap_or_default();
json!({
"prompt_id": record.prompt_id.as_str(),
"name": record.name,
"description": record.description,
"version": record.version,
"current_draft_version": record.version,
"latest_published_version": record.version,
"status": "published",
"sensitivity": record.sensitivity,
"effective_sensitivity": record.sensitivity,
"updated_at": published_at,
"created_at": published_at,
"definition": record.definition.as_json(),
})
}
fn parse_definition_body(body: &Value) -> Result<PromptDefinition, ApiError> {
let mut value = body.as_object().cloned().ok_or_else(invalid_body)?;
value.remove("sensitivity");
value.remove("expected_updated_at");
PromptDefinition::parse(&Value::Object(value)).map_err(map_prompt_error)
}
fn parse_sensitivity(value: Option<&str>) -> Result<PromptSensitivity, ApiError> {
match value {
Some("public") => Ok(PromptSensitivity::Public),
Some("internal") => Ok(PromptSensitivity::Internal),
Some("secret") => Ok(PromptSensitivity::Secret),
_ => Err(invalid_body()),
}
}
fn map_prompt_error(error: PromptError) -> ApiError {
let (message, field, code) = match error {
PromptError::InvalidDefinition => (
"prompt definition is invalid",
"definition".to_owned(),
"prompt_invalid_definition",
),
PromptError::MissingArgument(name) => (
"required prompt argument is missing",
name,
"prompt_missing_argument",
),
PromptError::UnknownArgument(name) => (
"unknown prompt argument was supplied",
name,
"prompt_unknown_argument",
),
PromptError::InvalidArgument(name) => (
"prompt argument has an invalid value",
name,
"prompt_invalid_argument",
),
PromptError::InvalidTemplate => (
"prompt template cannot be rendered safely",
"messages".to_owned(),
"prompt_invalid_template",
),
};
ApiError::validation_with_context(message, json!({ "field": field, "error_code": code }))
}
fn invalid_body() -> ApiError {
ApiError::validation_with_context(
"prompt request is invalid",
json!({ "error_code": "prompt_invalid_request" }),
)
}
fn truncate_to_micros(value: OffsetDateTime) -> OffsetDateTime {
let nanos = value.nanosecond();
value
.replace_nanosecond(nanos - nanos % 1_000)
.unwrap_or(value)
}