claude-db 0.6.0 → 0.7.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/CHANGELOG.md +79 -0
- package/dist/capture/turn-extractor.js +9 -3
- package/dist/cli/commands/adoption.d.ts +1 -0
- package/dist/cli/commands/adoption.js +88 -0
- package/dist/cli/index.js +4 -0
- package/dist/cli/install.js +14 -10
- package/dist/cli/instructions.js +5 -4
- package/dist/cli/usage.js +1 -0
- package/dist/hooks/grep-symbols.d.ts +2 -0
- package/dist/hooks/grep-symbols.js +13 -4
- package/dist/hooks/prefer-usages.js +25 -5
- package/dist/hooks/session-start.js +19 -0
- package/dist/mcp/tools/memory.js +25 -23
- package/dist/mcp/tools/observations.js +32 -30
- package/dist/mcp/tools/search.js +13 -12
- package/dist/mcp/tools/usages.js +21 -20
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,84 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- **The usages hook now directs instead of offering.** Replaying 1,871 Bash
|
|
8
|
+
commands from real transcripts showed the additive wording ("the grep below
|
|
9
|
+
still runs") produced 0% unprompted tool adoption — the graph answer arrived
|
|
10
|
+
and was ignored. The hook now names the grepped symbol and instructs the
|
|
11
|
+
agent to use `find_usages`, with the graph answer still inline so the
|
|
12
|
+
instruction is self-justifying.
|
|
13
|
+
|
|
14
|
+
- **Plain lowercase words count as symbols when the graph holds a real
|
|
15
|
+
declaration.** The symbol filter only matched camelCase, PascalCase and
|
|
16
|
+
snake_case, so single-word names — `search`, `forget`, `timeline`, exactly
|
|
17
|
+
the vocabulary a project's public surface tends to use — could never fire
|
|
18
|
+
the hook. Words of four or more characters now qualify, gated on resolving
|
|
19
|
+
to a declared function, method or class rather than a local `const`, so
|
|
20
|
+
greps for `value` or `result` stay silent. Measured on the replay corpus:
|
|
21
|
+
+9 fires, no regressions.
|
|
22
|
+
|
|
23
|
+
- **`git grep` and `rg` count as searching the tree.** Both are recursive by
|
|
24
|
+
default, but the hook required a `-r` flag or a path argument, so every
|
|
25
|
+
`git grep <symbol>` and bare `rg <symbol>` passed unseen. A piped `rg` is
|
|
26
|
+
still treated as output filtering. Space-separated flag values
|
|
27
|
+
(`rg -t ts`, `grep -A 3`) no longer confuse pattern extraction.
|
|
28
|
+
|
|
29
|
+
- **A preference's title is now the rule itself.** Titles were built from
|
|
30
|
+
the assistant's reasoning, so a turn that stated a standing rule while work
|
|
31
|
+
was in flight could be filed as a preference titled "140 checks pass" —
|
|
32
|
+
junk in the new session-start index. Preference titles now come from the
|
|
33
|
+
user's own words.
|
|
34
|
+
|
|
35
|
+
- **The installed instructions speak in the first person.** "This project has
|
|
36
|
+
persistent memory" reads as someone else's feature; "you have persistent
|
|
37
|
+
memory of this project" reads as the model's own recall. The installed
|
|
38
|
+
block now uses the second framing, matching how the model treats memory it
|
|
39
|
+
actually uses. Already-installed projects pick the new text up automatically
|
|
40
|
+
at the next session start.
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- **Session start injects a standing-rules index.** The model uses whatever is
|
|
45
|
+
already in its context and skips what costs a call, so memory it cannot see
|
|
46
|
+
is memory it does not use. The startup injection now lists the most recent
|
|
47
|
+
preference observations — one line each, with the id to expand via
|
|
48
|
+
`get_observations` — so recalling a standing rule becomes expanding a line
|
|
49
|
+
already on screen instead of discovering whether one exists. Rules recorded
|
|
50
|
+
explicitly with `remember` list ahead of auto-classified ones.
|
|
51
|
+
|
|
52
|
+
- **Symbol greps are blocked by default, with the graph answer in the deny
|
|
53
|
+
reason.** A blind A/B on a real task showed the block outperforms the
|
|
54
|
+
nudge: the agent pivots to `find_usages` immediately, loses no turn — the
|
|
55
|
+
answer it needed rides in the deny reason — and non-symbol greps pass
|
|
56
|
+
through untouched. `CLAUDE_DB_USAGES_HOOK=directive` keeps the softer
|
|
57
|
+
inject-only mode; `off` disables the hook entirely.
|
|
58
|
+
|
|
59
|
+
- **`claude-db adoption` measures whether any of this works.** It reads the
|
|
60
|
+
project's transcripts and reports Bash commands vs greps vs hook fires vs
|
|
61
|
+
memory tool calls — the grep-to-memory ratio that motivated this release,
|
|
62
|
+
reproducible on any project with one command.
|
|
63
|
+
|
|
64
|
+
### Fixed
|
|
65
|
+
|
|
66
|
+
- **`claude-db install` stacked duplicate hooks whenever the install path
|
|
67
|
+
changed.** Registration deduped by exact command string, so reinstalling
|
|
68
|
+
from a new location — a repo build vs the global install, or any node
|
|
69
|
+
upgrade under nvm moving the global path — appended a second registration
|
|
70
|
+
with the same matcher: two node processes and two database opens on every
|
|
71
|
+
Bash call. Install now replaces its own hook entries by file name wherever
|
|
72
|
+
they point, and uninstall removes them from any path, not just the one it
|
|
73
|
+
is run from.
|
|
74
|
+
|
|
75
|
+
- **The graph could not answer for the MCP tool names themselves.**
|
|
76
|
+
`find_usages("forget")` returned nothing: tool names existed only as string
|
|
77
|
+
literals with anonymous handlers, so there was no declaration to index.
|
|
78
|
+
Handlers are now named functions matching their tools (`search`, `forget`,
|
|
79
|
+
`timeline`, `remember`, `get_observations`, `find_usages`), so the graph
|
|
80
|
+
answers questions about the project's own public surface.
|
|
81
|
+
|
|
3
82
|
## 0.6.0
|
|
4
83
|
|
|
5
84
|
### Fixed
|
|
@@ -32,14 +32,15 @@ function buildObservation(turn, sessionId, project, config) {
|
|
|
32
32
|
.filter((line) => line !== '')
|
|
33
33
|
.join('\n'), config.capture.maxBodyChars));
|
|
34
34
|
const author = currentAuthor();
|
|
35
|
+
const kind = classifyTurn(turn);
|
|
35
36
|
return {
|
|
36
37
|
id: observationId(sessionId, turn.timestamp, turn.prompt),
|
|
37
38
|
sessionId,
|
|
38
39
|
project,
|
|
39
40
|
...(author ? { author } : {}),
|
|
40
41
|
status: files.length > 0 ? 'open' : 'done',
|
|
41
|
-
kind
|
|
42
|
-
title: redact(buildTitle(turn, files)),
|
|
42
|
+
kind,
|
|
43
|
+
title: redact(buildTitle(turn, files, kind)),
|
|
43
44
|
body,
|
|
44
45
|
files,
|
|
45
46
|
tags: topLevelDirs(files, project),
|
|
@@ -66,7 +67,12 @@ function reports(sentence) {
|
|
|
66
67
|
const text = sentence.replace(/\[redacted[^\]]*\]/g, '');
|
|
67
68
|
return EVIDENCE.some((test) => test.test(text)) ? 1 : 0;
|
|
68
69
|
}
|
|
69
|
-
function buildTitle(turn, files) {
|
|
70
|
+
function buildTitle(turn, files, kind) {
|
|
71
|
+
if (kind === 'preference') {
|
|
72
|
+
const rule = firstSentence(redact(turn.prompt));
|
|
73
|
+
if (rule)
|
|
74
|
+
return headline(rule);
|
|
75
|
+
}
|
|
70
76
|
const prose = stripMarkdown(redact(turn.reasoning));
|
|
71
77
|
const scored = scoreSentences(prose);
|
|
72
78
|
const best = scored.find(([, score]) => score > 0) ?? scored.find(([, score]) => score === 0);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function cmdAdoption(): Promise<void>;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createContext } from '../../context.js';
|
|
3
|
+
import { queryGraph } from '../../graph/index.js';
|
|
4
|
+
import { transcriptsFor } from '../../capture/transcript.js';
|
|
5
|
+
import { resolveProject } from '../../util/project.js';
|
|
6
|
+
import { DECLARED, isSymbol, symbolsGreppedIn } from '../../hooks/grep-symbols.js';
|
|
7
|
+
export async function cmdAdoption() {
|
|
8
|
+
const project = resolveProject(undefined);
|
|
9
|
+
const files = transcriptsFor(project);
|
|
10
|
+
if (files.length === 0) {
|
|
11
|
+
console.log(`No transcripts found for ${project}.`);
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
const bash = [];
|
|
16
|
+
const memory = new Map();
|
|
17
|
+
for (const file of files) {
|
|
18
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
19
|
+
if (!line.includes('"tool_use"'))
|
|
20
|
+
continue;
|
|
21
|
+
let entry;
|
|
22
|
+
try {
|
|
23
|
+
entry = JSON.parse(line);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const content = entry?.message?.content;
|
|
29
|
+
if (!Array.isArray(content))
|
|
30
|
+
continue;
|
|
31
|
+
for (const item of content) {
|
|
32
|
+
if (item?.type !== 'tool_use' || typeof item.id !== 'string' || seen.has(item.id))
|
|
33
|
+
continue;
|
|
34
|
+
seen.add(item.id);
|
|
35
|
+
const name = typeof item.name === 'string' ? item.name : '';
|
|
36
|
+
if (name === 'Bash' && typeof item.input?.command === 'string') {
|
|
37
|
+
bash.push(item.input.command);
|
|
38
|
+
}
|
|
39
|
+
if (name.startsWith('mcp__memory__')) {
|
|
40
|
+
const tool = name.slice('mcp__memory__'.length);
|
|
41
|
+
memory.set(tool, (memory.get(tool) ?? 0) + 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const greps = bash.filter((command) => /\b(?:grep|rg)\b/.test(command));
|
|
47
|
+
const candidates = greps.map((command) => symbolsGreppedIn(command)).filter((s) => s.length > 0);
|
|
48
|
+
const ctx = await createContext();
|
|
49
|
+
let fires = 0;
|
|
50
|
+
const cache = new Map();
|
|
51
|
+
try {
|
|
52
|
+
for (const symbols of candidates) {
|
|
53
|
+
let hit = false;
|
|
54
|
+
for (const symbol of symbols.slice(0, 2)) {
|
|
55
|
+
let fired = cache.get(symbol);
|
|
56
|
+
if (fired === undefined) {
|
|
57
|
+
const answer = await queryGraph(ctx.store, project, { mode: 'usages', symbol, limit: 20 });
|
|
58
|
+
fired =
|
|
59
|
+
!answer.empty &&
|
|
60
|
+
(isSymbol(symbol) || answer.definitions.some((d) => DECLARED.has(d.kind)));
|
|
61
|
+
cache.set(symbol, fired);
|
|
62
|
+
}
|
|
63
|
+
if (fired)
|
|
64
|
+
hit = true;
|
|
65
|
+
}
|
|
66
|
+
if (hit)
|
|
67
|
+
fires++;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
await ctx.close();
|
|
72
|
+
}
|
|
73
|
+
const memoryTotal = [...memory.values()].reduce((a, b) => a + b, 0);
|
|
74
|
+
const pct = (n, of) => (of === 0 ? '0.0%' : `${((n / of) * 100).toFixed(1)}%`);
|
|
75
|
+
console.log(`Adoption for ${project} (${files.length} transcripts)\n`);
|
|
76
|
+
console.log(` Bash commands ${bash.length}`);
|
|
77
|
+
console.log(` containing grep/rg ${greps.length} (${pct(greps.length, bash.length)})`);
|
|
78
|
+
console.log(` usages-hook candidates ${candidates.length}`);
|
|
79
|
+
console.log(` would fire today ${fires} (${pct(fires, bash.length)} of all commands)`);
|
|
80
|
+
console.log(`\n memory tool calls ${memoryTotal}`);
|
|
81
|
+
for (const [tool, count] of [...memory].sort((a, b) => b[1] - a[1])) {
|
|
82
|
+
console.log(` ${tool.padEnd(18)} ${count}`);
|
|
83
|
+
}
|
|
84
|
+
if (greps.length > 0) {
|
|
85
|
+
const ratio = memoryTotal === 0 ? 'no memory calls yet' : `${(greps.length / memoryTotal).toFixed(1)} greps per memory call`;
|
|
86
|
+
console.log(`\n ${ratio}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
package/dist/cli/index.js
CHANGED
|
@@ -11,6 +11,7 @@ import { cmdMerge, cmdProjects, cmdStats } from './commands/insight.js';
|
|
|
11
11
|
import { cmdFlush, cmdReset, cmdUpdate } from './commands/maintain.js';
|
|
12
12
|
import { cmdScan, cmdUsages } from './commands/graph.js';
|
|
13
13
|
import { cmdSeed } from './commands/seed.js';
|
|
14
|
+
import { cmdAdoption } from './commands/adoption.js';
|
|
14
15
|
import { silenceSqliteWarning } from '../util/warnings.js';
|
|
15
16
|
silenceSqliteWarning();
|
|
16
17
|
const [command, ...args] = process.argv.slice(2);
|
|
@@ -62,6 +63,9 @@ async function run() {
|
|
|
62
63
|
case 'stats':
|
|
63
64
|
await cmdStats();
|
|
64
65
|
break;
|
|
66
|
+
case 'adoption':
|
|
67
|
+
await cmdAdoption();
|
|
68
|
+
break;
|
|
65
69
|
case 'update':
|
|
66
70
|
await cmdUpdate(args);
|
|
67
71
|
break;
|
package/dist/cli/install.js
CHANGED
|
@@ -36,16 +36,17 @@ export function install(distDir, scope, project) {
|
|
|
36
36
|
const settings = readJson(path);
|
|
37
37
|
const hooks = (settings['hooks'] ?? {});
|
|
38
38
|
for (const [event, file, matcher] of HOOKS) {
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
39
|
+
const kept = (hooks[event] ?? [])
|
|
40
|
+
.map((entry) => ({
|
|
41
|
+
...entry,
|
|
42
|
+
hooks: entry.hooks.filter((hook) => !isOurHook(hook.command)),
|
|
43
|
+
}))
|
|
44
|
+
.filter((entry) => entry.hooks.length > 0);
|
|
45
|
+
kept.push({
|
|
45
46
|
...(matcher ? { matcher } : {}),
|
|
46
|
-
hooks: [{ type: 'command', command }],
|
|
47
|
+
hooks: [{ type: 'command', command: hookCommand(distDir, file) }],
|
|
47
48
|
});
|
|
48
|
-
hooks[event] =
|
|
49
|
+
hooks[event] = kept;
|
|
49
50
|
}
|
|
50
51
|
settings['hooks'] = hooks;
|
|
51
52
|
delete settings['mcpServers'];
|
|
@@ -81,13 +82,12 @@ export function uninstall(distDir, scope, project) {
|
|
|
81
82
|
const settings = readJson(path);
|
|
82
83
|
if (Object.keys(settings).length === 0)
|
|
83
84
|
return null;
|
|
84
|
-
const ours = new Set(HOOKS.map(([, file]) => hookCommand(distDir, file)));
|
|
85
85
|
const hooks = (settings['hooks'] ?? {});
|
|
86
86
|
for (const [event, entries] of Object.entries(hooks)) {
|
|
87
87
|
const kept = entries
|
|
88
88
|
.map((entry) => ({
|
|
89
89
|
...entry,
|
|
90
|
-
hooks: entry.hooks.filter((hook) => !
|
|
90
|
+
hooks: entry.hooks.filter((hook) => !isOurHook(hook.command)),
|
|
91
91
|
}))
|
|
92
92
|
.filter((entry) => entry.hooks.length > 0);
|
|
93
93
|
if (kept.length > 0)
|
|
@@ -121,3 +121,7 @@ export function uninstall(distDir, scope, project) {
|
|
|
121
121
|
function hookCommand(distDir, file) {
|
|
122
122
|
return `node ${resolve(distDir, 'hooks', file)}`;
|
|
123
123
|
}
|
|
124
|
+
function isOurHook(command) {
|
|
125
|
+
const path = command.replace(/\\/g, '/');
|
|
126
|
+
return HOOKS.some(([, file]) => path.endsWith(`/hooks/${file}`));
|
|
127
|
+
}
|
package/dist/cli/instructions.js
CHANGED
|
@@ -6,11 +6,12 @@ export const INSTRUCTIONS = [
|
|
|
6
6
|
BLOCK_START,
|
|
7
7
|
'## Project memory',
|
|
8
8
|
'',
|
|
9
|
-
'
|
|
10
|
-
'
|
|
11
|
-
'
|
|
9
|
+
'You have persistent memory of this project: your past sessions, decisions',
|
|
10
|
+
'and their reasoning, served by the `memory` MCP server. Session summaries',
|
|
11
|
+
'are injected at startup and the best matching observation is injected above',
|
|
12
|
+
'each prompt, but that is only ever a slice of what you know.',
|
|
12
13
|
'',
|
|
13
|
-
'
|
|
14
|
+
'Recall the rest *before* re-deriving something you already learned. That',
|
|
14
15
|
'means before grepping or reading git history to reconstruct why something is',
|
|
15
16
|
'the way it is, before saying you lack context, and before asking the user to',
|
|
16
17
|
're-explain a past decision or a failed approach: call `search`, then',
|
package/dist/cli/usage.js
CHANGED
|
@@ -15,6 +15,7 @@ export function usage() {
|
|
|
15
15
|
projects List every project with memory in this database
|
|
16
16
|
merge [<old-path>] [--yes] Move memory from an old project path onto this one
|
|
17
17
|
stats What this project's memory is made of
|
|
18
|
+
adoption How often sessions grep vs use the memory tools
|
|
18
19
|
flush Re-ingest every transcript for this project
|
|
19
20
|
seed --from-git [--limit n] Fill a cold memory from this repo's history
|
|
20
21
|
scan [--force] Map this repo's symbols and how they connect
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export declare const DECLARED: Set<string>;
|
|
1
2
|
export declare function isSymbol(pattern: string): boolean;
|
|
3
|
+
export declare function isWord(pattern: string): boolean;
|
|
2
4
|
/** Symbols a shell command searches the tree for, which the code graph also answers. */
|
|
3
5
|
export declare function symbolsGreppedIn(command: string): string[];
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
const SYMBOL = /^(?=.{4,})(?:[a-z]+(?:[A-Z][a-zA-Z0-9]*)+|[A-Z][a-z0-9]+(?:[A-Z][a-zA-Z0-9]*)*|[a-z][a-z0-9]*(?:_[a-z0-9]+)+)$/;
|
|
2
|
-
const
|
|
2
|
+
const WORD = /^[a-z][a-z0-9]{3,}$/;
|
|
3
|
+
export const DECLARED = new Set(['function', 'method', 'class', 'interface', 'type', 'enum']);
|
|
4
|
+
const GREP = /\b(?:grep|rg)\b((?:\s+(?:-[ABC]\s?\d+|-[tTg]\s\S+|-{1,2}[\w-]+(?:=\S+)?))*)\s+(?:(['"])(.+?)\2|(\S+))([^;&|]*)/g;
|
|
3
5
|
export function isSymbol(pattern) {
|
|
4
6
|
return SYMBOL.test(pattern);
|
|
5
7
|
}
|
|
8
|
+
export function isWord(pattern) {
|
|
9
|
+
return WORD.test(pattern);
|
|
10
|
+
}
|
|
6
11
|
/** Symbols a shell command searches the tree for, which the code graph also answers. */
|
|
7
12
|
export function symbolsGreppedIn(command) {
|
|
8
13
|
const found = new Set();
|
|
@@ -10,13 +15,17 @@ export function symbolsGreppedIn(command) {
|
|
|
10
15
|
const flags = match[1] ?? '';
|
|
11
16
|
const pattern = match[3] ?? match[4] ?? '';
|
|
12
17
|
const rest = match[5] ?? '';
|
|
13
|
-
if (!SYMBOL.test(pattern))
|
|
18
|
+
if (!SYMBOL.test(pattern) && !WORD.test(pattern))
|
|
14
19
|
continue;
|
|
15
20
|
if (/-\w*v/.test(flags))
|
|
16
21
|
continue;
|
|
17
|
-
|
|
22
|
+
const before = command.slice(0, match.index);
|
|
23
|
+
const searchesTree = /-\w*[rR]\b|--recursive/.test(flags) ||
|
|
24
|
+
/^\s+[^-|;&>][^\s|;&>]*/.test(rest) ||
|
|
25
|
+
/\bgit\s+$/.test(before) ||
|
|
26
|
+
(match[0].startsWith('rg') && !/\|\s*$/.test(before));
|
|
27
|
+
if (searchesTree)
|
|
18
28
|
found.add(pattern);
|
|
19
|
-
}
|
|
20
29
|
}
|
|
21
30
|
return [...found].sort();
|
|
22
31
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createContext } from '../context.js';
|
|
3
3
|
import { formatGraph, queryGraph } from '../graph/index.js';
|
|
4
|
-
import { isSymbol, symbolsGreppedIn } from './grep-symbols.js';
|
|
4
|
+
import { DECLARED, isSymbol, isWord, symbolsGreppedIn } from './grep-symbols.js';
|
|
5
5
|
import { readPayload, runHook } from './payload.js';
|
|
6
6
|
import { resolveProject } from '../util/project.js';
|
|
7
7
|
import { silenceSqliteWarning } from '../util/warnings.js';
|
|
@@ -12,7 +12,7 @@ function requested(payload) {
|
|
|
12
12
|
const input = payload.tool_input ?? {};
|
|
13
13
|
if (payload.tool_name === 'Grep') {
|
|
14
14
|
const pattern = typeof input['pattern'] === 'string' ? input['pattern'] : '';
|
|
15
|
-
return isSymbol(pattern) ? [pattern] : [];
|
|
15
|
+
return isSymbol(pattern) || isWord(pattern) ? [pattern] : [];
|
|
16
16
|
}
|
|
17
17
|
if (payload.tool_name === 'Bash') {
|
|
18
18
|
return symbolsGreppedIn(typeof input['command'] === 'string' ? input['command'] : '');
|
|
@@ -26,7 +26,8 @@ function trim(answer) {
|
|
|
26
26
|
return [...lines.slice(0, MAX_LINES), ` ... more via find_usages`].join('\n');
|
|
27
27
|
}
|
|
28
28
|
await runHook(async () => {
|
|
29
|
-
|
|
29
|
+
const mode = process.env['CLAUDE_DB_USAGES_HOOK'] ?? 'deny';
|
|
30
|
+
if (mode === 'off')
|
|
30
31
|
return;
|
|
31
32
|
const payload = await readPayload();
|
|
32
33
|
const symbols = requested(payload).slice(0, MAX_SYMBOLS);
|
|
@@ -35,11 +36,15 @@ await runHook(async () => {
|
|
|
35
36
|
const project = resolveProject(payload.cwd);
|
|
36
37
|
const ctx = await createContext();
|
|
37
38
|
const blocks = [];
|
|
39
|
+
const named = [];
|
|
38
40
|
try {
|
|
39
41
|
for (const symbol of symbols) {
|
|
40
42
|
const answer = await queryGraph(ctx.store, project, { mode: 'usages', symbol, limit: 20 });
|
|
41
43
|
if (answer.empty)
|
|
42
44
|
continue;
|
|
45
|
+
if (!isSymbol(symbol) && !answer.definitions.some((d) => DECLARED.has(d.kind)))
|
|
46
|
+
continue;
|
|
47
|
+
named.push(symbol);
|
|
43
48
|
blocks.push(trim(formatGraph(answer, project)));
|
|
44
49
|
}
|
|
45
50
|
}
|
|
@@ -48,11 +53,26 @@ await runHook(async () => {
|
|
|
48
53
|
}
|
|
49
54
|
if (blocks.length === 0)
|
|
50
55
|
return;
|
|
56
|
+
const names = named.map((s) => `\`${s}\``).join(', ');
|
|
57
|
+
if (mode === 'directive') {
|
|
58
|
+
process.stdout.write(JSON.stringify({
|
|
59
|
+
hookSpecificOutput: {
|
|
60
|
+
hookEventName: 'PreToolUse',
|
|
61
|
+
additionalContext: `You are grepping the declared symbol(s) ${names}. Use the \`find_usages\` MCP ` +
|
|
62
|
+
`tool for symbol lookups — grep cannot tell a call from an import or show the ` +
|
|
63
|
+
`blast radius. The graph's answer for this search is below; read it instead of ` +
|
|
64
|
+
`the grep output, and call find_usages directly next time:\n\n${blocks.join('\n\n')}`,
|
|
65
|
+
},
|
|
66
|
+
}));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
51
69
|
process.stdout.write(JSON.stringify({
|
|
52
70
|
hookSpecificOutput: {
|
|
53
71
|
hookEventName: 'PreToolUse',
|
|
54
|
-
|
|
55
|
-
|
|
72
|
+
permissionDecision: 'deny',
|
|
73
|
+
permissionDecisionReason: `Blocked: ${names} names a declared symbol — use the \`find_usages\` MCP tool ` +
|
|
74
|
+
`for symbol lookups, not grep. Its answer for this search is already below, so ` +
|
|
75
|
+
`nothing needs re-running:\n\n${blocks.join('\n\n')}`,
|
|
56
76
|
},
|
|
57
77
|
}));
|
|
58
78
|
});
|
|
@@ -7,6 +7,7 @@ import { createContext } from '../context.js';
|
|
|
7
7
|
import { openWork } from '../capture/index.js';
|
|
8
8
|
import { emitContext, readPayload, runHook } from './payload.js';
|
|
9
9
|
import { resolveProject } from '../util/project.js';
|
|
10
|
+
import { toShortId } from '../util/shortid.js';
|
|
10
11
|
import { refreshInstalled } from '../cli/refresh.js';
|
|
11
12
|
import { updateNotice } from '../update.js';
|
|
12
13
|
import { silenceSqliteWarning } from '../util/warnings.js';
|
|
@@ -72,6 +73,24 @@ await runHook(async () => {
|
|
|
72
73
|
lines.push(`- ${obs.title}`);
|
|
73
74
|
}
|
|
74
75
|
}
|
|
76
|
+
const rules = (await ctx.store.list({ project, kind: 'preference', limit: 100 }))
|
|
77
|
+
.sort((a, b) => {
|
|
78
|
+
const manual = Number(b.sessionId === 'manual') - Number(a.sessionId === 'manual');
|
|
79
|
+
return manual !== 0 ? manual : b.createdAt - a.createdAt;
|
|
80
|
+
})
|
|
81
|
+
.slice(0, 8);
|
|
82
|
+
if (rules.length > 0) {
|
|
83
|
+
lines.push('');
|
|
84
|
+
lines.push('Standing rules on record — expand any id with get_observations:');
|
|
85
|
+
for (const obs of rules) {
|
|
86
|
+
const when = new Date(obs.createdAt).toISOString().slice(0, 10);
|
|
87
|
+
const line = `- ${toShortId(obs.id)} [${when}] ${obs.title}`.slice(0, 140);
|
|
88
|
+
if (line.length > budget)
|
|
89
|
+
break;
|
|
90
|
+
budget -= line.length;
|
|
91
|
+
lines.push(line);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
75
94
|
lines.push('</project-memory>');
|
|
76
95
|
if (mcpRegistered(project)) {
|
|
77
96
|
lines.push("Search this project's full history with the memory MCP tools before " +
|
package/dist/mcp/tools/memory.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { KINDS } from './kinds.js';
|
|
3
|
-
import { remember } from '../../capture/index.js';
|
|
3
|
+
import { remember as record } from '../../capture/index.js';
|
|
4
4
|
import { toShortId } from '../../util/shortid.js';
|
|
5
5
|
import { resolveProject } from '../../util/project.js';
|
|
6
6
|
export function register(server, ctx) {
|
|
@@ -17,28 +17,30 @@ export function register(server, ctx) {
|
|
|
17
17
|
.describe('Stable name for a note meant to be kept current, e.g. "profile:stack". ' +
|
|
18
18
|
'Remembering the same key again replaces it instead of adding a duplicate'),
|
|
19
19
|
tags: z.array(z.string()).max(5).optional().describe('Extra tags for filtering'),
|
|
20
|
-
},
|
|
21
|
-
const observation = await remember(ctx, {
|
|
22
|
-
project: resolveProject(project),
|
|
23
|
-
text,
|
|
24
|
-
kind,
|
|
25
|
-
...(key ? { key } : {}),
|
|
26
|
-
...(tags ? { tags } : {}),
|
|
27
|
-
});
|
|
28
|
-
return {
|
|
29
|
-
content: [
|
|
30
|
-
{
|
|
31
|
-
type: 'text',
|
|
32
|
-
text: `Remembered ${toShortId(observation.id)} [${observation.kind}] ${observation.title}`,
|
|
33
|
-
},
|
|
34
|
-
],
|
|
35
|
-
};
|
|
36
|
-
});
|
|
20
|
+
}, (args) => remember(ctx, args));
|
|
37
21
|
server.tool('forget', 'Delete observations by id, for memory that is wrong or obsolete. Ids come ' +
|
|
38
|
-
'from search. This cannot be undone, so confirm with the user first.', { ids: z.array(z.string()).min(1).max(25) },
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
22
|
+
'from search. This cannot be undone, so confirm with the user first.', { ids: z.array(z.string()).min(1).max(25) }, (args) => forget(ctx, args));
|
|
23
|
+
}
|
|
24
|
+
async function remember(ctx, { text, kind, project, key, tags, }) {
|
|
25
|
+
const observation = await record(ctx, {
|
|
26
|
+
project: resolveProject(project),
|
|
27
|
+
text,
|
|
28
|
+
kind,
|
|
29
|
+
...(key ? { key } : {}),
|
|
30
|
+
...(tags ? { tags } : {}),
|
|
43
31
|
});
|
|
32
|
+
return {
|
|
33
|
+
content: [
|
|
34
|
+
{
|
|
35
|
+
type: 'text',
|
|
36
|
+
text: `Remembered ${toShortId(observation.id)} [${observation.kind}] ${observation.title}`,
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
async function forget(ctx, { ids }) {
|
|
42
|
+
const deleted = await ctx.store.remove({ ids });
|
|
43
|
+
return {
|
|
44
|
+
content: [{ type: 'text', text: `Forgot ${deleted} observation(s).` }],
|
|
45
|
+
};
|
|
44
46
|
}
|
|
@@ -8,18 +8,7 @@ export function register(server, ctx) {
|
|
|
8
8
|
observation_id: z.string(),
|
|
9
9
|
before: z.number().int().min(0).max(20).default(5),
|
|
10
10
|
after: z.number().int().min(0).max(20).default(5),
|
|
11
|
-
},
|
|
12
|
-
const entries = await ctx.search.timeline({ observationId: observation_id, before, after });
|
|
13
|
-
if (entries.length === 0) {
|
|
14
|
-
const [found] = await ctx.search.getObservations([observation_id]);
|
|
15
|
-
const text = found
|
|
16
|
-
? `No observations around ${observation_id}; it has no neighbours in that session.`
|
|
17
|
-
: `No observation with id ${observation_id}. Ids come from search, and are the short ` +
|
|
18
|
-
`ids it prints — run search first and pass one of those.`;
|
|
19
|
-
return { content: [{ type: 'text', text }] };
|
|
20
|
-
}
|
|
21
|
-
return { content: [{ type: 'text', text: renderIndex(entries) }] };
|
|
22
|
-
});
|
|
11
|
+
}, (args) => timeline(ctx, args));
|
|
23
12
|
server.tool('get_observations', 'Read the full body of observations search has already found, using the short ' +
|
|
24
13
|
'ids it printed. Use it whenever a search snippet looks like it answers your ' +
|
|
25
14
|
'question but is cut off — the snippet is one line, the body is the reasoning. ' +
|
|
@@ -34,22 +23,35 @@ export function register(server, ctx) {
|
|
|
34
23
|
.describe('Characters of each body to return. Bodies run to 4000 and this call ' +
|
|
35
24
|
'takes 25 ids, so the default keeps a batch readable; raise it when a ' +
|
|
36
25
|
'truncated answer says there is more'),
|
|
37
|
-
},
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
26
|
+
}, (args) => get_observations(ctx, args));
|
|
27
|
+
}
|
|
28
|
+
async function timeline(ctx, { observation_id, before, after, }) {
|
|
29
|
+
const entries = await ctx.search.timeline({ observationId: observation_id, before, after });
|
|
30
|
+
if (entries.length === 0) {
|
|
31
|
+
const [found] = await ctx.search.getObservations([observation_id]);
|
|
32
|
+
const text = found
|
|
33
|
+
? `No observations around ${observation_id}; it has no neighbours in that session.`
|
|
34
|
+
: `No observation with id ${observation_id}. Ids come from search, and are the short ` +
|
|
35
|
+
`ids it prints — run search first and pass one of those.`;
|
|
36
|
+
return { content: [{ type: 'text', text }] };
|
|
37
|
+
}
|
|
38
|
+
return { content: [{ type: 'text', text: renderIndex(entries) }] };
|
|
39
|
+
}
|
|
40
|
+
async function get_observations(ctx, { ids, chars }) {
|
|
41
|
+
const observations = await ctx.search.getObservations(ids);
|
|
42
|
+
if (observations.length === 0) {
|
|
43
|
+
return {
|
|
44
|
+
content: [
|
|
45
|
+
{
|
|
46
|
+
type: 'text',
|
|
47
|
+
text: `No observation matched ${ids.join(', ')}. Ids come from search — run it first ` +
|
|
48
|
+
`and pass the short ids it prints.`,
|
|
49
|
+
},
|
|
50
|
+
],
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
const missing = ids.filter((id) => !observations.some((obs) => obs.id === id || obs.id.startsWith(id)));
|
|
54
|
+
const body = observations.map((obs) => renderFull(obs, chars)).join('\n\n---\n\n');
|
|
55
|
+
const note = missing.length > 0 ? `\n\n(no observation matched ${missing.join(', ')})` : '';
|
|
56
|
+
return { content: [{ type: 'text', text: body + note }] };
|
|
55
57
|
}
|
package/dist/mcp/tools/search.js
CHANGED
|
@@ -24,19 +24,20 @@ export function register(server, ctx) {
|
|
|
24
24
|
.describe('Limit to one repository or top-level directory, e.g. "backend". Useful ' +
|
|
25
25
|
'when a workspace pools several repos under one project'),
|
|
26
26
|
limit: z.number().int().min(1).max(50).default(10),
|
|
27
|
-
},
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
})
|
|
35
|
-
|
|
36
|
-
return { content: [{ type: 'text', text: await noMatches(ctx, project) }] };
|
|
37
|
-
}
|
|
38
|
-
return { content: [{ type: 'text', text: renderIndex(entries) }] };
|
|
27
|
+
}, (args) => search(ctx, args));
|
|
28
|
+
}
|
|
29
|
+
async function search(ctx, { query, project, kind, tag, limit, }) {
|
|
30
|
+
const entries = await ctx.search.search({
|
|
31
|
+
text: query,
|
|
32
|
+
limit,
|
|
33
|
+
...(project === '*' ? {} : { project: resolveProject(project) }),
|
|
34
|
+
...(kind ? { kind } : {}),
|
|
35
|
+
...(tag ? { tag } : {}),
|
|
39
36
|
});
|
|
37
|
+
if (entries.length === 0) {
|
|
38
|
+
return { content: [{ type: 'text', text: await noMatches(ctx, project) }] };
|
|
39
|
+
}
|
|
40
|
+
return { content: [{ type: 'text', text: renderIndex(entries) }] };
|
|
40
41
|
}
|
|
41
42
|
async function noMatches(ctx, project) {
|
|
42
43
|
const scope = project === '*' ? undefined : resolveProject(project);
|
package/dist/mcp/tools/usages.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { findUsages, formatUsages, repoRootFor } from '../../usages/index.js';
|
|
2
|
+
import { findUsages as textUsages, formatUsages, repoRootFor } from '../../usages/index.js';
|
|
3
3
|
import { formatGraph, queryGraph, refreshGraph, suggestFor } from '../../graph/index.js';
|
|
4
4
|
import { resolveProject } from '../../util/project.js';
|
|
5
5
|
export function register(server, ctx) {
|
|
@@ -56,24 +56,25 @@ export function register(server, ctx) {
|
|
|
56
56
|
.max(500)
|
|
57
57
|
.default(100)
|
|
58
58
|
.describe('Cap on matching lines returned; the result says how many more exist'),
|
|
59
|
-
},
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
})
|
|
76
|
-
|
|
77
|
-
return { content: [{ type: 'text', text: formatGraph(answer, root) }] };
|
|
59
|
+
}, (args) => find_usages(ctx, args));
|
|
60
|
+
}
|
|
61
|
+
async function find_usages(ctx, { symbol, mode, target, path, regex, context, limit, }) {
|
|
62
|
+
if (mode === 'text') {
|
|
63
|
+
const result = textUsages({ symbol, regex, context, limit, ...(path ? { path } : {}) });
|
|
64
|
+
const missed = result.matches.length === 0
|
|
65
|
+
? await suggestFor(ctx.store, resolveProject(undefined), symbol)
|
|
66
|
+
: [];
|
|
67
|
+
return { content: [{ type: 'text', text: formatUsages(result, missed) }] };
|
|
68
|
+
}
|
|
69
|
+
const root = repoRootFor(path ?? process.cwd());
|
|
70
|
+
const project = resolveProject(undefined);
|
|
71
|
+
const refreshed = await refreshGraph(ctx.store, root, project);
|
|
72
|
+
const answer = await queryGraph(ctx.store, project, {
|
|
73
|
+
mode,
|
|
74
|
+
symbol,
|
|
75
|
+
...(target ? { target } : {}),
|
|
76
|
+
limit,
|
|
78
77
|
});
|
|
78
|
+
answer.refreshed = refreshed;
|
|
79
|
+
return { content: [{ type: 'text', text: formatGraph(answer, root) }] };
|
|
79
80
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-db",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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",
|