From a7603f59305a242a1962a6f7bb2e004424366e6d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 30 Jun 2026 11:32:41 +0000 Subject: [PATCH] feat(memory): add transport = "command" for non-git memory sync (S3/rclone/scp/USB) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Gap #4 shipped a git-remote transport; the encrypted blob is the real unit and git is just one way to move it. This adds a second, transport-agnostic option so you're not locked into git: set `transport = "command"` in ~/.kit/sync.toml with push_cmd / pull_cmd, and kit runs your command with the encrypted blob path exposed as $KIT_MEMORY_BLOB. [memory.sync] transport = "command" push_cmd = "aws s3 cp \"$KIT_MEMORY_BLOB\" s3://my-bucket/kit-memory.enc" pull_cmd = "aws s3 cp s3://my-bucket/kit-memory.enc \"$KIT_MEMORY_BLOB\"" Same guards as the git transport: the command is read ONLY from the LOCAL ~/.kit/sync.toml (never the project tree, so a cloned repo can't inject it), the payload stays AES-256-GCM encrypted (the store sees only ciphertext), and it's opt-in. push encrypts → runs push_cmd; pull runs pull_cmd → merges (last-write- wins) if a blob arrived, else reports "not found". SyncConfig gains a `transport` discriminator (git | command); push/pull branch on it; result field `remote` → `target` (the URL, or "command transport"). Help text shows both forms. 3 new tests (config validation, cp-based round trip, empty-pull) over the existing git ones. 1948 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 9 +++ src/commands/memory.ts | 13 ++-- src/memory/remote-sync.test.ts | 105 ++++++++++++++++++++++++++++++- src/memory/remote-sync.ts | 110 ++++++++++++++++++++++++--------- 4 files changed, 203 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47d7d750..4cffb4d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). AES-256-GCM encrypted (the remote sees only ciphertext; passphrase via `KIT_MEMORY_PASSPHRASE`, never stored); (4) fully opt-in — no config, no sync. Zero new dependencies (git + `node:crypto`). +- **Memory sync: a `transport = "command"` option for non-git stores + (S3/rclone/scp/USB).** You're not locked into a git remote — set + `transport = "command"` in `~/.kit/sync.toml` with `push_cmd`/`pull_cmd`, and kit + runs your command with the encrypted blob path exposed as `$KIT_MEMORY_BLOB` + (e.g. `aws s3 cp "$KIT_MEMORY_BLOB" s3://…`, `scp`, `rclone`). Same guards + apply: the command is read only from the LOCAL `~/.kit/sync.toml` (never the + project tree, so a cloned repo can't inject it), the payload is encrypted, and + it's opt-in. The blob is the real unit; git and command are just two ways to + move it. ### Security diff --git a/src/commands/memory.ts b/src/commands/memory.ts index ce24ca75..f3a37909 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -348,9 +348,14 @@ async function memSync(): Promise { function syncNotConfigured(): boolean { console.error( `${c.red}private memory sync is not configured${c.reset}\n` + - `${c.dim}create ${getSyncConfigPath()} (LOCAL — never committed) with:${c.reset}\n` + + `${c.dim}create ${getSyncConfigPath()} (LOCAL — never committed) with EITHER a git remote:${c.reset}\n` + ` [memory.sync]\n` + ` remote = "git@github.com:you/your-private-memory.git"\n` + + `${c.dim}...or your own transport command ($KIT_MEMORY_BLOB is the encrypted blob path):${c.reset}\n` + + ` [memory.sync]\n` + + ` transport = "command"\n` + + ` push_cmd = "scp \\"$KIT_MEMORY_BLOB\\" user@server:/srv/kit-memory.enc"\n` + + ` pull_cmd = "scp user@server:/srv/kit-memory.enc \\"$KIT_MEMORY_BLOB\\""\n` + `${c.dim}then set KIT_MEMORY_PASSPHRASE and run \`kit memory push\` / \`kit memory pull\`.${c.reset}`, ); return false; @@ -376,7 +381,7 @@ async function memPush(): Promise { const r = pushMemory(cfg, pass, getCurrentProjectRoot()); console.log( r.pushed - ? `${c.green}✓${c.reset} pushed encrypted memory → ${c.bold}${r.remote}${c.reset} ${c.dim}(${r.file})${c.reset}` + ? `${c.green}✓${c.reset} pushed encrypted memory → ${c.bold}${r.target}${c.reset} ${c.dim}(${r.file})${c.reset}` : `${c.dim}already up to date — nothing to push${c.reset}`, ); return true; @@ -400,13 +405,13 @@ async function memPull(): Promise { const r = pullMemory(cfg, pass, getCurrentProjectRoot()); if (!r.found) { console.log( - `${c.dim}no memory blob on ${r.remote} yet — push from another machine first${c.reset}`, + `${c.dim}no memory blob at ${r.target} yet — push from another machine first${c.reset}`, ); return true; } const m = r.merge!; console.log( - `${c.green}✓${c.reset} pulled ${c.bold}${m.messages}${c.reset} messages + ${m.toolUses} tool-uses · ${m.sessions} sessions · ${m.pending} pending · ${m.threads} copilots ${c.dim}from ${r.remote}${c.reset}`, + `${c.green}✓${c.reset} pulled ${c.bold}${m.messages}${c.reset} messages + ${m.toolUses} tool-uses · ${m.sessions} sessions · ${m.pending} pending · ${m.threads} copilots ${c.dim}from ${r.target}${c.reset}`, ); console.log( `${c.dim}last-write-wins on sessions; file_index (this machine's index state) left untouched${c.reset}`, diff --git a/src/memory/remote-sync.test.ts b/src/memory/remote-sync.test.ts index 9289ab3d..b8e068bc 100644 --- a/src/memory/remote-sync.test.ts +++ b/src/memory/remote-sync.test.ts @@ -106,7 +106,12 @@ describe("remote-sync — push → pull round trip over a git remote", () => { const marker = "gap4-roundtrip-marker-xyz"; try { execFileSync("git", ["init", "--bare", "-q", bare]); - const cfg: SyncConfig = { remote: bare, branch: "main", file: "memory.enc" }; + const cfg: SyncConfig = { + transport: "git", + remote: bare, + branch: "main", + file: "memory.enc", + }; // --- machine A: seed a message, then push --- process.env.KIT_MEMORY_DIR = machineA; @@ -160,7 +165,11 @@ describe("remote-sync — push → pull round trip over a git remote", () => { try { execFileSync("git", ["init", "--bare", "-q", bare]); process.env.KIT_MEMORY_DIR = machine; - const r = pullMemory({ remote: bare, branch: "main", file: "memory.enc" }, PASS, proj); + const r = pullMemory( + { transport: "git", remote: bare, branch: "main", file: "memory.enc" }, + PASS, + proj, + ); assert.equal(r.found, false); } finally { if (prevDir === undefined) delete process.env.KIT_MEMORY_DIR; @@ -171,3 +180,95 @@ describe("remote-sync — push → pull round trip over a git remote", () => { } }); }); + +describe("remote-sync — command transport (bring-your-own move: S3/rclone/scp/USB)", () => { + it("loadSyncConfig requires push_cmd + pull_cmd for transport=command", () => { + const dir = mkdtempSync(join(tmpdir(), "kit-cmdcfg-")); + const prev = process.env.KIT_MEMORY_DIR; + process.env.KIT_MEMORY_DIR = dir; + try { + writeFileSync(getSyncConfigPath(), '[memory.sync]\ntransport = "command"\n'); + assert.throws(() => loadSyncConfig(), /push_cmd and pull_cmd/); + writeFileSync( + getSyncConfigPath(), + '[memory.sync]\ntransport = "command"\npush_cmd = "true"\npull_cmd = "true"\n', + ); + const cfg = loadSyncConfig(); + assert.equal(cfg?.transport, "command"); + assert.equal(cfg?.pushCmd, "true"); + assert.equal(cfg?.pullCmd, "true"); + } finally { + if (prev === undefined) delete process.env.KIT_MEMORY_DIR; + else process.env.KIT_MEMORY_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("push runs push_cmd over the blob; pull runs pull_cmd then merges (round trip via a plain file)", () => { + const store = mkdtempSync(join(tmpdir(), "kit-store-")); + const storeBlob = join(store, "memory.enc"); // stands in for S3/scp target + const machineA = mkdtempSync(join(tmpdir(), "kit-cA-")); + const machineB = mkdtempSync(join(tmpdir(), "kit-cB-")); + const proj = mkdtempSync(join(tmpdir(), "kit-cproj-")); + const prevDir = process.env.KIT_MEMORY_DIR; + const marker = "cmd-transport-marker-zzz"; + // The "transport" is just `cp` to/from a fixed path — the same shape as + // `aws s3 cp`, `rclone copyto`, or `scp`, driven by $KIT_MEMORY_BLOB. + const cfg: SyncConfig = { + transport: "command", + file: "memory.enc", + pushCmd: `cp "$KIT_MEMORY_BLOB" "${storeBlob}"`, + pullCmd: `cp "${storeBlob}" "$KIT_MEMORY_BLOB"`, + }; + try { + process.env.KIT_MEMORY_DIR = machineA; + const dbA = openMemoryDb(); + upsertSession(dbA, { sessionId: "s-cmd", harness: "claude-code", project: "p" }); + insertMessage(dbA, { + uuid: "u-cmd", + sessionId: "s-cmd", + type: "message", + role: "user", + content: marker, + }); + dbA.close(); + + const pushed = pushMemory(cfg, PASS, proj); + assert.equal(pushed.pushed, true); + assert.ok(existsSync(storeBlob), "push_cmd deposited the encrypted blob in the store"); + + process.env.KIT_MEMORY_DIR = machineB; + const r = pullMemory(cfg, PASS, proj); + assert.equal(r.found, true); + const dbB = openMemoryDb(); + const hits = searchMessages(dbB, "marker"); + dbB.close(); + assert.ok(hits.some((h) => (h.content ?? "").includes(marker))); + } finally { + if (prevDir === undefined) delete process.env.KIT_MEMORY_DIR; + else process.env.KIT_MEMORY_DIR = prevDir; + for (const d of [store, machineA, machineB, proj]) { + rmSync(d, { recursive: true, force: true }); + } + } + }); + + it("pull reports 'not found' when the pull_cmd produces no blob", () => { + const machine = mkdtempSync(join(tmpdir(), "kit-cM-")); + const proj = mkdtempSync(join(tmpdir(), "kit-cproj2-")); + const prevDir = process.env.KIT_MEMORY_DIR; + try { + process.env.KIT_MEMORY_DIR = machine; + const r = pullMemory( + { transport: "command", file: "memory.enc", pushCmd: "true", pullCmd: "true" }, + PASS, + proj, + ); + assert.equal(r.found, false); + } finally { + if (prevDir === undefined) delete process.env.KIT_MEMORY_DIR; + else process.env.KIT_MEMORY_DIR = prevDir; + for (const d of [machine, proj]) rmSync(d, { recursive: true, force: true }); + } + }); +}); diff --git a/src/memory/remote-sync.ts b/src/memory/remote-sync.ts index 11a2981d..24571a97 100644 --- a/src/memory/remote-sync.ts +++ b/src/memory/remote-sync.ts @@ -19,7 +19,7 @@ * * Deterministic, zero-LLM, zero new dependencies (node:child_process + git). */ -import { execFileSync } from "node:child_process"; +import { execFileSync, execSync } from "node:child_process"; import { existsSync, readFileSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -29,13 +29,23 @@ import { backupEncrypted } from "./backup.js"; import { syncFromExport } from "./sync.js"; import type { MergeResult } from "./merge.js"; +/** How the encrypted blob travels. `git` = a private remote; `command` = your own shell command (S3/rclone/scp/USB/…). */ +export type SyncTransport = "git" | "command"; + export interface SyncConfig { + transport: SyncTransport; + /** Blob filename (default "memory.enc"). A bare name — no path. */ + file: string; + // git transport /** The private git remote that stores the encrypted blob. */ - remote: string; + remote?: string; /** Branch to push/pull (default "main"). */ - branch: string; - /** Blob filename within the remote (default "memory.enc"). A bare name — no path. */ - file: string; + branch?: string; + // command transport — kit writes/reads the blob at $KIT_MEMORY_BLOB and runs your command. + /** Shell command that UPLOADS the blob at $KIT_MEMORY_BLOB to your store. */ + pushCmd?: string; + /** Shell command that DOWNLOADS the blob to $KIT_MEMORY_BLOB from your store. */ + pullCmd?: string; } const DEFAULT_BRANCH = "main"; @@ -64,14 +74,27 @@ export function loadSyncConfig(): SyncConfig | null { const memory = (root.memory ?? {}) as Record; // Accept either `[memory.sync]` (preferred) or a top-level `[sync]`. const s = (memory.sync ?? root.sync ?? {}) as Record; - const remote = typeof s.remote === "string" ? s.remote.trim() : ""; - if (!remote) return null; - const branch = typeof s.branch === "string" && s.branch.trim() ? s.branch.trim() : DEFAULT_BRANCH; - const file = typeof s.file === "string" && s.file.trim() ? s.file.trim() : DEFAULT_FILE; + const str = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); + + const file = str(s.file) || DEFAULT_FILE; if (file.includes("/") || file.includes("\\") || file.includes("..")) { throw new Error(`invalid [memory.sync] file "${file}" — must be a bare filename`); } - return { remote, branch, file }; + + const transport: SyncTransport = s.transport === "command" ? "command" : "git"; + if (transport === "command") { + const pushCmd = str(s.push_cmd); + const pullCmd = str(s.pull_cmd); + if (!pushCmd || !pullCmd) { + throw new Error('[memory.sync] transport = "command" requires both push_cmd and pull_cmd'); + } + return { transport, file, pushCmd, pullCmd }; + } + + const remote = str(s.remote); + if (!remote) return null; // git transport with no remote → treat as unconfigured + const branch = str(s.branch) || DEFAULT_BRANCH; + return { transport, file, remote, branch }; } /** @@ -133,22 +156,37 @@ function git(args: string[], cwd: string): string { * remote/branch doesn't exist yet (first push), fall back to a fresh repo wired to * the remote so the initial push creates the branch. */ -function cloneOrInit(cfg: SyncConfig, dir: string): void { +function cloneOrInit(remote: string, branch: string, dir: string): void { try { - git(["clone", "--depth", "1", "--branch", cfg.branch, cfg.remote, "."], dir); + git(["clone", "--depth", "1", "--branch", branch, remote, "."], dir); return; } catch { // empty remote or missing branch — initialize a fresh repo targeting it } git(["init", "-q"], dir); - git(["remote", "add", "origin", cfg.remote], dir); - git(["checkout", "-q", "-B", cfg.branch], dir); + git(["remote", "add", "origin", remote], dir); + git(["checkout", "-q", "-B", branch], dir); +} + +/** + * Run a user-supplied transport command with the blob path exposed as + * $KIT_MEMORY_BLOB. The command comes ONLY from ~/.kit/sync.toml (a local file + * the operator owns), never the project tree — so a cloned repo can't inject it. + * Runs through the default shell so an operator can write `aws s3 cp …` etc. + */ +function runTransportCmd(cmd: string, blobPath: string): void { + execSync(cmd, { + env: { ...process.env, KIT_MEMORY_BLOB: blobPath }, + stdio: ["ignore", "inherit", "inherit"], + timeout: 120_000, + }); } export interface PushResult { - remote: string; + /** Display label for where the blob went (the remote URL, or "command transport"). */ + target: string; file: string; - /** False when the encrypted blob was byte-identical to what's already on the remote. */ + /** False when the encrypted blob was byte-identical to what's already on the remote (git only). */ pushed: boolean; } @@ -158,35 +196,42 @@ export interface PushResult { * commits and pushes only when it changed (so a no-op push is free and quiet). */ export function pushMemory(cfg: SyncConfig, passphrase: string, projectRoot: string): PushResult { - assertRemoteNotProjectOrigin(cfg.remote, projectRoot); const dir = mkdtempSync(join(tmpdir(), "kit-memsync-")); try { - cloneOrInit(cfg, dir); + if (cfg.transport === "command") { + const blob = join(dir, cfg.file); + backupEncrypted(passphrase, getMemoryDbPath(), blob); + runTransportCmd(cfg.pushCmd!, blob); + return { target: "command transport", file: cfg.file, pushed: true }; + } + // git transport — clone into the (empty) dir FIRST, then write the blob inside it. + assertRemoteNotProjectOrigin(cfg.remote!, projectRoot); + cloneOrInit(cfg.remote!, cfg.branch ?? DEFAULT_BRANCH, dir); backupEncrypted(passphrase, getMemoryDbPath(), join(dir, cfg.file)); git(["add", "--", cfg.file], dir); const dirty = git(["status", "--porcelain"], dir).trim(); - if (!dirty) return { remote: cfg.remote, file: cfg.file, pushed: false }; + if (!dirty) return { target: cfg.remote!, file: cfg.file, pushed: false }; // Identify the commit so a fresh-init repo has an author; rely on the user's // git identity, falling back to a neutral one only if git has none configured. ensureCommitIdentity(dir); git(["commit", "-q", "-m", "kit memory sync", "--", cfg.file], dir); - git(["push", "-q", "origin", `HEAD:${cfg.branch}`], dir); - return { remote: cfg.remote, file: cfg.file, pushed: true }; + git(["push", "-q", "origin", `HEAD:${cfg.branch ?? DEFAULT_BRANCH}`], dir); + return { target: cfg.remote!, file: cfg.file, pushed: true }; } finally { rmSync(dir, { recursive: true, force: true }); } } export interface PullResult { - remote: string; + target: string; file: string; - /** False when the remote has no blob yet (nothing to merge). */ + /** False when the store has no blob yet (nothing to merge). */ found: boolean; merge?: MergeResult; } /** - * Fetch the encrypted blob from the private remote and merge it into the local + * Fetch the encrypted blob from the configured store and merge it into the local * store (last-write-wins via mergeDb). The passphrase decrypts the blob; a raw * `.db` blob (unusual for this transport) needs none. */ @@ -195,16 +240,25 @@ export function pullMemory( passphrase: string | undefined, projectRoot: string, ): PullResult { - assertRemoteNotProjectOrigin(cfg.remote, projectRoot); const dir = mkdtempSync(join(tmpdir(), "kit-memsync-")); try { - cloneOrInit(cfg, dir); const blob = join(dir, cfg.file); - if (!existsSync(blob)) return { remote: cfg.remote, file: cfg.file, found: false }; + let target: string; + if (cfg.transport === "command") { + // The pull command must DOWNLOAD the blob to $KIT_MEMORY_BLOB. A command + // that finds nothing simply leaves the path absent → found:false. + runTransportCmd(cfg.pullCmd!, blob); + target = "command transport"; + } else { + assertRemoteNotProjectOrigin(cfg.remote!, projectRoot); + cloneOrInit(cfg.remote!, cfg.branch ?? DEFAULT_BRANCH, dir); + target = cfg.remote!; + } + if (!existsSync(blob)) return { target, file: cfg.file, found: false }; const db = openMemoryDb(); try { const merge = syncFromExport(db, blob, { passphrase }); - return { remote: cfg.remote, file: cfg.file, found: true, merge }; + return { target, file: cfg.file, found: true, merge }; } finally { db.close(); }