1use super::overrides::{self, CellOverrides, UnsafeOverrides};
15use super::profiles::{self, CellProfileData};
16use crate::parser::ast::{Ast, AstNode};
17use crate::projection::ids::{element_id, slug};
18use serde::Serialize;
19use serde_json::Value as JsonValue;
20use std::collections::HashMap;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
23#[serde(rename_all = "lowercase")]
24pub enum Origin {
25 Profile,
26 Sea,
27 Override,
28}
29
30#[derive(Debug, Clone, Serialize)]
31pub struct CellIdentity {
32 pub namespace: String,
33 pub name: String,
34 pub model_version: String,
35 pub owner: Option<String>,
36 pub cell_id: String,
37}
38
39#[derive(Debug, Clone, Serialize)]
40pub struct PlatformSpec {
41 pub architecture: String,
42 pub runtime_user: String,
43 pub network_default: String,
44}
45
46#[derive(Debug, Clone, Serialize)]
47pub struct ResourceSpec {
48 pub cpu: u32,
49 pub memory_mb: u32,
50 pub disk_mb: u32,
51 pub timeout_seconds: u32,
52}
53
54#[derive(Debug, Clone, Serialize)]
55pub struct SystemDependencyIr {
56 pub id: String,
57 pub name: String,
58 pub version: Option<String>,
59 pub realized_package: Option<String>,
62 pub origin: Origin,
63}
64
65#[derive(Debug, Clone, Serialize)]
66pub struct RuntimeIr {
67 pub id: String,
68 pub name: String,
69 pub version: String,
70 pub origin: Origin,
71}
72
73#[derive(Debug, Clone, Serialize)]
74pub struct ToolIr {
75 pub id: String,
76 pub name: String,
77 pub version: String,
78 pub origin: Origin,
79}
80
81#[derive(Debug, Clone, Serialize)]
82pub struct DependencySetIr {
83 pub id: String,
84 pub name: String,
85 pub ecosystem: String,
86 pub manifest: String,
87 pub lockfile: String,
88 pub install: String,
89 pub mutation: String,
91 pub origin: Origin,
92}
93
94#[derive(Debug, Clone, Serialize)]
95pub struct ServiceIr {
96 pub id: String,
97 pub name: String,
98 pub version: Option<String>,
99 pub activation: String,
100}
101
102#[derive(Debug, Clone, Serialize)]
103pub struct MountIr {
104 pub id: String,
105 pub name: String,
106 pub source: String,
107 pub target: String,
108 pub mode: String,
109}
110
111#[derive(Debug, Clone, Serialize)]
112pub struct EndpointIr {
113 pub id: String,
114 pub name: String,
115 pub host: String,
116 pub port: Option<u32>,
117 pub protocol: String,
118}
119
120#[derive(Debug, Clone, Serialize)]
121pub struct NetworkFlowIr {
122 pub id: String,
123 pub name: String,
124 pub from_ref: String,
125 pub to_ref: String,
126 pub operation: String,
127 pub credential: Option<String>,
128}
129
130#[derive(Debug, Clone, Serialize)]
131pub struct CredentialIr {
132 pub id: String,
133 pub name: String,
134 pub provider: String,
135 pub scope: String,
136 pub delivery: String,
137}
138
139#[derive(Debug, Clone, Serialize)]
140pub struct PolicyRefIr {
141 pub id: String,
142 pub name: String,
143 pub modality: String,
144 pub rationale: Option<String>,
145}
146
147#[derive(Debug, Clone, Serialize)]
148pub struct EvidenceProbeIr {
149 pub id: String,
150 pub command: String,
151 pub source: String,
152}
153
154#[derive(Debug, Clone, Serialize)]
155pub struct UnsafeOverrideRecord {
156 pub ticket: String,
157 pub authority: String,
158 pub rationale: String,
159 pub expires_at: String,
160}
161
162#[derive(Debug, Clone, Serialize)]
163pub struct CellIr {
164 pub identity: CellIdentity,
165 pub profile_id: String,
166 pub profile_version: String,
167 pub platform: PlatformSpec,
168 pub resources: ResourceSpec,
169 pub system_dependencies: Vec<SystemDependencyIr>,
170 pub runtimes: Vec<RuntimeIr>,
171 pub tools: Vec<ToolIr>,
172 pub dependency_sets: Vec<DependencySetIr>,
173 pub services: Vec<ServiceIr>,
174 pub mounts: Vec<MountIr>,
175 pub endpoints: Vec<EndpointIr>,
176 pub network_flows: Vec<NetworkFlowIr>,
177 pub credentials: Vec<CredentialIr>,
178 pub policies: Vec<PolicyRefIr>,
179 pub evidence_probes: Vec<EvidenceProbeIr>,
180 pub unsafe_override: Option<UnsafeOverrideRecord>,
181}
182
183fn ann_str<'a>(annotations: &'a HashMap<String, JsonValue>, key: &str) -> Option<&'a str> {
184 annotations.get(key).and_then(JsonValue::as_str)
185}
186
187fn ann_u32(annotations: &HashMap<String, JsonValue>, key: &str) -> Result<Option<u32>, String> {
188 match ann_str(annotations, key) {
189 None => Ok(None),
190 Some(raw) => raw.parse::<u32>().map(Some).map_err(|_| {
191 format!("CELL004 Cell annotation @{key} must be a non-negative integer, got '{raw}'")
192 }),
193 }
194}
195
196fn unwrap_export(node: &AstNode) -> &AstNode {
199 match node {
200 AstNode::Export(inner) => unwrap_export(&inner.node),
201 other => other,
202 }
203}
204
205impl CellIr {
206 pub fn build(
207 ast: &Ast,
208 model_ref: &str,
209 created_at: &str,
210 overrides: Option<&CellOverrides>,
211 ) -> Result<CellIr, String> {
212 let nodes: Vec<&AstNode> = ast
213 .declarations
214 .iter()
215 .map(|d| unwrap_export(&d.node))
216 .collect();
217
218 let cells: Vec<(&str, &HashMap<String, JsonValue>)> = nodes
219 .iter()
220 .filter_map(|n| match n {
221 AstNode::Cell { name, annotations } => Some((name.as_str(), annotations)),
222 _ => None,
223 })
224 .collect();
225
226 let (cell_name, cell_ann) = match cells.as_slice() {
227 [] => return Err("CELL002 no Cell declaration found; exactly one is required".to_string()),
228 [one] => *one,
229 _ => {
230 return Err(format!(
231 "CELL003 {} Cell declarations found; the cell-environment projection supports exactly one Cell per file",
232 cells.len()
233 ))
234 }
235 };
236
237 let profile_id = ann_str(cell_ann, "profile")
238 .ok_or_else(|| "CELL001 Cell is missing required @profile annotation".to_string())?;
239 let profile: CellProfileData = profiles::lookup(profile_id).ok_or_else(|| {
240 format!(
241 "CELL001 unknown profile '{profile_id}'; known profiles: {}",
242 profiles::KNOWN_PROFILES.join(", ")
243 )
244 })?;
245
246 let namespace = ast
247 .metadata
248 .namespace
249 .clone()
250 .unwrap_or_else(|| "default".to_string());
251 let model_version = ast
252 .metadata
253 .version
254 .clone()
255 .unwrap_or_else(|| "0.0.0".to_string());
256 let owner = ast.metadata.owner.clone();
257 let cell_id = element_id("cell", &[&namespace, cell_name]);
258
259 let platform = PlatformSpec {
260 architecture: ann_str(cell_ann, "architecture")
261 .unwrap_or("x86_64")
262 .to_string(),
263 runtime_user: ann_str(cell_ann, "runtime_user")
264 .unwrap_or("agent")
265 .to_string(),
266 network_default: ann_str(cell_ann, "network_default")
267 .unwrap_or("deny")
268 .to_string(),
269 };
270 let resources = ResourceSpec {
271 cpu: ann_u32(cell_ann, "cpu")?.unwrap_or(2),
272 memory_mb: ann_u32(cell_ann, "memory_mb")?.unwrap_or(4096),
273 disk_mb: ann_u32(cell_ann, "disk_mb")?.unwrap_or(10240),
274 timeout_seconds: ann_u32(cell_ann, "timeout_seconds")?.unwrap_or(1800),
275 };
276
277 let mut system_dependencies: Vec<SystemDependencyIr> = profile
279 .system_dependencies
280 .iter()
281 .map(|d| SystemDependencyIr {
282 id: element_id("cell:sysdep", &[&namespace, d.name]),
283 name: d.name.to_string(),
284 version: d.version.map(str::to_string),
285 realized_package: None,
286 origin: Origin::Profile,
287 })
288 .collect();
289 let mut runtimes: Vec<RuntimeIr> = profile
290 .runtimes
291 .iter()
292 .map(|t| RuntimeIr {
293 id: element_id("cell:runtime", &[&namespace, t.name]),
294 name: t.name.to_string(),
295 version: t.version.to_string(),
296 origin: Origin::Profile,
297 })
298 .collect();
299 let mut tools: Vec<ToolIr> = profile
300 .tools
301 .iter()
302 .map(|t| ToolIr {
303 id: element_id("cell:tool", &[&namespace, t.name]),
304 name: t.name.to_string(),
305 version: t.version.to_string(),
306 origin: Origin::Profile,
307 })
308 .collect();
309
310 let mut sea_sysdep_names: Vec<&str> = Vec::new();
316 let mut sea_runtime_names: Vec<&str> = Vec::new();
317 let mut sea_tool_names: Vec<&str> = Vec::new();
318 for n in &nodes {
319 match n {
320 AstNode::SystemDependency { name, version, .. } => {
321 sea_sysdep_names.push(name.as_str());
322 upsert_sysdep(&mut system_dependencies, &namespace, name, version.clone());
323 }
324 AstNode::Runtime { name, version, .. } => {
325 sea_runtime_names.push(name.as_str());
326 upsert_tool(
327 &mut runtimes,
328 &namespace,
329 "cell:runtime",
330 name,
331 version,
332 |id, name, version| RuntimeIr {
333 id,
334 name,
335 version,
336 origin: Origin::Sea,
337 },
338 );
339 }
340 AstNode::Tool { name, version, .. } => {
341 sea_tool_names.push(name.as_str());
342 upsert_tool(
343 &mut tools,
344 &namespace,
345 "cell:tool",
346 name,
347 version,
348 |id, name, version| ToolIr {
349 id,
350 name,
351 version,
352 origin: Origin::Sea,
353 },
354 );
355 }
356 _ => {}
357 }
358 }
359 check_no_duplicates("SystemDependency", sea_sysdep_names.into_iter())?;
362 check_no_duplicates("Runtime", sea_runtime_names.into_iter())?;
363 check_no_duplicates("Tool", sea_tool_names.into_iter())?;
364 check_no_duplicates(
365 "SystemDependency",
366 system_dependencies.iter().map(|d| d.name.as_str()),
367 )?;
368 check_no_duplicates("Runtime", runtimes.iter().map(|r| r.name.as_str()))?;
369 check_no_duplicates("Tool", tools.iter().map(|t| t.name.as_str()))?;
370
371 let mut dependency_sets = Vec::new();
373 for n in &nodes {
374 if let AstNode::DependencySet { name, annotations } = n {
375 let ecosystem = ann_str(annotations, "ecosystem").ok_or_else(|| {
376 format!("CELL005 DependencySet '{name}' is missing @ecosystem")
377 })?;
378 let contract = profile
379 .dependency_contract
380 .filter(|c| c.ecosystem == ecosystem);
381 let manifest = ann_str(annotations, "manifest")
382 .map(str::to_string)
383 .or_else(|| contract.map(|c| c.manifest.to_string()))
384 .ok_or_else(|| {
385 format!("CELL005 DependencySet '{name}' is missing @manifest")
386 })?;
387 let lockfile = ann_str(annotations, "lockfile")
388 .map(str::to_string)
389 .or_else(|| contract.map(|c| c.lockfile.to_string()))
390 .ok_or_else(|| {
391 format!("CELL005 DependencySet '{name}' is missing @lockfile")
392 })?;
393 let install = ann_str(annotations, "install")
394 .map(str::to_string)
395 .or_else(|| contract.map(|c| c.install.to_string()))
396 .ok_or_else(|| format!("CELL005 DependencySet '{name}' is missing @install"))?;
397 let mutation = ann_str(annotations, "mutation")
398 .unwrap_or("escalate")
399 .to_string();
400 dependency_sets.push(DependencySetIr {
401 id: element_id("cell:depset", &[&namespace, name]),
402 name: name.clone(),
403 ecosystem: ecosystem.to_string(),
404 manifest,
405 lockfile,
406 install,
407 mutation,
408 origin: Origin::Sea,
409 });
410 }
411 }
412 check_no_duplicates(
413 "DependencySet",
414 dependency_sets.iter().map(|d| d.name.as_str()),
415 )?;
416
417 let mut services = Vec::new();
419 let mut mounts = Vec::new();
420 let mut endpoints = Vec::new();
421 let mut network_flows = Vec::new();
422 let mut credentials = Vec::new();
423
424 for n in &nodes {
425 match n {
426 AstNode::Service {
427 name,
428 version,
429 annotations,
430 } => {
431 services.push(ServiceIr {
432 id: element_id("cell:service", &[&namespace, name]),
433 name: name.clone(),
434 version: version.clone(),
435 activation: ann_str(annotations, "activation")
436 .unwrap_or("required")
437 .to_string(),
438 });
439 }
440 AstNode::Mount { name, annotations } => {
441 mounts.push(MountIr {
442 id: element_id("cell:mount", &[&namespace, name]),
443 name: name.clone(),
444 source: ann_str(annotations, "source")
445 .ok_or_else(|| format!("CELL005 Mount '{name}' is missing @source"))?
446 .to_string(),
447 target: ann_str(annotations, "target")
448 .ok_or_else(|| format!("CELL005 Mount '{name}' is missing @target"))?
449 .to_string(),
450 mode: ann_str(annotations, "mode")
451 .unwrap_or("read-only")
452 .to_string(),
453 });
454 }
455 AstNode::Endpoint { name, annotations } => {
456 let port = ann_u32(annotations, "port")?;
457 endpoints.push(EndpointIr {
458 id: element_id("cell:endpoint", &[&namespace, name]),
459 name: name.clone(),
460 host: ann_str(annotations, "host")
461 .ok_or_else(|| format!("CELL005 Endpoint '{name}' is missing @host"))?
462 .to_string(),
463 port,
464 protocol: ann_str(annotations, "protocol")
465 .unwrap_or("https")
466 .to_string(),
467 });
468 }
469 AstNode::NetworkFlow {
470 name,
471 from_ref,
472 to_ref,
473 annotations,
474 } => {
475 network_flows.push(NetworkFlowIr {
476 id: element_id("cell:netflow", &[&namespace, name]),
477 name: name.clone(),
478 from_ref: from_ref.clone(),
479 to_ref: to_ref.clone(),
480 operation: ann_str(annotations, "operation")
481 .unwrap_or("read")
482 .to_string(),
483 credential: ann_str(annotations, "credential").map(str::to_string),
484 });
485 }
486 AstNode::Credential { name, annotations } => {
487 credentials.push(CredentialIr {
488 id: element_id("cell:credential", &[&namespace, name]),
489 name: name.clone(),
490 provider: ann_str(annotations, "provider")
491 .unwrap_or("broker")
492 .to_string(),
493 scope: ann_str(annotations, "scope")
494 .ok_or_else(|| {
495 format!("CELL005 Credential '{name}' is missing @scope")
496 })?
497 .to_string(),
498 delivery: ann_str(annotations, "delivery")
499 .unwrap_or("ephemeral")
500 .to_string(),
501 });
502 }
503 _ => {}
504 }
505 }
506 check_no_duplicates("Service", services.iter().map(|s| s.name.as_str()))?;
507 check_no_duplicates("Mount", mounts.iter().map(|m| m.name.as_str()))?;
508 check_no_duplicates("Endpoint", endpoints.iter().map(|e| e.name.as_str()))?;
509 check_no_duplicates("NetworkFlow", network_flows.iter().map(|f| f.name.as_str()))?;
510 check_no_duplicates("Credential", credentials.iter().map(|c| c.name.as_str()))?;
511
512 for flow in &network_flows {
515 let from_ok =
516 flow.from_ref == cell_name || services.iter().any(|s| s.name == flow.from_ref);
517 if !from_ok {
518 return Err(format!(
519 "CELL020 NetworkFlow '{}' references unknown 'from' object '{}' (must be the Cell or a declared Service)",
520 flow.name, flow.from_ref
521 ));
522 }
523 let to_ok = endpoints.iter().any(|e| e.name == flow.to_ref)
524 || services.iter().any(|s| s.name == flow.to_ref);
525 if !to_ok {
526 return Err(format!(
527 "CELL020 NetworkFlow '{}' references unknown 'to' object '{}' (must be a declared Endpoint or Service)",
528 flow.name, flow.to_ref
529 ));
530 }
531 }
532 for endpoint in &endpoints {
533 if endpoint.host == "*" || endpoint.host == "0.0.0.0" {
534 return Err(format!(
535 "CELL021 Endpoint '{}' declares wildcard host '{}'; wildcard egress requires an authorized unsafe override",
536 endpoint.name, endpoint.host
537 ));
538 }
539 }
540
541 let mut policies = Vec::new();
543 let mut evidence_probes = Vec::new();
544 for n in &nodes {
545 match n {
546 AstNode::Policy { name, metadata, .. } => {
547 policies.push(PolicyRefIr {
548 id: element_id("cell:policy", &[&namespace, name]),
549 name: name.clone(),
550 modality: metadata
551 .modality
552 .as_ref()
553 .map(|m| m.to_string())
554 .unwrap_or_else(|| "Obligation".to_string()),
555 rationale: metadata.rationale.clone(),
556 });
557 }
558 AstNode::Metric { name, .. } => {
559 evidence_probes.push(EvidenceProbeIr {
560 id: element_id("cell:evidence", &[&namespace, name]),
561 command: format!("metric:{name}"),
562 source: "metric".to_string(),
563 });
564 }
565 _ => {}
566 }
567 }
568 for tool in runtimes
569 .iter()
570 .map(|r| r.name.as_str())
571 .chain(tools.iter().map(|t| t.name.as_str()))
572 {
573 evidence_probes.push(EvidenceProbeIr {
574 id: element_id("cell:evidence", &[&namespace, tool, "version"]),
575 command: format!("{tool} --version"),
576 source: "tool-probe".to_string(),
577 });
578 }
579 for depset in &dependency_sets {
580 evidence_probes.push(EvidenceProbeIr {
581 id: element_id("cell:evidence", &[&namespace, &depset.name, "install"]),
582 command: depset.install.clone(),
583 source: "dependency-set".to_string(),
584 });
585 }
586
587 let mut ir = CellIr {
588 identity: CellIdentity {
589 namespace,
590 name: cell_name.to_string(),
591 model_version,
592 owner,
593 cell_id,
594 },
595 profile_id: profile.id.to_string(),
596 profile_version: profile.version.to_string(),
597 platform,
598 resources,
599 system_dependencies,
600 runtimes,
601 tools,
602 dependency_sets,
603 services,
604 mounts,
605 endpoints,
606 network_flows,
607 credentials,
608 policies,
609 evidence_probes,
610 unsafe_override: None,
611 };
612
613 if let Some(overrides) = overrides {
614 apply_overrides(&mut ir, overrides, created_at, model_ref)?;
615 }
616
617 sort_ir(&mut ir);
618 Ok(ir)
619 }
620}
621
622fn upsert_sysdep(
623 list: &mut Vec<SystemDependencyIr>,
624 namespace: &str,
625 name: &str,
626 version: Option<String>,
627) {
628 if let Some(existing) = list.iter_mut().find(|d| d.name == name) {
629 existing.version = version;
630 existing.origin = Origin::Sea;
631 } else {
632 list.push(SystemDependencyIr {
633 id: element_id("cell:sysdep", &[namespace, name]),
634 name: name.to_string(),
635 version,
636 realized_package: None,
637 origin: Origin::Sea,
638 });
639 }
640}
641
642fn upsert_tool<T>(
643 list: &mut Vec<T>,
644 namespace: &str,
645 family: &str,
646 name: &str,
647 version: &str,
648 make: impl Fn(String, String, String) -> T,
649) where
650 T: HasNameVersion,
651{
652 if let Some(existing) = list.iter_mut().find(|t| t.name() == name) {
653 existing.set_version(version.to_string());
654 existing.set_origin_sea();
655 } else {
656 list.push(make(
657 element_id(family, &[namespace, name]),
658 name.to_string(),
659 version.to_string(),
660 ));
661 }
662}
663
664trait HasNameVersion {
665 fn name(&self) -> &str;
666 fn set_version(&mut self, v: String);
667 fn set_origin_sea(&mut self);
668}
669
670impl HasNameVersion for RuntimeIr {
671 fn name(&self) -> &str {
672 &self.name
673 }
674 fn set_version(&mut self, v: String) {
675 self.version = v;
676 }
677 fn set_origin_sea(&mut self) {
678 self.origin = Origin::Sea;
679 }
680}
681
682impl HasNameVersion for ToolIr {
683 fn name(&self) -> &str {
684 &self.name
685 }
686 fn set_version(&mut self, v: String) {
687 self.version = v;
688 }
689 fn set_origin_sea(&mut self) {
690 self.origin = Origin::Sea;
691 }
692}
693
694fn check_no_duplicates<'a>(
695 category: &str,
696 names: impl Iterator<Item = &'a str>,
697) -> Result<(), String> {
698 let mut seen = std::collections::HashSet::new();
699 for name in names {
700 if !seen.insert(name) {
701 return Err(format!("CELL005 duplicate {category} declaration '{name}'"));
702 }
703 }
704 Ok(())
705}
706
707fn sort_ir(ir: &mut CellIr) {
708 ir.system_dependencies.sort_by(|a, b| a.name.cmp(&b.name));
709 ir.runtimes.sort_by(|a, b| a.name.cmp(&b.name));
710 ir.tools.sort_by(|a, b| a.name.cmp(&b.name));
711 ir.dependency_sets.sort_by(|a, b| a.name.cmp(&b.name));
712 ir.services.sort_by(|a, b| a.name.cmp(&b.name));
713 ir.mounts.sort_by(|a, b| a.name.cmp(&b.name));
714 ir.endpoints.sort_by(|a, b| a.name.cmp(&b.name));
715 ir.network_flows.sort_by(|a, b| a.name.cmp(&b.name));
716 ir.credentials.sort_by(|a, b| a.name.cmp(&b.name));
717 ir.policies.sort_by(|a, b| a.name.cmp(&b.name));
718 ir.evidence_probes.sort_by(|a, b| a.id.cmp(&b.id));
719 let _ = slug; }
721
722fn apply_overrides(
723 ir: &mut CellIr,
724 overrides: &CellOverrides,
725 created_at: &str,
726 model_ref: &str,
727) -> Result<(), String> {
728 let _ = model_ref;
729
730 if let Some(devbox) = &overrides.devbox {
731 for (name, package) in &devbox.packages {
732 let dep = ir
733 .system_dependencies
734 .iter_mut()
735 .find(|d| &d.name == name)
736 .ok_or_else(|| {
737 format!(
738 "CELL013 [devbox.packages] overrides undeclared SystemDependency '{name}'"
739 )
740 })?;
741 dep.realized_package = Some(package.clone());
742 }
743 }
744
745 if let Some(mise) = &overrides.mise {
746 for (name, version) in &mise.tools {
747 if let Some(runtime) = ir.runtimes.iter_mut().find(|r| &r.name == name) {
748 if overrides::version_key(version) < overrides::version_key(&runtime.version) {
749 return Err(format!(
750 "CELL011 [mise.tools].{name} = '{version}' weakens the declared version '{}'",
751 runtime.version
752 ));
753 }
754 runtime.version = version.clone();
755 runtime.origin = Origin::Override;
756 } else if let Some(tool) = ir.tools.iter_mut().find(|t| &t.name == name) {
757 if overrides::version_key(version) < overrides::version_key(&tool.version) {
758 return Err(format!(
759 "CELL011 [mise.tools].{name} = '{version}' weakens the declared version '{}'",
760 tool.version
761 ));
762 }
763 tool.version = version.clone();
764 tool.origin = Origin::Override;
765 } else {
766 return Err(format!(
767 "CELL013 [mise.tools] overrides undeclared runtime/tool '{name}'"
768 ));
769 }
770 }
771 }
772
773 for (name, dep_override) in &overrides.dependency_sets {
774 let depset = ir
775 .dependency_sets
776 .iter_mut()
777 .find(|d| &d.name == name)
778 .ok_or_else(|| {
779 format!("CELL013 [dependency_sets.{name}] overrides an undeclared DependencySet")
780 })?;
781 if let Some(cmd) = &dep_override.install_command {
782 depset.install = cmd.clone();
783 depset.origin = Origin::Override;
784 let probe_id = element_id(
788 "cell:evidence",
789 &[&ir.identity.namespace, &depset.name, "install"],
790 );
791 if let Some(probe) = ir.evidence_probes.iter_mut().find(|p| p.id == probe_id) {
792 probe.command = cmd.clone();
793 }
794 }
795 }
796
797 if let Some(res) = &overrides.resources {
798 macro_rules! check_reduce {
799 ($field:ident, $label:literal) => {
800 if let Some(v) = res.$field {
801 if v > ir.resources.$field {
802 return Err(format!(
803 "CELL012 [resources].{} = {} exceeds the declared ceiling {}",
804 $label, v, ir.resources.$field
805 ));
806 }
807 ir.resources.$field = v;
808 }
809 };
810 }
811 check_reduce!(cpu, "cpu");
812 check_reduce!(memory_mb, "memory_mb");
813 check_reduce!(disk_mb, "disk_mb");
814 check_reduce!(timeout_seconds, "timeout_seconds");
815 }
816
817 if let Some(network) = &overrides.network {
818 for (name, endpoint_override) in &network.endpoints {
819 let endpoint = ir
820 .endpoints
821 .iter_mut()
822 .find(|e| &e.name == name)
823 .ok_or_else(|| {
824 format!("CELL013 [network.endpoints.{name}] overrides an undeclared Endpoint")
825 })?;
826 if let Some(host) = &endpoint_override.host {
827 endpoint.host = host.clone();
828 if host == "*" || host == "0.0.0.0" {
832 match &overrides.unsafe_overrides {
833 Some(uo) if uo.enabled => {
834 overrides::validate_unsafe_overrides(uo, created_at)?;
835 }
836 _ => {
837 return Err(format!(
838 "CELL021 Endpoint '{}' override sets wildcard host '{}'; \
839 wildcard egress requires an authorized [unsafe_overrides] \
840 (enabled, ticket, authority, rationale, expires_at)",
841 endpoint.name, endpoint.host
842 ));
843 }
844 }
845 }
846 }
847 if let Some(port) = endpoint_override.port {
848 endpoint.port = Some(port);
849 }
850 }
851 }
852
853 if let Some(evidence) = &overrides.evidence {
854 for (i, probe) in evidence.extra_probes.iter().enumerate() {
855 ir.evidence_probes.push(EvidenceProbeIr {
856 id: element_id(
857 "cell:evidence",
858 &[&ir.identity.namespace, "override", &i.to_string()],
859 ),
860 command: probe.clone(),
861 source: "override".to_string(),
862 });
863 }
864 }
865
866 if let Some(unsafe_overrides) = &overrides.unsafe_overrides {
867 validate_and_record_unsafe(ir, unsafe_overrides, created_at)?;
868 }
869
870 Ok(())
871}
872
873fn validate_and_record_unsafe(
874 ir: &mut CellIr,
875 unsafe_overrides: &UnsafeOverrides,
876 created_at: &str,
877) -> Result<(), String> {
878 overrides::validate_unsafe_overrides(unsafe_overrides, created_at)?;
879 if unsafe_overrides.enabled {
880 ir.unsafe_override = Some(UnsafeOverrideRecord {
881 ticket: unsafe_overrides.ticket.clone(),
882 authority: unsafe_overrides.authority.clone(),
883 rationale: unsafe_overrides.rationale.clone(),
884 expires_at: unsafe_overrides.expires_at.clone(),
885 });
886 }
887 Ok(())
888}