1use crate::application::envelope::{
16 declaration_entity_ref, CanonicalDeclarationId, CanonicalReferenceTarget,
17 CanonicalSemanticEnvelopeDocument, CanonicalSemanticPayload,
18};
19use crate::application::resolve::resolve_application_graph;
20use crate::graph::Graph;
21use crate::semantic_pack::canonical_json::{canonical_json, compute_sha256};
22use serde_json::{json, Value};
23
24pub const SEMANTIC_VERIFICATION_PROFILE: &str = "domainforge-semantic-verification/v1";
26
27pub const ENVELOPE_KIND_WORK_REQUEST: &str = "work_request";
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ObligationKind {
34 FlowBehavior,
36 PolicyProof,
38 Availability,
40}
41
42impl ObligationKind {
43 fn key(self) -> &'static str {
44 match self {
45 ObligationKind::FlowBehavior => "flow_behavior",
46 ObligationKind::PolicyProof => "policy_proof",
47 ObligationKind::Availability => "availability",
48 }
49 }
50
51 fn evidence_type(self) -> &'static str {
53 match self {
54 ObligationKind::FlowBehavior => "test_result",
55 ObligationKind::PolicyProof => "conformance_result",
56 ObligationKind::Availability => "configuration_snapshot",
57 }
58 }
59
60 fn projection_artifact(self) -> &'static str {
62 match self {
63 ObligationKind::FlowBehavior => "gauge",
64 ObligationKind::PolicyProof => "lean",
65 ObligationKind::Availability => "gauge",
66 }
67 }
68
69 fn limitation(self) -> &'static str {
70 match self {
71 ObligationKind::FlowBehavior => {
72 "Gauge step implementations remain external to the projection"
73 }
74 ObligationKind::PolicyProof => {
75 "Lean checks the supported policy subset; unsupported policies are obligation stubs"
76 }
77 ObligationKind::Availability => {
78 "availability obligations are declared-state only; no runtime observation"
79 }
80 }
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, serde::Serialize)]
86pub struct VerificationObligation {
87 pub obligation_id: String,
88 pub decl_key: String,
89 pub claim_id: String,
90 pub question_id: String,
91 pub question_form: String,
92 pub expected_answer_shape: String,
93 pub evidence_types: Vec<String>,
94 pub projection_artifact_refs: Vec<String>,
95 pub limitations: Vec<String>,
96}
97
98fn content_id(fields: &Value) -> String {
101 let digest = compute_sha256(canonical_json(fields).as_bytes());
102 digest.strip_prefix("sha256:").unwrap_or(&digest)[..24].to_string()
103}
104
105#[allow(clippy::too_many_arguments)]
108pub fn build_verification_contract(
109 doc: &CanonicalSemanticEnvelopeDocument,
110 entry_logical_path: &str,
111 sources_json: &str,
112 source_set_hash: &str,
113 envelope_id: &str,
114 created_at: &str,
115 registry_content_hash: Option<&str>,
116 resolved_namespaces: &[(String, String)],
117) -> Result<Value, String> {
118 let semantic_hash = doc.semantic_closure_hash.clone();
119 let graph = resolve_application_graph(entry_logical_path, sources_json).map_err(|diags| {
120 diags
121 .iter()
122 .map(|d| format!("{}: {}", d.code.slug(), d.message))
123 .collect::<Vec<_>>()
124 .join("; ")
125 })?;
126
127 let obligations = project_obligations(doc, &graph, &semantic_hash);
128
129 let created_by = format!("domainforge {}", env!("CARGO_PKG_VERSION"));
131
132 let mut envelope = serde_json::Map::new();
133 envelope.insert("envelope_id".to_string(), json!(envelope_id));
134 envelope.insert("cep_version".to_string(), json!("0.1.0"));
135 envelope.insert("envelope_version".to_string(), json!("1.0.0"));
136 envelope.insert(
137 "envelope_kind".to_string(),
138 json!(ENVELOPE_KIND_WORK_REQUEST),
139 );
140 envelope.insert("created_at".to_string(), json!(created_at));
141 envelope.insert("created_by".to_string(), json!(created_by));
142 envelope.insert(
143 "scope".to_string(),
144 json!({
145 "entry_logical_path": entry_logical_path,
146 "semantic_hash": semantic_hash,
147 "snapshot_ref": format!("snapshot:{semantic_hash}"),
148 "profile": SEMANTIC_VERIFICATION_PROFILE,
149 }),
150 );
151 envelope.insert(
152 "boundary_record".to_string(),
153 json!({
154 "scope": entry_logical_path,
155 "included_sections": ["questions", "constraints", "references"],
156 "excluded_sections": ["benchmarks", "settlements"],
157 "known_omissions": ["runtime state", "implementation test bindings",
158 "postconditions", "CEP Evidence and Settlement results"],
159 "unknowns": [],
160 "redactions": [],
161 "compression_notes": [],
162 "out_of_scope_entities": [],
163 "limitations": ["declared-state only; does not observe runtime behavior"],
164 }),
165 );
166 envelope.insert(
167 "completeness_status".to_string(),
168 json!("complete_for_declared_state"),
169 );
170 envelope.insert(
171 "omission_status".to_string(),
172 json!("known_omissions_recorded"),
173 );
174 envelope.insert(
175 "provenance_refs".to_string(),
176 json!([format!("source-set:{source_set_hash}")]),
177 );
178 envelope.insert("validation_status".to_string(), json!("valid"));
179 envelope.insert("lineage_refs".to_string(), json!([]));
180 envelope.insert(
181 "provenance".to_string(),
182 json!([{
183 "provenance_id": format!("provenance:{envelope_id}"),
184 "source_system_refs": [format!("source-set:{source_set_hash}")],
185 "producer_refs": [created_by],
186 "production_method": "domainforge envelope --emit verification-contract",
187 "created_at": created_at,
188 "verification_status": "unverified",
189 }]),
190 );
191 envelope.insert(
192 "references".to_string(),
193 json!([{
194 "ref_id": format!("snapshot:{semantic_hash}"),
195 "ref_type": "semantic_snapshot",
196 "target_uri_or_id": entry_logical_path,
197 "target_hash": semantic_hash,
198 "availability_status": "available",
199 "integrity_status": "verifiable",
200 "scope": entry_logical_path,
201 "limitations": [],
202 }]),
203 );
204
205 let questions: Vec<Value> = obligations
207 .iter()
208 .map(|o| {
209 json!({
210 "question_id": o.question_id,
211 "question_form": o.question_form,
212 "question_type": "verification",
213 "scope": o.decl_key,
214 "target_entities": [o.decl_key],
215 "expected_answer_shape": o.expected_answer_shape,
216 })
217 })
218 .collect();
219 envelope.insert("questions".to_string(), json!(questions));
220
221 let constraints: Vec<Value> = obligations
222 .iter()
223 .map(|o| {
224 json!({
225 "constraint_id": format!("evidence:{}", o.obligation_id),
226 "constraint_type": "evidence_requirement",
227 "description": format!(
228 "obligation {} requires at least one evidence record of type {}",
229 o.obligation_id,
230 o.evidence_types.join(",")
231 ),
232 "scope": o.decl_key,
233 "source": SEMANTIC_VERIFICATION_PROFILE,
234 "status": "active",
235 })
236 })
237 .collect();
238 envelope.insert("constraints".to_string(), json!(constraints));
239
240 envelope.insert(
243 "extensions".to_string(),
244 json!({
245 "domainforge": {
246 "profile": SEMANTIC_VERIFICATION_PROFILE,
247 "semantic_hash": semantic_hash,
248 "snapshot_ref": format!("snapshot:{semantic_hash}"),
249 "obligations": obligations,
250 "registry_content_hash": registry_content_hash,
251 "resolved_namespaces": resolved_namespaces,
252 }
253 }),
254 );
255
256 Ok(Value::Object(envelope))
257}
258
259fn project_obligations(
262 doc: &CanonicalSemanticEnvelopeDocument,
263 graph: &Graph,
264 semantic_hash: &str,
265) -> Vec<VerificationObligation> {
266 let mut obligations: Vec<VerificationObligation> = Vec::new();
267
268 for decl in &doc.envelope.semantic_declarations {
269 let CanonicalSemanticPayload::Flow(flow) = &decl.declaration else {
270 continue;
271 };
272 let decl_key = declaration_entity_ref(&decl.id);
273 let reference = |target: &CanonicalReferenceTarget| match target {
274 CanonicalReferenceTarget::Declaration {
275 id: CanonicalDeclarationId::Concept { id },
276 } => id.to_string(),
277 CanonicalReferenceTarget::Declaration { id } => declaration_entity_ref(id),
278 CanonicalReferenceTarget::Namespace {
279 exact_name,
280 logical_module_id,
281 } => format!("{logical_module_id}:{exact_name}"),
282 };
283 let resource = reference(&flow.resource);
284 let from = reference(&flow.from_entity);
285 let to = reference(&flow.to_entity);
286 let question_content = json!({
287 "q": format!("does the declared flow {resource} from {from} to {to} hold at realization?"),
288 });
289 push_obligation(
290 &mut obligations,
291 semantic_hash,
292 &decl_key,
293 ObligationKind::FlowBehavior,
294 &question_content,
295 );
296 }
297
298 for policy in graph.all_policies() {
299 let decl_key = format!("concept:{}", policy.id);
300 let question_content = json!({
301 "q": format!("does declared policy {} hold under its proof polarity?", policy.name),
302 });
303 push_obligation(
304 &mut obligations,
305 semantic_hash,
306 &decl_key,
307 ObligationKind::PolicyProof,
308 &question_content,
309 );
310 }
311
312 for entity in graph.all_entities() {
313 let decl_key = format!("concept:{}", entity.id());
314 let question_content = json!({
315 "q": format!("is declared entity {} available at realization?", entity.name()),
316 });
317 push_obligation(
318 &mut obligations,
319 semantic_hash,
320 &decl_key,
321 ObligationKind::Availability,
322 &question_content,
323 );
324 }
325
326 obligations.sort_by(|a, b| a.decl_key.cmp(&b.decl_key));
327 obligations
328}
329
330fn push_obligation(
332 obligations: &mut Vec<VerificationObligation>,
333 semantic_hash: &str,
334 decl_key: &str,
335 kind: ObligationKind,
336 question_content: &Value,
337) {
338 let obligation_fields = json!({
339 "profile": SEMANTIC_VERIFICATION_PROFILE,
340 "semantic_hash": semantic_hash,
341 "decl_key": decl_key,
342 "kind": kind.key(),
343 });
344 let question_fields = json!({
345 "profile": SEMANTIC_VERIFICATION_PROFILE,
346 "semantic_hash": semantic_hash,
347 "decl_key": decl_key,
348 "kind": kind.key(),
349 "content": question_content,
350 });
351 let claim_content = json!({
352 "claim": format!("declared {} obligation is satisfied at realization", kind.key()),
353 });
354 let claim_fields = json!({
355 "profile": SEMANTIC_VERIFICATION_PROFILE,
356 "semantic_hash": semantic_hash,
357 "decl_key": decl_key,
358 "kind": kind.key(),
359 "content": claim_content,
360 });
361
362 let obligation_id = content_id(&obligation_fields);
363 let question_id = content_id(&question_fields);
364 let claim_id = content_id(&claim_fields);
365 let question_form = match kind {
366 ObligationKind::FlowBehavior => "does_hold",
367 ObligationKind::PolicyProof => "does_hold",
368 ObligationKind::Availability => "is_available",
369 };
370
371 obligations.push(VerificationObligation {
372 decl_key: decl_key.to_string(),
373 obligation_id,
374 claim_id,
375 question_id,
376 question_form: question_form.to_string(),
377 expected_answer_shape: "boolean_with_failure_list".to_string(),
378 evidence_types: vec![kind.evidence_type().to_string()],
379 projection_artifact_refs: vec![format!("projection:{}", kind.projection_artifact())],
380 limitations: vec![kind.limitation().to_string()],
381 });
382}