qualia_core_db/inference/runtime/receipt/
source.rs1use std::collections::BTreeSet;
2use std::io::Read;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5
6use sha2::{Digest, Sha256};
7
8use super::sha256_file;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct SourceProvenance {
12 pub commit: String,
13 pub dirty_source_hash: String,
14 pub executable_sha256: String,
15}
16
17pub fn capture_source_provenance() -> SourceProvenance {
19 let executable_sha256 = std::env::current_exe()
20 .ok()
21 .and_then(|path| sha256_file(&path).ok())
22 .unwrap_or_else(|| "unknown".into());
23 let root = git_stdout(&["rev-parse", "--show-toplevel"])
24 .and_then(|bytes| String::from_utf8(bytes).ok())
25 .map(|text| PathBuf::from(text.trim()))
26 .filter(|path| path.is_dir());
27 let commit = git_stdout(&["rev-parse", "HEAD"])
28 .and_then(|bytes| String::from_utf8(bytes).ok())
29 .map(|text| text.trim().to_string())
30 .filter(|text| !text.is_empty())
31 .unwrap_or_else(|| "unknown".into());
32 let dirty_source_hash = root
33 .as_deref()
34 .and_then(hash_relevant_dirty_sources)
35 .unwrap_or_else(|| "unknown".into());
36 SourceProvenance {
37 commit,
38 dirty_source_hash,
39 executable_sha256,
40 }
41}
42
43fn git_stdout(args: &[&str]) -> Option<Vec<u8>> {
44 let output = Command::new("git").args(args).output().ok()?;
45 output.status.success().then_some(output.stdout)
46}
47
48fn hash_relevant_dirty_sources(root: &Path) -> Option<String> {
49 const PATHS: &[&str] = &[
50 "crates/qualia-core-db",
51 "crates/qualia-cli",
52 "Cargo.toml",
53 "Cargo.lock",
54 ];
55 let mut changed = BTreeSet::new();
56 collect_git_paths(
57 root,
58 &[
59 "diff",
60 "--name-only",
61 "-z",
62 "HEAD",
63 "--",
64 PATHS[0],
65 PATHS[1],
66 PATHS[2],
67 PATHS[3],
68 ],
69 &mut changed,
70 )?;
71 collect_git_paths(
72 root,
73 &[
74 "ls-files",
75 "--others",
76 "--exclude-standard",
77 "-z",
78 "--",
79 PATHS[0],
80 PATHS[1],
81 PATHS[2],
82 PATHS[3],
83 ],
84 &mut changed,
85 )?;
86
87 let mut hasher = Sha256::new();
88 if changed.is_empty() {
89 hasher.update(b"clean");
90 }
91 let mut buffer = [0u8; 1024 * 1024];
92 for relative in changed {
93 hasher.update((relative.len() as u64).to_le_bytes());
94 hasher.update(relative.as_bytes());
95 let path = root.join(&relative);
96 match std::fs::File::open(path) {
97 Ok(mut file) => loop {
98 let read = file.read(&mut buffer).ok()?;
99 if read == 0 {
100 break;
101 }
102 hasher.update(&buffer[..read]);
103 },
104 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
105 hasher.update(b"<deleted>");
106 }
107 Err(_) => return None,
108 }
109 }
110 Some(hex::encode(hasher.finalize()))
111}
112
113fn collect_git_paths(root: &Path, args: &[&str], output: &mut BTreeSet<String>) -> Option<()> {
114 let command = Command::new("git")
115 .current_dir(root)
116 .args(args)
117 .output()
118 .ok()?;
119 if !command.status.success() {
120 return None;
121 }
122 for path in command.stdout.split(|byte| *byte == 0) {
123 if path.is_empty() {
124 continue;
125 }
126 let path = String::from_utf8(path.to_vec()).ok()?;
127 output.insert(path.replace('\\', "/"));
128 }
129 Some(())
130}