1use serde::Deserialize;
2
3use super::canonical_json;
4use super::diagnostics::{
5 DiagnosticSeverity, SemanticDiagnostic, SemanticDiagnosticCode, SemanticTruth,
6};
7use super::review::{self, DefinitionHashResult};
8use super::schema::{
9 AliasDef, ApprovalState, CompatibilityInfo, ConceptDef, ConceptStatus, GeneratorInfo, PackRef,
10 PackTrust, ReviewRecord, SemanticPack, SignatureState, SourceRef,
11};
12
13#[derive(Debug, Clone, Deserialize)]
15pub struct PackBuildInput {
16 pub org_id: String,
17 pub domain_id: String,
18 pub pack_version: String,
19 pub meaning_version: String,
20 pub approval: ApprovalState,
21 pub concepts: Vec<ConceptDef>,
22 pub relations: Vec<super::schema::RelationDef>,
23 pub metrics: Vec<super::schema::MetricDef>,
24 pub dimensions: Vec<super::schema::DimensionDef>,
25 pub units: Vec<super::schema::UnitDef>,
26 pub aliases: Vec<AliasDef>,
27 pub mapping_rules: Vec<super::schema::MappingRuleDef>,
28 pub review_records: Vec<ReviewRecord>,
29 pub previous_pack: Option<SemanticPack>,
30 pub allow_first_approved_version: bool,
31 pub source_graph_hash: String,
32}
33
34#[derive(Debug, Clone)]
36pub struct PackBuildOutput {
37 pub pack: SemanticPack,
38 pub pack_content_hash: String,
39 pub meaning_fingerprint: String,
40 pub pre_pack_diagnostics: Vec<SemanticDiagnostic>,
41 pub build_warnings: Vec<SemanticDiagnostic>,
42}
43
44pub fn build_semantic_pack(
46 input: PackBuildInput,
47) -> Result<PackBuildOutput, Vec<SemanticDiagnostic>> {
48 let mut pre_pack_diagnostics = Vec::new();
49
50 let mut build_warnings = Vec::new();
52 run_pre_pack_checks(&input, &mut pre_pack_diagnostics, &mut build_warnings);
53
54 if matches!(input.approval, ApprovalState::Approved) {
56 check_review_coverage(&input, &mut pre_pack_diagnostics, &mut build_warnings);
57 }
58
59 let pack_id = format!(
61 "{}/{}/{}",
62 input.org_id, input.domain_id, input.pack_version
63 );
64 let generator = GeneratorInfo {
65 name: "domainforge-core".to_string(),
66 version: "0.3".to_string(),
67 };
68
69 let review_manifest_hash = review::compute_review_manifest_hash(&input.review_records);
71
72 let mut concepts = input.concepts;
74 for c in &mut concepts {
75 if c.definition.definition_hash.is_empty() {
76 c.definition.definition_hash = canonical_json::compute_definition_hash(
77 &c.definition.text,
78 &c.examples,
79 &c.counterexamples,
80 &serde_json::to_value(c.status)
81 .ok()
82 .and_then(|v| v.as_str().map(String::from))
83 .unwrap_or_default(),
84 );
85 }
86 }
87
88 let mut aliases = input.aliases;
90 for a in &mut aliases {
91 a.normalized_alias = super::resolver::normalize_lookup_key(&a.alias);
92 }
93
94 let mut pack = SemanticPack {
95 schema_version: "0.3".to_string(),
96 pack_id: pack_id.clone(),
97 org_id: input.org_id,
98 domain_id: input.domain_id,
99 pack_version: input.pack_version,
100 meaning_version: input.meaning_version,
101 meaning_fingerprint: String::new(), source_graph_hash: input.source_graph_hash,
103 build_config_hash: canonical_json::compute_sha256(b"{}"),
104 review_manifest_hash,
105 created_at: crate::timefmt::now_rfc3339(),
106 generator,
107 trust: PackTrust {
108 approval_state: input.approval,
109 signature_state: SignatureState::Unsigned,
110 signed_by: None,
111 signature_alg: None,
112 signature: None,
113 },
114 concepts,
115 relations: input.relations,
116 metrics: input.metrics,
117 dimensions: input.dimensions,
118 units: input.units,
119 aliases,
120 mapping_rules: input.mapping_rules,
121 compatibility: CompatibilityInfo::default(),
122 };
123
124 pack.meaning_fingerprint = canonical_json::compute_meaning_fingerprint(&pack);
126
127 canonical_json::sort_pack_for_canonicalization(&mut pack);
129
130 let pack_content_hash = canonical_json::compute_pack_content_hash(&pack);
132
133 if let Some(ref prev) = input.previous_pack {
135 if prev.meaning_fingerprint != pack.meaning_fingerprint {
136 match version_increased(&prev.meaning_version, &pack.meaning_version) {
138 None => {
139 pre_pack_diagnostics.push(SemanticDiagnostic {
140 code: SemanticDiagnosticCode::MeaningVersionNotBumped,
141 severity: DiagnosticSeverity::Error,
142 semantic_truth: SemanticTruth::Invalid,
143 message: format!(
144 "Invalid version format: meaning_version '{}' or previous meaning_version '{}' contains non-numeric segments",
145 pack.meaning_version, prev.meaning_version
146 ),
147 source_ref: SourceRef::pack_uri(&pack_id),
148 pack_ref: PackRef {
149 pack_id: pack_id.clone(),
150 pack_content_hash: pack_content_hash.clone(),
151 path_or_uri: format!("pack://{}", pack_id),
152 priority: 0,
153 },
154 suggestions: vec![],
155 recoverability_hint: "Use numeric-only version format (e.g., MAJOR.MINOR.PATCH)".to_string(),
156 });
157 }
158 Some(false) => {
159 pre_pack_diagnostics.push(SemanticDiagnostic {
160 code: SemanticDiagnosticCode::MeaningVersionNotBumped,
161 severity: DiagnosticSeverity::Error,
162 semantic_truth: SemanticTruth::Invalid,
163 message: format!(
164 "meaning_fingerprint changed but meaning_version '{}' did not increase from '{}'",
165 pack.meaning_version, prev.meaning_version
166 ),
167 source_ref: SourceRef::pack_uri(&pack_id),
168 pack_ref: PackRef {
169 pack_id: pack_id.clone(),
170 pack_content_hash: pack_content_hash.clone(),
171 path_or_uri: format!("pack://{}", pack_id),
172 priority: 0,
173 },
174 suggestions: vec![],
175 recoverability_hint: "Bump meaning_version (MAJOR.MINOR.PATCH)".to_string(),
176 });
177 }
178 Some(true) => {
179 }
181 }
182 }
183 } else if matches!(input.approval, ApprovalState::Approved)
184 && !input.allow_first_approved_version
185 {
186 pre_pack_diagnostics.push(SemanticDiagnostic {
187 code: SemanticDiagnosticCode::MeaningVersionBaselineMissing,
188 severity: DiagnosticSeverity::Error,
189 semantic_truth: SemanticTruth::Unknown,
190 message: "No previous pack provided for approved build; use --allow-first-approved-version for initial pack".to_string(),
191 source_ref: SourceRef::pack_uri(&pack_id),
192 pack_ref: PackRef {
193 pack_id: pack_id.clone(),
194 pack_content_hash: pack_content_hash.clone(),
195 path_or_uri: format!("pack://{}", pack_id),
196 priority: 0,
197 },
198 suggestions: vec![],
199 recoverability_hint: "Provide --previous-pack or --allow-first-approved-version".to_string(),
200 });
201 }
202
203 if matches!(input.approval, ApprovalState::Approved) {
205 let has_errors = pre_pack_diagnostics
206 .iter()
207 .any(|d| d.severity == DiagnosticSeverity::Error);
208 if has_errors {
209 return Err(pre_pack_diagnostics);
210 }
211 }
212
213 let meaning_fingerprint = pack.meaning_fingerprint.clone();
214
215 Ok(PackBuildOutput {
216 pack,
217 pack_content_hash,
218 meaning_fingerprint,
219 pre_pack_diagnostics,
220 build_warnings,
221 })
222}
223
224fn run_pre_pack_checks(
225 input: &PackBuildInput,
226 diagnostics: &mut Vec<SemanticDiagnostic>,
227 build_warnings: &mut Vec<SemanticDiagnostic>,
228) {
229 let dummy_ref = PackRef {
230 pack_id: format!(
231 "{}/{}/{}",
232 input.org_id, input.domain_id, input.pack_version
233 ),
234 pack_content_hash: String::new(),
235 path_or_uri: String::new(),
236 priority: 0,
237 };
238
239 let mut seen_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
241 for c in &input.concepts {
242 if !seen_ids.insert(c.id.clone()) {
243 diagnostics.push(SemanticDiagnostic {
244 code: SemanticDiagnosticCode::DuplicateConceptId,
245 severity: DiagnosticSeverity::Error,
246 semantic_truth: SemanticTruth::Invalid,
247 message: format!("Duplicate concept ID: '{}'", c.id),
248 source_ref: SourceRef::pack_uri(&dummy_ref.pack_id),
249 pack_ref: dummy_ref.clone(),
250 suggestions: vec![],
251 recoverability_hint: "Rename duplicate concepts".to_string(),
252 });
253 }
254 }
255
256 let mut seen_names: std::collections::HashMap<String, String> =
258 std::collections::HashMap::new();
259 for c in &input.concepts {
260 let norm = super::resolver::normalize_lookup_key(&c.canonical_name);
261 if let Some(existing) = seen_names.get(&norm) {
262 if existing != &c.id {
263 diagnostics.push(SemanticDiagnostic {
264 code: SemanticDiagnosticCode::DuplicateCanonicalName,
265 severity: DiagnosticSeverity::Error,
266 semantic_truth: SemanticTruth::Invalid,
267 message: format!(
268 "Duplicate canonical name '{}' for concepts '{}' and '{}'",
269 c.canonical_name, existing, c.id
270 ),
271 source_ref: SourceRef::pack_uri(&dummy_ref.pack_id),
272 pack_ref: dummy_ref.clone(),
273 suggestions: vec![],
274 recoverability_hint: "Ensure canonical names are unique".to_string(),
275 });
276 }
277 } else {
278 seen_names.insert(norm, c.id.clone());
279 }
280 }
281
282 for c in &input.concepts {
284 if matches!(c.status, ConceptStatus::Active) && c.definition.text.is_empty() {
285 diagnostics.push(SemanticDiagnostic {
286 code: SemanticDiagnosticCode::MissingDefinition,
287 severity: DiagnosticSeverity::Warning,
288 semantic_truth: SemanticTruth::Unknown,
289 message: format!("Active concept '{}' missing definition", c.id),
290 source_ref: SourceRef::pack_uri(&dummy_ref.pack_id),
291 pack_ref: dummy_ref.clone(),
292 suggestions: vec![],
293 recoverability_hint: "Add definition text".to_string(),
294 });
295 }
296 }
297
298 for c in &input.concepts {
300 if matches!(c.status, ConceptStatus::Active) && c.owner.is_empty() {
301 diagnostics.push(SemanticDiagnostic {
302 code: SemanticDiagnosticCode::MissingOwner,
303 severity: DiagnosticSeverity::Warning,
304 semantic_truth: SemanticTruth::Unknown,
305 message: format!("Active concept '{}' missing owner", c.id),
306 source_ref: SourceRef::pack_uri(&dummy_ref.pack_id),
307 pack_ref: dummy_ref.clone(),
308 suggestions: vec![],
309 recoverability_hint: "Assign an owner".to_string(),
310 });
311 }
312 }
313
314 let concept_ids: std::collections::HashSet<&str> =
316 input.concepts.iter().map(|c| c.id.as_str()).collect();
317 for a in &input.aliases {
318 if !concept_ids.contains(a.target_concept_id.as_str()) {
319 diagnostics.push(SemanticDiagnostic {
320 code: SemanticDiagnosticCode::UnknownConcept,
321 severity: DiagnosticSeverity::Error,
322 semantic_truth: SemanticTruth::Invalid,
323 message: format!(
324 "Alias '{}' targets missing concept '{}'",
325 a.alias, a.target_concept_id
326 ),
327 source_ref: SourceRef::pack_uri(&dummy_ref.pack_id),
328 pack_ref: dummy_ref.clone(),
329 suggestions: vec![],
330 recoverability_hint: "Add the target concept".to_string(),
331 });
332 }
333 }
334
335 let conflict_report = super::resolver::detect_alias_conflicts(&input.aliases);
337 for key in &conflict_report.conflicting_keys {
338 diagnostics.push(SemanticDiagnostic {
339 code: SemanticDiagnosticCode::AliasConflict,
340 severity: DiagnosticSeverity::Error,
341 semantic_truth: SemanticTruth::Invalid,
342 message: format!(
343 "Alias conflict for key '{}': multiple targets through approved/deprecated entries",
344 key
345 ),
346 source_ref: SourceRef::pack_uri(&dummy_ref.pack_id),
347 pack_ref: dummy_ref.clone(),
348 suggestions: vec![],
349 recoverability_hint: "Resolve conflicting aliases".to_string(),
350 });
351 }
352 for key in &conflict_report.ambiguous_only_keys {
353 build_warnings_push(build_warnings, key, &dummy_ref);
354 }
355}
356
357fn build_warnings_push(diagnostics: &mut Vec<SemanticDiagnostic>, key: &str, pack_ref: &PackRef) {
358 diagnostics.push(SemanticDiagnostic {
359 code: SemanticDiagnosticCode::AmbiguousAliasGroup,
360 severity: DiagnosticSeverity::Warning,
361 semantic_truth: SemanticTruth::Unknown,
362 message: format!("Ambiguous-only alias group for key '{}'", key),
363 source_ref: SourceRef::pack_uri(&pack_ref.pack_id),
364 pack_ref: pack_ref.clone(),
365 suggestions: vec![],
366 recoverability_hint: String::new(),
367 });
368}
369
370fn check_review_coverage(
371 input: &PackBuildInput,
372 diagnostics: &mut Vec<SemanticDiagnostic>,
373 _build_warnings: &mut Vec<SemanticDiagnostic>,
374) {
375 let active_ids: Vec<String> = input
376 .concepts
377 .iter()
378 .filter(|c| matches!(c.status, ConceptStatus::Active))
379 .map(|c| c.id.clone())
380 .collect();
381
382 let gaps = review::validate_review_coverage(&active_ids, &input.review_records);
383 for gap in gaps {
384 diagnostics.push(SemanticDiagnostic {
385 code: SemanticDiagnosticCode::UnreviewedConcept,
386 severity: DiagnosticSeverity::Error,
387 semantic_truth: SemanticTruth::Unknown,
388 message: format!("Concept '{}' lacks review approval", gap.subject_id),
389 source_ref: SourceRef::pack_uri(&format!(
390 "{}/{}/{}",
391 input.org_id, input.domain_id, input.pack_version
392 )),
393 pack_ref: PackRef {
394 pack_id: format!(
395 "{}/{}/{}",
396 input.org_id, input.domain_id, input.pack_version
397 ),
398 pack_content_hash: String::new(),
399 path_or_uri: String::new(),
400 priority: 0,
401 },
402 suggestions: vec![],
403 recoverability_hint: "Add review decision for this concept".to_string(),
404 });
405 }
406
407 for c in &input.concepts {
409 if c.definition.definition_hash.is_empty() {
410 continue;
411 }
412 let hash_result = review::validate_definition_hashes(
413 &c.id,
414 &c.definition.definition_hash,
415 &input.review_records,
416 );
417 if let DefinitionHashResult::Mismatch {
418 reviewed_hash,
419 current_hash,
420 } = hash_result
421 {
422 diagnostics.push(SemanticDiagnostic {
423 code: SemanticDiagnosticCode::UnreviewedConcept,
424 severity: DiagnosticSeverity::Error,
425 semantic_truth: SemanticTruth::Unknown,
426 message: format!(
427 "Definition hash mismatch for '{}': reviewed='{}', current='{}'",
428 c.id, reviewed_hash, current_hash
429 ),
430 source_ref: SourceRef::pack_uri(&format!(
431 "{}/{}/{}",
432 input.org_id, input.domain_id, input.pack_version
433 )),
434 pack_ref: PackRef {
435 pack_id: format!(
436 "{}/{}/{}",
437 input.org_id, input.domain_id, input.pack_version
438 ),
439 pack_content_hash: String::new(),
440 path_or_uri: String::new(),
441 priority: 0,
442 },
443 suggestions: vec![],
444 recoverability_hint: "Re-review or record minor_amendment_no_semantic_change"
445 .to_string(),
446 });
447 }
448 }
449}
450
451pub(crate) fn version_increased(old: &str, new: &str) -> Option<bool> {
452 let parse = |s: &str| -> Option<Vec<u32>> {
453 s.split('.')
454 .map(|p| p.parse::<u32>().ok())
455 .collect::<Option<Vec<u32>>>()
456 };
457 let old_parts = parse(old)?;
458 let new_parts = parse(new)?;
459 for i in 0..std::cmp::max(old_parts.len(), new_parts.len()) {
460 let o = old_parts.get(i).copied().unwrap_or(0);
461 let n = new_parts.get(i).copied().unwrap_or(0);
462 if n > o {
463 return Some(true);
464 }
465 if n < o {
466 return Some(false);
467 }
468 }
469 Some(false)
470}