remem-ai 0.6.62

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
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use anyhow::{bail, Context, Result};
use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
use serde::Serialize;

use crate::{db, memory, workstream};

const CLEANUP_POLICY_VERSION: i64 = 1;
const FAILURE_ERROR_LIMIT_BYTES: usize = 1_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CleanupPolicy {
    archived_failure_days: Option<i64>,
}

impl CleanupPolicy {
    pub fn automatic() -> Self {
        Self {
            archived_failure_days: None,
        }
    }

    pub fn manual(archived_failure_days: Option<i64>) -> Result<Self> {
        if archived_failure_days.is_some_and(|days| days <= 0) {
            bail!("--archived-failures must be a positive number of days");
        }
        Ok(Self {
            archived_failure_days,
        })
    }

    pub fn retention_days(self) -> CleanupRetentionDays {
        CleanupRetentionDays {
            old_events: memory::OLD_EVENT_RETENTION_DAYS,
            compressed_source_observations: memory::COMPRESSED_SOURCE_OBSERVATION_RETENTION_DAYS,
            stale_memories: memory::STALE_MEMORY_ARCHIVE_DAYS,
            archived_failures: self
                .archived_failure_days
                .unwrap_or(db::ARCHIVED_FAILURE_PURGE_DAYS),
            workstream_auto_pause: workstream::DEFAULT_AUTO_PAUSE_DAYS,
            workstream_auto_abandon: workstream::DEFAULT_AUTO_ABANDON_DAYS,
        }
    }
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct CleanupRetentionDays {
    pub old_events: i64,
    pub compressed_source_observations: i64,
    pub stale_memories: i64,
    pub archived_failures: i64,
    pub workstream_auto_pause: i64,
    pub workstream_auto_abandon: i64,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct CleanupPlan {
    pub expired_memories_to_stale: usize,
    pub inactive_workstreams_to_pause: usize,
    pub long_paused_workstreams_to_abandon: usize,
    pub old_events_to_delete: usize,
    pub compressed_source_observations_to_delete: usize,
    pub stale_memories_to_archive: usize,
    pub archived_failures_to_purge: db::ArchivedFailurePurgePlan,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct CleanupApplied {
    pub expired_memories_marked_stale: usize,
    pub inactive_workstreams_paused: usize,
    pub long_paused_workstreams_abandoned: usize,
    pub old_events_deleted: usize,
    pub compressed_source_observations_deleted: usize,
    pub stale_memories_archived: usize,
    pub archived_failures_purged: db::ArchivedFailurePurgePlan,
}

impl CleanupApplied {
    fn matches_plan(&self, plan: &CleanupPlan) -> bool {
        self.expired_memories_marked_stale == plan.expired_memories_to_stale
            && self.inactive_workstreams_paused == plan.inactive_workstreams_to_pause
            && self.long_paused_workstreams_abandoned == plan.long_paused_workstreams_to_abandon
            && self.old_events_deleted == plan.old_events_to_delete
            && self.compressed_source_observations_deleted
                == plan.compressed_source_observations_to_delete
            && self.stale_memories_archived == plan.stale_memories_to_archive
            && self.archived_failures_purged == plan.archived_failures_to_purge
    }
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct CleanupExecution {
    pub plan: CleanupPlan,
    pub applied: CleanupApplied,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct CleanupReport {
    pub dry_run: bool,
    pub retention_days: CleanupRetentionDays,
    pub plan: CleanupPlan,
    pub applied: Option<CleanupApplied>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CleanupRun {
    pub id: i64,
    pub job_id: Option<i64>,
    pub started_at_epoch: i64,
    pub finished_at_epoch: i64,
    pub outcome: String,
    pub counts_json: Option<String>,
    pub error: Option<String>,
}

pub fn preview_cleanup(
    conn: &Connection,
    now_epoch: i64,
    policy: CleanupPolicy,
) -> Result<CleanupPlan> {
    build_cleanup_plan(conn, now_epoch, policy)
}

pub fn execute_manual_cleanup(
    conn: &Connection,
    now_epoch: i64,
    policy: CleanupPolicy,
) -> Result<CleanupExecution> {
    execute_cleanup(conn, now_epoch, policy, CleanupTrigger::Manual)
}

pub fn execute_automatic_cleanup_job(
    conn: &Connection,
    job_id: i64,
    lease_owner: &str,
    now_epoch: i64,
) -> Result<CleanupExecution> {
    execute_cleanup(
        conn,
        now_epoch,
        CleanupPolicy::automatic(),
        CleanupTrigger::Automatic {
            job_id,
            lease_owner,
        },
    )
}

pub fn latest_automatic_cleanup_run(
    conn: &Connection,
    outcome: &str,
) -> Result<Option<CleanupRun>> {
    if !matches!(outcome, "success" | "failure") {
        bail!("cleanup run outcome must be success or failure");
    }
    conn.query_row(
        "SELECT id, job_id, started_at_epoch, finished_at_epoch, outcome,
                counts_json, error
         FROM maintenance_runs
         WHERE \"trigger\" = 'automatic' AND outcome = ?1
         ORDER BY finished_at_epoch DESC, id DESC
         LIMIT 1",
        params![outcome],
        |row| {
            Ok(CleanupRun {
                id: row.get(0)?,
                job_id: row.get(1)?,
                started_at_epoch: row.get(2)?,
                finished_at_epoch: row.get(3)?,
                outcome: row.get(4)?,
                counts_json: row.get(5)?,
                error: row.get(6)?,
            })
        },
    )
    .optional()
    .context("read latest automatic cleanup run")
}

#[derive(Clone, Copy)]
enum CleanupTrigger<'a> {
    Manual,
    Automatic { job_id: i64, lease_owner: &'a str },
}

impl CleanupTrigger<'_> {
    fn as_str(self) -> &'static str {
        match self {
            Self::Manual => "manual",
            Self::Automatic { .. } => "automatic",
        }
    }

    fn job_id(self) -> Option<i64> {
        match self {
            Self::Manual => None,
            Self::Automatic { job_id, .. } => Some(job_id),
        }
    }
}

fn execute_cleanup(
    conn: &Connection,
    now_epoch: i64,
    policy: CleanupPolicy,
    trigger: CleanupTrigger<'_>,
) -> Result<CleanupExecution> {
    let tx = match Transaction::new_unchecked(conn, TransactionBehavior::Immediate) {
        Ok(tx) => tx,
        Err(error) => {
            let error = anyhow::Error::from(error).context("begin cleanup transaction");
            return Err(record_failure_after_rollback(
                conn, trigger, now_epoch, error,
            ));
        }
    };
    let execution = execute_cleanup_in_transaction(&tx, now_epoch, policy, trigger);
    let execution = match execution {
        Ok(execution) => execution,
        Err(error) => {
            drop(tx);
            return Err(record_failure_after_rollback(
                conn, trigger, now_epoch, error,
            ));
        }
    };
    if let Err(error) = tx.commit().context("commit cleanup transaction") {
        return Err(record_failure_after_rollback(
            conn, trigger, now_epoch, error,
        ));
    }
    Ok(execution)
}

fn execute_cleanup_in_transaction(
    conn: &Connection,
    started_at_epoch: i64,
    policy: CleanupPolicy,
    trigger: CleanupTrigger<'_>,
) -> Result<CleanupExecution> {
    if let CleanupTrigger::Automatic {
        job_id,
        lease_owner,
    } = trigger
    {
        validate_automatic_job(conn, job_id, lease_owner, started_at_epoch)?;
    }
    let plan = build_cleanup_plan(conn, started_at_epoch, policy)?;
    let applied = apply_cleanup_plan(conn, started_at_epoch, policy)?;
    if !applied.matches_plan(&plan) {
        bail!("cleanup plan/apply count invariant failed");
    }
    let finished_at_epoch = cleanup_finished_at(started_at_epoch);
    insert_success_run(conn, trigger, started_at_epoch, finished_at_epoch, &applied)?;
    if let CleanupTrigger::Automatic {
        job_id,
        lease_owner,
    } = trigger
    {
        finish_automatic_job(
            conn,
            job_id,
            lease_owner,
            started_at_epoch,
            finished_at_epoch,
        )?;
    }
    Ok(CleanupExecution { plan, applied })
}

fn build_cleanup_plan(
    conn: &Connection,
    now_epoch: i64,
    policy: CleanupPolicy,
) -> Result<CleanupPlan> {
    Ok(CleanupPlan {
        expired_memories_to_stale: memory::lifecycle::count_expired_active_memories(
            conn, now_epoch,
        )?,
        inactive_workstreams_to_pause: workstream::count_auto_pause_all_inactive_at(
            conn,
            now_epoch,
            workstream::DEFAULT_AUTO_PAUSE_DAYS,
        )?,
        long_paused_workstreams_to_abandon: workstream::count_auto_abandon_all_inactive_at(
            conn,
            now_epoch,
            workstream::DEFAULT_AUTO_ABANDON_DAYS,
        )?,
        old_events_to_delete: memory::count_old_events_at(
            conn,
            now_epoch,
            memory::OLD_EVENT_RETENTION_DAYS,
        )?,
        compressed_source_observations_to_delete:
            memory::count_compressed_source_observations_to_delete_at(
                conn,
                now_epoch,
                memory::COMPRESSED_SOURCE_OBSERVATION_RETENTION_DAYS,
            )?,
        stale_memories_to_archive: memory::count_stale_memories_to_archive_at(
            conn,
            now_epoch,
            memory::STALE_MEMORY_ARCHIVE_DAYS,
        )?,
        archived_failures_to_purge: match policy.archived_failure_days {
            Some(days) => db::count_archived_failures_to_purge_at(conn, now_epoch, days)?,
            None => db::ArchivedFailurePurgePlan::default(),
        },
    })
}

fn apply_cleanup_plan(
    conn: &Connection,
    now_epoch: i64,
    policy: CleanupPolicy,
) -> Result<CleanupApplied> {
    Ok(CleanupApplied {
        expired_memories_marked_stale: memory::lifecycle::expire_active_memories(conn, now_epoch)?,
        inactive_workstreams_paused: workstream::auto_pause_all_inactive_at(
            conn,
            now_epoch,
            workstream::DEFAULT_AUTO_PAUSE_DAYS,
        )?,
        long_paused_workstreams_abandoned: workstream::auto_abandon_all_inactive_at(
            conn,
            now_epoch,
            workstream::DEFAULT_AUTO_ABANDON_DAYS,
        )?,
        old_events_deleted: memory::cleanup_old_events_at(
            conn,
            now_epoch,
            memory::OLD_EVENT_RETENTION_DAYS,
        )?,
        compressed_source_observations_deleted: memory::cleanup_compressed_source_observations_at(
            conn,
            now_epoch,
            memory::COMPRESSED_SOURCE_OBSERVATION_RETENTION_DAYS,
        )?,
        stale_memories_archived: memory::archive_stale_memories_at(
            conn,
            now_epoch,
            memory::STALE_MEMORY_ARCHIVE_DAYS,
        )?,
        archived_failures_purged: match policy.archived_failure_days {
            Some(days) => db::purge_archived_failures_at(conn, now_epoch, days)?,
            None => db::ArchivedFailurePurgePlan::default(),
        },
    })
}

fn validate_automatic_job(
    conn: &Connection,
    job_id: i64,
    lease_owner: &str,
    now_epoch: i64,
) -> Result<()> {
    let valid: bool = conn.query_row(
        "SELECT EXISTS(
           SELECT 1 FROM jobs
           WHERE id = ?1 AND job_type = 'cleanup' AND state = 'processing'
             AND lease_owner = ?2 AND lease_expires_epoch IS NOT NULL
             AND lease_expires_epoch >= ?3
         )",
        params![job_id, lease_owner, now_epoch],
        |row| row.get(0),
    )?;
    if !valid {
        bail!("automatic cleanup job lease validation failed: job_id={job_id} owner={lease_owner}");
    }
    Ok(())
}

fn finish_automatic_job(
    conn: &Connection,
    job_id: i64,
    lease_owner: &str,
    lease_validation_epoch: i64,
    finished_at_epoch: i64,
) -> Result<()> {
    let changed = conn.execute(
        "UPDATE jobs
         SET state = 'done', lease_owner = NULL, lease_expires_epoch = NULL,
             next_retry_epoch = 0, last_error = NULL, failure_class = NULL,
             failed_at_epoch = NULL, archived_at_epoch = NULL,
             updated_at_epoch = ?1
         WHERE id = ?2 AND job_type = 'cleanup' AND state = 'processing'
           AND lease_owner = ?3 AND lease_expires_epoch IS NOT NULL
           AND lease_expires_epoch >= ?4",
        params![
            finished_at_epoch,
            job_id,
            lease_owner,
            lease_validation_epoch
        ],
    )?;
    if changed != 1 {
        bail!("automatic cleanup job completion lost its lease: job_id={job_id}");
    }
    Ok(())
}

fn insert_success_run(
    conn: &Connection,
    trigger: CleanupTrigger<'_>,
    started_at_epoch: i64,
    finished_at_epoch: i64,
    applied: &CleanupApplied,
) -> Result<()> {
    let counts_json = serde_json::to_string(applied)?;
    conn.execute(
        "INSERT INTO maintenance_runs
         (job_id, \"trigger\", policy_version, started_at_epoch,
          finished_at_epoch, outcome, counts_json, error)
         VALUES (?1, ?2, ?3, ?4, ?5, 'success', ?6, NULL)",
        params![
            trigger.job_id(),
            trigger.as_str(),
            CLEANUP_POLICY_VERSION,
            started_at_epoch,
            finished_at_epoch,
            counts_json
        ],
    )
    .context("record successful cleanup run")?;
    Ok(())
}

fn record_failure_after_rollback(
    conn: &Connection,
    trigger: CleanupTrigger<'_>,
    started_at_epoch: i64,
    error: anyhow::Error,
) -> anyhow::Error {
    let finished_at_epoch = cleanup_finished_at(started_at_epoch);
    let safe_error = safe_cleanup_error(&error);
    let ledger_result = record_failure_run(
        conn,
        trigger,
        started_at_epoch,
        finished_at_epoch,
        &safe_error,
    );
    match ledger_result {
        Ok(()) => anyhow::anyhow!(safe_error),
        Err(ledger_error) => {
            let safe_ledger_error = safe_cleanup_error(&ledger_error);
            anyhow::anyhow!(
                "{safe_error}; additionally failed to record cleanup failure: {safe_ledger_error}"
            )
        }
    }
}

fn record_failure_run(
    conn: &Connection,
    trigger: CleanupTrigger<'_>,
    started_at_epoch: i64,
    finished_at_epoch: i64,
    safe_error: &str,
) -> Result<()> {
    let tx = Transaction::new_unchecked(conn, TransactionBehavior::Immediate)
        .context("begin cleanup failure ledger transaction")?;
    let job_id = match trigger.job_id() {
        Some(job_id) if job_exists(&tx, job_id)? => Some(job_id),
        _ => None,
    };
    let stored_error = if safe_error.is_empty() {
        "cleanup transaction failed"
    } else {
        safe_error
    };
    tx.execute(
        "INSERT INTO maintenance_runs
         (job_id, \"trigger\", policy_version, started_at_epoch,
          finished_at_epoch, outcome, counts_json, error)
         VALUES (?1, ?2, ?3, ?4, ?5, 'failure', NULL, ?6)",
        params![
            job_id,
            trigger.as_str(),
            CLEANUP_POLICY_VERSION,
            started_at_epoch,
            finished_at_epoch,
            stored_error
        ],
    )
    .context("record failed cleanup run")?;
    tx.commit()
        .context("commit cleanup failure ledger transaction")?;
    Ok(())
}

fn cleanup_finished_at(started_at_epoch: i64) -> i64 {
    chrono::Utc::now().timestamp().max(started_at_epoch)
}

pub(crate) fn safe_cleanup_error(error: &anyhow::Error) -> String {
    let raw = format!("{error:#}");
    let bounded =
        crate::adapter::common::redact_hook_payload_preview(&raw, FAILURE_ERROR_LIMIT_BYTES);
    let bounded = bounded.trim();
    if bounded.is_empty() {
        "cleanup transaction failed".to_string()
    } else {
        bounded.to_string()
    }
}

fn job_exists(conn: &Connection, job_id: i64) -> Result<bool> {
    Ok(conn.query_row(
        "SELECT EXISTS(SELECT 1 FROM jobs WHERE id = ?1)",
        params![job_id],
        |row| row.get(0),
    )?)
}

#[cfg(test)]
mod tests;