claude-db 0.12.4 → 0.14.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 (158) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/dist/capture/cursors.d.ts +6 -0
  3. package/dist/capture/cursors.js +80 -0
  4. package/dist/capture/flush.d.ts +1 -3
  5. package/dist/capture/flush.js +35 -96
  6. package/dist/capture/index.d.ts +3 -3
  7. package/dist/capture/index.js +3 -3
  8. package/dist/capture/progress.js +4 -2
  9. package/dist/capture/reingest.d.ts +1 -0
  10. package/dist/capture/reingest.js +4 -1
  11. package/dist/capture/scrub.d.ts +1 -0
  12. package/dist/capture/scrub.js +4 -1
  13. package/dist/capture/transcript.d.ts +1 -1
  14. package/dist/capture/transcript.js +6 -6
  15. package/dist/capture/vectors.js +2 -1
  16. package/dist/catchup/gather.js +1 -1
  17. package/dist/cli/commands/catchup.js +2 -1
  18. package/dist/cli/commands/daemon.d.ts +1 -0
  19. package/dist/cli/commands/daemon.js +29 -0
  20. package/dist/cli/commands/distill.js +2 -1
  21. package/dist/cli/commands/graph.js +11 -11
  22. package/dist/cli/commands/insight.js +10 -1
  23. package/dist/cli/commands/maintain.js +3 -1
  24. package/dist/cli/commands/memory.js +2 -1
  25. package/dist/cli/commands/setup.js +1 -2
  26. package/dist/cli/commands/sync.js +4 -1
  27. package/dist/cli/index.js +4 -0
  28. package/dist/cli/install.js +1 -2
  29. package/dist/cli/instructions.d.ts +1 -3
  30. package/dist/cli/instructions.js +5 -40
  31. package/dist/cli/refresh.js +2 -6
  32. package/dist/cli/usage.js +1 -0
  33. package/dist/config/load.js +2 -1
  34. package/dist/config/schema.d.ts +4 -2
  35. package/dist/config/schema.js +6 -2
  36. package/dist/context.d.ts +1 -0
  37. package/dist/context.js +30 -6
  38. package/dist/daemon/client.d.ts +14 -0
  39. package/dist/daemon/client.js +106 -0
  40. package/dist/daemon/paths.d.ts +18 -0
  41. package/dist/daemon/paths.js +19 -0
  42. package/dist/daemon/pid.d.ts +3 -0
  43. package/dist/daemon/pid.js +20 -0
  44. package/dist/daemon/server.d.ts +2 -0
  45. package/dist/daemon/server.js +227 -0
  46. package/dist/embed/local.js +4 -1
  47. package/dist/facts/budget.d.ts +1 -0
  48. package/dist/facts/budget.js +4 -0
  49. package/dist/facts/claude-memory.js +3 -3
  50. package/dist/facts/distill.js +2 -2
  51. package/dist/facts/known.js +1 -1
  52. package/dist/facts/last-chat.d.ts +1 -1
  53. package/dist/facts/last-chat.js +5 -4
  54. package/dist/facts/model.d.ts +1 -1
  55. package/dist/facts/model.js +31 -16
  56. package/dist/facts/start-render.d.ts +13 -0
  57. package/dist/facts/start-render.js +43 -0
  58. package/dist/facts/start.d.ts +3 -6
  59. package/dist/facts/start.js +33 -47
  60. package/dist/graph/grammars.js +2 -1
  61. package/dist/graph/index.d.ts +1 -1
  62. package/dist/graph/index.js +1 -1
  63. package/dist/graph/query/index.d.ts +1 -0
  64. package/dist/graph/query/index.js +1 -0
  65. package/dist/graph/query/refresh.js +5 -1
  66. package/dist/graph/query/stale.js +19 -2
  67. package/dist/graph/query/usages.d.ts +12 -0
  68. package/dist/graph/query/usages.js +37 -0
  69. package/dist/graph/scan/cache.d.ts +1 -0
  70. package/dist/graph/scan/cache.js +3 -2
  71. package/dist/graph/scan/files.js +2 -2
  72. package/dist/graph/scan/persist.js +12 -16
  73. package/dist/hooks/compact.d.ts +3 -1
  74. package/dist/hooks/compact.js +4 -3
  75. package/dist/hooks/detached.js +2 -0
  76. package/dist/hooks/graph-presence.d.ts +3 -0
  77. package/dist/hooks/graph-presence.js +42 -0
  78. package/dist/hooks/grep-symbols.d.ts +3 -1
  79. package/dist/hooks/grep-symbols.js +41 -2
  80. package/dist/hooks/handlers/prefer-usages.d.ts +2 -0
  81. package/dist/hooks/handlers/prefer-usages.js +118 -0
  82. package/dist/hooks/handlers/session-end.d.ts +2 -0
  83. package/dist/hooks/handlers/session-end.js +60 -0
  84. package/dist/hooks/handlers/session-start.d.ts +2 -0
  85. package/dist/hooks/handlers/session-start.js +83 -0
  86. package/dist/hooks/handlers/turn-end.d.ts +2 -0
  87. package/dist/hooks/handlers/turn-end.js +31 -0
  88. package/dist/hooks/handlers/user-prompt.d.ts +2 -0
  89. package/dist/hooks/handlers/user-prompt.js +55 -0
  90. package/dist/hooks/local.d.ts +2 -0
  91. package/dist/hooks/local.js +22 -0
  92. package/dist/hooks/payload.d.ts +9 -4
  93. package/dist/hooks/payload.js +30 -20
  94. package/dist/hooks/pick-deliver.js +2 -1
  95. package/dist/hooks/prefer-usages.js +2 -118
  96. package/dist/hooks/prompt-recall.d.ts +4 -2
  97. package/dist/hooks/prompt-recall.js +10 -10
  98. package/dist/hooks/route.d.ts +2 -0
  99. package/dist/hooks/route.js +33 -0
  100. package/dist/hooks/run.d.ts +13 -0
  101. package/dist/hooks/run.js +12 -0
  102. package/dist/hooks/save-turn.d.ts +2 -0
  103. package/dist/hooks/save-turn.js +11 -0
  104. package/dist/hooks/session-end.js +2 -63
  105. package/dist/hooks/session-start.js +2 -90
  106. package/dist/hooks/turn-end.js +2 -25
  107. package/dist/hooks/turn-save.js +10 -15
  108. package/dist/hooks/user-prompt.js +2 -58
  109. package/dist/mcp/tools/ids.d.ts +3 -0
  110. package/dist/mcp/tools/ids.js +6 -0
  111. package/dist/mcp/tools/memory.js +2 -1
  112. package/dist/mcp/tools/observations.js +3 -2
  113. package/dist/mcp/tools/search.js +4 -9
  114. package/dist/mcp/tools/usages.js +18 -44
  115. package/dist/pick/worker.js +1 -2
  116. package/dist/search/service.d.ts +6 -0
  117. package/dist/search/service.js +27 -11
  118. package/dist/store/adapter.d.ts +7 -5
  119. package/dist/store/mongo/index.d.ts +3 -6
  120. package/dist/store/mongo/index.js +5 -0
  121. package/dist/store/mongo/observations.js +13 -1
  122. package/dist/store/postgres/driver.d.ts +10 -3
  123. package/dist/store/postgres/driver.js +12 -0
  124. package/dist/store/postgres/filters.d.ts +1 -0
  125. package/dist/store/postgres/filters.js +3 -0
  126. package/dist/store/postgres/graph.d.ts +3 -5
  127. package/dist/store/postgres/graph.js +59 -52
  128. package/dist/store/postgres/index.d.ts +3 -6
  129. package/dist/store/postgres/index.js +8 -5
  130. package/dist/store/postgres/insert.js +98 -50
  131. package/dist/store/postgres/meta.d.ts +1 -0
  132. package/dist/store/postgres/meta.js +4 -0
  133. package/dist/store/postgres/observations.js +3 -3
  134. package/dist/store/project-resolver.d.ts +4 -0
  135. package/dist/store/project-resolver.js +34 -23
  136. package/dist/store/scoped-store.js +4 -2
  137. package/dist/store/sqlite/filters.d.ts +1 -0
  138. package/dist/store/sqlite/filters.js +6 -2
  139. package/dist/store/sqlite/graph.d.ts +3 -5
  140. package/dist/store/sqlite/graph.js +45 -35
  141. package/dist/store/sqlite/index.d.ts +3 -6
  142. package/dist/store/sqlite/index.js +3 -0
  143. package/dist/store/sqlite/observations.js +12 -9
  144. package/dist/util/claude-binary.js +5 -4
  145. package/dist/util/claude-cli.js +2 -1
  146. package/dist/util/claude-dir.d.ts +2 -0
  147. package/dist/util/claude-dir.js +8 -0
  148. package/dist/util/env.d.ts +2 -0
  149. package/dist/util/env.js +6 -0
  150. package/dist/util/job-lock.d.ts +1 -0
  151. package/dist/util/job-lock.js +50 -10
  152. package/dist/util/shortid.d.ts +3 -0
  153. package/dist/util/shortid.js +11 -0
  154. package/docs/how-it-works.md +5 -10
  155. package/docs/setup-guide.md +6 -1
  156. package/package.json +7 -6
  157. package/dist/hooks/start-legacy.d.ts +0 -6
  158. package/dist/hooks/start-legacy.js +0 -47
@@ -3,3 +3,4 @@ export { formatGraph, formatText } from './format.js';
3
3
  export { queryGraph } from './lookup.js';
4
4
  export { refreshGraph } from './refresh.js';
5
5
  export { nearest, suggestFor } from './suggest.js';
6
+ export { usagesAnswer } from './usages.js';
@@ -1,4 +1,5 @@
1
1
  import { currentHashes, saveScan, scanRepository } from '../scan/index.js';
2
+ import { staleFiles } from './stale.js';
2
3
  function changesOnDisk(root, stored) {
3
4
  const current = currentHashes(root);
4
5
  for (const [path, hash] of current)
@@ -10,7 +11,10 @@ function changesOnDisk(root, stored) {
10
11
  return null;
11
12
  }
12
13
  export async function refreshGraph(store, root, project) {
13
- const stored = new Map((await store.scannedFiles(project)).map((file) => [file.path, file.hash]));
14
+ const scanned = await store.scannedFiles(project);
15
+ if (scanned.length > 0 && staleFiles(root, scanned).length === 0)
16
+ return [];
17
+ const stored = new Map(scanned.map((file) => [file.path, file.hash]));
14
18
  const hashes = changesOnDisk(root, stored);
15
19
  if (!hashes)
16
20
  return [];
@@ -22,9 +22,19 @@ function changedSinceScan(root, entry) {
22
22
  closeSync(fd);
23
23
  }
24
24
  }
25
- export function staleFiles(root, stored) {
25
+ function scannedByOtherScanner(root, stored) {
26
+ for (const entry of stored) {
27
+ try {
28
+ return hashOf(readFileSync(join(root, entry.path))) !== entry.hash;
29
+ }
30
+ catch {
31
+ continue;
32
+ }
33
+ }
34
+ return false;
35
+ }
36
+ function changedFiles(root, current, stored) {
26
37
  const known = new Map(stored.map((entry) => [entry.path, entry]));
27
- const current = sourceFiles(root);
28
38
  const stale = [];
29
39
  for (const path of current) {
30
40
  const entry = known.get(path);
@@ -37,3 +47,10 @@ export function staleFiles(root, stored) {
37
47
  stale.push(path);
38
48
  return stale;
39
49
  }
50
+ export function staleFiles(root, stored) {
51
+ const current = sourceFiles(root);
52
+ const changed = changedFiles(root, current, stored);
53
+ if (changed.length === 0 && scannedByOtherScanner(root, stored))
54
+ return current;
55
+ return changed;
56
+ }
@@ -0,0 +1,12 @@
1
+ import type { MemoryStore } from '../../store/adapter.js';
2
+ import type { GraphMode } from './lookup.js';
3
+ export interface UsagesRequest {
4
+ store: MemoryStore;
5
+ project: string;
6
+ mode: GraphMode;
7
+ symbol: string;
8
+ target?: string | undefined;
9
+ limit: number;
10
+ path?: string | undefined;
11
+ }
12
+ export declare function usagesAnswer(request: UsagesRequest): Promise<string>;
@@ -0,0 +1,37 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute, join, relative } from 'node:path';
3
+ import { repoRootFor } from '../../usages/find.js';
4
+ import { answerQuery } from './answer.js';
5
+ import { formatGraph } from './format.js';
6
+ function scopeWithin(root, path) {
7
+ const scope = relative(realpathSync(root), realpathSync(path));
8
+ if (scope.startsWith('..') || isAbsolute(scope)) {
9
+ throw new Error(`${path} is outside the project ${root}`);
10
+ }
11
+ return scope;
12
+ }
13
+ const inScope = (scope, file) => scope === '' || file === scope || file.startsWith(`${scope}/`);
14
+ function narrow(answer, scope) {
15
+ const keep = (item) => inScope(scope, item.file);
16
+ answer.definitions = answer.definitions.filter(keep);
17
+ answer.inbound = answer.inbound.filter(keep);
18
+ answer.outbound = answer.outbound.filter(keep);
19
+ if (answer.text)
20
+ answer.text.lines = answer.text.lines.filter(keep);
21
+ answer.empty = answer.definitions.length === 0 && answer.inbound.length === 0;
22
+ }
23
+ export async function usagesAnswer(request) {
24
+ const { store, project, mode, symbol, target, limit, path } = request;
25
+ const root = repoRootFor(project);
26
+ const scope = path && mode !== 'path' ? scopeWithin(root, path) : '';
27
+ const answer = await answerQuery({
28
+ store,
29
+ root,
30
+ project,
31
+ query: { mode, symbol, ...(target ? { target } : {}), limit },
32
+ refresh: true,
33
+ });
34
+ if (scope !== '')
35
+ narrow(answer, scope);
36
+ return formatGraph(answer, join(root, scope));
37
+ }
@@ -7,5 +7,6 @@ export interface CachedFile {
7
7
  edgesHash: string;
8
8
  }
9
9
  export declare const cacheHome: () => string;
10
+ export declare const cachePath: (project: string) => string;
10
11
  export declare function loadCache(project: string): ReadonlyMap<string, CachedFile>;
11
12
  export declare function saveCache(project: string, files: ReadonlyMap<string, CachedFile>): void;
@@ -3,9 +3,10 @@ import { join } from 'node:path';
3
3
  import { CONFIG_DIR } from '../../config/dir.js';
4
4
  import { scopeToken } from '../../util/scope.js';
5
5
  import { CACHE_KEY } from './files.js';
6
+ import { hookEnv } from '../../util/env.js';
6
7
  const MEMO_IDLE_MS = 10 * 60 * 1000;
7
- export const cacheHome = () => process.env['CLAUDE_DB_GRAPH_CACHE'] ?? join(CONFIG_DIR, 'graph-cache');
8
- const cachePath = (project) => join(cacheHome(), `${scopeToken(project)}.json`);
8
+ export const cacheHome = () => hookEnv()['CLAUDE_DB_GRAPH_CACHE'] ?? join(CONFIG_DIR, 'graph-cache');
9
+ export const cachePath = (project) => join(cacheHome(), `${scopeToken(project)}.json`);
9
10
  function receiverTable() {
10
11
  const list = [];
11
12
  const positions = new Map();
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { readFileSync } from 'node:fs';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { grammarSignature } from '../grammars.js';
6
6
  import { BASIC_FINGERPRINT, LANGUAGES, languageFor } from '../languages/index.js';
@@ -28,7 +28,7 @@ export function listFiles(root) {
28
28
  return [...new Set([...tracked, ...untracked])].sort();
29
29
  }
30
30
  export function sourceFiles(root) {
31
- return listFiles(root).filter((path) => languageFor(path) !== null);
31
+ return listFiles(root).filter((path) => languageFor(path) !== null && existsSync(join(root, path)));
32
32
  }
33
33
  export function readSource(root, path) {
34
34
  const spec = languageFor(path);
@@ -1,22 +1,18 @@
1
- const REMOVE_BATCH = 500;
2
- async function removeFiles(store, project, files) {
3
- for (let start = 0; start < files.length; start += REMOVE_BATCH) {
4
- const batch = files.slice(start, start + REMOVE_BATCH);
5
- if (batch.length > 0)
6
- await store.removeGraph(project, batch);
7
- }
8
- }
9
1
  export async function saveScan(store, project, scan, force = false) {
10
2
  if (force) {
11
- await store.removeGraph(project);
12
- await store.upsertGraph({ symbols: scan.symbols, edges: scan.edges, files: scan.files });
3
+ await store.replaceGraph(project, null, {
4
+ symbols: scan.symbols,
5
+ edges: scan.edges,
6
+ files: scan.files,
7
+ });
13
8
  return;
14
9
  }
15
- await removeFiles(store, project, [...scan.removed, ...scan.rewrite]);
16
10
  const rewrite = new Set(scan.rewrite);
17
- await store.upsertGraph({
18
- symbols: scan.symbols.filter((symbol) => rewrite.has(symbol.file)),
19
- edges: scan.edges.filter((edge) => rewrite.has(edge.file)),
20
- files: scan.files.filter((file) => rewrite.has(file.path)),
21
- });
11
+ const symbols = scan.symbols.filter((symbol) => rewrite.has(symbol.file));
12
+ const edges = scan.edges.filter((edge) => rewrite.has(edge.file));
13
+ const files = scan.files.filter((file) => rewrite.has(file.path));
14
+ const replaced = [...scan.removed, ...scan.rewrite];
15
+ if (replaced.length === 0 && symbols.length + edges.length + files.length === 0)
16
+ return;
17
+ await store.replaceGraph(project, replaced, { symbols, edges, files });
22
18
  }
@@ -1,8 +1,10 @@
1
1
  import type { RecallContext } from '../context.js';
2
2
  import type { Observation } from '../types.js';
3
+ import type { HookEnv } from './payload.js';
3
4
  export interface EarlierInChat {
4
5
  block: string;
5
6
  ids: ReadonlySet<string>;
7
+ titles: ReadonlySet<string>;
6
8
  }
7
- export declare function recoverAfterCompact(ctx: RecallContext, project: string, sessionId: string, transcriptPath: string | undefined): Promise<EarlierInChat | null>;
9
+ export declare function recoverAfterCompact(ctx: RecallContext, project: string, sessionId: string, transcriptPath: string | undefined, env?: HookEnv): Promise<EarlierInChat | null>;
8
10
  export declare function renderEarlierInChat(newestFirst: Observation[]): EarlierInChat | null;
@@ -2,6 +2,7 @@ import { flushSession } from '../capture/index.js';
2
2
  import { toShortId } from '../util/shortid.js';
3
3
  import { capturingDisabled } from './payload.js';
4
4
  import { forgetShown } from './shown.js';
5
+ import { hookEnv } from '../util/env.js';
5
6
  const MAX_LINES = 8;
6
7
  const SCANNED = 200;
7
8
  const LABELS = {
@@ -9,9 +10,9 @@ const LABELS = {
9
10
  deadend: 'Dead end',
10
11
  preference: 'Rule',
11
12
  };
12
- export async function recoverAfterCompact(ctx, project, sessionId, transcriptPath) {
13
+ export async function recoverAfterCompact(ctx, project, sessionId, transcriptPath, env = hookEnv()) {
13
14
  forgetShown(sessionId);
14
- if (!capturingDisabled(ctx.config.capture.scripted)) {
15
+ if (!capturingDisabled(ctx.config.capture.scripted, env)) {
15
16
  await flushSession(ctx, sessionId, project, transcriptPath);
16
17
  }
17
18
  const observations = await ctx.store.list({
@@ -44,5 +45,5 @@ export function renderEarlierInChat(newestFirst) {
44
45
  if (lines.length === 0)
45
46
  return null;
46
47
  const block = ['<memory>', 'Earlier in this chat:', ...lines.reverse(), '</memory>'].join('\n');
47
- return { block, ids };
48
+ return { block, ids, titles };
48
49
  }
@@ -3,6 +3,7 @@ import { appendFileSync, closeSync, mkdirSync, openSync, renameSync, statSync }
3
3
  import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { CONFIG_DIR } from '../config/dir.js';
6
+ import { hookEnv } from '../util/env.js';
6
7
  const DIST = resolve(dirname(fileURLToPath(import.meta.url)), '..');
7
8
  export const CLI = resolve(DIST, 'cli', 'index.js');
8
9
  export const PICK_WORKER = resolve(DIST, 'pick', 'worker.js');
@@ -36,6 +37,7 @@ export function runDetached(script, args, cwd, release) {
36
37
  try {
37
38
  spawn(process.execPath, [script, ...args], {
38
39
  cwd,
40
+ env: hookEnv(),
39
41
  detached: true,
40
42
  stdio: ['ignore', log, log],
41
43
  })
@@ -0,0 +1,3 @@
1
+ export declare function graphKnownAbsent(project: string, now?: number): boolean;
2
+ export declare function graphCachedHere(project: string): boolean;
3
+ export declare function noteGraphPresence(project: string, present: boolean): void;
@@ -0,0 +1,42 @@
1
+ import { mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CONFIG_DIR } from '../config/index.js';
4
+ import { cachePath } from '../graph/scan/cache.js';
5
+ import { scopeToken } from '../util/scope.js';
6
+ const ABSENT_FOR_MS = 10 * 60 * 1000;
7
+ const markerOf = (project) => join(CONFIG_DIR, 'graph-absent', `${scopeToken(project)}.flag`);
8
+ const modifiedAt = (file) => statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? null;
9
+ export function graphKnownAbsent(project, now = Date.now()) {
10
+ try {
11
+ const marked = modifiedAt(markerOf(project));
12
+ if (marked === null || now - marked >= ABSENT_FOR_MS)
13
+ return false;
14
+ const scanned = modifiedAt(cachePath(project));
15
+ return scanned === null || scanned < marked;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ export function graphCachedHere(project) {
22
+ try {
23
+ return modifiedAt(cachePath(project)) !== null;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ export function noteGraphPresence(project, present) {
30
+ const marker = markerOf(project);
31
+ try {
32
+ if (present) {
33
+ rmSync(marker, { force: true });
34
+ return;
35
+ }
36
+ mkdirSync(join(CONFIG_DIR, 'graph-absent'), { recursive: true });
37
+ writeFileSync(marker, project);
38
+ }
39
+ catch {
40
+ return;
41
+ }
42
+ }
@@ -1,4 +1,6 @@
1
+ export type PathCheck = (path: string) => boolean;
1
2
  export declare const DECLARED: Set<string>;
3
+ export declare function repoDirectory(cwd: string, root: string): PathCheck;
2
4
  export declare function isSymbol(pattern: string): boolean;
3
5
  export declare function isWord(pattern: string): boolean;
4
- export declare function symbolsGreppedIn(command: string): string[];
6
+ export declare function symbolsGreppedIn(command: string, pathOk?: PathCheck): string[];
@@ -1,14 +1,48 @@
1
+ import { realpathSync, statSync } from 'node:fs';
2
+ import { isAbsolute, relative, resolve } from 'node:path';
1
3
  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
4
  const WORD = /^[a-z][a-z0-9]{3,}$/;
3
5
  export const DECLARED = new Set(['function', 'method', 'class', 'interface', 'type', 'enum']);
4
6
  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;
7
+ const COUNT_OR_INVERT = /(?:^|\s)-[A-Za-z]*[cv]|--invert-match|--count/;
8
+ const OPERATOR_ONLY = /^\d*[<>]+$/;
9
+ const REDIRECT = /^\d*[<>]/;
10
+ const COMMAND_END = /;|&&|\|\||\n/;
11
+ const isOption = (token) => token.startsWith('-');
12
+ function argumentsOf(rest) {
13
+ const tokens = (rest.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((token) => token.replace(/^(['"])(.*)\1$/, '$2'));
14
+ const kept = [];
15
+ let skipNext = false;
16
+ for (const token of tokens) {
17
+ if (skipNext)
18
+ skipNext = false;
19
+ else if (OPERATOR_ONLY.test(token))
20
+ skipNext = true;
21
+ else if (!REDIRECT.test(token))
22
+ kept.push(token);
23
+ }
24
+ return kept;
25
+ }
26
+ const pipesOutput = (command, end) => (command.slice(end).split(COMMAND_END)[0] ?? '').includes('|');
27
+ export function repoDirectory(cwd, root) {
28
+ return (path) => {
29
+ try {
30
+ const target = realpathSync(resolve(cwd, path));
31
+ const scope = relative(realpathSync(root), target);
32
+ return !scope.startsWith('..') && !isAbsolute(scope) && statSync(target).isDirectory();
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ };
38
+ }
5
39
  export function isSymbol(pattern) {
6
40
  return SYMBOL.test(pattern);
7
41
  }
8
42
  export function isWord(pattern) {
9
43
  return WORD.test(pattern);
10
44
  }
11
- export function symbolsGreppedIn(command) {
45
+ export function symbolsGreppedIn(command, pathOk = () => true) {
12
46
  const found = new Set();
13
47
  for (const match of command.matchAll(GREP)) {
14
48
  const flags = match[1] ?? '';
@@ -16,7 +50,12 @@ export function symbolsGreppedIn(command) {
16
50
  const rest = match[5] ?? '';
17
51
  if (!SYMBOL.test(pattern) && !WORD.test(pattern))
18
52
  continue;
19
- if (/(?:^|\s)-[A-Za-z]*v|--invert-match/.test(flags))
53
+ const args = argumentsOf(rest);
54
+ if (COUNT_OR_INVERT.test([flags, ...args.filter(isOption)].join(' ')))
55
+ continue;
56
+ if (pipesOutput(command, match.index + match[0].length))
57
+ continue;
58
+ if (!args.filter((arg) => !isOption(arg)).every(pathOk))
20
59
  continue;
21
60
  const invocation = match[0];
22
61
  const piped = /^\s*\|/.test(invocation);
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function preferUsages(run: HookRun): Promise<void>;
@@ -0,0 +1,118 @@
1
+ import { addText, answerQuery, formatGraph, formatText } from '../../graph/index.js';
2
+ import { hasGraph } from '../../graph/query/answer.js';
3
+ import { staleFiles } from '../../graph/query/stale.js';
4
+ import { repoRootFor } from '../../usages/index.js';
5
+ import { DECLARED, isSymbol, isWord, repoDirectory, symbolsGreppedIn } from '../grep-symbols.js';
6
+ import { graphCachedHere, graphKnownAbsent, noteGraphPresence } from '../graph-presence.js';
7
+ import { refreshGraphInBackground } from '../graph-refresh.js';
8
+ import { resolveProject } from '../../util/project.js';
9
+ import { hookEnv } from '../../util/env.js';
10
+ const MAX_SYMBOLS = 2;
11
+ const MAX_LINES = 14;
12
+ const TEXT_LINES = 6;
13
+ const EDGE_LIMIT = 20;
14
+ function requested(payload, project) {
15
+ const input = payload.tool_input ?? {};
16
+ const inRepo = repoDirectory(payload.cwd ?? project, project);
17
+ if (payload.tool_name === 'Grep') {
18
+ const pattern = typeof input['pattern'] === 'string' ? input['pattern'] : '';
19
+ const path = input['path'];
20
+ if (input['output_mode'] === 'count')
21
+ return [];
22
+ if (typeof path === 'string' && !inRepo(path))
23
+ return [];
24
+ return isSymbol(pattern) || isWord(pattern) ? [pattern] : [];
25
+ }
26
+ if (payload.tool_name === 'Bash') {
27
+ const command = typeof input['command'] === 'string' ? input['command'] : '';
28
+ return symbolsGreppedIn(command, inRepo);
29
+ }
30
+ return [];
31
+ }
32
+ function trim(answer) {
33
+ const lines = answer.split('\n');
34
+ if (lines.length <= MAX_LINES)
35
+ return answer;
36
+ return [...lines.slice(0, MAX_LINES), ` ... more via find_usages`].join('\n');
37
+ }
38
+ const answers = (answer, symbol) => !answer.empty && (isSymbol(symbol) || answer.definitions.some((d) => DECLARED.has(d.kind)));
39
+ function block(answer, root) {
40
+ const graph = trim(formatGraph(answer, root, { text: false }));
41
+ return [graph, ...formatText(answer.text, TEXT_LINES)].join('\n');
42
+ }
43
+ const staleNote = (count) => `(${count} file(s) changed since the last scan and are being re-read in the background, ` +
44
+ 'so lines in them may have moved. The text matches are live.)';
45
+ async function freshnessNote(store, project) {
46
+ try {
47
+ const root = repoRootFor(project);
48
+ const stale = staleFiles(root, await store.scannedFiles(project));
49
+ if (stale.length === 0)
50
+ return null;
51
+ refreshGraphInBackground(project, root);
52
+ return staleNote(stale.length);
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ async function answerSymbols(ctx, project, symbols) {
59
+ const answered = { named: [], blocks: [] };
60
+ for (const symbol of symbols) {
61
+ const answer = await answerQuery({
62
+ store: ctx.store,
63
+ root: project,
64
+ project,
65
+ query: { mode: 'usages', symbol, limit: EDGE_LIMIT, suggest: false },
66
+ refresh: false,
67
+ text: false,
68
+ });
69
+ if (!answers(answer, symbol))
70
+ continue;
71
+ addText(answer, project);
72
+ answered.named.push(symbol);
73
+ answered.blocks.push(block(answer, project));
74
+ }
75
+ if (answered.blocks.length > 0) {
76
+ const note = await freshnessNote(ctx.store, project);
77
+ if (note)
78
+ answered.blocks.push(note);
79
+ }
80
+ else if (!graphCachedHere(project) && !(await hasGraph(ctx.store, project))) {
81
+ noteGraphPresence(project, false);
82
+ }
83
+ return answered;
84
+ }
85
+ export default async function preferUsages(run) {
86
+ const mode = hookEnv()['CLAUDE_DB_USAGES_HOOK'] ?? 'directive';
87
+ if (mode === 'off')
88
+ return;
89
+ const { payload } = run;
90
+ const project = resolveProject(payload.cwd);
91
+ const symbols = requested(payload, project).slice(0, MAX_SYMBOLS);
92
+ if (symbols.length === 0)
93
+ return;
94
+ if (graphKnownAbsent(project))
95
+ return;
96
+ const { named, blocks } = await run.withContext((ctx) => answerSymbols(ctx, project, symbols));
97
+ if (blocks.length === 0)
98
+ return;
99
+ const names = named.map((s) => `\`${s}\``).join(', ');
100
+ if (mode === 'directive') {
101
+ run.write(JSON.stringify({
102
+ hookSpecificOutput: {
103
+ hookEventName: 'PreToolUse',
104
+ additionalContext: `Code graph answer for ${names} (the grep still runs):\n\n${blocks.join('\n\n')}`,
105
+ },
106
+ }));
107
+ return;
108
+ }
109
+ run.write(JSON.stringify({
110
+ hookSpecificOutput: {
111
+ hookEventName: 'PreToolUse',
112
+ permissionDecision: 'deny',
113
+ permissionDecisionReason: `Blocked: ${names} names a declared symbol — use the \`find_usages\` MCP tool ` +
114
+ `for symbol lookups, not grep. Its answer for this search is already below, so ` +
115
+ `nothing needs re-running:\n\n${blocks.join('\n\n')}`,
116
+ },
117
+ }));
118
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function sessionEnd(run: HookRun): Promise<void>;
@@ -0,0 +1,60 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { hookEnv } from '../../util/env.js';
5
+ import { clearActive, sweepActive } from '../../capture/active.js';
6
+ import { aiSummary, flushSession, observationsFromTurns, readTranscript, transcriptPathFor, } from '../../capture/index.js';
7
+ import { loadConfig } from '../../config/index.js';
8
+ import { distillBlocked } from '../../facts/budget.js';
9
+ import { clearPick, sweepPicks } from '../../pick/pending.js';
10
+ import { isDue, readState } from '../../update.js';
11
+ import { resolveProject } from '../../util/project.js';
12
+ import { distillInBackground } from '../background.js';
13
+ import { capturingDisabled } from '../payload.js';
14
+ import { dropTurnSave, sweepTurnSaves } from '../turn-job.js';
15
+ const CLI = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', 'cli', 'index.js');
16
+ export default async function sessionEnd(run) {
17
+ if (capturingDisabled(loadConfig().capture.scripted))
18
+ return;
19
+ const { payload } = run;
20
+ const sessionId = payload.session_id;
21
+ if (!sessionId)
22
+ return;
23
+ const project = resolveProject(payload.cwd);
24
+ await run.withContext(async (ctx) => {
25
+ const result = await flushSession(ctx, sessionId, project, payload.transcript_path);
26
+ let summary = result.summary;
27
+ if (!ctx.config.distill.enabled && ctx.config.capture.summarize === 'on') {
28
+ const path = payload.transcript_path ?? transcriptPathFor(project, sessionId);
29
+ const { turns } = readTranscript(path, 0);
30
+ const observations = observationsFromTurns(turns, sessionId, project, ctx.config);
31
+ const ai = await aiSummary(observations.map((obs) => `${obs.title}\n${obs.body}`).join('\n\n'), ctx.config.capture.summarizeModel);
32
+ if (ai)
33
+ summary = `AI: ${ai}`;
34
+ }
35
+ await ctx.store.upsertSession({
36
+ id: sessionId,
37
+ project,
38
+ startedAt: Date.now(),
39
+ endedAt: Date.now(),
40
+ ...(summary ? { summary } : {}),
41
+ });
42
+ clearPick(sessionId);
43
+ sweepPicks();
44
+ dropTurnSave(sessionId);
45
+ sweepTurnSaves();
46
+ clearActive(sessionId);
47
+ sweepActive();
48
+ const { distill } = ctx.config;
49
+ if (distill.enabled && !distillBlocked(distill.dailyLimit)) {
50
+ distillInBackground(project, sessionId);
51
+ }
52
+ if (ctx.config.updates !== 'off' && isDue(readState())) {
53
+ spawn(process.execPath, [CLI, 'update', '--quiet'], {
54
+ env: hookEnv(),
55
+ detached: true,
56
+ stdio: 'ignore',
57
+ }).unref();
58
+ }
59
+ });
60
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function sessionStart(run: HookRun): Promise<void>;
@@ -0,0 +1,83 @@
1
+ import { dirname, resolve } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { sweepCursorsDaily } from '../../capture/index.js';
4
+ import { loadConfig } from '../../config/index.js';
5
+ import { distillNotice } from '../../facts/notice.js';
6
+ import { startFacts } from '../../facts/start.js';
7
+ import { startBackgroundWork } from '../background.js';
8
+ import { noteGraphPresence } from '../graph-presence.js';
9
+ import { refreshGraphInBackground } from '../graph-refresh.js';
10
+ import { recoverAfterCompact } from '../compact.js';
11
+ import { capturingDisabled, emitSessionStart } from '../payload.js';
12
+ import { markShown } from '../shown.js';
13
+ import { resolveProject } from '../../util/project.js';
14
+ import { repoRootFor } from '../../usages/index.js';
15
+ import { refreshInstalled } from '../../cli/refresh.js';
16
+ import { updateNotice } from '../../update.js';
17
+ const SCAN_HINT = 'Code graph not built yet — run `claude-db scan` once to enable ' +
18
+ 'find_usages and the symbol-grep hook.';
19
+ function refreshGraphQuietly(project) {
20
+ try {
21
+ refreshGraphInBackground(project, repoRootFor(project));
22
+ }
23
+ catch {
24
+ return;
25
+ }
26
+ }
27
+ function sweepCursorsQuietly() {
28
+ try {
29
+ sweepCursorsDaily();
30
+ }
31
+ catch {
32
+ return;
33
+ }
34
+ }
35
+ function refreshInstalledQuietly(project) {
36
+ try {
37
+ refreshInstalled(resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'), project);
38
+ }
39
+ catch {
40
+ return;
41
+ }
42
+ }
43
+ function isGitRepo(project) {
44
+ try {
45
+ repoRootFor(project);
46
+ return true;
47
+ }
48
+ catch {
49
+ return false;
50
+ }
51
+ }
52
+ export default async function sessionStart(run) {
53
+ const { payload } = run;
54
+ const project = resolveProject(payload.cwd);
55
+ refreshInstalledQuietly(project);
56
+ if (capturingDisabled(loadConfig().capture.scripted))
57
+ return;
58
+ await run.withContext(async (ctx) => {
59
+ startBackgroundWork(project, ctx.config.database);
60
+ const earlier = payload.source === 'compact' && payload.session_id
61
+ ? await recoverAfterCompact(ctx, project, payload.session_id, payload.transcript_path)
62
+ : null;
63
+ const restored = earlier?.ids ?? new Set();
64
+ const facts = await startFacts(ctx, project, restored, payload.session_id, earlier?.titles);
65
+ if (facts && payload.session_id)
66
+ markShown(payload.session_id, [...facts.ids]);
67
+ const scanned = (await ctx.store.scannedFiles(project, 1)).length > 0;
68
+ noteGraphPresence(project, scanned);
69
+ const update = ctx.config.updates === 'off' ? null : updateNotice();
70
+ const notice = [
71
+ await distillNotice(ctx, project),
72
+ !scanned && isGitRepo(project) ? SCAN_HINT : null,
73
+ update,
74
+ ]
75
+ .filter(Boolean)
76
+ .join('\n');
77
+ const body = [earlier?.block, facts?.block].filter(Boolean).join('\n');
78
+ emitSessionStart(body ? `${body}\n` : '', notice || null, run.write);
79
+ if (scanned)
80
+ refreshGraphQuietly(project);
81
+ sweepCursorsQuietly();
82
+ });
83
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function turnEnd(run: HookRun): Promise<void>;