claude-db 0.4.1 → 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 -194
  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 +46 -25
  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 +51 -54
  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,77 @@
1
+ import { basename } from 'node:path';
2
+ import { createContext } from '../../context.js';
3
+ import { remember } from '../../capture/index.js';
4
+ import { resolveProject } from '../../util/project.js';
5
+ import { toShortId } from '../../util/shortid.js';
6
+ import { valueOf, withoutFlags } from '../args.js';
7
+ export async function cmdSearch(argv) {
8
+ const all = argv.includes('--all');
9
+ const tag = valueOf(argv, '--tag');
10
+ const query = withoutFlags(argv, ['--tag'])
11
+ .filter((arg) => arg !== '--all')
12
+ .join(' ');
13
+ if (!query.trim()) {
14
+ console.error('Usage: claude-db search [--all] [--tag <name>] <query>');
15
+ process.exit(1);
16
+ }
17
+ const ctx = await createContext();
18
+ const results = await ctx.search.search({
19
+ text: query,
20
+ ...(all ? {} : { project: resolveProject(undefined) }),
21
+ ...(tag ? { tag } : {}),
22
+ limit: 10,
23
+ });
24
+ for (const entry of results) {
25
+ const date = new Date(entry.createdAt).toISOString().slice(0, 10);
26
+ const where = all ? ` ${basename(entry.project)}` : '';
27
+ console.log(`${toShortId(entry.id)} ${entry.kind.padEnd(10)} ${date}${where} ${entry.title}`);
28
+ if (entry.snippet)
29
+ console.log(` ${entry.snippet}`);
30
+ }
31
+ if (results.length === 0)
32
+ console.log('No matching observations.');
33
+ await ctx.close();
34
+ }
35
+ export async function cmdRemember(argv) {
36
+ const kind = valueOf(argv, '--kind');
37
+ const key = valueOf(argv, '--key');
38
+ const tag = valueOf(argv, '--tag');
39
+ const text = withoutFlags(argv, ['--kind', '--key', '--tag']).join(' ').trim();
40
+ if (!text) {
41
+ console.error('Usage: claude-db remember [--kind <kind>] [--key <name>] [--tag <name>] <text>');
42
+ process.exit(1);
43
+ }
44
+ const ctx = await createContext();
45
+ try {
46
+ const observation = await remember(ctx, {
47
+ project: resolveProject(undefined),
48
+ text,
49
+ ...(kind ? { kind: kind } : {}),
50
+ ...(key ? { key } : {}),
51
+ ...(tag ? { tags: [tag] } : {}),
52
+ });
53
+ console.log(`Remembered ${toShortId(observation.id)} [${observation.kind}] ${observation.title}`);
54
+ }
55
+ finally {
56
+ await ctx.close();
57
+ }
58
+ }
59
+ export async function cmdForget(argv) {
60
+ const ids = argv.filter((arg) => typeof arg === 'string' && arg.length > 0);
61
+ if (ids.length === 0) {
62
+ console.error('Usage: claude-db forget <id> [id...]');
63
+ process.exit(1);
64
+ }
65
+ const ctx = await createContext();
66
+ try {
67
+ const doomed = await ctx.store.getObservations(ids);
68
+ for (const obs of doomed) {
69
+ console.log(` ${toShortId(obs.id)} [${obs.kind}] ${obs.title}`);
70
+ }
71
+ const deleted = await ctx.store.remove({ ids });
72
+ console.log(deleted > 0 ? `Forgot ${deleted} observation(s).` : 'No match.');
73
+ }
74
+ finally {
75
+ await ctx.close();
76
+ }
77
+ }
@@ -0,0 +1 @@
1
+ export declare function cmdSeed(argv: (string | undefined)[]): Promise<void>;
@@ -0,0 +1,43 @@
1
+ import { BATCH } from '../constants.js';
2
+ import { createContext } from '../../context.js';
3
+ import { embedObservations, observationsFromGit } from '../../capture/index.js';
4
+ import { resolveProject } from '../../util/project.js';
5
+ import { valueOf } from '../args.js';
6
+ export async function cmdSeed(argv) {
7
+ if (!argv.includes('--from-git')) {
8
+ console.error('Usage: claude-db seed --from-git [--limit <n>]');
9
+ process.exit(1);
10
+ }
11
+ const limit = Number(valueOf(argv, '--limit') ?? 500);
12
+ if (!Number.isFinite(limit) || limit <= 0) {
13
+ console.error('--limit must be a positive number of commits.');
14
+ process.exit(1);
15
+ }
16
+ const project = resolveProject(undefined);
17
+ let observations;
18
+ try {
19
+ observations = observationsFromGit(project, limit);
20
+ }
21
+ catch (error) {
22
+ console.error(`Could not read git history: ${error instanceof Error ? error.message.split('\n')[0] : String(error)}`);
23
+ process.exit(1);
24
+ }
25
+ if (observations.length === 0) {
26
+ console.log(`No usable commits found in ${project}.`);
27
+ console.log('Merges, releases and commits touching no files are skipped.');
28
+ return;
29
+ }
30
+ const ctx = await createContext();
31
+ try {
32
+ for (let i = 0; i < observations.length; i += BATCH) {
33
+ const batch = observations.slice(i, i + BATCH);
34
+ await embedObservations(ctx, batch);
35
+ await ctx.store.insertObservations(batch);
36
+ }
37
+ }
38
+ finally {
39
+ await ctx.close();
40
+ }
41
+ console.log(`Seeded ${observations.length} observation(s) from git history.`);
42
+ console.log(`Oldest: ${new Date(observations[observations.length - 1]?.createdAt ?? 0).toISOString().slice(0, 10)}`);
43
+ }
@@ -0,0 +1,4 @@
1
+ import type { Scope } from '../paths.js';
2
+ export declare function cmdInstall(scope: Scope): Promise<void>;
3
+ export declare function cmdUninstall(scope: Scope): void;
4
+ export declare function cmdStatus(): Promise<void>;
@@ -0,0 +1,156 @@
1
+ import { toShortId } from '../../util/shortid.js';
2
+ import { closeLandedWork, openWork } from '../../capture/index.js';
3
+ import { CONFIG_PATH } from '../../config/index.js';
4
+ import { DIST_DIR } from '../constants.js';
5
+ import { assertStableLocation, install, uninstall } from '../install.js';
6
+ import { instructionsPathFor, mcpPathFor, settingsPathFor, skillPathFor } from '../paths.js';
7
+ import { createContext } from '../../context.js';
8
+ import { join, resolve } from 'node:path';
9
+ import { readFileSync, statSync } from 'node:fs';
10
+ import { resolveProject } from '../../util/project.js';
11
+ import { transcriptsFor } from '../../capture/index.js';
12
+ export async function cmdInstall(scope) {
13
+ const project = resolveProject(undefined);
14
+ try {
15
+ assertStableLocation(DIST_DIR);
16
+ }
17
+ catch (error) {
18
+ console.error(error instanceof Error ? error.message : String(error));
19
+ process.exit(1);
20
+ }
21
+ const settingsPath = install(DIST_DIR, scope, project);
22
+ const ctx = await createContext();
23
+ await ctx.close();
24
+ console.log(`Scope : ${scope === 'project' ? `this project only (${project})` : 'all projects on this machine'}`);
25
+ console.log(`Settings : ${settingsPath}`);
26
+ console.log(`Guidance : ${instructionsPathFor(scope, project)}`);
27
+ console.log(`Skill : ${skillPathFor(scope, project)} (/cdb-scan)`);
28
+ console.log(`Config : ${CONFIG_PATH}`);
29
+ console.log(`Database : ${ctx.config.database}`);
30
+ console.log('\nRestart Claude Code to activate.');
31
+ if (scope === 'project') {
32
+ warnIfCommittable(project);
33
+ console.log('Remove later with: claude-db uninstall --project');
34
+ }
35
+ }
36
+ function warnIfCommittable(project) {
37
+ const gitignore = join(project, '.gitignore');
38
+ let ignored = false;
39
+ try {
40
+ ignored = readFileSync(gitignore, 'utf8')
41
+ .split('\n')
42
+ .some((line) => line.trim().replace(/^\//, '') === '.mcp.json');
43
+ }
44
+ catch {
45
+ return;
46
+ }
47
+ if (ignored)
48
+ return;
49
+ console.log('\nNote: .mcp.json holds an absolute path to this machine.');
50
+ console.log('It would break for anyone else if committed. To keep it local:');
51
+ console.log(" echo '.mcp.json' >> .gitignore");
52
+ }
53
+ export function cmdUninstall(scope) {
54
+ const project = resolveProject(undefined);
55
+ const path = uninstall(DIST_DIR, scope, project);
56
+ console.log(path
57
+ ? `Removed hooks and MCP server from ${path}`
58
+ : 'Nothing to remove: no settings file found.');
59
+ console.log('Memory itself is untouched. Delete it with: rm -rf ~/.claude-memory');
60
+ }
61
+ const STALL_MS = 48 * 60 * 60 * 1000;
62
+ export async function cmdStatus() {
63
+ const project = resolveProject(undefined);
64
+ const ctx = await createContext();
65
+ try {
66
+ const sessions = await ctx.store.recentSessions(project, 100);
67
+ const wiring = [
68
+ { scope: 'project', label: 'this project' },
69
+ { scope: 'global', label: 'all projects' },
70
+ ].map((entry) => ({
71
+ ...entry,
72
+ path: settingsPathFor(entry.scope, project),
73
+ installed: isInstalled(settingsPathFor(entry.scope, project)),
74
+ }));
75
+ const active = wiring.filter((entry) => entry.installed);
76
+ console.log(`project : ${project}`);
77
+ console.log(`database : ${ctx.config.database}`);
78
+ console.log(`hooks : ${active.length > 0 ? active.map((entry) => entry.label).join(' + ') : 'NOT INSTALLED'}`);
79
+ const mcpFile = [mcpPathFor('project', project), mcpPathFor('global', project)].find((candidate) => fileMentions(candidate, resolve(DIST_DIR, 'mcp', 'server.js')));
80
+ console.log(`mcp : ${mcpFile ? `registered (${mcpFile})` : 'NOT REGISTERED'}`);
81
+ console.log(`sessions : ${sessions.length} recorded for this project`);
82
+ const saved = (await ctx.store.listProjects()).find((entry) => entry.project === project);
83
+ const lastSaved = saved?.lastActive ?? 0;
84
+ const worked = workedAt(project);
85
+ console.log(`recorded : ${lastSaved > 0 ? ago(lastSaved) : 'never'}`);
86
+ await closeLandedWork(ctx.store, project);
87
+ const open = await openWork(ctx.store, project);
88
+ if (open.length > 0) {
89
+ console.log(`\nNot committed yet (${open.length}), newest first:`);
90
+ for (const obs of open.slice(0, 5)) {
91
+ console.log(` ${toShortId(obs.id)} ${obs.title.slice(0, 68)}`);
92
+ }
93
+ }
94
+ if (active.length === 0) {
95
+ console.log('\nHooks are not registered, so nothing will ever be captured.');
96
+ console.log('Run this from the project you want to track:');
97
+ console.log(' claude-db install --project');
98
+ }
99
+ else if (hasStalled(lastSaved, worked)) {
100
+ console.log(`\nCapture looks stalled. This project was worked in ${ago(worked.last)},`);
101
+ console.log(lastSaved > 0
102
+ ? `but the newest memory is from ${ago(lastSaved)}.`
103
+ : 'but nothing has ever been recorded for it.');
104
+ console.log('Nothing reports this on its own: hooks swallow their errors so a');
105
+ console.log('memory layer can never break a session. Check it end to end with:');
106
+ console.log(' claude-db doctor --deep');
107
+ }
108
+ else if (sessions.length === 0) {
109
+ console.log('\nInstalled, but nothing recorded yet. Memory is written as you');
110
+ console.log('work, on every prompt, and only for turns that changed something.');
111
+ console.log('If you installed just now, restart Claude Code first.');
112
+ }
113
+ }
114
+ finally {
115
+ await ctx.close();
116
+ }
117
+ }
118
+ function workedAt(project) {
119
+ let first = Number.POSITIVE_INFINITY;
120
+ let last = 0;
121
+ for (const path of transcriptsFor(project)) {
122
+ try {
123
+ const { mtimeMs } = statSync(path);
124
+ first = Math.min(first, mtimeMs);
125
+ last = Math.max(last, mtimeMs);
126
+ }
127
+ catch { }
128
+ }
129
+ return { first: Number.isFinite(first) ? first : 0, last };
130
+ }
131
+ function hasStalled(lastSaved, worked) {
132
+ if (worked.last === 0)
133
+ return false;
134
+ return worked.last > (lastSaved > 0 ? lastSaved : worked.first) + STALL_MS;
135
+ }
136
+ function ago(when) {
137
+ const minutes = Math.max(0, Math.round((Date.now() - when) / 60_000));
138
+ const date = new Date(when).toISOString().slice(0, 10);
139
+ if (minutes < 90)
140
+ return `${minutes} minute(s) ago`;
141
+ const hours = Math.round(minutes / 60);
142
+ if (hours < 48)
143
+ return `${hours} hour(s) ago (${date})`;
144
+ return `${Math.round(hours / 24)} day(s) ago (${date})`;
145
+ }
146
+ function isInstalled(settingsPath) {
147
+ return fileMentions(settingsPath, resolve(DIST_DIR, 'hooks', 'session-end.js'));
148
+ }
149
+ function fileMentions(path, needle) {
150
+ try {
151
+ return readFileSync(path, 'utf8').includes(needle);
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
@@ -0,0 +1 @@
1
+ export declare function cmdSync(argv: (string | undefined)[]): Promise<void>;
@@ -0,0 +1,95 @@
1
+ import { BATCH } from '../constants.js';
2
+ import { createContext } from '../../context.js';
3
+ import { createStore } from '../../store/index.js';
4
+ export async function cmdSync(argv) {
5
+ const url = argv.find((arg) => typeof arg === 'string' && !arg.startsWith('-'));
6
+ const confirmed = argv.includes('--yes') || argv.includes('-y');
7
+ if (!url) {
8
+ console.error('Usage: claude-db sync <connection-string> [--yes]');
9
+ process.exit(1);
10
+ }
11
+ const local = await createContext();
12
+ if (local.config.database === url) {
13
+ await local.close();
14
+ console.error('That is the database memory already uses.');
15
+ process.exit(1);
16
+ }
17
+ const remote = await createStore(url);
18
+ try {
19
+ await remote.init();
20
+ const localIds = new Set();
21
+ await eachRemoteObservation(local.store, (batch) => {
22
+ for (const obs of batch)
23
+ localIds.add(obs.id);
24
+ });
25
+ const remoteIds = new Set();
26
+ let pulled = 0;
27
+ await eachRemoteObservation(remote, async (batch) => {
28
+ for (const obs of batch)
29
+ remoteIds.add(obs.id);
30
+ const fresh = batch.filter((obs) => !localIds.has(obs.id));
31
+ if (fresh.length === 0)
32
+ return;
33
+ pulled += fresh.length;
34
+ if (confirmed)
35
+ await local.store.insertObservations(fresh);
36
+ });
37
+ let pushed = 0;
38
+ await eachRemoteObservation(local.store, async (batch) => {
39
+ const fresh = batch.filter((obs) => !remoteIds.has(obs.id));
40
+ if (fresh.length === 0)
41
+ return;
42
+ pushed += fresh.length;
43
+ if (confirmed)
44
+ await remote.insertObservations(fresh);
45
+ });
46
+ if (!confirmed) {
47
+ console.log(`This would pull ${pulled} and push ${pushed} observation(s).`);
48
+ console.log('\nNothing was transferred. Re-run with --yes to confirm.');
49
+ return;
50
+ }
51
+ const sessions = await syncSessions(local.store, remote);
52
+ console.log(`Pulled ${pulled}, pushed ${pushed}, and reconciled ${sessions} session(s).`);
53
+ }
54
+ finally {
55
+ await remote.close();
56
+ await local.close();
57
+ }
58
+ }
59
+ async function syncSessions(local, remote) {
60
+ const projects = new Set();
61
+ for (const store of [local, remote]) {
62
+ for (const entry of await store.listProjects())
63
+ projects.add(entry.project);
64
+ }
65
+ let moved = 0;
66
+ for (const project of projects) {
67
+ for (const [from, to] of [
68
+ [local, remote],
69
+ [remote, local],
70
+ ]) {
71
+ for (const session of await from.recentSessions(project, 1000)) {
72
+ if (await to.getSession(session.id))
73
+ continue;
74
+ await to.upsertSession(session);
75
+ moved += 1;
76
+ }
77
+ }
78
+ }
79
+ return moved;
80
+ }
81
+ async function eachRemoteObservation(store, visit) {
82
+ let after = 0;
83
+ for (;;) {
84
+ const batch = await store.list({ after, limit: BATCH });
85
+ if (batch.length === 0)
86
+ return;
87
+ await visit(batch);
88
+ const last = batch[batch.length - 1];
89
+ if (!last)
90
+ return;
91
+ after = last.createdAt === after ? after + 1 : last.createdAt;
92
+ if (batch.length < BATCH)
93
+ return;
94
+ }
95
+ }
@@ -0,0 +1,9 @@
1
+ import type { Observation } from '../../types.js';
2
+ import type { RecallContext } from '../../context.js';
3
+ export declare function eachObservation(ctx: RecallContext, filter: {
4
+ project?: string;
5
+ }, visit: (batch: Observation[]) => Promise<void> | void): Promise<number>;
6
+ export declare function cmdExport(argv: (string | undefined)[]): Promise<void>;
7
+ export declare function cmdImport(path: string | undefined): Promise<void>;
8
+ export declare function cmdPrune(argv: (string | undefined)[]): Promise<void>;
9
+ export declare function cmdReembed(): Promise<void>;
@@ -0,0 +1,129 @@
1
+ import { BATCH } from '../constants.js';
2
+ import { createContext } from '../../context.js';
3
+ import { embedObservations } from '../../capture/index.js';
4
+ import { loadConfig } from '../../config/index.js';
5
+ import { readFileSync } from 'node:fs';
6
+ import { resolveProject } from '../../util/project.js';
7
+ import { valueOf } from '../args.js';
8
+ export async function eachObservation(ctx, filter, visit) {
9
+ let after = 0;
10
+ let total = 0;
11
+ for (;;) {
12
+ const batch = await ctx.store.list({ ...filter, after, limit: BATCH });
13
+ if (batch.length === 0)
14
+ return total;
15
+ await visit(batch);
16
+ total += batch.length;
17
+ const last = batch[batch.length - 1];
18
+ if (!last)
19
+ return total;
20
+ after = last.createdAt === after ? after + 1 : last.createdAt;
21
+ if (batch.length < BATCH)
22
+ return total;
23
+ }
24
+ }
25
+ export async function cmdExport(argv) {
26
+ const all = argv.includes('--all');
27
+ const ctx = await createContext();
28
+ try {
29
+ const count = await eachObservation(ctx, all ? {} : { project: resolveProject(undefined) }, (batch) => {
30
+ for (const obs of batch)
31
+ process.stdout.write(`${JSON.stringify(obs)}\n`);
32
+ });
33
+ process.stderr.write(`${count} observation(s) exported.\n`);
34
+ }
35
+ finally {
36
+ await ctx.close();
37
+ }
38
+ }
39
+ export async function cmdImport(path) {
40
+ if (!path) {
41
+ console.error('Usage: claude-db import <file.jsonl>');
42
+ process.exit(1);
43
+ }
44
+ const lines = readFileSync(path, 'utf8')
45
+ .split('\n')
46
+ .filter((line) => line.trim().length > 0);
47
+ const ctx = await createContext();
48
+ let imported = 0;
49
+ try {
50
+ for (let i = 0; i < lines.length; i += BATCH) {
51
+ const batch = lines
52
+ .slice(i, i + BATCH)
53
+ .map((line) => JSON.parse(line))
54
+ .filter((obs) => typeof obs.id === 'string' && typeof obs.project === 'string');
55
+ await ctx.store.insertObservations(batch);
56
+ imported += batch.length;
57
+ }
58
+ }
59
+ finally {
60
+ await ctx.close();
61
+ }
62
+ console.log(`Imported ${imported} observation(s).`);
63
+ }
64
+ export async function cmdPrune(argv) {
65
+ const days = Number(valueOf(argv, '--older-than') ?? NaN);
66
+ const kind = valueOf(argv, '--kind');
67
+ const confirmed = argv.includes('--yes') || argv.includes('-y');
68
+ const all = argv.includes('--all');
69
+ if (!Number.isFinite(days) || days <= 0) {
70
+ console.error('Usage: claude-db prune --older-than <days> [--kind <kind>] [--all] --yes');
71
+ process.exit(1);
72
+ }
73
+ const before = Date.now() - days * 86_400_000;
74
+ const filter = {
75
+ before,
76
+ ...(all ? {} : { project: resolveProject(undefined) }),
77
+ ...(kind ? { kind } : {}),
78
+ };
79
+ const ctx = await createContext();
80
+ try {
81
+ if (!confirmed) {
82
+ let matching = 0;
83
+ await eachObservation(ctx, all ? {} : { project: resolveProject(undefined) }, (batch) => {
84
+ for (const obs of batch) {
85
+ if (obs.createdAt < before && (!kind || obs.kind === kind))
86
+ matching += 1;
87
+ }
88
+ });
89
+ console.log(`This would delete ${matching} observation(s) older than ${days} day(s)` +
90
+ `${kind ? ` of kind ${kind}` : ''}.`);
91
+ console.log('\nNothing was deleted. Re-run with --yes to confirm.');
92
+ return;
93
+ }
94
+ const deleted = await ctx.store.remove(filter);
95
+ console.log(`Pruned ${deleted} observation(s).`);
96
+ }
97
+ finally {
98
+ await ctx.close();
99
+ }
100
+ }
101
+ export async function cmdReembed() {
102
+ const base = loadConfig();
103
+ const ctx = await createContext({ embeddings: { ...base.embeddings, timeoutMs: 0 } });
104
+ try {
105
+ const embedder = await ctx.embedder();
106
+ if (embedder.dimensions === 0) {
107
+ console.error('No embedder available; nothing to do.');
108
+ process.exit(1);
109
+ }
110
+ let updated = 0;
111
+ let skipped = 0;
112
+ const scanned = await eachObservation(ctx, {}, async (batch) => {
113
+ const stale = batch.filter((obs) => obs.embedder !== embedder.id);
114
+ skipped += batch.length - stale.length;
115
+ if (stale.length === 0)
116
+ return;
117
+ await embedObservations(ctx, stale);
118
+ await ctx.store.insertObservations(stale);
119
+ updated += stale.length;
120
+ process.stderr.write(`\r${updated} re-embedded...`);
121
+ });
122
+ process.stderr.write('\r');
123
+ console.log(`Scanned ${scanned}, re-embedded ${updated} with ${embedder.id}` +
124
+ `${skipped > 0 ? `, ${skipped} already current` : ''}.`);
125
+ }
126
+ finally {
127
+ await ctx.close();
128
+ }
129
+ }
@@ -0,0 +1 @@
1
+ export declare function cmdUse(argv: (string | undefined)[]): Promise<void>;
@@ -0,0 +1,90 @@
1
+ import { createStore } from '../../store/index.js';
2
+ import { loadConfig, saveConfig } from '../../config/index.js';
3
+ import { redact } from '../../capture/index.js';
4
+ export async function cmdUse(argv) {
5
+ const force = argv.includes('--force');
6
+ const uri = argv.find((arg) => typeof arg === 'string' && !arg.startsWith('-'));
7
+ if (!uri) {
8
+ console.error('Usage: claude-db use [--force] <connection-string>');
9
+ process.exit(1);
10
+ }
11
+ let kind = '';
12
+ let foreign = [];
13
+ let rows = 0;
14
+ try {
15
+ const store = await createStore(uri);
16
+ try {
17
+ if (!(await store.ping()))
18
+ throw new Error('connected, but it did not answer a ping');
19
+ kind = store.kind;
20
+ foreign = await store.inventory();
21
+ await store.init();
22
+ rows = await countObservations(store);
23
+ }
24
+ finally {
25
+ await store.close();
26
+ }
27
+ }
28
+ catch (error) {
29
+ console.error(`Could not reach that database: ${describe(error)}`);
30
+ if (!force) {
31
+ console.error('\nNothing was changed; memory still uses the previous database.');
32
+ console.error('Re-run with --force to save it anyway.');
33
+ process.exit(1);
34
+ }
35
+ }
36
+ const config = loadConfig();
37
+ const previous = config.database;
38
+ config.database = uri;
39
+ saveConfig(config);
40
+ console.log(kind ? `Connected. Using ${kind}.` : 'Saved, unverified.');
41
+ if (foreign.length > 0) {
42
+ const shown = foreign.slice(0, 6).join(', ');
43
+ console.log(`\nNote: this database already holds ${foreign.length} other table(s)/collection(s):`);
44
+ console.log(` ${shown}${foreign.length > 6 ? ', ...' : ''}`);
45
+ console.log('claude-db has added its own next to them. An application database is a');
46
+ console.log('poor place to keep memory; point it elsewhere if that was not deliberate.');
47
+ }
48
+ if (kind && rows === 0)
49
+ await warnAboutStranding(previous, uri);
50
+ }
51
+ async function countObservations(store) {
52
+ return (await store.listProjects()).reduce((total, entry) => total + entry.observations, 0);
53
+ }
54
+ async function warnAboutStranding(previous, uri) {
55
+ if (!previous || previous === uri)
56
+ return;
57
+ let stranded = 0;
58
+ try {
59
+ const store = await createStore(previous);
60
+ try {
61
+ await store.init();
62
+ stranded = await countObservations(store);
63
+ }
64
+ finally {
65
+ await store.close();
66
+ }
67
+ }
68
+ catch {
69
+ return;
70
+ }
71
+ if (stranded === 0)
72
+ return;
73
+ console.log(`\nThe database you just left (${redact(previous)})`);
74
+ console.log(`still holds ${stranded} observation(s), and this one is empty. Nothing moves`);
75
+ console.log('across on its own:');
76
+ console.log(' claude-db use <the previous url> && claude-db export --all > memory.jsonl');
77
+ console.log(' claude-db use <this url> && claude-db import memory.jsonl');
78
+ }
79
+ function describe(error) {
80
+ const message = error instanceof Error ? error.message : String(error);
81
+ if (/ENOTFOUND|EAI_AGAIN/.test(message)) {
82
+ return `${message}\n(that host does not resolve — check the name, or whether the service still exists)`;
83
+ }
84
+ if (/self[- ]signed certificate|unable to verify the first certificate|SELF_SIGNED_CERT/i.test(message)) {
85
+ return (`${message}\n(managed Postgres signs with its own CA, which node does not trust by ` +
86
+ `default —\n append &sslmode=no-verify to the URL, or point &sslrootcert= at the CA ` +
87
+ `file\n the provider gives you)`);
88
+ }
89
+ return message;
90
+ }
@@ -0,0 +1,2 @@
1
+ export declare const DIST_DIR: string;
2
+ export declare const BATCH = 500;
@@ -0,0 +1,4 @@
1
+ import { dirname, resolve } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ export const DIST_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
4
+ export const BATCH = 500;
@@ -0,0 +1,4 @@
1
+ export declare function readText(path: string): string;
2
+ export declare function writeAtomic(path: string, content: string): void;
3
+ export declare function readJson(path: string): Record<string, unknown>;
4
+ export declare function writeJson(path: string, value: unknown): void;
@@ -0,0 +1,33 @@
1
+ import { dirname } from 'node:path';
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ export function readText(path) {
4
+ try {
5
+ return readFileSync(path, 'utf8');
6
+ }
7
+ catch {
8
+ return '';
9
+ }
10
+ }
11
+ export function writeAtomic(path, content) {
12
+ mkdirSync(dirname(path), { recursive: true });
13
+ const temp = `${path}.${process.pid}.tmp`;
14
+ try {
15
+ writeFileSync(temp, content, 'utf8');
16
+ renameSync(temp, path);
17
+ }
18
+ catch (error) {
19
+ rmSync(temp, { force: true });
20
+ throw error;
21
+ }
22
+ }
23
+ export function readJson(path) {
24
+ try {
25
+ return JSON.parse(readFileSync(path, 'utf8'));
26
+ }
27
+ catch {
28
+ return {};
29
+ }
30
+ }
31
+ export function writeJson(path, value) {
32
+ writeAtomic(path, `${JSON.stringify(value, null, 2)}\n`);
33
+ }