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
@@ -0,0 +1,151 @@
1
+ export function renderPage(data, live) {
2
+ const payload = JSON.stringify({ ...data, live }).replace(/</g, '\\u003c');
3
+ return `<!doctype html>
4
+ <html lang="en">
5
+ <head>
6
+ <meta charset="utf-8">
7
+ <meta name="viewport" content="width=device-width, initial-scale=1">
8
+ <title>claude-db · memory</title>
9
+ <style>
10
+ :root {
11
+ --bg: #FAFAF7; --grid: #E7E5DC; --ink: #26231F; --muted: #6E6A62;
12
+ --accent: #C0532F; --surface: #FFFFFF; --line: #D8D5CC;
13
+ }
14
+ @media (prefers-color-scheme: dark) {
15
+ :root {
16
+ --bg: #1B1A18; --grid: #26241F; --ink: #E8E5DF; --muted: #9B968C;
17
+ --accent: #D96B45; --surface: #232120; --line: #3A372F;
18
+ }
19
+ }
20
+ * { box-sizing: border-box; }
21
+ body {
22
+ margin: 0; color: var(--ink); font: 15px/1.55 ui-sans-serif, system-ui, sans-serif;
23
+ background: linear-gradient(var(--grid) 1px, transparent 1px),
24
+ linear-gradient(90deg, var(--grid) 1px, transparent 1px), var(--bg);
25
+ background-size: 28px 28px;
26
+ }
27
+ main { max-width: 860px; margin: 0 auto; padding: 32px 20px 80px; }
28
+ h1 { font: 700 22px/1.2 ui-monospace, monospace; margin: 0; }
29
+ h2 { font: 600 12px/1 ui-monospace, monospace; letter-spacing: 0.1em;
30
+ text-transform: uppercase; color: var(--muted); margin: 28px 0 10px; }
31
+ .meta { color: var(--muted); font-size: 13px; margin-top: 4px; }
32
+ .chips { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
33
+ .chip { background: var(--surface); border: 1px solid var(--line); border-radius: 999px;
34
+ padding: 3px 12px; font: 500 12px ui-monospace, monospace; }
35
+ .chip b { color: var(--accent); }
36
+ .card { background: var(--surface); border: 1px solid var(--line); border-radius: 6px; }
37
+ .row { display: flex; gap: 12px; align-items: baseline; padding: 9px 14px;
38
+ border-bottom: 1px solid var(--line); }
39
+ .row:last-child { border-bottom: none; }
40
+ .kind { font: 500 11px ui-monospace, monospace; color: var(--accent); min-width: 76px; }
41
+ .when { font: 400 11px ui-monospace, monospace; color: var(--muted); min-width: 84px;
42
+ font-variant-numeric: tabular-nums; }
43
+ .title { flex: 1; min-width: 0; overflow-wrap: break-word; }
44
+ .id { font: 400 11px ui-monospace, monospace; color: var(--muted); }
45
+ input {
46
+ width: 100%; padding: 10px 14px; font: inherit; color: inherit;
47
+ background: var(--surface); border: 1px solid var(--line); border-radius: 6px;
48
+ }
49
+ input:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
50
+ .live { color: var(--accent); font: 600 11px ui-monospace, monospace; }
51
+ .empty { padding: 12px 14px; color: var(--muted); font-size: 13.5px; }
52
+ </style>
53
+ </head>
54
+ <body>
55
+ <main>
56
+ <h1>claude-db <span class="live" id="live"></span></h1>
57
+ <div class="meta" id="meta"></div>
58
+ <div class="chips" id="chips"></div>
59
+
60
+ <h2>Search memory</h2>
61
+ <input id="q" type="search" placeholder="why is … / what did we decide about …" autocomplete="off">
62
+ <div class="card" id="results" style="margin-top:10px; display:none"></div>
63
+
64
+ <h2>Standing rules</h2>
65
+ <div class="card" id="rules"></div>
66
+
67
+ <h2>Recent sessions</h2>
68
+ <div class="card" id="sessions"></div>
69
+
70
+ <h2>Memory stream</h2>
71
+ <div class="card" id="stream"></div>
72
+ </main>
73
+ <script id="data" type="application/json">${payload}</script>
74
+ <script>
75
+ let data = JSON.parse(document.getElementById('data').textContent);
76
+ const el = (id) => document.getElementById(id);
77
+ const when = (t) => new Date(t).toISOString().slice(0, 16).replace('T', ' ');
78
+ function row(parts) {
79
+ const div = document.createElement('div');
80
+ div.className = 'row';
81
+ for (const [cls, text] of parts) {
82
+ const span = document.createElement('span');
83
+ span.className = cls;
84
+ span.textContent = text;
85
+ div.appendChild(span);
86
+ }
87
+ return div;
88
+ }
89
+ function fill(id, rows, emptyText) {
90
+ const box = el(id);
91
+ box.textContent = '';
92
+ if (rows.length === 0) {
93
+ const d = document.createElement('div');
94
+ d.className = 'empty';
95
+ d.textContent = emptyText;
96
+ box.appendChild(d);
97
+ return;
98
+ }
99
+ for (const r of rows) box.appendChild(r);
100
+ }
101
+ function render() {
102
+ el('live').textContent = data.live ? '· live' : '· snapshot';
103
+ el('meta').textContent = data.project + ' · ' + data.database +
104
+ ' · code graph: ' + (data.scannedFiles > 0 ? data.scannedFiles + ' files scanned' : 'not built');
105
+ el('chips').textContent = '';
106
+ for (const [kind, count] of Object.entries(data.kinds).sort((a, b) => b[1] - a[1])) {
107
+ const chip = document.createElement('span');
108
+ chip.className = 'chip';
109
+ const b = document.createElement('b');
110
+ b.textContent = String(count);
111
+ chip.appendChild(b);
112
+ chip.appendChild(document.createTextNode(' ' + kind));
113
+ el('chips').appendChild(chip);
114
+ }
115
+ fill('rules', data.rules.map((r) => row([["when", when(r.when).slice(0, 10)], ["title", r.title], ["id", r.id]])), 'No standing rules recorded yet.');
116
+ fill('sessions', data.sessions.map((s) => row([["when", when(s.when)], ["title", s.summary || '(no summary yet)']])), 'No sessions recorded yet.');
117
+ fill('stream', data.observations.map((o) => row([["kind", o.kind], ["when", when(o.when)], ["title", o.title], ["id", o.id]])), 'Nothing captured yet — memory is written as you work.');
118
+ }
119
+ render();
120
+
121
+ if (data.live) {
122
+ setInterval(async () => {
123
+ try {
124
+ const fresh = await (await fetch('/api/data')).json();
125
+ data = Object.assign(fresh, { live: true });
126
+ render();
127
+ } catch {}
128
+ }, 5000);
129
+
130
+ let timer;
131
+ el('q').addEventListener('input', () => {
132
+ clearTimeout(timer);
133
+ timer = setTimeout(async () => {
134
+ const q = el('q').value.trim();
135
+ const box = el('results');
136
+ if (q.length < 3) { box.style.display = 'none'; return; }
137
+ try {
138
+ const hits = await (await fetch('/api/search?q=' + encodeURIComponent(q))).json();
139
+ box.style.display = '';
140
+ fill('results', hits.map((h) => row([["kind", h.kind], ["when", when(h.when).slice(0, 10)], ["title", h.title], ["id", h.id]])), 'No matches.');
141
+ } catch {}
142
+ }, 250);
143
+ });
144
+ } else {
145
+ el('q').placeholder = 'search needs the live viewer: claude-db view';
146
+ el('q').disabled = true;
147
+ }
148
+ </script>
149
+ </body>
150
+ </html>`;
151
+ }
@@ -0,0 +1,23 @@
1
+ export interface ViewData {
2
+ project: string;
3
+ database: string;
4
+ scannedFiles: number;
5
+ kinds: Record<string, number>;
6
+ rules: {
7
+ id: string;
8
+ when: number;
9
+ title: string;
10
+ }[];
11
+ sessions: {
12
+ when: number;
13
+ summary: string;
14
+ }[];
15
+ observations: {
16
+ id: string;
17
+ kind: string;
18
+ when: number;
19
+ title: string;
20
+ files: number;
21
+ }[];
22
+ }
23
+ export declare function cmdView(args: (string | undefined)[]): Promise<void>;
@@ -0,0 +1,99 @@
1
+ import { createServer } from 'node:http';
2
+ import { execFile } from 'node:child_process';
3
+ import { writeFileSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import { createContext } from '../../context.js';
6
+ import { resolveProject } from '../../util/project.js';
7
+ import { toShortId } from '../../util/shortid.js';
8
+ import { renderPage } from './view-page.js';
9
+ async function collect(ctx, project) {
10
+ const all = (await ctx.store.list({ project, limit: 500 })).sort((a, b) => b.createdAt - a.createdAt);
11
+ const kinds = {};
12
+ for (const obs of all)
13
+ kinds[obs.kind] = (kinds[obs.kind] ?? 0) + 1;
14
+ const rules = all
15
+ .filter((obs) => obs.kind === 'preference')
16
+ .sort((a, b) => {
17
+ const manual = Number(b.sessionId === 'manual') - Number(a.sessionId === 'manual');
18
+ return manual !== 0 ? manual : b.createdAt - a.createdAt;
19
+ })
20
+ .slice(0, 10)
21
+ .map((obs) => ({ id: toShortId(obs.id), when: obs.createdAt, title: obs.title }));
22
+ const sessions = (await ctx.store.recentSessions(project, 8)).map((session) => ({
23
+ when: session.startedAt,
24
+ summary: session.summary ?? '',
25
+ }));
26
+ return {
27
+ project,
28
+ database: ctx.config.database,
29
+ scannedFiles: (await ctx.store.scannedFiles(project)).length,
30
+ kinds,
31
+ rules,
32
+ sessions,
33
+ observations: all.slice(0, 80).map((obs) => ({
34
+ id: toShortId(obs.id),
35
+ kind: obs.kind,
36
+ when: obs.createdAt,
37
+ title: obs.title,
38
+ files: obs.files.length,
39
+ })),
40
+ };
41
+ }
42
+ export async function cmdView(args) {
43
+ const project = resolveProject(undefined);
44
+ const ctx = await createContext();
45
+ const exportAt = args.indexOf('--export');
46
+ if (exportAt >= 0) {
47
+ const target = resolve(args[exportAt + 1] ?? 'claude-db-memory.html');
48
+ writeFileSync(target, renderPage(await collect(ctx, project), false));
49
+ await ctx.close();
50
+ console.log(`Wrote snapshot to ${target}`);
51
+ return;
52
+ }
53
+ const server = createServer(async (req, res) => {
54
+ try {
55
+ const url = new URL(req.url ?? '/', 'http://localhost');
56
+ if (url.pathname === '/api/data') {
57
+ res.writeHead(200, { 'content-type': 'application/json' });
58
+ res.end(JSON.stringify(await collect(ctx, project)));
59
+ return;
60
+ }
61
+ if (url.pathname === '/api/search') {
62
+ const query = url.searchParams.get('q') ?? '';
63
+ const entries = await ctx.search.search({ text: query, project, limit: 20 });
64
+ res.writeHead(200, { 'content-type': 'application/json' });
65
+ res.end(JSON.stringify(entries.map((entry) => ({
66
+ id: toShortId(entry.id),
67
+ kind: entry.kind,
68
+ when: entry.createdAt,
69
+ title: entry.title,
70
+ }))));
71
+ return;
72
+ }
73
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
74
+ res.end(renderPage(await collect(ctx, project), true));
75
+ }
76
+ catch (error) {
77
+ res.writeHead(500, { 'content-type': 'text/plain' });
78
+ res.end(error instanceof Error ? error.message : String(error));
79
+ }
80
+ });
81
+ server.listen(0, '127.0.0.1', () => {
82
+ const address = server.address();
83
+ const port = typeof address === 'object' && address ? address.port : 0;
84
+ const url = `http://127.0.0.1:${port}`;
85
+ console.log(`Viewing ${project}`);
86
+ console.log(` ${url} (Ctrl+C to stop — nothing keeps running afterwards)`);
87
+ if (process.platform === 'darwin')
88
+ execFile('open', [url], () => { });
89
+ else if (process.platform === 'linux')
90
+ execFile('xdg-open', [url], () => { });
91
+ });
92
+ const stop = async () => {
93
+ server.close();
94
+ await ctx.close();
95
+ process.exit(0);
96
+ };
97
+ process.on('SIGINT', () => void stop());
98
+ process.on('SIGTERM', () => void stop());
99
+ }
package/dist/cli/index.js CHANGED
@@ -11,6 +11,8 @@ 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';
15
+ import { cmdView } from './commands/view.js';
14
16
  import { silenceSqliteWarning } from '../util/warnings.js';
15
17
  silenceSqliteWarning();
16
18
  const [command, ...args] = process.argv.slice(2);
@@ -62,6 +64,12 @@ async function run() {
62
64
  case 'stats':
63
65
  await cmdStats();
64
66
  break;
67
+ case 'adoption':
68
+ await cmdAdoption();
69
+ break;
70
+ case 'view':
71
+ await cmdView(args);
72
+ break;
65
73
  case 'update':
66
74
  await cmdUpdate(args);
67
75
  break;
@@ -18,7 +18,7 @@ const HOOKS = [
18
18
  ['SessionStart', 'session-start.js'],
19
19
  ['UserPromptSubmit', 'user-prompt.js'],
20
20
  ['SessionEnd', 'session-end.js'],
21
- ['PreToolUse', 'prefer-usages.js', 'Bash|Grep'],
21
+ ['PreToolUse', 'prefer-usages.js', 'Bash|Grep', 10],
22
22
  ];
23
23
  export function assertStableLocation(distDir) {
24
24
  const ephemeral = ['_npx', '_cacache'];
@@ -35,17 +35,24 @@ export function install(distDir, scope, project) {
35
35
  const path = settingsPathFor(scope, project);
36
36
  const settings = readJson(path);
37
37
  const hooks = (settings['hooks'] ?? {});
38
- for (const [event, file, matcher] of HOOKS) {
39
- const command = hookCommand(distDir, file);
40
- const existing = hooks[event] ?? [];
41
- const present = existing.some((entry) => entry.hooks.some((hook) => hook.command === command));
42
- if (present)
43
- continue;
44
- existing.push({
38
+ for (const [event, file, matcher, timeout] of HOOKS) {
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: [
48
+ {
49
+ type: 'command',
50
+ command: hookCommand(distDir, file),
51
+ ...(timeout ? { timeout } : {}),
52
+ },
53
+ ],
47
54
  });
48
- hooks[event] = existing;
55
+ hooks[event] = kept;
49
56
  }
50
57
  settings['hooks'] = hooks;
51
58
  delete settings['mcpServers'];
@@ -81,13 +88,12 @@ export function uninstall(distDir, scope, project) {
81
88
  const settings = readJson(path);
82
89
  if (Object.keys(settings).length === 0)
83
90
  return null;
84
- const ours = new Set(HOOKS.map(([, file]) => hookCommand(distDir, file)));
85
91
  const hooks = (settings['hooks'] ?? {});
86
92
  for (const [event, entries] of Object.entries(hooks)) {
87
93
  const kept = entries
88
94
  .map((entry) => ({
89
95
  ...entry,
90
- hooks: entry.hooks.filter((hook) => !ours.has(hook.command)),
96
+ hooks: entry.hooks.filter((hook) => !isOurHook(hook.command)),
91
97
  }))
92
98
  .filter((entry) => entry.hooks.length > 0);
93
99
  if (kept.length > 0)
@@ -121,3 +127,7 @@ export function uninstall(distDir, scope, project) {
121
127
  function hookCommand(distDir, file) {
122
128
  return `node ${resolve(distDir, 'hooks', file)}`;
123
129
  }
130
+ function isOurHook(command) {
131
+ const path = command.replace(/\\/g, '/');
132
+ return HOOKS.some(([, file]) => path.endsWith(`/hooks/${file}`));
133
+ }
@@ -6,11 +6,12 @@ export const INSTRUCTIONS = [
6
6
  BLOCK_START,
7
7
  '## Project memory',
8
8
  '',
9
- 'This project has persistent memory of past sessions, served by the `memory`',
10
- 'MCP server. Session summaries are injected at startup and the best matching',
11
- 'observation is injected above each prompt, but that is only ever a slice.',
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
- 'Search it *before* re-deriving something this project already knows. That',
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,8 @@ 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
19
+ view [--export <file>] See this project's memory live in the browser
18
20
  flush Re-ingest every transcript for this project
19
21
  seed --from-git [--limit n] Fill a cold memory from this repo's history
20
22
  scan [--force] Map this repo's symbols and how they connect
@@ -21,12 +21,22 @@ export declare const ConfigSchema: z.ZodObject<{
21
21
  tools: z.ZodDefault<z.ZodArray<z.ZodString>>;
22
22
  exclude: z.ZodDefault<z.ZodArray<z.ZodString>>;
23
23
  maxBodyChars: z.ZodDefault<z.ZodNumber>;
24
+ summarize: z.ZodDefault<z.ZodEnum<{
25
+ off: "off";
26
+ on: "on";
27
+ }>>;
28
+ summarizeModel: z.ZodDefault<z.ZodEnum<{
29
+ opus: "opus";
30
+ sonnet: "sonnet";
31
+ haiku: "haiku";
32
+ }>>;
24
33
  }, z.core.$strip>>;
25
34
  inject: z.ZodPrefault<z.ZodObject<{
26
35
  sessions: z.ZodDefault<z.ZodNumber>;
27
36
  maxChars: z.ZodDefault<z.ZodNumber>;
28
37
  perPrompt: z.ZodDefault<z.ZodBoolean>;
29
38
  promptResults: z.ZodDefault<z.ZodNumber>;
39
+ minOverlap: z.ZodDefault<z.ZodNumber>;
30
40
  promptMaxChars: z.ZodDefault<z.ZodNumber>;
31
41
  expandTop: z.ZodDefault<z.ZodNumber>;
32
42
  expandMaxChars: z.ZodDefault<z.ZodNumber>;
@@ -15,6 +15,8 @@ export const ConfigSchema = z.object({
15
15
  tools: z.array(z.string()).default(['Edit', 'Write', 'Bash', 'NotebookEdit']),
16
16
  exclude: z.array(z.string()).default(['.env', 'secrets', 'node_modules', '.git/']),
17
17
  maxBodyChars: z.number().int().positive().default(4000),
18
+ summarize: z.enum(['off', 'on']).default('off'),
19
+ summarizeModel: z.enum(['opus', 'sonnet', 'haiku']).default('opus'),
18
20
  })
19
21
  .prefault({}),
20
22
  inject: z
@@ -23,6 +25,7 @@ export const ConfigSchema = z.object({
23
25
  maxChars: z.number().int().positive().default(6000),
24
26
  perPrompt: z.boolean().default(true),
25
27
  promptResults: z.number().int().positive().max(10).default(4),
28
+ minOverlap: z.number().int().min(0).default(1),
26
29
  promptMaxChars: z.number().int().positive().default(700),
27
30
  expandTop: z.number().int().min(0).max(3).default(0),
28
31
  expandMaxChars: z.number().int().positive().default(900),
@@ -0,0 +1,11 @@
1
+ import type { LanguageSpec } from './rules.js';
2
+ import type { SymbolKind } from '../../types.js';
3
+ export declare const BASIC_FINGERPRINT: string;
4
+ export declare const BASIC_LANGUAGES: LanguageSpec[];
5
+ export interface BasicDeclaration {
6
+ name: string;
7
+ kind: SymbolKind;
8
+ line: number;
9
+ }
10
+ export declare function declarationsIn(source: string): BasicDeclaration[];
11
+ export declare function callsIn(source: string): BasicDeclaration[];
@@ -0,0 +1,156 @@
1
+ const LABELS = {
2
+ c: ['.c', '.h'],
3
+ cpp: ['.cc', '.cpp', '.cxx', '.hpp', '.hh'],
4
+ csharp: ['.cs'],
5
+ java: ['.java'],
6
+ kotlin: ['.kt', '.kts'],
7
+ swift: ['.swift'],
8
+ 'objective-c': ['.m', '.mm'],
9
+ scala: ['.scala'],
10
+ php: ['.php'],
11
+ perl: ['.pl', '.pm'],
12
+ lua: ['.lua'],
13
+ r: ['.r', '.R'],
14
+ julia: ['.jl'],
15
+ dart: ['.dart'],
16
+ elixir: ['.ex', '.exs'],
17
+ erlang: ['.erl'],
18
+ clojure: ['.clj', '.cljs', '.cljc'],
19
+ haskell: ['.hs'],
20
+ ocaml: ['.ml', '.mli'],
21
+ fsharp: ['.fs', '.fsx'],
22
+ groovy: ['.groovy', '.gradle'],
23
+ shell: ['.sh', '.bash', '.zsh'],
24
+ powershell: ['.ps1', '.psm1'],
25
+ sql: ['.sql'],
26
+ zig: ['.zig'],
27
+ nim: ['.nim'],
28
+ crystal: ['.cr'],
29
+ solidity: ['.sol'],
30
+ vala: ['.vala'],
31
+ };
32
+ const KEYWORDS = {
33
+ class: 'class',
34
+ struct: 'class',
35
+ object: 'class',
36
+ record: 'class',
37
+ actor: 'class',
38
+ contract: 'class',
39
+ module: 'class',
40
+ defmodule: 'class',
41
+ namespace: 'class',
42
+ interface: 'interface',
43
+ protocol: 'interface',
44
+ trait: 'interface',
45
+ typeclass: 'interface',
46
+ enum: 'enum',
47
+ type: 'type',
48
+ typedef: 'type',
49
+ data: 'type',
50
+ newtype: 'type',
51
+ def: 'function',
52
+ defp: 'function',
53
+ defn: 'function',
54
+ defun: 'function',
55
+ function: 'function',
56
+ func: 'function',
57
+ fn: 'function',
58
+ sub: 'function',
59
+ proc: 'function',
60
+ method: 'method',
61
+ };
62
+ const DECLARATION = new RegExp(`^[\\t ]*(?:[\\w@\\[\\]]+[\\t ]+){0,3}(${Object.keys(KEYWORDS).join('|')})[\\t ]+([A-Za-z_][\\w]*)`);
63
+ const CALLABLE = /^[\t ]*(?:[A-Za-z_][\w:<>,.\[\]*&\t ]*[\t *&]+)?([A-Za-z_]\w*)[\t ]*\([^;=]*\)[\t ]*(?:const[\t ]*)?\{[\t ]*$/;
64
+ const CALL = /\b([A-Za-z_]\w{2,})[\t ]*\(/g;
65
+ const NOT_A_CALL = new Set([
66
+ 'if',
67
+ 'for',
68
+ 'while',
69
+ 'switch',
70
+ 'catch',
71
+ 'return',
72
+ 'with',
73
+ 'else',
74
+ 'elsif',
75
+ 'unless',
76
+ 'until',
77
+ 'when',
78
+ 'case',
79
+ 'do',
80
+ 'end',
81
+ 'and',
82
+ 'not',
83
+ 'or',
84
+ 'sizeof',
85
+ 'typeof',
86
+ 'defined',
87
+ 'print',
88
+ 'printf',
89
+ 'echo',
90
+ 'assert',
91
+ 'require',
92
+ 'import',
93
+ 'include',
94
+ 'new',
95
+ 'delete',
96
+ 'throw',
97
+ 'super',
98
+ 'self',
99
+ 'this',
100
+ ...Object.keys(KEYWORDS),
101
+ ]);
102
+ export const BASIC_FINGERPRINT = [
103
+ DECLARATION.source,
104
+ CALLABLE.source,
105
+ CALL.source,
106
+ Object.keys(LABELS).join(','),
107
+ ].join('|');
108
+ export const BASIC_LANGUAGES = Object.entries(LABELS).map(([label, extensions]) => ({
109
+ id: 'basic',
110
+ label,
111
+ extensions,
112
+ definitions: [],
113
+ references: [],
114
+ basic: true,
115
+ }));
116
+ export function declarationsIn(source) {
117
+ const found = [];
118
+ const lines = source.split('\n');
119
+ for (let index = 0; index < lines.length; index++) {
120
+ const line = lines[index] ?? '';
121
+ if (line.length > 400)
122
+ continue;
123
+ const keyword = DECLARATION.exec(line);
124
+ if (keyword) {
125
+ const kind = KEYWORDS[keyword[1] ?? ''];
126
+ const name = keyword[2];
127
+ if (kind && name && !KEYWORDS[name])
128
+ found.push({ name, kind, line: index + 1 });
129
+ continue;
130
+ }
131
+ const callable = CALLABLE.exec(line);
132
+ const name = callable?.[1];
133
+ if (name && !NOT_A_CALL.has(name))
134
+ found.push({ name, kind: 'function', line: index + 1 });
135
+ }
136
+ return found;
137
+ }
138
+ const MAX_CALLS = 200;
139
+ export function callsIn(source) {
140
+ const found = [];
141
+ const lines = source.split('\n');
142
+ for (let index = 0; index < lines.length && found.length < MAX_CALLS; index++) {
143
+ const line = lines[index] ?? '';
144
+ if (line.length > 400)
145
+ continue;
146
+ if (DECLARATION.test(line) || CALLABLE.test(line))
147
+ continue;
148
+ for (const match of line.matchAll(CALL)) {
149
+ const name = match[1];
150
+ if (!name || NOT_A_CALL.has(name))
151
+ continue;
152
+ found.push({ name, kind: 'function', line: index + 1 });
153
+ }
154
+ }
155
+ return found;
156
+ }
@@ -2,5 +2,6 @@ import type { LanguageSpec } from './rules.js';
2
2
  export type { DefinitionRule, LanguageSpec, ReferenceRule } from './rules.js';
3
3
  export declare const LANGUAGES: LanguageSpec[];
4
4
  export declare const DYNAMIC_LANGUAGES: string[];
5
+ export { BASIC_FINGERPRINT, callsIn, declarationsIn } from './basic.js';
5
6
  export declare function languageFor(path: string): LanguageSpec | null;
6
7
  export declare function languageNames(): string;
@@ -1,11 +1,14 @@
1
+ import { BASIC_LANGUAGES } from './basic.js';
1
2
  import { javascript, tsx, typescript } from './ecmascript.js';
2
3
  import { go } from './go.js';
3
4
  import { python } from './python.js';
5
+ import { ruby } from './ruby.js';
4
6
  import { rust } from './rust.js';
5
- export const LANGUAGES = [typescript, tsx, javascript, python, go, rust];
6
- export const DYNAMIC_LANGUAGES = ['python', 'go', 'rust'];
7
+ export const LANGUAGES = [typescript, tsx, javascript, python, go, rust, ruby];
8
+ export const DYNAMIC_LANGUAGES = ['python', 'go', 'rust', 'ruby'];
9
+ export { BASIC_FINGERPRINT, callsIn, declarationsIn } from './basic.js';
7
10
  const BY_EXTENSION = new Map();
8
- for (const spec of LANGUAGES) {
11
+ for (const spec of [...LANGUAGES, ...BASIC_LANGUAGES]) {
9
12
  for (const extension of spec.extensions)
10
13
  BY_EXTENSION.set(extension, spec);
11
14
  }
@@ -16,5 +19,5 @@ export function languageFor(path) {
16
19
  return BY_EXTENSION.get(path.slice(dot).toLowerCase()) ?? null;
17
20
  }
18
21
  export function languageNames() {
19
- return LANGUAGES.map((spec) => spec.label).join(', ');
22
+ return `${LANGUAGES.map((spec) => spec.label).join(', ')}, and ${BASIC_LANGUAGES.length} more by pattern`;
20
23
  }
@@ -0,0 +1,2 @@
1
+ import type { LanguageSpec } from './rules.js';
2
+ export declare const ruby: LanguageSpec;
@@ -0,0 +1,16 @@
1
+ export const ruby = {
2
+ id: 'ruby',
3
+ label: 'ruby',
4
+ extensions: ['.rb', '.rake'],
5
+ definitions: [
6
+ { kind: 'method', field: ['name'], symbol: 'method' },
7
+ { kind: 'singleton_method', field: ['name'], symbol: 'method' },
8
+ { kind: 'class', field: ['name'], symbol: 'class' },
9
+ { kind: 'module', field: ['name'], symbol: 'class' },
10
+ ],
11
+ references: [
12
+ { kind: 'call', field: ['method'], relation: 'calls' },
13
+ { kind: 'call', field: ['receiver'], relation: 'references' },
14
+ { kind: 'class', field: ['superclass'], relation: 'extends' },
15
+ ],
16
+ };
@@ -15,4 +15,5 @@ export interface LanguageSpec {
15
15
  extensions: string[];
16
16
  definitions: DefinitionRule[];
17
17
  references: ReferenceRule[];
18
+ basic?: boolean;
18
19
  }
@@ -1,5 +1,4 @@
1
1
  import type { MemoryStore } from '../../store/adapter.js';
2
- /** Names closest to `symbol`, best first. A miss that names no alternative is where people quit. */
3
2
  export declare function nearest(names: Iterable<string>, symbol: string, limit?: number): string[];
4
3
  export declare function suggestFor(store: MemoryStore, project: string, symbol: string): Promise<string[]>;
5
4
  export declare function formatSuggestions(suggestions: string[]): string;