remimem 0.0.0-stage → 0.2.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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -2
  3. package/dist/chunker/index.js +129 -0
  4. package/dist/cli/commands.js +256 -0
  5. package/dist/cli/index.js +39 -0
  6. package/dist/cli/program.js +328 -0
  7. package/dist/cli/ui.js +138 -0
  8. package/dist/config/index.js +116 -0
  9. package/dist/dashboard/api.js +196 -0
  10. package/dist/dashboard/graph.js +58 -0
  11. package/dist/dashboard/server.js +164 -0
  12. package/dist/dashboard/ui/app.css +1 -0
  13. package/dist/dashboard/ui/app.js +324 -0
  14. package/dist/dashboard/ui/app.js.LEGAL.txt +18 -0
  15. package/dist/dashboard/ui/index.html +32 -0
  16. package/dist/embedder/index.js +226 -0
  17. package/dist/errors.js +15 -0
  18. package/dist/graph/describe.js +90 -0
  19. package/dist/graph/index.js +224 -0
  20. package/dist/indexer/index.js +183 -0
  21. package/dist/indexer/overview.js +75 -0
  22. package/dist/indexer/watch.js +55 -0
  23. package/dist/log.js +16 -0
  24. package/dist/mcp/server.js +82 -0
  25. package/dist/mcp/tools.js +273 -0
  26. package/dist/memory/index.js +262 -0
  27. package/dist/packer/index.js +149 -0
  28. package/dist/parser/index.js +294 -0
  29. package/dist/retriever/index.js +186 -0
  30. package/dist/scanner/index.js +129 -0
  31. package/dist/stats/index.js +32 -0
  32. package/dist/store/fts.js +26 -0
  33. package/dist/store/index.js +658 -0
  34. package/dist/tokens.js +8 -0
  35. package/grammars/README.md +15 -0
  36. package/grammars/ecma.scm +42 -0
  37. package/grammars/go.scm +37 -0
  38. package/grammars/go.wasm +0 -0
  39. package/grammars/javascript.scm +6 -0
  40. package/grammars/javascript.wasm +0 -0
  41. package/grammars/python.scm +21 -0
  42. package/grammars/python.wasm +0 -0
  43. package/grammars/tsx.wasm +0 -0
  44. package/grammars/typescript.scm +20 -0
  45. package/grammars/typescript.wasm +0 -0
  46. package/package.json +71 -4
@@ -0,0 +1,129 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { closeSync, lstatSync, openSync, readSync, readdirSync, realpathSync } from 'node:fs';
3
+ import { isAbsolute, join, matchesGlob, relative, resolve, sep } from 'node:path';
4
+ import { PathError } from '../errors.js';
5
+ export const DEFAULT_SCAN_OPTIONS = { maxFileSizeKb: 512, include: [], exclude: [] };
6
+ const EXCLUDED_DIRS = new Set([
7
+ '.git',
8
+ '.remimem',
9
+ 'node_modules',
10
+ 'dist',
11
+ 'vendor',
12
+ '__pycache__',
13
+ '.venv',
14
+ 'venv',
15
+ '.next',
16
+ 'coverage',
17
+ ]);
18
+ const LOCKFILES = /^(package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|bun\.lockb|go\.sum|.*\.lock)$/;
19
+ const GENERATED_NAME = /(\.min\.(js|css)|\.map|\.pb\.go|_pb2(_grpc)?\.pyi?)$|\.generated\./;
20
+ const SECRETS = /^(\.env.*|\.npmrc|\.netrc|\.pypirc|id_(rsa|dsa|ecdsa|ed25519).*|.*\.(pem|key|p12|pfx|jks|keystore))$/;
21
+ const GENERATED_HEADER = /Code generated .* DO NOT EDIT|@generated/;
22
+ const HEAD_BYTES = 8192;
23
+ /** True when the path is vendored, generated, a lockfile, or looks like a secret. */
24
+ export function isExcludedPath(path) {
25
+ const parts = path.split('/');
26
+ const base = parts.pop();
27
+ return (parts.some((dir) => EXCLUDED_DIRS.has(dir)) ||
28
+ LOCKFILES.test(base) ||
29
+ GENERATED_NAME.test(base) ||
30
+ SECRETS.test(base));
31
+ }
32
+ /** Resolves `path` against `root` and rejects anything outside it, following symlinks. */
33
+ export function resolveInRoot(root, path) {
34
+ const realRoot = realpathSync(root);
35
+ let target = resolve(realRoot, path);
36
+ try {
37
+ target = realpathSync(target);
38
+ }
39
+ catch {
40
+ // The file does not exist; the lexical check below still applies.
41
+ }
42
+ const rel = relative(realRoot, target);
43
+ if (rel.startsWith('..') || isAbsolute(rel)) {
44
+ throw new PathError(`Path is outside the repository root: ${path}`);
45
+ }
46
+ return target;
47
+ }
48
+ function listFiles(root) {
49
+ try {
50
+ // Tracked files plus untracked files that .gitignore does not exclude.
51
+ return execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
52
+ cwd: root,
53
+ encoding: 'utf8',
54
+ maxBuffer: 1 << 30,
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ })
57
+ .split('\0')
58
+ .filter(Boolean);
59
+ }
60
+ catch {
61
+ // shortcut: without git, .gitignore is not read, only the built-in excludes apply.
62
+ // Add a .gitignore parser if non-git folders turn out to matter.
63
+ const out = [];
64
+ const walk = (dir) => {
65
+ for (const entry of readdirSync(join(root, dir), { withFileTypes: true })) {
66
+ const rel = dir ? `${dir}/${entry.name}` : entry.name;
67
+ if (entry.isDirectory()) {
68
+ if (!EXCLUDED_DIRS.has(entry.name))
69
+ walk(rel);
70
+ }
71
+ else if (entry.isFile()) {
72
+ out.push(rel);
73
+ }
74
+ }
75
+ };
76
+ walk('');
77
+ return out;
78
+ }
79
+ }
80
+ /** True for binary, minified, or generated content, judged from the first bytes of the file. */
81
+ export function hasExcludedContent(file) {
82
+ const buffer = Buffer.alloc(HEAD_BYTES);
83
+ const fd = openSync(file, 'r');
84
+ let length;
85
+ try {
86
+ length = readSync(fd, buffer, 0, HEAD_BYTES, 0);
87
+ }
88
+ finally {
89
+ closeSync(fd);
90
+ }
91
+ const head = buffer.subarray(0, length);
92
+ if (head.includes(0))
93
+ return true;
94
+ const text = head.toString('utf8');
95
+ const minified = text.length >= 2000 && !text.slice(0, 2000).includes('\n');
96
+ return minified || GENERATED_HEADER.test(text.slice(0, 1000));
97
+ }
98
+ /**
99
+ * Files under `root` that pass every check on name, type, and size, sorted by path. Their
100
+ * content has not been looked at yet: see `hasExcludedContent`.
101
+ */
102
+ export function listCandidates(root, options = {}) {
103
+ const opts = { ...DEFAULT_SCAN_OPTIONS, ...options };
104
+ const matches = (globs, path) => globs.some((glob) => matchesGlob(path, glob));
105
+ const files = [];
106
+ for (const listed of new Set(listFiles(root))) {
107
+ const path = listed.split(sep).join('/');
108
+ if (isExcludedPath(path) || matches(opts.exclude, path))
109
+ continue;
110
+ if (opts.include.length > 0 && !matches(opts.include, path))
111
+ continue;
112
+ try {
113
+ const stat = lstatSync(join(root, path));
114
+ if (!stat.isFile())
115
+ continue; // symlinks, submodules, deleted files
116
+ if (stat.size === 0 || stat.size > opts.maxFileSizeKb * 1024)
117
+ continue;
118
+ files.push({ path, sizeBytes: stat.size, mtimeMs: stat.mtimeMs });
119
+ }
120
+ catch {
121
+ continue;
122
+ }
123
+ }
124
+ return files.sort((a, b) => (a.path < b.path ? -1 : 1));
125
+ }
126
+ /** Lists the files worth indexing under `root`, sorted by path. */
127
+ export function scan(root, options = {}) {
128
+ return listCandidates(root, options).filter((file) => !hasExcludedContent(join(root, file.path)));
129
+ }
@@ -0,0 +1,32 @@
1
+ const number = (n) => n.toLocaleString('en-US');
2
+ /**
3
+ * `remimem stats`: what the tools served, against an estimated baseline. The baseline of a
4
+ * query is the size of every whole file that a full result came from, which is what an agent
5
+ * reading files would have loaded to see the same code. Files that only contributed a
6
+ * signature are not counted. Tools that do not return code
7
+ * (references, memory, status) count the same on both sides, so they claim no saving.
8
+ */
9
+ export function formatStats(store) {
10
+ const rows = store.queryLogSummary();
11
+ if (rows.length === 0) {
12
+ return 'No queries logged yet. Queries are logged when an MCP client or `remimem context` uses the index.';
13
+ }
14
+ const total = (pick) => rows.reduce((sum, row) => sum + pick(row), 0);
15
+ const queries = total((r) => r.queries);
16
+ const served = total((r) => r.tokensReturned);
17
+ const baseline = total((r) => r.baselineTokens);
18
+ const saved = baseline - served;
19
+ const since = rows.map((r) => r.since).sort()[0] ?? '';
20
+ const width = Math.max(...rows.map((r) => r.tool.length));
21
+ return [
22
+ `Queries served: ${number(queries)} since ${since.slice(0, 10)}`,
23
+ `Tokens served: ~${number(served)}`,
24
+ `Estimated baseline: ~${number(baseline)} tokens (reading in full every file a result body came from)`,
25
+ `Estimated saving: up to ~${number(saved)} tokens (${baseline > 0 ? Math.round((saved / baseline) * 100) : 0}%)`,
26
+ '',
27
+ 'By tool (queries, tokens served, estimated baseline, mean latency):',
28
+ ...rows.map((r) => ` ${r.tool.padEnd(width)} ${number(r.queries)} ~${number(r.tokensReturned)} ~${number(r.baselineTokens)} ${r.meanLatencyMs} ms`),
29
+ '',
30
+ 'Token counts are approximate, and the baseline is an estimate, not a measurement: it assumes an agent would have read each of those files in full, so treat the saving as an upper bound. `remimem bench` measures savings against a simulated grep-and-read agent.',
31
+ ].join('\n');
32
+ }
@@ -0,0 +1,26 @@
1
+ // Code-friendly tokenization for FTS5. SQLite cannot load a custom tokenizer through
2
+ // better-sqlite3, so text is expanded here before it is indexed or queried: every identifier
3
+ // is kept whole and also split into its camelCase and snake_case parts.
4
+ const WORD = /[\p{L}\p{N}_$]+/gu;
5
+ /** `parseHTTPResponse` gives `['parse', 'http', 'response']`; `find_user` gives `['find', 'user']`. */
6
+ export function identifierParts(identifier) {
7
+ return identifier
8
+ .replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, '$1 $2')
9
+ .replace(/(\p{Lu}+)(\p{Lu}\p{Ll})/gu, '$1 $2')
10
+ .split(/[\s_$]+/)
11
+ .filter(Boolean)
12
+ .map((part) => part.toLowerCase());
13
+ }
14
+ /** Every identifier in lower case, followed by its parts when it has more than one. */
15
+ export function expandTerms(text) {
16
+ const out = [];
17
+ for (const word of text.match(WORD) ?? []) {
18
+ const parts = identifierParts(word);
19
+ out.push(word.toLowerCase());
20
+ if (parts.length > 1)
21
+ out.push(...parts);
22
+ }
23
+ return out;
24
+ }
25
+ /** The text stored in the FTS index for a piece of code, a symbol name, or a path. */
26
+ export const expandForIndex = (text) => expandTerms(text).join(' ');