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
@@ -1,62 +1,4 @@
1
- export type Scope = 'global' | 'project';
2
- /**
3
- * Where Claude Code reads settings from.
4
- *
5
- * `project` writes `settings.local.json` inside the target repo, which Claude
6
- * Code already treats as personal and gitignores. That makes it the right
7
- * choice for trying memory on one repo without touching every session on the
8
- * machine, and it is trivially reversible by deleting one file.
9
- */
10
- export declare function settingsPathFor(scope: Scope, project: string): string;
11
- /**
12
- * Where standing instructions go.
13
- *
14
- * Hook output is injected as conversation context, which the agent reads as
15
- * information about the current turn. It is not a rule, so "you could search
16
- * memory" competes with everything else in the transcript and loses. A memory
17
- * file is part of the system prompt and governs the whole session, which is
18
- * the only reliable way to make recall a default rather than a suggestion.
19
- *
20
- * Project scope writes CLAUDE.local.md rather than CLAUDE.md: it is personal
21
- * and uncommitted, matching settings.local.json, so installing memory for
22
- * yourself never tells a teammate's agent to call a server they do not have.
23
- */
24
- export declare function instructionsPathFor(scope: Scope, project: string): string;
25
- /**
26
- * Where the `/cdb-scan` skill is installed.
27
- *
28
- * A skill rather than a CLI command: surveying a codebase means reading it, and
29
- * the agent is already sitting in the repo with the tools to do that. A command
30
- * would need its own model, its own key and its own opinion about what matters.
31
- */
32
- export declare function skillPathFor(scope: Scope, project: string): string;
33
- /**
34
- * MCP servers live in a different file from hooks.
35
- *
36
- * Claude Code reads project-scoped MCP servers from `.mcp.json` at the repo
37
- * root, not from `settings.local.json`. Writing them alongside the hooks looks
38
- * correct and silently does nothing: the hooks fire, the tools never appear,
39
- * and the session-start text ends up advertising tools that do not exist.
40
- */
41
- export declare function mcpPathFor(scope: Scope, project: string): string;
42
- /**
43
- * Registers the three lifecycle hooks and the MCP server, merging into whatever
44
- * the user already has rather than overwriting it. Re-running is safe: a hook
45
- * whose command already appears is skipped rather than duplicated.
46
- */
47
- /**
48
- * Refuses to install from a location that will not survive.
49
- *
50
- * Hooks are registered as absolute paths to this build. `npx` unpacks into
51
- * `~/.npm/_npx/<hash>/`, which npm evicts on its own schedule, so an install
52
- * from there works until the cache is cleared and then fails silently on every
53
- * hook forever after. Failing loudly now is far better than a memory system
54
- * that quietly stops recording weeks later.
55
- */
1
+ import { Scope } from './paths.js';
56
2
  export declare function assertStableLocation(distDir: string): void;
57
3
  export declare function install(distDir: string, scope: Scope, project: string): string;
58
- /**
59
- * Removes only what `install` added, leaving unrelated hooks and servers in
60
- * place. Empty containers are pruned so an uninstall leaves no residue.
61
- */
62
4
  export declare function uninstall(distDir: string, scope: Scope, project: string): string | null;
@@ -1,53 +1,12 @@
1
+ import { instructionsPathFor, mcpPathFor, settingsPathFor, skillPathFor } from './paths.js';
2
+ import { dirname, resolve } from 'node:path';
1
3
  import { execFileSync } from 'node:child_process';
2
- import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
- import { dirname, join, resolve } from 'node:path';
4
- import { homedir } from 'node:os';
5
- /**
6
- * Where Claude Code reads settings from.
7
- *
8
- * `project` writes `settings.local.json` inside the target repo, which Claude
9
- * Code already treats as personal and gitignores. That makes it the right
10
- * choice for trying memory on one repo without touching every session on the
11
- * machine, and it is trivially reversible by deleting one file.
12
- */
13
- export function settingsPathFor(scope, project) {
14
- return scope === 'project'
15
- ? join(project, '.claude', 'settings.local.json')
16
- : join(homedir(), '.claude', 'settings.json');
17
- }
18
- /**
19
- * Where standing instructions go.
20
- *
21
- * Hook output is injected as conversation context, which the agent reads as
22
- * information about the current turn. It is not a rule, so "you could search
23
- * memory" competes with everything else in the transcript and loses. A memory
24
- * file is part of the system prompt and governs the whole session, which is
25
- * the only reliable way to make recall a default rather than a suggestion.
26
- *
27
- * Project scope writes CLAUDE.local.md rather than CLAUDE.md: it is personal
28
- * and uncommitted, matching settings.local.json, so installing memory for
29
- * yourself never tells a teammate's agent to call a server they do not have.
30
- */
31
- export function instructionsPathFor(scope, project) {
32
- return scope === 'project'
33
- ? join(project, 'CLAUDE.local.md')
34
- : join(homedir(), '.claude', 'CLAUDE.md');
35
- }
36
- /**
37
- * Where the `/cdb-scan` skill is installed.
38
- *
39
- * A skill rather than a CLI command: surveying a codebase means reading it, and
40
- * the agent is already sitting in the repo with the tools to do that. A command
41
- * would need its own model, its own key and its own opinion about what matters.
42
- */
43
- export function skillPathFor(scope, project) {
44
- const root = scope === 'project' ? join(project, '.claude') : join(homedir(), '.claude');
45
- return join(root, 'skills', 'cdb-scan', 'SKILL.md');
46
- }
4
+ import { readJson, readText, writeAtomic, writeJson } from './files.js';
5
+ import { removeInstructions, writeInstructions } from './instructions.js';
6
+ import { rmSync } from 'node:fs';
47
7
  function writeSkill(distDir, scope, project) {
48
8
  const source = resolve(distDir, '..', 'skills', 'cdb-scan', 'SKILL.md');
49
9
  const body = readText(source);
50
- // Absent only in a partial checkout; the rest of the install still stands.
51
10
  if (body.length > 0)
52
11
  writeAtomic(skillPathFor(scope, project), body);
53
12
  }
@@ -55,113 +14,12 @@ function removeSkill(scope, project) {
55
14
  const path = skillPathFor(scope, project);
56
15
  rmSync(dirname(path), { recursive: true, force: true });
57
16
  }
58
- const BLOCK_START = '<!-- claude-db:start -->';
59
- const BLOCK_END = '<!-- claude-db:end -->';
60
- const INSTRUCTIONS = [
61
- BLOCK_START,
62
- '## Project memory',
63
- '',
64
- 'This project has persistent memory of past sessions, served by the `memory`',
65
- 'MCP server. Session summaries are injected at startup and the best matching',
66
- 'observation is injected above each prompt, but that is only ever a slice.',
67
- '',
68
- 'Search it *before* re-deriving something this project already knows. That',
69
- 'means before grepping or reading git history to reconstruct why something is',
70
- 'the way it is, before saying you lack context, and before asking the user to',
71
- 're-explain a past decision or a failed approach: call `search`, then',
72
- '`get_observations` for the ids worth reading.',
73
- '',
74
- 'Verifying against the code afterwards is right — memory records what was',
75
- 'done, the source shows what is. Starting there is what wastes the memory.',
76
- '',
77
- '`search` covers *why*: past decisions, bugs, reasoning. It does not know',
78
- '*where* something is used right now — for that, call `find_usages` instead',
79
- 'of grepping yourself, specifically before editing or removing a shared or',
80
- 'exported name, and when asked what uses something. It re-derives the answer',
81
- 'from the current source on every call, so it is never stale. Plain-text or',
82
- 'log searching is still a job for grep.',
83
- '',
84
- 'When the user states a standing rule or preference, record it with',
85
- '`remember` so it survives this session.',
86
- BLOCK_END,
87
- ].join('\n');
88
- /** Adds or refreshes our block, leaving everything else in the file intact. */
89
- function writeInstructions(path) {
90
- const rest = withoutBlock(readText(path)).trimEnd();
91
- const body = rest.length > 0 ? `${rest}\n\n${INSTRUCTIONS}\n` : `${INSTRUCTIONS}\n`;
92
- writeAtomic(path, body);
93
- }
94
- function removeInstructions(path) {
95
- const existing = readText(path);
96
- if (!existing.includes(BLOCK_START))
97
- return;
98
- const rest = withoutBlock(existing).trim();
99
- // A file that held nothing but our block was ours to create, so take it with
100
- // us rather than leaving an empty CLAUDE.md behind.
101
- if (rest.length === 0)
102
- rmSync(path, { force: true });
103
- else
104
- writeAtomic(path, `${rest}\n`);
105
- }
106
- function withoutBlock(text) {
107
- const start = text.indexOf(BLOCK_START);
108
- const end = text.indexOf(BLOCK_END);
109
- if (start === -1 || end === -1 || end < start)
110
- return text;
111
- return `${text.slice(0, start)}${text.slice(end + BLOCK_END.length)}`.replace(/\n{3,}/g, '\n\n');
112
- }
113
- function readText(path) {
114
- try {
115
- return readFileSync(path, 'utf8');
116
- }
117
- catch {
118
- return '';
119
- }
120
- }
121
- /**
122
- * MCP servers live in a different file from hooks.
123
- *
124
- * Claude Code reads project-scoped MCP servers from `.mcp.json` at the repo
125
- * root, not from `settings.local.json`. Writing them alongside the hooks looks
126
- * correct and silently does nothing: the hooks fire, the tools never appear,
127
- * and the session-start text ends up advertising tools that do not exist.
128
- */
129
- export function mcpPathFor(scope, project) {
130
- return scope === 'project'
131
- ? join(project, '.mcp.json')
132
- : join(homedir(), '.claude.json');
133
- }
134
- /**
135
- * Three hooks, not four.
136
- *
137
- * There is deliberately no PostToolUse hook. It fired after every single tool
138
- * call and existed only to journal file paths, which the transcript already
139
- * records in far more detail. Removing it deletes the most frequently invoked
140
- * process in the system and loses nothing.
141
- */
142
17
  const HOOKS = [
143
18
  ['SessionStart', 'session-start.js'],
144
19
  ['UserPromptSubmit', 'user-prompt.js'],
145
20
  ['SessionEnd', 'session-end.js'],
146
21
  ];
147
- /**
148
- * Registers the three lifecycle hooks and the MCP server, merging into whatever
149
- * the user already has rather than overwriting it. Re-running is safe: a hook
150
- * whose command already appears is skipped rather than duplicated.
151
- */
152
- /**
153
- * Refuses to install from a location that will not survive.
154
- *
155
- * Hooks are registered as absolute paths to this build. `npx` unpacks into
156
- * `~/.npm/_npx/<hash>/`, which npm evicts on its own schedule, so an install
157
- * from there works until the cache is cleared and then fails silently on every
158
- * hook forever after. Failing loudly now is far better than a memory system
159
- * that quietly stops recording weeks later.
160
- */
161
22
  export function assertStableLocation(distDir) {
162
- // Only npm's own scratch areas. Matching on `/tmp/` generally would be a
163
- // false positive: a global prefix can legitimately live anywhere, and
164
- // refusing a valid install is worse than the problem being guarded against.
165
23
  const ephemeral = ['_npx', '_cacache'];
166
24
  const segments = distDir.split('/');
167
25
  if (!ephemeral.some((name) => segments.includes(name)))
@@ -189,17 +47,11 @@ export function install(distDir, scope, project) {
189
47
  hooks[event] = existing;
190
48
  }
191
49
  settings['hooks'] = hooks;
192
- // Never write mcpServers here; Claude Code ignores it in this file.
193
50
  delete settings['mcpServers'];
194
51
  writeJson(path, settings);
195
52
  const server = resolve(distDir, 'mcp', 'server.js');
196
53
  writeInstructions(instructionsPathFor(scope, project));
197
54
  writeSkill(distDir, scope, project);
198
- // A global install lands in ~/.claude.json, which holds all of Claude Code's
199
- // own state. Let its CLI own that file rather than round-tripping megabytes
200
- // of someone else's config through JSON.parse to add one key. The direct
201
- // write stays as a fallback, since `claude` is not always on PATH, and it is
202
- // the right thing for the project scope: .mcp.json is small and ours.
203
55
  if (scope === 'global' && registerViaCli(server))
204
56
  return path;
205
57
  const mcpPath = mcpPathFor(scope, project);
@@ -210,7 +62,6 @@ export function install(distDir, scope, project) {
210
62
  writeJson(mcpPath, mcpConfig);
211
63
  return path;
212
64
  }
213
- /** Both directions of the `claude mcp` CLI, false when it is unavailable. */
214
65
  function claudeMcp(args) {
215
66
  try {
216
67
  execFileSync('claude', args, { stdio: 'ignore' });
@@ -221,15 +72,9 @@ function claudeMcp(args) {
221
72
  }
222
73
  }
223
74
  function registerViaCli(server) {
224
- // Removed first because `add` refuses an existing name, and re-running
225
- // install has to stay safe.
226
75
  claudeMcp(['mcp', 'remove', 'memory', '-s', 'user']);
227
76
  return claudeMcp(['mcp', 'add', 'memory', '-s', 'user', '--', 'node', server]);
228
77
  }
229
- /**
230
- * Removes only what `install` added, leaving unrelated hooks and servers in
231
- * place. Empty containers are pruned so an uninstall leaves no residue.
232
- */
233
78
  export function uninstall(distDir, scope, project) {
234
79
  const path = settingsPathFor(scope, project);
235
80
  const settings = readJson(path);
@@ -256,15 +101,11 @@ export function uninstall(distDir, scope, project) {
256
101
  writeJson(path, settings);
257
102
  removeInstructions(instructionsPathFor(scope, project));
258
103
  removeSkill(scope, project);
259
- // Symmetric with install: if the CLI put it there, the CLI takes it out.
260
104
  if (scope === 'global' && claudeMcp(['mcp', 'remove', 'memory', '-s', 'user'])) {
261
105
  return path;
262
106
  }
263
107
  const mcpPath = mcpPathFor(scope, project);
264
108
  const mcpConfig = readJson(mcpPath);
265
- // Captured before the delete below can empty it. Testing emptiness
266
- // afterwards skipped the write for a config holding only our server, which
267
- // is the common case, so uninstall silently left it registered.
268
109
  const existed = Object.keys(mcpConfig).length > 0;
269
110
  const servers = (mcpConfig['mcpServers'] ?? {});
270
111
  delete servers['memory'];
@@ -279,32 +120,3 @@ export function uninstall(distDir, scope, project) {
279
120
  function hookCommand(distDir, file) {
280
121
  return `node ${resolve(distDir, 'hooks', file)}`;
281
122
  }
282
- function readJson(path) {
283
- try {
284
- return JSON.parse(readFileSync(path, 'utf8'));
285
- }
286
- catch {
287
- return {};
288
- }
289
- }
290
- /**
291
- * Written through a temporary file and renamed, because one of these targets
292
- * is `~/.claude.json`, which holds all of Claude Code's own state. Truncating
293
- * it and dying midway to add a single key would cost the user real data;
294
- * rename is atomic, so the file is either the old one or the new one.
295
- */
296
- function writeJson(path, value) {
297
- writeAtomic(path, `${JSON.stringify(value, null, 2)}\n`);
298
- }
299
- function writeAtomic(path, content) {
300
- mkdirSync(dirname(path), { recursive: true });
301
- const temp = `${path}.${process.pid}.tmp`;
302
- try {
303
- writeFileSync(temp, content, 'utf8');
304
- renameSync(temp, path);
305
- }
306
- catch (error) {
307
- rmSync(temp, { force: true });
308
- throw error;
309
- }
310
- }
@@ -0,0 +1,5 @@
1
+ export declare const BLOCK_START = "<!-- claude-db:start -->";
2
+ export declare const BLOCK_END = "<!-- claude-db:end -->";
3
+ export declare const INSTRUCTIONS: string;
4
+ export declare function writeInstructions(path: string): void;
5
+ export declare function removeInstructions(path: string): void;
@@ -0,0 +1,55 @@
1
+ import { readText, writeAtomic } from './files.js';
2
+ import { rmSync } from 'node:fs';
3
+ export const BLOCK_START = '<!-- claude-db:start -->';
4
+ export const BLOCK_END = '<!-- claude-db:end -->';
5
+ export const INSTRUCTIONS = [
6
+ BLOCK_START,
7
+ '## Project memory',
8
+ '',
9
+ 'This project has persistent memory of past sessions, served by the `memory`',
10
+ 'MCP server. Session summaries are injected at startup and the best matching',
11
+ 'observation is injected above each prompt, but that is only ever a slice.',
12
+ '',
13
+ 'Search it *before* re-deriving something this project already knows. That',
14
+ 'means before grepping or reading git history to reconstruct why something is',
15
+ 'the way it is, before saying you lack context, and before asking the user to',
16
+ 're-explain a past decision or a failed approach: call `search`, then',
17
+ '`get_observations` for the ids worth reading.',
18
+ '',
19
+ 'Verifying against the code afterwards is right — memory records what was',
20
+ 'done, the source shows what is. Starting there is what wastes the memory.',
21
+ '',
22
+ '`search` covers *why*: past decisions, bugs, reasoning. `find_usages` is',
23
+ 'the default the moment a question is about a symbol or identifier — before',
24
+ 'editing or removing a shared or exported name, or to look one up at all —',
25
+ 'since it tags the likely definition and re-derives the answer from the',
26
+ 'current source on every call, so it is never stale. grep still wins for',
27
+ 'everything that is not a code identifier: plain text, log files, comments,',
28
+ 'strings, and scoping with grep flags `find_usages` does not expose.',
29
+ '',
30
+ 'When the user states a standing rule or preference, record it with',
31
+ '`remember` so it survives this session.',
32
+ BLOCK_END,
33
+ ].join('\n');
34
+ export function writeInstructions(path) {
35
+ const rest = withoutBlock(readText(path)).trimEnd();
36
+ const body = rest.length > 0 ? `${rest}\n\n${INSTRUCTIONS}\n` : `${INSTRUCTIONS}\n`;
37
+ writeAtomic(path, body);
38
+ }
39
+ export function removeInstructions(path) {
40
+ const existing = readText(path);
41
+ if (!existing.includes(BLOCK_START))
42
+ return;
43
+ const rest = withoutBlock(existing).trim();
44
+ if (rest.length === 0)
45
+ rmSync(path, { force: true });
46
+ else
47
+ writeAtomic(path, `${rest}\n`);
48
+ }
49
+ function withoutBlock(text) {
50
+ const start = text.indexOf(BLOCK_START);
51
+ const end = text.indexOf(BLOCK_END);
52
+ if (start === -1 || end === -1 || end < start)
53
+ return text;
54
+ return `${text.slice(0, start)}${text.slice(end + BLOCK_END.length)}`.replace(/\n{3,}/g, '\n\n');
55
+ }
@@ -0,0 +1,5 @@
1
+ export type Scope = 'global' | 'project';
2
+ export declare function settingsPathFor(scope: Scope, project: string): string;
3
+ export declare function instructionsPathFor(scope: Scope, project: string): string;
4
+ export declare function skillPathFor(scope: Scope, project: string): string;
5
+ export declare function mcpPathFor(scope: Scope, project: string): string;
@@ -0,0 +1,19 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ export function settingsPathFor(scope, project) {
4
+ return scope === 'project'
5
+ ? join(project, '.claude', 'settings.local.json')
6
+ : join(homedir(), '.claude', 'settings.json');
7
+ }
8
+ export function instructionsPathFor(scope, project) {
9
+ return scope === 'project'
10
+ ? join(project, 'CLAUDE.local.md')
11
+ : join(homedir(), '.claude', 'CLAUDE.md');
12
+ }
13
+ export function skillPathFor(scope, project) {
14
+ const root = scope === 'project' ? join(project, '.claude') : join(homedir(), '.claude');
15
+ return join(root, 'skills', 'cdb-scan', 'SKILL.md');
16
+ }
17
+ export function mcpPathFor(scope, project) {
18
+ return scope === 'project' ? join(project, '.mcp.json') : join(homedir(), '.claude.json');
19
+ }
@@ -0,0 +1 @@
1
+ export declare function refreshInstalled(distDir: string, project: string): string[];
@@ -0,0 +1,25 @@
1
+ import { BLOCK_START, INSTRUCTIONS, writeInstructions } from './instructions.js';
2
+ import { instructionsPathFor, skillPathFor } from './paths.js';
3
+ import { readText, writeAtomic } from './files.js';
4
+ import { resolve } from 'node:path';
5
+ export function refreshInstalled(distDir, project) {
6
+ const refreshed = [];
7
+ for (const scope of ['project', 'global']) {
8
+ const skillPath = skillPathFor(scope, project);
9
+ const current = readText(skillPath);
10
+ if (current.length > 0) {
11
+ const packaged = readText(resolve(distDir, '..', 'skills', 'cdb-scan', 'SKILL.md'));
12
+ if (packaged.length > 0 && packaged !== current) {
13
+ writeAtomic(skillPath, packaged);
14
+ refreshed.push(skillPath);
15
+ }
16
+ }
17
+ const instructionsPath = instructionsPathFor(scope, project);
18
+ const existing = readText(instructionsPath);
19
+ if (existing.includes(BLOCK_START) && !existing.includes(INSTRUCTIONS)) {
20
+ writeInstructions(instructionsPath);
21
+ refreshed.push(instructionsPath);
22
+ }
23
+ }
24
+ return refreshed;
25
+ }
@@ -0,0 +1 @@
1
+ export declare function usage(): void;
@@ -0,0 +1,39 @@
1
+ export function usage() {
2
+ console.log(`claude-db
3
+
4
+ install [--project] Register hooks + MCP server with Claude Code
5
+ uninstall [--project] Remove them again, leaving memory intact
6
+ status Is it wired up, and has it recorded anything
7
+ doctor [--deep] Show resolved config; --deep proves a full
8
+ write, search, recall and delete round trip
9
+ use [--force] <url> Point memory at a database, once it answers
10
+ search [--all] <query> Search memory, this project or every project
11
+ [--tag <name>] ...limited to one repo or top-level directory
12
+ remember [--kind k] <text> Record something outright, e.g. a house rule
13
+ [--key <name>] ...under a stable name, replacing any earlier one
14
+ forget <id> [id...] Delete specific observations by id
15
+ projects List every project with memory in this database
16
+ merge [<old-path>] [--yes] Move memory from an old project path onto this one
17
+ stats What this project's memory is made of
18
+ flush Re-ingest every transcript for this project
19
+ seed --from-git [--limit n] Fill a cold memory from this repo's history
20
+ usages [--regex] <symbol> Find real usages via git grep, current source only
21
+ [--context n] [--path <dir>] [--limit n]
22
+ export [--all] > out.jsonl Dump memory as JSONL, for backup or migration
23
+ import <file.jsonl> Load a dump back in (safe to repeat)
24
+ sync <url> [--yes] Two-way merge with another database
25
+ update Install a newer compatible release now
26
+ reembed Re-embed everything with the current model
27
+ prune --older-than <days> Delete old memory (dry run without --yes)
28
+ reset [--project] --yes Delete stored memory (dry run without --yes)
29
+
30
+ --project scope to the current repo via .claude/settings.local.json
31
+ instead of every project on this machine
32
+
33
+ Connection strings:
34
+ mongodb+srv://user:pass@cluster.mongodb.net/memory
35
+ postgres://user:pass@host:5432/memory
36
+ /path/to/memory.db (SQLite, default)
37
+
38
+ Or set CLAUDE_DB_URL in the environment to override config.json.`);
39
+ }
@@ -2,10 +2,5 @@ import type { Config } from './schema.js';
2
2
  export declare const CONFIG_DIR: string;
3
3
  export declare const CONFIG_PATH: string;
4
4
  export declare const DEFAULT_DB_PATH: string;
5
- /**
6
- * Precedence: CLAUDE_DB_URL env var, then config.json, then a local SQLite
7
- * file. The env var wins so CI and containers can point at a shared database
8
- * without rewriting config on disk.
9
- */
10
5
  export declare function loadConfig(): Config;
11
6
  export declare function saveConfig(config: Config): void;
@@ -5,19 +5,12 @@ import { ConfigSchema } from './schema.js';
5
5
  export const CONFIG_DIR = join(homedir(), '.claude-memory');
6
6
  export const CONFIG_PATH = join(CONFIG_DIR, 'config.json');
7
7
  export const DEFAULT_DB_PATH = join(CONFIG_DIR, 'memory.db');
8
- /**
9
- * Precedence: CLAUDE_DB_URL env var, then config.json, then a local SQLite
10
- * file. The env var wins so CI and containers can point at a shared database
11
- * without rewriting config on disk.
12
- */
13
8
  export function loadConfig() {
14
9
  let fileConfig = {};
15
10
  try {
16
11
  fileConfig = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
17
12
  }
18
- catch {
19
- // Missing or unreadable config is not an error; defaults apply.
20
- }
13
+ catch { }
21
14
  const config = ConfigSchema.parse(fileConfig);
22
15
  const envUrl = process.env['CLAUDE_DB_URL']?.trim();
23
16
  return {
@@ -1,85 +1,29 @@
1
1
  import { z } from 'zod';
2
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
3
  database: z.string().default(''),
8
4
  embeddings: z
9
5
  .object({
10
6
  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
7
  maxScanCandidates: z.number().int().positive().default(25000),
19
- /**
20
- * How long to wait for the embedding model before giving up for this
21
- * one invocation and falling back to keyword-only search. The model is
22
- * fetched and loaded lazily inside a hook that runs on the critical path
23
- * of a prompt, so an unbounded wait is a hung prompt. 0 disables the
24
- * limit, which is what `doctor` uses to warm the model deliberately.
25
- */
26
8
  timeoutMs: z.number().int().nonnegative().default(3000),
27
9
  })
28
10
  .default({ provider: 'auto', maxScanCandidates: 25000, timeoutMs: 3000 }),
29
- /**
30
- * `notify` mentions a newer release at session start; `auto` also installs
31
- * it; `off` never asks.
32
- *
33
- * Notify is the default. Installing on someone's behalf means executing code
34
- * they did not choose, in a process holding their whole memory database, and
35
- * it turns a single bad publish into silent execution everywhere. The nudge
36
- * is what actually matters here: this tool fails silently by design — hooks
37
- * swallow their errors so they can never break a session — so a user left on
38
- * a broken release sees no error, just memory that never fills up.
39
- */
40
11
  updates: z.enum(['auto', 'notify', 'off']).default('notify'),
41
12
  capture: z
42
13
  .object({
43
- /** Tools whose invocations are worth remembering. */
44
- tools: z
45
- .array(z.string())
46
- .default(['Edit', 'Write', 'Bash', 'NotebookEdit']),
47
- /** Glob-ish fragments; matching paths are never persisted. */
48
- exclude: z
49
- .array(z.string())
50
- .default(['.env', 'secrets', 'node_modules', '.git/']),
14
+ tools: z.array(z.string()).default(['Edit', 'Write', 'Bash', 'NotebookEdit']),
15
+ exclude: z.array(z.string()).default(['.env', 'secrets', 'node_modules', '.git/']),
51
16
  maxBodyChars: z.number().int().positive().default(4000),
52
17
  })
53
- // `prefault` rather than `default`: zod 4 requires a `default` to satisfy
54
- // the full output type, so `{}` is rejected even though every field below
55
- // supplies its own default. `prefault` substitutes on the input side and
56
- // lets those field defaults fill the object in.
57
18
  .prefault({}),
58
19
  inject: z
59
20
  .object({
60
- /** Session summaries pulled in at SessionStart. */
61
21
  sessions: z.number().int().nonnegative().default(5),
62
- /** Hard ceiling on SessionStart context, in characters. */
63
22
  maxChars: z.number().int().positive().default(6000),
64
- /**
65
- * Search memory on every prompt and inject matching titles.
66
- * Set false to fall back to tool-only recall, where Claude decides.
67
- */
68
23
  perPrompt: z.boolean().default(true),
69
- /** How many titles a per-prompt injection may surface. */
70
24
  promptResults: z.number().int().positive().max(10).default(4),
71
- /** Character ceiling for the per-prompt block. Roughly 4 chars a token. */
72
25
  promptMaxChars: z.number().int().positive().default(500),
73
- /**
74
- * How many top matches to inject in full rather than as a title.
75
- *
76
- * Titles alone require the agent to decide to call get_observations,
77
- * which reintroduces exactly the "it might not bother" failure that
78
- * automatic injection exists to remove. Expanding the single best match
79
- * delivers the reasoning without a round trip.
80
- */
81
26
  expandTop: z.number().int().min(0).max(3).default(1),
82
- /** Character ceiling for each expanded body. */
83
27
  expandMaxChars: z.number().int().positive().default(900),
84
28
  })
85
29
  .prefault({}),
package/dist/context.d.ts CHANGED
@@ -5,18 +5,8 @@ import type { MemoryStore } from './store/adapter.js';
5
5
  export interface RecallContext {
6
6
  config: Config;
7
7
  store: MemoryStore;
8
- /** Resolves the embedder, constructing it on first use. */
9
8
  embedder(): Promise<Embedder>;
10
9
  search: SearchService;
11
10
  close(): Promise<void>;
12
11
  }
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
12
  export declare function createContext(overrides?: Partial<Config>): Promise<RecallContext>;
package/dist/context.js CHANGED
@@ -2,15 +2,6 @@ import { loadConfig } from './config/index.js';
2
2
  import { createEmbedder, NoopEmbedder } from './embed/index.js';
3
3
  import { SearchService } from './search/index.js';
4
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
5
  export async function createContext(overrides) {
15
6
  const config = { ...loadConfig(), ...overrides };
16
7
  const store = await createStore(config.database);
@@ -23,13 +14,6 @@ export async function createContext(overrides) {
23
14
  const search = new SearchService(store, embedder, config.embeddings.maxScanCandidates);
24
15
  return { config, store, embedder, search, close: () => store.close() };
25
16
  }
26
- /**
27
- * The first use of a local model downloads ~25MB and loads it, inside a hook
28
- * that is blocking the user's prompt. Bounding that turns a hung prompt into
29
- * one prompt with keyword-only recall; the next invocation finds the model
30
- * cached. Falls back to no embedder rather than to the builtin, so a timeout
31
- * never mixes a second vector width into the database.
32
- */
33
17
  async function withTimeout(pending, ms) {
34
18
  if (ms <= 0)
35
19
  return pending;