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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//! Canonical FeltDB State Subsystem Public API Facade
//!
//! This module presents the graduated state model as a unified, product-facing
//! subsystem. Applications should use this facade to access FeltDB's state
//! primitives rather than reimplementing them.
//!
//! Proven Contracts:
//! - Deterministic content-addressed state identifiers
//! - Immutable revisions with explicit ancestry
//! - Durable persistence with restart recovery
//! - Causal topology tracking
//! - Semantic diff computation
//! - Conflict classification
//! - Explicit reconciliation (no automatic merge)
use crate::state_model::{
ConflictClassification, ReconciliationPlan, Relationship, SemanticDiff, StateId,
StateReconciliationResult, StateRevision, StateStore, StateTopology, STATE_MODEL_VERSION,
};
use crate::FeltDb;
use std::sync::Arc;
/// FeltDB State System - canonical state subsystem public API
pub struct FeltDBStateSystem;
impl FeltDBStateSystem {
/// Create a new state store for an application with FeltDB persistence
///
/// Returns a StateStore that provides:
/// - Durable persistence through FeltDB's canonical operation log
/// - Immutable revisions
/// - Deterministic state identifiers
/// - Restart recovery (once implemented)
///
/// Applications MUST provide a FeltDb instance. This ensures all state
/// mutations are persisted through FeltDB's canonical persistence boundary.
///
/// # Arguments
/// * `db` - Arc<FeltDb> instance for durable storage
///
/// # Returns
/// * `Ok(StateStore)` - Successfully initialized store with FeltDB backing
/// * `Err(String)` - If initialization fails
///
/// # Example
/// ```ignore
/// let db = FeltDb::open("./data")?;
/// let store = FeltDBStateSystem::create_store(&Arc::new(db))?;
/// let initial = store.create("docs:1", json_string, "app-authority")?;
/// let same = store.get(&initial.id).expect("retrieved by identity");
/// ```
pub fn create_store(db: &Arc<FeltDb>) -> Result<StateStore, String> {
StateStore::with_feltdb(db.clone())
}
/// Create a volatile (in-memory only) state store for testing
///
/// This store is NOT persisted and will lose all data when dropped.
/// This is test-only and should not be used in production.
///
/// For production, use `create_store(&db)` which requires FeltDB persistence.
pub fn create_test_store() -> StateStore {
StateStore::new_volatile()
}
/// Get the version of the canonical state model
pub fn version() -> u32 {
STATE_MODEL_VERSION
}
/// Documentation: This is the canonical way to access FeltDB's state
/// primitives. Do not reimplement StateId, StateRevision, StateHistory,
/// StateStore, or related primitives.
pub fn documentation() -> &'static str {
r#"
FeltDB State Subsystem - Canonical Primitives
Applications should:
1. Initialize FeltDB: let db = FeltDb::open(path)?;
2. Use FeltDBStateSystem::create_store(&Arc::new(db)) to initialize state
3. Call store.create() for initial state
4. Call store.commit() for transitions
5. Call store.get(&id) to retrieve a revision by identity
(the store does not track which revision is "current" — see
StateStore's own documentation for why that is a separate concern)
6. Use StateTopology to inspect causal relationships
7. Use SemanticDiff to compute changes between states
8. Use ConflictClassification to analyze divergence
9. Use ReconciliationPlan with explicit caller policy
Applications should NOT:
- Reimplement StateId
- Reimplement StateRevision
- Reimplement StateStore
- Compute diffs independently
- Implement their own conflict classification
- Use implicit/automatic merge
- Create StateStore without FeltDB backing (use new_volatile() for testing only)
"#
}
}
// Note: All types are re-exported at lib.rs level for public API
#[cfg(test)]
mod facade_tests {
use super::*;
use crate::{
state_model::StateStore, ConflictClass, ConflictClassification, Relationship, SemanticDiff,
StateTopology,
};
use serde_json::json;
#[test]
fn test_facade_creates_store() {
// For testing, use new_volatile() - production must use create_store(&db)
let store = StateStore::new_volatile();
let initial = store
.create(
"docs:1",
r#"{"data":"test"}"#.to_string(),
"test-auth".to_string(),
)
.expect("Failed to create initial state");
let stored = store
.get(&initial.id)
.expect("the revision is retrievable by identity");
assert_eq!(stored.id, initial.id);
}
#[test]
fn test_facade_version() {
assert_eq!(FeltDBStateSystem::version(), 1);
}
#[test]
fn test_facade_comprehensive_workflow() {
// Initialize - for testing, use new_volatile()
let store = StateStore::new_volatile();
// Create initial state
let initial = store
.create(
"docs:1",
r#"{"users":{"alice":100}}"#.to_string(),
"app-auth".to_string(),
)
.expect("Failed to create");
// Verify the revision is retrievable by identity. The store tracks no
// "current" pointer; the caller holds the ids it cares about.
assert_eq!(store.get(&initial.id).unwrap().id, initial.id);
// Divergence 1: alice updates
let branch1 = store
.commit(
r#"{"users":{"alice":150}}"#.to_string(),
&initial,
"alice-auth".to_string(),
)
.expect("Failed branch 1");
// Divergence 2: from the same parent
let branch2 = store
.commit(
r#"{"users":{"alice":100,"bob":50}}"#.to_string(),
&initial,
"bob-auth".to_string(),
)
.expect("Failed branch 2");
// Inspect topology
let mut topology = StateTopology::new();
topology.add_revision(initial.clone());
topology.add_revision(branch1.clone());
topology.add_revision(branch2.clone());
// Verify relationships
match topology.relationship(&branch1.id, &branch2.id) {
Relationship::Diverged => {
// Expected: both descended from initial but different
}
_ => panic!("Expected Diverged relationship"),
}
// Compute diff using JSON values
let initial_json: serde_json::Value =
serde_json::from_str(r#"{"users":{"alice":100}}"#).unwrap();
let branch1_json: serde_json::Value =
serde_json::from_str(r#"{"users":{"alice":150}}"#).unwrap();
let diff = SemanticDiff::compute(&initial_json, &branch1_json);
assert!(!diff.changes.is_empty());
// Classify conflict
let classification = ConflictClassification::classify(&initial, &branch1, &branch2);
assert_eq!(classification.overall, ConflictClass::Independent);
}
#[test]
fn test_facade_immutability() {
let store = StateStore::new_volatile();
let initial = store
.create("docs:1", r#"{"v":1}"#.to_string(), "auth".to_string())
.unwrap();
let initial_id = initial.id.clone();
// Create another state
let second = store
.commit(r#"{"v":2}"#.to_string(), &initial, "auth".to_string())
.unwrap();
// Verify first state is unchanged
assert_eq!(store.get(&initial_id).unwrap().content, r#"{"v":1}"#);
assert_eq!(initial_id, initial.id);
}
#[test]
fn test_facade_restart_recovery() {
let store1 = StateStore::new_volatile();
let initial = store1
.create(
"docs:1",
r#"{"data":"test"}"#.to_string(),
"auth".to_string(),
)
.unwrap();
// Simulate restart: new store instance
let _store2 = StateStore::new_volatile();
// Note: In real scenario, store would load from persistent storage
// Here we demonstrate the API contract: states retrieved by id are valid
assert!(store1.exists(&initial.id));
}
#[test]
fn test_facade_authority_neutrality() {
let store = StateStore::new_volatile();
let initial = store
.create(
"docs:1",
r#"{"balance":100}"#.to_string(),
"alice".to_string(),
)
.unwrap();
let update1 = store
.commit(
r#"{"balance":150}"#.to_string(),
&initial,
"alice".to_string(),
)
.unwrap();
let update2 = store
.commit(
r#"{"balance":150}"#.to_string(),
&initial,
"bob".to_string(),
)
.unwrap();
// The same state, from the same parent, is the same historical fact —
// so it is one revision, whoever committed it. Authority is recorded
// but takes no part in identity.
assert_eq!(update1.id, update2.id);
assert_eq!(update1.content_id, update2.content_id);
// And because authority takes no part in identity, the second commit
// is a no-op that returns what was already recorded. The authority on a
// revision is whoever first committed that historical fact, not
// whoever last asked for it.
assert_eq!(update1.authority, "alice");
assert_eq!(update2.authority, "alice");
}
#[test]
fn test_facade_read_only_operations() {
let store = StateStore::new_volatile();
let initial = store
.create("docs:1", r#"{"v":1}"#.to_string(), "auth".to_string())
.unwrap();
let update = store
.commit(r#"{"v":2}"#.to_string(), &initial, "auth".to_string())
.unwrap();
// Topology operations should not mutate
let mut topology = StateTopology::new();
topology.add_revision(initial.clone());
topology.add_revision(update.clone());
let rel = topology.relationship(&initial.id, &update.id);
assert!(matches!(rel, Relationship::Ancestor));
// Verify both states still exist unchanged
assert_eq!(store.get(&initial.id).unwrap().id, initial.id);
assert_eq!(store.get(&update.id).unwrap().id, update.id);
}
#[test]
fn test_facade_no_git_dependency() {
// This test verifies we can use the state system without any .git access
let store = StateStore::new_volatile();
let state = store
.create(
"docs:1",
r#"{"test":"no-git"}"#.to_string(),
"auth".to_string(),
)
.expect("State creation should work without .git");
// Topology and diff operations should work without git
let mut topology = StateTopology::new();
topology.add_revision(state.clone());
assert!(topology.is_ancestor(&state.id, &state.id));
}
}