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,66 @@
1
+ import { z } from 'zod';
2
+ export const ConfigSchema = z.object({
3
+ /**
4
+ * Any supported connection string. Scheme selects the adapter.
5
+ * Defaults to a local SQLite file so the tool works before configuration.
6
+ */
7
+ database: z.string().default(''),
8
+ embeddings: z
9
+ .object({
10
+ provider: z.enum(['auto', 'local', 'builtin', 'none']).default('auto'),
11
+ /**
12
+ * Ceiling on how many vectors a brute-force backend will score in one
13
+ * query. Scanning is linear, so this converts an unbounded tail latency
14
+ * into a fixed one: the newest N observations in scope are scored and
15
+ * older ones are reachable through keyword search. Backends with a real
16
+ * vector index (pgvector, Atlas) ignore this.
17
+ */
18
+ maxScanCandidates: z.number().int().positive().default(25000),
19
+ })
20
+ .default({ provider: 'auto', maxScanCandidates: 25000 }),
21
+ capture: z
22
+ .object({
23
+ /** Tools whose invocations are worth remembering. */
24
+ tools: z
25
+ .array(z.string())
26
+ .default(['Edit', 'Write', 'Bash', 'NotebookEdit']),
27
+ /** Glob-ish fragments; matching paths are never persisted. */
28
+ exclude: z
29
+ .array(z.string())
30
+ .default(['.env', 'secrets', 'node_modules', '.git/']),
31
+ maxBodyChars: z.number().int().positive().default(4000),
32
+ })
33
+ // `prefault` rather than `default`: zod 4 requires a `default` to satisfy
34
+ // the full output type, so `{}` is rejected even though every field below
35
+ // supplies its own default. `prefault` substitutes on the input side and
36
+ // lets those field defaults fill the object in.
37
+ .prefault({}),
38
+ inject: z
39
+ .object({
40
+ /** Session summaries pulled in at SessionStart. */
41
+ sessions: z.number().int().nonnegative().default(5),
42
+ /** Hard ceiling on SessionStart context, in characters. */
43
+ maxChars: z.number().int().positive().default(6000),
44
+ /**
45
+ * Search memory on every prompt and inject matching titles.
46
+ * Set false to fall back to tool-only recall, where Claude decides.
47
+ */
48
+ perPrompt: z.boolean().default(true),
49
+ /** How many titles a per-prompt injection may surface. */
50
+ promptResults: z.number().int().positive().max(10).default(4),
51
+ /** Character ceiling for the per-prompt block. Roughly 4 chars a token. */
52
+ promptMaxChars: z.number().int().positive().default(500),
53
+ /**
54
+ * How many top matches to inject in full rather than as a title.
55
+ *
56
+ * Titles alone require the agent to decide to call get_observations,
57
+ * which reintroduces exactly the "it might not bother" failure that
58
+ * automatic injection exists to remove. Expanding the single best match
59
+ * delivers the reasoning without a round trip.
60
+ */
61
+ expandTop: z.number().int().min(0).max(3).default(1),
62
+ /** Character ceiling for each expanded body. */
63
+ expandMaxChars: z.number().int().positive().default(900),
64
+ })
65
+ .prefault({}),
66
+ });
@@ -0,0 +1,22 @@
1
+ import type { Config } from './config/index.js';
2
+ import type { Embedder } from './embed/index.js';
3
+ import { SearchService } from './search/index.js';
4
+ import type { MemoryStore } from './store/adapter.js';
5
+ export interface RecallContext {
6
+ config: Config;
7
+ store: MemoryStore;
8
+ /** Resolves the embedder, constructing it on first use. */
9
+ embedder(): Promise<Embedder>;
10
+ search: SearchService;
11
+ close(): Promise<void>;
12
+ }
13
+ /**
14
+ * Single composition root. Everything else takes its dependencies as
15
+ * constructor arguments, which keeps the units testable with fakes.
16
+ *
17
+ * The embedder is created lazily because `provider: auto` probes the model
18
+ * with a real inference call to decide whether it works. That probe is the
19
+ * single most expensive thing in a hook, and hooks that never embed (a trivial
20
+ * prompt, a status query) should not pay for it.
21
+ */
22
+ export declare function createContext(overrides?: Partial<Config>): Promise<RecallContext>;
@@ -0,0 +1,25 @@
1
+ import { loadConfig } from './config/index.js';
2
+ import { createEmbedder } from './embed/index.js';
3
+ import { SearchService } from './search/index.js';
4
+ import { createStore } from './store/index.js';
5
+ /**
6
+ * Single composition root. Everything else takes its dependencies as
7
+ * constructor arguments, which keeps the units testable with fakes.
8
+ *
9
+ * The embedder is created lazily because `provider: auto` probes the model
10
+ * with a real inference call to decide whether it works. That probe is the
11
+ * single most expensive thing in a hook, and hooks that never embed (a trivial
12
+ * prompt, a status query) should not pay for it.
13
+ */
14
+ export async function createContext(overrides) {
15
+ const config = { ...loadConfig(), ...overrides };
16
+ const store = await createStore(config.database);
17
+ await store.init();
18
+ let pending = null;
19
+ const embedder = () => {
20
+ pending ??= createEmbedder(config.embeddings.provider);
21
+ return pending;
22
+ };
23
+ const search = new SearchService(store, embedder, config.embeddings.maxScanCandidates);
24
+ return { config, store, embedder, search, close: () => store.close() };
25
+ }
@@ -0,0 +1,20 @@
1
+ import type { Embedder } from './embedder.js';
2
+ /**
3
+ * Zero-dependency embedder using the hashing trick over word and character
4
+ * n-grams. Installs nothing, downloads nothing, runs in microseconds.
5
+ *
6
+ * Honest about what this is: it captures lexical and morphological similarity,
7
+ * not meaning. "reconnect" matches "reconnecting" and survives typos, which
8
+ * plain FTS5 token matching does not. It will NOT match "car" to "automobile"
9
+ * the way a real sentence-transformer does.
10
+ *
11
+ * Its job is to be the floor, so that zero-config installs get fuzzy recall
12
+ * instead of nothing when the ONNX model is unavailable.
13
+ */
14
+ export declare class BuiltinEmbedder implements Embedder {
15
+ readonly id = "builtin-hashing";
16
+ readonly dimensions = 256;
17
+ readonly minRelevance = 0.18;
18
+ embed(texts: string[]): Promise<number[][]>;
19
+ private vectorize;
20
+ }
@@ -0,0 +1,66 @@
1
+ import { normalize } from './embedder.js';
2
+ const DIMENSIONS = 256;
3
+ /**
4
+ * Zero-dependency embedder using the hashing trick over word and character
5
+ * n-grams. Installs nothing, downloads nothing, runs in microseconds.
6
+ *
7
+ * Honest about what this is: it captures lexical and morphological similarity,
8
+ * not meaning. "reconnect" matches "reconnecting" and survives typos, which
9
+ * plain FTS5 token matching does not. It will NOT match "car" to "automobile"
10
+ * the way a real sentence-transformer does.
11
+ *
12
+ * Its job is to be the floor, so that zero-config installs get fuzzy recall
13
+ * instead of nothing when the ONNX model is unavailable.
14
+ */
15
+ export class BuiltinEmbedder {
16
+ id = 'builtin-hashing';
17
+ dimensions = DIMENSIONS;
18
+ // Measured: unrelated queries top out at 0.135, related start at 0.235.
19
+ minRelevance = 0.18;
20
+ async embed(texts) {
21
+ return texts.map((text) => this.vectorize(text));
22
+ }
23
+ vectorize(text) {
24
+ const vector = new Array(DIMENSIONS).fill(0);
25
+ const words = text
26
+ .toLowerCase()
27
+ .split(/[^a-z0-9]+/i)
28
+ .filter((word) => word.length > 1);
29
+ for (const word of words) {
30
+ // Whole word carries the most signal.
31
+ add(vector, `w:${word}`, 1);
32
+ // Character trigrams give partial credit for shared stems and typos.
33
+ for (const gram of trigrams(word))
34
+ add(vector, `g:${gram}`, 0.35);
35
+ }
36
+ // Adjacent word pairs retain a little word order.
37
+ for (let i = 1; i < words.length; i += 1) {
38
+ add(vector, `b:${words[i - 1]}_${words[i]}`, 0.5);
39
+ }
40
+ return normalize(vector);
41
+ }
42
+ }
43
+ function add(vector, token, weight) {
44
+ const hash = fnv1a(token);
45
+ const index = hash % DIMENSIONS;
46
+ // Sign from a spare hash bit keeps unrelated collisions from always
47
+ // accumulating constructively.
48
+ const sign = (hash >>> 31) & 1 ? -1 : 1;
49
+ vector[index] = (vector[index] ?? 0) + weight * sign;
50
+ }
51
+ function trigrams(word) {
52
+ const padded = `^${word}$`;
53
+ const grams = [];
54
+ for (let i = 0; i + 3 <= padded.length; i += 1) {
55
+ grams.push(padded.slice(i, i + 3));
56
+ }
57
+ return grams;
58
+ }
59
+ function fnv1a(text) {
60
+ let hash = 0x811c9dc5;
61
+ for (let i = 0; i < text.length; i += 1) {
62
+ hash ^= text.charCodeAt(i);
63
+ hash = Math.imul(hash, 0x01000193) >>> 0;
64
+ }
65
+ return hash >>> 0;
66
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Turns text into a normalized vector. Implementations must return unit-length
3
+ * vectors so downstream similarity is a plain dot product.
4
+ */
5
+ export interface Embedder {
6
+ readonly id: string;
7
+ readonly dimensions: number;
8
+ /**
9
+ * Cosine similarity below which a match is indistinguishable from noise.
10
+ *
11
+ * This belongs to the model, not to the search code: different embedding
12
+ * spaces have wildly different baselines. Measured on this codebase, the
13
+ * builtin hashing embedder scores unrelated text up to 0.135 and related
14
+ * text from 0.235, so its floor sits in that gap. Sentence transformers
15
+ * have a much higher baseline and need a correspondingly higher floor.
16
+ */
17
+ readonly minRelevance: number;
18
+ embed(texts: string[]): Promise<number[][]>;
19
+ }
20
+ /** Used when embeddings are disabled. Search falls back to keyword-only. */
21
+ export declare class NoopEmbedder implements Embedder {
22
+ readonly id = "none";
23
+ readonly dimensions = 0;
24
+ readonly minRelevance = 0;
25
+ embed(texts: string[]): Promise<number[][]>;
26
+ }
27
+ export declare function normalize(vector: number[]): number[];
@@ -0,0 +1,18 @@
1
+ /** Used when embeddings are disabled. Search falls back to keyword-only. */
2
+ export class NoopEmbedder {
3
+ id = 'none';
4
+ dimensions = 0;
5
+ minRelevance = 0;
6
+ async embed(texts) {
7
+ return texts.map(() => []);
8
+ }
9
+ }
10
+ export function normalize(vector) {
11
+ let sum = 0;
12
+ for (const value of vector)
13
+ sum += value * value;
14
+ const magnitude = Math.sqrt(sum);
15
+ if (magnitude === 0)
16
+ return vector;
17
+ return vector.map((value) => value / magnitude);
18
+ }
@@ -0,0 +1,15 @@
1
+ import type { Embedder } from './embedder.js';
2
+ export type { Embedder } from './embedder.js';
3
+ export { NoopEmbedder, normalize } from './embedder.js';
4
+ export { BuiltinEmbedder } from './builtin.js';
5
+ export type EmbeddingProvider = 'auto' | 'local' | 'builtin' | 'none';
6
+ /**
7
+ * `auto` is the default and the reason zero-config installs still get fuzzy
8
+ * recall: it prefers the real sentence-transformer, but a missing or broken
9
+ * ONNX runtime silently falls back to the builtin rather than leaving the
10
+ * user with keyword-only search and no explanation.
11
+ *
12
+ * The probe runs one real embedding, because importing the module succeeds in
13
+ * cases where the native backend still fails at inference time.
14
+ */
15
+ export declare function createEmbedder(provider: EmbeddingProvider): Promise<Embedder>;
@@ -0,0 +1,39 @@
1
+ import { NoopEmbedder } from './embedder.js';
2
+ import { BuiltinEmbedder } from './builtin.js';
3
+ export { NoopEmbedder, normalize } from './embedder.js';
4
+ export { BuiltinEmbedder } from './builtin.js';
5
+ /**
6
+ * `auto` is the default and the reason zero-config installs still get fuzzy
7
+ * recall: it prefers the real sentence-transformer, but a missing or broken
8
+ * ONNX runtime silently falls back to the builtin rather than leaving the
9
+ * user with keyword-only search and no explanation.
10
+ *
11
+ * The probe runs one real embedding, because importing the module succeeds in
12
+ * cases where the native backend still fails at inference time.
13
+ */
14
+ export async function createEmbedder(provider) {
15
+ switch (provider) {
16
+ case 'none':
17
+ return new NoopEmbedder();
18
+ case 'builtin':
19
+ return new BuiltinEmbedder();
20
+ case 'local':
21
+ return loadLocal();
22
+ case 'auto':
23
+ return (await tryLoadLocal()) ?? new BuiltinEmbedder();
24
+ }
25
+ }
26
+ async function loadLocal() {
27
+ const { LocalEmbedder } = await import('./local.js');
28
+ return new LocalEmbedder();
29
+ }
30
+ async function tryLoadLocal() {
31
+ try {
32
+ const embedder = await loadLocal();
33
+ const [probe] = await embedder.embed(['probe']);
34
+ return probe && probe.length > 0 ? embedder : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
@@ -0,0 +1,17 @@
1
+ import type { Embedder } from './embedder.js';
2
+ /**
3
+ * all-MiniLM-L6-v2 running locally through transformers.js. No API key, no
4
+ * per-token cost, and observations never leave the machine. The model (~25MB)
5
+ * downloads once on first use and is cached by the library thereafter.
6
+ *
7
+ * The pipeline is loaded lazily and memoized: importing this module must stay
8
+ * cheap because hook scripts import it on every tool call.
9
+ */
10
+ export declare class LocalEmbedder implements Embedder {
11
+ readonly id = "Xenova/all-MiniLM-L6-v2";
12
+ readonly dimensions = 384;
13
+ readonly minRelevance = 0.35;
14
+ private pipelinePromise;
15
+ embed(texts: string[]): Promise<number[][]>;
16
+ private load;
17
+ }
@@ -0,0 +1,41 @@
1
+ import { normalize } from './embedder.js';
2
+ /**
3
+ * all-MiniLM-L6-v2 running locally through transformers.js. No API key, no
4
+ * per-token cost, and observations never leave the machine. The model (~25MB)
5
+ * downloads once on first use and is cached by the library thereafter.
6
+ *
7
+ * The pipeline is loaded lazily and memoized: importing this module must stay
8
+ * cheap because hook scripts import it on every tool call.
9
+ */
10
+ export class LocalEmbedder {
11
+ id = 'Xenova/all-MiniLM-L6-v2';
12
+ dimensions = 384;
13
+ // MiniLM packs unrelated sentence pairs around 0.1-0.3 and related pairs
14
+ // above 0.4, so its noise floor sits well above the builtin's.
15
+ minRelevance = 0.35;
16
+ pipelinePromise = null;
17
+ async embed(texts) {
18
+ if (texts.length === 0)
19
+ return [];
20
+ const extract = await this.load();
21
+ const output = await extract(texts, { pooling: 'mean', normalize: true });
22
+ return output.tolist().map(normalize);
23
+ }
24
+ load() {
25
+ this.pipelinePromise ??= (async () => {
26
+ let transformers;
27
+ try {
28
+ // Widened specifier: the package is an optional peer and may be absent
29
+ // at build time, so TypeScript must not try to resolve it.
30
+ transformers = (await import('@xenova/transformers'));
31
+ }
32
+ catch {
33
+ throw new Error('Local embeddings need @xenova/transformers. ' +
34
+ 'Run: npm install @xenova/transformers, or set embeddings.provider to "none".');
35
+ }
36
+ transformers.env.allowLocalModels = false;
37
+ return (await transformers.pipeline('feature-extraction', this.id));
38
+ })();
39
+ return this.pipelinePromise;
40
+ }
41
+ }
@@ -0,0 +1,21 @@
1
+ /** Shape of the JSON Claude Code writes to a hook's stdin. */
2
+ export interface HookPayload {
3
+ session_id?: string;
4
+ cwd?: string;
5
+ /** Claude Code passes the session's JSONL transcript path directly. */
6
+ transcript_path?: string;
7
+ hook_event_name?: string;
8
+ tool_name?: string;
9
+ tool_input?: Record<string, unknown>;
10
+ tool_response?: unknown;
11
+ prompt?: string;
12
+ }
13
+ export declare function readPayload(): Promise<HookPayload>;
14
+ /**
15
+ * Hooks run on the critical path of the agent loop. A memory layer that breaks
16
+ * the user's session is worse than one that forgets, so every failure is
17
+ * swallowed and reported on stderr, never as a non-zero exit.
18
+ */
19
+ export declare function runHook(fn: () => Promise<void>): Promise<void>;
20
+ /** Text written to stdout is injected into the agent's context. */
21
+ export declare function emitContext(text: string): void;
@@ -0,0 +1,33 @@
1
+ export async function readPayload() {
2
+ const chunks = [];
3
+ for await (const chunk of process.stdin)
4
+ chunks.push(Buffer.from(chunk));
5
+ const raw = Buffer.concat(chunks).toString('utf8').trim();
6
+ if (raw.length === 0)
7
+ return {};
8
+ try {
9
+ return JSON.parse(raw);
10
+ }
11
+ catch {
12
+ return {};
13
+ }
14
+ }
15
+ /**
16
+ * Hooks run on the critical path of the agent loop. A memory layer that breaks
17
+ * the user's session is worse than one that forgets, so every failure is
18
+ * swallowed and reported on stderr, never as a non-zero exit.
19
+ */
20
+ export async function runHook(fn) {
21
+ try {
22
+ await fn();
23
+ }
24
+ catch (error) {
25
+ process.stderr.write(`[claude-db] ${error instanceof Error ? error.message : String(error)}\n`);
26
+ }
27
+ process.exit(0);
28
+ }
29
+ /** Text written to stdout is injected into the agent's context. */
30
+ export function emitContext(text) {
31
+ if (text.trim().length > 0)
32
+ process.stdout.write(text);
33
+ }
@@ -0,0 +1,20 @@
1
+ import type { Observation, ObservationIndexEntry } from '../types.js';
2
+ /**
3
+ * Decides whether a prompt is worth a memory lookup at all.
4
+ *
5
+ * This runs before the query, so a cheap reject here saves the entire search.
6
+ * The bar is deliberately low: two content words. The goal is to skip
7
+ * conversational filler, not to predict relevance, which is what search is for.
8
+ */
9
+ export declare function isSearchable(prompt: string): boolean;
10
+ /**
11
+ * Renders the block injected above a user prompt.
12
+ *
13
+ * Titles only, no bodies. The point is to tell Claude that relevant history
14
+ * exists and give it the ids to expand, not to pre-load the history itself.
15
+ * Pre-loading bodies is what makes naive memory tools expensive.
16
+ *
17
+ * Returns null when there is nothing worth saying, so the caller emits
18
+ * nothing at all rather than an empty container.
19
+ */
20
+ export declare function renderPromptContext(entries: ObservationIndexEntry[], maxChars: number, expanded?: Observation[], expandMaxChars?: number): string | null;
@@ -0,0 +1,84 @@
1
+ import { toShortId } from '../util/shortid.js';
2
+ /**
3
+ * Prompts that carry no retrievable intent. Searching memory for "ok" or
4
+ * "continue" wastes a query and, worse, risks injecting unrelated context that
5
+ * teaches the reader to ignore the memory block entirely.
6
+ */
7
+ const TRIVIAL = new Set([
8
+ 'ok', 'okay', 'yes', 'no', 'yep', 'nope', 'sure', 'thanks', 'thank you',
9
+ 'continue', 'go on', 'go ahead', 'next', 'stop', 'wait', 'done', 'good',
10
+ 'nice', 'perfect', 'great', 'do it', 'proceed', 'retry', 'again', 'fix it',
11
+ ]);
12
+ /** Tokens that appear in almost every prompt and cannot discriminate. */
13
+ const NOISE = new Set([
14
+ 'the', 'and', 'for', 'this', 'that', 'with', 'you', 'can', 'please', 'now',
15
+ 'what', 'why', 'how', 'when', 'where', 'are', 'was', 'were', 'have', 'has',
16
+ 'not', '但', 'let', 'make', 'get', 'add', 'use', 'need', 'want', 'should',
17
+ ]);
18
+ /**
19
+ * Decides whether a prompt is worth a memory lookup at all.
20
+ *
21
+ * This runs before the query, so a cheap reject here saves the entire search.
22
+ * The bar is deliberately low: two content words. The goal is to skip
23
+ * conversational filler, not to predict relevance, which is what search is for.
24
+ */
25
+ export function isSearchable(prompt) {
26
+ const normalized = prompt.trim().toLowerCase();
27
+ if (normalized.length < 8)
28
+ return false;
29
+ if (TRIVIAL.has(normalized.replace(/[.!?]+$/, '')))
30
+ return false;
31
+ const content = normalized
32
+ .split(/[^a-z0-9_]+/i)
33
+ .filter((word) => word.length > 2 && !NOISE.has(word));
34
+ return content.length >= 2;
35
+ }
36
+ /**
37
+ * Renders the block injected above a user prompt.
38
+ *
39
+ * Titles only, no bodies. The point is to tell Claude that relevant history
40
+ * exists and give it the ids to expand, not to pre-load the history itself.
41
+ * Pre-loading bodies is what makes naive memory tools expensive.
42
+ *
43
+ * Returns null when there is nothing worth saying, so the caller emits
44
+ * nothing at all rather than an empty container.
45
+ */
46
+ export function renderPromptContext(entries, maxChars, expanded = [], expandMaxChars = 900) {
47
+ if (entries.length === 0)
48
+ return null;
49
+ const expandedIds = new Set(expanded.map((obs) => obs.id));
50
+ const sections = [];
51
+ // Best match in full. This is the part that answers the question outright
52
+ // instead of telling the agent where it could look.
53
+ for (const obs of expanded) {
54
+ const date = new Date(obs.createdAt).toISOString().slice(0, 10);
55
+ sections.push(`${toShortId(obs.id)} ${obs.kind} ${date} ${obs.title}\n` +
56
+ clip(obs.body, expandMaxChars));
57
+ }
58
+ // Remaining matches stay as pointers, cheap enough to be worth listing.
59
+ const lines = [];
60
+ let budget = maxChars;
61
+ for (const entry of entries) {
62
+ if (expandedIds.has(entry.id))
63
+ continue;
64
+ const date = new Date(entry.createdAt).toISOString().slice(0, 7);
65
+ const line = `${toShortId(entry.id)} ${entry.kind} ${date} ${entry.title}`;
66
+ if (line.length > budget)
67
+ break;
68
+ budget -= line.length + 1;
69
+ lines.push(line);
70
+ }
71
+ if (sections.length === 0 && lines.length === 0)
72
+ return null;
73
+ return [
74
+ '<recalled-memory>',
75
+ ...sections,
76
+ ...(lines.length > 0 ? [lines.join('\n')] : []),
77
+ '</recalled-memory>',
78
+ 'Prior work on this project. Expand any listed id with get_observations ' +
79
+ 'before asking the user to re-explain.',
80
+ ].join('\n');
81
+ }
82
+ function clip(text, max) {
83
+ return text.length <= max ? text : `${text.slice(0, max)}\n... [truncated]`;
84
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import { flushSession } from '../capture/index.js';
3
+ import { createContext } from '../context.js';
4
+ import { readPayload, runHook } from './payload.js';
5
+ import { resolveProject } from '../util/project.js';
6
+ import { silenceSqliteWarning } from '../util/warnings.js';
7
+ silenceSqliteWarning();
8
+ /**
9
+ * SessionEnd: final flush, and mark the session closed.
10
+ *
11
+ * This is no longer the only chance to capture anything. Prompts flush as they
12
+ * happen, so a session that never reaches this hook has already been recorded.
13
+ * All this adds is the tail of the last turn and an end timestamp.
14
+ */
15
+ await runHook(async () => {
16
+ const payload = await readPayload();
17
+ const sessionId = payload.session_id;
18
+ if (!sessionId)
19
+ return;
20
+ const project = resolveProject(payload.cwd);
21
+ const ctx = await createContext();
22
+ try {
23
+ const result = await flushSession(ctx, sessionId, project, payload.transcript_path);
24
+ await ctx.store.upsertSession({
25
+ id: sessionId,
26
+ project,
27
+ startedAt: Date.now(),
28
+ endedAt: Date.now(),
29
+ ...(result.summary ? { summary: result.summary } : {}),
30
+ });
31
+ }
32
+ finally {
33
+ await ctx.close();
34
+ }
35
+ });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import { createContext } from '../context.js';
3
+ import { emitContext, readPayload, runHook } from './payload.js';
4
+ import { resolveProject } from '../util/project.js';
5
+ import { silenceSqliteWarning } from '../util/warnings.js';
6
+ silenceSqliteWarning();
7
+ /**
8
+ * SessionStart: prime the agent with what past sessions concluded.
9
+ *
10
+ * Only session summaries are injected, never raw observations. Summaries are
11
+ * dense and few; observations are numerous and are better pulled on demand
12
+ * through the MCP tools once the agent knows what it is looking for.
13
+ */
14
+ await runHook(async () => {
15
+ const payload = await readPayload();
16
+ const project = resolveProject(payload.cwd);
17
+ const ctx = await createContext();
18
+ try {
19
+ const sessions = await ctx.store.recentSessions(project, ctx.config.inject.sessions);
20
+ // One line on an empty database, so "installed but no history yet" is
21
+ // distinguishable from "never installed" without leaving the session.
22
+ // Costs ~12 tokens and disappears permanently after the first real session.
23
+ if (sessions.length === 0) {
24
+ emitContext('<project-memory>none yet for this project; ' +
25
+ 'it is recorded when a session ends</project-memory>\n');
26
+ return;
27
+ }
28
+ const lines = ['<project-memory>'];
29
+ let budget = ctx.config.inject.maxChars;
30
+ for (const session of sessions) {
31
+ const when = new Date(session.startedAt).toISOString().slice(0, 10);
32
+ const line = `- [${when}] ${session.summary ?? ''}`;
33
+ if (line.length > budget)
34
+ break;
35
+ budget -= line.length;
36
+ lines.push(line);
37
+ }
38
+ lines.push('</project-memory>');
39
+ lines.push('Search this project\'s full history with the memory MCP tools before ' +
40
+ 'asking the user to re-explain prior decisions.');
41
+ emitContext(`${lines.join('\n')}\n`);
42
+ }
43
+ finally {
44
+ await ctx.close();
45
+ }
46
+ });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};