claude-db 0.12.4 → 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 (100) hide show
  1. package/CHANGELOG.md +37 -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 +19 -80
  8. package/dist/capture/index.d.ts +3 -3
  9. package/dist/capture/index.js +3 -3
  10. package/dist/capture/reingest.d.ts +1 -0
  11. package/dist/capture/reingest.js +4 -1
  12. package/dist/capture/scrub.d.ts +1 -0
  13. package/dist/capture/scrub.js +4 -1
  14. package/dist/capture/vectors.js +2 -1
  15. package/dist/cli/commands/daemon.d.ts +1 -0
  16. package/dist/cli/commands/daemon.js +29 -0
  17. package/dist/cli/commands/distill.js +2 -1
  18. package/dist/cli/commands/graph.js +2 -1
  19. package/dist/cli/commands/maintain.js +3 -1
  20. package/dist/cli/index.js +4 -0
  21. package/dist/cli/usage.js +1 -0
  22. package/dist/config/schema.d.ts +4 -0
  23. package/dist/config/schema.js +6 -0
  24. package/dist/context.d.ts +1 -0
  25. package/dist/context.js +21 -6
  26. package/dist/daemon/client.d.ts +12 -0
  27. package/dist/daemon/client.js +88 -0
  28. package/dist/daemon/paths.d.ts +16 -0
  29. package/dist/daemon/paths.js +19 -0
  30. package/dist/daemon/server.d.ts +2 -0
  31. package/dist/daemon/server.js +225 -0
  32. package/dist/facts/budget.d.ts +1 -0
  33. package/dist/facts/budget.js +4 -0
  34. package/dist/facts/claude-memory.js +1 -1
  35. package/dist/facts/distill.js +2 -2
  36. package/dist/facts/known.js +1 -1
  37. package/dist/facts/model.d.ts +1 -1
  38. package/dist/facts/model.js +18 -7
  39. package/dist/facts/start.js +1 -1
  40. package/dist/graph/query/refresh.js +5 -1
  41. package/dist/graph/scan/cache.d.ts +1 -0
  42. package/dist/graph/scan/cache.js +1 -1
  43. package/dist/graph/scan/persist.js +12 -16
  44. package/dist/hooks/compact.d.ts +2 -1
  45. package/dist/hooks/compact.js +2 -2
  46. package/dist/hooks/detached.d.ts +1 -0
  47. package/dist/hooks/detached.js +6 -0
  48. package/dist/hooks/graph-presence.d.ts +3 -0
  49. package/dist/hooks/graph-presence.js +42 -0
  50. package/dist/hooks/handlers/prefer-usages.d.ts +2 -0
  51. package/dist/hooks/handlers/prefer-usages.js +113 -0
  52. package/dist/hooks/handlers/session-end.d.ts +2 -0
  53. package/dist/hooks/handlers/session-end.js +62 -0
  54. package/dist/hooks/handlers/session-start.d.ts +2 -0
  55. package/dist/hooks/handlers/session-start.js +104 -0
  56. package/dist/hooks/handlers/turn-end.d.ts +2 -0
  57. package/dist/hooks/handlers/turn-end.js +31 -0
  58. package/dist/hooks/handlers/user-prompt.d.ts +2 -0
  59. package/dist/hooks/handlers/user-prompt.js +55 -0
  60. package/dist/hooks/local.d.ts +2 -0
  61. package/dist/hooks/local.js +23 -0
  62. package/dist/hooks/payload.d.ts +9 -4
  63. package/dist/hooks/payload.js +26 -17
  64. package/dist/hooks/prefer-usages.js +2 -118
  65. package/dist/hooks/route.d.ts +2 -0
  66. package/dist/hooks/route.js +28 -0
  67. package/dist/hooks/run.d.ts +14 -0
  68. package/dist/hooks/run.js +12 -0
  69. package/dist/hooks/save-turn.d.ts +2 -0
  70. package/dist/hooks/save-turn.js +11 -0
  71. package/dist/hooks/session-end.js +2 -63
  72. package/dist/hooks/session-start.js +2 -90
  73. package/dist/hooks/turn-end.js +2 -25
  74. package/dist/hooks/turn-save.js +10 -15
  75. package/dist/hooks/user-prompt.js +2 -58
  76. package/dist/search/service.d.ts +1 -0
  77. package/dist/search/service.js +16 -6
  78. package/dist/store/adapter.d.ts +7 -5
  79. package/dist/store/mongo/index.d.ts +3 -6
  80. package/dist/store/mongo/index.js +5 -0
  81. package/dist/store/mongo/observations.js +13 -1
  82. package/dist/store/postgres/driver.d.ts +10 -3
  83. package/dist/store/postgres/driver.js +12 -0
  84. package/dist/store/postgres/graph.d.ts +3 -5
  85. package/dist/store/postgres/graph.js +56 -50
  86. package/dist/store/postgres/index.d.ts +3 -6
  87. package/dist/store/postgres/index.js +5 -4
  88. package/dist/store/postgres/insert.js +98 -50
  89. package/dist/store/project-resolver.d.ts +3 -0
  90. package/dist/store/project-resolver.js +34 -23
  91. package/dist/store/scoped-store.js +1 -1
  92. package/dist/store/sqlite/graph.d.ts +3 -5
  93. package/dist/store/sqlite/graph.js +42 -33
  94. package/dist/store/sqlite/index.d.ts +3 -6
  95. package/dist/store/sqlite/index.js +3 -0
  96. package/dist/store/sqlite/observations.js +6 -2
  97. package/dist/util/job-lock.d.ts +1 -0
  98. package/dist/util/job-lock.js +50 -10
  99. package/docs/setup-guide.md +5 -0
  100. package/package.json +6 -6
@@ -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>;
@@ -0,0 +1,104 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { sweepCursorsDaily } from '../../capture/index.js';
6
+ import { distillNotice } from '../../facts/notice.js';
7
+ import { recentWorkBlock, startFacts } from '../../facts/start.js';
8
+ import { startBackgroundWork } from '../background.js';
9
+ import { noteGraphPresence } from '../graph-presence.js';
10
+ import { refreshGraphInBackground } from '../graph-refresh.js';
11
+ import { recoverAfterCompact } from '../compact.js';
12
+ import { capturingDisabled, emitSessionStart } from '../payload.js';
13
+ import { markShown } from '../shown.js';
14
+ import { legacyBlock } from '../start-legacy.js';
15
+ import { resolveProject } from '../../util/project.js';
16
+ import { mentionsPath } from '../../util/paths.js';
17
+ import { repoRootFor } from '../../usages/index.js';
18
+ import { refreshInstalled } from '../../cli/refresh.js';
19
+ import { updateNotice } from '../../update.js';
20
+ const SERVER = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', 'mcp', 'server.js');
21
+ const SCAN_HINT = 'Code graph not built yet — run `claude-db scan` once to enable ' +
22
+ 'find_usages and the symbol-grep hook.';
23
+ function refreshGraphQuietly(project) {
24
+ try {
25
+ refreshGraphInBackground(project, repoRootFor(project));
26
+ }
27
+ catch {
28
+ return;
29
+ }
30
+ }
31
+ function sweepCursorsQuietly() {
32
+ try {
33
+ sweepCursorsDaily();
34
+ }
35
+ catch {
36
+ return;
37
+ }
38
+ }
39
+ function refreshInstalledQuietly(project) {
40
+ try {
41
+ refreshInstalled(resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'), project);
42
+ }
43
+ catch {
44
+ return;
45
+ }
46
+ }
47
+ function isGitRepo(project) {
48
+ try {
49
+ repoRootFor(project);
50
+ return true;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
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
+ export default async function sessionStart(run) {
67
+ const { payload } = run;
68
+ const project = resolveProject(payload.cwd);
69
+ refreshInstalledQuietly(project);
70
+ await run.withContext(async (ctx) => {
71
+ const capturing = !capturingDisabled(ctx.config.capture.scripted, run.env);
72
+ if (capturing)
73
+ startBackgroundWork(project, ctx.config.database);
74
+ const earlier = payload.source === 'compact' && payload.session_id
75
+ ? await recoverAfterCompact(ctx, project, payload.session_id, payload.transcript_path, run.env)
76
+ : null;
77
+ 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
+ }
90
+ const scanned = (await ctx.store.scannedFiles(project, 1)).length > 0;
91
+ noteGraphPresence(project, scanned);
92
+ if (!scanned && isGitRepo(project))
93
+ parts.push(SCAN_HINT);
94
+ 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);
100
+ if (scanned)
101
+ refreshGraphQuietly(project);
102
+ sweepCursorsQuietly();
103
+ });
104
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function turnEnd(run: HookRun): Promise<void>;
@@ -0,0 +1,31 @@
1
+ import { activeToken } from '../../capture/active.js';
2
+ import { loadConfig } from '../../config/index.js';
3
+ import { resolveProject } from '../../util/project.js';
4
+ import { TURN_WORKER, runDetached } from '../detached.js';
5
+ import { capturingDisabled } from '../payload.js';
6
+ import { saveQueuedTurn } from '../save-turn.js';
7
+ import { queueTurnSave } from '../turn-job.js';
8
+ export default function turnEnd(run) {
9
+ if (!capturingDisabled(loadConfig().capture.scripted, run.env))
10
+ queue(run);
11
+ return Promise.resolve();
12
+ }
13
+ function queue(run) {
14
+ const { payload } = run;
15
+ const sessionId = payload.session_id;
16
+ if (!sessionId)
17
+ return;
18
+ const project = resolveProject(payload.cwd);
19
+ const tasks = Array.isArray(payload.background_tasks) ? payload.background_tasks : [];
20
+ const crons = Array.isArray(payload.session_crons) ? payload.session_crons : [];
21
+ const stillWorking = crons.length > 0 || tasks.some((task) => task?.status === 'running');
22
+ queueTurnSave(sessionId, {
23
+ project,
24
+ ...(payload.transcript_path ? { transcriptPath: payload.transcript_path } : {}),
25
+ finalReply: payload.last_assistant_message ?? '',
26
+ activeToken: stillWorking ? null : activeToken(sessionId),
27
+ });
28
+ if (run.inDaemon(() => saveQueuedTurn(sessionId, run.withContext)))
29
+ return;
30
+ runDetached(TURN_WORKER, [sessionId], project, () => { });
31
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookRun } from '../run.js';
2
+ export default function userPrompt(run: HookRun): Promise<void>;
@@ -0,0 +1,55 @@
1
+ import { recordActive } from '../../capture/active.js';
2
+ import { flushSession, redact } from '../../capture/index.js';
3
+ import { loadConfig } from '../../config/index.js';
4
+ import { clearPick, startPick } from '../../pick/pending.js';
5
+ import { takePick } from '../../pick/run.js';
6
+ import { resolveProject } from '../../util/project.js';
7
+ import { pickInBackground } from '../background.js';
8
+ import { capturingDisabled, emitContext } from '../payload.js';
9
+ import { promptCandidates, strictRecall, withCost } from '../prompt-recall.js';
10
+ import { markShown, readShown } from '../shown.js';
11
+ export default async function userPrompt(run) {
12
+ if (capturingDisabled(loadConfig().capture.scripted, run.env))
13
+ return;
14
+ const { payload } = run;
15
+ const sessionId = payload.session_id;
16
+ if (!sessionId)
17
+ return;
18
+ const project = resolveProject(payload.cwd);
19
+ await run.withContext(async (ctx) => {
20
+ const startedAt = Date.now();
21
+ recordActive(sessionId, project, payload.prompt ?? '');
22
+ const flushed = await flushSession(ctx, sessionId, project, payload.transcript_path, false, '', { onTimeout: 'skip' });
23
+ const { lastReply } = flushed;
24
+ if (flushed.observations === 0) {
25
+ await ctx.store.upsertSession({ id: sessionId, project, startedAt });
26
+ }
27
+ const candidates = await promptCandidates(ctx, {
28
+ prompt: payload.prompt ?? '',
29
+ project,
30
+ sessionId,
31
+ shown: readShown(sessionId),
32
+ });
33
+ if (!candidates) {
34
+ clearPick(sessionId);
35
+ return;
36
+ }
37
+ const fallback = await strictRecall(ctx, candidates);
38
+ if (takePick(ctx.config)) {
39
+ const token = startPick(sessionId, {
40
+ project,
41
+ prompt: redact(candidates.prompt),
42
+ previousReply: redact(lastReply),
43
+ ids: candidates.entries.map((entry) => entry.id),
44
+ fallback: fallback ? { text: withCost(fallback.block), ids: fallback.ids } : null,
45
+ });
46
+ pickInBackground(project, sessionId, token);
47
+ return;
48
+ }
49
+ clearPick(sessionId);
50
+ if (!fallback)
51
+ return;
52
+ markShown(sessionId, fallback.ids);
53
+ emitContext(withCost(fallback.block), run.write);
54
+ });
55
+ }
@@ -0,0 +1,2 @@
1
+ import type { HookName } from './run.js';
2
+ export declare function runLocally(name: HookName, raw: string): Promise<void>;
@@ -0,0 +1,23 @@
1
+ import { createContext } from '../context.js';
2
+ import { silenceSqliteWarning } from '../util/warnings.js';
3
+ import { parsePayload, writeStdout } from './payload.js';
4
+ import { loadHandler } from './run.js';
5
+ export async function runLocally(name, raw) {
6
+ silenceSqliteWarning();
7
+ const handle = await loadHandler(name);
8
+ await handle({
9
+ payload: parsePayload(raw),
10
+ env: process.env,
11
+ write: writeStdout,
12
+ async withContext(work) {
13
+ const ctx = await createContext();
14
+ try {
15
+ return await work(ctx);
16
+ }
17
+ finally {
18
+ await ctx.close();
19
+ }
20
+ },
21
+ inDaemon: () => false,
22
+ });
23
+ }
@@ -14,9 +14,14 @@ export interface HookPayload {
14
14
  }[];
15
15
  session_crons?: unknown[];
16
16
  }
17
- export declare function capturingDisabled(scripted: boolean): boolean;
17
+ export type HookEnv = Readonly<Record<string, string | undefined>>;
18
+ export type Write = (text: string) => void;
19
+ export declare const writeStdout: Write;
20
+ export declare function capturingDisabled(scripted: boolean, env?: HookEnv): boolean;
21
+ export declare function parsePayload(raw: string): HookPayload;
22
+ export declare function readStdin(): Promise<string>;
18
23
  export declare function readPayload(): Promise<HookPayload>;
19
24
  export declare function runHook(fn: () => Promise<void>): Promise<void>;
20
- export declare function emitContext(text: string): void;
21
- export declare function emitToolContext(text: string): void;
22
- export declare function emitSessionStart(context: string, notice: string | null): void;
25
+ export declare function emitContext(text: string, write?: Write): void;
26
+ export declare function emitToolContext(text: string, write?: Write): void;
27
+ export declare function emitSessionStart(context: string, notice: string | null, write?: Write): void;
@@ -1,23 +1,32 @@
1
1
  import { rememberClaudeBinary } from '../util/claude-binary.js';
2
- export function capturingDisabled(scripted) {
3
- if (process.env['CLAUDE_DB_CAPTURE'] === 'off')
2
+ export const writeStdout = (text) => {
3
+ process.stdout.write(text);
4
+ };
5
+ export function capturingDisabled(scripted, env = process.env) {
6
+ if (env['CLAUDE_DB_CAPTURE'] === 'off')
4
7
  return true;
5
- return process.env['CLAUDE_CODE_ENTRYPOINT'] === 'sdk-cli' && !scripted;
8
+ return env['CLAUDE_CODE_ENTRYPOINT'] === 'sdk-cli' && !scripted;
6
9
  }
7
- export async function readPayload() {
8
- const chunks = [];
9
- for await (const chunk of process.stdin)
10
- chunks.push(chunk);
11
- const raw = Buffer.concat(chunks).toString('utf8').trim();
12
- if (raw.length === 0)
10
+ export function parsePayload(raw) {
11
+ const text = raw.trim();
12
+ if (text.length === 0)
13
13
  return {};
14
14
  try {
15
- return JSON.parse(raw);
15
+ return JSON.parse(text);
16
16
  }
17
17
  catch {
18
18
  return {};
19
19
  }
20
20
  }
21
+ export async function readStdin() {
22
+ const chunks = [];
23
+ for await (const chunk of process.stdin)
24
+ chunks.push(chunk);
25
+ return Buffer.concat(chunks).toString('utf8');
26
+ }
27
+ export async function readPayload() {
28
+ return parsePayload(await readStdin());
29
+ }
21
30
  export async function runHook(fn) {
22
31
  try {
23
32
  rememberClaudeBinary();
@@ -28,23 +37,23 @@ export async function runHook(fn) {
28
37
  }
29
38
  process.exit(0);
30
39
  }
31
- export function emitContext(text) {
40
+ export function emitContext(text, write = writeStdout) {
32
41
  if (text.trim().length > 0)
33
- process.stdout.write(text);
42
+ write(text);
34
43
  }
35
- export function emitToolContext(text) {
44
+ export function emitToolContext(text, write = writeStdout) {
36
45
  if (text.trim().length === 0)
37
46
  return;
38
- process.stdout.write(JSON.stringify({
47
+ write(JSON.stringify({
39
48
  hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: text },
40
49
  }));
41
50
  }
42
- export function emitSessionStart(context, notice) {
51
+ export function emitSessionStart(context, notice, write = writeStdout) {
43
52
  if (!notice) {
44
- emitContext(context);
53
+ emitContext(context, write);
45
54
  return;
46
55
  }
47
- process.stdout.write(JSON.stringify({
56
+ write(JSON.stringify({
48
57
  systemMessage: notice,
49
58
  hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context },
50
59
  }));