remem-ai 0.6.90

Local-first coding agent memory for Claude Code and OpenAI Codex
Documentation
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
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use fs2::FileExt;

use crate::db;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum WorkerSpawnDecision {
    Spawned,
    SkippedHealthyWorker,
    SkippedLaunchInProgress,
}

pub(super) fn spawn_worker_once_if_idle(
    conn: &rusqlite::Connection,
) -> Result<WorkerSpawnDecision> {
    spawn_worker_once_if_idle_with(conn, spawn_worker_once)
}

fn spawn_worker_once_if_idle_with(
    conn: &rusqlite::Connection,
    spawn: impl FnOnce() -> Result<()>,
) -> Result<WorkerSpawnDecision> {
    if !should_spawn_worker_once(conn)? {
        return Ok(WorkerSpawnDecision::SkippedHealthyWorker);
    }
    let Some(_guard) = acquire_worker_launch_lock()? else {
        return Ok(WorkerSpawnDecision::SkippedLaunchInProgress);
    };
    if !should_spawn_worker_once(conn)? {
        return Ok(WorkerSpawnDecision::SkippedHealthyWorker);
    }
    spawn()?;
    Ok(WorkerSpawnDecision::Spawned)
}

fn should_spawn_worker_once(conn: &rusqlite::Connection) -> Result<bool> {
    if let Some(heartbeat) =
        db::healthy_current_once_worker_heartbeat(conn, db::WORKER_HEARTBEAT_HEALTH_SECS)?
    {
        crate::log::info(
            "summarize",
            &format!(
                "current worker --once heartbeat owner={} is healthy; skip overlapping fallback",
                heartbeat.owner
            ),
        );
        return Ok(false);
    }
    let Some(heartbeat) =
        db::healthy_daemon_worker_heartbeat(conn, db::WORKER_HEARTBEAT_HEALTH_SECS)?
    else {
        return Ok(true);
    };
    if db::is_current_daemon_worker_owner(&heartbeat.owner) {
        return Ok(false);
    }
    crate::log::info(
        "summarize",
        &format!(
            "worker daemon heartbeat owner={} is from another binary version; spawning worker --once fallback",
            heartbeat.owner
        ),
    );
    Ok(true)
}

fn spawn_worker_once() -> Result<()> {
    let exe = std::env::current_exe()?;
    drop(spawn_worker_once_from_executable(&exe)?);
    Ok(())
}

fn spawn_worker_once_from_executable(current_exe: &Path) -> Result<std::process::Child> {
    let exe = worker_executable(current_exe)?;
    let worker_dir = stable_worker_dir();
    let stderr_file = crate::log::open_log_append();
    let stderr_cfg = match stderr_file {
        Some(file) => std::process::Stdio::from(file),
        None => std::process::Stdio::null(),
    };
    let mut command = std::process::Command::new(&exe);
    command
        .arg("worker")
        .arg("--once")
        .current_dir(&worker_dir)
        .env("REMEM_DATA_DIR", &worker_dir)
        .env("REMEM_STDERR_TO_LOG", "1")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(stderr_cfg);
    Ok(command.spawn()?)
}

fn worker_executable(current_exe: &Path) -> Result<PathBuf> {
    if crate::hook_cli::is_hook_binary(current_exe) {
        return crate::hook_cli::sibling_full_binary(current_exe).ok_or_else(|| {
            anyhow::anyhow!(
                "cannot launch worker from slim hook {}: executable sibling remem is missing",
                current_exe.display()
            )
        });
    }
    Ok(current_exe.to_path_buf())
}

fn stable_worker_dir() -> PathBuf {
    let data_dir = match crate::db::absolute_data_dir() {
        Ok(path) => path,
        Err(err) => {
            crate::log::warn(
                "summarize",
                &format!(
                    "failed to resolve worker dir from REMEM_DATA_DIR: {}; falling back to temp dir",
                    err
                ),
            );
            return std::env::temp_dir();
        }
    };
    if let Err(err) = std::fs::create_dir_all(&data_dir) {
        crate::log::warn(
            "summarize",
            &format!(
                "failed to create worker dir {}: {}; falling back to temp dir",
                data_dir.display(),
                err
            ),
        );
        return std::env::temp_dir();
    }
    data_dir
}

struct WorkerLaunchLockGuard {
    file: File,
}

fn acquire_worker_launch_lock() -> Result<Option<WorkerLaunchLockGuard>> {
    let path = worker_launch_lock_path()?;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("create worker launch lock directory {}", parent.display()))?;
    }
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)
        .with_context(|| format!("open worker launch lock {}", path.display()))?;

    match file.try_lock_exclusive() {
        Ok(()) => Ok(Some(WorkerLaunchLockGuard { file })),
        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(None),
        Err(error) => Err(error).with_context(|| format!("lock worker launch {}", path.display())),
    }
}

fn worker_launch_lock_path() -> Result<PathBuf> {
    Ok(crate::db::absolute_data_dir()?.join("worker-launch.lock"))
}

impl Drop for WorkerLaunchLockGuard {
    fn drop(&mut self) {
        if let Err(error) = self.file.unlock() {
            crate::log::warn(
                "summarize",
                &format!("unlock worker launch failed: {}", error),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc, Barrier,
    };
    use std::time::Duration;

    use crate::db::{self, test_support::ScopedTestDataDir};

    use super::{
        should_spawn_worker_once, spawn_worker_once_from_executable,
        spawn_worker_once_if_idle_with, stable_worker_dir, worker_executable, WorkerSpawnDecision,
    };

    #[cfg(unix)]
    #[test]
    fn immediately_exiting_full_sibling_does_not_publish_worker_health() -> anyhow::Result<()> {
        use std::os::unix::fs::PermissionsExt;

        let test_dir = ScopedTestDataDir::new("summary-slim-hook-worker");
        let conn = db::open_db()?;
        let hook = test_dir.path.join("remem-hook");
        let full = test_dir.path.join("remem");
        let args_file = test_dir.path.join("remem.args");
        std::fs::write(
            &full,
            format!(
                "#!/bin/sh\nprintf '%s\\n' \"$@\" > '{}'\n",
                args_file.display()
            ),
        )?;
        let mut permissions = std::fs::metadata(&full)?.permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&full, permissions)?;

        let mut child = spawn_worker_once_from_executable(&hook)?;
        let status = child.wait()?;

        assert!(
            status.success(),
            "stub full sibling should exit successfully"
        );
        assert_eq!(std::fs::read_to_string(args_file)?, "worker\n--once\n");
        assert!(db::healthy_current_once_worker_heartbeat(
            &conn,
            db::WORKER_HEARTBEAT_HEALTH_SECS
        )?
        .is_none());
        assert!(db::latest_worker_heartbeat(&conn)?.is_none());
        Ok(())
    }

    #[test]
    fn slim_hook_without_full_sibling_fails_before_launch() {
        let test_dir = ScopedTestDataDir::new("summary-slim-hook-missing-worker");
        let hook = test_dir.path.join("remem-hook");

        let error = worker_executable(&hook).expect_err("missing remem sibling must fail");

        assert!(error
            .to_string()
            .contains("executable sibling remem is missing"));
    }

    #[test]
    fn missing_worker_uses_stop_fallback_spawn() {
        let _test_dir = ScopedTestDataDir::new("summary-missing-worker");
        let conn = db::open_db().expect("db should open");

        assert!(
            should_spawn_worker_once(&conn).expect("worker check should run"),
            "missing heartbeat should keep worker --once fallback"
        );
    }

    #[test]
    fn current_healthy_daemon_skips_stop_spawn() {
        let _test_dir = ScopedTestDataDir::new("summary-healthy-daemon");
        let conn = db::open_db().expect("db should open");
        let now = chrono::Utc::now().timestamp();
        db::upsert_worker_heartbeat(
            &conn,
            &db::current_worker_owner("daemon", std::process::id(), now * 1000),
            i64::from(std::process::id()),
            now - 5,
            now - 5,
        )
        .expect("heartbeat should insert");

        assert!(
            !should_spawn_worker_once(&conn).expect("worker check should run"),
            "healthy daemon heartbeat should skip worker --once fallback"
        );
    }

    #[test]
    fn old_version_healthy_daemon_uses_stop_fallback_spawn() {
        let _test_dir = ScopedTestDataDir::new("summary-old-daemon-version");
        let conn = db::open_db().expect("db should open");
        let now = chrono::Utc::now().timestamp();
        db::upsert_worker_heartbeat(
            &conn,
            "worker-daemon",
            i64::from(std::process::id()),
            now - 5,
            now - 5,
        )
        .expect("heartbeat should insert");

        assert!(
            should_spawn_worker_once(&conn).expect("worker check should run"),
            "old-version daemon heartbeat should not suppress Stop fallback"
        );
    }

    #[test]
    fn healthy_once_worker_does_not_skip_stop_spawn() -> anyhow::Result<()> {
        let _test_dir = ScopedTestDataDir::new("summary-healthy-once-worker");
        let conn = db::open_db()?;
        let now = chrono::Utc::now().timestamp();
        db::upsert_worker_heartbeat(
            &conn,
            "worker-once-test",
            i64::from(std::process::id()),
            now - 5,
            now - 5,
        )?;

        assert!(
            should_spawn_worker_once(&conn)?,
            "healthy worker --once heartbeat should not suppress Stop fallback"
        );
        Ok(())
    }

    #[test]
    fn current_healthy_once_worker_skips_stop_spawn() -> anyhow::Result<()> {
        let _test_dir = ScopedTestDataDir::new("summary-current-healthy-once-worker");
        let conn = db::open_db()?;
        let now = chrono::Utc::now().timestamp();
        db::upsert_worker_heartbeat(
            &conn,
            &db::current_worker_owner("once", std::process::id(), now * 1000),
            i64::from(std::process::id()),
            now - 5,
            now - 5,
        )?;

        assert!(
            !should_spawn_worker_once(&conn)?,
            "a healthy current worker --once must suppress overlapping fallback workers"
        );
        Ok(())
    }

    #[test]
    fn current_once_suppresses_spawn_with_newer_old_daemon_heartbeat() -> anyhow::Result<()> {
        let _test_dir = ScopedTestDataDir::new("summary-current-once-with-old-daemon");
        let conn = db::open_db()?;
        let now = chrono::Utc::now().timestamp();
        db::upsert_worker_heartbeat(
            &conn,
            &db::current_worker_owner("once", std::process::id(), now * 1000),
            i64::from(std::process::id()),
            now - 10,
            now - 10,
        )?;
        db::upsert_worker_heartbeat(
            &conn,
            "worker-daemon-old-version",
            i64::from(std::process::id()),
            now - 5,
            now - 5,
        )?;

        assert!(
            !should_spawn_worker_once(&conn)?,
            "the old daemon's newer heartbeat must not hide an active current once worker"
        );
        Ok(())
    }

    #[test]
    fn stale_worker_uses_stop_fallback_spawn() {
        let _test_dir = ScopedTestDataDir::new("summary-stale-worker");
        let conn = db::open_db().expect("db should open");
        let now = chrono::Utc::now().timestamp();
        db::upsert_worker_heartbeat(&conn, "worker-once-old", 123, now - 900, now - 900)
            .expect("heartbeat should insert");

        assert!(
            should_spawn_worker_once(&conn).expect("worker check should run"),
            "stale heartbeat should keep worker --once fallback"
        );
    }

    #[test]
    fn concurrent_stop_spawn_attempts_are_bounded_by_launch_lock() -> anyhow::Result<()> {
        let _test_dir = ScopedTestDataDir::new("summary-launch-lock-concurrent");
        let setup = db::open_db()?;
        drop(setup);

        let workers = 8;
        let barrier = Arc::new(Barrier::new(workers));
        let spawned = Arc::new(AtomicUsize::new(0));
        let skipped_launch = Arc::new(AtomicUsize::new(0));
        let skipped_healthy = Arc::new(AtomicUsize::new(0));

        std::thread::scope(|scope| {
            let mut handles = Vec::new();
            for _ in 0..workers {
                let barrier = Arc::clone(&barrier);
                let spawned = Arc::clone(&spawned);
                let skipped_launch = Arc::clone(&skipped_launch);
                let skipped_healthy = Arc::clone(&skipped_healthy);
                handles.push(scope.spawn(move || -> anyhow::Result<()> {
                    let conn = db::open_db()?;
                    barrier.wait();
                    let decision = spawn_worker_once_if_idle_with(&conn, || {
                        spawned.fetch_add(1, Ordering::SeqCst);
                        std::thread::sleep(Duration::from_millis(50));
                        Ok(())
                    })?;
                    match decision {
                        WorkerSpawnDecision::Spawned => {}
                        WorkerSpawnDecision::SkippedLaunchInProgress => {
                            skipped_launch.fetch_add(1, Ordering::SeqCst);
                        }
                        WorkerSpawnDecision::SkippedHealthyWorker => {
                            skipped_healthy.fetch_add(1, Ordering::SeqCst);
                        }
                    }
                    Ok(())
                }));
            }
            for handle in handles {
                handle
                    .join()
                    .map_err(|_| anyhow::anyhow!("spawn thread panicked"))??;
            }
            Ok::<(), anyhow::Error>(())
        })?;

        assert_eq!(spawned.load(Ordering::SeqCst), 1);
        assert_eq!(
            spawned.load(Ordering::SeqCst)
                + skipped_launch.load(Ordering::SeqCst)
                + skipped_healthy.load(Ordering::SeqCst),
            workers
        );
        Ok(())
    }

    #[test]
    fn stable_worker_dir_uses_data_dir() {
        let data_dir = ScopedTestDataDir::new("summary-worker-dir");

        let got = stable_worker_dir();

        assert_eq!(got, data_dir.path);
        assert!(got.is_dir());
    }

    #[test]
    fn stable_worker_dir_absolutizes_relative_data_dir() -> anyhow::Result<()> {
        let relative = std::path::PathBuf::from(format!(
            ".remem-summary-worker-relative-{}-{}",
            std::process::id(),
            chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default()
        ));

        let got = db::with_data_dir(&relative, stable_worker_dir);

        assert_eq!(got, std::env::current_dir()?.join(&relative));
        assert!(got.is_absolute());
        assert!(got.is_dir());
        std::fs::remove_dir_all(relative)?;
        Ok(())
    }
}