claude-db 0.3.0 → 0.4.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 CHANGED
@@ -94,6 +94,7 @@ Ran: Test run: pnpm test
94
94
  | `claude-db remember [--key <name>] <text>` | Record a rule outright, e.g. "always use pnpm here" |
95
95
  | `claude-db forget <id>` | Delete specific observations by id |
96
96
  | `claude-db seed --from-git` | Fill a cold memory from this repo's history |
97
+ | `claude-db usages [--regex] <symbol>` | Find real usages via `git grep`, live — not a stored index |
97
98
  | `claude-db stats` | What this project's memory is made of |
98
99
  | `claude-db projects` | Every project with memory stored |
99
100
  | `claude-db merge [<path>]` | Move memory from an old project path onto this one |
package/dist/cli/index.js CHANGED
@@ -4,6 +4,7 @@ import { readFileSync, rmSync, statSync } from 'node:fs';
4
4
  import { basename, dirname, join, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { embedObservations, flushSession, remember, observationsFromGit, redact, resetCursor, sweepCursors, transcriptsFor, } from '../capture/index.js';
7
+ import { findUsages, formatUsages } from '../usages/index.js';
7
8
  import { createContext } from '../context.js';
8
9
  import { createStore } from '../store/index.js';
9
10
  import { CONFIG_DIR, CONFIG_PATH, loadConfig, saveConfig } from '../config/index.js';
@@ -95,6 +96,9 @@ async function run() {
95
96
  case 'seed':
96
97
  await cmdSeed(args);
97
98
  break;
99
+ case 'usages':
100
+ await cmdUsages(args);
101
+ break;
98
102
  case 'sync':
99
103
  await cmdSync(args);
100
104
  break;
@@ -149,6 +153,38 @@ async function cmdSeed(argv) {
149
153
  console.log(`Seeded ${observations.length} observation(s) from git history.`);
150
154
  console.log(`Oldest: ${new Date(observations[observations.length - 1]?.createdAt ?? 0).toISOString().slice(0, 10)}`);
151
155
  }
156
+ /**
157
+ * Live `git grep`, not a database lookup — the only command with no
158
+ * `createContext()` call, since it touches no store and no embedder.
159
+ *
160
+ * Never a persisted index: this project has already shipped three
161
+ * silent-staleness bugs, and a symbol index that drifts from an edit is the
162
+ * same failure shape. Re-deriving the answer from the current source on every
163
+ * call means there is nothing to invalidate.
164
+ */
165
+ async function cmdUsages(argv) {
166
+ const regex = argv.includes('--regex');
167
+ const path = valueOf(argv, '--path');
168
+ const context = Number(valueOf(argv, '--context') ?? 0);
169
+ const limit = Number(valueOf(argv, '--limit') ?? 100);
170
+ const symbol = withoutFlags(argv, ['--path', '--context', '--limit'])
171
+ .filter((arg) => arg !== '--regex')
172
+ .join(' ')
173
+ .trim();
174
+ if (!symbol) {
175
+ console.error('Usage: claude-db usages [--regex] [--context <n>] [--path <dir>] [--limit <n>] <symbol>');
176
+ process.exit(1);
177
+ }
178
+ if (!Number.isFinite(context) || context < 0) {
179
+ console.error('--context must be a non-negative number.');
180
+ process.exit(1);
181
+ }
182
+ if (!Number.isFinite(limit) || limit <= 0) {
183
+ console.error('--limit must be a positive number.');
184
+ process.exit(1);
185
+ }
186
+ console.log(formatUsages(findUsages({ symbol, regex, context, limit, ...(path ? { path } : {}) })));
187
+ }
152
188
  /**
153
189
  * Two-way merge with another database.
154
190
  *
@@ -1102,6 +1138,8 @@ function usage() {
1102
1138
  stats What this project's memory is made of
1103
1139
  flush Re-ingest every transcript for this project
1104
1140
  seed --from-git [--limit n] Fill a cold memory from this repo's history
1141
+ usages [--regex] <symbol> Find real usages via git grep, current source only
1142
+ [--context n] [--path <dir>] [--limit n]
1105
1143
  export [--all] > out.jsonl Dump memory as JSONL, for backup or migration
1106
1144
  import <file.jsonl> Load a dump back in (safe to repeat)
1107
1145
  sync <url> [--yes] Two-way merge with another database
@@ -74,6 +74,14 @@ const INSTRUCTIONS = [
74
74
  'Verifying against the code afterwards is right — memory records what was',
75
75
  'done, the source shows what is. Starting there is what wastes the memory.',
76
76
  '',
77
+ '`search` covers *why*: past decisions, bugs, reasoning. `find_usages` is',
78
+ 'the default the moment a question is about a symbol or identifier — before',
79
+ 'editing or removing a shared or exported name, or to look one up at all —',
80
+ 'since it tags the likely definition and re-derives the answer from the',
81
+ 'current source on every call, so it is never stale. grep still wins for',
82
+ 'everything that is not a code identifier: plain text, log files, comments,',
83
+ 'strings, and scoping with grep flags `find_usages` does not expose.',
84
+ '',
77
85
  'When the user states a standing rule or preference, record it with',
78
86
  '`remember` so it survives this session.',
79
87
  BLOCK_END,
@@ -26,11 +26,40 @@ export function renderIndex(entries) {
26
26
  const date = new Date(entry.createdAt).toISOString().slice(5, 10);
27
27
  const head = `${toShortId(entry.id)} ${entry.kind} ${date} ${entry.title}`;
28
28
  // Absent for a row only vector search found: it holds no query terms to
29
- // centre a fragment on.
30
- return entry.snippet ? `${head}\n ${entry.snippet}` : head;
29
+ // centre a fragment on. Dropped too when it only restates the title.
30
+ const worth = entry.snippet !== undefined && !echoesTitle(entry.snippet, entry.title);
31
+ return worth ? `${head}\n ${entry.snippet}` : head;
31
32
  });
32
33
  return `${entries.length} result(s):\n${rows.join('\n')}`;
33
34
  }
35
+ /** Lowercased alphanumeric runs — the only form the two sides share. */
36
+ function words(text) {
37
+ return text.toLowerCase().match(/[a-z0-9]+/g) ?? [];
38
+ }
39
+ /**
40
+ * True when a fragment says little the title has not already said.
41
+ *
42
+ * A search engine centres its window on the query match, and the title is taken
43
+ * from the body, so on a short observation the two are frequently the same
44
+ * sentence — the row then pays a second time for a line already shown. Observed
45
+ * live: a title of "Added as section 3 of PLAN.md, with the later sections
46
+ * renumbered" under a fragment reading "…Added as section 3 of [PLAN.md](PLAN.md),
47
+ * with the later…".
48
+ *
49
+ * Compared as a bag of words rather than by substring, because that example is
50
+ * exactly the case a substring test misses: the fragment comes from the raw body
51
+ * and still carries the markdown the title had stripped.
52
+ */
53
+ function echoesTitle(snippet, title) {
54
+ const tokens = words(snippet);
55
+ if (tokens.length === 0)
56
+ return true;
57
+ const inTitle = new Set(words(title));
58
+ const shared = tokens.filter((word) => inTitle.has(word)).length;
59
+ // Not 1.0: the window carries the ellipses and a spill word or two from the
60
+ // neighbouring sentence, so an exact echo never scores as one.
61
+ return shared / tokens.length >= 0.7;
62
+ }
34
63
  /** Layer 3. Full detail for one observation, bounded by `chars`. */
35
64
  export function renderFull(obs, chars) {
36
65
  return [
@@ -10,6 +10,7 @@ import { createContext } from '../context.js';
10
10
  import { toShortId } from '../util/shortid.js';
11
11
  import { renderFull, renderIndex } from './render.js';
12
12
  import { resolveProject } from '../util/project.js';
13
+ import { findUsages, formatUsages } from '../usages/index.js';
13
14
  import { silenceSqliteWarning } from '../util/warnings.js';
14
15
  silenceSqliteWarning();
15
16
  const KINDS = [
@@ -129,6 +130,43 @@ server.tool('get_observations', 'Layer 3. Fetch full bodies for specific observa
129
130
  ],
130
131
  };
131
132
  });
133
+ server.tool('find_usages', 'Find real usages of a symbol or component name via `git grep` — a live read ' +
134
+ 'of the current source, not a stored index, so it is never stale. Returns ' +
135
+ 'file:line and the matching line, with a best-effort [definition?] marker on ' +
136
+ 'lines that look like a declaration. Use this before editing or removing a ' +
137
+ 'shared or exported name, or to answer "what uses this" (structure). Use ' +
138
+ '`search` instead for "why is this the way it is" (history).', {
139
+ symbol: z.string().min(1).max(200).describe('Exact name to search for, e.g. "useAuth" or "CartButton"'),
140
+ path: z
141
+ .string()
142
+ .optional()
143
+ .describe('A file or directory to narrow the search to; omit to search the whole ' +
144
+ 'repository (never narrows on its own — a blast-radius check that quietly ' +
145
+ 'skipped part of the repo would be worse than no check). Must be inside a ' +
146
+ 'git working tree. Different from the memory tools’ project param, which ' +
147
+ 'can point at a folder pooling several repos rather than being one itself'),
148
+ regex: z
149
+ .boolean()
150
+ .default(false)
151
+ .describe('Treat symbol as an extended regular expression instead of a literal name'),
152
+ context: z
153
+ .number()
154
+ .int()
155
+ .min(0)
156
+ .max(10)
157
+ .default(0)
158
+ .describe('Lines of surrounding context before/after each match'),
159
+ limit: z
160
+ .number()
161
+ .int()
162
+ .min(1)
163
+ .max(500)
164
+ .default(100)
165
+ .describe('Cap on matching lines returned; the result says how many more exist'),
166
+ }, async ({ symbol, path, regex, context, limit }) => {
167
+ const result = findUsages({ symbol, regex, context, limit, ...(path ? { path } : {}) });
168
+ return { content: [{ type: 'text', text: formatUsages(result) }] };
169
+ });
132
170
  const transport = new StdioServerTransport();
133
171
  await server.connect(transport);
134
172
  for (const signal of ['SIGINT', 'SIGTERM']) {
@@ -0,0 +1,29 @@
1
+ export interface UsageMatch {
2
+ file: string;
3
+ line: number;
4
+ text: string;
5
+ isDefinition: boolean;
6
+ }
7
+ export interface UsagesResult {
8
+ root: string;
9
+ matches: UsageMatch[];
10
+ total: number;
11
+ truncated: boolean;
12
+ }
13
+ export interface FindUsagesInput {
14
+ symbol: string;
15
+ path?: string;
16
+ regex: boolean;
17
+ context: number;
18
+ limit: number;
19
+ }
20
+ /**
21
+ * Live `git grep`, never a persisted index.
22
+ *
23
+ * A symbol index that drifts from an edit is the same failure shape as every
24
+ * silent-staleness bug this project has already shipped and fixed. This
25
+ * re-derives the answer from the current source on every call, so there is
26
+ * nothing to invalidate.
27
+ */
28
+ export declare function findUsages(input: FindUsagesInput): UsagesResult;
29
+ export declare function formatUsages(result: UsagesResult): string;
@@ -0,0 +1,131 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import { relative, resolve } from 'node:path';
4
+ // A hit here means the term is too generic to be a symbol lookup at all; the
5
+ // fix is a narrower query, not a bigger buffer.
6
+ const MAX_BUFFER = 16 * 1024 * 1024;
7
+ /**
8
+ * Live `git grep`, never a persisted index.
9
+ *
10
+ * A symbol index that drifts from an edit is the same failure shape as every
11
+ * silent-staleness bug this project has already shipped and fixed. This
12
+ * re-derives the answer from the current source on every call, so there is
13
+ * nothing to invalidate.
14
+ */
15
+ export function findUsages(input) {
16
+ // realpath'd up front: git's own --show-toplevel always resolves symlinks
17
+ // (on macOS, tmpdir()'s /var/folders/... is itself a symlink to
18
+ // /private/var/folders/...), so comparing an un-resolved `start` against it
19
+ // below would produce a bogus, always-".."-prefixed relative path and
20
+ // silently disable scoping rather than apply it.
21
+ const start = realpathSync(resolve(input.path ?? process.cwd()));
22
+ const root = repoRootFor(start);
23
+ const args = buildArgs(input);
24
+ // An explicit path narrows the search to that subtree; omitting it searches
25
+ // the whole repository. Defaulting to cwd's subtree would silently hide a
26
+ // usage that lives elsewhere in the repo — exactly the case this tool
27
+ // exists to catch — so only a caller who deliberately asked to narrow gets
28
+ // narrowed. git accepts a file or a directory here equally.
29
+ if (input.path) {
30
+ const scope = relative(root, start);
31
+ if (scope && !scope.startsWith('..'))
32
+ args.push('--', scope);
33
+ }
34
+ let raw;
35
+ try {
36
+ raw = execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: MAX_BUFFER });
37
+ }
38
+ catch (error) {
39
+ const err = error;
40
+ // git grep exits 1 for "ran fine, found nothing" — not an error.
41
+ if (err.status === 1)
42
+ return { root, matches: [], total: 0, truncated: false };
43
+ if (/maxBuffer/i.test(err.message)) {
44
+ throw new Error(`too many matches for "${input.symbol}" to read at once — narrow it ` +
45
+ '(a longer name, --path to a subdirectory, or --regex to anchor it tighter)');
46
+ }
47
+ throw new Error((err.stderr ?? err.message).trim().split('\n')[0]);
48
+ }
49
+ const parsed = parseGrepOutput(raw).map((row) => ({
50
+ ...row,
51
+ isDefinition: isDefinitionLike(input.symbol, row.text),
52
+ }));
53
+ return {
54
+ root,
55
+ matches: parsed.slice(0, input.limit),
56
+ total: parsed.length,
57
+ truncated: parsed.length > input.limit,
58
+ };
59
+ }
60
+ /**
61
+ * Deliberately not resolveProject(): that widens to the repository root for
62
+ * MEMORY partitioning, and inside a workspace pooling several sibling repos
63
+ * it can resolve to a directory that is not itself a git working tree, which
64
+ * `git grep` cannot search at all. Delegating to git's own discovery keeps
65
+ * this in sync with whatever repo git itself would act on (worktrees,
66
+ * submodules, symlinks included) without a second implementation of the walk.
67
+ */
68
+ function repoRootFor(start) {
69
+ try {
70
+ return execFileSync('git', ['-C', start, 'rev-parse', '--show-toplevel'], {
71
+ encoding: 'utf8',
72
+ }).trim();
73
+ }
74
+ catch (error) {
75
+ const stderr = error.stderr?.trim();
76
+ throw new Error(`${start} is not inside a git working tree${stderr ? ` (${stderr})` : ''}`);
77
+ }
78
+ }
79
+ function buildArgs({ symbol, regex, context }) {
80
+ // -I: skip binary files — a binary hit otherwise prints a headerless
81
+ // "Binary file X matches" line that corrupts the -z parse below.
82
+ // --untracked: a brand-new file the agent just created and has not `git
83
+ // add`ed yet is exactly the blast-radius case this tool exists for; without
84
+ // this flag it is silently invisible. Still respects .gitignore.
85
+ const args = ['grep', '-n', '-z', '-I', '--untracked'];
86
+ if (context > 0)
87
+ args.push(`-B${context}`, `-A${context}`);
88
+ // Word-regexp only in literal mode: a regex author already controls their
89
+ // own boundaries, so imposing one on top would be a surprise, not a safety net.
90
+ args.push(...(regex ? ['--extended-regexp'] : ['--fixed-strings', '--word-regexp']));
91
+ args.push('-e', symbol);
92
+ return args;
93
+ }
94
+ /** `-z` NUL-delimits path\0line\0content per record; a stray line with no
95
+ * NUL (a `--` context divider, a binary-match notice) is simply dropped. */
96
+ function parseGrepOutput(raw) {
97
+ const rows = [];
98
+ for (const record of raw.split('\n')) {
99
+ if (!record.includes('\0'))
100
+ continue;
101
+ const [file, lineStr, ...rest] = record.split('\0');
102
+ const line = Number(lineStr);
103
+ if (!file || !Number.isFinite(line))
104
+ continue;
105
+ rows.push({ file, line, text: rest.join('\0') });
106
+ }
107
+ return rows;
108
+ }
109
+ /**
110
+ * Cheap, best-effort "this looks like the declaration" marker. Unlike
111
+ * classifyTurn's `because` regression, this never hides or filters a line —
112
+ * it only annotates one already-shown line, so a false positive costs a
113
+ * wrong label, not a silently misfiled result.
114
+ */
115
+ function isDefinitionLike(symbol, text) {
116
+ const s = symbol.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
117
+ return new RegExp(`\\b(function\\*?\\s+${s}\\b` +
118
+ `|class\\s+${s}\\b` +
119
+ `|(?:interface|type|enum)\\s+${s}\\b` +
120
+ `|(?:export\\s+)?(?:const|let|var)\\s+${s}\\s*[:=]` +
121
+ `|export\\s*\\{[^}]*\\b${s}\\b)`).test(text);
122
+ }
123
+ export function formatUsages(result) {
124
+ if (result.matches.length === 0)
125
+ return `No usages of that symbol found under ${result.root}.`;
126
+ const rows = result.matches.map((m) => `${m.file}:${m.line}${m.isDefinition ? ' [definition?]' : ''} ${m.text.trim()}`);
127
+ const header = result.truncated
128
+ ? `showing ${result.matches.length} of ${result.total}+ match(es) (raise \`limit\` or narrow \`symbol\`):`
129
+ : `${result.total} match(es):`;
130
+ return `${header}\n${rows.join('\n')}`;
131
+ }
@@ -0,0 +1,2 @@
1
+ export { findUsages, formatUsages } from './find.js';
2
+ export type { FindUsagesInput, UsagesResult, UsageMatch } from './find.js';
@@ -0,0 +1 @@
1
+ export { findUsages, formatUsages } from './find.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-db",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
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",