claude-db 0.13.0 → 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 (105) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/capture/cursors.d.ts +1 -3
  3. package/dist/capture/cursors.js +16 -35
  4. package/dist/capture/flush.d.ts +1 -3
  5. package/dist/capture/flush.js +34 -34
  6. package/dist/capture/progress.js +4 -2
  7. package/dist/capture/transcript.d.ts +1 -1
  8. package/dist/capture/transcript.js +6 -6
  9. package/dist/catchup/gather.js +1 -1
  10. package/dist/cli/commands/catchup.js +2 -1
  11. package/dist/cli/commands/graph.js +9 -10
  12. package/dist/cli/commands/insight.js +10 -1
  13. package/dist/cli/commands/memory.js +2 -1
  14. package/dist/cli/commands/setup.js +1 -2
  15. package/dist/cli/commands/sync.js +4 -1
  16. package/dist/cli/install.js +1 -2
  17. package/dist/cli/instructions.d.ts +1 -3
  18. package/dist/cli/instructions.js +5 -40
  19. package/dist/cli/refresh.js +2 -6
  20. package/dist/config/load.js +2 -1
  21. package/dist/config/schema.d.ts +0 -2
  22. package/dist/config/schema.js +0 -2
  23. package/dist/context.js +16 -7
  24. package/dist/daemon/client.d.ts +5 -3
  25. package/dist/daemon/client.js +43 -25
  26. package/dist/daemon/paths.d.ts +3 -1
  27. package/dist/daemon/pid.d.ts +3 -0
  28. package/dist/daemon/pid.js +20 -0
  29. package/dist/daemon/server.js +9 -7
  30. package/dist/embed/local.js +4 -1
  31. package/dist/facts/claude-memory.js +2 -2
  32. package/dist/facts/last-chat.d.ts +1 -1
  33. package/dist/facts/last-chat.js +5 -4
  34. package/dist/facts/model.d.ts +1 -1
  35. package/dist/facts/model.js +20 -16
  36. package/dist/facts/start-render.d.ts +13 -0
  37. package/dist/facts/start-render.js +43 -0
  38. package/dist/facts/start.d.ts +3 -6
  39. package/dist/facts/start.js +32 -46
  40. package/dist/graph/grammars.js +2 -1
  41. package/dist/graph/index.d.ts +1 -1
  42. package/dist/graph/index.js +1 -1
  43. package/dist/graph/query/index.d.ts +1 -0
  44. package/dist/graph/query/index.js +1 -0
  45. package/dist/graph/query/stale.js +19 -2
  46. package/dist/graph/query/usages.d.ts +12 -0
  47. package/dist/graph/query/usages.js +37 -0
  48. package/dist/graph/scan/cache.js +2 -1
  49. package/dist/graph/scan/files.js +2 -2
  50. package/dist/hooks/compact.d.ts +1 -0
  51. package/dist/hooks/compact.js +3 -2
  52. package/dist/hooks/detached.d.ts +0 -1
  53. package/dist/hooks/detached.js +2 -6
  54. package/dist/hooks/grep-symbols.d.ts +3 -1
  55. package/dist/hooks/grep-symbols.js +41 -2
  56. package/dist/hooks/handlers/prefer-usages.js +15 -10
  57. package/dist/hooks/handlers/session-end.js +4 -6
  58. package/dist/hooks/handlers/session-start.js +19 -40
  59. package/dist/hooks/handlers/turn-end.js +1 -1
  60. package/dist/hooks/handlers/user-prompt.js +5 -5
  61. package/dist/hooks/local.js +0 -1
  62. package/dist/hooks/payload.js +6 -5
  63. package/dist/hooks/pick-deliver.js +2 -1
  64. package/dist/hooks/prompt-recall.d.ts +4 -2
  65. package/dist/hooks/prompt-recall.js +10 -10
  66. package/dist/hooks/route.js +8 -3
  67. package/dist/hooks/run.d.ts +1 -2
  68. package/dist/mcp/tools/ids.d.ts +3 -0
  69. package/dist/mcp/tools/ids.js +6 -0
  70. package/dist/mcp/tools/memory.js +2 -1
  71. package/dist/mcp/tools/observations.js +3 -2
  72. package/dist/mcp/tools/search.js +4 -9
  73. package/dist/mcp/tools/usages.js +18 -44
  74. package/dist/pick/worker.js +1 -2
  75. package/dist/search/service.d.ts +5 -0
  76. package/dist/search/service.js +11 -5
  77. package/dist/store/postgres/filters.d.ts +1 -0
  78. package/dist/store/postgres/filters.js +3 -0
  79. package/dist/store/postgres/graph.js +3 -2
  80. package/dist/store/postgres/index.js +3 -1
  81. package/dist/store/postgres/meta.d.ts +1 -0
  82. package/dist/store/postgres/meta.js +4 -0
  83. package/dist/store/postgres/observations.js +3 -3
  84. package/dist/store/project-resolver.d.ts +1 -0
  85. package/dist/store/project-resolver.js +1 -1
  86. package/dist/store/scoped-store.js +3 -1
  87. package/dist/store/sqlite/filters.d.ts +1 -0
  88. package/dist/store/sqlite/filters.js +6 -2
  89. package/dist/store/sqlite/graph.js +3 -2
  90. package/dist/store/sqlite/observations.js +6 -7
  91. package/dist/util/claude-binary.js +5 -4
  92. package/dist/util/claude-cli.js +2 -1
  93. package/dist/util/claude-dir.d.ts +2 -0
  94. package/dist/util/claude-dir.js +8 -0
  95. package/dist/util/env.d.ts +2 -0
  96. package/dist/util/env.js +6 -0
  97. package/dist/util/shortid.d.ts +3 -0
  98. package/dist/util/shortid.js +11 -0
  99. package/docs/how-it-works.md +5 -10
  100. package/docs/setup-guide.md +1 -1
  101. package/package.json +7 -6
  102. package/dist/capture/flush-lock.d.ts +0 -11
  103. package/dist/capture/flush-lock.js +0 -108
  104. package/dist/hooks/start-legacy.d.ts +0 -6
  105. package/dist/hooks/start-legacy.js +0 -47
@@ -1,3 +1,3 @@
1
1
  export { LANGUAGES, languageFor, languageNames } from './languages/index.js';
2
2
  export { SCAN_VERSION, currentHashes, hashOf, saveScan, scanRepository } from './scan/index.js';
3
- export { NO_GRAPH, NO_GRAPH_FOR_PATH, addText, answerQuery, formatGraph, formatText, hasGraph, nearest, queryGraph, refreshGraph, suggestFor, } from './query/index.js';
3
+ export { NO_GRAPH, NO_GRAPH_FOR_PATH, addText, answerQuery, formatGraph, formatText, hasGraph, nearest, queryGraph, refreshGraph, suggestFor, usagesAnswer, } from './query/index.js';
@@ -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';
@@ -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';
@@ -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
+ }
@@ -3,8 +3,9 @@ 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
+ export const cacheHome = () => hookEnv()['CLAUDE_DB_GRAPH_CACHE'] ?? join(CONFIG_DIR, 'graph-cache');
8
9
  export const cachePath = (project) => join(cacheHome(), `${scopeToken(project)}.json`);
9
10
  function receiverTable() {
10
11
  const list = [];
@@ -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);
@@ -4,6 +4,7 @@ import type { HookEnv } from './payload.js';
4
4
  export interface EarlierInChat {
5
5
  block: string;
6
6
  ids: ReadonlySet<string>;
7
+ titles: ReadonlySet<string>;
7
8
  }
8
9
  export declare function recoverAfterCompact(ctx: RecallContext, project: string, sessionId: string, transcriptPath: string | undefined, env?: HookEnv): Promise<EarlierInChat | null>;
9
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,7 +10,7 @@ const LABELS = {
9
10
  deadend: 'Dead end',
10
11
  preference: 'Rule',
11
12
  };
12
- export async function recoverAfterCompact(ctx, project, sessionId, transcriptPath, env = process.env) {
13
+ export async function recoverAfterCompact(ctx, project, sessionId, transcriptPath, env = hookEnv()) {
13
14
  forgetShown(sessionId);
14
15
  if (!capturingDisabled(ctx.config.capture.scripted, env)) {
15
16
  await flushSession(ctx, sessionId, project, transcriptPath);
@@ -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
  }
@@ -1,6 +1,5 @@
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;
5
4
  export declare const backgroundLog: () => string;
6
5
  export declare function runDetached(script: string, args: string[], cwd: string, release: () => void): void;
@@ -1,18 +1,14 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
1
  import { spawn } from 'node:child_process';
3
2
  import { appendFileSync, closeSync, mkdirSync, openSync, renameSync, statSync } from 'node:fs';
4
3
  import { basename, dirname, join, resolve } from 'node:path';
5
4
  import { fileURLToPath } from 'node:url';
6
5
  import { CONFIG_DIR } from '../config/dir.js';
6
+ import { hookEnv } from '../util/env.js';
7
7
  const DIST = resolve(dirname(fileURLToPath(import.meta.url)), '..');
8
8
  export const CLI = resolve(DIST, 'cli', 'index.js');
9
9
  export const PICK_WORKER = resolve(DIST, 'pick', 'worker.js');
10
10
  export const TURN_WORKER = resolve(DIST, 'hooks', 'turn-save.js');
11
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
- }
16
12
  export const backgroundLog = () => join(CONFIG_DIR, 'logs', 'background.log');
17
13
  function rotate(path) {
18
14
  try {
@@ -41,7 +37,7 @@ export function runDetached(script, args, cwd, release) {
41
37
  try {
42
38
  spawn(process.execPath, [script, ...args], {
43
39
  cwd,
44
- env: workerEnvs.getStore() ?? process.env,
40
+ env: hookEnv(),
45
41
  detached: true,
46
42
  stdio: ['ignore', log, log],
47
43
  })
@@ -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);
@@ -2,22 +2,30 @@ import { addText, answerQuery, formatGraph, formatText } from '../../graph/index
2
2
  import { hasGraph } from '../../graph/query/answer.js';
3
3
  import { staleFiles } from '../../graph/query/stale.js';
4
4
  import { repoRootFor } from '../../usages/index.js';
5
- import { DECLARED, isSymbol, isWord, symbolsGreppedIn } from '../grep-symbols.js';
5
+ import { DECLARED, isSymbol, isWord, repoDirectory, symbolsGreppedIn } from '../grep-symbols.js';
6
6
  import { graphCachedHere, graphKnownAbsent, noteGraphPresence } from '../graph-presence.js';
7
7
  import { refreshGraphInBackground } from '../graph-refresh.js';
8
8
  import { resolveProject } from '../../util/project.js';
9
+ import { hookEnv } from '../../util/env.js';
9
10
  const MAX_SYMBOLS = 2;
10
11
  const MAX_LINES = 14;
11
12
  const TEXT_LINES = 6;
12
13
  const EDGE_LIMIT = 20;
13
- function requested(payload) {
14
+ function requested(payload, project) {
14
15
  const input = payload.tool_input ?? {};
16
+ const inRepo = repoDirectory(payload.cwd ?? project, project);
15
17
  if (payload.tool_name === 'Grep') {
16
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 [];
17
24
  return isSymbol(pattern) || isWord(pattern) ? [pattern] : [];
18
25
  }
19
26
  if (payload.tool_name === 'Bash') {
20
- return symbolsGreppedIn(typeof input['command'] === 'string' ? input['command'] : '');
27
+ const command = typeof input['command'] === 'string' ? input['command'] : '';
28
+ return symbolsGreppedIn(command, inRepo);
21
29
  }
22
30
  return [];
23
31
  }
@@ -75,14 +83,14 @@ async function answerSymbols(ctx, project, symbols) {
75
83
  return answered;
76
84
  }
77
85
  export default async function preferUsages(run) {
78
- const mode = run.env['CLAUDE_DB_USAGES_HOOK'] ?? 'deny';
86
+ const mode = hookEnv()['CLAUDE_DB_USAGES_HOOK'] ?? 'directive';
79
87
  if (mode === 'off')
80
88
  return;
81
89
  const { payload } = run;
82
- const symbols = requested(payload).slice(0, MAX_SYMBOLS);
90
+ const project = resolveProject(payload.cwd);
91
+ const symbols = requested(payload, project).slice(0, MAX_SYMBOLS);
83
92
  if (symbols.length === 0)
84
93
  return;
85
- const project = resolveProject(payload.cwd);
86
94
  if (graphKnownAbsent(project))
87
95
  return;
88
96
  const { named, blocks } = await run.withContext((ctx) => answerSymbols(ctx, project, symbols));
@@ -93,10 +101,7 @@ export default async function preferUsages(run) {
93
101
  run.write(JSON.stringify({
94
102
  hookSpecificOutput: {
95
103
  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')}`,
104
+ additionalContext: `Code graph answer for ${names} (the grep still runs):\n\n${blocks.join('\n\n')}`,
100
105
  },
101
106
  }));
102
107
  return;
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { dirname, resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { hookEnv } from '../../util/env.js';
4
5
  import { clearActive, sweepActive } from '../../capture/active.js';
5
6
  import { aiSummary, flushSession, observationsFromTurns, readTranscript, transcriptPathFor, } from '../../capture/index.js';
6
7
  import { loadConfig } from '../../config/index.js';
@@ -11,10 +12,9 @@ import { resolveProject } from '../../util/project.js';
11
12
  import { distillInBackground } from '../background.js';
12
13
  import { capturingDisabled } from '../payload.js';
13
14
  import { dropTurnSave, sweepTurnSaves } from '../turn-job.js';
14
- const END_LOCK_WAIT_MS = 1_000;
15
15
  const CLI = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', 'cli', 'index.js');
16
16
  export default async function sessionEnd(run) {
17
- if (capturingDisabled(loadConfig().capture.scripted, run.env))
17
+ if (capturingDisabled(loadConfig().capture.scripted))
18
18
  return;
19
19
  const { payload } = run;
20
20
  const sessionId = payload.session_id;
@@ -22,10 +22,7 @@ export default async function sessionEnd(run) {
22
22
  return;
23
23
  const project = resolveProject(payload.cwd);
24
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
- });
25
+ const result = await flushSession(ctx, sessionId, project, payload.transcript_path);
29
26
  let summary = result.summary;
30
27
  if (!ctx.config.distill.enabled && ctx.config.capture.summarize === 'on') {
31
28
  const path = payload.transcript_path ?? transcriptPathFor(project, sessionId);
@@ -54,6 +51,7 @@ export default async function sessionEnd(run) {
54
51
  }
55
52
  if (ctx.config.updates !== 'off' && isDue(readState())) {
56
53
  spawn(process.execPath, [CLI, 'update', '--quiet'], {
54
+ env: hookEnv(),
57
55
  detached: true,
58
56
  stdio: 'ignore',
59
57
  }).unref();
@@ -1,23 +1,19 @@
1
- import { readFileSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { dirname, join, resolve } from 'node:path';
1
+ import { dirname, resolve } from 'node:path';
4
2
  import { fileURLToPath } from 'node:url';
5
3
  import { sweepCursorsDaily } from '../../capture/index.js';
4
+ import { loadConfig } from '../../config/index.js';
6
5
  import { distillNotice } from '../../facts/notice.js';
7
- import { recentWorkBlock, startFacts } from '../../facts/start.js';
6
+ import { startFacts } from '../../facts/start.js';
8
7
  import { startBackgroundWork } from '../background.js';
9
8
  import { noteGraphPresence } from '../graph-presence.js';
10
9
  import { refreshGraphInBackground } from '../graph-refresh.js';
11
10
  import { recoverAfterCompact } from '../compact.js';
12
11
  import { capturingDisabled, emitSessionStart } from '../payload.js';
13
12
  import { markShown } from '../shown.js';
14
- import { legacyBlock } from '../start-legacy.js';
15
13
  import { resolveProject } from '../../util/project.js';
16
- import { mentionsPath } from '../../util/paths.js';
17
14
  import { repoRootFor } from '../../usages/index.js';
18
15
  import { refreshInstalled } from '../../cli/refresh.js';
19
16
  import { updateNotice } from '../../update.js';
20
- const SERVER = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', 'mcp', 'server.js');
21
17
  const SCAN_HINT = 'Code graph not built yet — run `claude-db scan` once to enable ' +
22
18
  'find_usages and the symbol-grep hook.';
23
19
  function refreshGraphQuietly(project) {
@@ -53,50 +49,33 @@ function isGitRepo(project) {
53
49
  return false;
54
50
  }
55
51
  }
56
- function mcpRegistered(project) {
57
- return [join(project, '.mcp.json'), join(homedir(), '.claude.json')].some((path) => {
58
- try {
59
- return mentionsPath(readFileSync(path, 'utf8'), SERVER);
60
- }
61
- catch {
62
- return false;
63
- }
64
- });
65
- }
66
52
  export default async function sessionStart(run) {
67
53
  const { payload } = run;
68
54
  const project = resolveProject(payload.cwd);
69
55
  refreshInstalledQuietly(project);
56
+ if (capturingDisabled(loadConfig().capture.scripted))
57
+ return;
70
58
  await run.withContext(async (ctx) => {
71
- const capturing = !capturingDisabled(ctx.config.capture.scripted, run.env);
72
- if (capturing)
73
- startBackgroundWork(project, ctx.config.database);
59
+ startBackgroundWork(project, ctx.config.database);
74
60
  const earlier = payload.source === 'compact' && payload.session_id
75
- ? await recoverAfterCompact(ctx, project, payload.session_id, payload.transcript_path, run.env)
61
+ ? await recoverAfterCompact(ctx, project, payload.session_id, payload.transcript_path)
76
62
  : null;
77
63
  const restored = earlier?.ids ?? new Set();
78
- const facts = await startFacts(ctx, project, restored, payload.session_id);
79
- const recent = facts ? null : await recentWorkBlock(ctx, project, payload.session_id, restored);
80
- const legacy = facts ? null : await legacyBlock(ctx, project, restored);
81
- const shown = [...(facts?.ids ?? []), ...(recent?.ids ?? [])];
82
- if (shown.length > 0 && payload.session_id)
83
- markShown(payload.session_id, shown);
84
- const fallback = legacy?.hasMemory || !recent ? legacy?.text : undefined;
85
- const parts = [earlier?.block, facts?.block ?? fallback, recent?.block].filter((part) => Boolean(part));
86
- if ((facts || recent || legacy?.hasMemory) && mcpRegistered(project)) {
87
- parts.push("Search this project's full history with the memory MCP tools before " +
88
- 'asking the user to re-explain prior decisions.');
89
- }
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]);
90
67
  const scanned = (await ctx.store.scannedFiles(project, 1)).length > 0;
91
68
  noteGraphPresence(project, scanned);
92
- if (!scanned && isGitRepo(project))
93
- parts.push(SCAN_HINT);
94
69
  const update = ctx.config.updates === 'off' ? null : updateNotice();
95
- if (update)
96
- parts.push(update);
97
- const body = parts.join('\n');
98
- const notice = capturing ? await distillNotice(ctx, project) : null;
99
- emitSessionStart(`${body}\n(context ≈ ${Math.round(body.length / 4)} tokens)\n`, notice, run.write);
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);
100
79
  if (scanned)
101
80
  refreshGraphQuietly(project);
102
81
  sweepCursorsQuietly();
@@ -6,7 +6,7 @@ import { capturingDisabled } from '../payload.js';
6
6
  import { saveQueuedTurn } from '../save-turn.js';
7
7
  import { queueTurnSave } from '../turn-job.js';
8
8
  export default function turnEnd(run) {
9
- if (!capturingDisabled(loadConfig().capture.scripted, run.env))
9
+ if (!capturingDisabled(loadConfig().capture.scripted))
10
10
  queue(run);
11
11
  return Promise.resolve();
12
12
  }
@@ -6,10 +6,10 @@ import { takePick } from '../../pick/run.js';
6
6
  import { resolveProject } from '../../util/project.js';
7
7
  import { pickInBackground } from '../background.js';
8
8
  import { capturingDisabled, emitContext } from '../payload.js';
9
- import { promptCandidates, strictRecall, withCost } from '../prompt-recall.js';
9
+ import { promptCandidates, strictRecall } from '../prompt-recall.js';
10
10
  import { markShown, readShown } from '../shown.js';
11
11
  export default async function userPrompt(run) {
12
- if (capturingDisabled(loadConfig().capture.scripted, run.env))
12
+ if (capturingDisabled(loadConfig().capture.scripted))
13
13
  return;
14
14
  const { payload } = run;
15
15
  const sessionId = payload.session_id;
@@ -19,7 +19,7 @@ export default async function userPrompt(run) {
19
19
  await run.withContext(async (ctx) => {
20
20
  const startedAt = Date.now();
21
21
  recordActive(sessionId, project, payload.prompt ?? '');
22
- const flushed = await flushSession(ctx, sessionId, project, payload.transcript_path, false, '', { onTimeout: 'skip' });
22
+ const flushed = await flushSession(ctx, sessionId, project, payload.transcript_path);
23
23
  const { lastReply } = flushed;
24
24
  if (flushed.observations === 0) {
25
25
  await ctx.store.upsertSession({ id: sessionId, project, startedAt });
@@ -41,7 +41,7 @@ export default async function userPrompt(run) {
41
41
  prompt: redact(candidates.prompt),
42
42
  previousReply: redact(lastReply),
43
43
  ids: candidates.entries.map((entry) => entry.id),
44
- fallback: fallback ? { text: withCost(fallback.block), ids: fallback.ids } : null,
44
+ fallback: fallback ? { text: `${fallback.block}\n`, ids: fallback.ids } : null,
45
45
  });
46
46
  pickInBackground(project, sessionId, token);
47
47
  return;
@@ -50,6 +50,6 @@ export default async function userPrompt(run) {
50
50
  if (!fallback)
51
51
  return;
52
52
  markShown(sessionId, fallback.ids);
53
- emitContext(withCost(fallback.block), run.write);
53
+ emitContext(`${fallback.block}\n`, run.write);
54
54
  });
55
55
  }
@@ -7,7 +7,6 @@ export async function runLocally(name, raw) {
7
7
  const handle = await loadHandler(name);
8
8
  await handle({
9
9
  payload: parsePayload(raw),
10
- env: process.env,
11
10
  write: writeStdout,
12
11
  async withContext(work) {
13
12
  const ctx = await createContext();
@@ -1,8 +1,9 @@
1
1
  import { rememberClaudeBinary } from '../util/claude-binary.js';
2
+ import { hookEnv } from '../util/env.js';
2
3
  export const writeStdout = (text) => {
3
4
  process.stdout.write(text);
4
5
  };
5
- export function capturingDisabled(scripted, env = process.env) {
6
+ export function capturingDisabled(scripted, env = hookEnv()) {
6
7
  if (env['CLAUDE_DB_CAPTURE'] === 'off')
7
8
  return true;
8
9
  return env['CLAUDE_CODE_ENTRYPOINT'] === 'sdk-cli' && !scripted;
@@ -53,8 +54,8 @@ export function emitSessionStart(context, notice, write = writeStdout) {
53
54
  emitContext(context, write);
54
55
  return;
55
56
  }
56
- write(JSON.stringify({
57
- systemMessage: notice,
58
- hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context },
59
- }));
57
+ const claudeSees = context.trim().length > 0
58
+ ? { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context } }
59
+ : {};
60
+ write(JSON.stringify({ systemMessage: notice, ...claudeSees }));
60
61
  }
@@ -2,8 +2,9 @@
2
2
  import { takeReady } from '../pick/pending.js';
3
3
  import { emitToolContext, readPayload, runHook } from './payload.js';
4
4
  import { markShown } from './shown.js';
5
+ import { hookEnv } from '../util/env.js';
5
6
  await runHook(async () => {
6
- if (process.env['CLAUDE_DB_CAPTURE'] === 'off')
7
+ if (hookEnv()['CLAUDE_DB_CAPTURE'] === 'off')
7
8
  return;
8
9
  const sessionId = (await readPayload()).session_id;
9
10
  if (!sessionId)
@@ -1,5 +1,5 @@
1
1
  import type { RecallContext } from '../context.js';
2
- import type { ObservationIndexEntry } from '../types.js';
2
+ import type { ObservationIndexEntry, SearchQuery } from '../types.js';
3
3
  export declare const PICK_POOL = 10;
4
4
  export interface PromptRecallRequest {
5
5
  prompt: string;
@@ -16,6 +16,8 @@ export interface PromptRecall {
16
16
  block: string;
17
17
  ids: string[];
18
18
  }
19
+ type QueryScope = Pick<PromptRecallRequest, 'project' | 'sessionId' | 'until'>;
20
+ export declare function recallQuery(prompt: string, scope: QueryScope): SearchQuery;
19
21
  export declare function promptCandidates(ctx: RecallContext, request: PromptRecallRequest): Promise<PromptCandidates | null>;
20
22
  export declare function strictRecall(ctx: RecallContext, candidates: PromptCandidates): Promise<PromptRecall | null>;
21
- export declare function withCost(block: string): string;
23
+ export {};
@@ -3,18 +3,21 @@ import { isSearchable, typedPrompt } from '../util/prompt.js';
3
3
  import { clearsOverlap, renderPromptContext } from './relevance.js';
4
4
  export const PICK_POOL = 10;
5
5
  const STRICT_OVERLAP = 4;
6
+ export function recallQuery(prompt, scope) {
7
+ return {
8
+ text: prompt,
9
+ project: scope.project,
10
+ excludeSessions: [scope.sessionId, FACT_SESSION],
11
+ limit: PICK_POOL,
12
+ ...(scope.until !== undefined ? { until: scope.until } : {}),
13
+ };
14
+ }
6
15
  export async function promptCandidates(ctx, request) {
7
16
  const { inject } = ctx.config;
8
17
  const prompt = typedPrompt(request.prompt);
9
18
  if (!inject.perPrompt || prompt === null || !isSearchable(prompt))
10
19
  return null;
11
- const found = await ctx.search.search({
12
- text: prompt,
13
- project: request.project,
14
- excludeSessions: [request.sessionId, FACT_SESSION],
15
- limit: PICK_POOL,
16
- ...(request.until !== undefined ? { until: request.until } : {}),
17
- });
20
+ const found = await ctx.search.search(recallQuery(prompt, request));
18
21
  const entries = found.filter((entry) => !request.shown.has(entry.id));
19
22
  if (!entries.some((entry) => clearsOverlap(prompt, entry, inject.minOverlap)))
20
23
  return null;
@@ -31,6 +34,3 @@ export async function strictRecall(ctx, candidates) {
31
34
  const block = renderPromptContext([top], inject.promptMaxChars, expanded, inject.expandMaxChars, ids);
32
35
  return block ? { block, ids } : null;
33
36
  }
34
- export function withCost(block) {
35
- return `${block}\n(context ≈ ${Math.round(block.length / 4)} tokens)\n`;
36
- }