domainforge_core/projection/baml/
ir.rs1use crate::projection::ai_learning::AiLearningContext;
13use crate::projection::ids::{element_id, sanitize_qname};
14use std::collections::{BTreeMap, BTreeSet};
15
16pub const BAML_FAMILY: &str = "baml";
19
20pub const BAML_TARGET_VERSION: &str = "0.68";
26
27#[derive(Debug, Clone)]
30pub struct Variant {
31 pub ident: String,
32 pub raw: String,
33}
34
35#[derive(Debug, Clone)]
37pub struct EnumDef {
38 pub name: String,
39 pub doc: String,
40 pub variants: Vec<Variant>,
41}
42
43#[derive(Debug, Clone)]
45pub struct FieldDef {
46 pub name: String,
47 pub type_ref: String,
48 pub doc: String,
49}
50
51#[derive(Debug, Clone)]
53pub struct ClassDef {
54 pub name: String,
55 pub doc: String,
56 pub fields: Vec<FieldDef>,
57}
58
59#[derive(Debug, Clone)]
61pub struct TestCase {
62 pub name: String,
64 pub role: String,
65 pub operation: String,
66 pub resource_type: String,
67 pub decision: String,
69 pub reason_code: String,
70 pub applicable_policies: Vec<String>,
71 pub id: String,
73}
74
75#[derive(Debug, Clone)]
78pub struct AICapabilityIR {
79 pub model_ref: String,
80 pub model_hash: String,
81 pub created_at: String,
82 pub generator_version: String,
83 pub capability_id: String,
85 pub function_name: String,
86 pub client_name: String,
87 pub entity_enum: EnumDef,
88 pub role_enum: EnumDef,
89 pub resource_enum: EnumDef,
90 pub operation_enum: EnumDef,
91 pub decision_enum: EnumDef,
92 pub request_class: ClassDef,
93 pub decision_class: ClassDef,
94 pub policy_lines: Vec<String>,
97 pub tests: Vec<TestCase>,
98}
99
100fn build_enum(name: &str, doc: &str, raws: impl IntoIterator<Item = String>) -> EnumDef {
104 let mut by_ident: BTreeMap<String, String> = BTreeMap::new();
105 for raw in raws {
106 let ident = sanitize_qname(&raw);
107 by_ident.entry(ident).or_insert(raw);
110 }
111 let variants = by_ident
112 .into_iter()
113 .map(|(ident, raw)| Variant { ident, raw })
114 .collect();
115 EnumDef {
116 name: name.to_string(),
117 doc: doc.to_string(),
118 variants,
119 }
120}
121
122impl AICapabilityIR {
123 pub fn build(ctx: &AiLearningContext) -> Result<Self, String> {
127 ctx.require_authority("baml")?;
128 let cfg = &ctx.recipe.projections.baml;
129
130 let mut entity_names: Vec<String> = ctx
132 .graph
133 .all_entities()
134 .into_iter()
135 .map(|e| e.name().to_string())
136 .collect();
137 entity_names.sort();
138 let mut role_names: Vec<String> = ctx
139 .graph
140 .all_roles()
141 .into_iter()
142 .map(|r| r.name().to_string())
143 .collect();
144 role_names.sort();
145 let mut resource_names: Vec<String> = ctx
146 .graph
147 .all_resources()
148 .into_iter()
149 .map(|r| r.name().to_string())
150 .collect();
151 resource_names.sort();
152
153 let operations: BTreeSet<String> = ctx
156 .authority_cases
157 .iter()
158 .map(|c| c.operation.clone())
159 .collect();
160 if operations.is_empty() {
161 return Err(
162 "baml projection requires at least one authority policy action; the \
163 provided authority environment declares none"
164 .to_string(),
165 );
166 }
167 if role_names.is_empty() || resource_names.is_empty() {
168 return Err(
169 "baml projection requires the model to declare at least one role and one \
170 resource (the authority request shape references both)"
171 .to_string(),
172 );
173 }
174
175 let entity_enum = build_enum(
176 "DomainEntity",
177 "Closed domain of entities declared in the model.",
178 entity_names,
179 );
180 let role_enum = build_enum(
181 "ActorRole",
182 "Closed domain of actor roles declared in the model.",
183 role_names,
184 );
185 let resource_enum = build_enum(
186 "ResourceType",
187 "Closed domain of resource types declared in the model.",
188 resource_names,
189 );
190 let operation_enum = build_enum(
191 "Operation",
192 "Operations governed by the authority pack (its action vocabulary).",
193 operations.into_iter().collect::<Vec<_>>(),
194 );
195 let decision_enum = EnumDef {
197 name: "AuthorityDecision".to_string(),
198 doc: "The authorization outcome, matching the DomainForge resolver's decision set."
199 .to_string(),
200 variants: ["Allow", "Deny", "Escalate", "Unknown", "Reject"]
201 .iter()
202 .map(|v| Variant {
203 ident: v.to_string(),
204 raw: v.to_lowercase(),
205 })
206 .collect(),
207 };
208
209 let request_class = ClassDef {
210 name: "AuthorityRequest".to_string(),
211 doc: "The authorization question: which actor role wants to perform which \
212 operation on which resource type."
213 .to_string(),
214 fields: vec![
215 FieldDef {
216 name: "actor_role".to_string(),
217 type_ref: role_enum.name.clone(),
218 doc: "The role the requesting actor holds.".to_string(),
219 },
220 FieldDef {
221 name: "operation".to_string(),
222 type_ref: operation_enum.name.clone(),
223 doc: "The operation being attempted.".to_string(),
224 },
225 FieldDef {
226 name: "resource_type".to_string(),
227 type_ref: resource_enum.name.clone(),
228 doc: "The type of resource the operation targets.".to_string(),
229 },
230 ],
231 };
232 let decision_class = ClassDef {
233 name: "AuthorityRuling".to_string(),
234 doc: "The decision plus its rationale and the policy ids that justify it.".to_string(),
235 fields: vec![
236 FieldDef {
237 name: "decision".to_string(),
238 type_ref: decision_enum.name.clone(),
239 doc: "The authorization outcome.".to_string(),
240 },
241 FieldDef {
242 name: "rationale".to_string(),
243 type_ref: "string".to_string(),
244 doc: "A short justification citing the governing policy.".to_string(),
245 },
246 FieldDef {
247 name: "policy_refs".to_string(),
248 type_ref: "string[]".to_string(),
249 doc: "Ids of the authority policies the decision relies on.".to_string(),
250 },
251 ],
252 };
253
254 let policy_lines = ctx
256 .policy_info
257 .values()
258 .map(|p| {
259 let scope = [
260 p.actor_role.as_deref().map(|r| format!("role={r}")),
261 p.action.as_deref().map(|a| format!("action={a}")),
262 p.resource_type.as_deref().map(|r| format!("resource={r}")),
263 ]
264 .into_iter()
265 .flatten()
266 .collect::<Vec<_>>()
267 .join(", ");
268 let desc = p.description.as_deref().unwrap_or("");
269 format!(
270 "{} [{}] (priority {}) applies to {{ {} }}{}",
271 p.policy_id,
272 p.modality,
273 p.priority,
274 scope,
275 if desc.is_empty() {
276 String::new()
277 } else {
278 format!(": {desc}")
279 }
280 )
281 })
282 .collect();
283
284 let mut cases: Vec<&crate::projection::ai_learning::AuthorityCase> = ctx
289 .authority_cases
290 .iter()
291 .filter(|c| cfg.include_unknown || c.label != "unknown")
292 .collect();
293 cases.sort_by(|a, b| {
294 (a.label, &a.role, &a.operation, &a.resource_type).cmp(&(
295 b.label,
296 &b.role,
297 &b.operation,
298 &b.resource_type,
299 ))
300 });
301 let tests = cases
302 .into_iter()
303 .map(|c| {
304 let id = element_id(
305 BAML_FAMILY,
306 &["test", &c.role, &c.operation, &c.resource_type],
307 );
308 let name = format!(
309 "t_{}_{}_{}_{}_{}",
310 c.label,
311 sanitize_qname(&c.role),
312 sanitize_qname(&c.operation),
313 sanitize_qname(&c.resource_type),
314 &id[..8],
315 );
316 TestCase {
317 name,
318 role: c.role.clone(),
319 operation: c.operation.clone(),
320 resource_type: c.resource_type.clone(),
321 decision: c.label.to_string(),
322 reason_code: c.reason_code.clone(),
323 applicable_policies: c.applicable_policies.clone(),
324 id,
325 }
326 })
327 .collect();
328
329 let function_name = cfg.function_name.clone();
330 let capability_id = element_id(BAML_FAMILY, &["capability", &function_name]);
331
332 Ok(Self {
333 model_ref: ctx.model_ref.clone(),
334 model_hash: ctx.model_hash.clone(),
335 created_at: ctx.created_at.clone(),
336 generator_version: crate::projection::ai_learning::GENERATOR_VERSION.to_string(),
337 capability_id,
338 function_name,
339 client_name: "DomainForgeAuthorityClient".to_string(),
340 entity_enum,
341 role_enum,
342 resource_enum,
343 operation_enum,
344 decision_enum,
345 request_class,
346 decision_class,
347 policy_lines,
348 tests,
349 })
350 }
351}