daat-locus 0.1.1

A long-running local agent runtime with memory, workflows, apps, and sleep-time self-improvement.
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::{
    fs::{self, OpenOptions},
    io::{self, Write},
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use miette::{IntoDiagnostic, Result};
use serde::{Serialize, de::DeserializeOwned};
use uuid::Uuid;

use crate::daat_locus_paths::{DaatLocusPaths, daat_locus_paths, daat_locus_paths_sync};

#[derive(Clone, Debug)]
pub struct PersistenceStore {
    paths: DaatLocusPaths,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PersistenceFileMode {
    Default,
    Private,
}

impl PersistenceStore {
    pub async fn runtime() -> Self {
        Self {
            paths: daat_locus_paths().await,
        }
    }

    pub fn runtime_sync() -> Self {
        Self {
            paths: daat_locus_paths_sync(),
        }
    }

    pub fn config_file(&self, file_name: &str) -> PathBuf {
        self.paths.config_file(file_name)
    }

    pub fn state_file(&self, file_name: &str) -> PathBuf {
        self.paths.state_file(file_name)
    }

    pub fn memory_file(&self, file_name: &str) -> PathBuf {
        self.paths.memory_file(file_name)
    }

    pub async fn read_postcard_state_or_default<T>(&self, file_name: &str, label: &str) -> T
    where
        T: DeserializeOwned + Default,
    {
        read_postcard_or_default(&self.state_file(file_name), label).await
    }

    pub fn read_postcard_state_or_default_sync<T>(&self, file_name: &str, label: &str) -> T
    where
        T: DeserializeOwned + Default,
    {
        read_postcard_or_default_sync(&self.state_file(file_name), label)
    }

    pub async fn read_postcard_memory<T>(&self, file_name: &str, label: &str) -> Option<T>
    where
        T: DeserializeOwned,
    {
        read_postcard_optional(&self.memory_file(file_name), label).await
    }

    pub async fn read_json_config_or_default<T>(&self, file_name: &str, label: &str) -> T
    where
        T: DeserializeOwned + Default,
    {
        read_json_or_default(&self.config_file(file_name), label).await
    }

    pub async fn read_json_memory<T>(&self, file_name: &str, label: &str) -> Option<T>
    where
        T: DeserializeOwned,
    {
        read_json_optional(&self.memory_file(file_name), label).await
    }

    pub fn read_json_file_sync<T>(&self, path: &Path, label: &str) -> Option<T>
    where
        T: DeserializeOwned,
    {
        read_json_optional_sync(path, label)
    }

    pub async fn write_postcard_memory<T>(&self, file_name: &str, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        write_postcard_atomic(
            &self.memory_file(file_name),
            value,
            PersistenceFileMode::Default,
        )
        .await
    }

    pub async fn write_json_memory<T>(&self, file_name: &str, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        let bytes = serde_json::to_vec_pretty(value).into_diagnostic()?;
        write_bytes_atomic(
            self.memory_file(file_name),
            bytes,
            PersistenceFileMode::Default,
        )
        .await
        .into_diagnostic()
    }

    pub fn write_json_file_sync<T>(&self, path: &Path, value: &T) -> Result<()>
    where
        T: Serialize + ?Sized,
    {
        write_json_pretty_atomic_sync(path, value, PersistenceFileMode::Default)
    }
}

pub async fn read_postcard_or_default<T>(path: &Path, label: &str) -> T
where
    T: DeserializeOwned + Default,
{
    read_postcard_optional(path, label)
        .await
        .unwrap_or_default()
}

pub async fn read_postcard_optional<T>(path: &Path, label: &str) -> Option<T>
where
    T: DeserializeOwned,
{
    let bytes = match tokio::fs::read(path).await {
        Ok(bytes) => bytes,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return None,
        Err(err) => {
            tracing::warn!("failed to read {label} {}: {err}", path.display());
            return None;
        }
    };
    match postcard::from_bytes::<T>(&bytes) {
        Ok(value) => Some(value),
        Err(err) => {
            tracing::warn!("failed to decode {label} {}: {err}", path.display());
            quarantine_corrupt_file(path, label).await;
            None
        }
    }
}

pub fn read_postcard_or_default_sync<T>(path: &Path, label: &str) -> T
where
    T: DeserializeOwned + Default,
{
    let bytes = match fs::read(path) {
        Ok(bytes) => bytes,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return T::default(),
        Err(err) => {
            tracing::warn!("failed to read {label} {}: {err}", path.display());
            return T::default();
        }
    };
    match postcard::from_bytes::<T>(&bytes) {
        Ok(value) => value,
        Err(err) => {
            tracing::warn!("failed to decode {label} {}: {err}", path.display());
            quarantine_corrupt_file_sync(path, label);
            T::default()
        }
    }
}

pub async fn read_json_or_default<T>(path: &Path, label: &str) -> T
where
    T: DeserializeOwned + Default,
{
    read_json_optional(path, label).await.unwrap_or_default()
}

pub async fn read_json_optional<T>(path: &Path, label: &str) -> Option<T>
where
    T: DeserializeOwned,
{
    let bytes = match tokio::fs::read(path).await {
        Ok(bytes) => bytes,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return None,
        Err(err) => {
            tracing::warn!("failed to read {label} {}: {err}", path.display());
            return None;
        }
    };
    match serde_json::from_slice::<T>(&bytes) {
        Ok(value) => Some(value),
        Err(err) => {
            tracing::warn!("failed to decode {label} {}: {err}", path.display());
            quarantine_corrupt_file(path, label).await;
            None
        }
    }
}

pub fn read_json_optional_sync<T>(path: &Path, label: &str) -> Option<T>
where
    T: DeserializeOwned,
{
    let bytes = match fs::read(path) {
        Ok(bytes) => bytes,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return None,
        Err(err) => {
            tracing::warn!("failed to read {label} {}: {err}", path.display());
            return None;
        }
    };
    match serde_json::from_slice::<T>(&bytes) {
        Ok(value) => Some(value),
        Err(err) => {
            tracing::warn!("failed to decode {label} {}: {err}", path.display());
            quarantine_corrupt_file_sync(path, label);
            None
        }
    }
}

pub async fn write_postcard_atomic<T>(
    path: &Path,
    value: &T,
    mode: PersistenceFileMode,
) -> Result<()>
where
    T: Serialize + ?Sized,
{
    let bytes = postcard::to_allocvec(value).into_diagnostic()?;
    write_bytes_atomic(path.to_path_buf(), bytes, mode)
        .await
        .into_diagnostic()
}

pub fn write_postcard_atomic_sync<T>(
    path: &Path,
    value: &T,
    mode: PersistenceFileMode,
) -> Result<()>
where
    T: Serialize + ?Sized,
{
    let bytes = postcard::to_allocvec(value).into_diagnostic()?;
    write_bytes_atomic_sync(path, &bytes, mode).into_diagnostic()
}

pub fn write_json_pretty_atomic_sync<T>(
    path: &Path,
    value: &T,
    mode: PersistenceFileMode,
) -> Result<()>
where
    T: Serialize + ?Sized,
{
    let bytes = serde_json::to_vec_pretty(value).into_diagnostic()?;
    write_bytes_atomic_sync(path, &bytes, mode).into_diagnostic()
}

pub async fn write_bytes_atomic(
    path: PathBuf,
    bytes: Vec<u8>,
    mode: PersistenceFileMode,
) -> io::Result<()> {
    tokio::task::spawn_blocking(move || write_bytes_atomic_sync(&path, &bytes, mode))
        .await
        .map_err(|err| io::Error::other(format!("atomic write task failed: {err}")))?
}

pub async fn append_bytes_durable(path: PathBuf, bytes: Vec<u8>) -> io::Result<()> {
    tokio::task::spawn_blocking(move || append_bytes_durable_sync(&path, &bytes))
        .await
        .map_err(|err| io::Error::other(format!("durable append task failed: {err}")))?
}

pub fn write_bytes_atomic_sync(
    path: &Path,
    bytes: &[u8],
    mode: PersistenceFileMode,
) -> io::Result<()> {
    let parent = path.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("path has no parent: {}", path.display()),
        )
    })?;
    fs::create_dir_all(parent)?;

    let temp_path = create_unique_temp_path(path);
    let write_result = (|| {
        let mut file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temp_path)?;
        if mode == PersistenceFileMode::Private {
            set_private_file_permissions(&temp_path)?;
        }
        file.write_all(bytes)?;
        file.sync_all()?;
        drop(file);
        fs::rename(&temp_path, path)?;
        sync_parent_dir(parent)?;
        Ok(())
    })();

    if write_result.is_err() {
        let _ = fs::remove_file(&temp_path);
    }
    write_result
}

pub fn append_bytes_durable_sync(path: &Path, bytes: &[u8]) -> io::Result<()> {
    let parent = path.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("path has no parent: {}", path.display()),
        )
    })?;
    fs::create_dir_all(parent)?;
    let mut file = OpenOptions::new().create(true).append(true).open(path)?;
    file.write_all(bytes)?;
    file.flush()?;
    file.sync_all()?;
    drop(file);
    sync_parent_dir(parent)
}

pub fn set_private_file_permissions(path: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}

fn create_unique_temp_path(path: &Path) -> PathBuf {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let name = path
        .file_name()
        .map(|name| name.to_string_lossy())
        .unwrap_or_else(|| "state".into());
    parent.join(format!(
        ".{name}.tmp-{}-{}",
        std::process::id(),
        Uuid::new_v4()
    ))
}

fn corrupt_path(path: &Path) -> PathBuf {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let name = path
        .file_name()
        .map(|name| name.to_string_lossy())
        .unwrap_or_else(|| "state".into());
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_millis())
        .unwrap_or_default();
    parent.join(format!("{name}.corrupt-{timestamp}-{}", Uuid::new_v4()))
}

async fn quarantine_corrupt_file(path: &Path, label: &str) {
    let quarantine_path = corrupt_path(path);
    match tokio::fs::rename(path, &quarantine_path).await {
        Ok(()) => tracing::warn!(
            "moved corrupt {label} state file from {} to {}",
            path.display(),
            quarantine_path.display()
        ),
        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
        Err(err) => tracing::warn!(
            "failed to move corrupt {label} state file {}: {err}",
            path.display()
        ),
    }
}

fn quarantine_corrupt_file_sync(path: &Path, label: &str) {
    let quarantine_path = corrupt_path(path);
    match fs::rename(path, &quarantine_path) {
        Ok(()) => tracing::warn!(
            "moved corrupt {label} state file from {} to {}",
            path.display(),
            quarantine_path.display()
        ),
        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
        Err(err) => tracing::warn!(
            "failed to move corrupt {label} state file {}: {err}",
            path.display()
        ),
    }
}

fn sync_parent_dir(path: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        fs::File::open(path)?.sync_all()?;
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};

    use super::*;

    #[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
    struct TestState {
        value: String,
    }

    #[test]
    fn atomic_write_replaces_complete_file() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("state.bin");

        write_bytes_atomic_sync(&path, b"old", PersistenceFileMode::Default).expect("write old");
        write_bytes_atomic_sync(&path, b"new", PersistenceFileMode::Default).expect("write new");

        assert_eq!(fs::read(&path).expect("read state"), b"new");
        assert!(
            fs::read_dir(tempdir.path())
                .expect("read dir")
                .all(|entry| !entry
                    .expect("dir entry")
                    .file_name()
                    .to_string_lossy()
                    .contains(".tmp-"))
        );
    }

    #[cfg(unix)]
    #[test]
    fn private_atomic_write_sets_private_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("config.toml");

        write_bytes_atomic_sync(&path, b"secret", PersistenceFileMode::Private)
            .expect("write private");

        let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    #[test]
    fn corrupt_postcard_file_is_quarantined_and_defaults() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("state.bin");
        fs::write(&path, b"not-postcard").expect("write corrupt");

        let state: TestState = read_postcard_or_default_sync(&path, "test state");

        assert_eq!(state, TestState::default());
        assert!(!path.exists());
        assert!(
            fs::read_dir(tempdir.path())
                .expect("read dir")
                .any(|entry| entry
                    .expect("dir entry")
                    .file_name()
                    .to_string_lossy()
                    .contains(".corrupt-"))
        );
    }

    #[test]
    fn durable_append_preserves_existing_content() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("records.jsonl");

        append_bytes_durable_sync(&path, b"one\n").expect("append one");
        append_bytes_durable_sync(&path, b"two\n").expect("append two");

        assert_eq!(
            fs::read_to_string(&path).expect("read records"),
            "one\ntwo\n"
        );
    }
}