claude-db 0.4.0 → 0.5.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 (203) hide show
  1. package/CHANGELOG.md +399 -0
  2. package/README.md +62 -94
  3. package/dist/capture/command.d.ts +0 -14
  4. package/dist/capture/command.js +0 -23
  5. package/dist/capture/flush.d.ts +1 -50
  6. package/dist/capture/flush.js +4 -63
  7. package/dist/capture/git.js +0 -20
  8. package/dist/capture/identity.d.ts +0 -17
  9. package/dist/capture/identity.js +1 -21
  10. package/dist/capture/index.d.ts +1 -0
  11. package/dist/capture/index.js +1 -0
  12. package/dist/capture/manual.d.ts +0 -19
  13. package/dist/capture/manual.js +0 -0
  14. package/dist/capture/progress.d.ts +4 -0
  15. package/dist/capture/progress.js +33 -0
  16. package/dist/capture/transcript.d.ts +0 -45
  17. package/dist/capture/transcript.js +4 -70
  18. package/dist/capture/turn-extractor.d.ts +0 -15
  19. package/dist/capture/turn-extractor.js +1 -104
  20. package/dist/cli/args.d.ts +4 -0
  21. package/dist/cli/args.js +16 -0
  22. package/dist/cli/commands/doctor.d.ts +1 -0
  23. package/dist/cli/commands/doctor.js +76 -0
  24. package/dist/cli/commands/graph.d.ts +2 -0
  25. package/dist/cli/commands/graph.js +93 -0
  26. package/dist/cli/commands/insight.d.ts +3 -0
  27. package/dist/cli/commands/insight.js +129 -0
  28. package/dist/cli/commands/maintain.d.ts +3 -0
  29. package/dist/cli/commands/maintain.js +77 -0
  30. package/dist/cli/commands/memory.d.ts +3 -0
  31. package/dist/cli/commands/memory.js +77 -0
  32. package/dist/cli/commands/seed.d.ts +1 -0
  33. package/dist/cli/commands/seed.js +43 -0
  34. package/dist/cli/commands/setup.d.ts +4 -0
  35. package/dist/cli/commands/setup.js +156 -0
  36. package/dist/cli/commands/sync.d.ts +1 -0
  37. package/dist/cli/commands/sync.js +95 -0
  38. package/dist/cli/commands/transfer.d.ts +9 -0
  39. package/dist/cli/commands/transfer.js +129 -0
  40. package/dist/cli/commands/use.d.ts +1 -0
  41. package/dist/cli/commands/use.js +90 -0
  42. package/dist/cli/constants.d.ts +2 -0
  43. package/dist/cli/constants.js +4 -0
  44. package/dist/cli/files.d.ts +4 -0
  45. package/dist/cli/files.js +33 -0
  46. package/dist/cli/index.js +15 -1080
  47. package/dist/cli/install.d.ts +1 -59
  48. package/dist/cli/install.js +5 -193
  49. package/dist/cli/instructions.d.ts +5 -0
  50. package/dist/cli/instructions.js +55 -0
  51. package/dist/cli/paths.d.ts +5 -0
  52. package/dist/cli/paths.js +19 -0
  53. package/dist/cli/refresh.d.ts +1 -0
  54. package/dist/cli/refresh.js +25 -0
  55. package/dist/cli/usage.d.ts +1 -0
  56. package/dist/cli/usage.js +39 -0
  57. package/dist/config/load.d.ts +0 -5
  58. package/dist/config/load.js +1 -8
  59. package/dist/config/schema.js +2 -58
  60. package/dist/context.d.ts +0 -10
  61. package/dist/context.js +0 -16
  62. package/dist/embed/builtin.d.ts +0 -12
  63. package/dist/embed/builtin.js +0 -20
  64. package/dist/embed/embedder.d.ts +0 -14
  65. package/dist/embed/embedder.js +0 -1
  66. package/dist/embed/index.d.ts +0 -9
  67. package/dist/embed/index.js +0 -9
  68. package/dist/embed/local.d.ts +0 -8
  69. package/dist/embed/local.js +0 -12
  70. package/dist/graph/index.d.ts +7 -0
  71. package/dist/graph/index.js +4 -0
  72. package/dist/graph/languages/ecmascript.d.ts +4 -0
  73. package/dist/graph/languages/ecmascript.js +47 -0
  74. package/dist/graph/languages/go.d.ts +2 -0
  75. package/dist/graph/languages/go.js +15 -0
  76. package/dist/graph/languages/index.d.ts +6 -0
  77. package/dist/graph/languages/index.js +20 -0
  78. package/dist/graph/languages/python.d.ts +2 -0
  79. package/dist/graph/languages/python.js +15 -0
  80. package/dist/graph/languages/rules.d.ts +18 -0
  81. package/dist/graph/languages/rules.js +1 -0
  82. package/dist/graph/languages/rust.d.ts +2 -0
  83. package/dist/graph/languages/rust.js +16 -0
  84. package/dist/graph/parser.d.ts +31 -0
  85. package/dist/graph/parser.js +29 -0
  86. package/dist/graph/query/format.d.ts +2 -0
  87. package/dist/graph/query/format.js +41 -0
  88. package/dist/graph/query/index.d.ts +5 -0
  89. package/dist/graph/query/index.js +4 -0
  90. package/dist/graph/query/lookup.d.ts +21 -0
  91. package/dist/graph/query/lookup.js +35 -0
  92. package/dist/graph/query/path.d.ts +2 -0
  93. package/dist/graph/query/path.js +48 -0
  94. package/dist/graph/query/refresh.d.ts +2 -0
  95. package/dist/graph/query/refresh.js +21 -0
  96. package/dist/graph/scan/extract.d.ts +15 -0
  97. package/dist/graph/scan/extract.js +101 -0
  98. package/dist/graph/scan/files.d.ts +12 -0
  99. package/dist/graph/scan/files.js +51 -0
  100. package/dist/graph/scan/index.d.ts +18 -0
  101. package/dist/graph/scan/index.js +44 -0
  102. package/dist/graph/scan/resolve.d.ts +3 -0
  103. package/dist/graph/scan/resolve.js +48 -0
  104. package/dist/hooks/payload.d.ts +0 -8
  105. package/dist/hooks/payload.js +0 -6
  106. package/dist/hooks/relevance.d.ts +0 -17
  107. package/dist/hooks/relevance.js +55 -38
  108. package/dist/hooks/session-end.js +0 -11
  109. package/dist/hooks/session-start.js +33 -14
  110. package/dist/hooks/user-prompt.js +0 -18
  111. package/dist/mcp/render.d.ts +0 -20
  112. package/dist/mcp/render.js +0 -39
  113. package/dist/mcp/server.js +50 -27
  114. package/dist/search/rank.d.ts +0 -14
  115. package/dist/search/rank.js +0 -16
  116. package/dist/search/service.d.ts +1 -32
  117. package/dist/search/service.js +1 -36
  118. package/dist/store/adapter.d.ts +11 -44
  119. package/dist/store/adapter.js +1 -12
  120. package/dist/store/index.d.ts +0 -11
  121. package/dist/store/index.js +0 -11
  122. package/dist/store/mongo/docs.d.ts +61 -0
  123. package/dist/store/mongo/docs.js +106 -0
  124. package/dist/store/mongo/driver.d.ts +1 -15
  125. package/dist/store/mongo/driver.js +0 -15
  126. package/dist/store/mongo/filters.d.ts +6 -0
  127. package/dist/store/mongo/filters.js +18 -0
  128. package/dist/store/mongo/graph.d.ts +12 -0
  129. package/dist/store/mongo/graph.js +61 -0
  130. package/dist/store/mongo/helpers.d.ts +2 -0
  131. package/dist/store/mongo/helpers.js +8 -0
  132. package/dist/store/mongo/index.d.ts +16 -13
  133. package/dist/store/mongo/index.js +52 -295
  134. package/dist/store/mongo/observations.d.ts +10 -0
  135. package/dist/store/mongo/observations.js +97 -0
  136. package/dist/store/mongo/search.d.ts +6 -0
  137. package/dist/store/mongo/search.js +51 -0
  138. package/dist/store/mongo/sessions.d.ts +6 -0
  139. package/dist/store/mongo/sessions.js +24 -0
  140. package/dist/store/mongo/vectorSearch.d.ts +5 -0
  141. package/dist/store/mongo/vectorSearch.js +57 -0
  142. package/dist/store/postgres/driver.d.ts +19 -0
  143. package/dist/store/postgres/driver.js +13 -0
  144. package/dist/store/postgres/filters.d.ts +2 -0
  145. package/dist/store/postgres/filters.js +22 -0
  146. package/dist/store/postgres/graph.d.ts +11 -0
  147. package/dist/store/postgres/graph.js +115 -0
  148. package/dist/store/postgres/index.d.ts +20 -33
  149. package/dist/store/postgres/index.js +43 -428
  150. package/dist/store/postgres/insert.d.ts +3 -0
  151. package/dist/store/postgres/insert.js +59 -0
  152. package/dist/store/postgres/meta.d.ts +10 -0
  153. package/dist/store/postgres/meta.js +54 -0
  154. package/dist/store/postgres/observations.d.ts +10 -0
  155. package/dist/store/postgres/observations.js +139 -0
  156. package/dist/store/postgres/rows.d.ts +6 -0
  157. package/dist/store/postgres/rows.js +74 -0
  158. package/dist/store/postgres/schema.d.ts +3 -0
  159. package/dist/store/postgres/schema.js +84 -0
  160. package/dist/store/postgres/search.d.ts +3 -0
  161. package/dist/store/postgres/search.js +20 -0
  162. package/dist/store/postgres/sessions.d.ts +5 -0
  163. package/dist/store/postgres/sessions.js +26 -0
  164. package/dist/store/postgres/vectorSearch.d.ts +3 -0
  165. package/dist/store/postgres/vectorSearch.js +21 -0
  166. package/dist/store/sqlite/filters.d.ts +9 -0
  167. package/dist/store/sqlite/filters.js +77 -0
  168. package/dist/store/sqlite/graph.d.ts +11 -0
  169. package/dist/store/sqlite/graph.js +100 -0
  170. package/dist/store/sqlite/index.d.ts +12 -10
  171. package/dist/store/sqlite/index.js +41 -379
  172. package/dist/store/sqlite/observations.d.ts +10 -0
  173. package/dist/store/sqlite/observations.js +128 -0
  174. package/dist/store/sqlite/rows.d.ts +8 -0
  175. package/dist/store/sqlite/rows.js +84 -0
  176. package/dist/store/sqlite/schema.sql +42 -2
  177. package/dist/store/sqlite/search.d.ts +5 -0
  178. package/dist/store/sqlite/search.js +86 -0
  179. package/dist/store/sqlite/sessions.d.ts +5 -0
  180. package/dist/store/sqlite/sessions.js +21 -0
  181. package/dist/types.d.ts +47 -40
  182. package/dist/types.js +0 -4
  183. package/dist/update.d.ts +0 -20
  184. package/dist/update.js +4 -29
  185. package/dist/usages/find.d.ts +2 -8
  186. package/dist/usages/find.js +58 -45
  187. package/dist/usages/index.d.ts +1 -1
  188. package/dist/usages/index.js +1 -1
  189. package/dist/util/project.d.ts +0 -12
  190. package/dist/util/project.js +0 -24
  191. package/dist/util/scope.d.ts +0 -9
  192. package/dist/util/scope.js +0 -9
  193. package/dist/util/shortid.d.ts +0 -5
  194. package/dist/util/shortid.js +1 -19
  195. package/dist/util/snippet.d.ts +0 -26
  196. package/dist/util/snippet.js +0 -30
  197. package/dist/util/vector.d.ts +0 -12
  198. package/dist/util/vector.js +0 -12
  199. package/dist/util/warnings.d.ts +0 -11
  200. package/dist/util/warnings.js +0 -11
  201. package/docs/how-it-works.md +183 -0
  202. package/package.json +14 -3
  203. package/skills/cdb-scan/SKILL.md +31 -6
@@ -0,0 +1,101 @@
1
+ import { observationId } from '../../capture/identity.js';
2
+ import { redact } from '../../capture/turn-extractor.js';
3
+ import { languageHandle, loadParser } from '../parser.js';
4
+ const CALLABLE = new Set(['function', 'method', 'class']);
5
+ export function symbolId(project, file, name, kind) {
6
+ return observationId('graph', 0, `${project}\0${file}\0${name}\0${kind}`);
7
+ }
8
+ function resolveField(node, path) {
9
+ let current = node;
10
+ for (const name of path) {
11
+ if (!current)
12
+ return null;
13
+ current = current.field(name);
14
+ }
15
+ return current;
16
+ }
17
+ function unquote(text) {
18
+ return text.replace(/^['"`]|['"`]$/g, '');
19
+ }
20
+ function enclosing(line, spans) {
21
+ let best = null;
22
+ let fallback = null;
23
+ for (const span of spans) {
24
+ if (line < span.start || line > span.end)
25
+ continue;
26
+ const width = span.end - span.start;
27
+ if (CALLABLE.has(span.symbol.kind)) {
28
+ if (!best || width < best.end - best.start)
29
+ best = span;
30
+ }
31
+ else if (!fallback || width < fallback.end - fallback.start) {
32
+ fallback = span;
33
+ }
34
+ }
35
+ return (best ?? fallback)?.symbol ?? null;
36
+ }
37
+ export function extractFile(file, project) {
38
+ const parser = loadParser();
39
+ const root = parser.parse(languageHandle(parser, file.spec.id), file.source).root();
40
+ const lines = file.source.split('\n');
41
+ const symbols = [];
42
+ const spans = [];
43
+ for (const rule of file.spec.definitions) {
44
+ for (const node of root.findAll({ rule: { kind: rule.kind } })) {
45
+ const named = resolveField(node, rule.field);
46
+ const name = named?.text();
47
+ if (!named || !name)
48
+ continue;
49
+ const line = named.range().start.line + 1;
50
+ const symbol = {
51
+ id: symbolId(project, file.path, name, rule.symbol),
52
+ project,
53
+ name,
54
+ kind: rule.symbol,
55
+ file: file.path,
56
+ line,
57
+ lang: file.spec.label,
58
+ signature: redact((lines[line - 1] ?? '').trim()).slice(0, 200),
59
+ };
60
+ symbols.push(symbol);
61
+ spans.push({
62
+ start: node.range().start.line + 1,
63
+ end: node.range().end.line + 1,
64
+ symbol,
65
+ });
66
+ }
67
+ }
68
+ const references = [];
69
+ for (const span of spans) {
70
+ const owner = enclosing(span.start, spans.filter((other) => other.symbol.id !== span.symbol.id));
71
+ if (!owner)
72
+ continue;
73
+ references.push({
74
+ file: file.path,
75
+ name: span.symbol.name,
76
+ relation: 'defines',
77
+ line: span.start,
78
+ from: owner,
79
+ });
80
+ }
81
+ for (const rule of file.spec.references) {
82
+ for (const node of root.findAll({ rule: { kind: rule.kind } })) {
83
+ const target = rule.field.length === 0 ? node : resolveField(node, rule.field);
84
+ const raw = target?.text();
85
+ if (!target || !raw)
86
+ continue;
87
+ const name = unquote(raw.trim());
88
+ if (!name || /\s/.test(name))
89
+ continue;
90
+ const line = target.range().start.line + 1;
91
+ references.push({
92
+ file: file.path,
93
+ name,
94
+ relation: rule.relation,
95
+ line,
96
+ from: enclosing(line, spans),
97
+ });
98
+ }
99
+ }
100
+ return { symbols, references };
101
+ }
@@ -0,0 +1,12 @@
1
+ import type { LanguageSpec } from '../languages/index.js';
2
+ export interface SourceFile {
3
+ path: string;
4
+ spec: LanguageSpec;
5
+ source: string;
6
+ hash: string;
7
+ }
8
+ export declare function hashOf(bytes: Buffer): string;
9
+ export declare function listFiles(root: string): string[];
10
+ export declare function sourceFiles(root: string): string[];
11
+ export declare function readSource(root: string, path: string): SourceFile | null;
12
+ export declare function currentHashes(root: string): Map<string, string>;
@@ -0,0 +1,51 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { languageFor } from '../languages/index.js';
6
+ const MAX_BUFFER = 64 * 1024 * 1024;
7
+ const MAX_FILE_BYTES = 1024 * 1024;
8
+ export function hashOf(bytes) {
9
+ return createHash('sha256').update(bytes).digest('hex').slice(0, 32);
10
+ }
11
+ export function listFiles(root) {
12
+ const list = (args) => execFileSync('git', ['-C', root, ...args], {
13
+ encoding: 'utf8',
14
+ maxBuffer: MAX_BUFFER,
15
+ })
16
+ .split('\0')
17
+ .filter((path) => path.length > 0);
18
+ const tracked = list(['ls-files', '-z']);
19
+ const untracked = list(['ls-files', '-z', '--others', '--exclude-standard']);
20
+ return [...new Set([...tracked, ...untracked])].sort();
21
+ }
22
+ export function sourceFiles(root) {
23
+ return listFiles(root).filter((path) => languageFor(path) !== null);
24
+ }
25
+ export function readSource(root, path) {
26
+ const spec = languageFor(path);
27
+ if (!spec)
28
+ return null;
29
+ let bytes;
30
+ try {
31
+ bytes = readFileSync(join(root, path));
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ if (bytes.length > MAX_FILE_BYTES || bytes.includes(0))
37
+ return null;
38
+ return { path, spec, source: bytes.toString('utf8'), hash: hashOf(bytes) };
39
+ }
40
+ export function currentHashes(root) {
41
+ const hashes = new Map();
42
+ for (const path of sourceFiles(root)) {
43
+ try {
44
+ hashes.set(path, hashOf(readFileSync(join(root, path))));
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ }
50
+ return hashes;
51
+ }
@@ -0,0 +1,18 @@
1
+ import type { CodeEdge, CodeSymbol, ScannedFile } from '../../types.js';
2
+ export type { SourceFile } from './files.js';
3
+ export { currentHashes, hashOf, listFiles, sourceFiles } from './files.js';
4
+ export interface ScanOptions {
5
+ root: string;
6
+ project: string;
7
+ known: Map<string, string>;
8
+ force?: boolean;
9
+ }
10
+ export interface ScanResult {
11
+ symbols: CodeSymbol[];
12
+ edges: CodeEdge[];
13
+ files: ScannedFile[];
14
+ changed: string[];
15
+ skipped: number;
16
+ unsupported: number;
17
+ }
18
+ export declare function scanRepository(options: ScanOptions): ScanResult;
@@ -0,0 +1,44 @@
1
+ import { loadParser } from '../parser.js';
2
+ import { extractFile } from './extract.js';
3
+ import { listFiles, readSource } from './files.js';
4
+ import { resolveEdges } from './resolve.js';
5
+ export { currentHashes, hashOf, listFiles, sourceFiles } from './files.js';
6
+ export function scanRepository(options) {
7
+ const { root, project, known, force } = options;
8
+ loadParser();
9
+ const result = {
10
+ symbols: [],
11
+ edges: [],
12
+ files: [],
13
+ changed: [],
14
+ skipped: 0,
15
+ unsupported: 0,
16
+ };
17
+ const references = [];
18
+ const scannedAt = Date.now();
19
+ for (const path of listFiles(root)) {
20
+ const file = readSource(root, path);
21
+ if (!file) {
22
+ result.unsupported += 1;
23
+ continue;
24
+ }
25
+ if (!force && known.get(path) === file.hash) {
26
+ result.skipped += 1;
27
+ continue;
28
+ }
29
+ let extracted;
30
+ try {
31
+ extracted = extractFile(file, project);
32
+ }
33
+ catch {
34
+ result.unsupported += 1;
35
+ continue;
36
+ }
37
+ result.symbols.push(...extracted.symbols);
38
+ references.push(...extracted.references);
39
+ result.changed.push(path);
40
+ result.files.push({ project, path, hash: file.hash, scannedAt });
41
+ }
42
+ result.edges = resolveEdges(project, result.symbols, references);
43
+ return result;
44
+ }
@@ -0,0 +1,3 @@
1
+ import type { CodeEdge, CodeSymbol } from '../../types.js';
2
+ import type { Reference } from './extract.js';
3
+ export declare function resolveEdges(project: string, symbols: CodeSymbol[], references: Reference[]): CodeEdge[];
@@ -0,0 +1,48 @@
1
+ import { observationId } from '../../capture/identity.js';
2
+ const SAME_FILE = 1;
3
+ const SINGLE_MATCH = 0.95;
4
+ const AMBIGUOUS_MATCH = 0.85;
5
+ function edgeId(project, file, line, from, to) {
6
+ return observationId('graph', 0, `${project}\0${file}\0${line}\0${from}\0${to}`);
7
+ }
8
+ export function resolveEdges(project, symbols, references) {
9
+ const byName = new Map();
10
+ for (const symbol of symbols) {
11
+ const bucket = byName.get(symbol.name);
12
+ if (bucket)
13
+ bucket.push(symbol);
14
+ else
15
+ byName.set(symbol.name, [symbol]);
16
+ }
17
+ const edges = [];
18
+ for (const reference of references) {
19
+ const candidates = byName.get(reference.name) ?? [];
20
+ const local = candidates.find((candidate) => candidate.file === reference.file);
21
+ const target = local ?? candidates[0];
22
+ let confidence = 'EXTRACTED';
23
+ let score = SAME_FILE;
24
+ if (!local && candidates.length === 1) {
25
+ confidence = 'INFERRED';
26
+ score = SINGLE_MATCH;
27
+ }
28
+ else if (!local && candidates.length > 1) {
29
+ confidence = 'INFERRED';
30
+ score = AMBIGUOUS_MATCH;
31
+ }
32
+ const fromName = reference.from?.name ?? reference.file;
33
+ edges.push({
34
+ id: edgeId(project, reference.file, reference.line, fromName, reference.name),
35
+ project,
36
+ srcId: reference.from?.id ?? '',
37
+ srcName: fromName,
38
+ dstId: target?.id ?? '',
39
+ dstName: reference.name,
40
+ relation: reference.relation,
41
+ confidence,
42
+ score,
43
+ file: reference.file,
44
+ line: reference.line,
45
+ });
46
+ }
47
+ return edges;
48
+ }
@@ -1,8 +1,6 @@
1
- /** Shape of the JSON Claude Code writes to a hook's stdin. */
2
1
  export interface HookPayload {
3
2
  session_id?: string;
4
3
  cwd?: string;
5
- /** Claude Code passes the session's JSONL transcript path directly. */
6
4
  transcript_path?: string;
7
5
  hook_event_name?: string;
8
6
  tool_name?: string;
@@ -11,11 +9,5 @@ export interface HookPayload {
11
9
  prompt?: string;
12
10
  }
13
11
  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
12
  export declare function runHook(fn: () => Promise<void>): Promise<void>;
20
- /** Text written to stdout is injected into the agent's context. */
21
13
  export declare function emitContext(text: string): void;
@@ -12,11 +12,6 @@ export async function readPayload() {
12
12
  return {};
13
13
  }
14
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
15
  export async function runHook(fn) {
21
16
  try {
22
17
  await fn();
@@ -26,7 +21,6 @@ export async function runHook(fn) {
26
21
  }
27
22
  process.exit(0);
28
23
  }
29
- /** Text written to stdout is injected into the agent's context. */
30
24
  export function emitContext(text) {
31
25
  if (text.trim().length > 0)
32
26
  process.stdout.write(text);
@@ -1,20 +1,3 @@
1
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
2
  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
3
  export declare function renderPromptContext(entries: ObservationIndexEntry[], maxChars: number, expanded?: Observation[], expandMaxChars?: number): string | null;
@@ -1,32 +1,63 @@
1
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
2
  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',
3
+ 'ok',
4
+ 'okay',
5
+ 'yes',
6
+ 'no',
7
+ 'yep',
8
+ 'nope',
9
+ 'sure',
10
+ 'thanks',
11
+ 'thank you',
12
+ 'continue',
13
+ 'go on',
14
+ 'go ahead',
15
+ 'next',
16
+ 'stop',
17
+ 'wait',
18
+ 'done',
19
+ 'good',
20
+ 'nice',
21
+ 'perfect',
22
+ 'great',
23
+ 'do it',
24
+ 'proceed',
25
+ 'retry',
26
+ 'again',
27
+ 'fix it',
11
28
  ]);
12
- /** Tokens that appear in almost every prompt and cannot discriminate. */
13
29
  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',
30
+ 'the',
31
+ 'and',
32
+ 'for',
33
+ 'this',
34
+ 'that',
35
+ 'with',
36
+ 'you',
37
+ 'can',
38
+ 'please',
39
+ 'now',
40
+ 'what',
41
+ 'why',
42
+ 'how',
43
+ 'when',
44
+ 'where',
45
+ 'are',
46
+ 'was',
47
+ 'were',
48
+ 'have',
49
+ 'has',
50
+ 'not',
51
+ 'let',
52
+ 'make',
53
+ 'get',
54
+ 'add',
55
+ 'use',
56
+ 'need',
57
+ 'want',
58
+ 'should',
17
59
  ]);
18
- /**
19
- * Scripts written without spaces. "修复登录接口的超时问题" is one token, so the
20
- * two-content-word bar has to be counted in characters instead.
21
- */
22
60
  const DENSE_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu;
23
- /**
24
- * Decides whether a prompt is worth a memory lookup at all.
25
- *
26
- * This runs before the query, so a cheap reject here saves the entire search.
27
- * The bar is deliberately low: two content words. The goal is to skip
28
- * conversational filler, not to predict relevance, which is what search is for.
29
- */
30
61
  export function isSearchable(prompt) {
31
62
  const normalized = prompt.trim().toLowerCase();
32
63
  if (TRIVIAL.has(normalized.replace(/[.!?]+$/, '')))
@@ -40,29 +71,15 @@ export function isSearchable(prompt) {
40
71
  .filter((word) => word.length > 2 && !NOISE.has(word));
41
72
  return content.length >= 2;
42
73
  }
43
- /**
44
- * Renders the block injected above a user prompt.
45
- *
46
- * Titles only, no bodies. The point is to tell Claude that relevant history
47
- * exists and give it the ids to expand, not to pre-load the history itself.
48
- * Pre-loading bodies is what makes naive memory tools expensive.
49
- *
50
- * Returns null when there is nothing worth saying, so the caller emits
51
- * nothing at all rather than an empty container.
52
- */
53
74
  export function renderPromptContext(entries, maxChars, expanded = [], expandMaxChars = 900) {
54
75
  if (entries.length === 0)
55
76
  return null;
56
77
  const expandedIds = new Set(expanded.map((obs) => obs.id));
57
78
  const sections = [];
58
- // Best match in full. This is the part that answers the question outright
59
- // instead of telling the agent where it could look.
60
79
  for (const obs of expanded) {
61
80
  const date = new Date(obs.createdAt).toISOString().slice(0, 10);
62
- sections.push(`${toShortId(obs.id)} ${obs.kind} ${date} ${obs.title}\n` +
63
- clip(obs.body, expandMaxChars));
81
+ sections.push(`${toShortId(obs.id)} ${obs.kind} ${date} ${obs.title}\n` + clip(obs.body, expandMaxChars));
64
82
  }
65
- // Remaining matches stay as pointers, cheap enough to be worth listing.
66
83
  const lines = [];
67
84
  let budget = maxChars;
68
85
  for (const entry of entries) {
@@ -9,13 +9,6 @@ import { readPayload, runHook } from './payload.js';
9
9
  import { resolveProject } from '../util/project.js';
10
10
  import { silenceSqliteWarning } from '../util/warnings.js';
11
11
  silenceSqliteWarning();
12
- /**
13
- * SessionEnd: final flush, and mark the session closed.
14
- *
15
- * This is no longer the only chance to capture anything. Prompts flush as they
16
- * happen, so a session that never reaches this hook has already been recorded.
17
- * All this adds is the tail of the last turn and an end timestamp.
18
- */
19
12
  await runHook(async () => {
20
13
  const payload = await readPayload();
21
14
  const sessionId = payload.session_id;
@@ -33,10 +26,6 @@ await runHook(async () => {
33
26
  ...(result.summary ? { summary: result.summary } : {}),
34
27
  });
35
28
  clearCursor(sessionId);
36
- // At session end rather than session start: `npm install -g` replaces the
37
- // files these hooks import, and this is the moment least likely to have a
38
- // hook running. Detached and unref'd, so the session never waits on the
39
- // network or on npm.
40
29
  if (ctx.config.updates !== 'off' && isDue(readState())) {
41
30
  const cli = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'cli', 'index.js');
42
31
  spawn(process.execPath, [cli, 'update', '--quiet'], {
@@ -4,12 +4,34 @@ import { homedir } from 'node:os';
4
4
  import { dirname, join, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createContext } from '../context.js';
7
+ import { openWork } from '../capture/index.js';
7
8
  import { emitContext, readPayload, runHook } from './payload.js';
8
9
  import { resolveProject } from '../util/project.js';
10
+ import { refreshInstalled } from '../cli/refresh.js';
9
11
  import { updateNotice } from '../update.js';
10
12
  import { silenceSqliteWarning } from '../util/warnings.js';
11
13
  silenceSqliteWarning();
12
14
  const SERVER = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'mcp', 'server.js');
15
+ async function refreshGraphQuietly(store, project) {
16
+ try {
17
+ if ((await store.scannedFiles(project)).length === 0)
18
+ return;
19
+ const { refreshGraph } = await import('../graph/index.js');
20
+ const { repoRootFor } = await import('../usages/index.js');
21
+ await refreshGraph(store, repoRootFor(project), project);
22
+ }
23
+ catch {
24
+ return;
25
+ }
26
+ }
27
+ function refreshInstalledQuietly(project) {
28
+ try {
29
+ refreshInstalled(resolve(dirname(fileURLToPath(import.meta.url)), '..'), project);
30
+ }
31
+ catch {
32
+ return;
33
+ }
34
+ }
13
35
  function mcpRegistered(project) {
14
36
  return [join(project, '.mcp.json'), join(homedir(), '.claude.json')].some((path) => {
15
37
  try {
@@ -20,22 +42,13 @@ function mcpRegistered(project) {
20
42
  }
21
43
  });
22
44
  }
23
- /**
24
- * SessionStart: prime the agent with what past sessions concluded.
25
- *
26
- * Only session summaries are injected, never raw observations. Summaries are
27
- * dense and few; observations are numerous and are better pulled on demand
28
- * through the MCP tools once the agent knows what it is looking for.
29
- */
30
45
  await runHook(async () => {
31
46
  const payload = await readPayload();
32
47
  const project = resolveProject(payload.cwd);
48
+ refreshInstalledQuietly(project);
33
49
  const ctx = await createContext();
34
50
  try {
35
51
  const sessions = await ctx.store.recentSessions(project, ctx.config.inject.sessions);
36
- // One line on an empty database, so "installed but no history yet" is
37
- // distinguishable from "never installed" without leaving the session.
38
- // Costs ~12 tokens and disappears permanently after the first real session.
39
52
  if (sessions.length === 0) {
40
53
  emitContext('<project-memory>none yet for this project; ' +
41
54
  'it is recorded as you work</project-memory>\n');
@@ -51,18 +64,24 @@ await runHook(async () => {
51
64
  budget -= line.length;
52
65
  lines.push(line);
53
66
  }
67
+ const open = await openWork(ctx.store, project);
68
+ if (open.length > 0) {
69
+ lines.push('');
70
+ lines.push('Not committed yet, newest first:');
71
+ for (const obs of open.slice(0, 3)) {
72
+ lines.push(`- ${obs.title}`);
73
+ }
74
+ }
54
75
  lines.push('</project-memory>');
55
- // Only advertise the tools when they are actually registered; pointing the
56
- // agent at an MCP server that was never installed just wastes a turn.
57
76
  if (mcpRegistered(project)) {
58
- lines.push('Search this project\'s full history with the memory MCP tools before ' +
77
+ lines.push("Search this project's full history with the memory MCP tools before " +
59
78
  'asking the user to re-explain prior decisions.');
60
79
  }
61
- // Read from a local file the detached updater wrote; never a live check.
62
80
  const notice = ctx.config.updates === 'off' ? null : updateNotice();
63
81
  if (notice)
64
82
  lines.push(notice);
65
83
  emitContext(`${lines.join('\n')}\n`);
84
+ await refreshGraphQuietly(ctx.store, project);
66
85
  }
67
86
  finally {
68
87
  await ctx.close();
@@ -6,18 +6,6 @@ import { isSearchable, renderPromptContext } from './relevance.js';
6
6
  import { resolveProject } from '../util/project.js';
7
7
  import { silenceSqliteWarning } from '../util/warnings.js';
8
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
9
  await runHook(async () => {
22
10
  const payload = await readPayload();
23
11
  const sessionId = payload.session_id;
@@ -27,11 +15,7 @@ await runHook(async () => {
27
15
  const ctx = await createContext();
28
16
  try {
29
17
  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
18
  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
19
  const prompt = payload.prompt ?? '';
36
20
  if (!ctx.config.inject.perPrompt || !isSearchable(prompt))
37
21
  return;
@@ -40,8 +24,6 @@ await runHook(async () => {
40
24
  project,
41
25
  limit: ctx.config.inject.promptResults,
42
26
  });
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
27
  const toExpand = entries.slice(0, ctx.config.inject.expandTop);
46
28
  const expanded = toExpand.length > 0
47
29
  ? await ctx.search.getObservations(toExpand.map((entry) => entry.id))
@@ -1,23 +1,3 @@
1
1
  import type { Observation, ObservationIndexEntry } from '../types.js';
2
- /**
3
- * How the three layers are shown to the agent.
4
- *
5
- * Split out of the server so it can be exercised without opening a stdio
6
- * transport: this is the format every search result is paid in, and it had no
7
- * test of any kind while the server module could only be imported by starting
8
- * a server.
9
- */
10
- /**
11
- * Layer 1. Every character here is multiplied by the number of results and
12
- * paid on every search, so the format stays terse: short id, kind, month-day,
13
- * title, and one indented line of the body around the match.
14
- *
15
- * The snippet is the half that was missing. Terseness only pays if the row can
16
- * be chosen from what is shown, and a title often cannot carry that — fifteen
17
- * results dated the same day, titled things like "Committed as 30daa92", leave
18
- * a reader nothing to pick on, so they expand two at random and pay a full body
19
- * for each guess. Sixty characters here saves several thousand there.
20
- */
21
2
  export declare function renderIndex(entries: ObservationIndexEntry[]): string;
22
- /** Layer 3. Full detail for one observation, bounded by `chars`. */
23
3
  export declare function renderFull(obs: Observation, chars: number): string;