claude-db 0.1.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 (80) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +306 -0
  3. package/dist/capture/command.d.ts +20 -0
  4. package/dist/capture/command.js +81 -0
  5. package/dist/capture/flush.d.ts +20 -0
  6. package/dist/capture/flush.js +102 -0
  7. package/dist/capture/identity.d.ts +13 -0
  8. package/dist/capture/identity.js +26 -0
  9. package/dist/capture/index.d.ts +7 -0
  10. package/dist/capture/index.js +5 -0
  11. package/dist/capture/transcript.d.ts +41 -0
  12. package/dist/capture/transcript.js +160 -0
  13. package/dist/capture/turn-extractor.d.ts +13 -0
  14. package/dist/capture/turn-extractor.js +135 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +349 -0
  17. package/dist/cli/install.d.ts +40 -0
  18. package/dist/cli/install.js +156 -0
  19. package/dist/config/index.d.ts +3 -0
  20. package/dist/config/index.js +2 -0
  21. package/dist/config/load.d.ts +11 -0
  22. package/dist/config/load.js +31 -0
  23. package/dist/config/schema.d.ts +28 -0
  24. package/dist/config/schema.js +66 -0
  25. package/dist/context.d.ts +22 -0
  26. package/dist/context.js +25 -0
  27. package/dist/embed/builtin.d.ts +20 -0
  28. package/dist/embed/builtin.js +66 -0
  29. package/dist/embed/embedder.d.ts +27 -0
  30. package/dist/embed/embedder.js +18 -0
  31. package/dist/embed/index.d.ts +15 -0
  32. package/dist/embed/index.js +39 -0
  33. package/dist/embed/local.d.ts +17 -0
  34. package/dist/embed/local.js +41 -0
  35. package/dist/hooks/payload.d.ts +21 -0
  36. package/dist/hooks/payload.js +33 -0
  37. package/dist/hooks/relevance.d.ts +20 -0
  38. package/dist/hooks/relevance.js +84 -0
  39. package/dist/hooks/session-end.d.ts +2 -0
  40. package/dist/hooks/session-end.js +35 -0
  41. package/dist/hooks/session-start.d.ts +2 -0
  42. package/dist/hooks/session-start.js +46 -0
  43. package/dist/hooks/user-prompt.d.ts +2 -0
  44. package/dist/hooks/user-prompt.js +56 -0
  45. package/dist/index.d.ts +10 -0
  46. package/dist/index.js +5 -0
  47. package/dist/mcp/server.d.ts +8 -0
  48. package/dist/mcp/server.js +87 -0
  49. package/dist/search/index.d.ts +2 -0
  50. package/dist/search/index.js +2 -0
  51. package/dist/search/rank.d.ts +17 -0
  52. package/dist/search/rank.js +43 -0
  53. package/dist/search/service.d.ts +44 -0
  54. package/dist/search/service.js +78 -0
  55. package/dist/store/adapter.d.ts +47 -0
  56. package/dist/store/adapter.js +1 -0
  57. package/dist/store/index.d.ts +14 -0
  58. package/dist/store/index.js +39 -0
  59. package/dist/store/mongo/driver.d.ts +44 -0
  60. package/dist/store/mongo/driver.js +28 -0
  61. package/dist/store/mongo/index.d.ts +36 -0
  62. package/dist/store/mongo/index.js +275 -0
  63. package/dist/store/postgres/index.d.ts +30 -0
  64. package/dist/store/postgres/index.js +289 -0
  65. package/dist/store/sqlite/index.d.ts +30 -0
  66. package/dist/store/sqlite/index.js +309 -0
  67. package/dist/store/sqlite/schema.sql +61 -0
  68. package/dist/types.d.ts +55 -0
  69. package/dist/types.js +5 -0
  70. package/dist/util/project.d.ts +14 -0
  71. package/dist/util/project.js +24 -0
  72. package/dist/util/scope.d.ts +10 -0
  73. package/dist/util/scope.js +17 -0
  74. package/dist/util/shortid.d.ts +11 -0
  75. package/dist/util/shortid.js +36 -0
  76. package/dist/util/vector.d.ts +5 -0
  77. package/dist/util/vector.js +17 -0
  78. package/dist/util/warnings.d.ts +12 -0
  79. package/dist/util/warnings.js +27 -0
  80. package/package.json +96 -0
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ import { flushSession } from '../capture/index.js';
3
+ import { createContext } from '../context.js';
4
+ import { emitContext, readPayload, runHook } from './payload.js';
5
+ import { isSearchable, renderPromptContext } from './relevance.js';
6
+ import { resolveProject } from '../util/project.js';
7
+ import { silenceSqliteWarning } from '../util/warnings.js';
8
+ silenceSqliteWarning();
9
+ /**
10
+ * UserPromptSubmit: persist the previous turn, then surface relevant memory.
11
+ *
12
+ * Flushing here rather than only at SessionEnd is what makes capture durable.
13
+ * A new prompt is the moment the previous turn is provably finished, and it is
14
+ * the one event guaranteed to fire while a session is alive. Sessions that
15
+ * crash, are force-quit, or simply stay open for days never reach SessionEnd,
16
+ * and under the old design everything they did was lost.
17
+ *
18
+ * Injecting here rather than relying on Claude to call the search tool is the
19
+ * same argument applied to reading: recall that happens, not recall that might.
20
+ */
21
+ await runHook(async () => {
22
+ const payload = await readPayload();
23
+ const sessionId = payload.session_id;
24
+ if (!sessionId)
25
+ return;
26
+ const project = resolveProject(payload.cwd);
27
+ const ctx = await createContext();
28
+ try {
29
+ await ctx.store.upsertSession({ id: sessionId, project, startedAt: Date.now() });
30
+ // Capture what just happened before searching, so this session's own work
31
+ // is already available to the query that follows.
32
+ await flushSession(ctx, sessionId, project, payload.transcript_path);
33
+ // Checked before any search so a trivial prompt never constructs the
34
+ // embedding model, which is the expensive part of this hook.
35
+ const prompt = payload.prompt ?? '';
36
+ if (!ctx.config.inject.perPrompt || !isSearchable(prompt))
37
+ return;
38
+ const entries = await ctx.search.search({
39
+ text: prompt,
40
+ project,
41
+ limit: ctx.config.inject.promptResults,
42
+ });
43
+ // Fetch full bodies only for the few we intend to expand, never for the
44
+ // whole result set: that is the layer-3 discipline applied to injection.
45
+ const toExpand = entries.slice(0, ctx.config.inject.expandTop);
46
+ const expanded = toExpand.length > 0
47
+ ? await ctx.search.getObservations(toExpand.map((entry) => entry.id))
48
+ : [];
49
+ const block = renderPromptContext(entries, ctx.config.inject.promptMaxChars, expanded, ctx.config.inject.expandMaxChars);
50
+ if (block)
51
+ emitContext(`${block}\n`);
52
+ }
53
+ finally {
54
+ await ctx.close();
55
+ }
56
+ });
@@ -0,0 +1,10 @@
1
+ export type { Observation, ObservationIndexEntry, ObservationKind, SearchQuery, Session, TimelineQuery, } from './types.js';
2
+ export type { MemoryStore, StoreFactory } from './store/index.js';
3
+ export { createStore } from './store/index.js';
4
+ export type { Embedder } from './embed/index.js';
5
+ export { createEmbedder, NoopEmbedder } from './embed/index.js';
6
+ export { SearchService, fuse, applyRecencyBoost } from './search/index.js';
7
+ export type { Config } from './config/index.js';
8
+ export { loadConfig, saveConfig } from './config/index.js';
9
+ export type { RecallContext } from './context.js';
10
+ export { createContext } from './context.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createStore } from './store/index.js';
2
+ export { createEmbedder, NoopEmbedder } from './embed/index.js';
3
+ export { SearchService, fuse, applyRecencyBoost } from './search/index.js';
4
+ export { loadConfig, saveConfig } from './config/index.js';
5
+ export { createContext } from './context.js';
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import type { ObservationIndexEntry } from '../types.js';
3
+ /**
4
+ * Layer 1 rendering. Every character here is multiplied by the number of
5
+ * results and paid on every search, so the format is deliberately terse:
6
+ * short id, kind, month-day, title. No padding, no separators, no year.
7
+ */
8
+ export declare function renderIndex(entries: ObservationIndexEntry[]): string;
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { z } from 'zod';
5
+ import { createContext } from '../context.js';
6
+ import { toShortId } from '../util/shortid.js';
7
+ import { resolveProject } from '../util/project.js';
8
+ import { silenceSqliteWarning } from '../util/warnings.js';
9
+ silenceSqliteWarning();
10
+ const KINDS = [
11
+ 'decision', 'pattern', 'bugfix', 'context', 'deadend', 'preference',
12
+ ];
13
+ /**
14
+ * Exposes memory as three tools that mirror the progressive disclosure layers.
15
+ * Tool descriptions spell out the intended order, because the saving only
16
+ * materializes if the agent filters at `search` before calling
17
+ * `get_observations`.
18
+ */
19
+ const ctx = await createContext();
20
+ const server = new McpServer({ name: 'claude-db', version: '0.1.0' });
21
+ server.tool('search', 'Layer 1. Search project memory and get a compact index of matches ' +
22
+ '(id, kind, title, date) without bodies. Start here, then fetch details ' +
23
+ 'for only the ids that look relevant.', {
24
+ query: z.string().describe('Natural language description of what you need'),
25
+ project: z.string().optional().describe('Absolute project path; defaults to cwd'),
26
+ kind: z.enum(KINDS).optional(),
27
+ limit: z.number().int().min(1).max(50).default(10),
28
+ }, async ({ query, project, kind, limit }) => {
29
+ const entries = await ctx.search.search({
30
+ text: query,
31
+ limit,
32
+ project: resolveProject(project),
33
+ ...(kind ? { kind } : {}),
34
+ });
35
+ return { content: [{ type: 'text', text: renderIndex(entries) }] };
36
+ });
37
+ server.tool('timeline', 'Layer 2. Show what happened immediately before and after a given ' +
38
+ 'observation, to understand the context a decision was made in.', {
39
+ observation_id: z.string(),
40
+ before: z.number().int().min(0).max(20).default(5),
41
+ after: z.number().int().min(0).max(20).default(5),
42
+ }, async ({ observation_id, before, after }) => {
43
+ const entries = await ctx.search.timeline({ observationId: observation_id, before, after });
44
+ return { content: [{ type: 'text', text: renderIndex(entries) }] };
45
+ });
46
+ server.tool('get_observations', 'Layer 3. Fetch full bodies for specific observation ids, using the short ' +
47
+ 'ids returned by search. Always batch every id you need into one call ' +
48
+ 'rather than calling repeatedly.', { ids: z.array(z.string()).min(1).max(25) }, async ({ ids }) => {
49
+ const observations = await ctx.search.getObservations(ids);
50
+ return { content: [{ type: 'text', text: observations.map(renderFull).join('\n\n---\n\n') }] };
51
+ });
52
+ /**
53
+ * Layer 1 rendering. Every character here is multiplied by the number of
54
+ * results and paid on every search, so the format is deliberately terse:
55
+ * short id, kind, month-day, title. No padding, no separators, no year.
56
+ */
57
+ export function renderIndex(entries) {
58
+ if (entries.length === 0)
59
+ return 'No matching observations.';
60
+ const rows = entries.map((entry) => {
61
+ const date = new Date(entry.createdAt).toISOString().slice(5, 10);
62
+ return `${toShortId(entry.id)} ${entry.kind} ${date} ${entry.title}`;
63
+ });
64
+ return `${entries.length} result(s):\n${rows.join('\n')}`;
65
+ }
66
+ function renderFull(obs) {
67
+ const date = new Date(obs.createdAt).toISOString();
68
+ return [
69
+ `id: ${toShortId(obs.id)}`,
70
+ `kind: ${obs.kind}`,
71
+ `when: ${date}`,
72
+ obs.files.length > 0 ? `files: ${obs.files.join(', ')}` : null,
73
+ '',
74
+ obs.title,
75
+ '',
76
+ obs.body,
77
+ ]
78
+ .filter((line) => line !== null)
79
+ .join('\n');
80
+ }
81
+ const transport = new StdioServerTransport();
82
+ await server.connect(transport);
83
+ for (const signal of ['SIGINT', 'SIGTERM']) {
84
+ process.on(signal, () => {
85
+ void ctx.close().finally(() => process.exit(0));
86
+ });
87
+ }
@@ -0,0 +1,2 @@
1
+ export { SearchService } from './service.js';
2
+ export { applyRecencyBoost, fuse } from './rank.js';
@@ -0,0 +1,2 @@
1
+ export { SearchService } from './service.js';
2
+ export { applyRecencyBoost, fuse } from './rank.js';
@@ -0,0 +1,17 @@
1
+ import type { ObservationIndexEntry } from '../types.js';
2
+ /**
3
+ * Reciprocal Rank Fusion.
4
+ *
5
+ * Keyword scores (BM25, ts_rank) and vector scores (cosine) live on
6
+ * incompatible scales, so normalizing them against each other is guesswork.
7
+ * RRF sidesteps that by discarding magnitudes and fusing on rank position
8
+ * alone: an item ranked 1st by either retriever scores 1/(k+1) from it.
9
+ * That makes the blend robust with no per-backend tuning.
10
+ */
11
+ export declare function fuse(rankings: ObservationIndexEntry[][], limit: number): ObservationIndexEntry[];
12
+ /**
13
+ * Mild recency preference applied after fusion. Memory about a codebase decays
14
+ * in usefulness: a decision from last week usually beats one from last year.
15
+ * Half-life is deliberately long so old-but-relevant results still surface.
16
+ */
17
+ export declare function applyRecencyBoost(entries: ObservationIndexEntry[], now: number, halfLifeDays?: number): ObservationIndexEntry[];
@@ -0,0 +1,43 @@
1
+ /** Damping constant from the original RRF paper. */
2
+ const RRF_K = 60;
3
+ /**
4
+ * Reciprocal Rank Fusion.
5
+ *
6
+ * Keyword scores (BM25, ts_rank) and vector scores (cosine) live on
7
+ * incompatible scales, so normalizing them against each other is guesswork.
8
+ * RRF sidesteps that by discarding magnitudes and fusing on rank position
9
+ * alone: an item ranked 1st by either retriever scores 1/(k+1) from it.
10
+ * That makes the blend robust with no per-backend tuning.
11
+ */
12
+ export function fuse(rankings, limit) {
13
+ const scores = new Map();
14
+ const entries = new Map();
15
+ for (const ranking of rankings) {
16
+ ranking.forEach((entry, index) => {
17
+ const contribution = 1 / (RRF_K + index + 1);
18
+ scores.set(entry.id, (scores.get(entry.id) ?? 0) + contribution);
19
+ if (!entries.has(entry.id))
20
+ entries.set(entry.id, entry);
21
+ });
22
+ }
23
+ return [...scores.entries()]
24
+ .sort((a, b) => b[1] - a[1])
25
+ .slice(0, limit)
26
+ .map(([id, score]) => ({ ...entries.get(id), score }));
27
+ }
28
+ /**
29
+ * Mild recency preference applied after fusion. Memory about a codebase decays
30
+ * in usefulness: a decision from last week usually beats one from last year.
31
+ * Half-life is deliberately long so old-but-relevant results still surface.
32
+ */
33
+ export function applyRecencyBoost(entries, now, halfLifeDays = 45) {
34
+ const halfLifeMs = halfLifeDays * 24 * 60 * 60 * 1000;
35
+ return entries
36
+ .map((entry) => {
37
+ const age = Math.max(0, now - entry.createdAt);
38
+ const decay = Math.pow(0.5, age / halfLifeMs);
39
+ // Floor at 0.7 so recency nudges ordering without overpowering relevance.
40
+ return { ...entry, score: entry.score * (0.7 + 0.3 * decay) };
41
+ })
42
+ .sort((a, b) => b.score - a.score);
43
+ }
@@ -0,0 +1,44 @@
1
+ import type { Embedder } from '../embed/index.js';
2
+ import type { MemoryStore } from '../store/adapter.js';
3
+ import type { Observation, ObservationIndexEntry, SearchQuery, TimelineQuery } from '../types.js';
4
+ /**
5
+ * Three-layer progressive disclosure.
6
+ *
7
+ * Naive memory search returns whole records and burns thousands of tokens on
8
+ * results the agent discards. Here retrieval is split so the agent pays for
9
+ * detail only once it has decided what is relevant:
10
+ *
11
+ * 1. search() compact index, roughly 50-100 tokens per hit
12
+ * 2. timeline() chronological neighbours of a promising hit
13
+ * 3. getObservations() full bodies, for a hand-picked set of ids
14
+ *
15
+ * Filtering at layer 1 and expanding at layer 3 is where the ~10x saving comes
16
+ * from versus returning full records up front.
17
+ */
18
+ export declare class SearchService {
19
+ private readonly store;
20
+ /** Lazily resolved: search must not force model construction. */
21
+ private readonly embedder;
22
+ /** Ceiling for brute-force vector scans on backends without an index. */
23
+ private readonly maxScanCandidates;
24
+ constructor(store: MemoryStore,
25
+ /** Lazily resolved: search must not force model construction. */
26
+ embedder: Embedder | (() => Promise<Embedder>),
27
+ /** Ceiling for brute-force vector scans on backends without an index. */
28
+ maxScanCandidates?: number);
29
+ /** Layer 1. Hybrid keyword + vector retrieval, fused by rank. */
30
+ search(query: SearchQuery): Promise<ObservationIndexEntry[]>;
31
+ /**
32
+ * Vector retrieval, isolated so its failure modes cannot take down search.
33
+ *
34
+ * The embedding model may be absent, still downloading, or unsupported by
35
+ * the backend. In every one of those cases the correct behaviour is to
36
+ * return no vector candidates and let keyword results stand, never to throw:
37
+ * degraded recall beats no recall.
38
+ */
39
+ private vectorSearch;
40
+ /** Layer 2. What was happening around a given observation. */
41
+ timeline(query: TimelineQuery): Promise<ObservationIndexEntry[]>;
42
+ /** Layer 3. Full detail, only for ids the caller already filtered down to. */
43
+ getObservations(ids: string[]): Promise<Observation[]>;
44
+ }
@@ -0,0 +1,78 @@
1
+ import { applyRecencyBoost, fuse } from './rank.js';
2
+ /**
3
+ * Three-layer progressive disclosure.
4
+ *
5
+ * Naive memory search returns whole records and burns thousands of tokens on
6
+ * results the agent discards. Here retrieval is split so the agent pays for
7
+ * detail only once it has decided what is relevant:
8
+ *
9
+ * 1. search() compact index, roughly 50-100 tokens per hit
10
+ * 2. timeline() chronological neighbours of a promising hit
11
+ * 3. getObservations() full bodies, for a hand-picked set of ids
12
+ *
13
+ * Filtering at layer 1 and expanding at layer 3 is where the ~10x saving comes
14
+ * from versus returning full records up front.
15
+ */
16
+ export class SearchService {
17
+ store;
18
+ embedder;
19
+ maxScanCandidates;
20
+ constructor(store,
21
+ /** Lazily resolved: search must not force model construction. */
22
+ embedder,
23
+ /** Ceiling for brute-force vector scans on backends without an index. */
24
+ maxScanCandidates = 25000) {
25
+ this.store = store;
26
+ this.embedder = embedder;
27
+ this.maxScanCandidates = maxScanCandidates;
28
+ }
29
+ /** Layer 1. Hybrid keyword + vector retrieval, fused by rank. */
30
+ async search(query) {
31
+ // Over-fetch from each retriever so fusion has room to disagree.
32
+ const wide = {
33
+ ...query,
34
+ limit: query.limit * 3,
35
+ maxScanCandidates: query.maxScanCandidates ?? this.maxScanCandidates,
36
+ };
37
+ const keyword = await this.store.searchKeyword(wide).catch(() => []);
38
+ const vector = await this.vectorSearch(wide);
39
+ const fused = fuse([keyword, vector].filter((r) => r.length > 0), query.limit);
40
+ return applyRecencyBoost(fused, Date.now());
41
+ }
42
+ /**
43
+ * Vector retrieval, isolated so its failure modes cannot take down search.
44
+ *
45
+ * The embedding model may be absent, still downloading, or unsupported by
46
+ * the backend. In every one of those cases the correct behaviour is to
47
+ * return no vector candidates and let keyword results stand, never to throw:
48
+ * degraded recall beats no recall.
49
+ */
50
+ async vectorSearch(query) {
51
+ try {
52
+ const embedder = typeof this.embedder === 'function' ? await this.embedder() : this.embedder;
53
+ if (embedder.dimensions === 0)
54
+ return [];
55
+ const [embedding] = await embedder.embed([query.text]);
56
+ if (!embedding || embedding.length === 0)
57
+ return [];
58
+ const candidates = await this.store.searchVector(embedding, query);
59
+ // Nearest-neighbour search always returns its top k, however poor the
60
+ // match. Without a floor, an unrelated prompt still yields results, and
61
+ // injecting those trains the reader to ignore memory entirely. Dropping
62
+ // them here rather than after fusion keeps weak candidates from
63
+ // borrowing rank credibility from the keyword list.
64
+ return candidates.filter((entry) => entry.score >= embedder.minRelevance);
65
+ }
66
+ catch {
67
+ return [];
68
+ }
69
+ }
70
+ /** Layer 2. What was happening around a given observation. */
71
+ async timeline(query) {
72
+ return this.store.timeline(query);
73
+ }
74
+ /** Layer 3. Full detail, only for ids the caller already filtered down to. */
75
+ async getObservations(ids) {
76
+ return this.store.getObservations(ids);
77
+ }
78
+ }
@@ -0,0 +1,47 @@
1
+ import type { Observation, ObservationIndexEntry, SearchQuery, Session, TimelineQuery } from '../types.js';
2
+ export interface ProjectSummary {
3
+ project: string;
4
+ observations: number;
5
+ lastActive: number;
6
+ }
7
+ /**
8
+ * The contract every database backend implements.
9
+ *
10
+ * Adapters own persistence only. Ranking, fusion and token budgeting live in
11
+ * src/search so they stay identical no matter which database is plugged in.
12
+ * An adapter that cannot do vectors returns [] from `searchVector`; the search
13
+ * service degrades to keyword-only rather than failing.
14
+ */
15
+ export interface MemoryStore {
16
+ readonly kind: string;
17
+ /** Create collections/tables and indexes. Must be idempotent. */
18
+ init(): Promise<void>;
19
+ close(): Promise<void>;
20
+ /** Cheap liveness probe used by `claude-db doctor`. */
21
+ ping(): Promise<boolean>;
22
+ upsertSession(session: Session): Promise<void>;
23
+ getSession(id: string): Promise<Session | null>;
24
+ recentSessions(project: string, limit: number): Promise<Session[]>;
25
+ insertObservations(observations: Observation[]): Promise<void>;
26
+ getObservations(ids: string[]): Promise<Observation[]>;
27
+ /**
28
+ * Deletes memory, scoped to one project or everything when omitted.
29
+ * Returns the number of observations removed.
30
+ *
31
+ * Belongs on the adapter rather than being handled by deleting a file,
32
+ * because on a shared Postgres or Mongo there is no file to delete.
33
+ */
34
+ clear(project?: string): Promise<number>;
35
+ /** Every project with memory in this database, most recently active first. */
36
+ listProjects(): Promise<ProjectSummary[]>;
37
+ /** Lexical match. Returns scores on an adapter-defined scale. */
38
+ searchKeyword(query: SearchQuery): Promise<ObservationIndexEntry[]>;
39
+ /** Vector match. Return [] when the backend has no vector support. */
40
+ searchVector(vector: number[], query: SearchQuery): Promise<ObservationIndexEntry[]>;
41
+ timeline(query: TimelineQuery): Promise<ObservationIndexEntry[]>;
42
+ }
43
+ export interface StoreFactory {
44
+ /** Lowercase URI schemes this factory claims, e.g. ['mongodb','mongodb+srv']. */
45
+ schemes: string[];
46
+ create(uri: string): Promise<MemoryStore>;
47
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import type { MemoryStore } from './adapter.js';
2
+ export type { MemoryStore, StoreFactory } from './adapter.js';
3
+ /**
4
+ * Resolve a store from a connection URI. The scheme alone decides the backend,
5
+ * so users configure one variable and never name an adapter explicitly.
6
+ *
7
+ * mongodb://... | mongodb+srv://... -> MongoDB
8
+ * postgres://... | postgresql://... -> Postgres + pgvector
9
+ * sqlite:///abs/path | ./file.db -> SQLite (default)
10
+ *
11
+ * Adapters are imported lazily so a user on Mongo never loads the Postgres
12
+ * driver, and a missing optional dependency surfaces as a clear message.
13
+ */
14
+ export declare function createStore(uri: string): Promise<MemoryStore>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Resolve a store from a connection URI. The scheme alone decides the backend,
3
+ * so users configure one variable and never name an adapter explicitly.
4
+ *
5
+ * mongodb://... | mongodb+srv://... -> MongoDB
6
+ * postgres://... | postgresql://... -> Postgres + pgvector
7
+ * sqlite:///abs/path | ./file.db -> SQLite (default)
8
+ *
9
+ * Adapters are imported lazily so a user on Mongo never loads the Postgres
10
+ * driver, and a missing optional dependency surfaces as a clear message.
11
+ */
12
+ export async function createStore(uri) {
13
+ const scheme = parseScheme(uri);
14
+ switch (scheme) {
15
+ case 'mongodb':
16
+ case 'mongodb+srv': {
17
+ const { MongoStore } = await import('./mongo/index.js');
18
+ return MongoStore.create(uri);
19
+ }
20
+ case 'postgres':
21
+ case 'postgresql': {
22
+ const { PostgresStore } = await import('./postgres/index.js');
23
+ return PostgresStore.create(uri);
24
+ }
25
+ case 'sqlite':
26
+ case 'file':
27
+ case '': {
28
+ const { SqliteStore } = await import('./sqlite/index.js');
29
+ return SqliteStore.create(uri);
30
+ }
31
+ default:
32
+ throw new Error(`Unsupported database scheme "${scheme}". ` +
33
+ `Use mongodb://, postgres://, or a sqlite file path.`);
34
+ }
35
+ }
36
+ function parseScheme(uri) {
37
+ const match = /^([a-z0-9+.-]+):\/\//i.exec(uri.trim());
38
+ return match?.[1]?.toLowerCase() ?? '';
39
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Structural types for the slice of the MongoDB driver this adapter uses.
3
+ *
4
+ * Declared locally rather than imported from `mongodb` so the project compiles
5
+ * with zero optional dependencies installed. A user who only ever uses SQLite
6
+ * should not need a Mongo driver on disk to run `npm run build`.
7
+ *
8
+ * These describe real driver behaviour, so if the shapes ever drift the
9
+ * adapter fails at runtime with a clear error rather than silently misbehaving.
10
+ */
11
+ export type Doc = Record<string, unknown>;
12
+ export interface FindCursor<T> {
13
+ sort(spec: Doc): FindCursor<T>;
14
+ limit(n: number): FindCursor<T>;
15
+ toArray(): Promise<T[]>;
16
+ }
17
+ export interface Collection<T> {
18
+ createIndex(spec: Doc, options?: Doc): Promise<string>;
19
+ findOne(filter: Doc, options?: Doc): Promise<T | null>;
20
+ find(filter: Doc, options?: Doc): FindCursor<T>;
21
+ updateOne(filter: Doc, update: Doc, options?: Doc): Promise<unknown>;
22
+ deleteMany(filter: Doc): Promise<unknown>;
23
+ bulkWrite(operations: Doc[], options?: Doc): Promise<unknown>;
24
+ aggregate<R>(pipeline: Doc[]): FindCursor<R>;
25
+ listSearchIndexes(): FindCursor<Doc>;
26
+ }
27
+ export interface Db {
28
+ command(spec: Doc): Promise<Doc>;
29
+ collection<T>(name: string): Collection<T>;
30
+ }
31
+ export interface MongoClient {
32
+ connect(): Promise<unknown>;
33
+ db(name: string): Db;
34
+ close(): Promise<void>;
35
+ }
36
+ export interface MongoModule {
37
+ MongoClient: new (uri: string) => MongoClient;
38
+ }
39
+ /**
40
+ * Loads the driver at runtime. The specifier is widened to `string` so
41
+ * TypeScript does not try to resolve `mongodb` at build time, which is the
42
+ * whole point of keeping it optional.
43
+ */
44
+ export declare function importMongo(): Promise<MongoModule>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Structural types for the slice of the MongoDB driver this adapter uses.
3
+ *
4
+ * Declared locally rather than imported from `mongodb` so the project compiles
5
+ * with zero optional dependencies installed. A user who only ever uses SQLite
6
+ * should not need a Mongo driver on disk to run `npm run build`.
7
+ *
8
+ * These describe real driver behaviour, so if the shapes ever drift the
9
+ * adapter fails at runtime with a clear error rather than silently misbehaving.
10
+ */
11
+ /**
12
+ * Loads the driver at runtime. The specifier is widened to `string` so
13
+ * TypeScript does not try to resolve `mongodb` at build time, which is the
14
+ * whole point of keeping it optional.
15
+ */
16
+ export async function importMongo() {
17
+ try {
18
+ const mod = (await import('mongodb'));
19
+ if (mod.MongoClient)
20
+ return { MongoClient: mod.MongoClient };
21
+ if (mod.default?.MongoClient)
22
+ return mod.default;
23
+ throw new Error('unexpected mongodb module shape');
24
+ }
25
+ catch {
26
+ throw new Error('MongoDB driver not installed. Run: npm install mongodb');
27
+ }
28
+ }
@@ -0,0 +1,36 @@
1
+ import type { MemoryStore, ProjectSummary } from '../adapter.js';
2
+ import type { Observation, ObservationIndexEntry, SearchQuery, Session, TimelineQuery } from '../../types.js';
3
+ /**
4
+ * Works against any MongoDB: Atlas, self-hosted, or a local container.
5
+ *
6
+ * Keyword search uses a compound text index, available in every deployment.
7
+ * Vector search prefers an Atlas `$vectorSearch` index when one exists and
8
+ * otherwise falls back to scoring candidates in process, so a plain
9
+ * `mongodb://localhost` connection string still gets semantic recall.
10
+ */
11
+ export declare class MongoStore implements MemoryStore {
12
+ private readonly client;
13
+ private readonly db;
14
+ private readonly sessions;
15
+ private readonly observations;
16
+ readonly kind = "mongodb";
17
+ /** Resolved on first vector query, then cached for the process lifetime. */
18
+ private atlasVectorIndex;
19
+ private constructor();
20
+ static create(uri: string): Promise<MongoStore>;
21
+ init(): Promise<void>;
22
+ close(): Promise<void>;
23
+ ping(): Promise<boolean>;
24
+ upsertSession(session: Session): Promise<void>;
25
+ getSession(id: string): Promise<Session | null>;
26
+ recentSessions(project: string, limit: number): Promise<Session[]>;
27
+ insertObservations(observations: Observation[]): Promise<void>;
28
+ getObservations(ids: string[]): Promise<Observation[]>;
29
+ clear(project?: string): Promise<number>;
30
+ listProjects(): Promise<ProjectSummary[]>;
31
+ searchKeyword(query: SearchQuery): Promise<ObservationIndexEntry[]>;
32
+ searchVector(vector: number[], query: SearchQuery): Promise<ObservationIndexEntry[]>;
33
+ timeline(query: TimelineQuery): Promise<ObservationIndexEntry[]>;
34
+ private scopeFilter;
35
+ private hasAtlasVectorIndex;
36
+ }