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.
- package/CHANGELOG.md +57 -0
- package/dist/capture/cursors.d.ts +8 -0
- package/dist/capture/cursors.js +99 -0
- package/dist/capture/flush-lock.d.ts +11 -0
- package/dist/capture/flush-lock.js +108 -0
- package/dist/capture/flush.d.ts +4 -4
- package/dist/capture/flush.js +27 -60
- package/dist/capture/index.d.ts +3 -3
- package/dist/capture/index.js +3 -3
- package/dist/capture/progress.js +8 -1
- package/dist/capture/reingest.d.ts +1 -0
- package/dist/capture/reingest.js +4 -1
- package/dist/capture/scrub.d.ts +1 -0
- package/dist/capture/scrub.js +4 -1
- package/dist/capture/vectors.js +2 -1
- package/dist/catchup/gather.js +1 -0
- package/dist/cli/commands/daemon.d.ts +1 -0
- package/dist/cli/commands/daemon.js +29 -0
- package/dist/cli/commands/distill.js +2 -1
- package/dist/cli/commands/graph.js +2 -1
- package/dist/cli/commands/maintain.js +3 -1
- package/dist/cli/commands/sync.js +5 -4
- package/dist/cli/commands/transfer.js +4 -3
- package/dist/cli/index.js +4 -0
- package/dist/cli/usage.js +1 -0
- package/dist/config/schema.d.ts +4 -0
- package/dist/config/schema.js +6 -0
- package/dist/context.d.ts +1 -0
- package/dist/context.js +21 -6
- package/dist/daemon/client.d.ts +12 -0
- package/dist/daemon/client.js +88 -0
- package/dist/daemon/paths.d.ts +16 -0
- package/dist/daemon/paths.js +19 -0
- package/dist/daemon/server.d.ts +2 -0
- package/dist/daemon/server.js +225 -0
- package/dist/facts/budget.d.ts +1 -0
- package/dist/facts/budget.js +4 -0
- package/dist/facts/claude-memory.js +7 -2
- package/dist/facts/distill.js +6 -3
- package/dist/facts/handoff.js +6 -1
- package/dist/facts/known.js +3 -1
- package/dist/facts/model.d.ts +1 -1
- package/dist/facts/model.js +18 -7
- package/dist/facts/start.js +2 -2
- package/dist/graph/query/answer.js +1 -1
- package/dist/graph/query/path.js +69 -37
- package/dist/graph/query/refresh.js +5 -1
- package/dist/graph/query/suggest.js +1 -2
- package/dist/graph/scan/cache.d.ts +1 -0
- package/dist/graph/scan/cache.js +1 -1
- package/dist/graph/scan/persist.js +12 -16
- package/dist/hooks/compact.d.ts +2 -1
- package/dist/hooks/compact.js +9 -3
- package/dist/hooks/detached.d.ts +1 -0
- package/dist/hooks/detached.js +6 -0
- package/dist/hooks/graph-presence.d.ts +3 -0
- package/dist/hooks/graph-presence.js +42 -0
- package/dist/hooks/handlers/prefer-usages.d.ts +2 -0
- package/dist/hooks/handlers/prefer-usages.js +113 -0
- package/dist/hooks/handlers/session-end.d.ts +2 -0
- package/dist/hooks/handlers/session-end.js +62 -0
- package/dist/hooks/handlers/session-start.d.ts +2 -0
- package/dist/hooks/handlers/session-start.js +104 -0
- package/dist/hooks/handlers/turn-end.d.ts +2 -0
- package/dist/hooks/handlers/turn-end.js +31 -0
- package/dist/hooks/handlers/user-prompt.d.ts +2 -0
- package/dist/hooks/handlers/user-prompt.js +55 -0
- package/dist/hooks/local.d.ts +2 -0
- package/dist/hooks/local.js +23 -0
- package/dist/hooks/payload.d.ts +9 -4
- package/dist/hooks/payload.js +26 -17
- package/dist/hooks/prefer-usages.js +2 -118
- package/dist/hooks/route.d.ts +2 -0
- package/dist/hooks/route.js +28 -0
- package/dist/hooks/run.d.ts +14 -0
- package/dist/hooks/run.js +12 -0
- package/dist/hooks/save-turn.d.ts +2 -0
- package/dist/hooks/save-turn.js +11 -0
- package/dist/hooks/session-end.js +2 -63
- package/dist/hooks/session-start.js +2 -90
- package/dist/hooks/start-legacy.js +1 -1
- package/dist/hooks/turn-end.js +2 -25
- package/dist/hooks/turn-save.js +10 -15
- package/dist/hooks/user-prompt.js +2 -58
- package/dist/search/service.d.ts +1 -0
- package/dist/search/service.js +16 -6
- package/dist/store/adapter.d.ts +11 -7
- package/dist/store/each.d.ts +2 -4
- package/dist/store/each.js +1 -0
- package/dist/store/mongo/graph.d.ts +2 -1
- package/dist/store/mongo/graph.js +17 -2
- package/dist/store/mongo/index.d.ts +7 -8
- package/dist/store/mongo/index.js +13 -2
- package/dist/store/mongo/observations.d.ts +2 -1
- package/dist/store/mongo/observations.js +38 -4
- package/dist/store/postgres/driver.d.ts +10 -3
- package/dist/store/postgres/driver.js +12 -0
- package/dist/store/postgres/graph.d.ts +5 -6
- package/dist/store/postgres/graph.js +78 -57
- package/dist/store/postgres/index.d.ts +7 -8
- package/dist/store/postgres/index.js +16 -11
- package/dist/store/postgres/insert.js +98 -48
- package/dist/store/postgres/meta.d.ts +1 -0
- package/dist/store/postgres/meta.js +4 -0
- package/dist/store/postgres/observations.d.ts +3 -2
- package/dist/store/postgres/observations.js +40 -6
- package/dist/store/postgres/rows.js +1 -1
- package/dist/store/project-resolver.d.ts +3 -0
- package/dist/store/project-resolver.js +34 -23
- package/dist/store/scoped-store.js +5 -1
- package/dist/store/sqlite/graph.d.ts +5 -6
- package/dist/store/sqlite/graph.js +61 -35
- package/dist/store/sqlite/index.d.ts +7 -8
- package/dist/store/sqlite/index.js +11 -2
- package/dist/store/sqlite/observations.d.ts +2 -1
- package/dist/store/sqlite/observations.js +38 -7
- package/dist/types.d.ts +9 -0
- package/dist/util/job-lock.d.ts +1 -0
- package/dist/util/job-lock.js +50 -10
- package/docs/setup-guide.md +5 -0
- package/package.json +6 -8
|
@@ -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,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,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,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
|
+
}
|
package/dist/hooks/payload.d.ts
CHANGED
|
@@ -14,9 +14,14 @@ export interface HookPayload {
|
|
|
14
14
|
}[];
|
|
15
15
|
session_crons?: unknown[];
|
|
16
16
|
}
|
|
17
|
-
export
|
|
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;
|
package/dist/hooks/payload.js
CHANGED
|
@@ -1,23 +1,32 @@
|
|
|
1
1
|
import { rememberClaudeBinary } from '../util/claude-binary.js';
|
|
2
|
-
export
|
|
3
|
-
|
|
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
|
|
8
|
+
return env['CLAUDE_CODE_ENTRYPOINT'] === 'sdk-cli' && !scripted;
|
|
6
9
|
}
|
|
7
|
-
export
|
|
8
|
-
const
|
|
9
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
56
|
+
write(JSON.stringify({
|
|
48
57
|
systemMessage: notice,
|
|
49
58
|
hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context },
|
|
50
59
|
}));
|
|
@@ -1,119 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { staleFiles } from '../graph/query/stale.js';
|
|
5
|
-
import { repoRootFor } from '../usages/index.js';
|
|
6
|
-
import { DECLARED, isSymbol, isWord, symbolsGreppedIn } from './grep-symbols.js';
|
|
7
|
-
import { refreshGraphInBackground } from './graph-refresh.js';
|
|
8
|
-
import { readPayload, runHook } from './payload.js';
|
|
9
|
-
import { resolveProject } from '../util/project.js';
|
|
10
|
-
import { silenceSqliteWarning } from '../util/warnings.js';
|
|
11
|
-
silenceSqliteWarning();
|
|
12
|
-
const MAX_SYMBOLS = 2;
|
|
13
|
-
const MAX_LINES = 14;
|
|
14
|
-
const TEXT_LINES = 6;
|
|
15
|
-
const EDGE_LIMIT = 20;
|
|
16
|
-
function requested(payload) {
|
|
17
|
-
const input = payload.tool_input ?? {};
|
|
18
|
-
if (payload.tool_name === 'Grep') {
|
|
19
|
-
const pattern = typeof input['pattern'] === 'string' ? input['pattern'] : '';
|
|
20
|
-
return isSymbol(pattern) || isWord(pattern) ? [pattern] : [];
|
|
21
|
-
}
|
|
22
|
-
if (payload.tool_name === 'Bash') {
|
|
23
|
-
return symbolsGreppedIn(typeof input['command'] === 'string' ? input['command'] : '');
|
|
24
|
-
}
|
|
25
|
-
return [];
|
|
26
|
-
}
|
|
27
|
-
function trim(answer) {
|
|
28
|
-
const lines = answer.split('\n');
|
|
29
|
-
if (lines.length <= MAX_LINES)
|
|
30
|
-
return answer;
|
|
31
|
-
return [...lines.slice(0, MAX_LINES), ` ... more via find_usages`].join('\n');
|
|
32
|
-
}
|
|
33
|
-
const answers = (answer, symbol) => !answer.empty && (isSymbol(symbol) || answer.definitions.some((d) => DECLARED.has(d.kind)));
|
|
34
|
-
function block(answer, root) {
|
|
35
|
-
const graph = trim(formatGraph(answer, root, { text: false }));
|
|
36
|
-
return [graph, ...formatText(answer.text, TEXT_LINES)].join('\n');
|
|
37
|
-
}
|
|
38
|
-
const staleNote = (count) => `(${count} file(s) changed since the last scan and are being re-read in the background, ` +
|
|
39
|
-
'so lines in them may have moved. The text matches are live.)';
|
|
40
|
-
async function freshnessNote(store, project) {
|
|
41
|
-
try {
|
|
42
|
-
const root = repoRootFor(project);
|
|
43
|
-
const stale = staleFiles(root, await store.scannedFiles(project));
|
|
44
|
-
if (stale.length === 0)
|
|
45
|
-
return null;
|
|
46
|
-
refreshGraphInBackground(project, root);
|
|
47
|
-
return staleNote(stale.length);
|
|
48
|
-
}
|
|
49
|
-
catch {
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
async function answerSymbols(ctx, project, symbols) {
|
|
54
|
-
const answered = { named: [], blocks: [] };
|
|
55
|
-
for (const symbol of symbols) {
|
|
56
|
-
const answer = await answerQuery({
|
|
57
|
-
store: ctx.store,
|
|
58
|
-
root: project,
|
|
59
|
-
project,
|
|
60
|
-
query: { mode: 'usages', symbol, limit: EDGE_LIMIT, suggest: false },
|
|
61
|
-
refresh: false,
|
|
62
|
-
text: false,
|
|
63
|
-
});
|
|
64
|
-
if (!answers(answer, symbol))
|
|
65
|
-
continue;
|
|
66
|
-
addText(answer, project);
|
|
67
|
-
answered.named.push(symbol);
|
|
68
|
-
answered.blocks.push(block(answer, project));
|
|
69
|
-
}
|
|
70
|
-
if (answered.blocks.length > 0) {
|
|
71
|
-
const note = await freshnessNote(ctx.store, project);
|
|
72
|
-
if (note)
|
|
73
|
-
answered.blocks.push(note);
|
|
74
|
-
}
|
|
75
|
-
return answered;
|
|
76
|
-
}
|
|
77
|
-
await runHook(async () => {
|
|
78
|
-
const mode = process.env['CLAUDE_DB_USAGES_HOOK'] ?? 'deny';
|
|
79
|
-
if (mode === 'off')
|
|
80
|
-
return;
|
|
81
|
-
const payload = await readPayload();
|
|
82
|
-
const symbols = requested(payload).slice(0, MAX_SYMBOLS);
|
|
83
|
-
if (symbols.length === 0)
|
|
84
|
-
return;
|
|
85
|
-
const project = resolveProject(payload.cwd);
|
|
86
|
-
const ctx = await createContext();
|
|
87
|
-
let answered;
|
|
88
|
-
try {
|
|
89
|
-
answered = await answerSymbols(ctx, project, symbols);
|
|
90
|
-
}
|
|
91
|
-
finally {
|
|
92
|
-
await ctx.close();
|
|
93
|
-
}
|
|
94
|
-
const { named, blocks } = answered;
|
|
95
|
-
if (blocks.length === 0)
|
|
96
|
-
return;
|
|
97
|
-
const names = named.map((s) => `\`${s}\``).join(', ');
|
|
98
|
-
if (mode === 'directive') {
|
|
99
|
-
process.stdout.write(JSON.stringify({
|
|
100
|
-
hookSpecificOutput: {
|
|
101
|
-
hookEventName: 'PreToolUse',
|
|
102
|
-
additionalContext: `You are grepping the declared symbol(s) ${names}. Use the \`find_usages\` MCP ` +
|
|
103
|
-
`tool for symbol lookups — grep cannot tell a call from an import or show the ` +
|
|
104
|
-
`blast radius. The graph's answer for this search is below; read it instead of ` +
|
|
105
|
-
`the grep output, and call find_usages directly next time:\n\n${blocks.join('\n\n')}`,
|
|
106
|
-
},
|
|
107
|
-
}));
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
process.stdout.write(JSON.stringify({
|
|
111
|
-
hookSpecificOutput: {
|
|
112
|
-
hookEventName: 'PreToolUse',
|
|
113
|
-
permissionDecision: 'deny',
|
|
114
|
-
permissionDecisionReason: `Blocked: ${names} names a declared symbol — use the \`find_usages\` MCP tool ` +
|
|
115
|
-
`for symbol lookups, not grep. Its answer for this search is already below, so ` +
|
|
116
|
-
`nothing needs re-running:\n\n${blocks.join('\n\n')}`,
|
|
117
|
-
},
|
|
118
|
-
}));
|
|
119
|
-
});
|
|
2
|
+
import { routeHook } from './route.js';
|
|
3
|
+
await routeHook('prefer-usages');
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { askDaemon, daemonWanted, forwardedEnv, startDaemon, workerEnv } from '../daemon/client.js';
|
|
2
|
+
import { buildId } from '../daemon/paths.js';
|
|
3
|
+
import { readStdin, runHook } from './payload.js';
|
|
4
|
+
const WAIT_MS = { 'prefer-usages': 8_000 };
|
|
5
|
+
const DEFAULT_WAIT_MS = 50_000;
|
|
6
|
+
async function viaDaemon(name, raw) {
|
|
7
|
+
if (!daemonWanted())
|
|
8
|
+
return false;
|
|
9
|
+
const asked = await askDaemon({ build: buildId(), hook: name, raw, env: forwardedEnv(), workerEnv: workerEnv() }, WAIT_MS[name] ?? DEFAULT_WAIT_MS);
|
|
10
|
+
if (asked.kind === 'done') {
|
|
11
|
+
if (asked.out.length > 0)
|
|
12
|
+
process.stdout.write(asked.out);
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
if (asked.kind === 'timeout')
|
|
16
|
+
return true;
|
|
17
|
+
startDaemon();
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
export async function routeHook(name) {
|
|
21
|
+
await runHook(async () => {
|
|
22
|
+
const raw = await readStdin();
|
|
23
|
+
if (await viaDaemon(name, raw))
|
|
24
|
+
return;
|
|
25
|
+
const { runLocally } = await import('./local.js');
|
|
26
|
+
await runLocally(name, raw);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { RecallContext } from '../context.js';
|
|
2
|
+
import type { HookEnv, HookPayload, Write } from './payload.js';
|
|
3
|
+
export interface HookRun {
|
|
4
|
+
payload: HookPayload;
|
|
5
|
+
env: HookEnv;
|
|
6
|
+
write: Write;
|
|
7
|
+
withContext: <T>(work: (ctx: RecallContext) => Promise<T>) => Promise<T>;
|
|
8
|
+
inDaemon: (task: () => Promise<void>) => boolean;
|
|
9
|
+
}
|
|
10
|
+
export type HookHandler = (run: HookRun) => Promise<void>;
|
|
11
|
+
export declare const HOOKS: readonly ["session-start", "user-prompt", "prefer-usages", "turn-end", "session-end"];
|
|
12
|
+
export type HookName = (typeof HOOKS)[number];
|
|
13
|
+
export declare const isHookName: (value: unknown) => value is HookName;
|
|
14
|
+
export declare function loadHandler(name: HookName): Promise<HookHandler>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const HOOKS = [
|
|
2
|
+
'session-start',
|
|
3
|
+
'user-prompt',
|
|
4
|
+
'prefer-usages',
|
|
5
|
+
'turn-end',
|
|
6
|
+
'session-end',
|
|
7
|
+
];
|
|
8
|
+
export const isHookName = (value) => typeof value === 'string' && HOOKS.includes(value);
|
|
9
|
+
export async function loadHandler(name) {
|
|
10
|
+
const loaded = (await import(`./handlers/${name}.js`));
|
|
11
|
+
return loaded.default;
|
|
12
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { clearActive } from '../capture/active.js';
|
|
2
|
+
import { flushSession } from '../capture/index.js';
|
|
3
|
+
import { takeTurnSave } from './turn-job.js';
|
|
4
|
+
export async function saveQueuedTurn(sessionId, withContext) {
|
|
5
|
+
const job = takeTurnSave(sessionId);
|
|
6
|
+
if (!job)
|
|
7
|
+
return;
|
|
8
|
+
await withContext((ctx) => flushSession(ctx, sessionId, job.project, job.transcriptPath, false, job.finalReply));
|
|
9
|
+
if (job.activeToken)
|
|
10
|
+
clearActive(sessionId, job.activeToken);
|
|
11
|
+
}
|
|
@@ -1,64 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { aiSummary, clearCursor, flushSession, observationsFromTurns, readTranscript, transcriptPathFor, } from '../capture/index.js';
|
|
6
|
-
import { isDue, readState } from '../update.js';
|
|
7
|
-
import { createContext } from '../context.js';
|
|
8
|
-
import { capturingDisabled, readPayload, runHook } from './payload.js';
|
|
9
|
-
import { loadConfig } from '../config/index.js';
|
|
10
|
-
import { resolveProject } from '../util/project.js';
|
|
11
|
-
import { silenceSqliteWarning } from '../util/warnings.js';
|
|
12
|
-
import { distillInBackground } from './background.js';
|
|
13
|
-
import { clearPick, sweepPicks } from '../pick/pending.js';
|
|
14
|
-
import { clearActive, sweepActive } from '../capture/active.js';
|
|
15
|
-
import { dropTurnSave, sweepTurnSaves } from './turn-job.js';
|
|
16
|
-
silenceSqliteWarning();
|
|
17
|
-
await runHook(async () => {
|
|
18
|
-
if (capturingDisabled(loadConfig().capture.scripted))
|
|
19
|
-
return;
|
|
20
|
-
const payload = await readPayload();
|
|
21
|
-
const sessionId = payload.session_id;
|
|
22
|
-
if (!sessionId)
|
|
23
|
-
return;
|
|
24
|
-
const project = resolveProject(payload.cwd);
|
|
25
|
-
const ctx = await createContext();
|
|
26
|
-
try {
|
|
27
|
-
const result = await flushSession(ctx, sessionId, project, payload.transcript_path);
|
|
28
|
-
let summary = result.summary;
|
|
29
|
-
if (!ctx.config.distill.enabled && ctx.config.capture.summarize === 'on') {
|
|
30
|
-
const path = payload.transcript_path ?? transcriptPathFor(project, sessionId);
|
|
31
|
-
const { turns } = readTranscript(path, 0);
|
|
32
|
-
const observations = observationsFromTurns(turns, sessionId, project, ctx.config);
|
|
33
|
-
const ai = await aiSummary(observations.map((obs) => `${obs.title}\n${obs.body}`).join('\n\n'), ctx.config.capture.summarizeModel);
|
|
34
|
-
if (ai)
|
|
35
|
-
summary = `AI: ${ai}`;
|
|
36
|
-
}
|
|
37
|
-
await ctx.store.upsertSession({
|
|
38
|
-
id: sessionId,
|
|
39
|
-
project,
|
|
40
|
-
startedAt: Date.now(),
|
|
41
|
-
endedAt: Date.now(),
|
|
42
|
-
...(summary ? { summary } : {}),
|
|
43
|
-
});
|
|
44
|
-
clearCursor(sessionId);
|
|
45
|
-
clearPick(sessionId);
|
|
46
|
-
sweepPicks();
|
|
47
|
-
dropTurnSave(sessionId);
|
|
48
|
-
sweepTurnSaves();
|
|
49
|
-
clearActive(sessionId);
|
|
50
|
-
sweepActive();
|
|
51
|
-
if (ctx.config.distill.enabled)
|
|
52
|
-
distillInBackground(project, sessionId);
|
|
53
|
-
if (ctx.config.updates !== 'off' && isDue(readState())) {
|
|
54
|
-
const cli = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'cli', 'index.js');
|
|
55
|
-
spawn(process.execPath, [cli, 'update', '--quiet'], {
|
|
56
|
-
detached: true,
|
|
57
|
-
stdio: 'ignore',
|
|
58
|
-
}).unref();
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
finally {
|
|
62
|
-
await ctx.close();
|
|
63
|
-
}
|
|
64
|
-
});
|
|
2
|
+
import { routeHook } from './route.js';
|
|
3
|
+
await routeHook('session-end');
|