claude-db 0.6.0 → 0.8.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/README.md +11 -3
  3. package/dist/capture/flush.js +0 -4
  4. package/dist/capture/index.d.ts +1 -0
  5. package/dist/capture/index.js +1 -0
  6. package/dist/capture/summarize.d.ts +3 -0
  7. package/dist/capture/summarize.js +32 -0
  8. package/dist/capture/turn-extractor.js +21 -6
  9. package/dist/cli/commands/adoption.d.ts +1 -0
  10. package/dist/cli/commands/adoption.js +94 -0
  11. package/dist/cli/commands/doctor.js +39 -0
  12. package/dist/cli/commands/setup.js +10 -0
  13. package/dist/cli/commands/view-page.d.ts +2 -0
  14. package/dist/cli/commands/view-page.js +151 -0
  15. package/dist/cli/commands/view.d.ts +23 -0
  16. package/dist/cli/commands/view.js +99 -0
  17. package/dist/cli/index.js +8 -0
  18. package/dist/cli/install.js +22 -12
  19. package/dist/cli/instructions.js +5 -4
  20. package/dist/cli/usage.js +2 -0
  21. package/dist/config/schema.d.ts +10 -0
  22. package/dist/config/schema.js +3 -0
  23. package/dist/graph/languages/basic.d.ts +11 -0
  24. package/dist/graph/languages/basic.js +156 -0
  25. package/dist/graph/languages/index.d.ts +1 -0
  26. package/dist/graph/languages/index.js +7 -4
  27. package/dist/graph/languages/ruby.d.ts +2 -0
  28. package/dist/graph/languages/ruby.js +16 -0
  29. package/dist/graph/languages/rules.d.ts +1 -0
  30. package/dist/graph/query/suggest.d.ts +0 -1
  31. package/dist/graph/query/suggest.js +2 -9
  32. package/dist/graph/scan/extract.d.ts +1 -0
  33. package/dist/graph/scan/extract.js +43 -2
  34. package/dist/graph/scan/files.d.ts +1 -1
  35. package/dist/graph/scan/files.js +3 -2
  36. package/dist/graph/scan/resolve.js +2 -0
  37. package/dist/hooks/grep-symbols.d.ts +2 -1
  38. package/dist/hooks/grep-symbols.js +14 -5
  39. package/dist/hooks/prefer-usages.js +25 -5
  40. package/dist/hooks/relevance.d.ts +4 -0
  41. package/dist/hooks/relevance.js +10 -0
  42. package/dist/hooks/session-end.js +11 -2
  43. package/dist/hooks/session-start.js +28 -2
  44. package/dist/hooks/user-prompt.js +6 -3
  45. package/dist/mcp/tools/memory.js +25 -23
  46. package/dist/mcp/tools/observations.js +32 -30
  47. package/dist/mcp/tools/search.js +13 -12
  48. package/dist/mcp/tools/usages.js +21 -20
  49. package/package.json +5 -3
@@ -1,20 +1,17 @@
1
1
  const CANDIDATES = 5000;
2
2
  function tokens(name) {
3
- return (name
3
+ return name
4
4
  .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
5
5
  .split(/[^A-Za-z0-9]+/)
6
6
  .filter(Boolean)
7
7
  .map((part) => part.toLowerCase())
8
- // Stem the plural: "hooks" and "hook" are the same misremembered name.
9
- .map((part) => (part.length > 3 && part.endsWith('s') ? part.slice(0, -1) : part)));
8
+ .map((part) => (part.length > 3 && part.endsWith('s') ? part.slice(0, -1) : part));
10
9
  }
11
10
  function score(candidate, query) {
12
11
  const left = candidate.toLowerCase();
13
12
  const right = query.toLowerCase();
14
13
  if (left === right)
15
14
  return 100;
16
- // Ratios are taken against the LONGER name: without that, one-letter locals
17
- // score as well as the real symbol, because everything contains "e".
18
15
  const longest = Math.max(left.length, right.length);
19
16
  let prefix = 0;
20
17
  while (prefix < left.length && prefix < right.length && left[prefix] === right[prefix]) {
@@ -29,16 +26,12 @@ function score(candidate, query) {
29
26
  const byContains = contains ? (Math.min(left.length, right.length) / longest) * 100 : 0;
30
27
  return Math.max(byPrefix, byToken, byContains);
31
28
  }
32
- /** Names closest to `symbol`, best first. A miss that names no alternative is where people quit. */
33
29
  export function nearest(names, symbol, limit = 5) {
34
30
  const scored = new Map();
35
31
  for (const name of names) {
36
- // Two-character locals are never what someone misremembered.
37
32
  if (name === symbol || name.length < 3)
38
33
  continue;
39
34
  const value = score(name, symbol);
40
- // Below this, matches are incidental ("widget" contains "get") and a wrong
41
- // suggestion costs more than none: it sends you looking for the wrong thing.
42
35
  if (value >= 40)
43
36
  scored.set(name, Math.max(scored.get(name) ?? 0, value));
44
37
  }
@@ -6,6 +6,7 @@ export interface Reference {
6
6
  relation: EdgeRelation;
7
7
  line: number;
8
8
  from: CodeSymbol | null;
9
+ weak?: boolean;
9
10
  }
10
11
  export interface Extraction {
11
12
  symbols: CodeSymbol[];
@@ -1,11 +1,50 @@
1
1
  import { observationId } from '../../capture/identity.js';
2
2
  import { redact } from '../../capture/turn-extractor.js';
3
+ import { callsIn, declarationsIn } from '../languages/index.js';
3
4
  import { languageHandle, loadParser } from '../parser.js';
4
5
  const CALLABLE = new Set(['function', 'method', 'class']);
5
- const IDENTIFIER = /^[\w$]+$/;
6
+ const IDENTIFIER = /^[\w$]+[?!]?$/;
6
7
  export function symbolId(project, file, name, kind) {
7
8
  return observationId('graph', 0, `${project}\0${file}\0${name}\0${kind}`);
8
9
  }
10
+ function extractByPattern(file, project) {
11
+ const lines = file.source.split('\n');
12
+ const symbols = [];
13
+ const spans = [];
14
+ for (const declaration of declarationsIn(file.source)) {
15
+ const symbol = {
16
+ id: symbolId(project, file.path, declaration.name, declaration.kind),
17
+ project,
18
+ name: declaration.name,
19
+ kind: declaration.kind,
20
+ file: file.path,
21
+ line: declaration.line,
22
+ lang: file.spec.label,
23
+ signature: redact((lines[declaration.line - 1] ?? '').trim()).slice(0, 200),
24
+ };
25
+ symbols.push(symbol);
26
+ spans.push({ start: declaration.line, end: declaration.line, symbol });
27
+ }
28
+ const references = callsIn(file.source).map((call) => ({
29
+ file: file.path,
30
+ name: call.name,
31
+ relation: 'calls',
32
+ line: call.line,
33
+ from: nearestAbove(call.line, spans),
34
+ weak: true,
35
+ }));
36
+ return { symbols, references };
37
+ }
38
+ function nearestAbove(line, spans) {
39
+ let best = null;
40
+ for (const span of spans) {
41
+ if (span.start > line)
42
+ continue;
43
+ if (!best || span.start > best.start)
44
+ best = span;
45
+ }
46
+ return best?.symbol ?? null;
47
+ }
9
48
  function resolveField(node, path) {
10
49
  let current = node;
11
50
  for (const name of path) {
@@ -16,7 +55,7 @@ function resolveField(node, path) {
16
55
  return current;
17
56
  }
18
57
  function unquote(text) {
19
- return text.replace(/^['"`]|['"`]$/g, '');
58
+ return text.replace(/^['"`]|['"`]$/g, '').replace(/^[<(:\s]+|[)\s]+$/g, '');
20
59
  }
21
60
  function enclosing(line, spans) {
22
61
  let best = null;
@@ -38,6 +77,8 @@ function enclosing(line, spans) {
38
77
  return (best ?? fallback)?.symbol ?? null;
39
78
  }
40
79
  export function extractFile(file, project) {
80
+ if (file.spec.basic)
81
+ return extractByPattern(file, project);
41
82
  const parser = loadParser();
42
83
  const root = parser.parse(languageHandle(parser, file.spec.id), file.source).root();
43
84
  const lines = file.source.split('\n');
@@ -5,7 +5,7 @@ export interface SourceFile {
5
5
  source: string;
6
6
  hash: string;
7
7
  }
8
- export declare const SCAN_VERSION = 2;
8
+ export declare const SCAN_VERSION = 3;
9
9
  export declare function hashOf(bytes: Buffer): string;
10
10
  export declare function listFiles(root: string): string[];
11
11
  export declare function sourceFiles(root: string): string[];
@@ -2,12 +2,13 @@ import { execFileSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
- import { LANGUAGES, languageFor } from '../languages/index.js';
5
+ import { BASIC_FINGERPRINT, LANGUAGES, languageFor } from '../languages/index.js';
6
6
  const MAX_BUFFER = 64 * 1024 * 1024;
7
7
  const MAX_FILE_BYTES = 1024 * 1024;
8
- export const SCAN_VERSION = 2;
8
+ export const SCAN_VERSION = 3;
9
9
  const RULES_FINGERPRINT = createHash('sha256')
10
10
  .update(JSON.stringify(LANGUAGES))
11
+ .update(BASIC_FINGERPRINT)
11
12
  .digest('hex')
12
13
  .slice(0, 12);
13
14
  const CACHE_KEY = `v${SCAN_VERSION}:${RULES_FINGERPRINT}\n`;
@@ -19,6 +19,8 @@ export function resolveEdges(project, symbols, references) {
19
19
  const candidates = byName.get(reference.name) ?? [];
20
20
  const local = candidates.find((candidate) => candidate.file === reference.file);
21
21
  const target = local ?? candidates[0];
22
+ if (!target && reference.weak)
23
+ continue;
22
24
  let confidence = 'EXTRACTED';
23
25
  let score = SAME_FILE;
24
26
  if (!local && candidates.length === 1) {
@@ -1,3 +1,4 @@
1
+ export declare const DECLARED: Set<string>;
1
2
  export declare function isSymbol(pattern: string): boolean;
2
- /** Symbols a shell command searches the tree for, which the code graph also answers. */
3
+ export declare function isWord(pattern: string): boolean;
3
4
  export declare function symbolsGreppedIn(command: string): string[];
@@ -1,22 +1,31 @@
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 GREP = /\b(?:grep|rg)\b((?:\s+-{1,2}[\w-]+(?:=\S+)?)*)\s+(?:(['"])(.+?)\2|(\S+))([^;&|]*)/g;
2
+ const WORD = /^[a-z][a-z0-9]{3,}$/;
3
+ export const DECLARED = new Set(['function', 'method', 'class', 'interface', 'type', 'enum']);
4
+ const GREP = /(?:^|[;&|(`]|\$\(|\bdo\s+|\bthen\s+|\belse\s+|\bxargs\s+|\bgit\s+|\bsudo\s+|\btime\s+|-exec\s+)\s*(?:grep|rg)\b((?:\s+(?:-[ABC]\s?\d+|-[tTg]\s\S+|-{1,2}[\w-]+(?:=\S+)?))*)\s+(?:(['"])(.+?)\2|(\S+))([^;&|]*)/gm;
3
5
  export function isSymbol(pattern) {
4
6
  return SYMBOL.test(pattern);
5
7
  }
6
- /** Symbols a shell command searches the tree for, which the code graph also answers. */
8
+ export function isWord(pattern) {
9
+ return WORD.test(pattern);
10
+ }
7
11
  export function symbolsGreppedIn(command) {
8
12
  const found = new Set();
9
13
  for (const match of command.matchAll(GREP)) {
10
14
  const flags = match[1] ?? '';
11
15
  const pattern = match[3] ?? match[4] ?? '';
12
16
  const rest = match[5] ?? '';
13
- if (!SYMBOL.test(pattern))
17
+ if (!SYMBOL.test(pattern) && !WORD.test(pattern))
14
18
  continue;
15
19
  if (/-\w*v/.test(flags))
16
20
  continue;
17
- if (/-\w*[rR]\b|--recursive/.test(flags) || /^\s+[^-|;&>][^\s|;&>]*/.test(rest)) {
21
+ const invocation = match[0];
22
+ const piped = /^\s*\|/.test(invocation);
23
+ const searchesTree = /-\w*[rR]\b|--recursive/.test(flags) ||
24
+ /^\s+[^-|;&>][^\s|;&>]*/.test(rest) ||
25
+ /\bgit\s+(?:grep|rg)\b/.test(invocation) ||
26
+ (/(?:^|[\s;&|(])rg\b/.test(invocation) && !piped);
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
- if (process.env['CLAUDE_DB_USAGES_HOOK'] === 'off')
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
- additionalContext: `Code graph, for the symbol(s) this search names — the grep below still runs, ` +
55
- `this is the structure it cannot show:\n\n${blocks.join('\n\n')}`,
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
  });
@@ -1,2 +1,6 @@
1
1
  import type { Observation, ObservationIndexEntry } from '../types.js';
2
+ export declare function overlapCount(prompt: string, entry: {
3
+ title: string;
4
+ snippet?: string | undefined;
5
+ }): number;
2
6
  export declare function renderPromptContext(entries: ObservationIndexEntry[], maxChars: number, expanded?: Observation[], expandMaxChars?: number): string | null;
@@ -1,4 +1,14 @@
1
+ import { meaningfulTokens } from '../search/stopwords.js';
1
2
  import { toShortId } from '../util/shortid.js';
3
+ export function overlapCount(prompt, entry) {
4
+ const wanted = new Set(meaningfulTokens(prompt.toLowerCase()));
5
+ const offered = new Set(meaningfulTokens(`${entry.title} ${entry.snippet ?? ''}`.toLowerCase()));
6
+ let shared = 0;
7
+ for (const word of wanted)
8
+ if (offered.has(word))
9
+ shared++;
10
+ return shared;
11
+ }
2
12
  export function renderPromptContext(entries, maxChars, expanded = [], expandMaxChars = 900) {
3
13
  if (entries.length === 0)
4
14
  return null;
@@ -2,7 +2,7 @@
2
2
  import { spawn } from 'node:child_process';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { clearCursor, flushSession } from '../capture/index.js';
5
+ import { aiSummary, clearCursor, flushSession, observationsFromTurns, readTranscript, transcriptPathFor, } from '../capture/index.js';
6
6
  import { isDue, readState } from '../update.js';
7
7
  import { createContext } from '../context.js';
8
8
  import { readPayload, runHook } from './payload.js';
@@ -18,12 +18,21 @@ await runHook(async () => {
18
18
  const ctx = await createContext();
19
19
  try {
20
20
  const result = await flushSession(ctx, sessionId, project, payload.transcript_path);
21
+ let summary = result.summary;
22
+ if (ctx.config.capture.summarize === 'on') {
23
+ const path = payload.transcript_path ?? transcriptPathFor(project, sessionId);
24
+ const { turns } = readTranscript(path, 0);
25
+ const observations = observationsFromTurns(turns, sessionId, project, ctx.config);
26
+ const ai = await aiSummary(observations.map((obs) => `${obs.title}\n${obs.body}`).join('\n\n'), ctx.config.capture.summarizeModel);
27
+ if (ai)
28
+ summary = `AI: ${ai}`;
29
+ }
21
30
  await ctx.store.upsertSession({
22
31
  id: sessionId,
23
32
  project,
24
33
  startedAt: Date.now(),
25
34
  endedAt: Date.now(),
26
- ...(result.summary ? { summary: result.summary } : {}),
35
+ ...(summary ? { summary } : {}),
27
36
  });
28
37
  clearCursor(sessionId);
29
38
  if (ctx.config.updates !== 'off' && isDue(readState())) {
@@ -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';
@@ -49,9 +50,13 @@ await runHook(async () => {
49
50
  const ctx = await createContext();
50
51
  try {
51
52
  const sessions = await ctx.store.recentSessions(project, ctx.config.inject.sessions);
53
+ const scanned = (await ctx.store.scannedFiles(project)).length;
54
+ const scanHint = 'Code graph not built yet — run `claude-db scan` once to enable ' +
55
+ 'find_usages and the symbol-grep hook.';
52
56
  if (sessions.length === 0) {
53
57
  emitContext('<project-memory>none yet for this project; ' +
54
- 'it is recorded as you work</project-memory>\n');
58
+ 'it is recorded as you work</project-memory>\n' +
59
+ (scanned === 0 ? `${scanHint}\n` : ''));
55
60
  return;
56
61
  }
57
62
  const lines = ['<project-memory>'];
@@ -72,15 +77,36 @@ await runHook(async () => {
72
77
  lines.push(`- ${obs.title}`);
73
78
  }
74
79
  }
80
+ const rules = (await ctx.store.list({ project, kind: 'preference', limit: 100 }))
81
+ .sort((a, b) => {
82
+ const manual = Number(b.sessionId === 'manual') - Number(a.sessionId === 'manual');
83
+ return manual !== 0 ? manual : b.createdAt - a.createdAt;
84
+ })
85
+ .slice(0, 8);
86
+ if (rules.length > 0) {
87
+ lines.push('');
88
+ lines.push('Standing rules on record — expand any id with get_observations:');
89
+ for (const obs of rules) {
90
+ const when = new Date(obs.createdAt).toISOString().slice(0, 10);
91
+ const line = `- ${toShortId(obs.id)} [${when}] ${obs.title}`.slice(0, 140);
92
+ if (line.length > budget)
93
+ break;
94
+ budget -= line.length;
95
+ lines.push(line);
96
+ }
97
+ }
75
98
  lines.push('</project-memory>');
76
99
  if (mcpRegistered(project)) {
77
100
  lines.push("Search this project's full history with the memory MCP tools before " +
78
101
  'asking the user to re-explain prior decisions.');
79
102
  }
103
+ if (scanned === 0)
104
+ lines.push(scanHint);
80
105
  const notice = ctx.config.updates === 'off' ? null : updateNotice();
81
106
  if (notice)
82
107
  lines.push(notice);
83
- emitContext(`${lines.join('\n')}\n`);
108
+ const body = lines.join('\n');
109
+ emitContext(`${body}\n(context ≈ ${Math.round(body.length / 4)} tokens)\n`);
84
110
  await refreshGraphQuietly(ctx.store, project);
85
111
  }
86
112
  finally {
@@ -3,7 +3,7 @@ import { flushSession } from '../capture/index.js';
3
3
  import { createContext } from '../context.js';
4
4
  import { emitContext, readPayload, runHook } from './payload.js';
5
5
  import { markShown, readShown } from './shown.js';
6
- import { renderPromptContext } from './relevance.js';
6
+ import { overlapCount, renderPromptContext } from './relevance.js';
7
7
  import { isSearchable } from '../util/prompt.js';
8
8
  import { resolveProject } from '../util/project.js';
9
9
  import { silenceSqliteWarning } from '../util/warnings.js';
@@ -27,7 +27,10 @@ await runHook(async () => {
27
27
  project,
28
28
  limit: ctx.config.inject.promptResults,
29
29
  });
30
- const entries = found.filter((entry) => !shown.has(entry.id));
30
+ const floor = ctx.config.inject.minOverlap;
31
+ const entries = found
32
+ .filter((entry) => !shown.has(entry.id))
33
+ .filter((entry) => floor === 0 || overlapCount(prompt, entry) >= floor);
31
34
  if (entries.length === 0)
32
35
  return;
33
36
  const toExpand = entries.slice(0, ctx.config.inject.expandTop);
@@ -38,7 +41,7 @@ await runHook(async () => {
38
41
  if (!block)
39
42
  return;
40
43
  markShown(sessionId, entries.map((entry) => entry.id));
41
- emitContext(`${block}\n`);
44
+ emitContext(`${block}\n(context ≈ ${Math.round(block.length / 4)} tokens)\n`);
42
45
  }
43
46
  finally {
44
47
  await ctx.close();
@@ -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
- }, async ({ text, kind, project, key, tags }) => {
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) }, async ({ ids }) => {
39
- const deleted = await ctx.store.remove({ ids });
40
- return {
41
- content: [{ type: 'text', text: `Forgot ${deleted} observation(s).` }],
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
- }, async ({ observation_id, before, after }) => {
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
- }, async ({ ids, chars }) => {
38
- const observations = await ctx.search.getObservations(ids);
39
- if (observations.length === 0) {
40
- return {
41
- content: [
42
- {
43
- type: 'text',
44
- text: `No observation matched ${ids.join(', ')}. Ids come from search — run it first ` +
45
- `and pass the short ids it prints.`,
46
- },
47
- ],
48
- };
49
- }
50
- const missing = ids.filter((id) => !observations.some((obs) => obs.id === id || obs.id.startsWith(id)));
51
- const body = observations.map((obs) => renderFull(obs, chars)).join('\n\n---\n\n');
52
- const note = missing.length > 0 ? `\n\n(no observation matched ${missing.join(', ')})` : '';
53
- return { content: [{ type: 'text', text: body + note }] };
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
  }
@@ -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
- }, async ({ query, project, kind, tag, limit }) => {
28
- const entries = await ctx.search.search({
29
- text: query,
30
- limit,
31
- ...(project === '*' ? {} : { project: resolveProject(project) }),
32
- ...(kind ? { kind } : {}),
33
- ...(tag ? { tag } : {}),
34
- });
35
- if (entries.length === 0) {
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);
@@ -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
- }, async ({ symbol, mode, target, path, regex, context, limit }) => {
60
- if (mode === 'text') {
61
- const result = findUsages({ symbol, regex, context, limit, ...(path ? { path } : {}) });
62
- const missed = result.matches.length === 0
63
- ? await suggestFor(ctx.store, resolveProject(undefined), symbol)
64
- : [];
65
- return { content: [{ type: 'text', text: formatUsages(result, missed) }] };
66
- }
67
- const root = repoRootFor(path ?? process.cwd());
68
- const project = resolveProject(undefined);
69
- const refreshed = await refreshGraph(ctx.store, root, project);
70
- const answer = await queryGraph(ctx.store, project, {
71
- mode,
72
- symbol,
73
- ...(target ? { target } : {}),
74
- limit,
75
- });
76
- answer.refreshed = refreshed;
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
  }