@feltdb/core 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/cli/commands.js +19 -21
  2. package/dist/cli/development-session.js +16 -0
  3. package/dist/cli/studio-artifact.js +33 -0
  4. package/dist/create/package-versions.js +1 -1
  5. package/dist/create/server-source/crates/feltdb/src/acceptance_tests.rs +8 -1
  6. package/dist/create/server-source/crates/feltdb/src/application.rs +16 -0
  7. package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +21 -22
  8. package/dist/create/server-source/crates/feltdb/src/lib.rs +451 -33
  9. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +48 -3
  10. package/dist/create/server-source/crates/feltdb/src/state_model.rs +569 -4
  11. package/dist/create/server-source/crates/feltdb/src/state_trigger.rs +1 -0
  12. package/dist/create/server-source/crates/feltdb/src/versioned_object_substrate.rs +708 -0
  13. package/dist/create/server-source/crates/feltdb/src/worker_mesh.rs +1 -0
  14. package/dist/create/server-source/crates/feltdb/src/workload.rs +480 -44
  15. package/dist/create/server-source/crates/feltdb/tests/generalized_version_control_evidence.rs +123 -0
  16. package/dist/create/server-source/crates/feltdb/tests/generalized_version_control_substrate_completion.rs +281 -0
  17. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +15 -3
  18. package/dist/create/server-source/crates/feltdb/tests/revision_retention_boundary_evidence.rs +28 -18
  19. package/dist/create/server-source/crates/feltdb/tests/storage_independent_versioned_object_substrate.rs +328 -0
  20. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +20 -3
  21. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +14 -4
  22. package/dist/create/server-source/crates/feltdb-server/src/backup.rs +0 -4
  23. package/dist/create/server-source/crates/feltdb-server/src/canonical_principals.rs +1093 -0
  24. package/dist/create/server-source/crates/feltdb-server/src/causal.rs +905 -144
  25. package/dist/create/server-source/crates/feltdb-server/src/connections.rs +9 -6
  26. package/dist/create/server-source/crates/feltdb-server/src/control_plane.rs +90 -0
  27. package/dist/create/server-source/crates/feltdb-server/src/lib.rs +1 -0
  28. package/dist/create/server-source/crates/feltdb-server/src/main.rs +408 -74
  29. package/dist/create/server-source/crates/feltdb-server/src/principals.rs +9 -501
  30. package/dist/create/server-source/crates/feltdb-server/src/tenancy.rs +22 -0
  31. package/dist/create/server-source/crates/feltdb-server/tests/principal_tenant_migration.rs +247 -0
  32. package/dist/db.d.ts +6 -5
  33. package/dist/db.d.ts.map +1 -1
  34. package/dist/db.js +18 -24
  35. package/dist/deployment.d.ts.map +1 -1
  36. package/dist/deployment.js +4 -2
  37. package/dist/embedded-transaction.d.ts.map +1 -1
  38. package/dist/embedded-transaction.js +4 -0
  39. package/dist/error-codes.d.ts +12 -0
  40. package/dist/error-codes.d.ts.map +1 -1
  41. package/dist/error-codes.js +20 -2
  42. package/dist/feltdb.d.ts +4 -0
  43. package/dist/feltdb.d.ts.map +1 -1
  44. package/dist/file-db.d.ts +10 -0
  45. package/dist/file-db.d.ts.map +1 -1
  46. package/dist/file-db.js +18 -0
  47. package/dist/http-db.d.ts +4 -0
  48. package/dist/http-db.d.ts.map +1 -1
  49. package/dist/http-db.js +73 -12
  50. package/dist/index-core.d.ts +1 -0
  51. package/dist/index-core.d.ts.map +1 -1
  52. package/dist/index-core.js +1 -0
  53. package/dist/public-contract.d.ts +112 -0
  54. package/dist/public-contract.d.ts.map +1 -0
  55. package/dist/public-contract.js +125 -0
  56. package/dist/studio/app.d.ts +23 -0
  57. package/dist/studio/app.d.ts.map +1 -1
  58. package/dist/studio/components/ContractInspector.d.ts +5 -0
  59. package/dist/studio/components/ContractInspector.d.ts.map +1 -1
  60. package/dist/studio/components/SettingsPanel.d.ts +4 -1
  61. package/dist/studio/components/SettingsPanel.d.ts.map +1 -1
  62. package/dist/studio/components/index.js +4 -4
  63. package/dist/studio/{components-CehkcX_k.js → components-CJFgdKG6.js} +322 -303
  64. package/dist/studio/control-plane/Data.d.ts.map +1 -1
  65. package/dist/studio/control-plane/Instance.d.ts +10 -0
  66. package/dist/studio/control-plane/Instance.d.ts.map +1 -1
  67. package/dist/studio/control-plane/Operations.d.ts +3 -0
  68. package/dist/studio/control-plane/Operations.d.ts.map +1 -1
  69. package/dist/studio/control-plane/State.d.ts.map +1 -1
  70. package/dist/studio/control-plane/index.d.ts +4 -2
  71. package/dist/studio/control-plane/index.d.ts.map +1 -1
  72. package/dist/studio/control-plane/index.js +2 -2
  73. package/dist/studio/control-plane-DP8ljTDO.js +3207 -0
  74. package/dist/studio/index.js +96 -75
  75. package/dist/studio/utils/api.d.ts +1 -1
  76. package/dist/studio/utils/api.d.ts.map +1 -1
  77. package/dist/studio/utils/control-plane-api.d.ts +12 -1
  78. package/dist/studio/utils/control-plane-api.d.ts.map +1 -1
  79. package/dist/studio/utils/control-plane-api.js +1 -1
  80. package/dist/studio/utils/index.js +16 -16
  81. package/dist/studio/utils/service-api.d.ts +8 -0
  82. package/dist/studio/utils/service-api.d.ts.map +1 -1
  83. package/dist/studio/utils/service-api.js +15 -12
  84. package/dist/studio-app/assets/{feltdb_wasm-DksXDnLa.js → feltdb_wasm-CfNb3IoF.js} +1 -1
  85. package/dist/studio-app/assets/feltdb_wasm_bg-D9d3gY-E.wasm +0 -0
  86. package/dist/studio-app/assets/index-SDXdROi1.js +30 -0
  87. package/dist/studio-app/feltdb-studio.json +6 -0
  88. package/dist/studio-app/index.html +1 -1
  89. package/dist/transaction.d.ts +9 -1
  90. package/dist/transaction.d.ts.map +1 -1
  91. package/dist/transaction.js +6 -2
  92. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  93. package/dist/workspace/local-development-authority.d.ts +8 -0
  94. package/dist/workspace/local-development-authority.d.ts.map +1 -1
  95. package/dist/workspace/local-development-authority.js +136 -1
  96. package/package.json +2 -2
  97. package/dist/studio/control-plane-D6TT2fCQ.js +0 -3064
  98. package/dist/studio-app/assets/feltdb_wasm_bg-Yy4QRHJT.wasm +0 -0
  99. package/dist/studio-app/assets/index-CZ55nLgp.js +0 -30
@@ -0,0 +1,708 @@
1
+ use crate::{
2
+ reconcile, resolve_path, ConflictClassification, MaterializationProjection, PathComponent, StateId,
3
+ StateRevision,
4
+ };
5
+ use serde::{Deserialize, Serialize};
6
+ use serde_json::Value;
7
+ use std::collections::{BTreeSet, HashMap};
8
+ use std::fs;
9
+ use std::path::{Path, PathBuf};
10
+ use std::sync::{Arc, Mutex};
11
+
12
+ pub trait DurableObjectStore: Send + Sync + Clone + 'static {
13
+ fn put_if_absent(&self, key: &str, value: &[u8]) -> Result<(), String>;
14
+ fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String>;
15
+ fn delete(&self, key: &str) -> Result<bool, String>;
16
+ fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, String>;
17
+ fn compare_and_swap(
18
+ &self,
19
+ key: &str,
20
+ expected: Option<&[u8]>,
21
+ replacement: &[u8],
22
+ ) -> Result<bool, String>;
23
+ }
24
+
25
+ #[derive(Clone)]
26
+ pub struct LocalObjectStore {
27
+ root: Arc<PathBuf>,
28
+ lock: Arc<Mutex<()>>,
29
+ }
30
+
31
+ impl LocalObjectStore {
32
+ pub fn new(root: impl AsRef<Path>) -> Result<Self, String> {
33
+ let root = root.as_ref().to_path_buf();
34
+ fs::create_dir_all(&root).map_err(|e| e.to_string())?;
35
+ Ok(Self {
36
+ root: Arc::new(root),
37
+ lock: Arc::new(Mutex::new(())),
38
+ })
39
+ }
40
+
41
+ fn path_for(&self, key: &str) -> PathBuf {
42
+ self.root.join(encode_key(key))
43
+ }
44
+ }
45
+
46
+ impl DurableObjectStore for LocalObjectStore {
47
+ fn put_if_absent(&self, key: &str, value: &[u8]) -> Result<(), String> {
48
+ let _guard = self.lock.lock().unwrap();
49
+ let path = self.path_for(key);
50
+ if path.exists() {
51
+ return Ok(());
52
+ }
53
+ let tmp = self
54
+ .root
55
+ .join(format!(".tmp-{}-{}", std::process::id(), encode_key(key)));
56
+ fs::write(&tmp, value).map_err(|e| e.to_string())?;
57
+ match fs::rename(&tmp, &path) {
58
+ Ok(()) => Ok(()),
59
+ Err(_) if path.exists() => {
60
+ let _ = fs::remove_file(&tmp);
61
+ Ok(())
62
+ }
63
+ Err(e) => Err(e.to_string()),
64
+ }
65
+ }
66
+
67
+ fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String> {
68
+ let path = self.path_for(key);
69
+ match fs::read(path) {
70
+ Ok(bytes) => Ok(Some(bytes)),
71
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
72
+ Err(e) => Err(e.to_string()),
73
+ }
74
+ }
75
+
76
+ fn delete(&self, key: &str) -> Result<bool, String> {
77
+ let _guard = self.lock.lock().unwrap();
78
+ let path = self.path_for(key);
79
+ match fs::remove_file(path) {
80
+ Ok(()) => Ok(true),
81
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
82
+ Err(e) => Err(e.to_string()),
83
+ }
84
+ }
85
+
86
+ fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, String> {
87
+ let entries = fs::read_dir(&*self.root).map_err(|e| e.to_string())?;
88
+ let mut keys = Vec::new();
89
+ for entry in entries {
90
+ let entry = entry.map_err(|e| e.to_string())?;
91
+ let Some(name) = entry.file_name().to_str().map(|v| v.to_string()) else {
92
+ continue;
93
+ };
94
+ let key = decode_key(&name);
95
+ if key.starts_with(prefix) {
96
+ keys.push(key);
97
+ }
98
+ }
99
+ keys.sort();
100
+ Ok(keys)
101
+ }
102
+
103
+ fn compare_and_swap(
104
+ &self,
105
+ key: &str,
106
+ expected: Option<&[u8]>,
107
+ replacement: &[u8],
108
+ ) -> Result<bool, String> {
109
+ let _guard = self.lock.lock().unwrap();
110
+ let path = self.path_for(key);
111
+ let current = match fs::read(&path) {
112
+ Ok(bytes) => Some(bytes),
113
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
114
+ Err(e) => return Err(e.to_string()),
115
+ };
116
+
117
+ let expected_matches = match (expected, current.as_deref()) {
118
+ (None, None) => true,
119
+ (Some(expected), Some(current)) => expected == current,
120
+ _ => false,
121
+ };
122
+ if !expected_matches {
123
+ return Ok(false);
124
+ }
125
+
126
+ let tmp = self
127
+ .root
128
+ .join(format!(".tmp-cas-{}-{}", std::process::id(), encode_key(key)));
129
+ fs::write(&tmp, replacement).map_err(|e| e.to_string())?;
130
+ fs::rename(tmp, path).map_err(|e| e.to_string())?;
131
+ Ok(true)
132
+ }
133
+ }
134
+
135
+ #[derive(Clone, Default)]
136
+ pub struct S3CompatibleBucket {
137
+ inner: Arc<Mutex<HashMap<String, Vec<u8>>>>,
138
+ }
139
+
140
+ #[derive(Clone)]
141
+ pub struct S3CompatibleObjectStore {
142
+ bucket: S3CompatibleBucket,
143
+ }
144
+
145
+ impl S3CompatibleObjectStore {
146
+ pub fn new(bucket: S3CompatibleBucket) -> Self {
147
+ Self { bucket }
148
+ }
149
+ }
150
+
151
+ impl DurableObjectStore for S3CompatibleObjectStore {
152
+ fn put_if_absent(&self, key: &str, value: &[u8]) -> Result<(), String> {
153
+ self.bucket
154
+ .inner
155
+ .lock()
156
+ .unwrap()
157
+ .entry(key.to_string())
158
+ .or_insert_with(|| value.to_vec());
159
+ Ok(())
160
+ }
161
+
162
+ fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String> {
163
+ Ok(self.bucket.inner.lock().unwrap().get(key).cloned())
164
+ }
165
+
166
+ fn delete(&self, key: &str) -> Result<bool, String> {
167
+ Ok(self.bucket.inner.lock().unwrap().remove(key).is_some())
168
+ }
169
+
170
+ fn list_prefix(&self, prefix: &str) -> Result<Vec<String>, String> {
171
+ let mut keys = self
172
+ .bucket
173
+ .inner
174
+ .lock()
175
+ .unwrap()
176
+ .keys()
177
+ .filter(|k| k.starts_with(prefix))
178
+ .cloned()
179
+ .collect::<Vec<_>>();
180
+ keys.sort();
181
+ Ok(keys)
182
+ }
183
+
184
+ fn compare_and_swap(
185
+ &self,
186
+ key: &str,
187
+ expected: Option<&[u8]>,
188
+ replacement: &[u8],
189
+ ) -> Result<bool, String> {
190
+ let mut guard = self.bucket.inner.lock().unwrap();
191
+ let current = guard.get(key).map(|bytes| bytes.as_slice());
192
+ let expected_matches = match (expected, current) {
193
+ (None, None) => true,
194
+ (Some(expected), Some(current)) => expected == current,
195
+ _ => false,
196
+ };
197
+ if !expected_matches {
198
+ return Ok(false);
199
+ }
200
+ guard.insert(key.to_string(), replacement.to_vec());
201
+ Ok(true)
202
+ }
203
+ }
204
+
205
+ #[derive(Clone, Debug, Serialize, Deserialize)]
206
+ pub struct DurableRef {
207
+ pub namespace: String,
208
+ pub name: String,
209
+ pub target: StateId,
210
+ pub version: u64,
211
+ pub authority: String,
212
+ }
213
+
214
+ #[derive(Clone)]
215
+ pub struct VersionedObjectSubstrate<S: DurableObjectStore> {
216
+ store: S,
217
+ cache: Arc<Mutex<HashMap<String, Vec<u8>>>>,
218
+ }
219
+
220
+ #[derive(Clone, Debug, Serialize, Deserialize)]
221
+ struct RevisionRecord {
222
+ revision: StateRevision,
223
+ }
224
+
225
+ #[derive(Clone, Debug, PartialEq, Eq)]
226
+ pub enum SubstrateError {
227
+ NotFound(String),
228
+ Conflict(String),
229
+ Storage(String),
230
+ Invalid(String),
231
+ }
232
+
233
+ impl std::fmt::Display for SubstrateError {
234
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235
+ match self {
236
+ SubstrateError::NotFound(v) => write!(f, "{v}"),
237
+ SubstrateError::Conflict(v) => write!(f, "{v}"),
238
+ SubstrateError::Storage(v) => write!(f, "{v}"),
239
+ SubstrateError::Invalid(v) => write!(f, "{v}"),
240
+ }
241
+ }
242
+ }
243
+
244
+ impl std::error::Error for SubstrateError {}
245
+
246
+ #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
247
+ pub struct Reachability {
248
+ pub revisions: Vec<StateId>,
249
+ pub objects: Vec<StateId>,
250
+ }
251
+
252
+ impl<S: DurableObjectStore> VersionedObjectSubstrate<S> {
253
+ pub fn new(store: S) -> Self {
254
+ Self {
255
+ store,
256
+ cache: Arc::new(Mutex::new(HashMap::new())),
257
+ }
258
+ }
259
+
260
+ pub fn clear_cache(&self) {
261
+ self.cache.lock().unwrap().clear();
262
+ }
263
+
264
+ pub fn store_object(&self, content: &str) -> Result<StateId, SubstrateError> {
265
+ let id = StateId::compute(content);
266
+ let key = object_key(&id);
267
+ self.store
268
+ .put_if_absent(&key, content.as_bytes())
269
+ .map_err(SubstrateError::Storage)?;
270
+ self.cache
271
+ .lock()
272
+ .unwrap()
273
+ .insert(key, content.as_bytes().to_vec());
274
+ Ok(id)
275
+ }
276
+
277
+ pub fn get_object(&self, id: &StateId) -> Result<String, SubstrateError> {
278
+ let key = object_key(id);
279
+ // durable backend is authoritative; cache is advisory only
280
+ let Some(bytes) = self.store.get(&key).map_err(SubstrateError::Storage)? else {
281
+ self.cache.lock().unwrap().remove(&key);
282
+ return Err(SubstrateError::NotFound(format!("object {} not found", id.as_hex())));
283
+ };
284
+ self.cache.lock().unwrap().insert(key, bytes.clone());
285
+ String::from_utf8(bytes)
286
+ .map_err(|e| SubstrateError::Invalid(format!("object is not utf8: {e}")))
287
+ }
288
+
289
+ pub fn create_revision(
290
+ &self,
291
+ resource: &str,
292
+ content: String,
293
+ parent: Option<StateId>,
294
+ authority: String,
295
+ ) -> Result<StateRevision, SubstrateError> {
296
+ let parent_revision = if let Some(parent_id) = parent {
297
+ Some(self.get_revision(&parent_id)?)
298
+ } else {
299
+ None
300
+ };
301
+ let revision = match parent_revision {
302
+ Some(parent_revision) => {
303
+ if parent_revision.resource != resource {
304
+ return Err(SubstrateError::Invalid(
305
+ "parent belongs to another resource".to_string(),
306
+ ));
307
+ }
308
+ StateRevision::child(content, &parent_revision, authority)
309
+ }
310
+ None => StateRevision::initial(resource.to_string(), content, authority),
311
+ };
312
+ let _ = self.store_object(&revision.content)?;
313
+ self.persist_revision(&revision)?;
314
+ Ok(revision)
315
+ }
316
+
317
+ pub fn get_revision(&self, id: &StateId) -> Result<StateRevision, SubstrateError> {
318
+ let Some(bytes) = self
319
+ .store
320
+ .get(&revision_key(id))
321
+ .map_err(SubstrateError::Storage)?
322
+ else {
323
+ return Err(SubstrateError::NotFound(format!("revision {} not found", id)));
324
+ };
325
+ let record: RevisionRecord =
326
+ serde_json::from_slice(&bytes).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
327
+ let _ = self.get_object(&record.revision.content_id)?;
328
+ Ok(record.revision)
329
+ }
330
+
331
+ pub fn list_revisions(&self) -> Result<Vec<StateRevision>, SubstrateError> {
332
+ let keys = self
333
+ .store
334
+ .list_prefix("revision:")
335
+ .map_err(SubstrateError::Storage)?;
336
+ let mut revisions = keys
337
+ .into_iter()
338
+ .map(|key| {
339
+ self.store
340
+ .get(&key)
341
+ .map_err(SubstrateError::Storage)?
342
+ .ok_or_else(|| SubstrateError::NotFound(format!("missing revision key {key}")))
343
+ .and_then(|bytes| {
344
+ serde_json::from_slice::<RevisionRecord>(&bytes)
345
+ .map(|record| record.revision)
346
+ .map_err(|e| SubstrateError::Invalid(e.to_string()))
347
+ })
348
+ })
349
+ .collect::<Result<Vec<_>, _>>()?;
350
+ revisions.sort_by(|one, two| one.id.as_hex().cmp(two.id.as_hex()));
351
+ Ok(revisions)
352
+ }
353
+
354
+ pub fn create_ref(
355
+ &self,
356
+ namespace: &str,
357
+ name: &str,
358
+ target: StateId,
359
+ authority: String,
360
+ ) -> Result<DurableRef, SubstrateError> {
361
+ let _ = self.get_revision(&target)?;
362
+ let reference = DurableRef {
363
+ namespace: namespace.to_string(),
364
+ name: name.to_string(),
365
+ target,
366
+ version: 1,
367
+ authority,
368
+ };
369
+ let bytes = serde_json::to_vec(&reference)
370
+ .map_err(|e| SubstrateError::Invalid(e.to_string()))?;
371
+ let inserted = self
372
+ .store
373
+ .compare_and_swap(&ref_key(namespace, name), None, &bytes)
374
+ .map_err(SubstrateError::Storage)?;
375
+ if !inserted {
376
+ return Err(SubstrateError::Conflict("ref already exists".to_string()));
377
+ }
378
+ Ok(reference)
379
+ }
380
+
381
+ pub fn get_ref(&self, namespace: &str, name: &str) -> Result<Option<DurableRef>, SubstrateError> {
382
+ let Some(bytes) = self
383
+ .store
384
+ .get(&ref_key(namespace, name))
385
+ .map_err(SubstrateError::Storage)?
386
+ else {
387
+ return Ok(None);
388
+ };
389
+ let reference =
390
+ serde_json::from_slice(&bytes).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
391
+ Ok(Some(reference))
392
+ }
393
+
394
+ pub fn cas_move_ref(
395
+ &self,
396
+ namespace: &str,
397
+ name: &str,
398
+ expected_version: u64,
399
+ target: StateId,
400
+ authority: String,
401
+ ) -> Result<DurableRef, SubstrateError> {
402
+ let _ = self.get_revision(&target)?;
403
+ let Some(current) = self.get_ref(namespace, name)? else {
404
+ return Err(SubstrateError::NotFound("ref not found".to_string()));
405
+ };
406
+ if current.version != expected_version {
407
+ return Err(SubstrateError::Conflict(format!(
408
+ "stale version {}, current {}",
409
+ expected_version, current.version
410
+ )));
411
+ }
412
+
413
+ let next = DurableRef {
414
+ version: current.version + 1,
415
+ target,
416
+ authority,
417
+ ..current.clone()
418
+ };
419
+ let current_bytes =
420
+ serde_json::to_vec(&current).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
421
+ let next_bytes =
422
+ serde_json::to_vec(&next).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
423
+ let applied = self
424
+ .store
425
+ .compare_and_swap(&ref_key(namespace, name), Some(&current_bytes), &next_bytes)
426
+ .map_err(SubstrateError::Storage)?;
427
+ if !applied {
428
+ return Err(SubstrateError::Conflict("concurrent ref update".to_string()));
429
+ }
430
+ Ok(next)
431
+ }
432
+
433
+ pub fn delete_ref(
434
+ &self,
435
+ namespace: &str,
436
+ name: &str,
437
+ expected_version: Option<u64>,
438
+ ) -> Result<(), SubstrateError> {
439
+ if let Some(expected) = expected_version {
440
+ let Some(reference) = self.get_ref(namespace, name)? else {
441
+ return Err(SubstrateError::NotFound("ref not found".to_string()));
442
+ };
443
+ if reference.version != expected {
444
+ return Err(SubstrateError::Conflict("stale ref delete".to_string()));
445
+ }
446
+ }
447
+ let deleted = self
448
+ .store
449
+ .delete(&ref_key(namespace, name))
450
+ .map_err(SubstrateError::Storage)?;
451
+ if !deleted {
452
+ return Err(SubstrateError::NotFound("ref not found".to_string()));
453
+ }
454
+ Ok(())
455
+ }
456
+
457
+ pub fn list_refs(&self, namespace: Option<&str>) -> Result<Vec<DurableRef>, SubstrateError> {
458
+ let keys = self
459
+ .store
460
+ .list_prefix("ref:")
461
+ .map_err(SubstrateError::Storage)?;
462
+ let mut refs = Vec::new();
463
+ for key in keys {
464
+ let Some(bytes) = self.store.get(&key).map_err(SubstrateError::Storage)? else {
465
+ continue;
466
+ };
467
+ let reference: DurableRef =
468
+ serde_json::from_slice(&bytes).map_err(|e| SubstrateError::Invalid(e.to_string()))?;
469
+ if namespace.is_none_or(|scope| scope == reference.namespace) {
470
+ refs.push(reference);
471
+ }
472
+ }
473
+ refs.sort_by(|one, two| {
474
+ one.namespace
475
+ .cmp(&two.namespace)
476
+ .then_with(|| one.name.cmp(&two.name))
477
+ });
478
+ Ok(refs)
479
+ }
480
+
481
+ pub fn materialize(
482
+ &self,
483
+ revision_id: &StateId,
484
+ projection: &MaterializationProjection,
485
+ ) -> Result<Value, SubstrateError> {
486
+ let revision = self.get_revision(revision_id)?;
487
+ let source: Value = serde_json::from_str(&revision.content)
488
+ .map_err(|e| SubstrateError::Invalid(format!("unparseable json: {e}")))?;
489
+
490
+ if projection.is_full() {
491
+ return Ok(source);
492
+ }
493
+
494
+ let mut paths = projection.paths.clone();
495
+ paths.sort();
496
+ paths.dedup();
497
+ if paths
498
+ .windows(2)
499
+ .any(|pair| path_overlap(&pair[0], &pair[1]))
500
+ {
501
+ return Err(SubstrateError::Invalid(
502
+ "overlapping projection paths".to_string(),
503
+ ));
504
+ }
505
+
506
+ let mut projected = Value::Object(serde_json::Map::new());
507
+ for path in paths {
508
+ let value = resolve_path(&source, &path)
509
+ .cloned()
510
+ .ok_or_else(|| SubstrateError::NotFound(format!("path missing: {path:?}")))?;
511
+ assign_projection(&mut projected, &path, value)?;
512
+ }
513
+ Ok(projected)
514
+ }
515
+
516
+ pub fn conflict_classification(
517
+ &self,
518
+ base: &StateId,
519
+ left: &StateId,
520
+ right: &StateId,
521
+ ) -> Result<ConflictClassification, SubstrateError> {
522
+ let base = self.get_revision(base)?;
523
+ let left = self.get_revision(left)?;
524
+ let right = self.get_revision(right)?;
525
+ Ok(ConflictClassification::classify(&base, &left, &right))
526
+ }
527
+
528
+ pub fn reconcile(
529
+ &self,
530
+ base: &StateId,
531
+ left: &StateId,
532
+ right: &StateId,
533
+ authority: &str,
534
+ ) -> Result<StateRevision, SubstrateError> {
535
+ let base_revision = self.get_revision(base)?;
536
+ let left_revision = self.get_revision(left)?;
537
+ let right_revision = self.get_revision(right)?;
538
+ let plan = crate::ReconciliationPlan::new(
539
+ left_revision.id.clone(),
540
+ right_revision.id.clone(),
541
+ base_revision.id.clone(),
542
+ true,
543
+ );
544
+ let reconciled = reconcile(
545
+ &base_revision,
546
+ &left_revision,
547
+ &right_revision,
548
+ &plan,
549
+ authority.to_string(),
550
+ )
551
+ .map_err(SubstrateError::Invalid)?;
552
+ self.persist_revision(&reconciled.materialized_state)?;
553
+ let _ = self.store_object(&reconciled.materialized_state.content)?;
554
+ Ok(reconciled.materialized_state)
555
+ }
556
+
557
+ pub fn reachability(&self) -> Result<Reachability, SubstrateError> {
558
+ let refs = self.list_refs(None)?;
559
+ let mut revision_ids = BTreeSet::new();
560
+ let mut object_ids = BTreeSet::new();
561
+ let mut stack = refs.into_iter().map(|reference| reference.target).collect::<Vec<_>>();
562
+ while let Some(revision_id) = stack.pop() {
563
+ if !revision_ids.insert(revision_id.clone()) {
564
+ continue;
565
+ }
566
+ let revision = self.get_revision(&revision_id)?;
567
+ object_ids.insert(revision.content_id.clone());
568
+ if let Some(parent) = revision.parent_id {
569
+ stack.push(parent);
570
+ }
571
+ }
572
+ Ok(Reachability {
573
+ revisions: revision_ids.into_iter().collect(),
574
+ objects: object_ids.into_iter().collect(),
575
+ })
576
+ }
577
+
578
+ pub fn collect_unreachable(&self) -> Result<Reachability, SubstrateError> {
579
+ let reachable = self.reachability()?;
580
+ let keep_revisions: BTreeSet<_> = reachable.revisions.iter().cloned().collect();
581
+ let keep_objects: BTreeSet<_> = reachable.objects.iter().cloned().collect();
582
+
583
+ for revision in self.list_revisions()? {
584
+ if !keep_revisions.contains(&revision.id) {
585
+ self.store
586
+ .delete(&revision_key(&revision.id))
587
+ .map_err(SubstrateError::Storage)?;
588
+ }
589
+ }
590
+
591
+ for key in self
592
+ .store
593
+ .list_prefix("object:")
594
+ .map_err(SubstrateError::Storage)?
595
+ {
596
+ if let Some(id_hex) = key.strip_prefix("object:") {
597
+ let id = StateId::from_hex(id_hex.to_string());
598
+ if !keep_objects.contains(&id) {
599
+ self.store.delete(&key).map_err(SubstrateError::Storage)?;
600
+ }
601
+ }
602
+ }
603
+ self.reachability()
604
+ }
605
+
606
+ fn persist_revision(&self, revision: &StateRevision) -> Result<(), SubstrateError> {
607
+ let record = RevisionRecord {
608
+ revision: revision.clone(),
609
+ };
610
+ let bytes = serde_json::to_vec(&record)
611
+ .map_err(|e| SubstrateError::Invalid(format!("serialize revision: {e}")))?;
612
+ self.store
613
+ .put_if_absent(&revision_key(&revision.id), &bytes)
614
+ .map_err(SubstrateError::Storage)
615
+ }
616
+ }
617
+
618
+ fn revision_key(id: &StateId) -> String {
619
+ format!("revision:{}", id.as_hex())
620
+ }
621
+
622
+ fn object_key(id: &StateId) -> String {
623
+ format!("object:{}", id.as_hex())
624
+ }
625
+
626
+ fn ref_key(namespace: &str, name: &str) -> String {
627
+ format!("ref:{}:{}", encode_key(namespace), encode_key(name))
628
+ }
629
+
630
+ fn encode_key(value: &str) -> String {
631
+ value
632
+ .replace('%', "%25")
633
+ .replace(':', "%3A")
634
+ .replace('/', "%2F")
635
+ }
636
+
637
+ fn decode_key(value: &str) -> String {
638
+ value
639
+ .replace("%2F", "/")
640
+ .replace("%3A", ":")
641
+ .replace("%25", "%")
642
+ }
643
+
644
+ fn path_overlap(one: &[PathComponent], two: &[PathComponent]) -> bool {
645
+ one == two
646
+ || (one.len() < two.len() && two.starts_with(one))
647
+ || (two.len() < one.len() && one.starts_with(two))
648
+ }
649
+
650
+ fn assign_projection(state: &mut Value, path: &[PathComponent], value: Value) -> Result<(), SubstrateError> {
651
+ let Some((last, prefix)) = path.split_last() else {
652
+ *state = value;
653
+ return Ok(());
654
+ };
655
+
656
+ let mut current = state;
657
+ for component in prefix {
658
+ match component {
659
+ PathComponent::Key(key) => {
660
+ if current.is_null() {
661
+ *current = Value::Object(serde_json::Map::new());
662
+ }
663
+ let Some(object) = current.as_object_mut() else {
664
+ return Err(SubstrateError::Invalid("projection path type mismatch".to_string()));
665
+ };
666
+ current = object.entry(key.clone()).or_insert(Value::Null);
667
+ }
668
+ PathComponent::Index(index) => {
669
+ if current.is_null() {
670
+ *current = Value::Array(Vec::new());
671
+ }
672
+ let Some(array) = current.as_array_mut() else {
673
+ return Err(SubstrateError::Invalid("projection path type mismatch".to_string()));
674
+ };
675
+ while array.len() <= *index {
676
+ array.push(Value::Null);
677
+ }
678
+ current = &mut array[*index];
679
+ }
680
+ }
681
+ }
682
+
683
+ match last {
684
+ PathComponent::Key(key) => {
685
+ if current.is_null() {
686
+ *current = Value::Object(serde_json::Map::new());
687
+ }
688
+ let Some(object) = current.as_object_mut() else {
689
+ return Err(SubstrateError::Invalid("projection terminal mismatch".to_string()));
690
+ };
691
+ object.insert(key.clone(), value);
692
+ Ok(())
693
+ }
694
+ PathComponent::Index(index) => {
695
+ if current.is_null() {
696
+ *current = Value::Array(Vec::new());
697
+ }
698
+ let Some(array) = current.as_array_mut() else {
699
+ return Err(SubstrateError::Invalid("projection terminal mismatch".to_string()));
700
+ };
701
+ while array.len() <= *index {
702
+ array.push(Value::Null);
703
+ }
704
+ array[*index] = value;
705
+ Ok(())
706
+ }
707
+ }
708
+ }
@@ -883,6 +883,7 @@ mod tests {
883
883
  trigger: "manual".into(),
884
884
  input: serde_json::json!({"file":"artifact://x"}),
885
885
  requested_by: subject,
886
+ session_id: None,
886
887
  authorization_snapshot: grant,
887
888
  capability_snapshot: ["documents.extract".into()].into(),
888
889
  connection_scopes: BTreeSet::new(),