1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! Epoch: Frozen input state for reproducibility
//!
//! An epoch represents a frozen point-in-time snapshot of all input ontologies.
//! This is the "O" in A = μ(O) - the immutable input substrate.
use crate::utils::error::{Error, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// SHA-256 hash identifying an epoch
pub type EpochId = String;
/// A frozen input epoch containing all ontology hashes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Epoch {
/// SHA-256 hash of all input hashes (the epoch ID)
pub id: EpochId,
/// When this epoch was created (ISO 8601)
pub timestamp: String,
/// All ontology inputs with their hashes
pub inputs: BTreeMap<PathBuf, OntologyInput>,
/// Total triple count across all inputs
pub total_triples: usize,
}
/// A single ontology input file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OntologyInput {
/// Relative path from project root
pub path: PathBuf,
/// SHA-256 hash of file contents
pub hash: String,
/// File size in bytes
pub size_bytes: usize,
/// Number of RDF triples
pub triple_count: usize,
}
impl Epoch {
/// Create a new epoch from a set of ontology files
///
/// # Arguments
/// * `base_path` - Base directory for resolving paths
/// * `ontology_paths` - Paths to ontology files
///
/// # Returns
/// * `Ok(Epoch)` - Frozen epoch with all hashes computed
/// * `Err(Error)` - If any file cannot be read
pub fn create(base_path: &Path, ontology_paths: &[PathBuf]) -> Result<Self> {
let timestamp = chrono::Utc::now().to_rfc3339();
let mut inputs = BTreeMap::new();
let mut total_triples = 0;
// Process each ontology file
for rel_path in ontology_paths {
let full_path = base_path.join(rel_path);
let input = OntologyInput::from_file(&full_path, rel_path)?;
total_triples += input.triple_count;
inputs.insert(rel_path.clone(), input);
}
// Compute epoch ID from all input hashes
let id = Self::compute_epoch_id(&inputs);
Ok(Self {
id,
timestamp,
inputs,
total_triples,
})
}
/// Epoch when inputs come only from merged pack ontologies (no project TTL files).
///
/// `content_digest` should be a deterministic hash of the merged graph serialization
/// (e.g. SHA-256 hex of canonical Turtle).
pub fn from_pack_merged_substrate(content_digest: String, triple_count: usize) -> Self {
let timestamp = chrono::Utc::now().to_rfc3339();
let mut inputs = BTreeMap::new();
let pseudo = PathBuf::from(".ggen/pack-merged-substrate.ttl");
inputs.insert(
pseudo.clone(),
OntologyInput {
path: pseudo,
hash: content_digest,
size_bytes: 0,
triple_count,
},
);
let id = Self::compute_epoch_id(&inputs);
Self {
id,
timestamp,
inputs,
total_triples: triple_count,
}
}
/// Compute the epoch ID by hashing all input hashes
fn compute_epoch_id(inputs: &BTreeMap<PathBuf, OntologyInput>) -> EpochId {
let mut hasher = Sha256::new();
// Hash inputs in deterministic order (BTreeMap guarantees this)
for (path, input) in inputs {
hasher.update(path.to_string_lossy().as_bytes());
hasher.update(b":");
hasher.update(input.hash.as_bytes());
hasher.update(b"\n");
}
format!("{:x}", hasher.finalize())
}
/// Verify that all input files still match their recorded hashes
///
/// # Arguments
/// * `base_path` - Base directory for resolving paths
///
/// # Returns
/// * `Ok(true)` - All files match
/// * `Ok(false)` - At least one file has changed
/// * `Err(Error)` - If a file cannot be read
pub fn verify(&self, base_path: &Path) -> Result<bool> {
for (rel_path, input) in &self.inputs {
let full_path = base_path.join(rel_path);
let current_hash = Self::hash_file(&full_path)?;
if current_hash != input.hash {
return Ok(false);
}
}
Ok(true)
}
/// Get list of changed files since epoch was created
pub fn get_changed_files(&self, base_path: &Path) -> Result<Vec<PathBuf>> {
let mut changed = Vec::new();
for (rel_path, input) in &self.inputs {
let full_path = base_path.join(rel_path);
let current_hash = Self::hash_file(&full_path)?;
if current_hash != input.hash {
changed.push(rel_path.clone());
}
}
Ok(changed)
}
/// Compute SHA-256 hash of a file
fn hash_file(path: &Path) -> Result<String> {
let content = std::fs::read(path)
.map_err(|e| Error::new(&format!("Failed to read file '{}': {}", path.display(), e)))?;
let hash = Sha256::digest(&content);
Ok(format!("{:x}", hash))
}
}
impl OntologyInput {
/// Create an ontology input from a file
///
/// # Arguments
/// * `full_path` - Full path to the file
/// * `rel_path` - Relative path for storage
pub fn from_file(full_path: &Path, rel_path: &Path) -> Result<Self> {
let content = std::fs::read(full_path).map_err(|e| {
Error::new(&format!(
"Failed to read ontology '{}': {}",
full_path.display(),
e
))
})?;
let hash = format!("{:x}", Sha256::digest(&content));
let size_bytes = content.len();
// Count triples (approximate by counting lines starting with valid RDF patterns)
let content_str = String::from_utf8_lossy(&content);
let triple_count = Self::estimate_triple_count(&content_str);
Ok(Self {
path: rel_path.to_path_buf(),
hash,
size_bytes,
triple_count,
})
}
/// Estimate triple count from Turtle content
fn estimate_triple_count(content: &str) -> usize {
// Simple heuristic: count statements (lines ending with . or ;)
// This is approximate but sufficient for auditing
content
.lines()
.filter(|line| {
let trimmed = line.trim();
!trimmed.is_empty()
&& !trimmed.starts_with('#')
&& !trimmed.starts_with("@prefix")
&& (trimmed.ends_with('.') || trimmed.ends_with(';'))
})
.count()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::TempDir;
#[test]
fn test_epoch_creation() {
let temp_dir = TempDir::new().unwrap();
let ontology_path = temp_dir.path().join("test.ttl");
let mut file = std::fs::File::create(&ontology_path).unwrap();
writeln!(
file,
r#"
@prefix ex: <http://example.org/> .
ex:alice a ex:Person .
ex:bob a ex:Person .
"#
)
.unwrap();
let epoch = Epoch::create(temp_dir.path(), &[PathBuf::from("test.ttl")]).unwrap();
assert!(!epoch.id.is_empty());
assert_eq!(epoch.id.len(), 64); // SHA-256 hex length
assert_eq!(epoch.inputs.len(), 1);
assert!(epoch.total_triples > 0);
}
#[test]
fn test_epoch_verify() {
let temp_dir = TempDir::new().unwrap();
let ontology_path = temp_dir.path().join("test.ttl");
// Create initial file
std::fs::write(&ontology_path, "ex:alice a ex:Person .").unwrap();
let epoch = Epoch::create(temp_dir.path(), &[PathBuf::from("test.ttl")]).unwrap();
// Should verify true when unchanged
assert!(epoch.verify(temp_dir.path()).unwrap());
// Modify file
std::fs::write(&ontology_path, "ex:bob a ex:Person .").unwrap();
// Should verify false when changed
assert!(!epoch.verify(temp_dir.path()).unwrap());
}
#[test]
fn test_epoch_id_deterministic() {
let temp_dir = TempDir::new().unwrap();
let ontology_path = temp_dir.path().join("test.ttl");
std::fs::write(&ontology_path, "ex:alice a ex:Person .").unwrap();
let epoch1 = Epoch::create(temp_dir.path(), &[PathBuf::from("test.ttl")]).unwrap();
let epoch2 = Epoch::create(temp_dir.path(), &[PathBuf::from("test.ttl")]).unwrap();
// Same content should produce same epoch ID (ignoring timestamp)
assert_eq!(epoch1.id, epoch2.id);
}
}