claude-db 0.2.0 → 0.2.2

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.
@@ -1,5 +1,6 @@
1
1
  import { embedObservations } from './flush.js';
2
2
  import { currentAuthor, observationId } from './identity.js';
3
+ import { redact } from './turn-extractor.js';
3
4
  /**
4
5
  * Records something the user stated outright, rather than something inferred
5
6
  * from a transcript.
@@ -15,14 +16,18 @@ import { currentAuthor, observationId } from './identity.js';
15
16
  export async function remember(ctx, input) {
16
17
  const createdAt = Date.now();
17
18
  const author = currentAuthor();
18
- const title = firstLine(input.text);
19
+ // Dictated memory is redacted exactly like captured memory. This is the
20
+ // likelier of the two paths to carry a credential: "remember the staging DSN
21
+ // is ..." is a natural thing to say to something whose job is remembering.
22
+ const text = redact(input.text);
23
+ const title = firstLine(text);
19
24
  const observation = {
20
25
  id: observationId('manual', createdAt, input.text),
21
26
  sessionId: 'manual',
22
27
  project: input.project,
23
28
  kind: input.kind ?? 'preference',
24
29
  title,
25
- body: input.text,
30
+ body: text,
26
31
  files: input.files ?? [],
27
32
  tags: ['manual'],
28
33
  createdAt,
@@ -11,3 +11,4 @@ import type { Turn } from './transcript.js';
11
11
  * produce a memory worth recalling.
12
12
  */
13
13
  export declare function observationsFromTurns(turns: Turn[], sessionId: string, project: string, config: Config): Observation[];
14
+ export declare function redact(text: string): string;
@@ -56,22 +56,51 @@ function buildObservation(turn, sessionId, project, config) {
56
56
  };
57
57
  }
58
58
  /**
59
- * Prefers the agent's own opening sentence over the raw prompt.
59
+ * Sentences that announce work rather than report it.
60
+ *
61
+ * The original rule took the reply's opening sentence, assuming it stated the
62
+ * outcome. Mid-task it almost never does: it says "Now the use command and the
63
+ * top-level handler:" or "Right — let me do that properly". Measured on a real
64
+ * database, about half of all titles were transitions like these, which is fatal
65
+ * because the title is the whole payload of a search result and of the injected
66
+ * block — the body may hold the answer, but nothing ever surfaces it.
67
+ */
68
+ const ANNOUNCEMENT = /^(now|next|then|first|right|ok|okay|good question|great|sure|perfect|let me|let's|i'?ll|here'?s|two|three|four|before|starting|continuing)\b/i;
69
+ function announces(sentence) {
70
+ return sentence.endsWith(':') || ANNOUNCEMENT.test(sentence);
71
+ }
72
+ /**
73
+ * Prefers the first sentence of the reply that reports something.
60
74
  *
61
75
  * The prompt states a request ("can you create one icon"); the reply states
62
76
  * what actually happened ("Built mouse-scroll-icon.tsx, first of the Huge
63
77
  * Tier 1 Gestures batch"). The second is what someone searching their history
64
- * is looking for, and it is written in the vocabulary of the codebase.
78
+ * is looking for, and it is written in the vocabulary of the codebase — but
79
+ * only once the throat-clearing in front of it is skipped.
65
80
  */
66
81
  function buildTitle(turn, files) {
67
- const sentence = firstSentence(stripMarkdown(turn.reasoning));
68
- if (sentence && sentence.length >= 15)
69
- return headline(sentence);
82
+ const prose = stripMarkdown(turn.reasoning);
83
+ // Bounded: past the first few sentences a reply has moved on to detail that
84
+ // no longer summarises the turn.
85
+ for (const sentence of sentences(prose).slice(0, 6)) {
86
+ if (sentence.length >= 15 && !announces(sentence))
87
+ return headline(sentence);
88
+ }
89
+ const opening = firstSentence(prose);
90
+ if (opening && opening.length >= 15)
91
+ return headline(opening);
70
92
  const prompt = firstSentence(turn.prompt);
71
93
  if (prompt)
72
94
  return headline(prompt);
73
95
  return files.length > 0 ? `Changed ${shortPath(files[0] ?? '')}` : 'Session work';
74
96
  }
97
+ /** Split on sentence enders followed by space, so "0.2.1" stays intact. */
98
+ function sentences(text) {
99
+ return text
100
+ .split(/(?<=[.!?])\s+|\n+/)
101
+ .map((sentence) => sentence.trim())
102
+ .filter((sentence) => sentence.length > 0);
103
+ }
75
104
  const TITLE_MAX = 80;
76
105
  /**
77
106
  * Trims a sentence to a scannable headline.
@@ -151,10 +180,15 @@ function isExcluded(file, patterns) {
151
180
  }
152
181
  const PRIVATE_BLOCK = /<private>[\s\S]*?<\/private>/gi;
153
182
  const PRIVATE_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g;
154
- function redact(text) {
183
+ export function redact(text) {
155
184
  return text
156
185
  .replace(PRIVATE_BLOCK, '[redacted]')
157
186
  .replace(PRIVATE_KEY, '[redacted-private-key]')
187
+ // Credentials inside a URL: postgres://, mongodb+srv://, https://. A
188
+ // connection string is the likeliest secret to be pasted into a tool whose
189
+ // whole job is remembering what you pasted. The host survives, so the
190
+ // memory stays useful.
191
+ .replace(/\/\/[^\s:/@]+:[^\s@]+@/g, '//[redacted]@')
158
192
  .replace(/\b(sk-[A-Za-z0-9_-]{16,})\b/g, '[redacted-key]')
159
193
  .replace(/\b(gh[pousr]_[A-Za-z0-9]{16,})\b/g, '[redacted-token]')
160
194
  .replace(/\bAKIA[0-9A-Z]{16}\b/g, '[redacted-key]')
package/dist/cli/index.js CHANGED
@@ -15,60 +15,72 @@ const DIST_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
15
15
  // module's bindings initialise.
16
16
  const BATCH = 500;
17
17
  const [command, ...args] = process.argv.slice(2);
18
- switch (command) {
19
- case 'install':
20
- await cmdInstall(scopeFrom(args));
21
- break;
22
- case 'uninstall':
23
- cmdUninstall(scopeFrom(args));
24
- break;
25
- case 'status':
26
- await cmdStatus();
27
- break;
28
- case 'use':
29
- await cmdUse(args[0]);
30
- break;
31
- case 'doctor':
32
- await cmdDoctor();
33
- break;
34
- case 'search':
35
- await cmdSearch(args);
36
- break;
37
- case 'remember':
38
- await cmdRemember(args);
39
- break;
40
- case 'forget':
41
- await cmdForget(args);
42
- break;
43
- case 'export':
44
- await cmdExport(args);
45
- break;
46
- case 'import':
47
- await cmdImport(args[0]);
48
- break;
49
- case 'prune':
50
- await cmdPrune(args);
51
- break;
52
- case 'reembed':
53
- await cmdReembed();
54
- break;
55
- case 'stats':
56
- await cmdStats();
57
- break;
58
- case 'flush':
59
- await cmdFlush();
60
- break;
61
- case 'reset':
62
- await cmdReset(args);
63
- break;
64
- case 'projects':
65
- await cmdProjects();
66
- break;
67
- case 'merge':
68
- await cmdMerge(args);
69
- break;
70
- default:
71
- usage();
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
+ }
72
84
  }
73
85
  /** Shows how memory is partitioned, and which partition you are currently in. */
74
86
  async function cmdProjects() {
@@ -359,19 +371,52 @@ function fileMentions(path, needle) {
359
371
  return false;
360
372
  }
361
373
  }
362
- async function cmdUse(uri) {
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('-'));
363
385
  if (!uri) {
364
- console.error('Usage: claude-db use <connection-string>');
386
+ console.error('Usage: claude-db use [--force] <connection-string>');
365
387
  process.exit(1);
366
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
+ }
367
409
  const config = loadConfig();
368
410
  config.database = uri;
369
411
  saveConfig(config);
370
- // Fail loudly here rather than silently at the next SessionStart.
371
- const ctx = await createContext({ database: uri });
372
- const ok = await ctx.store.ping();
373
- await ctx.close();
374
- console.log(ok ? `Connected. Using ${ctx.store.kind}.` : 'Saved, but ping failed.');
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;
375
420
  }
376
421
  async function cmdDoctor() {
377
422
  // No embedder timeout here: doctor is where you want to wait for a first
@@ -669,7 +714,7 @@ function usage() {
669
714
  uninstall [--project] Remove them again, leaving memory intact
670
715
  status Is it wired up, and has it recorded anything
671
716
  doctor Show resolved config and test connectivity
672
- use <connection-string> Point memory at any database and verify it
717
+ use [--force] <url> Point memory at a database, once it answers
673
718
  search [--all] <query> Search memory, this project or every project
674
719
  remember [--kind k] <text> Record something outright, e.g. a house rule
675
720
  forget <id> [id...] Delete specific observations by id
@@ -43,10 +43,14 @@ const INSTRUCTIONS = [
43
43
  'MCP server. Session summaries are injected at startup and the best matching',
44
44
  'observation is injected above each prompt, but that is only ever a slice.',
45
45
  '',
46
- 'Before saying you lack context on this codebase, or asking the user to',
47
- 're-explain a past decision, a failed approach, or why something is the way',
48
- 'it is: call `search` first, then `get_observations` for the ids worth',
49
- 'reading. Treat asking the user as the fallback, not the first move.',
46
+ 'Search it *before* re-deriving something this project already knows. That',
47
+ 'means before grepping or reading git history to reconstruct why something is',
48
+ 'the way it is, before saying you lack context, and before asking the user to',
49
+ 're-explain a past decision or a failed approach: call `search`, then',
50
+ '`get_observations` for the ids worth reading.',
51
+ '',
52
+ 'Verifying against the code afterwards is right — memory records what was',
53
+ 'done, the source shows what is. Starting there is what wastes the memory.',
50
54
  '',
51
55
  'When the user states a standing rule or preference, record it with',
52
56
  '`remember` so it survives this session.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-db",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Persistent memory for Claude Code. Captures why decisions were made, not just which files changed. Bring your own database: SQLite, MongoDB or Postgres. No cloud, no subscription.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",