claude-db 0.12.3 → 0.13.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 (121) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/capture/cursors.d.ts +8 -0
  3. package/dist/capture/cursors.js +99 -0
  4. package/dist/capture/flush-lock.d.ts +11 -0
  5. package/dist/capture/flush-lock.js +108 -0
  6. package/dist/capture/flush.d.ts +4 -4
  7. package/dist/capture/flush.js +27 -60
  8. package/dist/capture/index.d.ts +3 -3
  9. package/dist/capture/index.js +3 -3
  10. package/dist/capture/progress.js +8 -1
  11. package/dist/capture/reingest.d.ts +1 -0
  12. package/dist/capture/reingest.js +4 -1
  13. package/dist/capture/scrub.d.ts +1 -0
  14. package/dist/capture/scrub.js +4 -1
  15. package/dist/capture/vectors.js +2 -1
  16. package/dist/catchup/gather.js +1 -0
  17. package/dist/cli/commands/daemon.d.ts +1 -0
  18. package/dist/cli/commands/daemon.js +29 -0
  19. package/dist/cli/commands/distill.js +2 -1
  20. package/dist/cli/commands/graph.js +2 -1
  21. package/dist/cli/commands/maintain.js +3 -1
  22. package/dist/cli/commands/sync.js +5 -4
  23. package/dist/cli/commands/transfer.js +4 -3
  24. package/dist/cli/index.js +4 -0
  25. package/dist/cli/usage.js +1 -0
  26. package/dist/config/schema.d.ts +4 -0
  27. package/dist/config/schema.js +6 -0
  28. package/dist/context.d.ts +1 -0
  29. package/dist/context.js +21 -6
  30. package/dist/daemon/client.d.ts +12 -0
  31. package/dist/daemon/client.js +88 -0
  32. package/dist/daemon/paths.d.ts +16 -0
  33. package/dist/daemon/paths.js +19 -0
  34. package/dist/daemon/server.d.ts +2 -0
  35. package/dist/daemon/server.js +225 -0
  36. package/dist/facts/budget.d.ts +1 -0
  37. package/dist/facts/budget.js +4 -0
  38. package/dist/facts/claude-memory.js +7 -2
  39. package/dist/facts/distill.js +6 -3
  40. package/dist/facts/handoff.js +6 -1
  41. package/dist/facts/known.js +3 -1
  42. package/dist/facts/model.d.ts +1 -1
  43. package/dist/facts/model.js +18 -7
  44. package/dist/facts/start.js +2 -2
  45. package/dist/graph/query/answer.js +1 -1
  46. package/dist/graph/query/path.js +69 -37
  47. package/dist/graph/query/refresh.js +5 -1
  48. package/dist/graph/query/suggest.js +1 -2
  49. package/dist/graph/scan/cache.d.ts +1 -0
  50. package/dist/graph/scan/cache.js +1 -1
  51. package/dist/graph/scan/persist.js +12 -16
  52. package/dist/hooks/compact.d.ts +2 -1
  53. package/dist/hooks/compact.js +9 -3
  54. package/dist/hooks/detached.d.ts +1 -0
  55. package/dist/hooks/detached.js +6 -0
  56. package/dist/hooks/graph-presence.d.ts +3 -0
  57. package/dist/hooks/graph-presence.js +42 -0
  58. package/dist/hooks/handlers/prefer-usages.d.ts +2 -0
  59. package/dist/hooks/handlers/prefer-usages.js +113 -0
  60. package/dist/hooks/handlers/session-end.d.ts +2 -0
  61. package/dist/hooks/handlers/session-end.js +62 -0
  62. package/dist/hooks/handlers/session-start.d.ts +2 -0
  63. package/dist/hooks/handlers/session-start.js +104 -0
  64. package/dist/hooks/handlers/turn-end.d.ts +2 -0
  65. package/dist/hooks/handlers/turn-end.js +31 -0
  66. package/dist/hooks/handlers/user-prompt.d.ts +2 -0
  67. package/dist/hooks/handlers/user-prompt.js +55 -0
  68. package/dist/hooks/local.d.ts +2 -0
  69. package/dist/hooks/local.js +23 -0
  70. package/dist/hooks/payload.d.ts +9 -4
  71. package/dist/hooks/payload.js +26 -17
  72. package/dist/hooks/prefer-usages.js +2 -118
  73. package/dist/hooks/route.d.ts +2 -0
  74. package/dist/hooks/route.js +28 -0
  75. package/dist/hooks/run.d.ts +14 -0
  76. package/dist/hooks/run.js +12 -0
  77. package/dist/hooks/save-turn.d.ts +2 -0
  78. package/dist/hooks/save-turn.js +11 -0
  79. package/dist/hooks/session-end.js +2 -63
  80. package/dist/hooks/session-start.js +2 -90
  81. package/dist/hooks/start-legacy.js +1 -1
  82. package/dist/hooks/turn-end.js +2 -25
  83. package/dist/hooks/turn-save.js +10 -15
  84. package/dist/hooks/user-prompt.js +2 -58
  85. package/dist/search/service.d.ts +1 -0
  86. package/dist/search/service.js +16 -6
  87. package/dist/store/adapter.d.ts +11 -7
  88. package/dist/store/each.d.ts +2 -4
  89. package/dist/store/each.js +1 -0
  90. package/dist/store/mongo/graph.d.ts +2 -1
  91. package/dist/store/mongo/graph.js +17 -2
  92. package/dist/store/mongo/index.d.ts +7 -8
  93. package/dist/store/mongo/index.js +13 -2
  94. package/dist/store/mongo/observations.d.ts +2 -1
  95. package/dist/store/mongo/observations.js +38 -4
  96. package/dist/store/postgres/driver.d.ts +10 -3
  97. package/dist/store/postgres/driver.js +12 -0
  98. package/dist/store/postgres/graph.d.ts +5 -6
  99. package/dist/store/postgres/graph.js +78 -57
  100. package/dist/store/postgres/index.d.ts +7 -8
  101. package/dist/store/postgres/index.js +16 -11
  102. package/dist/store/postgres/insert.js +98 -48
  103. package/dist/store/postgres/meta.d.ts +1 -0
  104. package/dist/store/postgres/meta.js +4 -0
  105. package/dist/store/postgres/observations.d.ts +3 -2
  106. package/dist/store/postgres/observations.js +40 -6
  107. package/dist/store/postgres/rows.js +1 -1
  108. package/dist/store/project-resolver.d.ts +3 -0
  109. package/dist/store/project-resolver.js +34 -23
  110. package/dist/store/scoped-store.js +5 -1
  111. package/dist/store/sqlite/graph.d.ts +5 -6
  112. package/dist/store/sqlite/graph.js +61 -35
  113. package/dist/store/sqlite/index.d.ts +7 -8
  114. package/dist/store/sqlite/index.js +11 -2
  115. package/dist/store/sqlite/observations.d.ts +2 -1
  116. package/dist/store/sqlite/observations.js +38 -7
  117. package/dist/types.d.ts +9 -0
  118. package/dist/util/job-lock.d.ts +1 -0
  119. package/dist/util/job-lock.js +50 -10
  120. package/docs/setup-guide.md +5 -0
  121. package/package.json +6 -8
@@ -1,5 +1,7 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { hostname } from 'node:os';
2
+ import { existsSync } from 'node:fs';
3
+ import { homedir, hostname } from 'node:os';
4
+ import { isAbsolute } from 'node:path';
3
5
  import { currentAuthor, observationId } from '../capture/identity.js';
4
6
  import { redact } from '../capture/redact.js';
5
7
  import { scopeToken } from '../util/scope.js';
@@ -22,20 +24,29 @@ const LABELS = {
22
24
  todo: 'To do',
23
25
  fact: 'Fact',
24
26
  };
25
- let you = null;
26
- export function youScope() {
27
- if (you === null) {
27
+ const you = new Map();
28
+ function folderOf(project) {
29
+ if (project && isAbsolute(project) && existsSync(project))
30
+ return project;
31
+ return homedir();
32
+ }
33
+ export function youScope(project) {
34
+ const folder = folderOf(project);
35
+ let scope = you.get(folder);
36
+ if (scope === undefined) {
28
37
  let email = '';
29
38
  try {
30
39
  email = execFileSync('git', ['config', '--get', 'user.email'], {
40
+ cwd: folder,
31
41
  encoding: 'utf8',
32
42
  stdio: ['ignore', 'pipe', 'ignore'],
33
43
  }).trim();
34
44
  }
35
45
  catch { }
36
- you = `@you:${email || currentAuthor() || 'unknown'}`;
46
+ scope = `@you:${email || currentAuthor() || 'unknown'}`;
47
+ you.set(folder, scope);
37
48
  }
38
- return you;
49
+ return scope;
39
50
  }
40
51
  export function machineTag() {
41
52
  return `machine:${scopeToken(hostname())}`;
@@ -44,7 +55,7 @@ export function originTag(project) {
44
55
  return `origin:${scopeToken(project)}`;
45
56
  }
46
57
  export function scopeProject(scope, project) {
47
- return scope === 'you' ? youScope() : project;
58
+ return scope === 'you' ? youScope(project) : project;
48
59
  }
49
60
  export function factId(owner, key) {
50
61
  return observationId(FACT_SESSION, 0, `${owner}\0${key}`);
@@ -13,8 +13,8 @@ const UNCOMMITTED = 3;
13
13
  const ORDER = ['rule', 'decision', 'deadend', 'fact'];
14
14
  export async function startFacts(ctx, project, hidden = new Set(), current) {
15
15
  const visible = (obs) => obs.status !== 'replaced' && !hidden.has(obs.id) && !seenByClaude(obs, project);
16
- const list = async (owner, sessionId, limit) => (await ctx.store.list({ project: owner, sessionId, newest: true, limit })).filter(visible);
17
- const you = onePerKey(await list(youScope(), FACT_SESSION, 50));
16
+ const list = async (owner, sessionId, limit) => (await ctx.store.list({ project: owner, sessionId, newest: true, limit, bodies: false })).filter(visible);
17
+ const you = onePerKey(await list(youScope(project), FACT_SESSION, 50));
18
18
  const facts = onePerKey(await list(project, FACT_SESSION, 300));
19
19
  const handoff = await newestHandoff(ctx, project);
20
20
  const shownHandoff = handoff && visible(handoff) ? handoff : null;
@@ -10,7 +10,7 @@ export function addText(answer, root) {
10
10
  return;
11
11
  answer.text = unlinkedText(root, answer.symbol, answer.definitions, answer.inbound);
12
12
  }
13
- export const hasGraph = async (store, project) => (await store.scannedFiles(project)).length > 0;
13
+ export const hasGraph = async (store, project) => (await store.scannedFiles(project, 1)).length > 0;
14
14
  export async function answerQuery(request) {
15
15
  const { store, root, project, query } = request;
16
16
  const refreshed = request.refresh ? await refreshGraph(store, root, project) : [];
@@ -1,48 +1,80 @@
1
1
  const MAX_EDGES = 20000;
2
- const MAX_SYMBOLS = 20000;
2
+ const MAX_ENDPOINTS = 5000;
3
+ const UNRESOLVED = 'name:';
4
+ const nodeFor = (id, name) => (id ? id : `${UNRESOLVED}${name}`);
5
+ function sideFrom(nodes) {
6
+ return {
7
+ parent: new Map(nodes.map((node) => [node, null])),
8
+ depth: new Map(nodes.map((node) => [node, 0])),
9
+ frontier: nodes,
10
+ };
11
+ }
12
+ async function endpoints(store, project, name) {
13
+ const symbols = await store.findSymbols({ project, name, limit: MAX_ENDPOINTS });
14
+ return [...new Set(symbols.map((symbol) => symbol.id)), `${UNRESOLVED}${name}`];
15
+ }
16
+ function edgesOf(store, project, frontier, forward, limit) {
17
+ const ids = frontier.filter((node) => !node.startsWith(UNRESOLVED));
18
+ const names = frontier
19
+ .filter((node) => node.startsWith(UNRESOLVED))
20
+ .map((node) => node.slice(UNRESOLVED.length));
21
+ return store.findEdges(forward
22
+ ? { project, srcIds: ids, unresolvedSrcNames: names, limit }
23
+ : { project, dstIds: ids, unresolvedDstNames: names, limit });
24
+ }
25
+ function chain(side, from) {
26
+ const nodes = [];
27
+ for (let node = from; node; node = side.parent.get(node)) {
28
+ nodes.push(node);
29
+ }
30
+ return nodes;
31
+ }
3
32
  export async function shortestPath(store, project, from, to) {
4
33
  if (!from || !to)
5
34
  return [];
6
35
  if (from === to)
7
36
  return [from];
8
- const graphology = (await import('graphology'));
9
- const Graph = graphology.default;
10
- const { bidirectional } = (await import('graphology-shortest-path/unweighted.js'));
11
- const [symbols, edges] = await Promise.all([
12
- store.findSymbols({ project, limit: MAX_SYMBOLS }),
13
- store.findEdges({ project, limit: MAX_EDGES }),
14
- ]);
15
37
  const label = new Map();
16
- for (const symbol of symbols)
17
- label.set(symbol.id, symbol.name);
18
- const graph = new Graph({ type: 'directed', multi: false, allowSelfLoops: false });
19
- const nodeFor = (id, name) => (id ? id : `name:${name}`);
20
- for (const edge of edges) {
21
- const src = nodeFor(edge.srcId, edge.srcName);
22
- const dst = nodeFor(edge.dstId, edge.dstName);
23
- if (src === dst)
24
- continue;
25
- graph.mergeDirectedEdge(src, dst);
26
- }
27
- const endpoints = (name) => {
28
- const ids = symbols.filter((symbol) => symbol.name === name).map((symbol) => symbol.id);
29
- const nodes = ids.filter((id) => graph.hasNode(id));
30
- const unresolved = `name:${name}`;
31
- if (graph.hasNode(unresolved))
32
- nodes.push(unresolved);
33
- return nodes;
34
- };
35
- let best = null;
36
- for (const start of endpoints(from)) {
37
- for (const end of endpoints(to)) {
38
- if (start === end)
38
+ const ahead = sideFrom(await endpoints(store, project, from));
39
+ const behind = sideFrom(await endpoints(store, project, to));
40
+ for (const node of ahead.frontier)
41
+ label.set(node, from);
42
+ for (const node of behind.frontier)
43
+ label.set(node, to);
44
+ let spent = 0;
45
+ while (ahead.frontier.length > 0 && behind.frontier.length > 0) {
46
+ const forward = ahead.frontier.length <= behind.frontier.length;
47
+ const [mine, other] = forward ? [ahead, behind] : [behind, ahead];
48
+ const current = new Set(mine.frontier);
49
+ const edges = await edgesOf(store, project, mine.frontier, forward, MAX_EDGES - spent + 1);
50
+ spent += edges.length;
51
+ if (spent > MAX_EDGES)
52
+ return [];
53
+ const next = [];
54
+ let meet = null;
55
+ for (const edge of edges) {
56
+ const src = nodeFor(edge.srcId, edge.srcName);
57
+ const dst = nodeFor(edge.dstId, edge.dstName);
58
+ if (src === dst)
59
+ continue;
60
+ if (!label.has(src))
61
+ label.set(src, edge.srcName);
62
+ const [near, far] = forward ? [src, dst] : [dst, src];
63
+ if (!current.has(near) || mine.parent.has(far))
39
64
  continue;
40
- const found = bidirectional(graph, start, end);
41
- if (found && (!best || found.length < best.length))
42
- best = found;
65
+ mine.parent.set(far, near);
66
+ mine.depth.set(far, (mine.depth.get(near) ?? 0) + 1);
67
+ next.push(far);
68
+ const reached = other.depth.get(far);
69
+ if (reached !== undefined && (meet === null || reached < (other.depth.get(meet) ?? 0))) {
70
+ meet = far;
71
+ }
43
72
  }
73
+ if (meet !== null) {
74
+ const nodes = [...chain(ahead, meet).reverse(), ...chain(behind, meet).slice(1)];
75
+ return nodes.map((node) => label.get(node) ?? node.replace(/^name:/, ''));
76
+ }
77
+ mine.frontier = next;
44
78
  }
45
- if (!best)
46
- return [];
47
- return best.map((node) => label.get(node) ?? node.replace(/^name:/, ''));
79
+ return [];
48
80
  }
@@ -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 [];
@@ -44,8 +44,7 @@ export async function suggestFor(store, project, symbol) {
44
44
  if (!symbol)
45
45
  return [];
46
46
  try {
47
- const symbols = await store.findSymbols({ project, limit: CANDIDATES });
48
- return nearest(symbols.map((entry) => entry.name), symbol);
47
+ return nearest(await store.symbolNames(project, CANDIDATES), symbol);
49
48
  }
50
49
  catch {
51
50
  return [];
@@ -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;
@@ -5,7 +5,7 @@ import { scopeToken } from '../../util/scope.js';
5
5
  import { CACHE_KEY } from './files.js';
6
6
  const MEMO_IDLE_MS = 10 * 60 * 1000;
7
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 cachePath = (project) => join(cacheHome(), `${scopeToken(project)}.json`);
9
9
  function receiverTable() {
10
10
  const list = [];
11
11
  const positions = new Map();
@@ -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,9 @@
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>;
6
7
  }
7
- export declare function recoverAfterCompact(ctx: RecallContext, project: string, sessionId: string, transcriptPath: string | undefined): Promise<EarlierInChat | null>;
8
+ export declare function recoverAfterCompact(ctx: RecallContext, project: string, sessionId: string, transcriptPath: string | undefined, env?: HookEnv): Promise<EarlierInChat | null>;
8
9
  export declare function renderEarlierInChat(newestFirst: Observation[]): EarlierInChat | null;
@@ -9,12 +9,18 @@ const LABELS = {
9
9
  deadend: 'Dead end',
10
10
  preference: 'Rule',
11
11
  };
12
- export async function recoverAfterCompact(ctx, project, sessionId, transcriptPath) {
12
+ export async function recoverAfterCompact(ctx, project, sessionId, transcriptPath, env = process.env) {
13
13
  forgetShown(sessionId);
14
- if (!capturingDisabled(ctx.config.capture.scripted)) {
14
+ if (!capturingDisabled(ctx.config.capture.scripted, env)) {
15
15
  await flushSession(ctx, sessionId, project, transcriptPath);
16
16
  }
17
- const observations = await ctx.store.list({ project, sessionId, newest: true, limit: SCANNED });
17
+ const observations = await ctx.store.list({
18
+ project,
19
+ sessionId,
20
+ newest: true,
21
+ limit: SCANNED,
22
+ bodies: false,
23
+ });
18
24
  return renderEarlierInChat(observations);
19
25
  }
20
26
  export function renderEarlierInChat(newestFirst) {
@@ -1,5 +1,6 @@
1
1
  export declare const CLI: string;
2
2
  export declare const PICK_WORKER: string;
3
3
  export declare const TURN_WORKER: string;
4
+ export declare function withWorkerEnv<T>(env: NodeJS.ProcessEnv | undefined, work: () => T): T;
4
5
  export declare const backgroundLog: () => string;
5
6
  export declare function runDetached(script: string, args: string[], cwd: string, release: () => void): void;
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { appendFileSync, closeSync, mkdirSync, openSync, renameSync, statSync } from 'node:fs';
3
4
  import { basename, dirname, join, resolve } from 'node:path';
@@ -8,6 +9,10 @@ export const CLI = resolve(DIST, 'cli', 'index.js');
8
9
  export const PICK_WORKER = resolve(DIST, 'pick', 'worker.js');
9
10
  export const TURN_WORKER = resolve(DIST, 'hooks', 'turn-save.js');
10
11
  const LOG_LIMIT = 1024 * 1024;
12
+ const workerEnvs = new AsyncLocalStorage();
13
+ export function withWorkerEnv(env, work) {
14
+ return env ? workerEnvs.run(env, work) : work();
15
+ }
11
16
  export const backgroundLog = () => join(CONFIG_DIR, 'logs', 'background.log');
12
17
  function rotate(path) {
13
18
  try {
@@ -36,6 +41,7 @@ export function runDetached(script, args, cwd, release) {
36
41
  try {
37
42
  spawn(process.execPath, [script, ...args], {
38
43
  cwd,
44
+ env: workerEnvs.getStore() ?? process.env,
39
45
  detached: true,
40
46
  stdio: ['ignore', log, log],
41
47
  })
@@ -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
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function preferUsages(run: HookRun): Promise<void>;
@@ -0,0 +1,113 @@
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, 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
+ const MAX_SYMBOLS = 2;
10
+ const MAX_LINES = 14;
11
+ const TEXT_LINES = 6;
12
+ const EDGE_LIMIT = 20;
13
+ function requested(payload) {
14
+ const input = payload.tool_input ?? {};
15
+ if (payload.tool_name === 'Grep') {
16
+ const pattern = typeof input['pattern'] === 'string' ? input['pattern'] : '';
17
+ return isSymbol(pattern) || isWord(pattern) ? [pattern] : [];
18
+ }
19
+ if (payload.tool_name === 'Bash') {
20
+ return symbolsGreppedIn(typeof input['command'] === 'string' ? input['command'] : '');
21
+ }
22
+ return [];
23
+ }
24
+ function trim(answer) {
25
+ const lines = answer.split('\n');
26
+ if (lines.length <= MAX_LINES)
27
+ return answer;
28
+ return [...lines.slice(0, MAX_LINES), ` ... more via find_usages`].join('\n');
29
+ }
30
+ const answers = (answer, symbol) => !answer.empty && (isSymbol(symbol) || answer.definitions.some((d) => DECLARED.has(d.kind)));
31
+ function block(answer, root) {
32
+ const graph = trim(formatGraph(answer, root, { text: false }));
33
+ return [graph, ...formatText(answer.text, TEXT_LINES)].join('\n');
34
+ }
35
+ const staleNote = (count) => `(${count} file(s) changed since the last scan and are being re-read in the background, ` +
36
+ 'so lines in them may have moved. The text matches are live.)';
37
+ async function freshnessNote(store, project) {
38
+ try {
39
+ const root = repoRootFor(project);
40
+ const stale = staleFiles(root, await store.scannedFiles(project));
41
+ if (stale.length === 0)
42
+ return null;
43
+ refreshGraphInBackground(project, root);
44
+ return staleNote(stale.length);
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ async function answerSymbols(ctx, project, symbols) {
51
+ const answered = { named: [], blocks: [] };
52
+ for (const symbol of symbols) {
53
+ const answer = await answerQuery({
54
+ store: ctx.store,
55
+ root: project,
56
+ project,
57
+ query: { mode: 'usages', symbol, limit: EDGE_LIMIT, suggest: false },
58
+ refresh: false,
59
+ text: false,
60
+ });
61
+ if (!answers(answer, symbol))
62
+ continue;
63
+ addText(answer, project);
64
+ answered.named.push(symbol);
65
+ answered.blocks.push(block(answer, project));
66
+ }
67
+ if (answered.blocks.length > 0) {
68
+ const note = await freshnessNote(ctx.store, project);
69
+ if (note)
70
+ answered.blocks.push(note);
71
+ }
72
+ else if (!graphCachedHere(project) && !(await hasGraph(ctx.store, project))) {
73
+ noteGraphPresence(project, false);
74
+ }
75
+ return answered;
76
+ }
77
+ export default async function preferUsages(run) {
78
+ const mode = run.env['CLAUDE_DB_USAGES_HOOK'] ?? 'deny';
79
+ if (mode === 'off')
80
+ return;
81
+ const { payload } = run;
82
+ const symbols = requested(payload).slice(0, MAX_SYMBOLS);
83
+ if (symbols.length === 0)
84
+ return;
85
+ const project = resolveProject(payload.cwd);
86
+ if (graphKnownAbsent(project))
87
+ return;
88
+ const { named, blocks } = await run.withContext((ctx) => answerSymbols(ctx, project, symbols));
89
+ if (blocks.length === 0)
90
+ return;
91
+ const names = named.map((s) => `\`${s}\``).join(', ');
92
+ if (mode === 'directive') {
93
+ run.write(JSON.stringify({
94
+ hookSpecificOutput: {
95
+ hookEventName: 'PreToolUse',
96
+ additionalContext: `You are grepping the declared symbol(s) ${names}. Use the \`find_usages\` MCP ` +
97
+ `tool for symbol lookups — grep cannot tell a call from an import or show the ` +
98
+ `blast radius. The graph's answer for this search is below; read it instead of ` +
99
+ `the grep output, and call find_usages directly next time:\n\n${blocks.join('\n\n')}`,
100
+ },
101
+ }));
102
+ return;
103
+ }
104
+ run.write(JSON.stringify({
105
+ hookSpecificOutput: {
106
+ hookEventName: 'PreToolUse',
107
+ permissionDecision: 'deny',
108
+ permissionDecisionReason: `Blocked: ${names} names a declared symbol — use the \`find_usages\` MCP tool ` +
109
+ `for symbol lookups, not grep. Its answer for this search is already below, so ` +
110
+ `nothing needs re-running:\n\n${blocks.join('\n\n')}`,
111
+ },
112
+ }));
113
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function sessionEnd(run: HookRun): Promise<void>;
@@ -0,0 +1,62 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { clearActive, sweepActive } from '../../capture/active.js';
5
+ import { aiSummary, flushSession, observationsFromTurns, readTranscript, transcriptPathFor, } from '../../capture/index.js';
6
+ import { loadConfig } from '../../config/index.js';
7
+ import { distillBlocked } from '../../facts/budget.js';
8
+ import { clearPick, sweepPicks } from '../../pick/pending.js';
9
+ import { isDue, readState } from '../../update.js';
10
+ import { resolveProject } from '../../util/project.js';
11
+ import { distillInBackground } from '../background.js';
12
+ import { capturingDisabled } from '../payload.js';
13
+ import { dropTurnSave, sweepTurnSaves } from '../turn-job.js';
14
+ const END_LOCK_WAIT_MS = 1_000;
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, run.env))
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, false, '', {
26
+ waitMs: END_LOCK_WAIT_MS,
27
+ onTimeout: 'run',
28
+ });
29
+ let summary = result.summary;
30
+ if (!ctx.config.distill.enabled && ctx.config.capture.summarize === 'on') {
31
+ const path = payload.transcript_path ?? transcriptPathFor(project, sessionId);
32
+ const { turns } = readTranscript(path, 0);
33
+ const observations = observationsFromTurns(turns, sessionId, project, ctx.config);
34
+ const ai = await aiSummary(observations.map((obs) => `${obs.title}\n${obs.body}`).join('\n\n'), ctx.config.capture.summarizeModel);
35
+ if (ai)
36
+ summary = `AI: ${ai}`;
37
+ }
38
+ await ctx.store.upsertSession({
39
+ id: sessionId,
40
+ project,
41
+ startedAt: Date.now(),
42
+ endedAt: Date.now(),
43
+ ...(summary ? { summary } : {}),
44
+ });
45
+ clearPick(sessionId);
46
+ sweepPicks();
47
+ dropTurnSave(sessionId);
48
+ sweepTurnSaves();
49
+ clearActive(sessionId);
50
+ sweepActive();
51
+ const { distill } = ctx.config;
52
+ if (distill.enabled && !distillBlocked(distill.dailyLimit)) {
53
+ distillInBackground(project, sessionId);
54
+ }
55
+ if (ctx.config.updates !== 'off' && isDue(readState())) {
56
+ spawn(process.execPath, [CLI, 'update', '--quiet'], {
57
+ detached: true,
58
+ stdio: 'ignore',
59
+ }).unref();
60
+ }
61
+ });
62
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function sessionStart(run: HookRun): Promise<void>;