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,12 +1,14 @@
1
- import { askDaemon, daemonWanted, forwardedEnv, startDaemon, workerEnv } from '../daemon/client.js';
1
+ import { askDaemon, daemonWanted, envForDaemon, replaceDaemon, startDaemon, } from '../daemon/client.js';
2
2
  import { buildId } from '../daemon/paths.js';
3
+ import { readDaemonPid } from '../daemon/pid.js';
3
4
  import { readStdin, runHook } from './payload.js';
4
5
  const WAIT_MS = { 'prefer-usages': 8_000 };
5
6
  const DEFAULT_WAIT_MS = 50_000;
6
7
  async function viaDaemon(name, raw) {
7
8
  if (!daemonWanted())
8
9
  return false;
9
- const asked = await askDaemon({ build: buildId(), hook: name, raw, env: forwardedEnv(), workerEnv: workerEnv() }, WAIT_MS[name] ?? DEFAULT_WAIT_MS);
10
+ const daemon = readDaemonPid();
11
+ const asked = await askDaemon({ build: buildId(), hook: name, raw, env: envForDaemon() }, WAIT_MS[name] ?? DEFAULT_WAIT_MS);
10
12
  if (asked.kind === 'done') {
11
13
  if (asked.out.length > 0)
12
14
  process.stdout.write(asked.out);
@@ -14,7 +16,10 @@ async function viaDaemon(name, raw) {
14
16
  }
15
17
  if (asked.kind === 'timeout')
16
18
  return true;
17
- startDaemon();
19
+ if (asked.kind === 'silent')
20
+ replaceDaemon(daemon);
21
+ else
22
+ startDaemon();
18
23
  return false;
19
24
  }
20
25
  export async function routeHook(name) {
@@ -1,8 +1,7 @@
1
1
  import type { RecallContext } from '../context.js';
2
- import type { HookEnv, HookPayload, Write } from './payload.js';
2
+ import type { HookPayload, Write } from './payload.js';
3
3
  export interface HookRun {
4
4
  payload: HookPayload;
5
- env: HookEnv;
6
5
  write: Write;
7
6
  withContext: <T>(work: (ctx: RecallContext) => Promise<T>) => Promise<T>;
8
7
  inDaemon: (task: () => Promise<void>) => boolean;
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+ export declare const observationIdSchema: z.ZodString;
3
+ export declare const observationIdsSchema: z.ZodArray<z.ZodString>;
@@ -0,0 +1,6 @@
1
+ import { z } from 'zod';
2
+ import { INVALID_ID_HINT, isObservationId } from '../../util/shortid.js';
3
+ export const observationIdSchema = z.string().refine(isObservationId, {
4
+ error: (issue) => `${JSON.stringify(issue.input)} ${INVALID_ID_HINT}`,
5
+ });
6
+ export const observationIdsSchema = z.array(observationIdSchema).min(1).max(25);
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { observationIdsSchema } from './ids.js';
2
3
  import { KINDS } from './kinds.js';
3
4
  import { remember as record } from '../../capture/index.js';
4
5
  import { toShortId } from '../../util/shortid.js';
@@ -19,7 +20,7 @@ export function register(server, ctx) {
19
20
  tags: z.array(z.string()).max(5).optional().describe('Extra tags for filtering'),
20
21
  }, (args) => remember(ctx, args));
21
22
  server.tool('forget', 'Delete observations by id, for memory that is wrong or obsolete. Ids come ' +
22
- 'from search. This cannot be undone, so confirm with the user first.', { ids: z.array(z.string()).min(1).max(25) }, (args) => forget(ctx, args));
23
+ 'from search. This cannot be undone, so confirm with the user first.', { ids: observationIdsSchema }, (args) => forget(ctx, args));
23
24
  }
24
25
  async function remember(ctx, { text, kind, project, key, tags, }) {
25
26
  const observation = await record(ctx, {
@@ -1,11 +1,12 @@
1
1
  import { z } from 'zod';
2
+ import { observationIdSchema, observationIdsSchema } from './ids.js';
2
3
  import { renderFull, renderIndex } from '../render.js';
3
4
  export function register(server, ctx) {
4
5
  server.tool('timeline', 'Given one observation id from search, show what happened immediately before ' +
5
6
  'and after it. Use it when a single result is not enough to explain itself ' +
6
7
  'and you need the session around it — what led to a decision and what came ' +
7
8
  'of it. Ids are the short ids search prints.', {
8
- observation_id: z.string(),
9
+ observation_id: observationIdSchema,
9
10
  before: z.number().int().min(0).max(20).default(5),
10
11
  after: z.number().int().min(0).max(20).default(5),
11
12
  }, (args) => timeline(ctx, args));
@@ -13,7 +14,7 @@ export function register(server, ctx) {
13
14
  'ids it printed. Use it whenever a search snippet looks like it answers your ' +
14
15
  'question but is cut off — the snippet is one line, the body is the reasoning. ' +
15
16
  'Always batch every id you need into one call rather than calling repeatedly.', {
16
- ids: z.array(z.string()).min(1).max(25),
17
+ ids: observationIdsSchema,
17
18
  chars: z
18
19
  .number()
19
20
  .int()
@@ -3,15 +3,10 @@ import { KINDS } from './kinds.js';
3
3
  import { renderIndex } from '../render.js';
4
4
  import { resolveProject } from '../../util/project.js';
5
5
  export function register(server, ctx) {
6
- server.tool('search', 'USE THIS BEFORE re-deriving anything this project already decided — before ' +
7
- 'reading git history to reconstruct why code is the way it is, before saying ' +
8
- 'you lack context, and before asking the user to re-explain a past decision ' +
9
- 'or a failed approach. This answers WHY: decisions, dead ends, bugs and the ' +
10
- 'reasoning behind them, which the source code cannot tell you. Returns a ' +
11
- 'compact index (id, kind, date, title, and a line of the matching body) ' +
12
- 'without full bodies; use the snippet to decide which ids are worth passing ' +
13
- 'to get_observations rather than expanding on the title alone. For a code ' +
14
- 'symbol use find_usages instead.', {
6
+ server.tool('search', 'Answers WHY: decisions, dead ends, bugs and the reasoning behind them, which the ' +
7
+ 'source code cannot tell you. Returns a compact index (id, kind, date, title, a line ' +
8
+ 'of the matching body) without full bodies; pick the ids worth passing to ' +
9
+ 'get_observations from the snippet. For a code symbol use find_usages instead.', {
15
10
  query: z.string().describe('Natural language description of what you need'),
16
11
  project: z
17
12
  .string()
@@ -1,61 +1,43 @@
1
1
  import { z } from 'zod';
2
- import { findUsages as textUsages, formatUsages, repoRootFor } from '../../usages/index.js';
3
- import { NO_GRAPH, NO_GRAPH_FOR_PATH, answerQuery, formatGraph, hasGraph, suggestFor, } from '../../graph/index.js';
2
+ import { findUsages as textUsages, formatUsages } from '../../usages/index.js';
3
+ import { NO_GRAPH, NO_GRAPH_FOR_PATH, hasGraph, suggestFor, usagesAnswer, } from '../../graph/index.js';
4
4
  import { resolveProject } from '../../util/project.js';
5
5
  export function register(server, ctx) {
6
- server.tool('find_usages', 'USE THIS INSTEAD OF grep/rg WHENEVER THE THING YOU ARE LOOKING UP IS A CODE ' +
7
- 'SYMBOL — a function, class, method, type, interface, constant or any ' +
8
- 'identifier — and ALWAYS before editing, renaming or deleting one, because ' +
9
- 'grep cannot tell a call from an import from an inherit and will not show ' +
10
- 'you the blast radius. Reach for grep only for what is genuinely text: ' +
11
- 'plain prose, comments, log output, string literals, multi-pattern regex, ' +
12
- 'or the scoping flags this tool does not expose. Modes: "usages" (default) ' +
13
- 'lists what references the symbol, with the relation on each line, then the ' +
14
- 'grep lines the graph could not link; "explain" adds what the symbol reaches, ' +
15
- '"path" traces how two symbols connect (pass the second as `target`), and ' +
16
- '"text" is a plain live `git grep`. Graph modes re-parse anything that ' +
17
- 'changed before replying, and answer from text until `claude-db scan` has ' +
18
- 'run. Every edge is tagged EXTRACTED (read literally from the syntax) or ' +
19
- 'INFERRED (matched by name across files, with a score). A miss suggests near ' +
20
- 'names, so a half-remembered symbol is still worth asking about. Use `search` ' +
21
- 'instead for "why is this the way it is" (history).', {
22
- symbol: z
23
- .string()
24
- .min(1)
25
- .max(200)
26
- .describe('Exact name to search for, e.g. "useAuth" or "CartButton"'),
6
+ server.tool('find_usages', 'Look up a code symbol (function, class, method, type, constant): what references it ' +
7
+ 'and how. Use it before editing, renaming or deleting one; use grep for plain text, ' +
8
+ 'comments, logs and strings. Modes: "usages" (default) lists references with their ' +
9
+ 'relation, then grep lines the graph could not link; "explain" adds what the symbol ' +
10
+ 'reaches; "path" shows how `symbol` connects to `target`; "text" is a live git grep. ' +
11
+ 'Edges are EXTRACTED (from syntax) or INFERRED (matched by name, scored). A miss ' +
12
+ 'suggests near names.', {
13
+ symbol: z.string().min(1).max(200).describe('Exact name, e.g. "useAuth"'),
27
14
  mode: z
28
15
  .enum(['text', 'usages', 'explain', 'path'])
29
16
  .default('usages')
30
- .describe('How to answer. "usages" (default) uses the code graph plus grep; "text" ' +
31
- 'greps live only'),
32
- target: z.string().optional().describe('The second symbol, for mode "path" only'),
17
+ .describe('Default "usages"'),
18
+ target: z.string().optional().describe('Second symbol, for mode "path"'),
33
19
  path: z
34
20
  .string()
35
21
  .optional()
36
- .describe('A file or directory to narrow the search to; omit to search the whole ' +
37
- 'repository (never narrows on its own — a blast-radius check that quietly ' +
38
- 'skipped part of the repo would be worse than no check). Must be inside a ' +
39
- 'git working tree. Different from the memory tools’ project param, which ' +
40
- 'can point at a folder pooling several repos rather than being one itself'),
22
+ .describe('A file or folder inside a git working tree; omit for the whole repository'),
41
23
  regex: z
42
24
  .boolean()
43
25
  .default(false)
44
- .describe('Treat symbol as an extended regular expression instead of a literal name'),
26
+ .describe('Treat symbol as a regular expression (mode "text" only)'),
45
27
  context: z
46
28
  .number()
47
29
  .int()
48
30
  .min(0)
49
31
  .max(10)
50
32
  .default(0)
51
- .describe('Lines of surrounding context before/after each match'),
33
+ .describe('Lines of context around each match (mode "text" only)'),
52
34
  limit: z
53
35
  .number()
54
36
  .int()
55
37
  .min(1)
56
38
  .max(500)
57
39
  .default(100)
58
- .describe('Cap on matching lines returned; the result says how many more exist'),
40
+ .describe('Cap on matching lines; the result says how many more exist'),
59
41
  }, (args) => find_usages(ctx, args));
60
42
  }
61
43
  const reply = (text) => ({ content: [{ type: 'text', text }] });
@@ -76,14 +58,6 @@ async function find_usages(ctx, args) {
76
58
  return reply(NO_GRAPH_FOR_PATH);
77
59
  return reply(`${NO_GRAPH}\n${await textAnswer(ctx, args)}`);
78
60
  }
79
- const root = repoRootFor(args.path ?? process.cwd());
80
- const { mode, symbol, target, limit } = args;
81
- const answer = await answerQuery({
82
- store: ctx.store,
83
- root,
84
- project,
85
- query: { mode, symbol, ...(target ? { target } : {}), limit },
86
- refresh: true,
87
- });
88
- return reply(formatGraph(answer, root));
61
+ const { mode, symbol, target, limit, path } = args;
62
+ return reply(await usagesAnswer({ store: ctx.store, project, mode, symbol, target, limit, path }));
89
63
  }
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createContext } from '../context.js';
3
3
  import { runHook } from '../hooks/payload.js';
4
- import { withCost } from '../hooks/prompt-recall.js';
5
4
  import { silenceSqliteWarning } from '../util/warnings.js';
6
5
  import { finishPick, takeJob } from './pending.js';
7
6
  import { headlessPicker, pickMemories, recordPickFailure, recordPickSuccess } from './run.js';
@@ -24,7 +23,7 @@ await runHook(async () => {
24
23
  }
25
24
  recordPickSuccess();
26
25
  if (outcome.kind === 'picked') {
27
- finishPick(sessionId, token, { text: withCost(outcome.block), ids: outcome.ids });
26
+ finishPick(sessionId, token, { text: `${outcome.block}\n`, ids: outcome.ids });
28
27
  }
29
28
  }
30
29
  finally {
@@ -1,12 +1,17 @@
1
1
  import type { Embedder } from '../embed/index.js';
2
2
  import type { MemoryStore } from '../store/adapter.js';
3
3
  import type { Observation, ObservationIndexEntry, SearchQuery, TimelineQuery } from '../types.js';
4
+ export interface RankedCandidates {
5
+ keyword: ObservationIndexEntry[];
6
+ fused: ObservationIndexEntry[];
7
+ }
4
8
  export declare class SearchService {
5
9
  private readonly store;
6
10
  private readonly embedder;
7
11
  private readonly maxScanCandidates;
8
12
  constructor(store: MemoryStore, embedder: Embedder | (() => Promise<Embedder>), maxScanCandidates?: number);
9
13
  search(query: SearchQuery): Promise<ObservationIndexEntry[]>;
14
+ candidates(query: SearchQuery): Promise<RankedCandidates>;
10
15
  private embed;
11
16
  private vectorSearch;
12
17
  timeline(query: TimelineQuery): Promise<ObservationIndexEntry[]>;
@@ -1,5 +1,6 @@
1
1
  import { applyRecencyBoost, fuse } from './rank.js';
2
2
  import { meaningfulTokens } from './stopwords.js';
3
+ const WIDE_FACTOR = 3;
3
4
  export class SearchService {
4
5
  store;
5
6
  embedder;
@@ -10,18 +11,23 @@ export class SearchService {
10
11
  this.maxScanCandidates = maxScanCandidates;
11
12
  }
12
13
  async search(query) {
13
- if (meaningfulTokens(query.text).length === 0)
14
- return [];
14
+ const { fused } = await this.candidates(query);
15
+ return applyRecencyBoost(fused, query.until ?? Date.now());
16
+ }
17
+ async candidates(query) {
18
+ const keywordText = meaningfulTokens(query.text).join(' ');
19
+ if (keywordText === '')
20
+ return { keyword: [], fused: [] };
15
21
  const wide = {
16
22
  ...query,
17
- limit: query.limit * 3,
23
+ limit: query.limit * WIDE_FACTOR,
18
24
  maxScanCandidates: query.maxScanCandidates ?? this.maxScanCandidates,
19
25
  };
20
26
  const embedded = this.embed(wide.text);
21
- const keyword = await this.store.searchKeyword(wide).catch(() => []);
27
+ const keyword = await this.store.searchKeyword({ ...wide, text: keywordText }).catch(() => []);
22
28
  const vector = await this.vectorSearch(wide, await embedded);
23
29
  const fused = fuse([keyword, vector].filter((r) => r.length > 0), query.limit);
24
- return applyRecencyBoost(fused, Date.now());
30
+ return { keyword, fused };
25
31
  }
26
32
  async embed(text) {
27
33
  try {
@@ -1,4 +1,5 @@
1
1
  import type { ProjectFilter, SearchQuery } from '../../types.js';
2
2
  export declare function projectClause(filter: ProjectFilter | undefined, values: unknown[], column?: string): string | null;
3
+ export declare function likePrefix(prefix: string): string;
3
4
  export declare function excludeSessionsClause(sessions: string[] | undefined, values: unknown[]): string | null;
4
5
  export declare function appendScope(query: SearchQuery, conditions: string[], values: unknown[]): void;
@@ -6,6 +6,9 @@ export function projectClause(filter, values, column = 'project') {
6
6
  values.push(projects);
7
7
  return `${column} = ANY($${values.length}::text[])`;
8
8
  }
9
+ export function likePrefix(prefix) {
10
+ return `${prefix.replace(/[\\%_]/g, '\\$&')}%`;
11
+ }
9
12
  export function excludeSessionsClause(sessions, values) {
10
13
  if (!sessions || sessions.length === 0)
11
14
  return null;
@@ -138,8 +138,9 @@ export async function findEdges(pool, filter) {
138
138
  }
139
139
  let where = sides.length > 0 ? ` AND (${sides.join(' OR ')})` : '';
140
140
  if (filter.dstName !== undefined) {
141
- values.push(filter.dstName, `%.${filter.dstName}`);
142
- where += ` AND (dst_name = $${values.length - 1} OR dst_name LIKE $${values.length})`;
141
+ values.push(filter.dstName, `.${filter.dstName}`);
142
+ const [exact, suffix] = [`$${values.length - 1}`, `$${values.length}`];
143
+ where += ` AND (dst_name = ${exact} OR right(dst_name, length(${suffix})) = ${suffix})`;
143
144
  }
144
145
  values.push(filter.limit ?? 2000);
145
146
  const res = await pool.query(`SELECT ${EDGE_COLUMNS} FROM symbol_edges WHERE project = $1${where}
@@ -22,7 +22,9 @@ export class PostgresStore {
22
22
  }
23
23
  async init() {
24
24
  const meta = await this.readMeta();
25
- if (meta?.version === SCHEMA_VERSION) {
25
+ const cachedOff = meta?.version === SCHEMA_VERSION && !meta.vectorEnabled;
26
+ const installed = cachedOff && (await metaOps.hasVectorExtension(this.pool));
27
+ if (meta?.version === SCHEMA_VERSION && !installed) {
26
28
  this.vectorEnabled = meta.vectorEnabled;
27
29
  this.vectorDims = meta.vectorDims;
28
30
  return;
@@ -6,6 +6,7 @@ export declare function readMeta(pool: Pool): Promise<{
6
6
  } | null>;
7
7
  export declare function ensureTagsIndexed(pool: Pool): Promise<void>;
8
8
  export declare function readVectorDims(pool: Pool): Promise<number | null>;
9
+ export declare function hasVectorExtension(pool: Pool): Promise<boolean>;
9
10
  export declare function tryEnableVector(pool: Pool): Promise<boolean>;
10
11
  export declare function writeMeta(pool: Pool, vectorEnabled: boolean, vectorDims: number | null): Promise<void>;
11
12
  export declare function indexEmbeddings(pool: Pool): Promise<void>;
@@ -48,6 +48,10 @@ export async function readVectorDims(pool) {
48
48
  const dims = Number(res.rows[0]?.['dims'] ?? -1);
49
49
  return dims > 0 ? dims : null;
50
50
  }
51
+ export async function hasVectorExtension(pool) {
52
+ const res = await pool.query("SELECT 1 AS found FROM pg_extension WHERE extname = 'vector'");
53
+ return res.rows.length > 0;
54
+ }
51
55
  export async function tryEnableVector(pool) {
52
56
  try {
53
57
  await pool.query('CREATE EXTENSION IF NOT EXISTS vector');
@@ -1,6 +1,6 @@
1
1
  import { foreignNames, isWholeScope } from '../adapter.js';
2
2
  import { partitionIds } from '../../util/shortid.js';
3
- import { excludeSessionsClause, projectClause } from './filters.js';
3
+ import { excludeSessionsClause, likePrefix, projectClause } from './filters.js';
4
4
  import { toIndexEntry, toObservation } from './rows.js';
5
5
  import { noProjects } from '../project-scope.js';
6
6
  const COLUMNS = 'id, session_id, project, kind, title, body, files, tags, created_at, embedder, author, status';
@@ -21,7 +21,7 @@ export async function getObservations(pool, ids) {
21
21
  clauses.push(`id = ANY($${values.length}::text[])`);
22
22
  }
23
23
  for (const prefix of prefixes) {
24
- values.push(`${prefix.replace(/[%_]/g, '')}%`);
24
+ values.push(likePrefix(prefix));
25
25
  clauses.push(`id LIKE $${values.length}`);
26
26
  }
27
27
  const res = await pool.query(`SELECT ${COLUMNS} FROM observations WHERE ${clauses.join(' OR ')}`, values);
@@ -42,7 +42,7 @@ export async function remove(pool, filter) {
42
42
  alternatives.push(`id = ANY($${values.length}::text[])`);
43
43
  }
44
44
  for (const prefix of prefixes) {
45
- values.push(`${prefix.replace(/[%_]/g, '')}%`);
45
+ values.push(likePrefix(prefix));
46
46
  alternatives.push(`id LIKE $${values.length}`);
47
47
  }
48
48
  conditions.push(`(${alternatives.join(' OR ')})`);
@@ -15,5 +15,6 @@ export interface ScopeResolver {
15
15
  key(value: string): Promise<string>;
16
16
  resolve(value: string): Promise<ProjectScope>;
17
17
  }
18
+ export declare const SCOPE_TTL_MS = 60000;
18
19
  export declare function isExistingFolder(value: string): boolean;
19
20
  export declare function createScopeResolver(options: ScopeResolverOptions): ScopeResolver;
@@ -2,7 +2,7 @@ import { statSync } from 'node:fs';
2
2
  import { isAbsolute } from 'node:path';
3
3
  import { projectKey } from '../util/project-key.js';
4
4
  import { isLinkable, orderScope } from './project-scope.js';
5
- const SCOPE_TTL_MS = 60_000;
5
+ export const SCOPE_TTL_MS = 60_000;
6
6
  export function isExistingFolder(value) {
7
7
  if (!isAbsolute(value))
8
8
  return false;
@@ -1,3 +1,4 @@
1
+ import { assertValidIds } from '../util/shortid.js';
1
2
  export function withProjectScope(inner, resolver) {
2
3
  const keyOf = (project) => resolver.key(project);
3
4
  async function expand(filter) {
@@ -11,7 +12,7 @@ export function withProjectScope(inner, resolver) {
11
12
  const overrides = {
12
13
  async insertObservations(observations) {
13
14
  const keyed = await Promise.all(observations.map(async (obs) => ({ ...obs, project: await keyOf(obs.project) })));
14
- return inner.insertObservations(keyed);
15
+ return inner.insertObservations([...new Map(keyed.map((obs) => [obs.id, obs])).values()]);
15
16
  },
16
17
  async upsertSession(session) {
17
18
  return inner.upsertSession({ ...session, project: await keyOf(session.project) });
@@ -20,6 +21,7 @@ export function withProjectScope(inner, resolver) {
20
21
  return inner.recentSessions((await expand(project)) ?? project, limit);
21
22
  },
22
23
  async remove(filter) {
24
+ assertValidIds(filter.ids ?? []);
23
25
  const project = await expand(filter.project);
24
26
  return inner.remove(project === undefined ? filter : { ...filter, project });
25
27
  },
@@ -1,6 +1,7 @@
1
1
  import type { ProjectFilter, RemoveFilter, SearchQuery } from '../../types.js';
2
2
  export declare function projectClause(column: string, filter: ProjectFilter | undefined, params: unknown[]): string | null;
3
3
  export declare function excludeSessionsClause(column: string, sessions: string[] | undefined, params: unknown[]): string | null;
4
+ export declare function globPrefix(prefix: string): string;
4
5
  export declare function removeWhere(filter: RemoveFilter): {
5
6
  where: string;
6
7
  params: unknown[];
@@ -3,6 +3,7 @@ import { partitionIds } from '../../util/shortid.js';
3
3
  import { resolve } from 'node:path';
4
4
  import { scopeToken } from '../../util/scope.js';
5
5
  import { meaningfulTokens } from '../../search/stopwords.js';
6
+ import { hookEnv } from '../../util/env.js';
6
7
  export function projectClause(column, filter, params) {
7
8
  const projects = projectsOf(filter);
8
9
  if (projects.length === 0)
@@ -18,6 +19,9 @@ export function excludeSessionsClause(column, sessions, params) {
18
19
  params.push(...sessions);
19
20
  return `${column} NOT IN (${sessions.map(() => '?').join(',')})`;
20
21
  }
22
+ export function globPrefix(prefix) {
23
+ return `${prefix.replace(/[*?[]/g, '[$&]')}*`;
24
+ }
21
25
  export function removeWhere(filter) {
22
26
  const conditions = [];
23
27
  const params = [];
@@ -30,7 +34,7 @@ export function removeWhere(filter) {
30
34
  }
31
35
  for (const prefix of prefixes) {
32
36
  alternatives.push('id GLOB ?');
33
- params.push(`${prefix}*`);
37
+ params.push(globPrefix(prefix));
34
38
  }
35
39
  conditions.push(`(${alternatives.join(' OR ')})`);
36
40
  }
@@ -92,7 +96,7 @@ export function toMatchExpression(text, project) {
92
96
  }
93
97
  export function toFilePath(uri) {
94
98
  if (!uri || uri.trim() === '') {
95
- return resolve(process.env['HOME'] ?? '.', '.claude-memory/memory.db');
99
+ return resolve(hookEnv()['HOME'] ?? '.', '.claude-memory/memory.db');
96
100
  }
97
101
  const stripped = uri.replace(/^(sqlite|file):\/\//, '');
98
102
  return resolve(stripped === '' ? './memory.db' : stripped);
@@ -104,8 +104,9 @@ export async function findEdges(db, filter) {
104
104
  }
105
105
  let where = sides.length > 0 ? ` AND (${sides.join(' OR ')})` : '';
106
106
  if (filter.dstName !== undefined) {
107
- where += ' AND (dst_name = ? OR dst_name LIKE ?)';
108
- params.push(filter.dstName, `%.${filter.dstName}`);
107
+ const suffix = `.${filter.dstName}`;
108
+ where += ' AND (dst_name = ? OR substr(dst_name, -length(?)) = ?)';
109
+ params.push(filter.dstName, suffix, suffix);
109
110
  }
110
111
  params.push(filter.limit ?? 2000);
111
112
  const rows = db
@@ -1,6 +1,6 @@
1
1
  import { foreignNames, isWholeScope } from '../adapter.js';
2
2
  import { toObservation } from './rows.js';
3
- import { TAG_PREDICATE, excludeSessionsClause, projectClause, removeWhere } from './filters.js';
3
+ import { TAG_PREDICATE, excludeSessionsClause, globPrefix, projectClause, removeWhere, } from './filters.js';
4
4
  import { partitionIds } from '../../util/shortid.js';
5
5
  import { packVector } from '../../util/vector.js';
6
6
  import { scopeToken } from '../../util/scope.js';
@@ -40,7 +40,7 @@ export async function getObservations(db, ids) {
40
40
  }
41
41
  for (const prefix of prefixes) {
42
42
  clauses.push('id GLOB ?');
43
- params.push(`${prefix}*`);
43
+ params.push(globPrefix(prefix));
44
44
  }
45
45
  const rows = db
46
46
  .prepare(`SELECT * FROM observations WHERE ${clauses.join(' OR ')}`)
@@ -171,11 +171,10 @@ export async function closeObservations(db, ids) {
171
171
  if (ids.length === 0)
172
172
  return 0;
173
173
  const holes = ids.map(() => '?').join(',');
174
- const row = db
175
- .prepare(`SELECT COUNT(*) AS n FROM observations WHERE status = 'open' AND id IN (${holes})`)
176
- .get(...ids);
177
- db.prepare(`UPDATE observations SET status = 'done' WHERE id IN (${holes})`).run(...ids);
178
- return row?.n ?? 0;
174
+ const result = db
175
+ .prepare(`UPDATE observations SET status = 'done' WHERE status = 'open' AND id IN (${holes})`)
176
+ .run(...ids);
177
+ return Number(result.changes);
179
178
  }
180
179
  export async function markReplaced(db, ids) {
181
180
  if (ids.length === 0)
@@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process';
2
2
  import { accessSync, constants, mkdirSync, readFileSync, readlinkSync, statSync, writeFileSync, } from 'node:fs';
3
3
  import { basename, delimiter, isAbsolute, join } from 'node:path';
4
4
  import { CONFIG_DIR } from '../config/dir.js';
5
+ import { hookEnv } from './env.js';
5
6
  const REMEMBERED_FILE = join(CONFIG_DIR, 'claude-binary');
6
7
  const MAX_ANCESTORS = 8;
7
8
  function inspectOnLinux(pid) {
@@ -58,7 +59,7 @@ export function rememberedBinary(file = REMEMBERED_FILE) {
58
59
  return null;
59
60
  }
60
61
  }
61
- export function rememberClaudeBinary(env = process.env, file = REMEMBERED_FILE, find = findClaudeAncestor) {
62
+ export function rememberClaudeBinary(env = hookEnv(), file = REMEMBERED_FILE, find = findClaudeAncestor) {
62
63
  const known = rememberedBinary(file);
63
64
  const path = env['CLAUDE_CODE_EXECPATH'] || (known === null ? find() : null);
64
65
  if (!path || path === known)
@@ -69,7 +70,7 @@ export function rememberClaudeBinary(env = process.env, file = REMEMBERED_FILE,
69
70
  }
70
71
  catch { }
71
72
  }
72
- export function findOnPath(env = process.env) {
73
+ export function findOnPath(env = hookEnv()) {
73
74
  const names = process.platform === 'win32' ? ['claude.exe', 'claude.cmd'] : ['claude'];
74
75
  for (const dir of (env['PATH'] ?? '').split(delimiter)) {
75
76
  if (dir === '')
@@ -87,7 +88,7 @@ export function findOnPath(env = process.env) {
87
88
  }
88
89
  return null;
89
90
  }
90
- export function resolveClaude(env = process.env, lookup = {}) {
91
+ export function resolveClaude(env = hookEnv(), lookup = {}) {
91
92
  const { remembered = rememberedBinary, ancestor = findClaudeAncestor, onPath = findOnPath, } = lookup;
92
93
  const fromEnv = env['CLAUDE_CODE_EXECPATH'];
93
94
  if (fromEnv)
@@ -101,6 +102,6 @@ export function resolveClaude(env = process.env, lookup = {}) {
101
102
  const found = onPath(env);
102
103
  return found ? { path: found, source: 'PATH' } : null;
103
104
  }
104
- export function claudeBinary(env = process.env, lookup = {}) {
105
+ export function claudeBinary(env = hookEnv(), lookup = {}) {
105
106
  return resolveClaude(env, lookup)?.path ?? 'claude';
106
107
  }
@@ -1,5 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { claudeBinary } from './claude-binary.js';
3
+ import { hookEnv } from './env.js';
3
4
  const MAX_BUFFER = 1024 * 1024;
4
5
  const REASON_CHARS = 120;
5
6
  const OPTIONAL_FLAGS = [
@@ -69,7 +70,7 @@ function call(args, timeoutMs, env) {
69
70
  const child = execFile(claudeBinary(), args, {
70
71
  timeout: timeoutMs,
71
72
  maxBuffer: MAX_BUFFER,
72
- env: { ...process.env, ...env, CLAUDE_DB_CAPTURE: 'off' },
73
+ env: { ...hookEnv(), ...env, CLAUDE_DB_CAPTURE: 'off' },
73
74
  }, (error, stdout, stderr) => {
74
75
  if (!error) {
75
76
  done({ ok: true, stdout });
@@ -0,0 +1,2 @@
1
+ export declare function claudeConfigDir(): string;
2
+ export declare const claudeProjectsDir: () => string;
@@ -0,0 +1,8 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { hookEnv } from './env.js';
4
+ export function claudeConfigDir() {
5
+ const custom = hookEnv()['CLAUDE_CONFIG_DIR'];
6
+ return custom ? custom : join(homedir(), '.claude');
7
+ }
8
+ export const claudeProjectsDir = () => join(claudeConfigDir(), 'projects');
@@ -0,0 +1,2 @@
1
+ export declare const hookEnv: () => NodeJS.ProcessEnv;
2
+ export declare function withHookEnv<T>(env: NodeJS.ProcessEnv | undefined, work: () => T): T;
@@ -0,0 +1,6 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ const requests = new AsyncLocalStorage();
3
+ export const hookEnv = () => requests.getStore() ?? process.env;
4
+ export function withHookEnv(env, work) {
5
+ return env ? requests.run(env, work) : work();
6
+ }
@@ -1,4 +1,7 @@
1
1
  export declare function toShortId(id: string): string;
2
+ export declare const INVALID_ID_HINT = "is not an observation id. Use the 8 to 36 hex characters search prints.";
3
+ export declare function isObservationId(id: string): boolean;
4
+ export declare function assertValidIds(ids: string[]): void;
2
5
  export declare function isShortId(id: string): boolean;
3
6
  export declare function partitionIds(ids: string[]): {
4
7
  exact: string[];
@@ -2,6 +2,17 @@ const SHORT_LENGTH = 13;
2
2
  export function toShortId(id) {
3
3
  return id.slice(0, SHORT_LENGTH);
4
4
  }
5
+ const VALID_ID = /^[0-9a-f-]{8,36}$/;
6
+ export const INVALID_ID_HINT = 'is not an observation id. Use the 8 to 36 hex characters search prints.';
7
+ export function isObservationId(id) {
8
+ return VALID_ID.test(id);
9
+ }
10
+ export function assertValidIds(ids) {
11
+ const bad = ids.find((id) => !isObservationId(id));
12
+ if (bad === undefined)
13
+ return;
14
+ throw new Error(`${JSON.stringify(bad)} ${INVALID_ID_HINT}`);
15
+ }
5
16
  export function isShortId(id) {
6
17
  return id.length < 36;
7
18
  }