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,309 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { cosine, packVector, unpackVector } from '../../util/vector.js';
6
+ import { scopeToken } from '../../util/scope.js';
7
+ import { partitionIds } from '../../util/shortid.js';
8
+ const HERE = dirname(fileURLToPath(import.meta.url));
9
+ /**
10
+ * Zero-config default backend, built on Node's own `node:sqlite`.
11
+ *
12
+ * Using the builtin rather than better-sqlite3 means no node-gyp, no prebuilt
13
+ * binary to mismatch, and no install step that can fail on a user's machine.
14
+ * Keyword search is FTS5; vectors are scored by exact brute-force cosine,
15
+ * which stays comfortably fast past the ~100k observations one developer
16
+ * accumulates and avoids an approximate index that would need tuning.
17
+ */
18
+ export class SqliteStore {
19
+ db;
20
+ kind = 'sqlite';
21
+ constructor(db) {
22
+ this.db = db;
23
+ }
24
+ static async create(uri) {
25
+ const path = toFilePath(uri);
26
+ mkdirSync(dirname(path), { recursive: true });
27
+ return new SqliteStore(new DatabaseSync(path));
28
+ }
29
+ async init() {
30
+ this.db.exec(readFileSync(resolve(HERE, 'schema.sql'), 'utf8'));
31
+ }
32
+ async close() {
33
+ this.db.close();
34
+ }
35
+ async ping() {
36
+ return this.db.prepare('SELECT 1 AS ok').get() !== undefined;
37
+ }
38
+ async upsertSession(session) {
39
+ this.db
40
+ .prepare(`INSERT INTO sessions (id, project, started_at, ended_at, summary)
41
+ VALUES (?, ?, ?, ?, ?)
42
+ ON CONFLICT(id) DO UPDATE SET
43
+ ended_at = COALESCE(excluded.ended_at, sessions.ended_at),
44
+ summary = COALESCE(excluded.summary, sessions.summary)`)
45
+ .run(session.id, session.project, session.startedAt, session.endedAt ?? null, session.summary ?? null);
46
+ }
47
+ async getSession(id) {
48
+ const row = this.db.prepare('SELECT * FROM sessions WHERE id = ?').get(id);
49
+ return row ? toSession(row) : null;
50
+ }
51
+ async recentSessions(project, limit) {
52
+ const rows = this.db
53
+ .prepare(`SELECT * FROM sessions
54
+ WHERE project = ? AND summary IS NOT NULL
55
+ ORDER BY started_at DESC LIMIT ?`)
56
+ .all(project, limit);
57
+ return rows.map(toSession);
58
+ }
59
+ async insertObservations(observations) {
60
+ if (observations.length === 0)
61
+ return;
62
+ const stmt = this.db.prepare(`INSERT OR REPLACE INTO observations
63
+ (id, session_id, project, scope, kind, title, body, files, tags, created_at, embedding)
64
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
65
+ this.db.exec('BEGIN');
66
+ try {
67
+ for (const obs of observations) {
68
+ stmt.run(obs.id, obs.sessionId, obs.project, scopeToken(obs.project), obs.kind, obs.title, obs.body, JSON.stringify(obs.files), JSON.stringify(obs.tags), obs.createdAt, obs.embedding ? packVector(obs.embedding) : null);
69
+ }
70
+ this.db.exec('COMMIT');
71
+ }
72
+ catch (error) {
73
+ this.db.exec('ROLLBACK');
74
+ throw error;
75
+ }
76
+ }
77
+ async getObservations(ids) {
78
+ if (ids.length === 0)
79
+ return [];
80
+ const { exact, prefixes } = partitionIds(ids);
81
+ const clauses = [];
82
+ const params = [];
83
+ if (exact.length > 0) {
84
+ clauses.push(`id IN (${exact.map(() => '?').join(',')})`);
85
+ params.push(...exact);
86
+ }
87
+ // GLOB with a trailing star is prefix-anchored, so SQLite can serve it
88
+ // from the primary key index rather than scanning.
89
+ for (const prefix of prefixes) {
90
+ clauses.push('id GLOB ?');
91
+ params.push(`${prefix}*`);
92
+ }
93
+ const rows = this.db
94
+ .prepare(`SELECT * FROM observations WHERE ${clauses.join(' OR ')}`)
95
+ .all(...params);
96
+ return rows.map(toObservation);
97
+ }
98
+ async clear(project) {
99
+ const where = project ? 'WHERE project = ?' : '';
100
+ const params = project ? [project] : [];
101
+ const count = this.db
102
+ .prepare(`SELECT COUNT(*) AS n FROM observations ${where}`)
103
+ .get(...params);
104
+ this.db.exec('BEGIN');
105
+ try {
106
+ // The FTS mirror is kept in sync by triggers, so deleting rows here is
107
+ // enough; dropping it manually would desynchronise the two.
108
+ this.db.prepare(`DELETE FROM observations ${where}`).run(...params);
109
+ this.db.prepare(`DELETE FROM sessions ${where}`).run(...params);
110
+ this.db.exec('COMMIT');
111
+ }
112
+ catch (error) {
113
+ this.db.exec('ROLLBACK');
114
+ throw error;
115
+ }
116
+ this.db.exec('VACUUM');
117
+ return count?.n ?? 0;
118
+ }
119
+ async listProjects() {
120
+ const rows = this.db
121
+ .prepare(`SELECT project, COUNT(*) AS n, MAX(created_at) AS last
122
+ FROM observations GROUP BY project ORDER BY last DESC`)
123
+ .all();
124
+ return rows.map((row) => ({
125
+ project: row['project'],
126
+ observations: Number(row['n']),
127
+ lastActive: Number(row['last']),
128
+ }));
129
+ }
130
+ async searchKeyword(query) {
131
+ // The project constraint goes inside the MATCH expression, not the WHERE
132
+ // clause. Filtering after the match makes FTS5 rank every project's
133
+ // documents and discard all but one project's worth of that work.
134
+ const match = toMatchExpression(query.text, query.project);
135
+ if (match === null)
136
+ return [];
137
+ // Remaining filters are cheap and genuinely post-match.
138
+ const conditions = ['observations_fts MATCH ?'];
139
+ const params = [match];
140
+ if (query.kind) {
141
+ conditions.push('o.kind = ?');
142
+ params.push(query.kind);
143
+ }
144
+ if (query.since !== undefined) {
145
+ conditions.push('o.created_at >= ?');
146
+ params.push(query.since);
147
+ }
148
+ if (query.until !== undefined) {
149
+ conditions.push('o.created_at <= ?');
150
+ params.push(query.until);
151
+ }
152
+ params.push(query.limit);
153
+ // bm25() is lower-is-better, so negate it into a descending score. Column
154
+ // weights (title, body, tags, scope) make a hit in the one-sentence claim
155
+ // outrank the same word buried in a long body; scope carries no weight
156
+ // because it is a filter, not a relevance signal.
157
+ const rows = this.db
158
+ .prepare(`SELECT o.id, o.kind, o.title, o.project, o.created_at,
159
+ -bm25(observations_fts, 10.0, 1.0, 5.0, 0.0) AS score
160
+ FROM observations_fts
161
+ JOIN observations o ON o.rowid = observations_fts.rowid
162
+ WHERE ${conditions.join(' AND ')}
163
+ ORDER BY score DESC
164
+ LIMIT ?`)
165
+ .all(...params);
166
+ return rows.map(toIndexEntry);
167
+ }
168
+ async searchVector(vector, query) {
169
+ const conditions = ['embedding IS NOT NULL'];
170
+ const params = [];
171
+ appendScope(query, conditions, params, '');
172
+ // Newest-first with a hard cap. The scan is linear in rows returned, so
173
+ // this is what keeps p95 flat as history grows: recent memory stays
174
+ // semantically searchable and older memory remains reachable by keyword.
175
+ params.push(query.maxScanCandidates ?? 25000);
176
+ const rows = this.db
177
+ .prepare(`SELECT id, kind, title, project, created_at, embedding
178
+ FROM observations WHERE ${conditions.join(' AND ')}
179
+ ORDER BY created_at DESC LIMIT ?`)
180
+ .all(...params);
181
+ return rows
182
+ .map((row) => ({
183
+ id: row['id'],
184
+ kind: row['kind'],
185
+ title: row['title'],
186
+ project: row['project'],
187
+ createdAt: Number(row['created_at']),
188
+ score: row['embedding']
189
+ ? cosine(vector, unpackVector(toBuffer(row['embedding'])))
190
+ : 0,
191
+ }))
192
+ .sort((a, b) => b.score - a.score)
193
+ .slice(0, query.limit);
194
+ }
195
+ async timeline(query) {
196
+ const anchor = this.db
197
+ .prepare('SELECT project, created_at FROM observations WHERE id = ?')
198
+ .get(query.observationId);
199
+ if (!anchor)
200
+ return [];
201
+ const rows = this.db
202
+ .prepare(`SELECT id, kind, title, project, created_at, 0 AS score FROM (
203
+ SELECT * FROM observations
204
+ WHERE project = ? AND created_at <= ?
205
+ ORDER BY created_at DESC LIMIT ?
206
+ )
207
+ UNION
208
+ SELECT id, kind, title, project, created_at, 0 AS score FROM (
209
+ SELECT * FROM observations
210
+ WHERE project = ? AND created_at > ?
211
+ ORDER BY created_at ASC LIMIT ?
212
+ )
213
+ ORDER BY created_at ASC`)
214
+ .all(anchor['project'], anchor['created_at'], query.before + 1, anchor['project'], anchor['created_at'], query.after);
215
+ return rows.map(toIndexEntry);
216
+ }
217
+ }
218
+ function appendScope(query, conditions, params, prefix) {
219
+ if (query.project) {
220
+ conditions.push(`${prefix}project = ?`);
221
+ params.push(query.project);
222
+ }
223
+ if (query.kind) {
224
+ conditions.push(`${prefix}kind = ?`);
225
+ params.push(query.kind);
226
+ }
227
+ if (query.since !== undefined) {
228
+ conditions.push(`${prefix}created_at >= ?`);
229
+ params.push(query.since);
230
+ }
231
+ if (query.until !== undefined) {
232
+ conditions.push(`${prefix}created_at <= ?`);
233
+ params.push(query.until);
234
+ }
235
+ }
236
+ function toFilePath(uri) {
237
+ if (!uri || uri.trim() === '') {
238
+ return resolve(process.env['HOME'] ?? '.', '.claude-memory/memory.db');
239
+ }
240
+ const stripped = uri.replace(/^(sqlite|file):\/\//, '');
241
+ return resolve(stripped === '' ? './memory.db' : stripped);
242
+ }
243
+ /**
244
+ * Builds the FTS5 MATCH expression.
245
+ *
246
+ * FTS5 treats punctuation as query syntax, so raw user text can throw: every
247
+ * token is quoted. Terms are OR'd so recall stays forgiving and bm25 sorts out
248
+ * what actually mattered, but the whole disjunction is AND'd with the project
249
+ * scope token so the engine never walks other projects' postings.
250
+ *
251
+ * Returns null when there is nothing searchable, so the caller can skip the
252
+ * query entirely rather than issue one that matches everything.
253
+ */
254
+ function toMatchExpression(text, project) {
255
+ const tokens = text
256
+ .toLowerCase()
257
+ .split(/[^a-z0-9_]+/i)
258
+ .filter((token) => token.length > 1);
259
+ const scope = project ? `scope:${scopeToken(project)}` : null;
260
+ if (tokens.length === 0)
261
+ return scope;
262
+ const terms = tokens.map((token) => `"${token}"`).join(' OR ');
263
+ return scope ? `${scope} AND (${terms})` : terms;
264
+ }
265
+ function toBuffer(value) {
266
+ if (Buffer.isBuffer(value))
267
+ return value;
268
+ if (value instanceof Uint8Array)
269
+ return Buffer.from(value);
270
+ return Buffer.alloc(0);
271
+ }
272
+ function toSession(row) {
273
+ const session = {
274
+ id: row['id'],
275
+ project: row['project'],
276
+ startedAt: Number(row['started_at']),
277
+ };
278
+ if (row['ended_at'] != null)
279
+ session.endedAt = Number(row['ended_at']);
280
+ if (row['summary'] != null)
281
+ session.summary = row['summary'];
282
+ return session;
283
+ }
284
+ function toObservation(row) {
285
+ const obs = {
286
+ id: row['id'],
287
+ sessionId: row['session_id'],
288
+ project: row['project'],
289
+ kind: row['kind'],
290
+ title: row['title'],
291
+ body: row['body'],
292
+ files: JSON.parse(row['files'] ?? '[]'),
293
+ tags: JSON.parse(row['tags'] ?? '[]'),
294
+ createdAt: Number(row['created_at']),
295
+ };
296
+ if (row['embedding'])
297
+ obs.embedding = unpackVector(toBuffer(row['embedding']));
298
+ return obs;
299
+ }
300
+ function toIndexEntry(row) {
301
+ return {
302
+ id: row['id'],
303
+ kind: row['kind'],
304
+ title: row['title'],
305
+ project: row['project'],
306
+ createdAt: Number(row['created_at']),
307
+ score: Number(row['score'] ?? 0),
308
+ };
309
+ }
@@ -0,0 +1,61 @@
1
+ PRAGMA journal_mode = WAL;
2
+ PRAGMA synchronous = NORMAL;
3
+
4
+ CREATE TABLE IF NOT EXISTS sessions (
5
+ id TEXT PRIMARY KEY,
6
+ project TEXT NOT NULL,
7
+ started_at INTEGER NOT NULL,
8
+ ended_at INTEGER,
9
+ summary TEXT
10
+ );
11
+
12
+ CREATE INDEX IF NOT EXISTS idx_sessions_project
13
+ ON sessions(project, started_at DESC);
14
+
15
+ CREATE TABLE IF NOT EXISTS observations (
16
+ id TEXT PRIMARY KEY,
17
+ session_id TEXT NOT NULL,
18
+ project TEXT NOT NULL,
19
+ -- Single opaque token identifying the project, indexed inside FTS so that
20
+ -- scoping happens during the match rather than as a post-filter join.
21
+ scope TEXT NOT NULL DEFAULT '',
22
+ kind TEXT NOT NULL,
23
+ title TEXT NOT NULL,
24
+ body TEXT NOT NULL,
25
+ files TEXT NOT NULL DEFAULT '[]',
26
+ tags TEXT NOT NULL DEFAULT '[]',
27
+ created_at INTEGER NOT NULL,
28
+ embedding BLOB
29
+ );
30
+
31
+ CREATE INDEX IF NOT EXISTS idx_obs_project_time
32
+ ON observations(project, created_at DESC);
33
+ CREATE INDEX IF NOT EXISTS idx_obs_kind
34
+ ON observations(project, kind, created_at DESC);
35
+ -- Covers the vector candidate scan, which reads only these columns.
36
+ CREATE INDEX IF NOT EXISTS idx_obs_vector_scan
37
+ ON observations(project, kind) WHERE embedding IS NOT NULL;
38
+
39
+ CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
40
+ title, body, tags, scope,
41
+ content='observations',
42
+ content_rowid='rowid',
43
+ tokenize='porter unicode61'
44
+ );
45
+
46
+ CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
47
+ INSERT INTO observations_fts(rowid, title, body, tags, scope)
48
+ VALUES (new.rowid, new.title, new.body, new.tags, new.scope);
49
+ END;
50
+
51
+ CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
52
+ INSERT INTO observations_fts(observations_fts, rowid, title, body, tags, scope)
53
+ VALUES ('delete', old.rowid, old.title, old.body, old.tags, old.scope);
54
+ END;
55
+
56
+ CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
57
+ INSERT INTO observations_fts(observations_fts, rowid, title, body, tags, scope)
58
+ VALUES ('delete', old.rowid, old.title, old.body, old.tags, old.scope);
59
+ INSERT INTO observations_fts(rowid, title, body, tags, scope)
60
+ VALUES (new.rowid, new.title, new.body, new.tags, new.scope);
61
+ END;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Core domain types. Storage-agnostic on purpose: every adapter maps these
3
+ * to its own representation, and nothing outside src/store knows the difference.
4
+ */
5
+ export type ObservationKind = 'decision' | 'pattern' | 'bugfix' | 'context' | 'deadend' | 'preference';
6
+ export interface Session {
7
+ /** Stable id supplied by the agent host (Claude Code session id). */
8
+ id: string;
9
+ /** Absolute path of the project root this session ran in. */
10
+ project: string;
11
+ startedAt: number;
12
+ endedAt?: number;
13
+ /** One-paragraph recap written at session end. */
14
+ summary?: string;
15
+ }
16
+ export interface Observation {
17
+ id: string;
18
+ sessionId: string;
19
+ project: string;
20
+ kind: ObservationKind;
21
+ /** Single-sentence claim. This is what gets ranked and shown in the index. */
22
+ title: string;
23
+ /** Full reasoning, code excerpts, file paths. Fetched only on demand. */
24
+ body: string;
25
+ files: string[];
26
+ tags: string[];
27
+ createdAt: number;
28
+ /** Present only when an embedder is configured. */
29
+ embedding?: number[];
30
+ }
31
+ /** Compact projection returned by search. Deliberately excludes `body`. */
32
+ export interface ObservationIndexEntry {
33
+ id: string;
34
+ kind: ObservationKind;
35
+ title: string;
36
+ project: string;
37
+ createdAt: number;
38
+ score: number;
39
+ }
40
+ export interface SearchQuery {
41
+ text: string;
42
+ project?: string;
43
+ kind?: ObservationKind;
44
+ since?: number;
45
+ until?: number;
46
+ limit: number;
47
+ /** Ceiling for brute-force vector scans. Ignored by indexed backends. */
48
+ maxScanCandidates?: number;
49
+ }
50
+ export interface TimelineQuery {
51
+ /** Anchor observation. Results are the ones surrounding it in time. */
52
+ observationId: string;
53
+ before: number;
54
+ after: number;
55
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Core domain types. Storage-agnostic on purpose: every adapter maps these
3
+ * to its own representation, and nothing outside src/store knows the difference.
4
+ */
5
+ export {};
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Canonicalises a project path so scoping survives symlinks.
3
+ *
4
+ * Project scoping is an exact string comparison, so two spellings of the same
5
+ * directory silently split a project's memory in half. macOS makes this the
6
+ * default case rather than an edge case: `/tmp` is a symlink to `/private/tmp`
7
+ * and `/var` to `/private/var`, so a hook receiving `cwd` from the agent and a
8
+ * CLI reading `process.cwd()` disagree about the same folder.
9
+ *
10
+ * Resolving to the real path makes every entry point agree. Falls back to the
11
+ * absolute path when the directory does not exist yet, which keeps callers
12
+ * working against paths that have not been created.
13
+ */
14
+ export declare function resolveProject(path: string | undefined): string;
@@ -0,0 +1,24 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ /**
4
+ * Canonicalises a project path so scoping survives symlinks.
5
+ *
6
+ * Project scoping is an exact string comparison, so two spellings of the same
7
+ * directory silently split a project's memory in half. macOS makes this the
8
+ * default case rather than an edge case: `/tmp` is a symlink to `/private/tmp`
9
+ * and `/var` to `/private/var`, so a hook receiving `cwd` from the agent and a
10
+ * CLI reading `process.cwd()` disagree about the same folder.
11
+ *
12
+ * Resolving to the real path makes every entry point agree. Falls back to the
13
+ * absolute path when the directory does not exist yet, which keeps callers
14
+ * working against paths that have not been created.
15
+ */
16
+ export function resolveProject(path) {
17
+ const absolute = resolve(path ?? process.cwd());
18
+ try {
19
+ return realpathSync(absolute);
20
+ }
21
+ catch {
22
+ return absolute;
23
+ }
24
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Maps a project path to a single opaque FTS-safe token.
3
+ *
4
+ * Project paths contain slashes, dots and hyphens, all of which FTS5 treats as
5
+ * token separators, so a path cannot be matched as one unit. Hashing it to a
6
+ * single alphanumeric token lets project scoping happen inside the FTS match
7
+ * instead of as a post-match join, which is the difference between scanning
8
+ * one project's index and scanning every project's.
9
+ */
10
+ export declare function scopeToken(project: string): string;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Maps a project path to a single opaque FTS-safe token.
3
+ *
4
+ * Project paths contain slashes, dots and hyphens, all of which FTS5 treats as
5
+ * token separators, so a path cannot be matched as one unit. Hashing it to a
6
+ * single alphanumeric token lets project scoping happen inside the FTS match
7
+ * instead of as a post-match join, which is the difference between scanning
8
+ * one project's index and scanning every project's.
9
+ */
10
+ export function scopeToken(project) {
11
+ let hash = 0x811c9dc5;
12
+ for (let i = 0; i < project.length; i += 1) {
13
+ hash ^= project.charCodeAt(i);
14
+ hash = Math.imul(hash, 0x01000193) >>> 0;
15
+ }
16
+ return `scope${(hash >>> 0).toString(36)}`;
17
+ }
@@ -0,0 +1,11 @@
1
+ export declare function toShortId(id: string): string;
2
+ /** True when a caller passed a short form rather than a full uuid. */
3
+ export declare function isShortId(id: string): boolean;
4
+ /**
5
+ * Split incoming ids into exact matches and prefixes so adapters can issue one
6
+ * indexed `IN (...)` query plus one prefix query, rather than a scan per id.
7
+ */
8
+ export declare function partitionIds(ids: string[]): {
9
+ exact: string[];
10
+ prefixes: string[];
11
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Display form for observation ids.
3
+ *
4
+ * A full UUID costs about 9 tokens per line, roughly as much as the title it
5
+ * labels, so nearly half of a search result is identifier noise. Taking the
6
+ * first two UUID groups keeps 12 hex digits of entropy (2.8e14 values), which
7
+ * makes a collision vanishingly unlikely at the scale one database holds, and
8
+ * cuts the identifier to about 4 tokens.
9
+ *
10
+ * The short form is a literal prefix of the stored id, so resolution is a
11
+ * prefix match that every backend can serve from its primary key index. Same
12
+ * idea as an abbreviated git SHA.
13
+ */
14
+ const SHORT_LENGTH = 13; // "2904a5fd-0f22"
15
+ export function toShortId(id) {
16
+ return id.slice(0, SHORT_LENGTH);
17
+ }
18
+ /** True when a caller passed a short form rather than a full uuid. */
19
+ export function isShortId(id) {
20
+ return id.length < 36;
21
+ }
22
+ /**
23
+ * Split incoming ids into exact matches and prefixes so adapters can issue one
24
+ * indexed `IN (...)` query plus one prefix query, rather than a scan per id.
25
+ */
26
+ export function partitionIds(ids) {
27
+ const exact = [];
28
+ const prefixes = [];
29
+ for (const id of ids) {
30
+ if (isShortId(id))
31
+ prefixes.push(id);
32
+ else
33
+ exact.push(id);
34
+ }
35
+ return { exact, prefixes };
36
+ }
@@ -0,0 +1,5 @@
1
+ /** Serialize an embedding for BLOB columns / BSON binary. */
2
+ export declare function packVector(values: number[]): Buffer;
3
+ export declare function unpackVector(buffer: Buffer): number[];
4
+ /** Assumes both inputs are L2-normalized, which the embedder guarantees. */
5
+ export declare function cosine(a: number[], b: number[]): number;
@@ -0,0 +1,17 @@
1
+ /** Serialize an embedding for BLOB columns / BSON binary. */
2
+ export function packVector(values) {
3
+ const floats = Float32Array.from(values);
4
+ return Buffer.from(floats.buffer, floats.byteOffset, floats.byteLength);
5
+ }
6
+ export function unpackVector(buffer) {
7
+ const copy = Buffer.from(buffer);
8
+ return Array.from(new Float32Array(copy.buffer, copy.byteOffset, copy.byteLength / 4));
9
+ }
10
+ /** Assumes both inputs are L2-normalized, which the embedder guarantees. */
11
+ export function cosine(a, b) {
12
+ const len = Math.min(a.length, b.length);
13
+ let dot = 0;
14
+ for (let i = 0; i < len; i += 1)
15
+ dot += (a[i] ?? 0) * (b[i] ?? 0);
16
+ return dot;
17
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Suppresses Node's ExperimentalWarning for `node:sqlite`.
3
+ *
4
+ * The warning is correct but useless here: the API is deliberate, not
5
+ * accidental, and it fires on every hook invocation. Left alone it prints two
6
+ * lines of noise before every prompt the user types, which makes real errors
7
+ * from these hooks impossible to spot.
8
+ *
9
+ * Only that one warning is swallowed. Everything else is re-emitted to stderr
10
+ * so genuine problems still surface.
11
+ */
12
+ export declare function silenceSqliteWarning(): void;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Suppresses Node's ExperimentalWarning for `node:sqlite`.
3
+ *
4
+ * The warning is correct but useless here: the API is deliberate, not
5
+ * accidental, and it fires on every hook invocation. Left alone it prints two
6
+ * lines of noise before every prompt the user types, which makes real errors
7
+ * from these hooks impossible to spot.
8
+ *
9
+ * Only that one warning is swallowed. Everything else is re-emitted to stderr
10
+ * so genuine problems still surface.
11
+ */
12
+ export function silenceSqliteWarning() {
13
+ const original = process.listeners('warning');
14
+ process.removeAllListeners('warning');
15
+ process.on('warning', (warning) => {
16
+ const isSqliteExperimental = warning.name === 'ExperimentalWarning' && /SQLite/i.test(warning.message);
17
+ if (isSqliteExperimental)
18
+ return;
19
+ if (original.length > 0) {
20
+ for (const listener of original)
21
+ listener(warning);
22
+ }
23
+ else {
24
+ process.stderr.write(`${warning.name}: ${warning.message}\n`);
25
+ }
26
+ });
27
+ }