claude-db 0.1.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.
- package/LICENSE +201 -0
- package/README.md +306 -0
- package/dist/capture/command.d.ts +20 -0
- package/dist/capture/command.js +81 -0
- package/dist/capture/flush.d.ts +20 -0
- package/dist/capture/flush.js +102 -0
- package/dist/capture/identity.d.ts +13 -0
- package/dist/capture/identity.js +26 -0
- package/dist/capture/index.d.ts +7 -0
- package/dist/capture/index.js +5 -0
- package/dist/capture/transcript.d.ts +41 -0
- package/dist/capture/transcript.js +160 -0
- package/dist/capture/turn-extractor.d.ts +13 -0
- package/dist/capture/turn-extractor.js +135 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +349 -0
- package/dist/cli/install.d.ts +40 -0
- package/dist/cli/install.js +156 -0
- package/dist/config/index.d.ts +3 -0
- package/dist/config/index.js +2 -0
- package/dist/config/load.d.ts +11 -0
- package/dist/config/load.js +31 -0
- package/dist/config/schema.d.ts +28 -0
- package/dist/config/schema.js +66 -0
- package/dist/context.d.ts +22 -0
- package/dist/context.js +25 -0
- package/dist/embed/builtin.d.ts +20 -0
- package/dist/embed/builtin.js +66 -0
- package/dist/embed/embedder.d.ts +27 -0
- package/dist/embed/embedder.js +18 -0
- package/dist/embed/index.d.ts +15 -0
- package/dist/embed/index.js +39 -0
- package/dist/embed/local.d.ts +17 -0
- package/dist/embed/local.js +41 -0
- package/dist/hooks/payload.d.ts +21 -0
- package/dist/hooks/payload.js +33 -0
- package/dist/hooks/relevance.d.ts +20 -0
- package/dist/hooks/relevance.js +84 -0
- package/dist/hooks/session-end.d.ts +2 -0
- package/dist/hooks/session-end.js +35 -0
- package/dist/hooks/session-start.d.ts +2 -0
- package/dist/hooks/session-start.js +46 -0
- package/dist/hooks/user-prompt.d.ts +2 -0
- package/dist/hooks/user-prompt.js +56 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +5 -0
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +87 -0
- package/dist/search/index.d.ts +2 -0
- package/dist/search/index.js +2 -0
- package/dist/search/rank.d.ts +17 -0
- package/dist/search/rank.js +43 -0
- package/dist/search/service.d.ts +44 -0
- package/dist/search/service.js +78 -0
- package/dist/store/adapter.d.ts +47 -0
- package/dist/store/adapter.js +1 -0
- package/dist/store/index.d.ts +14 -0
- package/dist/store/index.js +39 -0
- package/dist/store/mongo/driver.d.ts +44 -0
- package/dist/store/mongo/driver.js +28 -0
- package/dist/store/mongo/index.d.ts +36 -0
- package/dist/store/mongo/index.js +275 -0
- package/dist/store/postgres/index.d.ts +30 -0
- package/dist/store/postgres/index.js +289 -0
- package/dist/store/sqlite/index.d.ts +30 -0
- package/dist/store/sqlite/index.js +309 -0
- package/dist/store/sqlite/schema.sql +61 -0
- package/dist/types.d.ts +55 -0
- package/dist/types.js +5 -0
- package/dist/util/project.d.ts +14 -0
- package/dist/util/project.js +24 -0
- package/dist/util/scope.d.ts +10 -0
- package/dist/util/scope.js +17 -0
- package/dist/util/shortid.d.ts +11 -0
- package/dist/util/shortid.js +36 -0
- package/dist/util/vector.d.ts +5 -0
- package/dist/util/vector.js +17 -0
- package/dist/util/warnings.d.ts +12 -0
- package/dist/util/warnings.js +27 -0
- package/package.json +96 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readdirSync, readFileSync, rmSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { flushSession, resetCursor } from '../capture/index.js';
|
|
7
|
+
import { createContext } from '../context.js';
|
|
8
|
+
import { CONFIG_DIR, CONFIG_PATH, loadConfig, saveConfig } from '../config/index.js';
|
|
9
|
+
import { assertStableLocation, install, mcpPathFor, settingsPathFor, uninstall } from './install.js';
|
|
10
|
+
import { resolveProject } from '../util/project.js';
|
|
11
|
+
import { silenceSqliteWarning } from '../util/warnings.js';
|
|
12
|
+
import { toShortId } from '../util/shortid.js';
|
|
13
|
+
silenceSqliteWarning();
|
|
14
|
+
const DIST_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
15
|
+
const [command, ...args] = process.argv.slice(2);
|
|
16
|
+
switch (command) {
|
|
17
|
+
case 'install':
|
|
18
|
+
await cmdInstall(scopeFrom(args));
|
|
19
|
+
break;
|
|
20
|
+
case 'uninstall':
|
|
21
|
+
cmdUninstall(scopeFrom(args));
|
|
22
|
+
break;
|
|
23
|
+
case 'status':
|
|
24
|
+
await cmdStatus();
|
|
25
|
+
break;
|
|
26
|
+
case 'use':
|
|
27
|
+
await cmdUse(args[0]);
|
|
28
|
+
break;
|
|
29
|
+
case 'doctor':
|
|
30
|
+
await cmdDoctor();
|
|
31
|
+
break;
|
|
32
|
+
case 'search':
|
|
33
|
+
await cmdSearch(args.join(' '));
|
|
34
|
+
break;
|
|
35
|
+
case 'flush':
|
|
36
|
+
await cmdFlush();
|
|
37
|
+
break;
|
|
38
|
+
case 'reset':
|
|
39
|
+
await cmdReset(args);
|
|
40
|
+
break;
|
|
41
|
+
case 'projects':
|
|
42
|
+
await cmdProjects();
|
|
43
|
+
break;
|
|
44
|
+
default:
|
|
45
|
+
usage();
|
|
46
|
+
}
|
|
47
|
+
/** Shows how memory is partitioned, and which partition you are currently in. */
|
|
48
|
+
async function cmdProjects() {
|
|
49
|
+
const here = resolveProject(undefined);
|
|
50
|
+
const ctx = await createContext();
|
|
51
|
+
try {
|
|
52
|
+
const projects = await ctx.store.listProjects();
|
|
53
|
+
if (projects.length === 0) {
|
|
54
|
+
console.log('No memory stored yet.');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
console.log(`database: ${ctx.config.database}\n`);
|
|
58
|
+
for (const entry of projects) {
|
|
59
|
+
const marker = entry.project === here ? '*' : ' ';
|
|
60
|
+
const date = new Date(entry.lastActive).toISOString().slice(0, 10);
|
|
61
|
+
console.log(`${marker} ${String(entry.observations).padStart(5)} ${date} ${entry.project}`);
|
|
62
|
+
}
|
|
63
|
+
console.log('\n* is the project you are in now. Searches only ever see one row.');
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await ctx.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Deletes stored memory. Scoped to this project with `--project`, otherwise
|
|
71
|
+
* everything in the configured database.
|
|
72
|
+
*
|
|
73
|
+
* Goes through the adapter rather than deleting a file, because on a shared
|
|
74
|
+
* Postgres or Mongo there is no file to delete and removing the local config
|
|
75
|
+
* directory would silently do nothing.
|
|
76
|
+
*/
|
|
77
|
+
async function cmdReset(argv) {
|
|
78
|
+
const scoped = argv.includes('--project') || argv.includes('-p');
|
|
79
|
+
const confirmed = argv.includes('--yes') || argv.includes('-y');
|
|
80
|
+
const project = resolveProject(undefined);
|
|
81
|
+
const ctx = await createContext();
|
|
82
|
+
try {
|
|
83
|
+
const target = scoped ? project : ctx.config.database;
|
|
84
|
+
// Confirmation is checked before the destructive call, not after: a dry
|
|
85
|
+
// run that deletes is worse than having no dry run at all.
|
|
86
|
+
if (!confirmed) {
|
|
87
|
+
console.log(`This would delete ${scoped ? 'this project\'s' : 'ALL'} memory from:`);
|
|
88
|
+
console.log(` ${target}`);
|
|
89
|
+
console.log('\nNothing was deleted. Re-run with --yes to confirm.');
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const deleted = await ctx.store.clear(scoped ? project : undefined);
|
|
93
|
+
console.log(`Deleted ${deleted} observation(s) from ${target}.`);
|
|
94
|
+
if (!scoped) {
|
|
95
|
+
clearLocalState();
|
|
96
|
+
console.log('Cleared transcript cursors so the next flush starts clean.');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
await ctx.close();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Transcript cursors are local scratch state keyed to a database that no
|
|
105
|
+
* longer has the rows. Leaving them behind makes the next flush skip turns it
|
|
106
|
+
* believes were already stored.
|
|
107
|
+
*/
|
|
108
|
+
function clearLocalState() {
|
|
109
|
+
rmSync(join(CONFIG_DIR, 'cursors'), { recursive: true, force: true });
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Ingests every transcript for this project, including sessions still open.
|
|
113
|
+
*
|
|
114
|
+
* Recovery path for anything the hooks missed: sessions that predate the
|
|
115
|
+
* install, sessions that were force-quit, or a database that was wiped. Safe
|
|
116
|
+
* to run repeatedly because observation ids are content-derived.
|
|
117
|
+
*/
|
|
118
|
+
async function cmdFlush() {
|
|
119
|
+
const project = resolveProject(undefined);
|
|
120
|
+
const dir = transcriptDirFor(project);
|
|
121
|
+
let files;
|
|
122
|
+
try {
|
|
123
|
+
files = readdirSync(dir).filter((name) => name.endsWith('.jsonl'));
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
console.error(`No transcripts found at ${dir}`);
|
|
127
|
+
process.exit(1);
|
|
128
|
+
}
|
|
129
|
+
const ctx = await createContext();
|
|
130
|
+
let total = 0;
|
|
131
|
+
try {
|
|
132
|
+
for (const file of files) {
|
|
133
|
+
const sessionId = file.replace(/\.jsonl$/, '');
|
|
134
|
+
// Ignore any stored cursor: a manual flush is asking for a full re-read.
|
|
135
|
+
resetCursor(sessionId);
|
|
136
|
+
const result = await flushSession(ctx, sessionId, project, join(dir, file));
|
|
137
|
+
if (result.observations > 0) {
|
|
138
|
+
console.log(`${sessionId.slice(0, 8)} ${String(result.observations).padStart(4)} observations`);
|
|
139
|
+
total += result.observations;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
await ctx.close();
|
|
145
|
+
}
|
|
146
|
+
console.log(`\n${total} observations from ${files.length} transcript(s).`);
|
|
147
|
+
}
|
|
148
|
+
/** `--project` limits the install to the current repo; default is machine-wide. */
|
|
149
|
+
function scopeFrom(args) {
|
|
150
|
+
return args.includes('--project') || args.includes('-p') ? 'project' : 'global';
|
|
151
|
+
}
|
|
152
|
+
async function cmdInstall(scope) {
|
|
153
|
+
const project = resolveProject(undefined);
|
|
154
|
+
try {
|
|
155
|
+
assertStableLocation(DIST_DIR);
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
159
|
+
process.exit(1);
|
|
160
|
+
}
|
|
161
|
+
const settingsPath = install(DIST_DIR, scope, project);
|
|
162
|
+
const ctx = await createContext();
|
|
163
|
+
await ctx.close();
|
|
164
|
+
console.log(`Scope : ${scope === 'project' ? `this project only (${project})` : 'all projects on this machine'}`);
|
|
165
|
+
console.log(`Settings : ${settingsPath}`);
|
|
166
|
+
console.log(`Config : ${CONFIG_PATH}`);
|
|
167
|
+
console.log(`Database : ${ctx.config.database}`);
|
|
168
|
+
console.log('\nRestart Claude Code to activate.');
|
|
169
|
+
if (scope === 'project') {
|
|
170
|
+
warnIfCommittable(project);
|
|
171
|
+
console.log('Remove later with: claude-db uninstall --project');
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* `.mcp.json` is conventionally committed so a team shares MCP servers, but
|
|
176
|
+
* ours points at an absolute path under this user's home directory. Committing
|
|
177
|
+
* it hands teammates a server that cannot start. Warn rather than silently
|
|
178
|
+
* editing .gitignore, since that file is the user's to manage.
|
|
179
|
+
*/
|
|
180
|
+
function warnIfCommittable(project) {
|
|
181
|
+
const gitignore = join(project, '.gitignore');
|
|
182
|
+
let ignored = false;
|
|
183
|
+
try {
|
|
184
|
+
ignored = readFileSync(gitignore, 'utf8')
|
|
185
|
+
.split('\n')
|
|
186
|
+
.some((line) => line.trim().replace(/^\//, '') === '.mcp.json');
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return; // not a git repo, or no .gitignore: nothing to warn about
|
|
190
|
+
}
|
|
191
|
+
if (ignored)
|
|
192
|
+
return;
|
|
193
|
+
console.log('\nNote: .mcp.json holds an absolute path to this machine.');
|
|
194
|
+
console.log('It would break for anyone else if committed. To keep it local:');
|
|
195
|
+
console.log(" echo '.mcp.json' >> .gitignore");
|
|
196
|
+
}
|
|
197
|
+
function cmdUninstall(scope) {
|
|
198
|
+
const project = resolveProject(undefined);
|
|
199
|
+
const path = uninstall(DIST_DIR, scope, project);
|
|
200
|
+
console.log(path
|
|
201
|
+
? `Removed hooks and MCP server from ${path}`
|
|
202
|
+
: 'Nothing to remove: no settings file found.');
|
|
203
|
+
console.log('Memory itself is untouched. Delete it with: rm -rf ~/.claude-memory');
|
|
204
|
+
}
|
|
205
|
+
/** Answers "is it actually wired up, and does it have anything in it?" */
|
|
206
|
+
async function cmdStatus() {
|
|
207
|
+
const project = resolveProject(undefined);
|
|
208
|
+
const ctx = await createContext();
|
|
209
|
+
try {
|
|
210
|
+
const sessions = await ctx.store.recentSessions(project, 100);
|
|
211
|
+
// Reading the database says nothing about whether the hooks were ever
|
|
212
|
+
// registered, and "0 sessions" looks identical whether you have not worked
|
|
213
|
+
// yet or never installed. Check both and say which.
|
|
214
|
+
const wiring = [
|
|
215
|
+
{ scope: 'project', label: 'this project' },
|
|
216
|
+
{ scope: 'global', label: 'all projects' },
|
|
217
|
+
].map((entry) => ({
|
|
218
|
+
...entry,
|
|
219
|
+
path: settingsPathFor(entry.scope, project),
|
|
220
|
+
installed: isInstalled(settingsPathFor(entry.scope, project)),
|
|
221
|
+
}));
|
|
222
|
+
const active = wiring.filter((entry) => entry.installed);
|
|
223
|
+
console.log(`project : ${project}`);
|
|
224
|
+
console.log(`database : ${ctx.config.database}`);
|
|
225
|
+
console.log(`hooks : ${active.length > 0
|
|
226
|
+
? active.map((entry) => entry.label).join(' + ')
|
|
227
|
+
: 'NOT INSTALLED'}`);
|
|
228
|
+
const mcpFile = [mcpPathFor('project', project), mcpPathFor('global', project)].find((candidate) => fileMentions(candidate, resolve(DIST_DIR, 'mcp', 'server.js')));
|
|
229
|
+
console.log(`mcp : ${mcpFile ? `registered (${mcpFile})` : 'NOT REGISTERED'}`);
|
|
230
|
+
console.log(`sessions : ${sessions.length} recorded for this project`);
|
|
231
|
+
if (active.length === 0) {
|
|
232
|
+
console.log('\nHooks are not registered, so nothing will ever be captured.');
|
|
233
|
+
console.log('Run this from the project you want to track:');
|
|
234
|
+
console.log(' claude-db install --project');
|
|
235
|
+
}
|
|
236
|
+
else if (sessions.length === 0) {
|
|
237
|
+
console.log('\nInstalled, but nothing recorded yet. Memory is written when a');
|
|
238
|
+
console.log('session ENDS. Work in this project, close the session, then re-check.');
|
|
239
|
+
console.log('If you installed just now, restart Claude Code first.');
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
await ctx.close();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/** True when a settings file contains one of our hook commands. */
|
|
247
|
+
function isInstalled(settingsPath) {
|
|
248
|
+
return fileMentions(settingsPath, resolve(DIST_DIR, 'hooks', 'session-end.js'));
|
|
249
|
+
}
|
|
250
|
+
/** Claude Code stores transcripts under a dash-encoded absolute path. */
|
|
251
|
+
function transcriptDirFor(project) {
|
|
252
|
+
return join(homedir(), '.claude', 'projects', project.replace(/[/.]/g, '-'));
|
|
253
|
+
}
|
|
254
|
+
function fileMentions(path, needle) {
|
|
255
|
+
try {
|
|
256
|
+
return readFileSync(path, 'utf8').includes(needle);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
async function cmdUse(uri) {
|
|
263
|
+
if (!uri) {
|
|
264
|
+
console.error('Usage: claude-db use <connection-string>');
|
|
265
|
+
process.exit(1);
|
|
266
|
+
}
|
|
267
|
+
const config = loadConfig();
|
|
268
|
+
config.database = uri;
|
|
269
|
+
saveConfig(config);
|
|
270
|
+
// Fail loudly here rather than silently at the next SessionStart.
|
|
271
|
+
const ctx = await createContext({ database: uri });
|
|
272
|
+
const ok = await ctx.store.ping();
|
|
273
|
+
await ctx.close();
|
|
274
|
+
console.log(ok ? `Connected. Using ${ctx.store.kind}.` : 'Saved, but ping failed.');
|
|
275
|
+
}
|
|
276
|
+
async function cmdDoctor() {
|
|
277
|
+
const ctx = await createContext();
|
|
278
|
+
const reachable = await ctx.store.ping();
|
|
279
|
+
// Report measured capability, not configured intent. Printing "384d" for an
|
|
280
|
+
// embedder that cannot actually run is worse than printing nothing.
|
|
281
|
+
const embedder = await ctx.embedder();
|
|
282
|
+
const vectors = await probeEmbedder(embedder);
|
|
283
|
+
console.log(`database : ${ctx.config.database}`);
|
|
284
|
+
console.log(`adapter : ${ctx.store.kind}`);
|
|
285
|
+
console.log(`reachable: ${reachable ? 'yes' : 'no'}`);
|
|
286
|
+
console.log(`requested: embeddings.provider = ${ctx.config.embeddings.provider}`);
|
|
287
|
+
console.log(`embedder : ${embedder.id} (${embedder.dimensions}d)`);
|
|
288
|
+
console.log(`vectors : ${vectors}`);
|
|
289
|
+
console.log(`search : ${vectors.startsWith('working') ? 'hybrid (keyword + vector)' : 'keyword only'}`);
|
|
290
|
+
await ctx.close();
|
|
291
|
+
process.exit(reachable ? 0 : 1);
|
|
292
|
+
}
|
|
293
|
+
async function probeEmbedder(embedder) {
|
|
294
|
+
if (embedder.dimensions === 0)
|
|
295
|
+
return 'disabled';
|
|
296
|
+
try {
|
|
297
|
+
const [vector] = await embedder.embed(['connectivity probe']);
|
|
298
|
+
return vector && vector.length > 0
|
|
299
|
+
? `working (${vector.length}d)`
|
|
300
|
+
: 'unavailable (empty vector)';
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
return `unavailable (${error instanceof Error ? error.message.split('.')[0] : 'error'})`;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async function cmdSearch(query) {
|
|
307
|
+
if (!query.trim()) {
|
|
308
|
+
console.error('Usage: claude-db search <query>');
|
|
309
|
+
process.exit(1);
|
|
310
|
+
}
|
|
311
|
+
const ctx = await createContext();
|
|
312
|
+
const results = await ctx.search.search({
|
|
313
|
+
text: query,
|
|
314
|
+
project: resolveProject(undefined),
|
|
315
|
+
limit: 10,
|
|
316
|
+
});
|
|
317
|
+
// Same short-id format the MCP tools emit, so ids copied from either place
|
|
318
|
+
// work in the other.
|
|
319
|
+
for (const entry of results) {
|
|
320
|
+
const date = new Date(entry.createdAt).toISOString().slice(0, 10);
|
|
321
|
+
console.log(`${toShortId(entry.id)} ${entry.kind.padEnd(10)} ${date} ${entry.title}`);
|
|
322
|
+
}
|
|
323
|
+
if (results.length === 0)
|
|
324
|
+
console.log('No matching observations.');
|
|
325
|
+
await ctx.close();
|
|
326
|
+
}
|
|
327
|
+
function usage() {
|
|
328
|
+
console.log(`claude-db
|
|
329
|
+
|
|
330
|
+
install [--project] Register hooks + MCP server with Claude Code
|
|
331
|
+
uninstall [--project] Remove them again, leaving memory intact
|
|
332
|
+
status Is it wired up, and has it recorded anything
|
|
333
|
+
doctor Show resolved config and test connectivity
|
|
334
|
+
use <connection-string> Point memory at any database and verify it
|
|
335
|
+
search <query> Search memory for the current project
|
|
336
|
+
projects List every project with memory in this database
|
|
337
|
+
flush Re-ingest every transcript for this project
|
|
338
|
+
reset [--project] --yes Delete stored memory (dry run without --yes)
|
|
339
|
+
|
|
340
|
+
--project scope to the current repo via .claude/settings.local.json
|
|
341
|
+
instead of every project on this machine
|
|
342
|
+
|
|
343
|
+
Connection strings:
|
|
344
|
+
mongodb+srv://user:pass@cluster.mongodb.net/memory
|
|
345
|
+
postgres://user:pass@host:5432/memory
|
|
346
|
+
/path/to/memory.db (SQLite, default)
|
|
347
|
+
|
|
348
|
+
Or set CLAUDE_DB_URL in the environment to override config.json.`);
|
|
349
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type Scope = 'global' | 'project';
|
|
2
|
+
/**
|
|
3
|
+
* Where Claude Code reads settings from.
|
|
4
|
+
*
|
|
5
|
+
* `project` writes `settings.local.json` inside the target repo, which Claude
|
|
6
|
+
* Code already treats as personal and gitignores. That makes it the right
|
|
7
|
+
* choice for trying memory on one repo without touching every session on the
|
|
8
|
+
* machine, and it is trivially reversible by deleting one file.
|
|
9
|
+
*/
|
|
10
|
+
export declare function settingsPathFor(scope: Scope, project: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* MCP servers live in a different file from hooks.
|
|
13
|
+
*
|
|
14
|
+
* Claude Code reads project-scoped MCP servers from `.mcp.json` at the repo
|
|
15
|
+
* root, not from `settings.local.json`. Writing them alongside the hooks looks
|
|
16
|
+
* correct and silently does nothing: the hooks fire, the tools never appear,
|
|
17
|
+
* and the session-start text ends up advertising tools that do not exist.
|
|
18
|
+
*/
|
|
19
|
+
export declare function mcpPathFor(scope: Scope, project: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* Registers the four lifecycle hooks and the MCP server, merging into whatever
|
|
22
|
+
* the user already has rather than overwriting it. Re-running is safe: a hook
|
|
23
|
+
* whose command already appears is skipped rather than duplicated.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Refuses to install from a location that will not survive.
|
|
27
|
+
*
|
|
28
|
+
* Hooks are registered as absolute paths to this build. `npx` unpacks into
|
|
29
|
+
* `~/.npm/_npx/<hash>/`, which npm evicts on its own schedule, so an install
|
|
30
|
+
* from there works until the cache is cleared and then fails silently on every
|
|
31
|
+
* hook forever after. Failing loudly now is far better than a memory system
|
|
32
|
+
* that quietly stops recording weeks later.
|
|
33
|
+
*/
|
|
34
|
+
export declare function assertStableLocation(distDir: string): void;
|
|
35
|
+
export declare function install(distDir: string, scope: Scope, project: string): string;
|
|
36
|
+
/**
|
|
37
|
+
* Removes only what `install` added, leaving unrelated hooks and servers in
|
|
38
|
+
* place. Empty containers are pruned so an uninstall leaves no residue.
|
|
39
|
+
*/
|
|
40
|
+
export declare function uninstall(distDir: string, scope: Scope, project: string): string | null;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
/**
|
|
5
|
+
* Where Claude Code reads settings from.
|
|
6
|
+
*
|
|
7
|
+
* `project` writes `settings.local.json` inside the target repo, which Claude
|
|
8
|
+
* Code already treats as personal and gitignores. That makes it the right
|
|
9
|
+
* choice for trying memory on one repo without touching every session on the
|
|
10
|
+
* machine, and it is trivially reversible by deleting one file.
|
|
11
|
+
*/
|
|
12
|
+
export function settingsPathFor(scope, project) {
|
|
13
|
+
return scope === 'project'
|
|
14
|
+
? join(project, '.claude', 'settings.local.json')
|
|
15
|
+
: join(homedir(), '.claude', 'settings.json');
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* MCP servers live in a different file from hooks.
|
|
19
|
+
*
|
|
20
|
+
* Claude Code reads project-scoped MCP servers from `.mcp.json` at the repo
|
|
21
|
+
* root, not from `settings.local.json`. Writing them alongside the hooks looks
|
|
22
|
+
* correct and silently does nothing: the hooks fire, the tools never appear,
|
|
23
|
+
* and the session-start text ends up advertising tools that do not exist.
|
|
24
|
+
*/
|
|
25
|
+
export function mcpPathFor(scope, project) {
|
|
26
|
+
return scope === 'project'
|
|
27
|
+
? join(project, '.mcp.json')
|
|
28
|
+
: join(homedir(), '.claude.json');
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Three hooks, not four.
|
|
32
|
+
*
|
|
33
|
+
* There is deliberately no PostToolUse hook. It fired after every single tool
|
|
34
|
+
* call and existed only to journal file paths, which the transcript already
|
|
35
|
+
* records in far more detail. Removing it deletes the most frequently invoked
|
|
36
|
+
* process in the system and loses nothing.
|
|
37
|
+
*/
|
|
38
|
+
const HOOKS = [
|
|
39
|
+
['SessionStart', 'session-start.js'],
|
|
40
|
+
['UserPromptSubmit', 'user-prompt.js'],
|
|
41
|
+
['SessionEnd', 'session-end.js'],
|
|
42
|
+
];
|
|
43
|
+
/**
|
|
44
|
+
* Registers the four lifecycle hooks and the MCP server, merging into whatever
|
|
45
|
+
* the user already has rather than overwriting it. Re-running is safe: a hook
|
|
46
|
+
* whose command already appears is skipped rather than duplicated.
|
|
47
|
+
*/
|
|
48
|
+
/**
|
|
49
|
+
* Refuses to install from a location that will not survive.
|
|
50
|
+
*
|
|
51
|
+
* Hooks are registered as absolute paths to this build. `npx` unpacks into
|
|
52
|
+
* `~/.npm/_npx/<hash>/`, which npm evicts on its own schedule, so an install
|
|
53
|
+
* from there works until the cache is cleared and then fails silently on every
|
|
54
|
+
* hook forever after. Failing loudly now is far better than a memory system
|
|
55
|
+
* that quietly stops recording weeks later.
|
|
56
|
+
*/
|
|
57
|
+
export function assertStableLocation(distDir) {
|
|
58
|
+
// Only npm's own scratch areas. Matching on `/tmp/` generally would be a
|
|
59
|
+
// false positive: a global prefix can legitimately live anywhere, and
|
|
60
|
+
// refusing a valid install is worse than the problem being guarded against.
|
|
61
|
+
const ephemeral = ['_npx', '_cacache'];
|
|
62
|
+
const segments = distDir.split('/');
|
|
63
|
+
if (!ephemeral.some((name) => segments.includes(name)))
|
|
64
|
+
return;
|
|
65
|
+
throw new Error(`Refusing to install from a temporary location:\n ${distDir}\n\n` +
|
|
66
|
+
`Hooks are registered as absolute paths, and this one will be deleted.\n` +
|
|
67
|
+
`Install persistently first:\n\n` +
|
|
68
|
+
` npm install -g claude-db\n` +
|
|
69
|
+
` claude-db install --project\n`);
|
|
70
|
+
}
|
|
71
|
+
export function install(distDir, scope, project) {
|
|
72
|
+
const path = settingsPathFor(scope, project);
|
|
73
|
+
const settings = readJson(path);
|
|
74
|
+
const hooks = (settings['hooks'] ?? {});
|
|
75
|
+
for (const [event, file, matcher] of HOOKS) {
|
|
76
|
+
const command = hookCommand(distDir, file);
|
|
77
|
+
const existing = hooks[event] ?? [];
|
|
78
|
+
const present = existing.some((entry) => entry.hooks.some((hook) => hook.command === command));
|
|
79
|
+
if (present)
|
|
80
|
+
continue;
|
|
81
|
+
existing.push({
|
|
82
|
+
...(matcher ? { matcher } : {}),
|
|
83
|
+
hooks: [{ type: 'command', command }],
|
|
84
|
+
});
|
|
85
|
+
hooks[event] = existing;
|
|
86
|
+
}
|
|
87
|
+
settings['hooks'] = hooks;
|
|
88
|
+
// Never write mcpServers here; Claude Code ignores it in this file.
|
|
89
|
+
delete settings['mcpServers'];
|
|
90
|
+
writeJson(path, settings);
|
|
91
|
+
const mcpPath = mcpPathFor(scope, project);
|
|
92
|
+
const mcpConfig = readJson(mcpPath);
|
|
93
|
+
const servers = (mcpConfig['mcpServers'] ?? {});
|
|
94
|
+
servers['memory'] = {
|
|
95
|
+
command: 'node',
|
|
96
|
+
args: [resolve(distDir, 'mcp', 'server.js')],
|
|
97
|
+
};
|
|
98
|
+
mcpConfig['mcpServers'] = servers;
|
|
99
|
+
writeJson(mcpPath, mcpConfig);
|
|
100
|
+
return path;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Removes only what `install` added, leaving unrelated hooks and servers in
|
|
104
|
+
* place. Empty containers are pruned so an uninstall leaves no residue.
|
|
105
|
+
*/
|
|
106
|
+
export function uninstall(distDir, scope, project) {
|
|
107
|
+
const path = settingsPathFor(scope, project);
|
|
108
|
+
const settings = readJson(path);
|
|
109
|
+
if (Object.keys(settings).length === 0)
|
|
110
|
+
return null;
|
|
111
|
+
const ours = new Set(HOOKS.map(([, file]) => hookCommand(distDir, file)));
|
|
112
|
+
const hooks = (settings['hooks'] ?? {});
|
|
113
|
+
for (const [event, entries] of Object.entries(hooks)) {
|
|
114
|
+
const kept = entries
|
|
115
|
+
.map((entry) => ({
|
|
116
|
+
...entry,
|
|
117
|
+
hooks: entry.hooks.filter((hook) => !ours.has(hook.command)),
|
|
118
|
+
}))
|
|
119
|
+
.filter((entry) => entry.hooks.length > 0);
|
|
120
|
+
if (kept.length > 0)
|
|
121
|
+
hooks[event] = kept;
|
|
122
|
+
else
|
|
123
|
+
delete hooks[event];
|
|
124
|
+
}
|
|
125
|
+
if (Object.keys(hooks).length > 0)
|
|
126
|
+
settings['hooks'] = hooks;
|
|
127
|
+
else
|
|
128
|
+
delete settings['hooks'];
|
|
129
|
+
writeJson(path, settings);
|
|
130
|
+
const mcpPath = mcpPathFor(scope, project);
|
|
131
|
+
const mcpConfig = readJson(mcpPath);
|
|
132
|
+
const servers = (mcpConfig['mcpServers'] ?? {});
|
|
133
|
+
delete servers['memory'];
|
|
134
|
+
if (Object.keys(servers).length > 0)
|
|
135
|
+
mcpConfig['mcpServers'] = servers;
|
|
136
|
+
else
|
|
137
|
+
delete mcpConfig['mcpServers'];
|
|
138
|
+
if (Object.keys(mcpConfig).length > 0)
|
|
139
|
+
writeJson(mcpPath, mcpConfig);
|
|
140
|
+
return path;
|
|
141
|
+
}
|
|
142
|
+
function hookCommand(distDir, file) {
|
|
143
|
+
return `node ${resolve(distDir, 'hooks', file)}`;
|
|
144
|
+
}
|
|
145
|
+
function readJson(path) {
|
|
146
|
+
try {
|
|
147
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return {};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function writeJson(path, value) {
|
|
154
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
155
|
+
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
156
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Config } from './schema.js';
|
|
2
|
+
export declare const CONFIG_DIR: string;
|
|
3
|
+
export declare const CONFIG_PATH: string;
|
|
4
|
+
export declare const DEFAULT_DB_PATH: string;
|
|
5
|
+
/**
|
|
6
|
+
* Precedence: CLAUDE_DB_URL env var, then config.json, then a local SQLite
|
|
7
|
+
* file. The env var wins so CI and containers can point at a shared database
|
|
8
|
+
* without rewriting config on disk.
|
|
9
|
+
*/
|
|
10
|
+
export declare function loadConfig(): Config;
|
|
11
|
+
export declare function saveConfig(config: Config): void;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { ConfigSchema } from './schema.js';
|
|
5
|
+
export const CONFIG_DIR = join(homedir(), '.claude-memory');
|
|
6
|
+
export const CONFIG_PATH = join(CONFIG_DIR, 'config.json');
|
|
7
|
+
export const DEFAULT_DB_PATH = join(CONFIG_DIR, 'memory.db');
|
|
8
|
+
/**
|
|
9
|
+
* Precedence: CLAUDE_DB_URL env var, then config.json, then a local SQLite
|
|
10
|
+
* file. The env var wins so CI and containers can point at a shared database
|
|
11
|
+
* without rewriting config on disk.
|
|
12
|
+
*/
|
|
13
|
+
export function loadConfig() {
|
|
14
|
+
let fileConfig = {};
|
|
15
|
+
try {
|
|
16
|
+
fileConfig = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// Missing or unreadable config is not an error; defaults apply.
|
|
20
|
+
}
|
|
21
|
+
const config = ConfigSchema.parse(fileConfig);
|
|
22
|
+
const envUrl = process.env['CLAUDE_DB_URL']?.trim();
|
|
23
|
+
return {
|
|
24
|
+
...config,
|
|
25
|
+
database: envUrl && envUrl.length > 0 ? envUrl : config.database || DEFAULT_DB_PATH,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function saveConfig(config) {
|
|
29
|
+
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
|
|
30
|
+
writeFileSync(CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
|
|
31
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const ConfigSchema: z.ZodObject<{
|
|
3
|
+
database: z.ZodDefault<z.ZodString>;
|
|
4
|
+
embeddings: z.ZodDefault<z.ZodObject<{
|
|
5
|
+
provider: z.ZodDefault<z.ZodEnum<{
|
|
6
|
+
auto: "auto";
|
|
7
|
+
local: "local";
|
|
8
|
+
builtin: "builtin";
|
|
9
|
+
none: "none";
|
|
10
|
+
}>>;
|
|
11
|
+
maxScanCandidates: z.ZodDefault<z.ZodNumber>;
|
|
12
|
+
}, z.core.$strip>>;
|
|
13
|
+
capture: z.ZodPrefault<z.ZodObject<{
|
|
14
|
+
tools: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
15
|
+
exclude: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
16
|
+
maxBodyChars: z.ZodDefault<z.ZodNumber>;
|
|
17
|
+
}, z.core.$strip>>;
|
|
18
|
+
inject: z.ZodPrefault<z.ZodObject<{
|
|
19
|
+
sessions: z.ZodDefault<z.ZodNumber>;
|
|
20
|
+
maxChars: z.ZodDefault<z.ZodNumber>;
|
|
21
|
+
perPrompt: z.ZodDefault<z.ZodBoolean>;
|
|
22
|
+
promptResults: z.ZodDefault<z.ZodNumber>;
|
|
23
|
+
promptMaxChars: z.ZodDefault<z.ZodNumber>;
|
|
24
|
+
expandTop: z.ZodDefault<z.ZodNumber>;
|
|
25
|
+
expandMaxChars: z.ZodDefault<z.ZodNumber>;
|
|
26
|
+
}, z.core.$strip>>;
|
|
27
|
+
}, z.core.$strip>;
|
|
28
|
+
export type Config = z.infer<typeof ConfigSchema>;
|