1use serde::{Deserialize, Serialize};
5use sha2::{Digest, Sha256};
6use std::collections::{BTreeMap, BTreeSet};
7
8pub type Files = BTreeMap<String, String>;
9pub fn digest(value: &impl Serialize) -> String {
10 format!(
11 "{:x}",
12 Sha256::digest(serde_json::to_vec(value).expect("serializable map"))
13 )
14}
15fn version() -> u32 {
16 1
17}
18
19#[derive(
21 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
22)]
23#[serde(rename_all = "camelCase", deny_unknown_fields)]
24pub struct Anchor {
25 pub file: String,
26 pub line: usize,
27 pub column: usize,
28 pub text: String,
29}
30
31pub fn local_path(file: &str) -> bool {
32 !file.is_empty()
33 && !file.contains(['\\', ':'])
34 && file.split('/').all(|p| !matches!(p, "" | "." | ".."))
35}
36impl Anchor {
37 pub fn new(file: &str, source: &str, start: usize, end: usize) -> Self {
38 Self {
39 file: file.into(),
40 line: source[..start].bytes().filter(|b| *b == b'\n').count() + 1,
41 column: start - source[..start].rfind('\n').map_or(0, |n| n + 1) + 1,
42 text: source[start..end].into(),
43 }
44 }
45 pub fn offset(&self, files: &Files) -> Option<usize> {
46 if !local_path(&self.file) || self.text.is_empty() || self.line == 0 || self.column == 0 {
47 return None;
48 }
49 let source = files.get(&self.file)?;
50 let start = source
51 .split_inclusive('\n')
52 .take(self.line - 1)
53 .map(str::len)
54 .sum::<usize>();
55 if source[..start].bytes().filter(|b| *b == b'\n').count() != self.line - 1 {
56 return None;
57 }
58 let line = source.get(start..)?.split('\n').next()?;
59 if self.column - 1 > line.len() {
60 return None;
61 }
62 let pos = start.checked_add(self.column - 1)?;
63 source.get(pos..)?.starts_with(&self.text).then_some(pos)
64 }
65}
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
68#[serde(rename_all = "camelCase", deny_unknown_fields)]
69pub struct InventorySite {
70 pub at: Anchor,
71 pub operation: String,
72}
73
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
77#[serde(rename_all = "camelCase", deny_unknown_fields)]
78pub struct Inputs {
79 #[serde(default = "version")]
80 pub schema_version: u32,
81 pub language: String,
82 pub context_digest: String,
83 pub files: Files,
84 pub assertions: Vec<InventorySite>,
85 pub limitations: Vec<String>,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase", deny_unknown_fields)]
90pub struct FileFingerprint {
91 pub sha256: String,
92 pub bytes: usize,
93}
94impl FileFingerprint {
95 pub fn of(source: &str) -> Self {
96 Self {
97 sha256: format!("{:x}", Sha256::digest(source.as_bytes())),
98 bytes: source.len(),
99 }
100 }
101}
102pub type FileManifest = BTreeMap<String, FileFingerprint>;
103
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
106#[serde(rename_all = "camelCase", deny_unknown_fields)]
107pub struct InputManifest {
108 pub schema_version: u32,
109 pub language: String,
110 pub context_digest: String,
111 pub files: FileManifest,
112 pub assertions: Vec<InventorySite>,
113 pub limitations: Vec<String>,
114}
115impl Inputs {
116 pub fn manifest(&self) -> InputManifest {
117 InputManifest {
118 schema_version: 2,
119 language: self.language.clone(),
120 context_digest: self.context_digest.clone(),
121 files: self
122 .files
123 .iter()
124 .map(|(p, s)| (p.clone(), FileFingerprint::of(s)))
125 .collect(),
126 assertions: self.assertions.clone(),
127 limitations: self.limitations.clone(),
128 }
129 }
130 pub fn identity(&self) -> String {
131 digest(&self.manifest())
132 }
133}
134impl InputManifest {
135 pub fn with_sources(&self, files: Files) -> Inputs {
136 Inputs {
137 schema_version: 1,
138 language: self.language.clone(),
139 context_digest: self.context_digest.clone(),
140 files,
141 assertions: self.assertions.clone(),
142 limitations: self.limitations.clone(),
143 }
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
148#[serde(rename_all = "camelCase", deny_unknown_fields)]
149pub struct Node {
150 pub id: String,
151 pub at: Anchor,
152 #[serde(default, skip_serializing_if = "String::is_empty")]
153 pub role: String,
154 #[serde(default, skip_serializing_if = "String::is_empty")]
155 pub meaning: String,
156}
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
158#[serde(rename_all = "camelCase", deny_unknown_fields)]
159pub struct Edge {
160 pub from: String,
161 pub to: String,
162 pub kind: String,
163 #[serde(default, skip_serializing_if = "String::is_empty")]
164 pub basis: String,
165}
166#[derive(
167 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
168)]
169#[serde(rename_all = "camelCase", deny_unknown_fields)]
170pub struct TestSelector {
171 pub file: String,
172 pub name: String,
173}
174
175#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
176#[serde(rename_all = "camelCase", deny_unknown_fields)]
177pub struct Flow {
178 pub id: String,
179 #[serde(deserialize_with = "required_basis")]
180 #[schemars(required, schema_with = "basis_schema")]
181 pub basis: Option<String>,
182 pub explanation: String,
183 pub applies_to: Vec<TestSelector>,
184 pub nodes: Vec<Node>,
185 #[serde(default)]
186 pub edges: Vec<Edge>,
187 pub counts_as_asserted: Vec<String>,
188 pub watch: Vec<String>,
189 #[serde(default, skip_serializing_if = "Vec::is_empty")]
190 pub questions: Vec<String>,
191}
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
193#[serde(rename_all = "camelCase", deny_unknown_fields)]
194pub struct Assertion {
195 pub id: String,
196 pub at: Anchor,
197 #[serde(default, skip_serializing_if = "Vec::is_empty")]
198 pub questions: Vec<String>,
199 #[serde(default)]
200 pub observes: Vec<String>,
201 #[serde(default)]
202 pub flows: Vec<Flow>,
203}
204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
205#[serde(rename_all = "camelCase", deny_unknown_fields)]
206pub struct Retired {
207 pub assertion: Assertion,
208 pub reason: String,
209}
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
211#[serde(rename_all = "camelCase", deny_unknown_fields)]
212pub struct AssertionMap {
213 #[schemars(range(min = 2, max = 2))]
214 pub schema_version: u32,
215 pub assertions: Vec<Assertion>,
216 #[serde(default, skip_serializing_if = "Vec::is_empty")]
217 pub change_assessments: Vec<ChangeAssessment>,
218 #[serde(default, skip_serializing_if = "Vec::is_empty")]
219 pub retired_assertions: Vec<Retired>,
220}
221
222fn required_basis<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
224 let value = Option::<String>::deserialize(d)?;
225 if value.as_deref().is_some_and(|s| !valid_basis(s)) {
226 return Err(serde::de::Error::custom(
227 "expected null or scov2:<64 lowercase hex digits>",
228 ));
229 }
230 Ok(value)
231}
232fn basis_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
233 schemars::json_schema!({"type":["string","null"],"pattern":"^scov2:[0-9a-f]{64}$"})
234}
235fn valid_basis(s: &str) -> bool {
236 s.strip_prefix("scov2:").is_some_and(|h| {
237 h.len() == 64
238 && h.bytes()
239 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
240 })
241}
242#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
243#[serde(rename_all = "camelCase", deny_unknown_fields)]
244pub struct ChangeAssessment {
245 pub id: String,
246 #[serde(deserialize_with = "required_basis")]
247 #[schemars(required, schema_with = "basis_schema")]
248 pub basis: Option<String>,
249 pub affected_flows: Vec<String>,
250 pub explanation: String,
251}
252
253pub fn schema() -> serde_json::Value {
256 serde_json::to_value(schemars::schema_for!(AssertionMap)).expect("schema")
257}
258
259#[derive(Debug, Serialize)]
260#[serde(rename_all = "camelCase")]
261pub struct ParseError {
262 pub pointer: String,
263 pub line: usize,
264 pub column: usize,
265 pub message: String,
266}
267impl std::fmt::Display for ParseError {
268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269 write!(
270 f,
271 "{} at {} (JSON line {}, column {})",
272 self.message, self.pointer, self.line, self.column
273 )
274 }
275}
276pub fn parse(bytes: &[u8]) -> Result<AssertionMap, ParseError> {
277 let mut deserializer = serde_json::Deserializer::from_slice(bytes);
278 let map: AssertionMap = serde_path_to_error::deserialize(&mut deserializer).map_err(|e| {
279 let pointer = e
280 .path()
281 .iter()
282 .map(|segment| {
283 use serde_path_to_error::Segment;
284 let part = match segment {
285 Segment::Seq { index } => index.to_string(),
286 Segment::Map { key } => key.clone(),
287 Segment::Enum { variant } => variant.clone(),
288 Segment::Unknown => "?".into(),
289 };
290 format!("/{}", part.replace('~', "~0").replace('/', "~1"))
291 })
292 .collect();
293 ParseError {
294 pointer,
295 line: e.inner().line(),
296 column: e.inner().column(),
297 message: e.inner().to_string(),
298 }
299 })?;
300 deserializer.end().map_err(|e| ParseError {
301 pointer: String::new(),
302 line: e.line(),
303 column: e.column(),
304 message: e.to_string(),
305 })?;
306 if map.schema_version != 2 {
307 return Err(ParseError {
308 pointer: "/schemaVersion".into(),
309 line: 0,
310 column: 0,
311 message: "unsupported map schema version; expected 2".into(),
312 });
313 }
314 Ok(map)
315}
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317#[serde(rename_all = "camelCase", deny_unknown_fields)]
318pub struct FlowState {
319 pub generation: String,
320 pub reasons: BTreeSet<String>,
321}
322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
323#[serde(rename_all = "camelCase", deny_unknown_fields)]
324pub struct Change {
325 pub id: String,
326 pub file: Option<String>,
327 pub before: Option<String>,
328 pub after: Option<String>,
329 pub reason: String,
330 pub known_flows: BTreeSet<String>,
331}
332#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
333#[serde(rename_all = "camelCase", deny_unknown_fields)]
334pub struct State {
335 pub schema_version: u32,
336 pub inputs_digest: String,
337 pub evidence_digest: String,
338 pub flows: BTreeMap<String, FlowState>,
339 pub changes: Vec<Change>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub inheritance: Option<Inheritance>,
342}
343#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
344#[serde(rename_all = "camelCase", deny_unknown_fields)]
345pub struct Inheritance {
346 pub from: Option<String>,
347 pub skipped: Vec<SkippedMap>,
348}
349#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
350#[serde(rename_all = "camelCase", deny_unknown_fields)]
351pub struct SkippedMap {
352 pub run: String,
353 pub reason: String,
354}
355pub fn flow_key(a: &Assertion, f: &Flow) -> String {
356 format!("{}/{}", a.id, f.id)
357}
358fn valid_id(id: &str) -> bool {
359 !id.is_empty()
360 && id
361 .bytes()
362 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
363}
364
365pub fn seed(inputs: &Inputs, evidence_digest: &str) -> (AssertionMap, State) {
366 seed_manifest(&inputs.manifest(), evidence_digest)
367}
368pub fn seed_manifest(inputs: &InputManifest, evidence_digest: &str) -> (AssertionMap, State) {
369 (
370 AssertionMap {
371 schema_version: 2,
372 assertions: inputs
373 .assertions
374 .iter()
375 .map(|site| Assertion {
376 id: format!("a_{}", &digest(&site.at)[..20]),
377 at: site.at.clone(),
378 questions: vec![],
379 observes: vec![],
380 flows: vec![],
381 })
382 .collect(),
383 change_assessments: vec![],
384 retired_assertions: vec![],
385 },
386 State {
387 schema_version: 3,
388 inputs_digest: digest(inputs),
389 evidence_digest: evidence_digest.into(),
390 flows: BTreeMap::new(),
391 changes: vec![],
392 inheritance: None,
393 },
394 )
395}
396
397pub fn validate(map: &AssertionMap, inputs: &Inputs) -> Vec<String> {
399 let mut errors = Vec::new();
400 if map.schema_version != 2 || inputs.schema_version != 1 {
401 errors.push("unsupported schema version".into());
402 }
403 let mut ids = BTreeSet::new();
404 let mut sites = BTreeSet::new();
405 for a in &map.assertions {
406 if !valid_id(&a.id) || !ids.insert(&a.id) {
407 errors.push(format!("{}: invalid/duplicate assertion ID", a.id));
408 }
409 if !sites.insert(&a.at) {
410 errors.push(format!("{}: duplicate assertion location", a.id));
411 }
412 if a.at.offset(&inputs.files).is_none() {
413 errors.push(format!("{}: invalid assertion anchor", a.id));
414 }
415 let mut flows = BTreeSet::new();
418 for f in &a.flows {
419 let key = flow_key(a, f);
420 if !valid_id(&f.id) || !flows.insert(&f.id) {
421 errors.push(format!("{key}: invalid/duplicate flow ID"));
422 }
423 errors.extend(
424 validate_flow(f, &inputs.files)
425 .into_iter()
426 .map(|e| format!("{key}: {e}")),
427 );
428 }
429 }
430 let mut changes = BTreeSet::new();
431 for change in &map.change_assessments {
432 if !valid_id(&change.id) || !changes.insert(&change.id) {
433 errors.push("invalid/duplicate change assessment ID".into());
434 }
435 }
436 errors
437}
438pub fn validate_flow(flow: &Flow, files: &Files) -> Vec<String> {
439 let mut errors = Vec::new();
440 let mut nodes = BTreeSet::new();
441 for node in &flow.nodes {
442 if !valid_id(&node.id) || !nodes.insert(&node.id) {
443 errors.push("invalid/duplicate node ID".into());
444 }
445 if node.at.offset(files).is_none() {
446 errors.push(format!("node {}: invalid anchor", node.id));
447 }
448 }
449 for edge in &flow.edges {
450 if !nodes.contains(&edge.from) || (!nodes.contains(&edge.to) && edge.to != "$assertion") {
451 errors.push("dangling edge".into());
452 }
453 }
454 if flow.counts_as_asserted.iter().any(|id| !nodes.contains(id)) {
455 errors.push("unknown counted node".into());
456 }
457 let mut reaches = BTreeSet::from(["$assertion".to_owned()]);
459 loop {
460 let size = reaches.len();
461 for edge in &flow.edges {
462 if reaches.contains(&edge.to) {
463 reaches.insert(edge.from.clone());
464 }
465 }
466 if reaches.len() == size {
467 break;
468 }
469 }
470 for id in &flow.counts_as_asserted {
471 if !reaches.contains(id) {
472 errors.push(format!(
473 "counted node {id} has no authored path to $assertion"
474 ));
475 }
476 }
477 if flow.edges.iter().any(|e| e.kind.trim().is_empty()) {
478 errors.push("missing edge kind".into());
479 }
480 if flow
481 .applies_to
482 .iter()
483 .any(|t| !local_path(&t.file) || !files.contains_key(&t.file) || t.name.trim().is_empty())
484 {
485 errors.push("invalid test selector file or name".into());
486 }
487 if flow.applies_to.iter().collect::<BTreeSet<_>>().len() != flow.applies_to.len() {
488 errors.push("duplicate test selector".into());
489 }
490 if flow
491 .counts_as_asserted
492 .iter()
493 .collect::<BTreeSet<_>>()
494 .len()
495 != flow.counts_as_asserted.len()
496 {
497 errors.push("duplicate counted node".into());
498 }
499 if flow.explanation.trim().is_empty() {
500 errors.push("missing explanation".into());
501 }
502 for file in &flow.watch {
503 if !local_path(file) || !files.contains_key(file) {
504 errors.push(format!("watched file missing: {file}"));
505 }
506 }
507 errors
508}
509
510pub fn dependencies<'a>(a: &'a Assertion, f: &'a Flow) -> BTreeSet<&'a str> {
512 std::iter::once(a.at.file.as_str())
513 .chain(f.applies_to.iter().map(|t| t.file.as_str()))
514 .chain(f.nodes.iter().map(|n| n.at.file.as_str()))
515 .chain(f.watch.iter().map(String::as_str))
516 .collect()
517}
518fn token(value: &impl Serialize) -> String {
519 format!("scov2:{}", digest(value))
520}
521pub fn change_errors(
522 map: &AssertionMap,
523 change: &Change,
524 response: &ChangeAssessment,
525) -> Vec<String> {
526 let keys = map
527 .assertions
528 .iter()
529 .flat_map(|a| a.flows.iter().map(move |f| flow_key(a, f)))
530 .collect::<BTreeSet<_>>();
531 let affected = response
532 .affected_flows
533 .iter()
534 .cloned()
535 .collect::<BTreeSet<_>>();
536 let mut errors = Vec::new();
537 if response.explanation.trim().is_empty() {
538 errors.push("missing impact explanation".into());
539 }
540 if affected.len() != response.affected_flows.len() {
541 errors.push("duplicate affected flow".into());
542 }
543 if !affected.is_subset(&keys) {
544 errors.push("unknown affected flow".into());
545 }
546 if !change
547 .known_flows
548 .intersection(&keys)
549 .all(|k| affected.contains(k))
550 {
551 errors.push("known dependent flows must be included unless removed from the map".into());
552 }
553 errors
554}
555pub fn expected_change_basis(
556 change: &Change,
557 response: &ChangeAssessment,
558 inputs: &InputManifest,
559) -> String {
560 token(&(
561 "supercov-change-v2",
562 change,
563 digest(inputs),
564 &response.id,
565 &response.affected_flows,
566 &response.explanation,
567 ))
568}
569pub fn change_current(map: &AssertionMap, change: &Change, inputs: &InputManifest) -> bool {
570 let responses = map
571 .change_assessments
572 .iter()
573 .filter(|r| r.id == change.id)
574 .collect::<Vec<_>>();
575 matches!(responses.as_slice(), [r] if change_errors(map, change, r).is_empty() && r.basis.as_deref() == Some(expected_change_basis(change, r, inputs).as_str()))
576}
577fn generation(
578 a: &Assertion,
579 f: &Flow,
580 map: &AssertionMap,
581 state: &State,
582 inputs: &InputManifest,
583) -> String {
584 let key = flow_key(a, f);
585 let base = state.flows.get(&key).map_or("0", |s| s.generation.as_str());
586 let impacts = state
587 .changes
588 .iter()
589 .filter(|c| change_current(map, c, inputs))
590 .filter_map(|c| {
591 map.change_assessments
592 .iter()
593 .find(|r| r.id == c.id && r.affected_flows.contains(&key))
594 .map(|r| (&c.id, &r.basis))
595 })
596 .collect::<BTreeMap<_, _>>();
597 if impacts.is_empty() {
598 base.into()
599 } else {
600 digest(&("supercov-generation-v2", base, impacts))
601 }
602}
603pub fn expected_basis(
604 a: &Assertion,
605 f: &Flow,
606 map: &AssertionMap,
607 state: &State,
608 inputs: &InputManifest,
609) -> String {
610 let mut claim = f.clone();
611 claim.basis = None;
612 let hashes = dependencies(a, f)
613 .into_iter()
614 .map(|p| (p, inputs.files.get(p)))
615 .collect::<BTreeMap<_, _>>();
616 token(&(
617 "supercov-flow-v2",
618 &inputs.context_digest,
619 &a.id,
620 &a.at,
621 &a.observes,
622 claim,
623 hashes,
624 generation(a, f, map, state, inputs),
625 ))
626}
627pub fn reasons(
628 a: &Assertion,
629 f: &Flow,
630 map: &AssertionMap,
631 state: &State,
632 inputs: &Inputs,
633) -> BTreeSet<String> {
634 reasons_for_manifest(a, f, map, state, inputs, &inputs.manifest())
635}
636pub fn reasons_for_manifest(
637 a: &Assertion,
638 f: &Flow,
639 map: &AssertionMap,
640 state: &State,
641 inputs: &Inputs,
642 manifest: &InputManifest,
643) -> BTreeSet<String> {
644 let mut reasons = BTreeSet::new();
645 if state.schema_version != 3 || state.inputs_digest != digest(manifest) {
646 reasons.insert("state does not match run inputs".into());
647 }
648 if f.basis.as_deref() != Some(expected_basis(a, f, map, state, manifest).as_str()) {
649 reasons.insert(
650 if f.basis.is_none() {
651 "draft: input acknowledgement not recorded"
652 } else {
653 "claim or inputs changed; needs rechecking"
654 }
655 .into(),
656 );
657 if let Some(s) = state.flows.get(&flow_key(a, f)) {
658 reasons.extend(s.reasons.iter().cloned());
659 }
660 }
661 reasons.extend(validate_flow(f, &inputs.files));
662 if a.at.offset(&inputs.files).is_none() {
663 reasons.insert("invalid assertion anchor".into());
664 }
665 if !f.questions.is_empty() {
666 reasons.insert("flow has unresolved questions".into());
667 }
668 reasons
669}
670pub fn validation(map: &AssertionMap, state: &State, inputs: &Inputs) -> serde_json::Value {
672 use serde_json::json;
673 let manifest = inputs.manifest();
674 let mut errors = validate(map, inputs);
675 for r in &map.change_assessments {
676 if !state.changes.iter().any(|c| c.id == r.id) {
677 errors.push(format!("{}: unknown change assessment", r.id));
678 }
679 }
680 let changes = state.changes.iter().map(|c| {
681 let response = map.change_assessments.iter().find(|r| r.id == c.id);
682 let faults = response.map(|r| change_errors(map, c, r)).unwrap_or_default();
683 errors.extend(faults.iter().map(|e| format!("{}: {e}", c.id)));
684 json!({"id":c.id,"file":c.file,"before":c.before,"after":c.after,"reason":c.reason,"knownFlows":c.known_flows,
685 "current":change_current(map,c,&manifest),"assessment":response,"errors":faults,
686 "expectedBasis":response.map(|r| expected_change_basis(c,r,&manifest))})
687 }).collect::<Vec<_>>();
688 let flows = map.assertions.iter().flat_map(|a| a.flows.iter().map(move |f| (a,f))).map(|(a,f)| {
689 json!({"id":flow_key(a,f),"expectedBasis":expected_basis(a,f,map,state,&manifest),"reasons":reasons_for_manifest(a,f,map,state,inputs,&manifest)})
690 }).collect::<Vec<_>>();
691 json!({"valid":errors.is_empty(),"stage":"references","errors":errors,"flows":flows,"changes":changes,
692 "meaning":"Authored graph references and input acknowledgements only; no semantic proof or completeness claim"})
693}
694pub fn invalidate(state: &mut State, map: &AssertionMap, reason: &str) {
695 for a in &map.assertions {
696 for f in &a.flows {
697 let key = flow_key(a, f);
698 let base = state.flows.get(&key).map_or("0", |s| s.generation.as_str());
699 state.flows.insert(
700 key,
701 FlowState {
702 generation: digest(&(base, reason, &state.inputs_digest)),
703 reasons: BTreeSet::from([reason.into()]),
704 },
705 );
706 }
707 }
708}
709pub fn add_change(
710 state: &mut State,
711 file: Option<String>,
712 before: Option<String>,
713 after: Option<String>,
714 reason: String,
715 known_flows: BTreeSet<String>,
716) {
717 let id = format!(
719 "c_{}",
720 &digest(&(
721 "supercov-change-id-v2",
722 &state.changes,
723 &file,
724 &before,
725 &after,
726 &reason
727 ))[..24]
728 );
729 state.changes.push(Change {
730 id,
731 file,
732 before,
733 after,
734 reason,
735 known_flows,
736 });
737}
738
739fn unique_occurrence(text: &str, snippet: &str) -> Option<usize> {
740 if snippet.is_empty() {
741 return None;
742 }
743 let first = text.find(snippet)?;
744 let next = first + text[first..].chars().next()?.len_utf8();
746 text[next..]
747 .contains(snippet)
748 .then_some(())
749 .map_or(Some(first), |_| None)
750}
751fn target_file(file: &str, old: &FileManifest, new: &Files) -> Option<String> {
752 if new.contains_key(file) {
753 return Some(file.into());
754 }
755 let hash = old.get(file)?;
756 let mut matches = new.iter().filter(|(_, s)| FileFingerprint::of(s) == *hash);
757 let first = matches.next()?.0;
758 matches.next().is_none().then(|| first.clone())
759}
760pub fn relocate(at: &Anchor, old: &FileManifest, new: &Files) -> Option<Anchor> {
761 let before = old.get(&at.file)?;
762 let target = target_file(&at.file, old, new)?;
763 let after = &new[&target];
764 let mut candidate = at.clone();
765 candidate.file.clone_from(&target);
766 if FileFingerprint::of(after) == *before && candidate.offset(new).is_some() {
767 return Some(candidate);
768 }
769 let position = unique_occurrence(after, &at.text)?;
770 Some(Anchor::new(
771 &target,
772 after,
773 position,
774 position + at.text.len(),
775 ))
776}
777
778pub fn carry(
781 map: &AssertionMap,
782 state: &State,
783 old: &InputManifest,
784 new: &Inputs,
785 evidence_digest: &str,
786 context_changed: bool,
787) -> Result<(AssertionMap, State), String> {
788 if map.schema_version != 2 || old.schema_version != 2 || new.schema_version != 1 {
789 return Err("unsupported map/input schema version".into());
790 }
791 if state.inputs_digest != digest(old) || state.schema_version != 3 {
792 return Err("old map state does not match its run inputs".into());
793 }
794 let new_manifest = new.manifest();
795 let (mut next, mut next_state) = seed_manifest(&new_manifest, evidence_digest);
796 next.assertions.clear();
797 next.retired_assertions = map.retired_assertions.clone();
798 next_state.changes = state
799 .changes
800 .iter()
801 .filter(|c| !change_current(map, c, old))
802 .cloned()
803 .collect();
804 next.change_assessments = map
805 .change_assessments
806 .iter()
807 .filter(|r| next_state.changes.iter().any(|c| c.id == r.id))
808 .cloned()
809 .collect();
810 let mut consumed = BTreeSet::new();
811 let exact = map
812 .assertions
813 .iter()
814 .map(|a| {
815 relocate(&a.at, &old.files, &new.files).filter(|at| {
816 new.assertions.iter().any(|s| &s.at == at)
817 || !old.assertions.iter().any(|s| s.at == a.at)
818 })
819 })
820 .collect::<Vec<_>>();
821 let reserved = exact.iter().flatten().collect::<BTreeSet<_>>();
822 for (index, a) in map.assertions.iter().enumerate() {
823 let candidates = new
826 .assertions
827 .iter()
828 .filter(|s| s.at.file == a.at.file && !reserved.contains(&s.at))
829 .collect::<Vec<_>>();
830 let unmatched = map
831 .assertions
832 .iter()
833 .zip(&exact)
834 .filter(|(other, at)| other.at.file == a.at.file && at.is_none())
835 .count();
836 let replacement = if exact[index].is_none() && unmatched == 1 && candidates.len() == 1 {
837 Some(&candidates[0].at)
838 } else {
839 None
840 };
841 let matched = exact[index]
842 .as_ref()
843 .or(replacement)
844 .filter(|at| !consumed.contains(*at));
845 let Some(at) = matched else {
846 next.retired_assertions.push(Retired {
847 assertion: a.clone(),
848 reason:
849 "assertion removed, changed or ambiguous; reuse its explanation after review"
850 .into(),
851 });
852 continue;
853 };
854 consumed.insert(at.clone());
855 let mut updated = a.clone();
856 updated.at = at.clone();
857 for (prior, f) in a.flows.iter().zip(&mut updated.flows) {
858 let base = generation(a, prior, map, state, old);
859 let mut dirty = BTreeSet::new();
860 if prior
861 .basis
862 .as_deref()
863 .is_some_and(|basis| basis != expected_basis(a, prior, map, state, old))
864 {
865 dirty.insert("inherited claim still needs rechecking".into());
866 }
867 for file in dependencies(a, prior) {
868 if old.files.get(file) != new_manifest.files.get(file)
869 || !old.files.contains_key(file)
870 {
871 dirty.insert(format!("dependency file changed or removed: {file}"));
872 }
873 }
874 if replacement.is_some() {
875 dirty.insert("assertion changed or replaced; confirm identity and meaning".into());
876 }
877 for node in &mut f.nodes {
878 if let Some(at) = relocate(&node.at, &old.files, &new.files) {
879 node.at = at;
880 } else {
881 dirty.insert(format!("node {} changed or ambiguous", node.id));
882 }
883 }
884 for file in f
885 .watch
886 .iter_mut()
887 .chain(f.applies_to.iter_mut().map(|t| &mut t.file))
888 {
889 if let Some(target) = target_file(file, &old.files, &new.files) {
890 *file = target;
891 } else {
892 dirty.insert(format!("dependency file removed: {file}"));
893 }
894 }
895 if context_changed {
896 dirty.insert("run configuration, dependencies or execution context changed".into());
897 }
898 next_state.flows.insert(
899 flow_key(a, f),
900 FlowState {
901 generation: if dirty.is_empty() {
902 base
903 } else {
904 digest(&("supercov-carry-v2", base, &new_manifest, &dirty))
905 },
906 reasons: dirty,
907 },
908 );
909 }
910 next.assertions.push(updated);
911 }
912 let mut ids = map
913 .assertions
914 .iter()
915 .map(|a| a.id.clone())
916 .chain(
917 map.retired_assertions
918 .iter()
919 .map(|r| r.assertion.id.clone()),
920 )
921 .collect::<BTreeSet<_>>();
922 for a in seed(new, evidence_digest).0.assertions {
923 if !consumed.contains(&a.at) {
924 let mut a = a;
925 while !ids.insert(a.id.clone()) {
926 a.id.push('_');
927 }
928 next.assertions.push(a);
929 }
930 }
931 for file in old
932 .files
933 .keys()
934 .chain(new_manifest.files.keys())
935 .collect::<BTreeSet<_>>()
936 {
937 if old.files.get(file) != new_manifest.files.get(file) {
938 let known = map
939 .assertions
940 .iter()
941 .flat_map(|a| {
942 a.flows
943 .iter()
944 .filter(|f| dependencies(a, f).contains(file.as_str()))
945 .map(move |f| flow_key(a, f))
946 })
947 .collect();
948 add_change(
949 &mut next_state,
950 Some(file.clone()),
951 old.files.get(file).map(|f| f.sha256.clone()),
952 new_manifest.files.get(file).map(|f| f.sha256.clone()),
953 "captured source file changed".into(),
954 known,
955 );
956 }
957 }
958 next.assertions.sort_by(|a, b| a.at.cmp(&b.at));
959 Ok((next, next_state))
960}
961
962#[path = "assertion_legacy.rs"]
963mod legacy;
964pub fn parse_stored(bytes: &[u8]) -> Result<AssertionMap, String> {
965 let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
966 match value
967 .get("schemaVersion")
968 .and_then(serde_json::Value::as_u64)
969 {
970 None | Some(1) => legacy::import(bytes),
971 _ => parse(bytes).map_err(|e| e.to_string()),
972 }
973}
974pub fn parse_state(
975 bytes: &[u8],
976 map: &AssertionMap,
977 inputs: &InputManifest,
978 evidence: &str,
979 legacy_digest: Option<&str>,
980) -> Result<State, String> {
981 let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
982 if value["schemaVersion"] == 3 {
983 let state: State = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
984 if state.inputs_digest != digest(inputs) || state.evidence_digest != evidence {
985 return Err("Assertion state belongs to different run evidence; rerun tests".into());
986 }
987 Ok(state)
988 } else {
989 legacy::state(bytes, map, inputs, evidence, legacy_digest)
990 }
991}