mnemonad-cli 0.2.0 → 0.3.1

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.
@@ -0,0 +1,171 @@
1
+ import { join } from 'node:path';
2
+ import {
3
+ Indexer, TextWindowChunkingStrategy, VectorIndex, DEFAULT_DB_NAME, DEFAULT_MODEL,
4
+ createProvider, resolveModelName, embedderOfIndex, ModelMismatchError, MissingExtensionError,
5
+ } from '../search/index.js';
6
+ import { FSFolder } from '../FSFolder.js';
7
+ import { resolvePath, DEFAULT_FS_EXCLUDES, userError } from './shared.js';
8
+
9
+ /**
10
+ * The vector index, shared by `mnemonad index` and by `push --index` / `watch --index`.
11
+ * Kept in one place so all three agree on which file it is, which files it covers, and how
12
+ * they're chunked and embedded — an index built by `push --index` is the same index
13
+ * `mnemonad index` would have built.
14
+ *
15
+ * The default filename is at the folder root and not dot-prefixed: unlike `.mnemonad`, it's
16
+ * meant to be pushed and pulled like any other file, so a pull is searchable immediately.
17
+ */
18
+
19
+ /** @returns {string} the index's filename (`--db`, default `search_index.db`). */
20
+ export function indexDbName(args) {
21
+ return args.searchDb || DEFAULT_DB_NAME;
22
+ }
23
+
24
+ /** @returns {string[]} what the index skips: the push's own excludes, plus the index file.
25
+ * The index file itself must never be walked as content to embed — explicit, not left to
26
+ * chance: a SQLite file's own header/padding bytes are plausible-looking text in places,
27
+ * so relying on the binary-content sniff alone to skip it would be fragile. */
28
+ export function indexExcludes(args) {
29
+ const excludes = [...DEFAULT_FS_EXCLUDES, indexDbName(args)];
30
+ if (args.exclude) excludes.push(...args.exclude.split(',').map((s) => s.trim()));
31
+ return excludes;
32
+ }
33
+
34
+ function chunkingFrom(args) {
35
+ return new TextWindowChunkingStrategy({
36
+ size: args.chunkSize ?? 1000,
37
+ overlap: args.chunkOverlap ?? 150,
38
+ });
39
+ }
40
+
41
+ /**
42
+ * Which model to index `destPath` with. An explicit `--model` wins (an alias like `minilm`, or
43
+ * a full id). Without one, an existing index keeps the model it was built with — so re-indexing
44
+ * a folder someone indexed with MiniLM just works — and only a new index (or `--rebuild`)
45
+ * gets the built-in default.
46
+ *
47
+ * @returns {{model: string, embedder: ?string, dtype: ?string}}
48
+ */
49
+ export function chooseModel(destPath, args) {
50
+ if (args.model) return { model: resolveModelName(args.model), embedder: null, dtype: null };
51
+ const meta = args.rebuild ? null : VectorIndex.readMeta(join(destPath, indexDbName(args)));
52
+ if (meta?.model) {
53
+ return { model: meta.model, embedder: embedderOfIndex(meta), dtype: meta.dtype || null };
54
+ }
55
+ return { model: DEFAULT_MODEL, embedder: null, dtype: null };
56
+ }
57
+
58
+ /**
59
+ * An Indexer configured from the CLI flags. Hold on to it across runs (as `watch --index`
60
+ * does) and the embedding model loads once, on first use, instead of on every run.
61
+ * Rejects straight away on bad chunking flags or a missing extension, before anything is
62
+ * read or written.
63
+ */
64
+ export async function makeIndexer(destPath, args) {
65
+ const chunkingStrategy = chunkingFrom(args);
66
+ const { model, embedder, dtype } = chooseModel(destPath, args);
67
+ let embeddingProvider;
68
+ try {
69
+ embeddingProvider = await createProvider({ model, ...(embedder ? { embedder } : {}), dtype });
70
+ } catch (err) {
71
+ throw explainIndexError(err, destPath, args);
72
+ }
73
+ return new Indexer({ embeddingProvider, chunkingStrategy });
74
+ }
75
+
76
+ /**
77
+ * Builds or updates `destPath`'s index, printing the same summary `mnemonad index` does.
78
+ *
79
+ * @param {string} destPath - resolved folder path
80
+ * @param {Object} args - parsed CLI args (`rebuild` starts the index over)
81
+ * @param {Object} [opts]
82
+ * @param {Indexer} [opts.indexer] - reuse one (and its loaded model) across calls
83
+ * @param {boolean} [opts.quiet] - one summary line instead of the full report
84
+ * @param {boolean} [opts.rebuild] - overrides `args.rebuild` (watch rebuilds only once)
85
+ * @returns {Promise<{filesChanged: number, filesSkipped: number, filesRemoved: number, chunksAdded: number}>}
86
+ */
87
+ export async function updateIndex(destPath, args, { indexer = null, quiet = false, rebuild = args.rebuild } = {}) {
88
+ indexer = indexer || await makeIndexer(destPath, { ...args, rebuild });
89
+ const dbName = indexDbName(args);
90
+ const fsFolder = new FSFolder(destPath, indexExcludes(args));
91
+
92
+ if (!quiet) {
93
+ console.log(' embedding model:', indexer.embeddingProvider.modelId, '(downloads and caches on first use)');
94
+ if (rebuild) console.log(` rebuilding ${dbName} from scratch`);
95
+ console.log(' scanning for changed files...');
96
+ }
97
+ let result;
98
+ try {
99
+ result = await indexer.index(fsFolder, join(destPath, dbName), { rebuild: !!rebuild });
100
+ } catch (err) {
101
+ throw explainIndexError(err, destPath, args);
102
+ }
103
+
104
+ if (quiet) {
105
+ const changed = result.filesChanged + result.filesRemoved;
106
+ console.log(changed
107
+ ? ` index: ${result.filesChanged} file(s) re-embedded, ${result.filesRemoved} removed (${result.chunksAdded} chunks)`
108
+ : ' index: up to date');
109
+ } else {
110
+ console.log(' files changed:', result.filesChanged);
111
+ console.log(' files skipped:', result.filesSkipped, '(content unchanged since last index)');
112
+ console.log(' files removed:', result.filesRemoved);
113
+ console.log(' chunks added: ', result.chunksAdded);
114
+ }
115
+ return result;
116
+ }
117
+
118
+ /**
119
+ * How far `destPath`'s index has drifted from its files, without updating it — no model is
120
+ * loaded (not even the extension looked up) and the index is opened read-only (see
121
+ * Indexer.status()). Null when there's no index.
122
+ *
123
+ * @returns {Promise<?{changed: string[], added: string[], removed: string[], total: number}>}
124
+ */
125
+ export async function checkIndex(destPath, args) {
126
+ const fsFolder = new FSFolder(destPath, indexExcludes(args));
127
+ // Chunking decides which files count (an empty one is never indexed), so it's configured
128
+ // exactly as for a real run; status() never embeds, so no provider is needed.
129
+ const indexer = new Indexer({ embeddingProvider: null, chunkingStrategy: chunkingFrom(args) });
130
+ const status = await indexer.status(fsFolder, join(destPath, indexDbName(args)));
131
+ if (!status) return null;
132
+ return { ...status, total: status.changed.length + status.added.length + status.removed.length };
133
+ }
134
+
135
+ /** Turns the two errors a user can act on into CLI messages that say what to do. */
136
+ function explainIndexError(err, destPath, args) {
137
+ if (err instanceof MissingExtensionError) {
138
+ const lines = [err.message];
139
+ if (!args.model) {
140
+ lines.push(
141
+ ' Or rebuild the index with the built-in model instead:',
142
+ ` mnemonad index ${destPath} --rebuild`,
143
+ );
144
+ }
145
+ return userError(lines.join('\n'));
146
+ }
147
+ if (err instanceof ModelMismatchError) {
148
+ return userError(
149
+ `${indexDbName(args)} was built with ${err.indexModel}, but this run asked for ${err.providerModel} —\n` +
150
+ ' one index can\'t mix two models. Either drop --model to keep using the index\'s own model, or\n' +
151
+ ` add --rebuild to re-embed every file with ${err.providerModel} (the next push then uploads the\n` +
152
+ ' whole index again).'
153
+ );
154
+ }
155
+ return err;
156
+ }
157
+
158
+ /** `mnemonad index <path>` */
159
+ export async function buildIndex(args) {
160
+ const destPath = resolvePath(args.path, { mustExist: true });
161
+ const result = await updateIndex(destPath, args);
162
+
163
+ if (result.filesChanged > 0 || result.filesRemoved > 0) {
164
+ // Said explicitly rather than left implicit: unlike `.mnemonad`, this file is not
165
+ // dot-prefixed, so the very next `push` from this folder includes it automatically —
166
+ // worth knowing before that push happens, not after.
167
+ console.log(`\n note: ${indexDbName(args)} will be included in the next \`mnemonad push\` from this folder`);
168
+ } else {
169
+ console.log('\n no changes — nothing new to push');
170
+ }
171
+ }
@@ -21,7 +21,7 @@ export async function burn(args) {
21
21
  throw new Error('stream-id is required for burn');
22
22
  }
23
23
 
24
- const client = makeChainClient(args);
24
+ const client = await makeChainClient(args);
25
25
  requireWalletClient(client);
26
26
 
27
27
  const mn = new Mnemonad({
@@ -12,6 +12,7 @@ import {
12
12
  resolveOffloadParams,
13
13
  discoverStreamId,
14
14
  } from './shared.js';
15
+ import { settleStreamJobs } from '../jobs.js';
15
16
 
16
17
  /**
17
18
  * Monad has no rebate/refund concept — truncating a stream's history here gives back no
@@ -28,13 +29,14 @@ export async function compact(args) {
28
29
  if (!args.streamId) {
29
30
  throw new Error('stream-id is required for compact');
30
31
  }
32
+ await settleStreamJobs(args, { reason: 'before replacing the history with a fresh snapshot' });
31
33
 
32
34
  const fsFolder = new FSFolder(destPath, makeExcludes(args));
33
35
 
34
36
  const counts = await countTree(fsFolder);
35
37
  console.log(' scanning...', counts.files, 'files,', counts.folders, 'folders');
36
38
 
37
- const client = makeChainClient(args);
39
+ const client = await makeChainClient(args);
38
40
  requireWalletClient(client);
39
41
 
40
42
  // No `password` at construction — see shared.js's unlockStream() for why.
@@ -12,6 +12,7 @@ import {
12
12
  folderExists,
13
13
  discoverStreamId,
14
14
  } from './shared.js';
15
+ import { settleStreamJobs } from '../jobs.js';
15
16
 
16
17
  export function compareFileMaps(localFiles, remoteFiles) {
17
18
  const added = [];
@@ -55,8 +56,9 @@ export async function diff(args) {
55
56
  if (!args.streamId) {
56
57
  throw new Error('stream-id is required for diff');
57
58
  }
59
+ await settleStreamJobs(args, { wait: false });
58
60
 
59
- const client = makeChainClient(args);
61
+ const client = await makeChainClient(args);
60
62
 
61
63
  const mn = new Mnemonad({
62
64
  publicClient: client.publicClient,
@@ -5,3 +5,5 @@ export { diff } from './diff.js';
5
5
  export { watch } from './watch.js';
6
6
  export { compact } from './compact.js';
7
7
  export { burn } from './burn.js';
8
+ export { buildIndex } from './buildIndex.js';
9
+ export { search } from './search.js';
@@ -12,9 +12,10 @@ import {
12
12
  readManifest,
13
13
  streamIdsEqual,
14
14
  } from './shared.js';
15
+ import { streamKey, latestJob, describeJob } from '../jobs.js';
15
16
 
16
17
  export async function info(args) {
17
- const client = makeChainClient(args);
18
+ const client = await makeChainClient(args);
18
19
 
19
20
  console.log(' chain: ', args.chain);
20
21
  console.log(' your wallet: ', client.account?.address || '(none)');
@@ -45,6 +46,14 @@ export async function info(args) {
45
46
  }
46
47
  }
47
48
 
49
+ // The last background push (`push --detach`) for this stream, whichever way its id is
50
+ // known — even with no --manifest, the folder's own manifest names the stream.
51
+ const jobStreamId = args.streamId || manifest?.streamId;
52
+ if (jobStreamId) {
53
+ const job = latestJob(streamKey({ chain: args.chain, contractAddress: args.contractAddress, streamId: jobStreamId }));
54
+ if (job) console.log(' background push:', describeJob(job));
55
+ }
56
+
48
57
  if (!args.streamId) {
49
58
  return;
50
59
  }
@@ -11,6 +11,7 @@ import {
11
11
  formatStreamId,
12
12
  discoverStreamId,
13
13
  } from './shared.js';
14
+ import { settleStreamJobs } from '../jobs.js';
14
15
 
15
16
  export async function pull(args) {
16
17
  // Resolved up front (throws if missing) so a missing path fails fast, before any chain
@@ -24,7 +25,11 @@ export async function pull(args) {
24
25
  throw new Error('stream-id is required for pull');
25
26
  }
26
27
 
27
- const client = makeChainClient(args);
28
+ // Pulling while a background push of this folder is still sending would restore the
29
+ // version before it — and delete the very files that push is uploading.
30
+ await settleStreamJobs(args, { reason: 'so the pull includes it' });
31
+
32
+ const client = await makeChainClient(args);
28
33
 
29
34
  const mn = new Mnemonad({
30
35
  publicClient: client.publicClient,
@@ -18,7 +18,13 @@ import {
18
18
  formatStreamId,
19
19
  streamIdsEqual,
20
20
  discoverStreamId,
21
+ userError,
22
+ formatBytes,
23
+ formatPath,
21
24
  } from './shared.js';
25
+ import { updateIndex, checkIndex, indexDbName } from './buildIndex.js';
26
+ import { streamKey, waitForJobs, settleStreamJobs, startPushJob } from '../jobs.js';
27
+ import { formatEther } from 'viem';
22
28
 
23
29
  export async function push(args) {
24
30
  const destPath = resolvePath(args.path, { mustExist: true });
@@ -29,6 +35,42 @@ export async function push(args) {
29
35
  await discoverStreamId(args, destPath);
30
36
  let streamId = args.streamId;
31
37
 
38
+ if (args.detach) {
39
+ // Creating a stream prints the id the user has to keep, and needs signatures that have
40
+ // to be seen to succeed — nothing worth handing off. --passkey's signer is a browser
41
+ // tab that closes when this process exits.
42
+ if (!streamId) {
43
+ throw userError(
44
+ '--detach only pushes to an existing stream. Pass its id, or --manifest on a folder\n' +
45
+ ' that has a .mnemonad, or push once without --detach to create the stream first.'
46
+ );
47
+ }
48
+ if (args.passkey) {
49
+ throw userError('--detach can\'t be combined with --passkey: the browser tab signing for it closes when this command exits.');
50
+ }
51
+ }
52
+
53
+ // A background push still sending to this stream means its next version isn't on chain
54
+ // yet — building on top of the current tip now would only lose the race to it.
55
+ await settleStreamJobs(args, { reason: 'before building the next version on top of it' });
56
+
57
+ // Before anything is scanned or signed: the push below then picks the updated index up
58
+ // like any other file. A failure stops the push outright — a push that silently went out
59
+ // without the index asked for would leave the stream unsearchable with no sign of why.
60
+ if (args.rebuild && !args.index) {
61
+ throw userError('--rebuild only applies with --index (it starts the search index over)');
62
+ }
63
+ if (args.index) {
64
+ console.log(args.rebuild ? ' rebuilding search index...' : ' updating search index...');
65
+ try {
66
+ await updateIndex(destPath, args, { quiet: true });
67
+ } catch (err) {
68
+ throw userError(`indexing failed, so nothing was pushed: ${err.message}`);
69
+ }
70
+ } else {
71
+ await warnIfIndexStale(destPath, args);
72
+ }
73
+
32
74
  const fsFolder = new FSFolder(destPath, makeExcludes(args));
33
75
 
34
76
  const counts = await countTree(fsFolder);
@@ -45,9 +87,15 @@ export async function push(args) {
45
87
  }
46
88
  }
47
89
 
48
- const client = makeChainClient(args);
90
+ const client = await makeChainClient(args);
49
91
  requireWalletClient(client);
50
92
 
93
+ // Same wallet, different stream: two processes sending at once would race for one nonce.
94
+ await waitForJobs(
95
+ { signer: client.account.address, chain: args.chain },
96
+ { reason: 'so the two pushes don\'t race for the same wallet nonce' },
97
+ );
98
+
51
99
  const baseParams = {
52
100
  publicClient: client.publicClient,
53
101
  walletClient: client.walletClient,
@@ -120,6 +168,11 @@ export async function push(args) {
120
168
  }
121
169
  }
122
170
 
171
+ if (args.detach) {
172
+ await detachPush({ args, mn, monadSync, fsFolder, client, streamId, destPath, existingVersions });
173
+ return;
174
+ }
175
+
123
176
  console.log(' building patch + pushing to chain...');
124
177
  const result = await monadSync.push(fsFolder);
125
178
 
@@ -136,3 +189,101 @@ export async function push(args) {
136
189
  await writeManifest(destPath, { streamId: formatStreamId(streamId), version: result.version, files: localFiles });
137
190
  }
138
191
  }
192
+
193
+ /**
194
+ * `push --detach`: everything up to a finished patch runs here, so every error a user can act
195
+ * on still surfaces before this command exits. Only the sending — transactions, receipts, an
196
+ * IPFS upload — goes to a detached child (see lib/jobs.js), and this process exits as soon
197
+ * as it has started.
198
+ *
199
+ * The patch is frozen now: files edited after this command returns go into the next push,
200
+ * not this one. The manifest's file hashes are taken at the same moment for the same reason.
201
+ */
202
+ async function detachPush({ args, mn, monadSync, fsFolder, client, streamId, destPath, existingVersions }) {
203
+ console.log(' building patch...');
204
+ const prepared = await monadSync.preparePush(fsFolder);
205
+
206
+ // A single-item patch is the common case and the only one estimatePushCost models; a
207
+ // segmented one (over 8 MB) just goes without an estimate rather than a wrong one.
208
+ let cost = null;
209
+ if (prepared.itemCount === 1) {
210
+ try {
211
+ cost = await mn.estimatePushCost(prepared.patchBytes);
212
+ } catch {
213
+ // No estimate is not a reason to stop — the child surfaces any real send error.
214
+ }
215
+ }
216
+ if (cost) {
217
+ const balance = await client.publicClient.getBalance({ address: client.account.address });
218
+ if (balance < cost.total) {
219
+ throw userError(
220
+ `not enough MON to push: about ${formatEther(cost.total)} needed, ` +
221
+ `${formatEther(balance)} in ${client.account.address}. Nothing was sent.`
222
+ );
223
+ }
224
+ }
225
+
226
+ const files = args.manifest ? await hashLocalTree(fsFolder) : null;
227
+ const job = await startPushJob(
228
+ {
229
+ streamId: formatStreamId(streamId),
230
+ streamKey: streamKey({ chain: args.chain, contractAddress: args.contractAddress, streamId }),
231
+ chain: args.chain,
232
+ signer: client.account.address,
233
+ folder: destPath,
234
+ baseLength: prepared.baseLength,
235
+ version: prepared.version,
236
+ kind: prepared.kind,
237
+ bytes: prepared.patchBytes.length,
238
+ manifest: files ? { files } : null,
239
+ // Everything the child needs to rebuild the same chain client — never a secret.
240
+ args: {
241
+ chain: args.chain,
242
+ rpcUrl: args.rpcUrl,
243
+ contractAddress: args.contractAddress,
244
+ gatewayUrl: args.gatewayUrl,
245
+ presignUrl: args.presignUrl,
246
+ },
247
+ },
248
+ prepared.patchBytes,
249
+ {
250
+ key: args.key || process.env.MNEMONAD_KEY || null,
251
+ phrase: args.phrase,
252
+ password: args.password,
253
+ pinataJwt: args.pinataJwt,
254
+ },
255
+ );
256
+
257
+ const patchType = existingVersions === 0 || prepared.kind === 'patch' ? 'full snapshot' : 'diff';
258
+ const compressedNote = args.compress !== false ? ', gzip compressed' : '';
259
+ console.log(' version', prepared.version, 'prepared (' + patchType + compressedNote + ', ' + formatBytes(prepared.patchBytes.length) + ')');
260
+ if (cost) console.log(' estimated cost:', formatEther(cost.total), 'MON');
261
+ console.log(' stream:', formatStreamId(streamId));
262
+ console.log(' sending in the background: job', job.id, '(pid ' + job.pid + ')');
263
+ console.log(' log: ', formatPath(job.dir + '/push.log'));
264
+ console.log(' check: mnemonad info', formatPath(destPath) + (args.manifest ? ' --manifest' : ''));
265
+ }
266
+
267
+ /**
268
+ * A folder that already carries an index, pushed without `--index` after its files changed,
269
+ * would publish an index that no longer matches them — searches keep returning the old text's
270
+ * offsets. Cheap to catch (a hash per file, no model load, the index opened read-only) and
271
+ * worth a line; never a reason to fail the push itself.
272
+ */
273
+ async function warnIfIndexStale(destPath, args) {
274
+ let status;
275
+ try {
276
+ status = await checkIndex(destPath, args);
277
+ } catch {
278
+ return;
279
+ }
280
+ if (!status || status.total === 0) return;
281
+ const parts = [];
282
+ if (status.changed.length) parts.push(`${status.changed.length} changed`);
283
+ if (status.added.length) parts.push(`${status.added.length} new`);
284
+ if (status.removed.length) parts.push(`${status.removed.length} removed`);
285
+ console.log(
286
+ ` note: ${indexDbName(args)} is out of date (${parts.join(', ')} file(s) since it was built).\n` +
287
+ ' Push with --index to update it first, or run `mnemonad index <path>`.'
288
+ );
289
+ }
@@ -0,0 +1,91 @@
1
+ import { join } from 'node:path';
2
+ import {
3
+ Searcher, VectorIndex, DEFAULT_DB_NAME, createProvider, resolveModelName, MissingExtensionError,
4
+ } from '../search/index.js';
5
+ import { resolvePath, folderExists } from './shared.js';
6
+
7
+ export async function search(args) {
8
+ if (!args.query) {
9
+ throw userError('a search query is required (e.g. `mnemonad search /path/to/folder "how does chunking work"`)');
10
+ }
11
+ const destPath = resolvePath(args.path, { mustExist: true });
12
+ const dbName = args.searchDb || DEFAULT_DB_NAME;
13
+ const dbPath = join(destPath, dbName);
14
+
15
+ if (!folderExists(destPath) || !(await _fileExists(dbPath))) {
16
+ throw userError(
17
+ `no ${dbName} found in ${destPath}\n` +
18
+ ' Run `mnemonad index <path>` first — either yours, or whoever pushed this stream\'s\n' +
19
+ ' (a pull already brings theirs down with the rest of the folder).'
20
+ );
21
+ }
22
+
23
+ // The query has to be embedded by the model that built the index — which the index records,
24
+ // so there's nothing to choose. An explicit --model that disagrees is a mistake worth
25
+ // naming rather than a preference to honour.
26
+ const indexModel = VectorIndex.readMeta(dbPath)?.model;
27
+ if (args.model && indexModel && resolveModelName(args.model) !== indexModel) {
28
+ throw userError(
29
+ `${dbName} was built with ${indexModel}; a search has to use the same model — drop --model\n` +
30
+ ' (search always uses the index\'s own), or rebuild the index with the other one:\n' +
31
+ ` mnemonad index ${destPath} --model ${args.model} --rebuild`
32
+ );
33
+ }
34
+
35
+ const searcher = new Searcher({ createProvider });
36
+ const k = args.limit ? Number(args.limit) : 5;
37
+ let hits;
38
+ try {
39
+ hits = await searcher.search(dbPath, args.query, k);
40
+ } catch (err) {
41
+ if (err instanceof MissingExtensionError) {
42
+ throw userError(
43
+ `this folder's index was built with ${err.model}, which ${err.message.slice(err.message.indexOf('needs'))}\n` +
44
+ ' Or rebuild the index with the built-in model:\n' +
45
+ ` mnemonad index ${destPath} --rebuild`
46
+ );
47
+ }
48
+ throw err;
49
+ }
50
+
51
+ if (hits.length === 0) {
52
+ console.log(' no matches');
53
+ return;
54
+ }
55
+
56
+ for (const [i, hit] of hits.entries()) {
57
+ console.log(`\n${i + 1}. ${hit.path} (chunk ${hit.chunkIndex}, distance ${hit.distance.toFixed(4)})`);
58
+ const snippet = await _readSnippet(destPath, hit);
59
+ if (snippet) console.log(' ' + snippet.replace(/\s+/g, ' ').slice(0, 200));
60
+ }
61
+ }
62
+
63
+ async function _fileExists(path) {
64
+ try {
65
+ const { stat } = await import('node:fs/promises');
66
+ const s = await stat(path);
67
+ return s.isFile();
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /** Re-reads the hit's snippet straight from the already-pulled source file — the index
74
+ * deliberately doesn't store chunk text itself (see ../search/VectorIndex.js),
75
+ * so this is the one place that cost is paid, and only for hits actually shown. */
76
+ async function _readSnippet(destPath, hit) {
77
+ try {
78
+ const { readFile } = await import('node:fs/promises');
79
+ const bytes = await readFile(join(destPath, hit.path));
80
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
81
+ return text.slice(hit.startOffset, hit.endOffset);
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+
87
+ function userError(message) {
88
+ const err = new Error(message);
89
+ err._isUserError = true;
90
+ return err;
91
+ }
@@ -12,7 +12,7 @@ import { DoubleSync as SyncEngine, CDCStore, DoubleSyncSnapshot as SyncSnapshot
12
12
  import { FSFolder } from '../FSFolder.js';
13
13
  import { createPresignProvider } from '../presignProvider.js';
14
14
 
15
- const DEFAULT_FS_EXCLUDES = ['node_modules', '.git', '.env', '.DS_Store', '.mnemonad', '.claude', 'pnpm-lock.yaml', 'package-lock.json'];
15
+ export const DEFAULT_FS_EXCLUDES = ['node_modules', '.git', '.env', '.DS_Store', '.mnemonad', '.claude', 'pnpm-lock.yaml', 'package-lock.json'];
16
16
 
17
17
  export function makeExcludes(args) {
18
18
  if (!args.exclude) return undefined;
@@ -305,7 +305,8 @@ export async function unlockStream(mn, credentials = {}) {
305
305
  return true;
306
306
  }
307
307
 
308
- function userError(message) {
308
+ /** An error the CLI prints as a plain message (no stack trace) — see bin/mnemonad.js. */
309
+ export function userError(message) {
309
310
  const err = new Error(message);
310
311
  err._isUserError = true;
311
312
  return err;