Files
crank/crates/crank-core/src/prompt_composition.rs
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

235 lines
8.9 KiB
Rust

//! Story 3.16 (FR-18): pure composition of a Prompt with its pinned Resource dependencies.
//!
//! One renderer serves the admin preview and MCP `prompts/get`: the accepted typed renderer
//! (`PromptDefinition::preview`) validates arguments and renders the template text first, then the
//! pinned content of every declared `resource_refs` index is appended to the message the author
//! declared. Message count, order and roles come from the published template only — dependency
//! content can never add, remove or re-role a message. There is no tool dispatch and no code path
//! that interprets dependency content, so a `{"tool_calls": …}` block stays inert text.
//!
//! Failures are typed and total: the caller receives a reason and a position/source path, never a
//! partially composed message list and never the matched secret text.
use serde_json::{Map, Value};
use crate::prompt::{
MAX_TEXT_BYTES, PromptDefinition, PromptError, PromptMessage, PromptSensitivity,
};
use crate::resource::{ResourceKind, publication_include_directives, publication_secret_findings};
/// Bound of the `dependencies` array (contract §1, `MAX_PROMPT_DEPENDENCIES`).
pub const MAX_PROMPT_DEPENDENCIES: usize = 16;
/// Wire values of `dependencies[i].source_class` (contract §4).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PromptDependencySourceClass {
Static,
Dynamic,
}
impl PromptDependencySourceClass {
pub fn as_str(self) -> &'static str {
match self {
Self::Static => "static",
Self::Dynamic => "dynamic",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"static" => Some(Self::Static),
"dynamic" => Some(Self::Dynamic),
_ => None,
}
}
}
/// One resolved pin of a published dependency: the exact version the Prompt was published with,
/// plus the metadata the provenance block reports. It carries no content.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptDependencyPin {
pub position: usize,
pub resource_id: String,
pub version: u32,
pub digest: String,
pub kind: ResourceKind,
pub mime_type: String,
pub source_class: PromptDependencySourceClass,
pub sensitivity: PromptSensitivity,
}
impl PromptDependencyPin {
/// Provenance row of the preview contract (§7): declaration order, no content.
pub fn provenance_json(pin: &Self) -> Value {
serde_json::json!({
"position": pin.position,
"resource_id": pin.resource_id,
"version": pin.version,
"digest": pin.digest,
"kind": pin.kind.as_str(),
"mime_type": pin.mime_type,
"source_class": pin.source_class.as_str(),
"sensitivity": pin.sensitivity,
})
}
}
/// Ordered provenance block of a composed result.
pub fn provenance_json(pins: &[PromptDependencyPin]) -> Vec<Value> {
pins.iter()
.map(PromptDependencyPin::provenance_json)
.collect()
}
/// Typed refusal of the composition boundary.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PromptCompositionError {
/// A dependency no message references: pinning content that is never delivered (contract §1).
DependencyUnused {
position: usize,
resource_id: String,
version: u32,
},
/// The pinned exact version cannot be resolved/read right now (revoked, archived, foreign).
DependencyUnavailable { position: usize },
/// `binary` has no negotiated message representation (contract §4).
DependencyRepresentationUnsupported { position: usize },
/// The template text itself carries a raw credential.
CredentialFinding { source_path: String },
/// The template text itself carries an explicit `include:` access-bypass directive.
AccessBypassFinding { source_path: String },
/// Read-time content of a dynamic dependency carries a raw credential.
DependencyCredentialFinding { position: usize },
/// Read-time content of a dynamic dependency carries an `include:` directive.
DependencyAccessBypassFinding { position: usize },
/// The accepted renderer refused the template/arguments.
Template(PromptError),
}
impl From<PromptError> for PromptCompositionError {
fn from(error: PromptError) -> Self {
Self::Template(error)
}
}
/// Strictest-sensitivity fold: `effective = max(local, every pinned dependency)` (contract §3).
pub fn effective_sensitivity(
local: PromptSensitivity,
pins: &[PromptDependencyPin],
) -> PromptSensitivity {
pins.iter().fold(local, |strictest, pin| {
if rank(pin.sensitivity) > rank(strictest) {
pin.sensitivity
} else {
strictest
}
})
}
fn rank(sensitivity: PromptSensitivity) -> u8 {
match sensitivity {
PromptSensitivity::Public => 0,
PromptSensitivity::Internal => 1,
PromptSensitivity::Secret => 2,
}
}
/// The first dependency (declaration order) that no message references.
pub fn unused_dependency(definition: &PromptDefinition) -> Option<usize> {
(0..definition.dependencies().len()).find(|position| {
!definition
.messages()
.iter()
.any(|message| message.resource_refs.contains(position))
})
}
/// Bounded scan of the Prompt template text (messages, contract §5).
pub fn scan_template(definition: &PromptDefinition) -> Result<(), PromptCompositionError> {
for (position, message) in definition.messages().iter().enumerate() {
let bytes = message.content.as_bytes();
if publication_secret_findings(bytes).is_some() {
return Err(PromptCompositionError::CredentialFinding {
source_path: format!("messages[{position}].content"),
});
}
if !publication_include_directives(bytes).is_empty() {
return Err(PromptCompositionError::AccessBypassFinding {
source_path: format!("messages[{position}].content"),
});
}
}
Ok(())
}
/// Bounded scan of dynamic dependency content, fetched at read time (contract §5).
pub fn scan_dependency_content(
position: usize,
bytes: &[u8],
) -> Result<(), PromptCompositionError> {
if publication_secret_findings(bytes).is_some() {
return Err(PromptCompositionError::DependencyCredentialFinding { position });
}
if !publication_include_directives(bytes).is_empty() {
return Err(PromptCompositionError::DependencyAccessBypassFinding { position });
}
Ok(())
}
/// Content of every dependency, indexed by declaration position.
///
/// `None` means the exact pinned version could not be read now; a dependency that is absent from
/// this slice is treated the same way, so composition is total and never silently short.
pub fn render(
definition: &PromptDefinition,
pins: &[PromptDependencyPin],
arguments: &Map<String, Value>,
contents: &[Option<Vec<u8>>],
) -> Result<Vec<PromptMessage>, PromptCompositionError> {
let mut messages = definition.preview(arguments)?;
for message in &mut messages {
for index in &message.resource_refs {
let Some(Some(bytes)) = contents.get(*index) else {
return Err(PromptCompositionError::DependencyUnavailable { position: *index });
};
let pin = pins
.iter()
.find(|pin| pin.position == *index)
.ok_or(PromptCompositionError::DependencyUnavailable { position: *index })?;
let text = match pin.kind {
ResourceKind::Text | ResourceKind::Json => {
std::str::from_utf8(bytes).map_err(|_| {
PromptCompositionError::DependencyRepresentationUnsupported {
position: *index,
}
})?
}
ResourceKind::Binary => {
return Err(
PromptCompositionError::DependencyRepresentationUnsupported {
position: *index,
},
);
}
};
// Contract §5: dynamic content is fetched at read time and was never scanned at
// publication, so it is scanned here — one call site for preview and `prompts/get`.
if pin.source_class == PromptDependencySourceClass::Dynamic {
scan_dependency_content(*index, text.as_bytes())?;
}
if !message.content.is_empty() {
message.content.push_str("\n\n");
}
message.content.push_str(text);
// shortcut: one composed message keeps the accepted 16 KiB text bound; a larger
// composed message is refused instead of silently truncated.
if message.content.len() > MAX_TEXT_BYTES {
return Err(PromptCompositionError::Template(
PromptError::InvalidTemplate,
));
}
}
}
Ok(messages)
}