use crate::projection::ai_learning::provenance::Provenance;
use crate::projection::ai_learning::split::{TRAIN, VALIDATION};
use crate::projection::ai_learning::AiLearningContext;
use crate::projection::ids::element_id;
use std::collections::BTreeSet;
pub const DSPY_FAMILY: &str = "dspy";
pub const DSPY_TARGET_VERSION: &str = "2.5";
pub const LLM_DATASET_SUBDIR: &str = "llm_dataset";
pub const SOURCE_FAMILY: &str = "authorization_qa";
#[derive(Debug, Clone)]
pub struct DatasetRef {
pub root: String,
pub train: String,
pub dev: String,
pub family: String,
}
#[derive(Debug, Clone)]
pub struct OptimizerSpec {
pub name: String,
pub max_bootstrapped_demos: u32,
pub max_labeled_demos: u32,
pub regression_threshold: f64,
}
#[derive(Debug, Clone)]
pub struct AIOptimizationIR {
pub model_ref: String,
pub model_hash: String,
pub created_at: String,
pub generator_version: String,
pub capability_id: String,
pub signature_name: String,
pub program_name: String,
pub module_strategy: String,
pub decision_labels: Vec<String>,
pub policy_lines: Vec<String>,
pub metric_name: String,
pub dataset: DatasetRef,
pub optimizer: OptimizerSpec,
pub provenance: Provenance,
}
impl AIOptimizationIR {
pub fn build(ctx: &AiLearningContext) -> Result<Self, String> {
ctx.require_authority("dspy")?;
let cfg = &ctx.recipe.projections.dspy;
let has_decisive = ctx
.authority_cases
.iter()
.any(|c| cfg.include_unknown || c.label != "unknown");
if !has_decisive {
return Err(
"dspy projection requires at least one decisive authority case (allow/deny/\
escalate); the provided authority environment produced only 'unknown' tuples"
.to_string(),
);
}
let decision_labels: Vec<String> = ["allow", "deny", "escalate", "reject", "unknown"]
.iter()
.filter(|l| cfg.include_unknown || **l != "unknown")
.map(|l| l.to_string())
.collect();
let policy_lines = ctx
.policy_info
.values()
.map(|p| {
let scope = [
p.actor_role.as_deref().map(|r| format!("role={r}")),
p.action.as_deref().map(|a| format!("action={a}")),
p.resource_type.as_deref().map(|r| format!("resource={r}")),
]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(", ");
let desc = p.description.as_deref().unwrap_or("");
format!(
"{} [{}] (priority {}) applies to {{ {} }}{}",
p.policy_id,
p.modality,
p.priority,
scope,
if desc.is_empty() {
String::new()
} else {
format!(": {desc}")
}
)
})
.collect();
let operations: BTreeSet<&str> = ctx
.authority_cases
.iter()
.map(|c| c.operation.as_str())
.collect();
if operations.is_empty() {
return Err(
"dspy projection requires at least one authority policy action; the provided \
authority environment declares none"
.to_string(),
);
}
let signature_name = cfg.signature_name.clone();
let program_name = format!("{signature_name}Program");
let capability_id = element_id(DSPY_FAMILY, &["capability", &signature_name]);
let dataset = DatasetRef {
root: "../ai_learning".to_string(),
train: format!("{LLM_DATASET_SUBDIR}/{TRAIN}.jsonl"),
dev: format!("{LLM_DATASET_SUBDIR}/{VALIDATION}.jsonl"),
family: SOURCE_FAMILY.to_string(),
};
let optimizer = OptimizerSpec {
name: cfg.optimizer.clone(),
max_bootstrapped_demos: cfg.max_bootstrapped_demos,
max_labeled_demos: cfg.max_labeled_demos,
regression_threshold: cfg.regression_threshold,
};
let provenance = ctx.provenance(
ctx.policy_info.keys().cloned().collect(),
"authority_resolver",
"unreviewed",
);
Ok(Self {
model_ref: ctx.model_ref.clone(),
model_hash: ctx.model_hash.clone(),
created_at: ctx.created_at.clone(),
generator_version: crate::projection::ai_learning::GENERATOR_VERSION.to_string(),
capability_id,
signature_name,
program_name,
module_strategy: cfg.module_strategy.clone(),
decision_labels,
policy_lines,
metric_name: "decision_match".to_string(),
dataset,
optimizer,
provenance,
})
}
pub fn dspy_module_call(&self) -> &'static str {
match self.module_strategy.as_str() {
"chain_of_thought" => "dspy.ChainOfThought",
_ => "dspy.Predict",
}
}
}