Skip to main content

domainforge_core/projection/baml/
ir.rs

1//! BAML capability IR: the intermediate representation the renderer lowers to
2//! `.baml` source. Built entirely from an [`AiLearningContext`] so BAML reuses
3//! the same resolver-grounded authority cases and policy information the
4//! ai-learning datasets are built from — the examples/tests are the resolver's
5//! own decisions, never re-derived here.
6//!
7//! Every id is minted through [`crate::projection::ids`] so identity is uniform
8//! across projection families and stable run-to-run. All collections are built
9//! in sorted order (BTreeMap/BTreeSet only) so the rendered output is
10//! byte-deterministic for a fixed `created_at`.
11
12use crate::projection::ai_learning::AiLearningContext;
13use crate::projection::ids::{element_id, sanitize_qname};
14use std::collections::{BTreeMap, BTreeSet};
15
16/// Family tag for [`element_id`]: keeps BAML ids disjoint from every other
17/// projection family's ids for the same part tuple.
18pub const BAML_FAMILY: &str = "baml";
19
20/// Pinned BAML language target. The generated `.baml` is written against this
21/// syntax revision. Bump procedure: change this constant, regenerate the
22/// fixture, and confirm the `verify-baml` CI job (structural well-formedness
23/// check) stays green. See `docs/baml-projections.md` for what is and is not
24/// live-validated.
25pub const BAML_TARGET_VERSION: &str = "0.68";
26
27/// One enum variant: the BAML identifier plus the raw model string it came from
28/// (kept for doc comments and so the raw name appears verbatim in the source).
29#[derive(Debug, Clone)]
30pub struct Variant {
31    pub ident: String,
32    pub raw: String,
33}
34
35/// A BAML `enum` lowered from a closed model domain.
36#[derive(Debug, Clone)]
37pub struct EnumDef {
38    pub name: String,
39    pub doc: String,
40    pub variants: Vec<Variant>,
41}
42
43/// One class field: `name type` plus an optional doc line.
44#[derive(Debug, Clone)]
45pub struct FieldDef {
46    pub name: String,
47    pub type_ref: String,
48    pub doc: String,
49}
50
51/// A BAML `class` (a structured input or output schema).
52#[derive(Debug, Clone)]
53pub struct ClassDef {
54    pub name: String,
55    pub doc: String,
56    pub fields: Vec<FieldDef>,
57}
58
59/// One BAML `test` block seeded from a resolver-grounded authority case.
60#[derive(Debug, Clone)]
61pub struct TestCase {
62    /// Deterministic BAML test identifier (valid ident, starts with a letter).
63    pub name: String,
64    pub role: String,
65    pub operation: String,
66    pub resource_type: String,
67    /// Resolver decision label: "allow" | "deny" | "escalate" | "reject".
68    pub decision: String,
69    pub reason_code: String,
70    pub applicable_policies: Vec<String>,
71    /// Deterministic element id for the (role, operation, resource) tuple.
72    pub id: String,
73}
74
75/// The whole BAML capability: type defs, one policy-decision function, its
76/// tests, and the placeholder client — everything a renderer needs.
77#[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    /// Deterministic id for the capability (function) itself.
84    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    /// One human-readable line per authority policy, embedded in the prompt so
95    /// the function carries the policy semantics it must respect.
96    pub policy_lines: Vec<String>,
97    pub tests: Vec<TestCase>,
98}
99
100/// Build a distinct-variant enum from an iterator of raw model names, sorted and
101/// de-duplicated on the sanitized identifier so the output is deterministic and
102/// no two variants collide.
103fn 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        // First raw wins for a given sanitized ident (deterministic: inputs are
108        // pre-sorted by the caller / BTree keeps ident order).
109        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    /// Lower an [`AiLearningContext`] into the BAML capability IR. Requires a
124    /// resolver-grounded authority environment: without it there are no
125    /// policy-decision capabilities to represent.
126    pub fn build(ctx: &AiLearningContext) -> Result<Self, String> {
127        ctx.require_authority("baml")?;
128        let cfg = &ctx.recipe.projections.baml;
129
130        // Closed domains, sorted for determinism.
131        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        // Operations come from the authority pack action vocabulary, surfaced
154        // via the resolver-enumerated cases (single source of truth).
155        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        // Fixed output vocabulary: the resolver's five decision outcomes.
196        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        // Policy semantics for the prompt, deterministic via the BTreeMap.
255        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        // Tests seeded from the resolver's decisions. "unknown" cases (no
285        // applicable policy) are excluded by default: they add many rows with
286        // no governing policy and drown the meaningful examples. Sorted for a
287        // stable, readable order.
288        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}