claude-db 0.1.1 → 0.2.1
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/README.md +17 -2
- package/dist/capture/flush.d.ts +22 -0
- package/dist/capture/flush.js +45 -10
- package/dist/capture/identity.d.ts +6 -0
- package/dist/capture/identity.js +14 -0
- package/dist/capture/index.d.ts +5 -3
- package/dist/capture/index.js +4 -3
- package/dist/capture/manual.d.ts +21 -0
- package/dist/capture/manual.js +45 -0
- package/dist/capture/transcript.d.ts +12 -0
- package/dist/capture/transcript.js +69 -1
- package/dist/capture/turn-extractor.d.ts +1 -0
- package/dist/capture/turn-extractor.js +46 -9
- package/dist/cli/index.js +458 -67
- package/dist/cli/install.d.ts +15 -1
- package/dist/cli/install.js +127 -8
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +9 -1
- package/dist/context.js +24 -2
- package/dist/embed/builtin.js +3 -1
- package/dist/hooks/relevance.js +11 -4
- package/dist/hooks/session-end.js +2 -1
- package/dist/hooks/session-start.js +22 -3
- package/dist/mcp/server.js +56 -6
- package/dist/search/service.js +4 -1
- package/dist/store/adapter.d.ts +22 -6
- package/dist/store/adapter.js +10 -1
- package/dist/store/mongo/driver.d.ts +1 -0
- package/dist/store/mongo/index.d.ts +3 -2
- package/dist/store/mongo/index.js +57 -7
- package/dist/store/postgres/index.d.ts +22 -8
- package/dist/store/postgres/index.js +165 -21
- package/dist/store/sqlite/index.d.ts +3 -2
- package/dist/store/sqlite/index.js +112 -9
- package/dist/store/sqlite/schema.sql +4 -3
- package/dist/types.d.ts +28 -0
- package/dist/util/project.d.ts +9 -10
- package/dist/util/project.js +52 -13
- package/dist/util/vector.d.ts +11 -1
- package/dist/util/vector.js +14 -3
- package/package.json +2 -2
package/dist/cli/index.js
CHANGED
|
@@ -1,48 +1,86 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { dirname, join, resolve } from 'node:path';
|
|
2
|
+
import { readFileSync, rmSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
5
4
|
import { fileURLToPath } from 'node:url';
|
|
6
|
-
import { flushSession, resetCursor } from '../capture/index.js';
|
|
5
|
+
import { embedObservations, flushSession, remember, resetCursor, transcriptsFor, } from '../capture/index.js';
|
|
7
6
|
import { createContext } from '../context.js';
|
|
8
7
|
import { CONFIG_DIR, CONFIG_PATH, loadConfig, saveConfig } from '../config/index.js';
|
|
9
|
-
import { assertStableLocation, install, mcpPathFor, settingsPathFor, uninstall } from './install.js';
|
|
8
|
+
import { assertStableLocation, install, instructionsPathFor, mcpPathFor, settingsPathFor, uninstall, } from './install.js';
|
|
10
9
|
import { resolveProject } from '../util/project.js';
|
|
11
10
|
import { silenceSqliteWarning } from '../util/warnings.js';
|
|
12
11
|
import { toShortId } from '../util/shortid.js';
|
|
13
12
|
silenceSqliteWarning();
|
|
14
13
|
const DIST_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
|
+
// Declared above the command switch below, which runs before the rest of this
|
|
15
|
+
// module's bindings initialise.
|
|
16
|
+
const BATCH = 500;
|
|
15
17
|
const [command, ...args] = process.argv.slice(2);
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
18
|
+
// Every command runs inside this. A driver that cannot reach its database
|
|
19
|
+
// rejects deep inside an adapter, and with nothing catching it the CLI printed
|
|
20
|
+
// a twenty-line Node stack trace at the user instead of saying what went wrong.
|
|
21
|
+
try {
|
|
22
|
+
await run();
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
console.error(`claude-db: ${error instanceof Error ? error.message : String(error)}`);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
async function run() {
|
|
29
|
+
switch (command) {
|
|
30
|
+
case 'install':
|
|
31
|
+
await cmdInstall(scopeFrom(args));
|
|
32
|
+
break;
|
|
33
|
+
case 'uninstall':
|
|
34
|
+
cmdUninstall(scopeFrom(args));
|
|
35
|
+
break;
|
|
36
|
+
case 'status':
|
|
37
|
+
await cmdStatus();
|
|
38
|
+
break;
|
|
39
|
+
case 'use':
|
|
40
|
+
await cmdUse(args);
|
|
41
|
+
break;
|
|
42
|
+
case 'doctor':
|
|
43
|
+
await cmdDoctor();
|
|
44
|
+
break;
|
|
45
|
+
case 'search':
|
|
46
|
+
await cmdSearch(args);
|
|
47
|
+
break;
|
|
48
|
+
case 'remember':
|
|
49
|
+
await cmdRemember(args);
|
|
50
|
+
break;
|
|
51
|
+
case 'forget':
|
|
52
|
+
await cmdForget(args);
|
|
53
|
+
break;
|
|
54
|
+
case 'export':
|
|
55
|
+
await cmdExport(args);
|
|
56
|
+
break;
|
|
57
|
+
case 'import':
|
|
58
|
+
await cmdImport(args[0]);
|
|
59
|
+
break;
|
|
60
|
+
case 'prune':
|
|
61
|
+
await cmdPrune(args);
|
|
62
|
+
break;
|
|
63
|
+
case 'reembed':
|
|
64
|
+
await cmdReembed();
|
|
65
|
+
break;
|
|
66
|
+
case 'stats':
|
|
67
|
+
await cmdStats();
|
|
68
|
+
break;
|
|
69
|
+
case 'flush':
|
|
70
|
+
await cmdFlush();
|
|
71
|
+
break;
|
|
72
|
+
case 'reset':
|
|
73
|
+
await cmdReset(args);
|
|
74
|
+
break;
|
|
75
|
+
case 'projects':
|
|
76
|
+
await cmdProjects();
|
|
77
|
+
break;
|
|
78
|
+
case 'merge':
|
|
79
|
+
await cmdMerge(args);
|
|
80
|
+
break;
|
|
81
|
+
default:
|
|
82
|
+
usage();
|
|
83
|
+
}
|
|
46
84
|
}
|
|
47
85
|
/** Shows how memory is partitioned, and which partition you are currently in. */
|
|
48
86
|
async function cmdProjects() {
|
|
@@ -66,6 +104,87 @@ async function cmdProjects() {
|
|
|
66
104
|
await ctx.close();
|
|
67
105
|
}
|
|
68
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Re-keys memory recorded under an old project path onto this one.
|
|
109
|
+
*
|
|
110
|
+
* Memory used to be keyed on the exact directory the agent was launched in, so
|
|
111
|
+
* anyone who worked from `repo/frontend` accumulated a second, disjoint memory.
|
|
112
|
+
* Keying on the repository root fixes that going forward but strands whatever
|
|
113
|
+
* is already under the old path, and nothing about it is visible: the memory
|
|
114
|
+
* simply does not appear.
|
|
115
|
+
*
|
|
116
|
+
* Re-inserting rather than issuing an UPDATE is deliberate. Observation ids are
|
|
117
|
+
* content-derived and independent of the project, so writing the same rows with
|
|
118
|
+
* a new project overwrites in place, and every derived field that depends on the
|
|
119
|
+
* project — the FTS scope token above all — is recomputed on the way through.
|
|
120
|
+
*/
|
|
121
|
+
async function cmdMerge(argv) {
|
|
122
|
+
const into = resolveProject(undefined);
|
|
123
|
+
const confirmed = argv.includes('--yes') || argv.includes('-y');
|
|
124
|
+
const given = argv.find((arg) => typeof arg === 'string' && !arg.startsWith('-'));
|
|
125
|
+
const ctx = await createContext();
|
|
126
|
+
try {
|
|
127
|
+
if (!given) {
|
|
128
|
+
await listShards(ctx, into);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
// Resolved but deliberately not run through resolveProject: that maps a
|
|
132
|
+
// subdirectory to the repository root, which is the very key being merged
|
|
133
|
+
// *into*, so the source would resolve to the destination and match nothing.
|
|
134
|
+
const from = resolve(given);
|
|
135
|
+
if (from === into) {
|
|
136
|
+
console.error('Source and destination are the same project.');
|
|
137
|
+
process.exit(1);
|
|
138
|
+
}
|
|
139
|
+
let moved = 0;
|
|
140
|
+
const total = await eachObservation(ctx, { project: from }, async (batch) => {
|
|
141
|
+
if (!confirmed)
|
|
142
|
+
return;
|
|
143
|
+
await ctx.store.insertObservations(batch.map((obs) => ({ ...obs, project: into })));
|
|
144
|
+
moved += batch.length;
|
|
145
|
+
});
|
|
146
|
+
if (total === 0) {
|
|
147
|
+
console.error(`No memory stored under ${from}.`);
|
|
148
|
+
console.error('Run `claude-db projects` to see the exact paths in this database.');
|
|
149
|
+
process.exit(1);
|
|
150
|
+
}
|
|
151
|
+
if (!confirmed) {
|
|
152
|
+
console.log(`This would move ${total} observation(s):`);
|
|
153
|
+
console.log(` from ${from}`);
|
|
154
|
+
console.log(` into ${into}`);
|
|
155
|
+
console.log('\nNothing was moved. Re-run with --yes to confirm.');
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
// Sessions carry the recap injected at SessionStart, so they follow their
|
|
159
|
+
// observations. Only summarised ones are worth moving; the rest go with
|
|
160
|
+
// the cleanup below.
|
|
161
|
+
for (const session of await ctx.store.recentSessions(from, 1000)) {
|
|
162
|
+
await ctx.store.upsertSession({ ...session, project: into });
|
|
163
|
+
}
|
|
164
|
+
const swept = await ctx.store.remove({ project: from });
|
|
165
|
+
console.log(`Moved ${moved} observation(s) into ${into}.`);
|
|
166
|
+
if (swept > 0)
|
|
167
|
+
console.log(`Cleaned up ${swept} leftover row(s) under the old path.`);
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
await ctx.close();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Projects in this database that sit underneath the current one. */
|
|
174
|
+
async function listShards(ctx, into) {
|
|
175
|
+
const shards = (await ctx.store.listProjects()).filter((entry) => entry.project !== into && entry.project.startsWith(`${into}/`));
|
|
176
|
+
if (shards.length === 0) {
|
|
177
|
+
console.log(`No memory is stored under a subdirectory of ${into}.`);
|
|
178
|
+
console.log('Nothing to merge.');
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
console.log(`Memory recorded under subdirectories of ${into}:\n`);
|
|
182
|
+
for (const shard of shards) {
|
|
183
|
+
console.log(` ${String(shard.observations).padStart(5)} ${shard.project}`);
|
|
184
|
+
}
|
|
185
|
+
console.log('\nMerge one in with:');
|
|
186
|
+
console.log(` claude-db merge ${shards[0]?.project} --yes`);
|
|
187
|
+
}
|
|
69
188
|
/**
|
|
70
189
|
* Deletes stored memory. Scoped to this project with `--project`, otherwise
|
|
71
190
|
* everything in the configured database.
|
|
@@ -89,7 +208,7 @@ async function cmdReset(argv) {
|
|
|
89
208
|
console.log('\nNothing was deleted. Re-run with --yes to confirm.');
|
|
90
209
|
return;
|
|
91
210
|
}
|
|
92
|
-
const deleted = await ctx.store.
|
|
211
|
+
const deleted = await ctx.store.remove(scoped ? { project } : {});
|
|
93
212
|
console.log(`Deleted ${deleted} observation(s) from ${target}.`);
|
|
94
213
|
if (!scoped) {
|
|
95
214
|
clearLocalState();
|
|
@@ -117,23 +236,19 @@ function clearLocalState() {
|
|
|
117
236
|
*/
|
|
118
237
|
async function cmdFlush() {
|
|
119
238
|
const project = resolveProject(undefined);
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
files = readdirSync(dir).filter((name) => name.endsWith('.jsonl'));
|
|
124
|
-
}
|
|
125
|
-
catch {
|
|
126
|
-
console.error(`No transcripts found at ${dir}`);
|
|
239
|
+
const transcripts = transcriptsFor(project);
|
|
240
|
+
if (transcripts.length === 0) {
|
|
241
|
+
console.error(`No transcripts found for ${project}`);
|
|
127
242
|
process.exit(1);
|
|
128
243
|
}
|
|
129
244
|
const ctx = await createContext();
|
|
130
245
|
let total = 0;
|
|
131
246
|
try {
|
|
132
|
-
for (const
|
|
133
|
-
const sessionId =
|
|
247
|
+
for (const path of transcripts) {
|
|
248
|
+
const sessionId = basename(path, '.jsonl');
|
|
134
249
|
// Ignore any stored cursor: a manual flush is asking for a full re-read.
|
|
135
250
|
resetCursor(sessionId);
|
|
136
|
-
const result = await flushSession(ctx, sessionId, project,
|
|
251
|
+
const result = await flushSession(ctx, sessionId, project, path);
|
|
137
252
|
if (result.observations > 0) {
|
|
138
253
|
console.log(`${sessionId.slice(0, 8)} ${String(result.observations).padStart(4)} observations`);
|
|
139
254
|
total += result.observations;
|
|
@@ -143,7 +258,7 @@ async function cmdFlush() {
|
|
|
143
258
|
finally {
|
|
144
259
|
await ctx.close();
|
|
145
260
|
}
|
|
146
|
-
console.log(`\n${total} observations from ${
|
|
261
|
+
console.log(`\n${total} observations from ${transcripts.length} transcript(s).`);
|
|
147
262
|
}
|
|
148
263
|
/** `--project` limits the install to the current repo; default is machine-wide. */
|
|
149
264
|
function scopeFrom(args) {
|
|
@@ -163,6 +278,7 @@ async function cmdInstall(scope) {
|
|
|
163
278
|
await ctx.close();
|
|
164
279
|
console.log(`Scope : ${scope === 'project' ? `this project only (${project})` : 'all projects on this machine'}`);
|
|
165
280
|
console.log(`Settings : ${settingsPath}`);
|
|
281
|
+
console.log(`Guidance : ${instructionsPathFor(scope, project)}`);
|
|
166
282
|
console.log(`Config : ${CONFIG_PATH}`);
|
|
167
283
|
console.log(`Database : ${ctx.config.database}`);
|
|
168
284
|
console.log('\nRestart Claude Code to activate.');
|
|
@@ -234,8 +350,8 @@ async function cmdStatus() {
|
|
|
234
350
|
console.log(' claude-db install --project');
|
|
235
351
|
}
|
|
236
352
|
else if (sessions.length === 0) {
|
|
237
|
-
console.log('\nInstalled, but nothing recorded yet. Memory is written
|
|
238
|
-
console.log('
|
|
353
|
+
console.log('\nInstalled, but nothing recorded yet. Memory is written as you');
|
|
354
|
+
console.log('work, on every prompt, and only for turns that changed something.');
|
|
239
355
|
console.log('If you installed just now, restart Claude Code first.');
|
|
240
356
|
}
|
|
241
357
|
}
|
|
@@ -247,10 +363,6 @@ async function cmdStatus() {
|
|
|
247
363
|
function isInstalled(settingsPath) {
|
|
248
364
|
return fileMentions(settingsPath, resolve(DIST_DIR, 'hooks', 'session-end.js'));
|
|
249
365
|
}
|
|
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
366
|
function fileMentions(path, needle) {
|
|
255
367
|
try {
|
|
256
368
|
return readFileSync(path, 'utf8').includes(needle);
|
|
@@ -259,22 +371,60 @@ function fileMentions(path, needle) {
|
|
|
259
371
|
return false;
|
|
260
372
|
}
|
|
261
373
|
}
|
|
262
|
-
|
|
374
|
+
/**
|
|
375
|
+
* Points memory at a database, but only once it answers.
|
|
376
|
+
*
|
|
377
|
+
* Saving first and connecting second is how this used to work, and a typo or a
|
|
378
|
+
* decommissioned host left the config pointing at nothing. The command crashed,
|
|
379
|
+
* and so did every hook after it — so the damage surfaced on some later prompt,
|
|
380
|
+
* far from the cause, as memory quietly recording nothing at all.
|
|
381
|
+
*/
|
|
382
|
+
async function cmdUse(argv) {
|
|
383
|
+
const force = argv.includes('--force');
|
|
384
|
+
const uri = argv.find((arg) => typeof arg === 'string' && !arg.startsWith('-'));
|
|
263
385
|
if (!uri) {
|
|
264
|
-
console.error('Usage: claude-db use <connection-string>');
|
|
386
|
+
console.error('Usage: claude-db use [--force] <connection-string>');
|
|
265
387
|
process.exit(1);
|
|
266
388
|
}
|
|
389
|
+
let kind = '';
|
|
390
|
+
try {
|
|
391
|
+
const ctx = await createContext({ database: uri });
|
|
392
|
+
try {
|
|
393
|
+
if (!(await ctx.store.ping()))
|
|
394
|
+
throw new Error('connected, but it did not answer a ping');
|
|
395
|
+
kind = ctx.store.kind;
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
await ctx.close();
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
console.error(`Could not reach that database: ${describe(error)}`);
|
|
403
|
+
if (!force) {
|
|
404
|
+
console.error('\nNothing was changed; memory still uses the previous database.');
|
|
405
|
+
console.error('Re-run with --force to save it anyway.');
|
|
406
|
+
process.exit(1);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
267
409
|
const config = loadConfig();
|
|
268
410
|
config.database = uri;
|
|
269
411
|
saveConfig(config);
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
412
|
+
console.log(kind ? `Connected. Using ${kind}.` : 'Saved, unverified.');
|
|
413
|
+
}
|
|
414
|
+
function describe(error) {
|
|
415
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
416
|
+
// A bare ENOTFOUND says nothing about what to do next.
|
|
417
|
+
return /ENOTFOUND|EAI_AGAIN/.test(message)
|
|
418
|
+
? `${message}\n(that host does not resolve — check the name, or whether the service still exists)`
|
|
419
|
+
: message;
|
|
275
420
|
}
|
|
276
421
|
async function cmdDoctor() {
|
|
277
|
-
|
|
422
|
+
// No embedder timeout here: doctor is where you want to wait for a first
|
|
423
|
+
// model download, so that the hooks afterwards find it cached.
|
|
424
|
+
const base = loadConfig();
|
|
425
|
+
const ctx = await createContext({
|
|
426
|
+
embeddings: { ...base.embeddings, timeoutMs: 0 },
|
|
427
|
+
});
|
|
278
428
|
const reachable = await ctx.store.ping();
|
|
279
429
|
// Report measured capability, not configured intent. Printing "384d" for an
|
|
280
430
|
// embedder that cannot actually run is worse than printing nothing.
|
|
@@ -303,27 +453,260 @@ async function probeEmbedder(embedder) {
|
|
|
303
453
|
return `unavailable (${error instanceof Error ? error.message.split('.')[0] : 'error'})`;
|
|
304
454
|
}
|
|
305
455
|
}
|
|
306
|
-
async function cmdSearch(
|
|
456
|
+
async function cmdSearch(argv) {
|
|
457
|
+
const all = argv.includes('--all');
|
|
458
|
+
const query = argv.filter((arg) => arg !== '--all').join(' ');
|
|
307
459
|
if (!query.trim()) {
|
|
308
|
-
console.error('Usage: claude-db search <query>');
|
|
460
|
+
console.error('Usage: claude-db search [--all] <query>');
|
|
309
461
|
process.exit(1);
|
|
310
462
|
}
|
|
311
463
|
const ctx = await createContext();
|
|
312
464
|
const results = await ctx.search.search({
|
|
313
465
|
text: query,
|
|
314
|
-
|
|
466
|
+
// Scoping is right for injection, but "where did I solve this before" is
|
|
467
|
+
// inherently cross-project, and only the CLI can ask that question.
|
|
468
|
+
...(all ? {} : { project: resolveProject(undefined) }),
|
|
315
469
|
limit: 10,
|
|
316
470
|
});
|
|
317
471
|
// Same short-id format the MCP tools emit, so ids copied from either place
|
|
318
472
|
// work in the other.
|
|
319
473
|
for (const entry of results) {
|
|
320
474
|
const date = new Date(entry.createdAt).toISOString().slice(0, 10);
|
|
321
|
-
|
|
475
|
+
const where = all ? ` ${basename(entry.project)}` : '';
|
|
476
|
+
console.log(`${toShortId(entry.id)} ${entry.kind.padEnd(10)} ${date}${where} ${entry.title}`);
|
|
322
477
|
}
|
|
323
478
|
if (results.length === 0)
|
|
324
479
|
console.log('No matching observations.');
|
|
325
480
|
await ctx.close();
|
|
326
481
|
}
|
|
482
|
+
async function cmdRemember(argv) {
|
|
483
|
+
const kindFlag = argv.indexOf('--kind');
|
|
484
|
+
const kind = kindFlag >= 0 ? argv[kindFlag + 1] : undefined;
|
|
485
|
+
const text = (kindFlag >= 0
|
|
486
|
+
? argv.filter((_, index) => index !== kindFlag && index !== kindFlag + 1)
|
|
487
|
+
: argv)
|
|
488
|
+
.join(' ')
|
|
489
|
+
.trim();
|
|
490
|
+
if (!text) {
|
|
491
|
+
console.error('Usage: claude-db remember [--kind <kind>] <text>');
|
|
492
|
+
process.exit(1);
|
|
493
|
+
}
|
|
494
|
+
const ctx = await createContext();
|
|
495
|
+
try {
|
|
496
|
+
const observation = await remember(ctx, {
|
|
497
|
+
project: resolveProject(undefined),
|
|
498
|
+
text,
|
|
499
|
+
...(kind ? { kind: kind } : {}),
|
|
500
|
+
});
|
|
501
|
+
console.log(`Remembered ${toShortId(observation.id)} [${observation.kind}] ${observation.title}`);
|
|
502
|
+
}
|
|
503
|
+
finally {
|
|
504
|
+
await ctx.close();
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async function cmdForget(argv) {
|
|
508
|
+
const ids = argv.filter((arg) => typeof arg === 'string' && arg.length > 0);
|
|
509
|
+
if (ids.length === 0) {
|
|
510
|
+
console.error('Usage: claude-db forget <id> [id...]');
|
|
511
|
+
process.exit(1);
|
|
512
|
+
}
|
|
513
|
+
const ctx = await createContext();
|
|
514
|
+
try {
|
|
515
|
+
// Shown before deleting: a short id is a prefix match, and the only way to
|
|
516
|
+
// be sure it means what you think is to read the titles back.
|
|
517
|
+
const doomed = await ctx.store.getObservations(ids);
|
|
518
|
+
for (const obs of doomed) {
|
|
519
|
+
console.log(` ${toShortId(obs.id)} [${obs.kind}] ${obs.title}`);
|
|
520
|
+
}
|
|
521
|
+
const deleted = await ctx.store.remove({ ids });
|
|
522
|
+
console.log(deleted > 0 ? `Forgot ${deleted} observation(s).` : 'No match.');
|
|
523
|
+
}
|
|
524
|
+
finally {
|
|
525
|
+
await ctx.close();
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
/** Pages rather than loading everything: a shared database can be large. */
|
|
529
|
+
async function eachObservation(ctx, filter, visit) {
|
|
530
|
+
let after = 0;
|
|
531
|
+
let total = 0;
|
|
532
|
+
for (;;) {
|
|
533
|
+
const batch = await ctx.store.list({ ...filter, after, limit: BATCH });
|
|
534
|
+
if (batch.length === 0)
|
|
535
|
+
return total;
|
|
536
|
+
await visit(batch);
|
|
537
|
+
total += batch.length;
|
|
538
|
+
const last = batch[batch.length - 1];
|
|
539
|
+
if (!last)
|
|
540
|
+
return total;
|
|
541
|
+
// createdAt is not unique, so a batch that lands entirely on one timestamp
|
|
542
|
+
// would loop forever. Nudging past it drops at most a co-timestamped tail.
|
|
543
|
+
after = last.createdAt === after ? after + 1 : last.createdAt;
|
|
544
|
+
if (batch.length < BATCH)
|
|
545
|
+
return total;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
async function cmdExport(argv) {
|
|
549
|
+
const all = argv.includes('--all');
|
|
550
|
+
const ctx = await createContext();
|
|
551
|
+
try {
|
|
552
|
+
const count = await eachObservation(ctx, all ? {} : { project: resolveProject(undefined) }, (batch) => {
|
|
553
|
+
for (const obs of batch)
|
|
554
|
+
process.stdout.write(`${JSON.stringify(obs)}\n`);
|
|
555
|
+
});
|
|
556
|
+
process.stderr.write(`${count} observation(s) exported.\n`);
|
|
557
|
+
}
|
|
558
|
+
finally {
|
|
559
|
+
await ctx.close();
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
async function cmdImport(path) {
|
|
563
|
+
if (!path) {
|
|
564
|
+
console.error('Usage: claude-db import <file.jsonl>');
|
|
565
|
+
process.exit(1);
|
|
566
|
+
}
|
|
567
|
+
const lines = readFileSync(path, 'utf8').split('\n').filter((line) => line.trim().length > 0);
|
|
568
|
+
const ctx = await createContext();
|
|
569
|
+
let imported = 0;
|
|
570
|
+
try {
|
|
571
|
+
for (let i = 0; i < lines.length; i += BATCH) {
|
|
572
|
+
const batch = lines
|
|
573
|
+
.slice(i, i + BATCH)
|
|
574
|
+
.map((line) => JSON.parse(line))
|
|
575
|
+
.filter((obs) => typeof obs.id === 'string' && typeof obs.project === 'string');
|
|
576
|
+
await ctx.store.insertObservations(batch);
|
|
577
|
+
imported += batch.length;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
finally {
|
|
581
|
+
await ctx.close();
|
|
582
|
+
}
|
|
583
|
+
// Ids are content-derived, so re-importing the same file is a no-op rather
|
|
584
|
+
// than a second copy of every memory.
|
|
585
|
+
console.log(`Imported ${imported} observation(s).`);
|
|
586
|
+
}
|
|
587
|
+
async function cmdPrune(argv) {
|
|
588
|
+
const days = Number(valueOf(argv, '--older-than') ?? NaN);
|
|
589
|
+
const kind = valueOf(argv, '--kind');
|
|
590
|
+
const confirmed = argv.includes('--yes') || argv.includes('-y');
|
|
591
|
+
const all = argv.includes('--all');
|
|
592
|
+
if (!Number.isFinite(days) || days <= 0) {
|
|
593
|
+
console.error('Usage: claude-db prune --older-than <days> [--kind <kind>] [--all] --yes');
|
|
594
|
+
process.exit(1);
|
|
595
|
+
}
|
|
596
|
+
const before = Date.now() - days * 86_400_000;
|
|
597
|
+
const filter = {
|
|
598
|
+
before,
|
|
599
|
+
...(all ? {} : { project: resolveProject(undefined) }),
|
|
600
|
+
...(kind ? { kind } : {}),
|
|
601
|
+
};
|
|
602
|
+
const ctx = await createContext();
|
|
603
|
+
try {
|
|
604
|
+
if (!confirmed) {
|
|
605
|
+
// Counted by paging rather than one unbounded query, and against the
|
|
606
|
+
// same predicate the delete uses, so the dry run cannot disagree with it.
|
|
607
|
+
let matching = 0;
|
|
608
|
+
await eachObservation(ctx, all ? {} : { project: resolveProject(undefined) }, (batch) => {
|
|
609
|
+
for (const obs of batch) {
|
|
610
|
+
if (obs.createdAt < before && (!kind || obs.kind === kind))
|
|
611
|
+
matching += 1;
|
|
612
|
+
}
|
|
613
|
+
});
|
|
614
|
+
console.log(`This would delete ${matching} observation(s) older than ${days} day(s)` +
|
|
615
|
+
`${kind ? ` of kind ${kind}` : ''}.`);
|
|
616
|
+
console.log('\nNothing was deleted. Re-run with --yes to confirm.');
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
const deleted = await ctx.store.remove(filter);
|
|
620
|
+
console.log(`Pruned ${deleted} observation(s).`);
|
|
621
|
+
}
|
|
622
|
+
finally {
|
|
623
|
+
await ctx.close();
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Re-embeds everything with the currently configured model.
|
|
628
|
+
*
|
|
629
|
+
* Installing @xenova/transformers changes the embedding space from 256d to
|
|
630
|
+
* 384d, and `cosine` refuses to compare across widths, so without this an
|
|
631
|
+
* upgrade makes existing memory *less* searchable rather than more.
|
|
632
|
+
*/
|
|
633
|
+
async function cmdReembed() {
|
|
634
|
+
const base = loadConfig();
|
|
635
|
+
const ctx = await createContext({ embeddings: { ...base.embeddings, timeoutMs: 0 } });
|
|
636
|
+
try {
|
|
637
|
+
const embedder = await ctx.embedder();
|
|
638
|
+
if (embedder.dimensions === 0) {
|
|
639
|
+
console.error('No embedder available; nothing to do.');
|
|
640
|
+
process.exit(1);
|
|
641
|
+
}
|
|
642
|
+
let updated = 0;
|
|
643
|
+
let skipped = 0;
|
|
644
|
+
const scanned = await eachObservation(ctx, {}, async (batch) => {
|
|
645
|
+
const stale = batch.filter((obs) => obs.embedder !== embedder.id);
|
|
646
|
+
skipped += batch.length - stale.length;
|
|
647
|
+
if (stale.length === 0)
|
|
648
|
+
return;
|
|
649
|
+
await embedObservations(ctx, stale);
|
|
650
|
+
await ctx.store.insertObservations(stale);
|
|
651
|
+
updated += stale.length;
|
|
652
|
+
process.stderr.write(`\r${updated} re-embedded...`);
|
|
653
|
+
});
|
|
654
|
+
process.stderr.write('\r');
|
|
655
|
+
console.log(`Scanned ${scanned}, re-embedded ${updated} with ${embedder.id}` +
|
|
656
|
+
`${skipped > 0 ? `, ${skipped} already current` : ''}.`);
|
|
657
|
+
}
|
|
658
|
+
finally {
|
|
659
|
+
await ctx.close();
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
async function cmdStats() {
|
|
663
|
+
const project = resolveProject(undefined);
|
|
664
|
+
const ctx = await createContext();
|
|
665
|
+
try {
|
|
666
|
+
const kinds = new Map();
|
|
667
|
+
const tags = new Map();
|
|
668
|
+
let embedded = 0;
|
|
669
|
+
let earliest = Number.POSITIVE_INFINITY;
|
|
670
|
+
let latest = 0;
|
|
671
|
+
const total = await eachObservation(ctx, { project }, (batch) => {
|
|
672
|
+
for (const obs of batch) {
|
|
673
|
+
kinds.set(obs.kind, (kinds.get(obs.kind) ?? 0) + 1);
|
|
674
|
+
for (const tag of obs.tags)
|
|
675
|
+
tags.set(tag, (tags.get(tag) ?? 0) + 1);
|
|
676
|
+
if (obs.embedding && obs.embedding.length > 0)
|
|
677
|
+
embedded += 1;
|
|
678
|
+
earliest = Math.min(earliest, obs.createdAt);
|
|
679
|
+
latest = Math.max(latest, obs.createdAt);
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
if (total === 0) {
|
|
683
|
+
console.log(`No memory stored for ${project}.`);
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
const day = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
687
|
+
console.log(`project : ${project}`);
|
|
688
|
+
console.log(`observations: ${total}`);
|
|
689
|
+
console.log(`range : ${day(earliest)} to ${day(latest)}`);
|
|
690
|
+
console.log(`embedded : ${embedded} of ${total}`);
|
|
691
|
+
console.log('\nby kind');
|
|
692
|
+
for (const [kind, n] of [...kinds].sort((a, b) => b[1] - a[1])) {
|
|
693
|
+
console.log(` ${String(n).padStart(5)} ${kind}`);
|
|
694
|
+
}
|
|
695
|
+
if (tags.size > 0) {
|
|
696
|
+
console.log('\nby area');
|
|
697
|
+
for (const [tag, n] of [...tags].sort((a, b) => b[1] - a[1]).slice(0, 10)) {
|
|
698
|
+
console.log(` ${String(n).padStart(5)} ${tag}`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
finally {
|
|
703
|
+
await ctx.close();
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
function valueOf(argv, flag) {
|
|
707
|
+
const index = argv.indexOf(flag);
|
|
708
|
+
return index >= 0 ? argv[index + 1] : undefined;
|
|
709
|
+
}
|
|
327
710
|
function usage() {
|
|
328
711
|
console.log(`claude-db
|
|
329
712
|
|
|
@@ -331,10 +714,18 @@ function usage() {
|
|
|
331
714
|
uninstall [--project] Remove them again, leaving memory intact
|
|
332
715
|
status Is it wired up, and has it recorded anything
|
|
333
716
|
doctor Show resolved config and test connectivity
|
|
334
|
-
use <
|
|
335
|
-
search <query>
|
|
717
|
+
use [--force] <url> Point memory at a database, once it answers
|
|
718
|
+
search [--all] <query> Search memory, this project or every project
|
|
719
|
+
remember [--kind k] <text> Record something outright, e.g. a house rule
|
|
720
|
+
forget <id> [id...] Delete specific observations by id
|
|
336
721
|
projects List every project with memory in this database
|
|
722
|
+
merge [<old-path>] [--yes] Move memory from an old project path onto this one
|
|
723
|
+
stats What this project's memory is made of
|
|
337
724
|
flush Re-ingest every transcript for this project
|
|
725
|
+
export [--all] > out.jsonl Dump memory as JSONL, for backup or migration
|
|
726
|
+
import <file.jsonl> Load a dump back in (safe to repeat)
|
|
727
|
+
reembed Re-embed everything with the current model
|
|
728
|
+
prune --older-than <days> Delete old memory (dry run without --yes)
|
|
338
729
|
reset [--project] --yes Delete stored memory (dry run without --yes)
|
|
339
730
|
|
|
340
731
|
--project scope to the current repo via .claude/settings.local.json
|
package/dist/cli/install.d.ts
CHANGED
|
@@ -8,6 +8,20 @@ export type Scope = 'global' | 'project';
|
|
|
8
8
|
* machine, and it is trivially reversible by deleting one file.
|
|
9
9
|
*/
|
|
10
10
|
export declare function settingsPathFor(scope: Scope, project: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* Where standing instructions go.
|
|
13
|
+
*
|
|
14
|
+
* Hook output is injected as conversation context, which the agent reads as
|
|
15
|
+
* information about the current turn. It is not a rule, so "you could search
|
|
16
|
+
* memory" competes with everything else in the transcript and loses. A memory
|
|
17
|
+
* file is part of the system prompt and governs the whole session, which is
|
|
18
|
+
* the only reliable way to make recall a default rather than a suggestion.
|
|
19
|
+
*
|
|
20
|
+
* Project scope writes CLAUDE.local.md rather than CLAUDE.md: it is personal
|
|
21
|
+
* and uncommitted, matching settings.local.json, so installing memory for
|
|
22
|
+
* yourself never tells a teammate's agent to call a server they do not have.
|
|
23
|
+
*/
|
|
24
|
+
export declare function instructionsPathFor(scope: Scope, project: string): string;
|
|
11
25
|
/**
|
|
12
26
|
* MCP servers live in a different file from hooks.
|
|
13
27
|
*
|
|
@@ -18,7 +32,7 @@ export declare function settingsPathFor(scope: Scope, project: string): string;
|
|
|
18
32
|
*/
|
|
19
33
|
export declare function mcpPathFor(scope: Scope, project: string): string;
|
|
20
34
|
/**
|
|
21
|
-
* Registers the
|
|
35
|
+
* Registers the three lifecycle hooks and the MCP server, merging into whatever
|
|
22
36
|
* the user already has rather than overwriting it. Re-running is safe: a hook
|
|
23
37
|
* whose command already appears is skipped rather than duplicated.
|
|
24
38
|
*/
|