Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

refactor(memories): @import sidecar so CLAUDE.md stays slim

Louis Beaumont12fe62f275dd
diff --git a/crates/screenpipe-connect/src/connections/claude_code.rs b/crates/screenpipe-connect/src/connections/claude_code.rs
index 0e4eda20d..5a0f60da6 100644
--- a/crates/screenpipe-connect/src/connections/claude_code.rs
+++ b/crates/screenpipe-connect/src/connections/claude_code.rs
@@ -13,7 +13,7 @@ static DEF: IntegrationDef = IntegrationDef {
name: "Claude Code",
icon: "claude",
category: Category::Productivity,
- description: "Continuously sync screenpipe memories into Claude Code's user-level CLAUDE.md so Claude has long-term context across every session. The sync writes a marker block (\"<!-- screenpipe-memories:start -->\") that screenpipe owns and rewrites idempotently — anything outside the block stays untouched. Leave home_path empty to use the default (~/.claude). For per-project memory, point home_path at a specific project's directory containing CLAUDE.md.",
+ description: "Continuously sync screenpipe memories into Claude Code so it has long-term context across every session. CLAUDE.md gets a tiny screenpipe-owned marker block that `@`-imports a sibling `screenpipe-memories.md` sidecar — the sidecar holds the full digest and is rewritten end-to-end on each sync, while CLAUDE.md stays small and hand-editable outside the marker block. Leave home_path empty to use the default (~/.claude). For per-project memory, point home_path at a specific project's directory containing CLAUDE.md.",
fields: &[FieldDef {
key: "home_path",
label: "Claude home directory (optional)",
diff --git a/crates/screenpipe-core/src/memories/external_sync.rs b/crates/screenpipe-core/src/memories/external_sync.rs
index a3b8bf2d9..f25680443 100644
--- a/crates/screenpipe-core/src/memories/external_sync.rs
+++ b/crates/screenpipe-core/src/memories/external_sync.rs
@@ -68,6 +68,13 @@ pub struct Destination {
pub display_name: &'static str,
/// Filename inside the integration's home dir we write to.
pub filename: &'static str,
+ /// Optional sidecar file (same dir as `filename`) that holds the full
+ /// digest. When set, the marker block in the outer file only contains
+ /// an `@<sidecar_filename>` reference — used for assistants that
+ /// natively resolve file imports (Claude Code's `@path` syntax). This
+ /// keeps the outer file small and hand-editable while screenpipe owns
+ /// the sidecar end-to-end.
+ pub sidecar_filename: Option<&'static str>,
}
impl Destination {
@@ -75,17 +82,23 @@ impl Destination {
id: "claude-code",
display_name: "Claude Code",
filename: "CLAUDE.md",
+ sidecar_filename: Some("screenpipe-memories.md"),
};
pub const CODEX: Destination = Destination {
id: "codex",
display_name: "Codex CLI",
filename: "AGENTS.md",
+ sidecar_filename: None,
};
pub fn target_path(&self, home: &Path) -> PathBuf {
home.join(self.filename)
}
+
+ pub fn sidecar_path(&self, home: &Path) -> Option<PathBuf> {
+ self.sidecar_filename.map(|f| home.join(f))
+ }
}
/// Bound how big the rendered block can get. Above ~200 entries the
@@ -93,12 +106,38 @@ impl Destination {
/// budget. Beyond the cap we drop low-importance rows first.
pub const MAX_ENTRIES_PER_DIGEST: usize = 200;
-/// Build the body that will live *inside* the marker block (no markers
-/// themselves). Pure — no I/O.
+/// Build the body that will live *inside* the marker block in the outer
+/// file (`CLAUDE.md` / `AGENTS.md`). Pure — no I/O.
+///
+/// For destinations with a sidecar (Claude Code), this returns a short
+/// `@<sidecar>` import reference so the actual digest stays in its own
+/// file. For destinations without sidecar support (Codex), this is the
+/// full digest inline — same shape as before.
+pub fn render_block_body(entries: &[MemoryEntry], dest: &Destination) -> String {
+ if let Some(sidecar) = dest.sidecar_filename {
+ // `@<relative-path>` is Claude Code's import syntax. Resolved
+ // relative to the file containing the directive, so as long as
+ // the sidecar lives alongside CLAUDE.md this works regardless of
+ // where the user's home dir actually is.
+ return format!(
+ "## screenpipe memories\n\n\
+ screenpipe writes durable memory facts to the sidecar below. \
+ Manage them in the screenpipe app — the file is rewritten \
+ on every sync.\n\n\
+ @{}\n",
+ sidecar
+ );
+ }
+ render_digest(entries, dest)
+}
+
+/// Build the full memory digest. Used as the body of the sidecar file
+/// (when the destination supports imports) and as the inline marker-block
+/// body otherwise. Pure — no I/O.
///
/// Sorting: importance DESC, then updated_at DESC (newest tiebreak).
/// Capped at [`MAX_ENTRIES_PER_DIGEST`] entries.
-pub fn render_block_body(entries: &[MemoryEntry], dest: &Destination) -> String {
+pub fn render_digest(entries: &[MemoryEntry], dest: &Destination) -> String {
let mut sorted: Vec<&MemoryEntry> = entries.iter().collect();
sorted.sort_by(|a, b| {
b.importance
@@ -210,26 +249,39 @@ pub enum SyncOutcome {
Skipped { reason: &'static str },
}
-/// Write the digest into `target_path` atomically. Returns whether the
-/// file changed (so the scheduler can debounce no-op writes).
+/// Write the marker-spliced digest into `target_path` atomically.
+/// Preserves any pre-existing content outside the marker block byte for
+/// byte. Returns whether the file changed (so the scheduler can debounce
+/// no-op writes).
///
/// Atomicity: we write to a sibling temp file then `rename` it onto the
/// target. `rename` is atomic on POSIX and on NTFS for same-volume
/// moves, which is what we have here (sibling files in the same dir).
pub fn write_atomic(target_path: &Path, body: &str) -> std::io::Result<bool> {
+ let existing = std::fs::read_to_string(target_path).unwrap_or_default();
+ let next = splice_block(&existing, body);
+ write_file_if_changed(target_path, &next)
+}
+
+/// Write `body` to `target_path` atomically, replacing the entire file
+/// contents. Used for screenpipe-owned sidecar files where there's no
+/// hand-edited content to preserve. Returns whether the file changed.
+pub fn write_atomic_full(target_path: &Path, body: &str) -> std::io::Result<bool> {
+ write_file_if_changed(target_path, body)
+}
+
+fn write_file_if_changed(target_path: &Path, next: &str) -> std::io::Result<bool> {
if let Some(parent) = target_path.parent() {
std::fs::create_dir_all(parent)?;
}
let existing = std::fs::read_to_string(target_path).unwrap_or_default();
- let next = splice_block(&existing, body);
-
if next == existing {
return Ok(false);
}
let tmp = sibling_tmp_path(target_path);
- std::fs::write(&tmp, &next)?;
+ std::fs::write(&tmp, next)?;
// On Windows, `rename` fails if the destination exists *and* the
// source is on a different volume. Both same-volume here, so the
// plain rename works on every platform we support.
@@ -268,13 +320,13 @@ mod tests {
}
#[test]
- fn sorts_by_importance_then_updated_at() {
+ fn digest_sorts_by_importance_then_updated_at() {
let entries = vec![
entry("low recent", 0.1, "2026-01-02T00:00:00Z"),
entry("high old", 0.9, "2026-01-01T00:00:00Z"),
entry("high recent", 0.9, "2026-01-03T00:00:00Z"),
];
- let body = render_block_body(&entries, &Destination::CLAUDE_CODE);
+ let body = render_digest(&entries, &Destination::CLAUDE_CODE);
let high_recent_idx = body.find("high recent").unwrap();
let high_old_idx = body.find("high old").unwrap();
let low_recent_idx = body.find("low recent").unwrap();
@@ -283,21 +335,69 @@ mod tests {
}
#[test]
- fn caps_at_max_entries() {
+ fn digest_caps_at_max_entries() {
let entries: Vec<MemoryEntry> = (0..MAX_ENTRIES_PER_DIGEST + 50)
.map(|i| entry(&format!("m{}", i), 0.5, "2026-01-01T00:00:00Z"))
.collect();
- let body = render_block_body(&entries, &Destination::CLAUDE_CODE);
+ let body = render_digest(&entries, &Destination::CLAUDE_CODE);
let bullet_count = body.matches("\n- ").count();
assert_eq!(bullet_count, MAX_ENTRIES_PER_DIGEST);
}
#[test]
- fn renders_empty_state() {
- let body = render_block_body(&[], &Destination::CLAUDE_CODE);
+ fn digest_renders_empty_state() {
+ let body = render_digest(&[], &Destination::CLAUDE_CODE);
assert!(body.contains("no memories yet"));
}
+ #[test]
+ fn block_body_for_claude_is_import_reference_not_full_digest() {
+ // Claude Code resolves `@<path>` imports, so the outer file's
+ // marker block should be a tiny reference. The full digest lives
+ // in the sidecar. Crucially the memory contents themselves must
+ // NOT appear inline in CLAUDE.md.
+ let entries = vec![entry("secret memory body", 0.9, "2026-01-01T00:00:00Z")];
+ let body = render_block_body(&entries, &Destination::CLAUDE_CODE);
+ assert!(
+ body.contains("@screenpipe-memories.md"),
+ "expected import reference, got:\n{}",
+ body
+ );
+ assert!(
+ !body.contains("secret memory body"),
+ "memory contents leaked into outer block:\n{}",
+ body
+ );
+ }
+
+ #[test]
+ fn block_body_for_codex_is_full_digest_inline() {
+ // Codex has no `@import` equivalent, so we keep its existing
+ // inline-digest behavior untouched.
+ let entries = vec![entry("codex inline content", 0.9, "2026-01-01T00:00:00Z")];
+ let body = render_block_body(&entries, &Destination::CODEX);
+ assert!(
+ body.contains("codex inline content"),
+ "codex destination must inline the digest:\n{}",
+ body
+ );
+ assert!(
+ !body.contains('@'),
+ "codex outer block must not contain @import directives:\n{}",
+ body
+ );
+ }
+
+ #[test]
+ fn sidecar_path_set_for_claude_unset_for_codex() {
+ let home = std::path::Path::new("/tmp/fake-home");
+ assert_eq!(
+ Destination::CLAUDE_CODE.sidecar_path(home),
+ Some(home.join("screenpipe-memories.md"))
+ );
+ assert_eq!(Destination::CODEX.sidecar_path(home), None);
+ }
+
#[test]
fn splice_appends_when_no_marker_present() {
let existing = "# my notes\n\nsome user content\n";
@@ -416,6 +516,41 @@ mod tests {
assert_eq!(after.matches(&marker_start()).count(), 1);
}
+ #[test]
+ fn write_atomic_full_creates_new_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let target = dir.path().join("screenpipe-memories.md");
+ let changed = write_atomic_full(&target, "complete owned body").unwrap();
+ assert!(changed);
+ let contents = std::fs::read_to_string(&target).unwrap();
+ assert_eq!(contents, "complete owned body");
+ }
+
+ #[test]
+ fn write_atomic_full_overwrites_entire_file() {
+ // Sidecar files are screenpipe-owned end-to-end — no splice.
+ // Anything that was in the file before is replaced.
+ let dir = tempfile::tempdir().unwrap();
+ let target = dir.path().join("screenpipe-memories.md");
+ std::fs::write(&target, "stale content from a previous version\n").unwrap();
+
+ let changed = write_atomic_full(&target, "fresh full body").unwrap();
+ assert!(changed);
+ let contents = std::fs::read_to_string(&target).unwrap();
+ assert_eq!(contents, "fresh full body");
+ assert!(!contents.contains("stale content"));
+ }
+
+ #[test]
+ fn write_atomic_full_is_idempotent_on_disk() {
+ let dir = tempfile::tempdir().unwrap();
+ let target = dir.path().join("screenpipe-memories.md");
+ let first = write_atomic_full(&target, "same body").unwrap();
+ let second = write_atomic_full(&target, "same body").unwrap();
+ assert!(first);
+ assert!(!second, "second write with identical body must be a no-op");
+ }
+
#[test]
fn write_atomic_leaves_no_temp_sibling_after_success() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/screenpipe-engine/src/external_memory_sync.rs b/crates/screenpipe-engine/src/external_memory_sync.rs
index a9d1933f0..f8b032940 100644
--- a/crates/screenpipe-engine/src/external_memory_sync.rs
+++ b/crates/screenpipe-engine/src/external_memory_sync.rs
@@ -32,7 +32,8 @@ use std::time::Duration;
use anyhow::Result;
use screenpipe_connect::connections::{load_connection, SavedConnection};
use screenpipe_core::memories::external_sync::{
- render_block_body, write_atomic, Destination, MemoryEntry, SyncOutcome,
+ render_block_body, render_digest, write_atomic, write_atomic_full, Destination, MemoryEntry,
+ SyncOutcome,
};
use screenpipe_db::DatabaseManager;
use screenpipe_secrets::SecretStore;
@@ -310,23 +311,37 @@ fn apply(
let home = resolver(credentials)?;
let target = dest.target_path(&home);
- let body = render_block_body(entries, dest);
- let changed = write_atomic(&target, &body)
+ // Outer file (CLAUDE.md / AGENTS.md) gets the marker-spliced block.
+ // For destinations with a sidecar that's just an `@import` reference;
+ // for the others it's the full digest inline.
+ let block_body = render_block_body(entries, dest);
+ let outer_changed = write_atomic(&target, &block_body)
.map_err(|e| anyhow::anyhow!("write {}: {}", target.display(), e))?;
- if changed {
+ // Sidecar file (when supported) holds the full digest. It's fully
+ // screenpipe-owned — no hand-edited content to preserve — so we
+ // rewrite it whole.
+ let sidecar_changed = if let Some(sidecar) = dest.sidecar_path(&home) {
+ let sidecar_body = render_digest(entries, dest);
+ write_atomic_full(&sidecar, &sidecar_body)
+ .map_err(|e| anyhow::anyhow!("write {}: {}", sidecar.display(), e))?
+ } else {
+ false
+ };
+
+ let entries_used = entries
+ .len()
+ .min(screenpipe_core::memories::external_sync::MAX_ENTRIES_PER_DIGEST);
+
+ if outer_changed || sidecar_changed {
Ok(SyncOutcome::Wrote {
path: target,
- entries: entries
- .len()
- .min(screenpipe_core::memories::external_sync::MAX_ENTRIES_PER_DIGEST),
+ entries: entries_used,
})
} else {
Ok(SyncOutcome::Unchanged {
path: target,
- entries: entries
- .len()
- .min(screenpipe_core::memories::external_sync::MAX_ENTRIES_PER_DIGEST),
+ entries: entries_used,
})
}
}
@@ -422,10 +437,33 @@ mod tests {
SyncOutcome::Wrote { path, entries: n } => {
assert_eq!(n, 1);
assert!(path.ends_with("CLAUDE.md"));
- let body = std::fs::read_to_string(&path).unwrap();
- assert!(body.contains("user prefers bun over npm"));
- assert!(body.contains(&marker_start()));
- assert!(body.contains(&marker_end()));
+
+ // Outer CLAUDE.md must be the slim marker block + @import,
+ // not the memory body itself. This is the whole point of
+ // the sidecar split.
+ let outer = std::fs::read_to_string(&path).unwrap();
+ assert!(outer.contains(&marker_start()));
+ assert!(outer.contains(&marker_end()));
+ assert!(
+ outer.contains("@screenpipe-memories.md"),
+ "outer file missing @import reference:\n{}",
+ outer
+ );
+ assert!(
+ !outer.contains("user prefers bun over npm"),
+ "memory body leaked into outer file:\n{}",
+ outer
+ );
+
+ // Sidecar lives alongside CLAUDE.md and holds the digest.
+ let sidecar = dir.path().join("screenpipe-memories.md");
+ assert!(sidecar.exists(), "sidecar file was not created");
+ let sidecar_body = std::fs::read_to_string(&sidecar).unwrap();
+ assert!(
+ sidecar_body.contains("user prefers bun over npm"),
+ "sidecar missing memory body:\n{}",
+ sidecar_body
+ );
}
other => panic!("expected Wrote, got {:?}", other),
}
@@ -454,6 +492,9 @@ mod tests {
#[test]
fn apply_reports_change_when_entries_shift() {
+ // For Claude Code the outer CLAUDE.md @import line is identical
+ // regardless of entry count — but the sidecar body changes when
+ // entries do, so the overall `apply` must still report a write.
let dir = tempfile::tempdir().unwrap();
let creds = serde_json::Map::new();
let resolver = {
@@ -478,6 +519,11 @@ mod tests {
SyncOutcome::Wrote { entries: n, .. } => assert_eq!(n, 2),
other => panic!("expected Wrote on second apply, got {:?}", other),
}
+
+ // Sidecar must reflect the new entry set.
+ let sidecar = std::fs::read_to_string(dir.path().join("screenpipe-memories.md")).unwrap();
+ assert!(sidecar.contains("fact A"));
+ assert!(sidecar.contains("fact B"));
}
#[test]
@@ -596,9 +642,15 @@ mod tests {
Ok(SyncOutcome::Wrote { path, entries: n }) => {
assert_eq!(n, 2);
assert_eq!(path, target_dir.join("CLAUDE.md"));
- let body = std::fs::read_to_string(&path).unwrap();
- assert!(body.contains("first fact"));
- assert!(body.contains("second fact"));
+ // Outer CLAUDE.md only carries the import directive.
+ let outer = std::fs::read_to_string(&path).unwrap();
+ assert!(outer.contains("@screenpipe-memories.md"));
+ assert!(!outer.contains("first fact"));
+ // The memory bodies land in the sidecar.
+ let sidecar =
+ std::fs::read_to_string(target_dir.join("screenpipe-memories.md")).unwrap();
+ assert!(sidecar.contains("first fact"));
+ assert!(sidecar.contains("second fact"));
}
other => panic!("expected Wrote, got {:?}", other),
}