@radaz-tech/recall 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "recall",
3
+ "owner": { "name": "recall" },
4
+ "metadata": { "description": "Recall: persistent memory for Claude Code" },
5
+ "plugins": [
6
+ {
7
+ "name": "recall",
8
+ "version": "1.0.0",
9
+ "source": "./plugin",
10
+ "description": "Persistent memory for Claude Code: each session picks up where the last one stopped."
11
+ }
12
+ ]
13
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Recall contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ <p align="center"><img src="assets/logo.svg" width="96" alt="Recall logo"></p>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <h1 align="center">Recall</h1>
4
+ <p align="center">Persistent memory for Claude Code. Each session picks up where the last one stopped.</p>
5
+
6
+ ---
7
+
8
+ Recall watches what Claude does in a session (the prompts and tool calls). At the end of each turn it compresses that activity into short, searchable **observations** and a **session summary**. The next session in the same folder starts with that memory injected, and Claude can search older memory through MCP tools.
9
+
10
+ Everything lives in one local SQLite file. There are no background services to keep alive and no vector server, and the core has zero npm dependencies.
11
+
12
+ ## What's in the box
13
+
14
+ | Part | What it does |
15
+ |---|---|
16
+ | `plugin/` | Claude Code plugin with hooks, an MCP server and the `recall` CLI (Node ≥ 22.13, zero dependencies) |
17
+ | `viewer/` | Next.js web viewer on `localhost:37800`: overview, live feed, search, project pages |
18
+ | `desktop/` | Tauri tray app. It spots new Claude sessions, asks whether to record them, and lets you browse memory by project and date |
19
+
20
+ ## How it works
21
+
22
+ ```
23
+ UserPromptSubmit ─► prompt saved
24
+ PostToolUse ─► tool event saved (raw, pending)
25
+ Stop ─► background process: pending events → claude -p (Haiku) → observations + summary
26
+ SessionStart ─► recent summaries + observations for this folder injected as context
27
+ MCP ─► recall_search · recall_get · recall_recent
28
+ ```
29
+
30
+ - **Storage:** `~/.recall/recall.db` (set `RECALL_HOME` to move it), SQLite in WAL mode, with FTS5 full-text search ranked by BM25.
31
+ - **Compression:** uses your own Claude login via the headless `claude` CLI, so no API key is needed. Failed batches stay pending and are retried at the next turn or session start. A crash never loses events.
32
+ - **Privacy:** anything inside `<private>…</private>` is replaced before it is stored. Injected `<system-reminder>` blocks are stripped. Capture can be turned off globally or per project.
33
+ - **Projects:** memory is keyed by the working folder's name.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ # in Claude Code
39
+ /plugin marketplace add <path-or-git-url-of-this-repo>
40
+ /plugin install recall@recall
41
+ ```
42
+
43
+ Restart Claude Code. That's it: memory builds as you work.
44
+
45
+ Optional: put the CLI on your PATH with `npm i -g @radaz-tech/recall` (or `npm link` in the repo root) (or run `node plugin/scripts/recall.mjs`).
46
+
47
+ ## CLI
48
+
49
+ ```
50
+ recall status what Recall is doing right now
51
+ recall search <words> full-text search [--project p] [--type t]
52
+ recall recent [--today|--week] latest observations
53
+ recall show <id...> full detail
54
+ recall context preview what the next session here will see
55
+ recall projects per-project counts and activity bars
56
+ recall on | off [--project p|--here]
57
+ recall record <transcript.jsonl> save memory from a past session, offline
58
+ recall sessions Claude transcripts that can be recorded
59
+ recall compress process pending events now
60
+ recall config [key] [value] show or change settings
61
+ recall import [--from db] copy memory from claude-mem; re-run to sync new rows
62
+ recall export [--out file] JSON export
63
+ recall forget --project p --yes delete a project's memory
64
+ recall doctor check Node, FTS5, the claude CLI and the plugin
65
+ ```
66
+
67
+ ## Moving over from claude-mem
68
+
69
+ ```bash
70
+ recall import
71
+ ```
72
+
73
+ The import opens `~/.claude-mem/claude-mem.db` **read-only** and copies observations and session summaries, keeping their original timestamps. It records which rows it has copied, so running it again only adds new rows. You can keep both tools side by side while you switch, then uninstall the old one.
74
+
75
+ ## Settings
76
+
77
+ `~/.recall/settings.json`. Change values with `recall config <key> <value>`.
78
+
79
+ | Key | Default | Meaning |
80
+ |---|---|---|
81
+ | `enabled` | `true` | global capture switch |
82
+ | `projects` | `{}` | per-project override, `{"my-repo": "off"}` |
83
+ | `model` | `haiku` | model used for compression |
84
+ | `claudePath` | `claude` | path to the Claude CLI |
85
+ | `contextObservations` | `25` | observations injected at session start |
86
+ | `contextSummaries` | `3` | summaries injected at session start |
87
+ | `contextMaxChars` | `10000` | cap on injected context |
88
+ | `maxEventChars` | `4000` | per tool input/output before compression |
89
+ | `skipTools` | TodoWrite, … | tools never recorded |
90
+
91
+ ## Viewer
92
+
93
+ ```bash
94
+ cd viewer && npm install && npm run build && npm start # http://localhost:37800
95
+ ```
96
+
97
+ ## Desktop app
98
+
99
+ ```bash
100
+ cd desktop && cargo tauri build # or: cargo build --release
101
+ ```
102
+
103
+ ## Development
104
+
105
+ ```bash
106
+ npm test # node:test suite, uses a temp RECALL_HOME
107
+ ```
108
+
109
+ ## License
110
+
111
+ MIT
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" role="img" aria-labelledby="t">
2
+ <title id="t">Recall</title>
3
+ <rect width="128" height="128" rx="28" fill="#0f172a"/>
4
+ <!-- a loop that returns to its start: memory carried into the next session -->
5
+ <path d="M38 78a28 28 0 1 1 18 16" fill="none" stroke="#f59e0b" stroke-width="10" stroke-linecap="round"/>
6
+ <path d="M46 98l10-4-4-10" fill="none" stroke="#f59e0b" stroke-width="10" stroke-linecap="round" stroke-linejoin="round"/>
7
+ <circle cx="64" cy="62" r="9" fill="#e2e8f0"/>
8
+ </svg>
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@radaz-tech/recall",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Persistent memory for Claude Code. Local SQLite + FTS5, zero runtime dependencies.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "recall": "plugin/scripts/recall.mjs"
9
+ },
10
+ "engines": {
11
+ "node": ">=22.13"
12
+ },
13
+ "scripts": {
14
+ "test": "node --test tests/",
15
+ "viewer": "npm --prefix viewer run dev"
16
+ },
17
+ "files": [
18
+ "plugin/",
19
+ ".claude-plugin/",
20
+ "assets/logo.svg"
21
+ ],
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/ks-rdz-07/recall.git"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ }
29
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "recall",
3
+ "version": "1.0.0",
4
+ "description": "Persistent memory for Claude Code: each session picks up where the last one stopped. Local SQLite, full-text search, no services.",
5
+ "license": "MIT",
6
+ "keywords": ["memory", "context", "sqlite", "mcp", "hooks"]
7
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "mcpServers": {
3
+ "recall": {
4
+ "type": "stdio",
5
+ "command": "node",
6
+ "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/recall.mjs", "mcp"]
7
+ }
8
+ }
9
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "description": "Recall memory hooks",
3
+ "hooks": {
4
+ "SessionStart": [{ "matcher": "startup|resume|clear|compact", "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/recall.mjs\" hook session-start", "timeout": 30 }] }],
5
+ "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/recall.mjs\" hook prompt", "timeout": 15 }] }],
6
+ "PostToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/recall.mjs\" hook tool", "timeout": 15 }] }],
7
+ "PostToolUseFailure": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/recall.mjs\" hook tool", "timeout": 15 }] }],
8
+ "Stop": [{ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/recall.mjs\" hook stop", "timeout": 15 }] }],
9
+ "SessionEnd": [{ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/recall.mjs\" hook session-end", "timeout": 15 }] }]
10
+ }
11
+ }
@@ -0,0 +1,87 @@
1
+ // Turns raw tool events into structured observations + a turn summary via the headless Claude CLI.
2
+ import { spawnSync } from 'node:child_process';
3
+ import { claimEvents, finishEvents, lastPrompt, saveObservation, saveSummary, settings } from './db.mjs';
4
+
5
+ const SYSTEM = `You are a memory recorder for a coding assistant. You read a log of tool calls from one work turn
6
+ and write durable memory a future session will need. Ignore noise (directory listings, failed retries, trivia).
7
+ Reply with ONLY a JSON object, no prose, no code fences:
8
+ {"observations":[{"type":"decision|bugfix|feature|refactor|discovery|change","title":"<=12 words, specific",
9
+ "narrative":"2-4 sentences: what and why","facts":["short verifiable facts"],"files":["paths touched"],
10
+ "concepts":["keywords"]}],
11
+ "summary":{"request":"what the user asked","completed":"what got done","learned":"non-obvious findings",
12
+ "next_steps":"what remains"}}
13
+ Write 0-6 observations. If nothing is worth remembering, return {"observations":[],"summary":null}.`;
14
+
15
+ export function buildPrompt(prompt, events) {
16
+ const log = events
17
+ .map((e, i) => `### ${i + 1}. ${e.tool}\ninput: ${e.input}\noutput: ${e.output}`)
18
+ .join('\n\n');
19
+ return `User request: ${prompt || '(unknown)'}\n\nTool log:\n${log}`;
20
+ }
21
+
22
+ // Pull the first {...} JSON object out of model text, tolerating fences or stray prose.
23
+ export function parseModelJson(text) {
24
+ const s = String(text || '');
25
+ const start = s.indexOf('{');
26
+ const end = s.lastIndexOf('}');
27
+ if (start < 0 || end <= start) throw new Error('no JSON object in model output');
28
+ const obj = JSON.parse(s.slice(start, end + 1));
29
+ return { observations: Array.isArray(obj.observations) ? obj.observations : [], summary: obj.summary || null };
30
+ }
31
+
32
+ function askClaude(input, cfg) {
33
+ const run = (args, stdin, shell) => spawnSync(cfg.claudePath, args, {
34
+ input: stdin,
35
+ encoding: 'utf8',
36
+ timeout: 180_000,
37
+ maxBuffer: 16 * 1024 * 1024,
38
+ windowsHide: true,
39
+ shell,
40
+ env: { ...process.env, RECALL_CHILD: '1' }, // stops our own hooks firing inside the child session
41
+ });
42
+ const base = ['-p', '--model', cfg.model, '--output-format', 'json', '--no-session-persistence'];
43
+ let r = run([...base, '--tools', '', '--system-prompt', SYSTEM], input, false);
44
+ // npm installs ship claude as a .cmd shim that needs a shell; cmd mangles multi-line args, so send instructions on stdin.
45
+ if (r.error?.code === 'ENOENT' && process.platform === 'win32') r = run(base, `${SYSTEM}\n\n${input}`, true);
46
+ if (r.error) throw r.error;
47
+ if (r.status !== 0) throw new Error(`claude exited ${r.status}: ${(r.stderr || r.stdout || '').slice(0, 500)}`);
48
+ const envelope = JSON.parse(r.stdout);
49
+ if (envelope.is_error) throw new Error(`claude error: ${envelope.result}`);
50
+ return envelope.result;
51
+ }
52
+
53
+ // Process every pending event (optionally for one session). Failures put events back to pending.
54
+ const CHUNK = 40;
55
+
56
+ export function compress(db, sessionId, ask = askClaude, onProgress = () => {}) {
57
+ const cfg = settings();
58
+ const events = claimEvents(db, sessionId);
59
+ const bySession = Map.groupBy(events, (e) => e.session_id);
60
+ let saved = 0, failed = 0, done = 0, lastError = '';
61
+ // Long sessions are sent in chunks so one model call never gets an oversized log.
62
+ const jobs = [];
63
+ for (const [sid, all] of bySession) for (let i = 0; i < all.length; i += CHUNK) jobs.push([sid, all.slice(i, i + CHUNK)]);
64
+ for (const [sid, evs] of jobs) {
65
+ const ids = evs.map((e) => e.id);
66
+ try {
67
+ const out = parseModelJson(ask(buildPrompt(lastPrompt(db, sid), evs), cfg));
68
+ db.exec('BEGIN');
69
+ try {
70
+ for (const o of out.observations) if (saveObservation(db, sid, evs[0].project, o)) saved++;
71
+ saveSummary(db, sid, evs[0].project, out.summary);
72
+ finishEvents(db, ids, true);
73
+ db.exec('COMMIT');
74
+ } catch (e) {
75
+ db.exec('ROLLBACK');
76
+ throw e;
77
+ }
78
+ } catch (e) {
79
+ finishEvents(db, ids, false);
80
+ failed++;
81
+ lastError = e.message;
82
+ }
83
+ onProgress(++done, jobs.length);
84
+ }
85
+ if (failed) throw new Error(`${failed}/${jobs.length} batches failed, events kept for retry: ${lastError}`);
86
+ return saved;
87
+ }
@@ -0,0 +1,279 @@
1
+ // Storage: one SQLite file (node:sqlite, built into Node >= 22.13) with FTS5 full-text search.
2
+ import { DatabaseSync } from 'node:sqlite';
3
+ import { mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { join, basename } from 'node:path';
6
+
7
+ export const HOME = process.env.RECALL_HOME || join(homedir(), '.recall');
8
+
9
+ const DEFAULTS = {
10
+ enabled: true,
11
+ model: 'haiku', // model used to compress tool events into observations
12
+ claudePath: 'claude', // headless CLI used for compression (uses your Claude login)
13
+ contextObservations: 25, // observations injected at session start
14
+ contextSummaries: 3, // session summaries injected at session start
15
+ maxEventChars: 4000, // per tool input/output, before compression
16
+ contextMaxChars: 10000, // Claude Code moves larger hook output to a file, so stay under it
17
+ skipTools: ['TodoWrite', 'TaskCreate', 'TaskUpdate', 'ListMcpResourcesTool', 'AskUserQuestion', 'Skill'],
18
+ projects: {}, // per-project override: { "<folder name>": "on" | "off" }
19
+ };
20
+
21
+ export const SETTINGS_FILE = join(HOME, 'settings.json');
22
+
23
+ export function settings() {
24
+ try {
25
+ return { ...DEFAULTS, ...JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')) };
26
+ } catch {
27
+ return { ...DEFAULTS };
28
+ }
29
+ }
30
+
31
+ // Write only the keys that differ from defaults; atomic rename so a crash never leaves half a file.
32
+ export function saveSettings(patch) {
33
+ let current = {};
34
+ try { current = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')); } catch {}
35
+ const next = { ...current, ...patch };
36
+ mkdirSync(HOME, { recursive: true });
37
+ writeFileSync(SETTINGS_FILE + '.tmp', JSON.stringify(next, null, 2) + '\n');
38
+ renameSync(SETTINGS_FILE + '.tmp', SETTINGS_FILE);
39
+ return { ...DEFAULTS, ...next };
40
+ }
41
+
42
+ // A project override beats the global switch, so "off globally, on for one repo" works.
43
+ export function isEnabled(cfg, project) {
44
+ const o = cfg.projects?.[project];
45
+ return o ? o === 'on' : cfg.enabled !== false;
46
+ }
47
+
48
+ export const DEFAULT_SETTINGS = DEFAULTS;
49
+
50
+ // Project identity = the working directory's folder name (the same key the old store used, so imports line up).
51
+ export const projectOf = (cwd) => basename(String(cwd || process.cwd()).replace(/[\\/]+$/, '')) || 'unknown';
52
+ export const projectName = (project) => project;
53
+
54
+ const MIGRATIONS = [
55
+ `
56
+ CREATE TABLE sessions (
57
+ id TEXT PRIMARY KEY, project TEXT NOT NULL,
58
+ started_at INTEGER NOT NULL, ended_at INTEGER, prompt_count INTEGER NOT NULL DEFAULT 0
59
+ );
60
+ CREATE TABLE prompts (
61
+ id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, project TEXT NOT NULL,
62
+ text TEXT NOT NULL, created_at INTEGER NOT NULL
63
+ );
64
+ -- raw tool events waiting for compression; status 0=pending 1=done 2=claimed
65
+ CREATE TABLE events (
66
+ id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, project TEXT NOT NULL,
67
+ tool TEXT NOT NULL, input TEXT, output TEXT, created_at INTEGER NOT NULL,
68
+ status INTEGER NOT NULL DEFAULT 0, claimed_at INTEGER
69
+ );
70
+ CREATE INDEX events_pending ON events(status, session_id);
71
+ CREATE TABLE observations (
72
+ id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, project TEXT NOT NULL,
73
+ type TEXT NOT NULL, title TEXT NOT NULL, narrative TEXT NOT NULL DEFAULT '',
74
+ facts TEXT NOT NULL DEFAULT '[]', files TEXT NOT NULL DEFAULT '[]', concepts TEXT NOT NULL DEFAULT '[]',
75
+ created_at INTEGER NOT NULL
76
+ );
77
+ CREATE INDEX observations_project ON observations(project, created_at DESC);
78
+ CREATE TABLE summaries (
79
+ id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, project TEXT NOT NULL,
80
+ request TEXT NOT NULL DEFAULT '', completed TEXT NOT NULL DEFAULT '',
81
+ learned TEXT NOT NULL DEFAULT '', next_steps TEXT NOT NULL DEFAULT '',
82
+ created_at INTEGER NOT NULL
83
+ );
84
+ CREATE INDEX summaries_project ON summaries(project, created_at DESC);
85
+
86
+ CREATE VIRTUAL TABLE observations_fts USING fts5(
87
+ title, narrative, facts, concepts, files, content='observations', content_rowid='id', tokenize='porter unicode61'
88
+ );
89
+ CREATE TRIGGER observations_ai AFTER INSERT ON observations BEGIN
90
+ INSERT INTO observations_fts(rowid, title, narrative, facts, concepts, files)
91
+ VALUES (new.id, new.title, new.narrative, new.facts, new.concepts, new.files);
92
+ END;
93
+ CREATE TRIGGER observations_ad AFTER DELETE ON observations BEGIN
94
+ INSERT INTO observations_fts(observations_fts, rowid, title, narrative, facts, concepts, files)
95
+ VALUES ('delete', old.id, old.title, old.narrative, old.facts, old.concepts, old.files);
96
+ END;
97
+ `,
98
+ // v2: remember which rows came from an import so re-running it only copies new rows
99
+ `
100
+ CREATE TABLE imported (
101
+ source TEXT NOT NULL, kind TEXT NOT NULL, source_id TEXT NOT NULL, local_id INTEGER,
102
+ PRIMARY KEY (source, kind, source_id)
103
+ );
104
+ `,
105
+ ];
106
+
107
+ export function open(file = join(HOME, 'recall.db')) {
108
+ if (file !== ':memory:') mkdirSync(HOME, { recursive: true });
109
+ const db = new DatabaseSync(file);
110
+ db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;');
111
+ const version = db.prepare('PRAGMA user_version').get().user_version;
112
+ for (let v = version; v < MIGRATIONS.length; v++) {
113
+ db.exec('BEGIN');
114
+ try {
115
+ db.exec(MIGRATIONS[v]);
116
+ db.exec(`PRAGMA user_version = ${v + 1}`);
117
+ db.exec('COMMIT');
118
+ } catch (e) {
119
+ db.exec('ROLLBACK');
120
+ throw e;
121
+ }
122
+ }
123
+ return db;
124
+ }
125
+
126
+ const now = () => Date.now();
127
+
128
+ // Anything inside <private>...</private> never reaches the database.
129
+ // Injected harness/context blocks are stripped too, so memory never re-records its own injected text.
130
+ export const redact = (s) =>
131
+ s == null ? s : String(s)
132
+ .replace(/<private>[\s\S]*?<\/private>/gi, '[private]')
133
+ .replace(/<(system-reminder|recall-context)>[\s\S]*?<\/\1>/gi, '');
134
+
135
+ const clip = (s, n) => (s && s.length > n ? s.slice(0, n) + `\n…[${s.length - n} more chars]` : s);
136
+
137
+ export function touchSession(db, sessionId, project) {
138
+ db.prepare('INSERT OR IGNORE INTO sessions (id, project, started_at) VALUES (?, ?, ?)').run(sessionId, project, now());
139
+ }
140
+
141
+ export function addPrompt(db, sessionId, project, text) {
142
+ touchSession(db, sessionId, project);
143
+ db.prepare('INSERT INTO prompts (session_id, project, text, created_at) VALUES (?, ?, ?, ?)')
144
+ .run(sessionId, project, redact(text), now());
145
+ db.prepare('UPDATE sessions SET prompt_count = prompt_count + 1 WHERE id = ?').run(sessionId);
146
+ }
147
+
148
+ export function addEvent(db, sessionId, project, tool, input, output, maxChars = 4000) {
149
+ touchSession(db, sessionId, project);
150
+ const str = (v) => clip(redact(typeof v === 'string' ? v : JSON.stringify(v ?? null)), maxChars);
151
+ db.prepare('INSERT INTO events (session_id, project, tool, input, output, created_at) VALUES (?, ?, ?, ?, ?, ?)')
152
+ .run(sessionId, project, tool, str(input), str(output), now());
153
+ }
154
+
155
+ // Atomically claim pending events so two compressors never process the same rows.
156
+ // Claims older than 10 minutes are treated as abandoned (crashed compressor) and reclaimed.
157
+ export function claimEvents(db, sessionId) {
158
+ const stale = now() - 10 * 60 * 1000;
159
+ const where = sessionId ? 'AND session_id = ?' : '';
160
+ const args = sessionId ? [now(), stale, sessionId] : [now(), stale];
161
+ return db.prepare(
162
+ `UPDATE events SET status = 2, claimed_at = ?
163
+ WHERE (status = 0 OR (status = 2 AND claimed_at < ?)) ${where}
164
+ RETURNING id, session_id, project, tool, input, output, created_at`
165
+ ).all(...args).sort((a, b) => a.id - b.id);
166
+ }
167
+
168
+ export function finishEvents(db, ids, ok) {
169
+ if (!ids.length) return;
170
+ const q = ids.map(() => '?').join(',');
171
+ db.prepare(`UPDATE events SET status = ?, claimed_at = NULL WHERE id IN (${q})`).run(ok ? 1 : 0, ...ids);
172
+ }
173
+
174
+ // The latest few prompts of a session, oldest first: what the user was asking for.
175
+ export function lastPrompt(db, sessionId, n = 3) {
176
+ return db.prepare('SELECT text FROM prompts WHERE session_id = ? ORDER BY id DESC LIMIT ?').all(sessionId, n)
177
+ .reverse().map((r) => r.text.slice(0, 1500)).join('\n---\n');
178
+ }
179
+
180
+ export const sessionHasEvents = (db, sessionId) =>
181
+ !!db.prepare('SELECT 1 FROM events WHERE session_id = ? LIMIT 1').get(sessionId);
182
+
183
+ const TYPES = new Set(['decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change']);
184
+ const arr = (v) => JSON.stringify(Array.isArray(v) ? v.map(String).slice(0, 20) : []);
185
+
186
+ export function saveObservation(db, sessionId, project, o, createdAt = now()) {
187
+ if (!o || !o.title) return null;
188
+ return db.prepare(
189
+ `INSERT INTO observations (session_id, project, type, title, narrative, facts, files, concepts, created_at)
190
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
191
+ ).run(
192
+ sessionId, project, TYPES.has(o.type) ? o.type : 'change',
193
+ redact(String(o.title)).slice(0, 200), redact(String(o.narrative || '')),
194
+ arr(o.facts), arr(o.files), arr(o.concepts), createdAt
195
+ ).lastInsertRowid;
196
+ }
197
+
198
+ export function saveSummary(db, sessionId, project, s, createdAt = now()) {
199
+ if (!s || !(s.request || s.completed || s.learned || s.next_steps)) return null;
200
+ const t = (v) => redact(String(v || ''));
201
+ return db.prepare(
202
+ `INSERT INTO summaries (session_id, project, request, completed, learned, next_steps, created_at)
203
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
204
+ ).run(sessionId, project, t(s.request), t(s.completed), t(s.learned), t(s.next_steps), createdAt).lastInsertRowid;
205
+ }
206
+
207
+ const parseObs = (r) => r && { ...r, facts: JSON.parse(r.facts), files: JSON.parse(r.files), concepts: JSON.parse(r.concepts) };
208
+
209
+ // Turn free text into a safe FTS5 query: each word quoted, OR-ed, so punctuation can't break syntax.
210
+ export function ftsQuery(q) {
211
+ const words = String(q || '').match(/[\p{L}\p{N}_]+/gu) || [];
212
+ return words.map((w) => `"${w}"`).join(' OR ');
213
+ }
214
+
215
+ export function search(db, { query, project, type, limit = 20 } = {}) {
216
+ const fts = ftsQuery(query);
217
+ const lim = Math.min(Math.max(Number(limit) || 20, 1), 200);
218
+ const filters = [];
219
+ const args = [];
220
+ if (project) { filters.push('o.project = ?'); args.push(projectOf(project)); }
221
+ if (type) { filters.push('o.type = ?'); args.push(type); }
222
+ if (!fts) return recent(db, { project, type, limit: lim });
223
+ const rows = db.prepare(
224
+ `SELECT o.*, bm25(observations_fts, 8, 2, 3, 3, 1) AS rank
225
+ FROM observations_fts JOIN observations o ON o.id = observations_fts.rowid
226
+ WHERE observations_fts MATCH ? ${filters.map((f) => 'AND ' + f).join(' ')}
227
+ ORDER BY rank LIMIT ?`
228
+ ).all(fts, ...args, lim);
229
+ return rows.map(parseObs);
230
+ }
231
+
232
+ export function recent(db, { project, type, limit = 20 } = {}) {
233
+ const filters = [];
234
+ const args = [];
235
+ if (project) { filters.push('project = ?'); args.push(projectOf(project)); }
236
+ if (type) { filters.push('type = ?'); args.push(type); }
237
+ const where = filters.length ? 'WHERE ' + filters.join(' AND ') : '';
238
+ return db.prepare(`SELECT * FROM observations ${where} ORDER BY created_at DESC, id DESC LIMIT ?`)
239
+ .all(...args, Math.min(Math.max(Number(limit) || 20, 1), 1_000_000)).map(parseObs);
240
+ }
241
+
242
+ export function getObservations(db, ids) {
243
+ const list = (Array.isArray(ids) ? ids : [ids]).map(Number).filter(Number.isInteger).slice(0, 100);
244
+ if (!list.length) return [];
245
+ return db.prepare(`SELECT * FROM observations WHERE id IN (${list.map(() => '?').join(',')}) ORDER BY id`)
246
+ .all(...list).map(parseObs);
247
+ }
248
+
249
+ export function recentSummaries(db, project, limit = 3) {
250
+ return db.prepare('SELECT * FROM summaries WHERE project = ? ORDER BY created_at DESC, id DESC LIMIT ?')
251
+ .all(projectOf(project), limit);
252
+ }
253
+
254
+ export function stats(db) {
255
+ const one = (sql) => db.prepare(sql).get().n;
256
+ return {
257
+ observations: one('SELECT COUNT(*) n FROM observations'),
258
+ summaries: one('SELECT COUNT(*) n FROM summaries'),
259
+ sessions: one('SELECT COUNT(*) n FROM sessions'),
260
+ pending: one('SELECT COUNT(*) n FROM events WHERE status != 1'),
261
+ projects: db.prepare(
262
+ 'SELECT project, COUNT(*) observations, MAX(created_at) last FROM observations GROUP BY project ORDER BY last DESC'
263
+ ).all(),
264
+ };
265
+ }
266
+
267
+ export function forgetProject(db, project) {
268
+ const p = projectOf(project);
269
+ db.exec('BEGIN');
270
+ try {
271
+ for (const t of ['observations', 'summaries', 'events', 'prompts', 'sessions']) {
272
+ db.prepare(`DELETE FROM ${t} WHERE project = ?`).run(p);
273
+ }
274
+ db.exec('COMMIT');
275
+ } catch (e) {
276
+ db.exec('ROLLBACK');
277
+ throw e;
278
+ }
279
+ }
@@ -0,0 +1,56 @@
1
+ // One-way, re-runnable import from an existing claude-mem database (~/.claude-mem/claude-mem.db).
2
+ // Opens the source read-only; tracks copied ids so every run only adds rows it has not seen.
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { existsSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { saveObservation, saveSummary, touchSession } from './db.mjs';
8
+
9
+ export const DEFAULT_SOURCE = join(homedir(), '.claude-mem', 'claude-mem.db');
10
+ const SOURCE = 'claude-mem';
11
+ const TYPE_MAP = { gotcha: 'discovery', security_note: 'decision' };
12
+
13
+ const list = (v) => {
14
+ try { const a = JSON.parse(v || '[]'); return Array.isArray(a) ? a : []; } catch { return []; }
15
+ };
16
+
17
+ export function importClaudeMem(db, file = DEFAULT_SOURCE) {
18
+ if (!existsSync(file)) throw new Error(`no claude-mem database at ${file}`);
19
+ const src = new DatabaseSync(file, { readOnly: true });
20
+ const seen = db.prepare('SELECT 1 FROM imported WHERE source = ? AND kind = ? AND source_id = ?');
21
+ const mark = db.prepare('INSERT INTO imported (source, kind, source_id, local_id) VALUES (?, ?, ?, ?)');
22
+ const counts = { observations: 0, summaries: 0, skipped: 0 };
23
+ db.exec('BEGIN');
24
+ try {
25
+ for (const r of src.prepare('SELECT * FROM observations ORDER BY id').iterate()) {
26
+ if (seen.get(SOURCE, 'observation', String(r.id))) { counts.skipped++; continue; }
27
+ touchSession(db, r.memory_session_id, r.project);
28
+ const id = saveObservation(db, r.memory_session_id, r.project, {
29
+ type: TYPE_MAP[r.type] || r.type,
30
+ title: r.title || r.subtitle || (r.text || '').slice(0, 120) || 'Untitled',
31
+ narrative: r.narrative || r.text || '',
32
+ facts: list(r.facts),
33
+ files: [...new Set([...list(r.files_modified), ...list(r.files_read)])],
34
+ concepts: list(r.concepts),
35
+ }, r.created_at_epoch);
36
+ mark.run(SOURCE, 'observation', String(r.id), id);
37
+ counts.observations++;
38
+ }
39
+ for (const r of src.prepare('SELECT * FROM session_summaries ORDER BY id').iterate()) {
40
+ if (seen.get(SOURCE, 'summary', String(r.id))) { counts.skipped++; continue; }
41
+ touchSession(db, r.memory_session_id, r.project);
42
+ const learned = [r.investigated, r.learned].filter(Boolean).join('\n');
43
+ const id = saveSummary(db, r.memory_session_id, r.project,
44
+ { request: r.request, completed: r.completed, learned, next_steps: r.next_steps }, r.created_at_epoch);
45
+ mark.run(SOURCE, 'summary', String(r.id), id ?? null);
46
+ counts.summaries++;
47
+ }
48
+ db.exec('COMMIT');
49
+ } catch (e) {
50
+ db.exec('ROLLBACK');
51
+ throw e;
52
+ } finally {
53
+ src.close();
54
+ }
55
+ return counts;
56
+ }
@@ -0,0 +1,102 @@
1
+ // Minimal MCP server over stdio (newline-delimited JSON-RPC 2.0). Read-only access to memory.
2
+ import { createInterface } from 'node:readline';
3
+ import * as store from './db.mjs';
4
+
5
+ const TOOLS = [
6
+ {
7
+ name: 'recall_search',
8
+ description: 'Full-text search over memory from earlier sessions. Returns compact results; use recall_get for full detail.',
9
+ inputSchema: {
10
+ type: 'object',
11
+ properties: {
12
+ query: { type: 'string', description: 'Words to search for' },
13
+ project: { type: 'string', description: 'Project folder name; omit to search all projects' },
14
+ type: { type: 'string', enum: ['decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change'] },
15
+ limit: { type: 'number', description: 'Max results, default 10' },
16
+ },
17
+ required: ['query'],
18
+ },
19
+ },
20
+ {
21
+ name: 'recall_get',
22
+ description: 'Full observations (narrative, facts, files, concepts) by id.',
23
+ inputSchema: {
24
+ type: 'object',
25
+ properties: { ids: { type: 'array', items: { type: 'number' } } },
26
+ required: ['ids'],
27
+ },
28
+ },
29
+ {
30
+ name: 'recall_recent',
31
+ description: 'Latest observations and session summaries, optionally for one project.',
32
+ inputSchema: {
33
+ type: 'object',
34
+ properties: { project: { type: 'string' }, limit: { type: 'number' } },
35
+ },
36
+ },
37
+ ];
38
+
39
+ const line = (o) => `#${o.id} [${o.type}] ${o.title} · ${o.project} · ${new Date(o.created_at).toISOString().slice(0, 10)}`;
40
+
41
+ export function callTool(db, name, a = {}) {
42
+ switch (name) {
43
+ case 'recall_search': {
44
+ const rows = store.search(db, { query: a.query, project: a.project, type: a.type, limit: a.limit || 10 });
45
+ return rows.length ? rows.map(line).join('\n') : 'No matches.';
46
+ }
47
+ case 'recall_get':
48
+ return JSON.stringify(store.getObservations(db, a.ids || []), null, 2);
49
+ case 'recall_recent': {
50
+ const out = store.recent(db, { project: a.project, limit: a.limit || 15 }).map(line);
51
+ if (a.project) {
52
+ for (const s of store.recentSummaries(db, a.project, 3)) {
53
+ out.unshift(`summary ${new Date(s.created_at).toISOString().slice(0, 10)}: ${s.request} → ${s.completed}`);
54
+ }
55
+ }
56
+ return out.join('\n') || 'No memory yet.';
57
+ }
58
+ default:
59
+ throw new Error(`unknown tool: ${name}`);
60
+ }
61
+ }
62
+
63
+ export function handle(db, msg, version = '1.0.0') {
64
+ const { id, method, params } = msg;
65
+ if (id === undefined) return null; // notification
66
+ const ok = (result) => ({ jsonrpc: '2.0', id, result });
67
+ switch (method) {
68
+ case 'initialize':
69
+ return ok({
70
+ protocolVersion: params?.protocolVersion || '2025-06-18',
71
+ capabilities: { tools: {} },
72
+ serverInfo: { name: 'recall', version },
73
+ });
74
+ case 'ping':
75
+ return ok({});
76
+ case 'tools/list':
77
+ return ok({ tools: TOOLS });
78
+ case 'tools/call':
79
+ try {
80
+ return ok({ content: [{ type: 'text', text: callTool(db, params?.name, params?.arguments) }] });
81
+ } catch (e) {
82
+ return ok({ content: [{ type: 'text', text: `Error: ${e.message}` }], isError: true });
83
+ }
84
+ default:
85
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } };
86
+ }
87
+ }
88
+
89
+ export function serveMcp() {
90
+ const db = store.open();
91
+ const rl = createInterface({ input: process.stdin });
92
+ rl.on('line', (text) => {
93
+ if (!text.trim()) return;
94
+ let msg;
95
+ try { msg = JSON.parse(text); } catch {
96
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }) + '\n');
97
+ return;
98
+ }
99
+ const res = handle(db, msg);
100
+ if (res) process.stdout.write(JSON.stringify(res) + '\n');
101
+ });
102
+ }
@@ -0,0 +1,403 @@
1
+ #!/usr/bin/env node
2
+ // Recall CLI: Claude Code hook handler, MCP server and user commands.
3
+ import { readFileSync, appendFileSync, mkdirSync, statSync, existsSync, writeFileSync, readdirSync } from 'node:fs';
4
+ import { spawn, spawnSync } from 'node:child_process';
5
+ import { join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { homedir } from 'node:os';
8
+ import { createInterface } from 'node:readline';
9
+ import * as store from './db.mjs';
10
+ import { compress } from './compress.mjs';
11
+ import { serveMcp } from './mcp.mjs';
12
+ import { importClaudeMem, DEFAULT_SOURCE } from './import.mjs';
13
+ import { recordTranscript } from './transcript.mjs';
14
+ import { c, banner, spinner, ok, warn, fail, kv, typeTag } from './ui.mjs';
15
+
16
+ export const VERSION = '1.0.0';
17
+ const SELF = fileURLToPath(import.meta.url);
18
+
19
+ function log(msg) {
20
+ try {
21
+ mkdirSync(store.HOME, { recursive: true });
22
+ appendFileSync(join(store.HOME, 'recall.log'), `${new Date().toISOString()} ${msg}\n`);
23
+ } catch {}
24
+ }
25
+
26
+ const readStdin = () => {
27
+ try { return JSON.parse(readFileSync(0, 'utf8') || '{}'); } catch { return {}; }
28
+ };
29
+
30
+ // Compression is slow (a model call), so hooks always run it in a detached background process.
31
+ function compressInBackground(sessionId) {
32
+ const args = [SELF, 'compress', ...(sessionId ? [sessionId] : [])];
33
+ spawn(process.execPath, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();
34
+ }
35
+
36
+ // Interactive compression: a child process does the blocking work and streams progress,
37
+ // so the spinner here keeps animating.
38
+ function compressWithSpinner(sessionId, label = 'Compressing memory') {
39
+ const spin = spinner(label);
40
+ return new Promise((done) => {
41
+ const child = spawn(process.execPath, [SELF, 'compress', ...(sessionId ? [sessionId] : []), '--progress'],
42
+ { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
43
+ let err = '';
44
+ createInterface({ input: child.stdout }).on('line', (l) => {
45
+ const m = l.match(/^progress (\d+)\/(\d+)/);
46
+ if (m) spin.update(`${label} ${c.amber(`${m[1]}/${m[2]}`)} batches`);
47
+ });
48
+ child.stderr.on('data', (d) => { err += d; });
49
+ child.on('close', (code) => {
50
+ spin.stop();
51
+ if (code === 0) ok('Memory saved');
52
+ else fail(`Compression failed, events kept for retry: ${err.trim().split('\n').pop() || 'exit ' + code}`);
53
+ done(code === 0);
54
+ });
55
+ });
56
+ }
57
+
58
+ const ago = (ms) => {
59
+ const m = Math.round((Date.now() - ms) / 60000);
60
+ return m < 1 ? 'just now' : m < 60 ? `${m}m ago` : m < 1440 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`;
61
+ };
62
+ const short = (s, n) => (s && s.length > n ? s.slice(0, n - 1) + '…' : s || '');
63
+
64
+ export function buildContext(db, project, cfg = store.settings()) {
65
+ const sums = store.recentSummaries(db, project, cfg.contextSummaries);
66
+ const obs = store.recent(db, { project, limit: cfg.contextObservations });
67
+ if (!sums.length && !obs.length) return '';
68
+ const head = `# Recall: memory from earlier sessions in ${project}`;
69
+ const tail = 'Use the recall_search and recall_get tools to look up details or older memory.';
70
+ const sumLines = sums.flatMap((s) => [
71
+ `- ${ago(s.created_at)}: ${short(s.request, 160)}`,
72
+ ...(s.completed ? [` done: ${short(s.completed, 240)}`] : []),
73
+ ...(s.next_steps ? [` next: ${short(s.next_steps, 200)}`] : []),
74
+ ]);
75
+ const obsLines = obs.map((o) => `- #${o.id} [${o.type}] ${o.title} (${ago(o.created_at)}): ${short(o.narrative, 180)}`);
76
+ const render = () => [head,
77
+ ...(sumLines.length ? ['', '## Recent sessions', ...sumLines] : []),
78
+ ...(obsLines.length ? ['', '## Observations (newest first)', ...obsLines] : []),
79
+ '', tail].join('\n');
80
+ // Drop the oldest observations until the block fits the hook output limit.
81
+ let out = render();
82
+ while (out.length > cfg.contextMaxChars && obsLines.length) { obsLines.pop(); out = render(); }
83
+ return out.slice(0, cfg.contextMaxChars);
84
+ }
85
+
86
+ const OWN_TOOL = /(^|__)recall_/;
87
+
88
+ export function handleHook(event, input, db = store.open()) {
89
+ const cfg = store.settings();
90
+ const project = store.projectOf(input.cwd);
91
+ if (!store.isEnabled(cfg, project)) return '';
92
+ const sid = input.session_id || 'unknown';
93
+ switch (event) {
94
+ case 'session-start': {
95
+ compressInBackground(); // recover anything a crashed or interrupted session left pending
96
+ const ctx = buildContext(db, project, cfg);
97
+ return ctx ? JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: ctx } }) : '';
98
+ }
99
+ case 'prompt':
100
+ if (input.prompt) store.addPrompt(db, sid, project, input.prompt);
101
+ return '';
102
+ case 'tool': {
103
+ const tool = input.tool_name || '?';
104
+ if (cfg.skipTools.includes(tool) || OWN_TOOL.test(tool)) return '';
105
+ store.addEvent(db, sid, project, tool, input.tool_input, input.tool_response ?? input.error, cfg.maxEventChars);
106
+ return '';
107
+ }
108
+ case 'stop':
109
+ compressInBackground(sid);
110
+ return '';
111
+ case 'session-end':
112
+ db.prepare('UPDATE sessions SET ended_at = ? WHERE id = ?').run(Date.now(), sid);
113
+ compressInBackground(sid);
114
+ return '';
115
+ default:
116
+ throw new Error(`unknown hook event: ${event}`);
117
+ }
118
+ }
119
+
120
+ // ---------- user commands ----------
121
+
122
+ function printObs(o, full = false) {
123
+ console.log(`${c.gray('#' + o.id)} ${typeTag(o.type)} ${c.bold(o.title)}`);
124
+ console.log(` ${c.amber(o.project)} ${c.gray('· ' + ago(o.created_at))}`);
125
+ if (full) {
126
+ if (o.narrative) console.log('\n' + o.narrative.replace(/^/gm, ' '));
127
+ if (o.facts.length) console.log(`\n ${c.bold('Facts')}\n` + o.facts.map((f) => ` ${c.amber('›')} ${f}`).join('\n'));
128
+ if (o.files.length) console.log(`\n ${c.bold('Files')} ${o.files.map(c.blue).join(c.gray(', '))}`);
129
+ if (o.concepts.length) console.log(` ${c.bold('Tags')} ${o.concepts.map((t) => c.pink('#' + t)).join(' ')}`);
130
+ } else if (o.narrative) {
131
+ console.log(` ${c.dim(short(o.narrative, 160))}`);
132
+ }
133
+ console.log();
134
+ }
135
+
136
+ function parseArgs(args) {
137
+ const flags = {}, rest = [];
138
+ for (let i = 0; i < args.length; i++) {
139
+ const a = args[i];
140
+ if (a.startsWith('--')) {
141
+ const [k, v] = a.slice(2).split('=');
142
+ if (v !== undefined) flags[k] = v;
143
+ else if (args[i + 1] && !args[i + 1].startsWith('--')) flags[k] = args[++i];
144
+ else flags[k] = true;
145
+ } else rest.push(a);
146
+ }
147
+ return { flags, rest };
148
+ }
149
+
150
+ const here = () => store.projectOf(process.cwd());
151
+ const fileSize = (f) => { try { return statSync(f).size; } catch { return 0; } };
152
+ const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
153
+ const claudeDir = () => process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
154
+
155
+ function claudeAvailable(cfg) {
156
+ const r = spawnSync(cfg.claudePath, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 10000 });
157
+ if (!r.error && r.status === 0) return r.stdout.trim();
158
+ const s = spawnSync(cfg.claudePath, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 10000, shell: true });
159
+ return !s.error && s.status === 0 ? s.stdout.trim() : null;
160
+ }
161
+
162
+ function pluginInstalled() {
163
+ try {
164
+ const f = JSON.parse(readFileSync(join(claudeDir(), 'plugins', 'installed_plugins.json'), 'utf8'));
165
+ return Object.keys(f.plugins || f).some((k) => k.startsWith('recall@'));
166
+ } catch { return false; }
167
+ }
168
+
169
+ const HELP = [
170
+ ['Memory', [
171
+ ['status', 'what Recall is doing right now'],
172
+ ['search <words>', 'full-text search [--project p] [--type t] [--limit n]'],
173
+ ['recent', 'latest observations [--project p] [--today|--week]'],
174
+ ['show <id...>', 'full detail of observations'],
175
+ ['context', 'preview what the next session in this folder will see'],
176
+ ['projects', 'every project with counts and last activity'],
177
+ ]],
178
+ ['Control', [
179
+ ['on | off', 'turn capture on/off globally [--project p | --here]'],
180
+ ['record <transcript.jsonl>', 'save memory from a past session, offline'],
181
+ ['sessions', 'list Claude transcripts that can be recorded'],
182
+ ['compress', 'process pending tool events now'],
183
+ ['config [key] [value]', 'show or change settings'],
184
+ ]],
185
+ ['Data', [
186
+ ['import', 'copy memory from claude-mem (re-run to sync new rows) [--from db]'],
187
+ ['export', 'write memory as JSON [--project p] [--out file]'],
188
+ ['forget --project p', 'delete all memory for a project'],
189
+ ['doctor', 'check Node, SQLite, the claude CLI and the plugin'],
190
+ ]],
191
+ ['Integration', [
192
+ ['mcp', 'MCP server over stdio (used by the plugin)'],
193
+ ['hook <event>', 'Claude Code hook entry point'],
194
+ ]],
195
+ ];
196
+
197
+ async function help() {
198
+ await banner(`v${VERSION} · persistent memory for Claude Code`);
199
+ console.log();
200
+ for (const [group, rows] of HELP) {
201
+ console.log(c.bold(c.amber(group)));
202
+ for (const [cmd, desc] of rows) console.log(` ${c.bold(('recall ' + cmd).padEnd(34))} ${c.gray(desc)}`);
203
+ console.log();
204
+ }
205
+ console.log(c.gray(` data: ${store.HOME}`));
206
+ }
207
+
208
+ async function status(db) {
209
+ const cfg = store.settings();
210
+ const s = store.stats(db);
211
+ const p = here();
212
+ await banner(`v${VERSION}`);
213
+ console.log();
214
+ const on = (b) => (b ? c.green('● on') : c.red('○ off'));
215
+ kv('capture', on(cfg.enabled !== false) + c.gray(' (global)'));
216
+ kv('this project', `${on(store.isEnabled(cfg, p))} ${c.amber(p)}${cfg.projects?.[p] ? c.gray(' (override)') : ''}`);
217
+ kv('plugin', pluginInstalled() ? c.green('installed') : c.gold('not installed in Claude Code'));
218
+ kv('memory', `${c.bold(s.observations)} observations · ${s.summaries} summaries · ${s.sessions} sessions`);
219
+ kv('pending', s.pending ? c.gold(`${s.pending} tool events waiting`) : c.green('nothing waiting'));
220
+ const last = store.recent(db, { limit: 1 })[0];
221
+ kv('last saved', last ? `${ago(last.created_at)} · ${short(last.title, 60)}` : c.gray('never'));
222
+ kv('database', `${join(store.HOME, 'recall.db')} ${c.gray(mb(fileSize(join(store.HOME, 'recall.db'))))}`);
223
+ kv('model', cfg.model);
224
+ }
225
+
226
+ function listSessions(db) {
227
+ const root = join(claudeDir(), 'projects');
228
+ const rows = [];
229
+ for (const dir of existsSync(root) ? readdirSync(root) : []) {
230
+ if (dir.includes('observer-sessions')) continue;
231
+ for (const f of readdirSync(join(root, dir)).filter((n) => n.endsWith('.jsonl'))) {
232
+ const path = join(root, dir, f);
233
+ rows.push({ path, id: f.replace('.jsonl', ''), mtime: statSync(path).mtimeMs });
234
+ }
235
+ }
236
+ rows.sort((a, b) => b.mtime - a.mtime);
237
+ return rows.slice(0, 20).map((r) => ({ ...r, recorded: store.sessionHasEvents(db, r.id) }));
238
+ }
239
+
240
+ const typed = (v) => (v === 'true' ? true : v === 'false' ? false : /^-?\d+$/.test(v) ? Number(v) : v);
241
+
242
+ export async function main(argv = process.argv.slice(2)) {
243
+ const [cmd, ...args] = argv;
244
+ if (cmd === 'hook') {
245
+ // Hooks must never break the user's session: swallow and log every error, always exit 0.
246
+ if (process.env.RECALL_CHILD) return;
247
+ try {
248
+ const out = handleHook(args[0], readStdin());
249
+ if (out) process.stdout.write(out);
250
+ } catch (e) {
251
+ log(`hook ${args[0]} failed: ${e.stack || e.message}`);
252
+ }
253
+ return;
254
+ }
255
+ if (cmd === 'mcp') return serveMcp();
256
+ if (cmd === 'compress' && (process.env.RECALL_CHILD || args.includes('--progress') || !process.stdout.isTTY)) {
257
+ if (process.env.RECALL_CHILD) return;
258
+ const progress = args.includes('--progress');
259
+ const sid = args.find((a) => !a.startsWith('--'));
260
+ try {
261
+ compress(store.open(), sid, undefined, (n, t) => progress && console.log(`progress ${n}/${t}`));
262
+ } catch (e) {
263
+ log(`compress failed: ${e.message}`);
264
+ console.error(e.message);
265
+ process.exitCode = 1;
266
+ }
267
+ return;
268
+ }
269
+
270
+ const { flags, rest } = parseArgs(args);
271
+ const db = store.open();
272
+ const project = flags.here ? here() : flags.project;
273
+ switch (cmd) {
274
+ case 'status':
275
+ return status(db);
276
+ case 'search': {
277
+ const rows = store.search(db, { query: rest.join(' '), project, type: flags.type, limit: flags.limit || 15 });
278
+ if (!rows.length) return warn('No matches.');
279
+ console.log(c.gray(`${rows.length} result${rows.length > 1 ? 's' : ''}\n`));
280
+ return rows.forEach((o) => printObs(o));
281
+ }
282
+ case 'recent': {
283
+ const since = flags.today ? Date.now() - 864e5 : flags.week ? Date.now() - 7 * 864e5 : 0;
284
+ const rows = store.recent(db, { project, type: flags.type, limit: flags.limit || 15 }).filter((o) => o.created_at >= since);
285
+ if (!rows.length) return warn('No memory yet.');
286
+ return rows.forEach((o) => printObs(o));
287
+ }
288
+ case 'show':
289
+ return store.getObservations(db, rest).forEach((o) => printObs(o, true));
290
+ case 'context': {
291
+ const ctx = buildContext(db, project || here());
292
+ return ctx ? console.log(ctx) : warn(`No memory for ${project || here()} yet.`);
293
+ }
294
+ case 'projects':
295
+ case 'stats': {
296
+ const s = store.stats(db);
297
+ const cfg = store.settings();
298
+ if (!s.projects.length) return warn('No memory yet.');
299
+ const max = Math.max(...s.projects.map((p) => p.observations));
300
+ for (const p of s.projects) {
301
+ const bar = c.amber('█'.repeat(Math.max(1, Math.round((p.observations / max) * 20))));
302
+ const off = store.isEnabled(cfg, p.project) ? '' : c.red(' off');
303
+ console.log(` ${p.project.padEnd(28)} ${String(p.observations).padStart(5)} ${bar} ${c.gray(ago(p.last))}${off}`);
304
+ }
305
+ return;
306
+ }
307
+ case 'on':
308
+ case 'off': {
309
+ const cfg = store.settings();
310
+ if (project) {
311
+ store.saveSettings({ projects: { ...cfg.projects, [project]: cmd } });
312
+ return ok(`Capture ${cmd === 'on' ? c.green('on') : c.red('off')} for ${c.amber(project)}`);
313
+ }
314
+ store.saveSettings({ enabled: cmd === 'on' });
315
+ return ok(`Capture ${cmd === 'on' ? c.green('on') : c.red('off')} globally`);
316
+ }
317
+ case 'record': {
318
+ if (!rest[0]) return fail('record needs a transcript path (see: recall sessions)');
319
+ const r = recordTranscript(db, resolve(rest[0]));
320
+ if (r.skipped) return warn(`Skipped: ${r.skipped}`);
321
+ ok(`Read ${r.prompts} prompts and ${r.events} tool calls from ${c.amber(r.project)}`);
322
+ if (r.events && !flags['no-compress']) {
323
+ const good = await compressWithSpinner(r.sessionId);
324
+ if (!good) process.exitCode = 1;
325
+ }
326
+ return;
327
+ }
328
+ case 'sessions': {
329
+ const rows = listSessions(db);
330
+ if (!rows.length) return warn('No Claude transcripts found.');
331
+ for (const r of rows) {
332
+ const mark = r.recorded ? c.green('✔ recorded') : c.gold('○ not yet');
333
+ console.log(` ${mark.padEnd(22)} ${c.gray(ago(r.mtime).padEnd(9))} ${r.path}`);
334
+ }
335
+ return console.log(c.gray('\n record one with: recall record <path>'));
336
+ }
337
+ case 'compress':
338
+ return void (await compressWithSpinner(rest[0]));
339
+ case 'config': {
340
+ const cfg = store.settings();
341
+ if (!rest[0]) return console.log(JSON.stringify(cfg, null, 2));
342
+ if (rest[1] === undefined) return console.log(JSON.stringify(cfg[rest[0]]));
343
+ if (!(rest[0] in store.DEFAULT_SETTINGS)) return fail(`unknown setting: ${rest[0]}`);
344
+ store.saveSettings({ [rest[0]]: typed(rest[1]) });
345
+ return ok(`${rest[0]} = ${rest[1]}`);
346
+ }
347
+ case 'import': {
348
+ const spin = spinner('Importing from claude-mem');
349
+ try {
350
+ const n = importClaudeMem(db, flags.from || DEFAULT_SOURCE);
351
+ spin.stop();
352
+ return ok(`Imported ${c.bold(n.observations)} observations and ${c.bold(n.summaries)} summaries ${c.gray(`(${n.skipped} already imported)`)}`);
353
+ } catch (e) {
354
+ spin.stop();
355
+ process.exitCode = 1;
356
+ return fail(e.message);
357
+ }
358
+ }
359
+ case 'export': {
360
+ const data = {
361
+ version: VERSION, exported_at: new Date().toISOString(),
362
+ observations: store.recent(db, { project, limit: 500000 }),
363
+ summaries: db.prepare(`SELECT * FROM summaries ${project ? 'WHERE project = ?' : ''} ORDER BY created_at`)
364
+ .all(...(project ? [project] : [])),
365
+ };
366
+ if (typeof flags.out === 'string') {
367
+ writeFileSync(flags.out, JSON.stringify(data, null, 2));
368
+ return ok(`Wrote ${data.observations.length} observations to ${flags.out}`);
369
+ }
370
+ return console.log(JSON.stringify(data, null, 2));
371
+ }
372
+ case 'forget':
373
+ if (!project) { process.exitCode = 1; return fail('forget needs --project <name> or --here'); }
374
+ if (!flags.yes) {
375
+ const n = store.recent(db, { project, limit: 500000 }).length;
376
+ return warn(`This deletes ${n} observations for ${project}. Re-run with --yes to confirm.`);
377
+ }
378
+ store.forgetProject(db, project);
379
+ return ok(`Deleted all memory for ${project}`);
380
+ case 'doctor': {
381
+ const cfg = store.settings();
382
+ const [maj, min] = process.versions.node.split('.').map(Number);
383
+ const check = (good, label, hint) => (good ? ok(label) : fail(`${label}${hint ? c.gray(' → ' + hint) : ''}`));
384
+ check(maj > 22 || (maj === 22 && min >= 13), `Node ${process.versions.node}`, 'needs Node 22.13 or newer');
385
+ let fts = false;
386
+ try { db.prepare("SELECT * FROM observations_fts WHERE observations_fts MATCH 'x' LIMIT 1").all(); fts = true; } catch {}
387
+ check(fts, 'SQLite FTS5 search', 'this Node build lacks FTS5');
388
+ const ver = claudeAvailable(cfg);
389
+ check(!!ver, `claude CLI ${ver || ''}`.trim(), `set claudePath: recall config claudePath <path>`);
390
+ check(pluginInstalled(), 'plugin installed in Claude Code', '/plugin marketplace add <repo> then /plugin install recall');
391
+ if (existsSync(DEFAULT_SOURCE)) warn(`claude-mem data found ${c.gray('→ recall import')}`);
392
+ return;
393
+ }
394
+ case 'version': case '--version': case '-v':
395
+ return console.log(VERSION);
396
+ default:
397
+ if (cmd && cmd !== 'help' && cmd !== '--help' && cmd !== '-h') fail(`unknown command: ${cmd}\n`);
398
+ return help();
399
+ }
400
+ }
401
+
402
+ const same = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);
403
+ if (process.argv[1] && same(resolve(process.argv[1]), SELF)) main();
@@ -0,0 +1,58 @@
1
+ // Offline recording: turn a Claude Code transcript (.jsonl) into prompts + tool events.
2
+ import { readFileSync } from 'node:fs';
3
+ import { addEvent, addPrompt, projectOf, sessionHasEvents, settings } from './db.mjs';
4
+
5
+ const text = (c) =>
6
+ typeof c === 'string' ? c : Array.isArray(c) ? c.map((p) => (p.type === 'text' ? p.text : '')).join('\n') : '';
7
+
8
+ export function parseTranscript(raw) {
9
+ let sessionId = null, cwd = null;
10
+ const prompts = [];
11
+ const calls = new Map(); // tool_use id -> { name, input, output }
12
+ for (const lineText of raw.split(/\r?\n/)) {
13
+ if (!lineText.trim()) continue;
14
+ let e;
15
+ try { e = JSON.parse(lineText); } catch { continue; } // tolerate a half-written last line
16
+ sessionId ??= e.sessionId;
17
+ cwd ??= e.cwd;
18
+ const content = e.message?.content;
19
+ if (e.type === 'user' && !e.isMeta) {
20
+ if (typeof content === 'string') prompts.push(content);
21
+ else if (Array.isArray(content)) {
22
+ for (const p of content) {
23
+ if (p.type === 'tool_result' && calls.has(p.tool_use_id)) calls.get(p.tool_use_id).output = text(p.content) || p.content;
24
+ else if (p.type === 'text' && p.text) prompts.push(p.text);
25
+ }
26
+ }
27
+ } else if (e.type === 'assistant' && Array.isArray(content)) {
28
+ for (const p of content) if (p.type === 'tool_use') calls.set(p.id, { name: p.name, input: p.input, output: null });
29
+ }
30
+ }
31
+ // Slash-command wrappers and interrupt markers are not real requests.
32
+ const real = prompts.filter((p) => !/^<(command-|local-command)|^\[Request interrupted/.test(p.trim()));
33
+ return { sessionId, cwd, prompts: real, calls: [...calls.values()] };
34
+ }
35
+
36
+ // Returns { sessionId, project, prompts, events } or { skipped: reason }.
37
+ export function recordTranscript(db, file) {
38
+ const t = parseTranscript(readFileSync(file, 'utf8'));
39
+ if (!t.sessionId) return { skipped: 'no session id in transcript' };
40
+ if (sessionHasEvents(db, t.sessionId)) return { skipped: 'session already captured', sessionId: t.sessionId };
41
+ const cfg = settings();
42
+ const project = projectOf(t.cwd);
43
+ db.exec('BEGIN');
44
+ try {
45
+ for (const p of t.prompts) addPrompt(db, t.sessionId, project, p);
46
+ let events = 0;
47
+ for (const c of t.calls) {
48
+ if (cfg.skipTools.includes(c.name) || /(^|__)recall_/.test(c.name)) continue;
49
+ addEvent(db, t.sessionId, project, c.name, c.input, c.output, cfg.maxEventChars);
50
+ events++;
51
+ }
52
+ db.exec('COMMIT');
53
+ return { sessionId: t.sessionId, project, prompts: t.prompts.length, events };
54
+ } catch (e) {
55
+ db.exec('ROLLBACK');
56
+ throw e;
57
+ }
58
+ }
@@ -0,0 +1,62 @@
1
+ // Terminal styling: colors, spinner, animated banner. Plain text when piped, in CI or with NO_COLOR.
2
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR && !process.env.CI;
3
+ const wrap = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
4
+
5
+ export const c = {
6
+ bold: wrap('1'), dim: wrap('2'), amber: wrap('38;5;214'), gold: wrap('38;5;220'), orange: wrap('38;5;208'),
7
+ green: wrap('38;5;42'), red: wrap('38;5;203'), blue: wrap('38;5;75'), violet: wrap('38;5;141'),
8
+ cyan: wrap('38;5;80'), pink: wrap('38;5;211'), gray: wrap('38;5;245'),
9
+ };
10
+
11
+ export const TYPE_COLOR = {
12
+ decision: c.violet, bugfix: c.red, feature: c.green, refactor: c.blue, discovery: c.cyan, change: c.gold,
13
+ };
14
+ export const typeTag = (t) => (TYPE_COLOR[t] || c.gray)(`● ${t}`);
15
+
16
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
17
+ const GRADIENT = [214, 215, 220, 221, 222, 215, 209, 208];
18
+
19
+ const LOGO = [
20
+ ' ╭─╮ ┏━┓┏━╸┏━╸┏━┓╻ ╻ ',
21
+ ' │↺│ ┣┳┛┣╸ ┃ ┣━┫┃ ┃ ',
22
+ ' ╰─╯ ╹┗╸┗━╸┗━╸╹ ╹┗━╸┗━╸',
23
+ ];
24
+
25
+ // Banner sweeps in left to right with an amber gradient; prints instantly when not a TTY.
26
+ export async function banner(subtitle = '') {
27
+ if (!tty) { console.log(`recall ${subtitle}`.trim()); return; }
28
+ const width = Math.max(...LOGO.map((l) => [...l].length));
29
+ process.stdout.write('\x1b[?25l');
30
+ try {
31
+ for (let col = 0; col <= width; col += 2) {
32
+ const frame = LOGO.map((l) => [...l].slice(0, col).map((ch, i) =>
33
+ `\x1b[38;5;${GRADIENT[(i + col) % GRADIENT.length]}m${ch}`).join('') + '\x1b[0m');
34
+ process.stdout.write(frame.join('\n') + '\n');
35
+ await sleep(12);
36
+ process.stdout.write(`\x1b[${LOGO.length}A`);
37
+ }
38
+ process.stdout.write(LOGO.map((l) => [...l].map((ch, i) =>
39
+ `\x1b[38;5;${GRADIENT[i % GRADIENT.length]}m${ch}`).join('') + '\x1b[0m').join('\n') + '\n');
40
+ } finally {
41
+ process.stdout.write('\x1b[?25h');
42
+ }
43
+ if (subtitle) console.log(c.gray(' ' + subtitle));
44
+ }
45
+
46
+ const FRAMES = ['◜', '◠', '◝', '◞', '◡', '◟'];
47
+
48
+ // Spinner for long sync work. The work runs in a child-free sync call, so we tick around awaited promises.
49
+ export function spinner(label) {
50
+ if (!tty) { process.stderr.write(label + '…\n'); return { update() {}, stop(msg) { if (msg) console.log(msg); } }; }
51
+ let i = 0, text = label;
52
+ const id = setInterval(() => process.stdout.write(`\r\x1b[2K${c.amber(FRAMES[i++ % FRAMES.length])} ${text}`), 80);
53
+ return {
54
+ update(t) { text = t; },
55
+ stop(msg) { clearInterval(id); process.stdout.write('\r\x1b[2K'); if (msg) console.log(msg); },
56
+ };
57
+ }
58
+
59
+ export const ok = (s) => console.log(`${c.green('✔')} ${s}`);
60
+ export const warn = (s) => console.log(`${c.gold('▲')} ${s}`);
61
+ export const fail = (s) => console.error(`${c.red('✖')} ${s}`);
62
+ export const kv = (k, v) => console.log(` ${c.gray(k.padEnd(14))} ${v}`);