@functional-systems/memdrive 0.1.1-dev.1 → 0.1.1-dev.3

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 (117) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +20 -250
  3. package/dist/commonjs/chunking.d.ts +1 -2
  4. package/dist/commonjs/chunking.d.ts.map +1 -1
  5. package/dist/commonjs/chunking.js +2 -5
  6. package/dist/commonjs/chunking.js.map +1 -1
  7. package/dist/commonjs/config.d.ts +17 -0
  8. package/dist/commonjs/config.d.ts.map +1 -0
  9. package/dist/commonjs/config.js +116 -0
  10. package/dist/commonjs/config.js.map +1 -0
  11. package/dist/commonjs/errors.d.ts +10 -6
  12. package/dist/commonjs/errors.d.ts.map +1 -1
  13. package/dist/commonjs/errors.js +25 -5
  14. package/dist/commonjs/errors.js.map +1 -1
  15. package/dist/commonjs/index.d.ts +15 -5
  16. package/dist/commonjs/index.d.ts.map +1 -1
  17. package/dist/commonjs/index.js +331 -307
  18. package/dist/commonjs/index.js.map +1 -1
  19. package/dist/commonjs/records.d.ts +44 -0
  20. package/dist/commonjs/records.d.ts.map +1 -0
  21. package/dist/commonjs/records.js +88 -0
  22. package/dist/commonjs/records.js.map +1 -0
  23. package/dist/commonjs/search.d.ts +8 -0
  24. package/dist/commonjs/search.d.ts.map +1 -0
  25. package/dist/commonjs/search.js +56 -0
  26. package/dist/commonjs/search.js.map +1 -0
  27. package/dist/commonjs/types.d.ts +84 -252
  28. package/dist/commonjs/types.d.ts.map +1 -1
  29. package/dist/esm/chunking.d.ts +1 -2
  30. package/dist/esm/chunking.d.ts.map +1 -1
  31. package/dist/esm/chunking.js +2 -4
  32. package/dist/esm/chunking.js.map +1 -1
  33. package/dist/esm/config.d.ts +17 -0
  34. package/dist/esm/config.d.ts.map +1 -0
  35. package/dist/esm/config.js +107 -0
  36. package/dist/esm/config.js.map +1 -0
  37. package/dist/esm/errors.d.ts +10 -6
  38. package/dist/esm/errors.d.ts.map +1 -1
  39. package/dist/esm/errors.js +22 -4
  40. package/dist/esm/errors.js.map +1 -1
  41. package/dist/esm/index.d.ts +15 -5
  42. package/dist/esm/index.d.ts.map +1 -1
  43. package/dist/esm/index.js +331 -305
  44. package/dist/esm/index.js.map +1 -1
  45. package/dist/esm/records.d.ts +44 -0
  46. package/dist/esm/records.d.ts.map +1 -0
  47. package/dist/esm/records.js +77 -0
  48. package/dist/esm/records.js.map +1 -0
  49. package/dist/esm/search.d.ts +8 -0
  50. package/dist/esm/search.d.ts.map +1 -0
  51. package/dist/esm/search.js +52 -0
  52. package/dist/esm/search.js.map +1 -0
  53. package/dist/esm/types.d.ts +84 -252
  54. package/dist/esm/types.d.ts.map +1 -1
  55. package/package.json +10 -32
  56. package/src/chunking.ts +2 -3
  57. package/src/config.ts +121 -0
  58. package/src/errors.ts +20 -6
  59. package/src/index.ts +351 -289
  60. package/src/records.ts +83 -0
  61. package/src/search.ts +57 -0
  62. package/src/types.ts +74 -253
  63. package/dist/commonjs/filter.d.ts +0 -30
  64. package/dist/commonjs/filter.d.ts.map +0 -1
  65. package/dist/commonjs/filter.js +0 -224
  66. package/dist/commonjs/filter.js.map +0 -1
  67. package/dist/commonjs/storage.d.ts +0 -274
  68. package/dist/commonjs/storage.d.ts.map +0 -1
  69. package/dist/commonjs/storage.js +0 -861
  70. package/dist/commonjs/storage.js.map +0 -1
  71. package/dist/commonjs/tools/definitions.d.ts +0 -5
  72. package/dist/commonjs/tools/definitions.d.ts.map +0 -1
  73. package/dist/commonjs/tools/definitions.js +0 -129
  74. package/dist/commonjs/tools/definitions.js.map +0 -1
  75. package/dist/commonjs/tools/index.d.ts +0 -6
  76. package/dist/commonjs/tools/index.d.ts.map +0 -1
  77. package/dist/commonjs/tools/index.js +0 -104
  78. package/dist/commonjs/tools/index.js.map +0 -1
  79. package/dist/commonjs/tools/types.d.ts +0 -50
  80. package/dist/commonjs/tools/types.d.ts.map +0 -1
  81. package/dist/commonjs/tools/types.js +0 -3
  82. package/dist/commonjs/tools/types.js.map +0 -1
  83. package/dist/commonjs/values.d.ts +0 -17
  84. package/dist/commonjs/values.d.ts.map +0 -1
  85. package/dist/commonjs/values.js +0 -90
  86. package/dist/commonjs/values.js.map +0 -1
  87. package/dist/esm/filter.d.ts +0 -30
  88. package/dist/esm/filter.d.ts.map +0 -1
  89. package/dist/esm/filter.js +0 -209
  90. package/dist/esm/filter.js.map +0 -1
  91. package/dist/esm/storage.d.ts +0 -274
  92. package/dist/esm/storage.d.ts.map +0 -1
  93. package/dist/esm/storage.js +0 -845
  94. package/dist/esm/storage.js.map +0 -1
  95. package/dist/esm/tools/definitions.d.ts +0 -5
  96. package/dist/esm/tools/definitions.d.ts.map +0 -1
  97. package/dist/esm/tools/definitions.js +0 -126
  98. package/dist/esm/tools/definitions.js.map +0 -1
  99. package/dist/esm/tools/index.d.ts +0 -6
  100. package/dist/esm/tools/index.d.ts.map +0 -1
  101. package/dist/esm/tools/index.js +0 -101
  102. package/dist/esm/tools/index.js.map +0 -1
  103. package/dist/esm/tools/types.d.ts +0 -50
  104. package/dist/esm/tools/types.d.ts.map +0 -1
  105. package/dist/esm/tools/types.js +0 -2
  106. package/dist/esm/tools/types.js.map +0 -1
  107. package/dist/esm/values.d.ts +0 -17
  108. package/dist/esm/values.d.ts.map +0 -1
  109. package/dist/esm/values.js +0 -87
  110. package/dist/esm/values.js.map +0 -1
  111. package/docs/tools.md +0 -163
  112. package/src/filter.ts +0 -189
  113. package/src/storage.ts +0 -765
  114. package/src/tools/definitions.ts +0 -156
  115. package/src/tools/index.ts +0 -97
  116. package/src/tools/types.ts +0 -45
  117. package/src/values.ts +0 -103
package/dist/esm/index.js CHANGED
@@ -1,335 +1,361 @@
1
- import { createBackend, openBackend, listBackends, validateChunk, publicMatch, validateVector, vectorMatch } from './storage.js';
2
- import { buildSearchFilter, validateFilter, matchesFilter } from './filter.js';
3
- import { MemDriveError, requireInput, operationOptions, checkAbort, abortError } from './errors.js';
4
- import { createValueCounter } from './values.js';
1
+ import { checkAbort, databaseError, MemDriveError, nativeOptions, nativeRequest, operationOptions, requireInput } from './errors.js';
2
+ import { keysOnly, parseStore, storeConfiguration } from './config.js';
3
+ import { bytes, decodeFile, fileRecords, originalId, resultDocs, validFileId, validPath } from './records.js';
4
+ import { searchQuery, validateReranking } from './search.js';
5
5
  export { MemDriveError } from './errors.js';
6
- const keys = (value, allowed) => value !== null && typeof value === 'object' && !Array.isArray(value)
7
- && Object.keys(value).every(key => allowed.includes(key));
8
- const nonempty = (value) => typeof value === 'string' && value.trim().length > 0;
9
- function validateOptions(options, creating) {
10
- requireInput(keys(options, ['client', 'name', 'maxConcurrentRequests', 'observe', 'record',
11
- ...(creating ? ['metadataSchema', 'textSearch', 'embedding', 'labels', 'description'] : ['branch'])]), 'Use the documented MemDrive options.');
12
- requireInput(creating || options.branch === undefined || (typeof options.branch === 'string'
13
- && /^[A-Za-z0-9_-]{3,52}$/.test(options.branch)), 'branch must be a valid branch name.');
14
- if (creating && options.embedding?.mode === 'external')
15
- requireInput(options.textSearch === undefined, 'External embeddings do not support textSearch.');
16
- const concurrency = options.maxConcurrentRequests ?? 5;
17
- requireInput(Number.isSafeInteger(concurrency) && concurrency > 0, 'maxConcurrentRequests must be a positive integer.');
18
- for (const name of ['observe', 'record'])
19
- requireInput(options[name] === undefined || typeof options[name] === 'function', `${name} must be a callback.`);
20
- return { ...options };
6
+ const main = 'main';
7
+ const prefix = 'fork-';
8
+ const clients = new WeakMap();
9
+ const requestMaxBytes = 6_029_312;
10
+ const maximumInputBytes = 300_000;
11
+ const maximumRequestDocuments = 1000;
12
+ const writeBatchLimit = 100;
13
+ const validName = (name, maxLength = 52) => typeof name === 'string' && name.length >= 3 && name.length <= maxLength && /^[A-Za-z0-9_-]+$/.test(name);
14
+ const validForkName = (name) => validName(name, 52 - prefix.length) && name !== main;
15
+ function validateConnection(options, keys) {
16
+ requireInput(keysOnly(options, keys) && options.client !== null && typeof options.client === 'object'
17
+ && 'collection' in options.client && typeof options.client.collection === 'function', 'Provide a LambdaDB client and documented file store options.');
18
+ requireInput(validName(options.name), 'Store name must be 3–52 letters, digits, underscores or hyphens.');
21
19
  }
22
- // Separate queues bound logical recalls and database work across all branch views.
23
- function requestQueue(limit) {
24
- let active = 0;
25
- const waiting = [];
26
- return (operation, signal) => new Promise((resolve, reject) => {
27
- try {
28
- checkAbort(signal);
29
- }
30
- catch (error) {
31
- reject(error);
32
- return;
33
- }
34
- const entry = { start() {
35
- signal?.removeEventListener('abort', cancel);
36
- active++;
37
- Promise.resolve().then(() => { checkAbort(signal); return operation(); }).then(resolve, reject).finally(() => {
38
- active--;
39
- waiting.shift()?.start();
40
- });
41
- } };
42
- const cancel = () => {
43
- const index = waiting.indexOf(entry);
44
- if (index < 0)
45
- return;
46
- waiting.splice(index, 1);
47
- signal?.removeEventListener('abort', cancel);
48
- reject(abortError(undefined, signal));
49
- };
50
- if (active < limit)
51
- entry.start();
52
- else {
53
- waiting.push(entry);
54
- signal?.addEventListener('abort', cancel, { once: true });
55
- if (signal?.aborted)
56
- cancel();
57
- }
58
- });
59
- }
60
- function recallInput(request, schema, embedding) {
61
- const external = embedding.mode === 'external';
62
- requireInput(keys(request, [...(external ? ['queryVector'] : ['query', 'recentDialogue', 'context']), 'filter', 'excludeIds', 'limit', 'rerank']), 'Use the documented recall arguments.');
63
- if (external) {
64
- validateVector(request.queryVector, embedding);
20
+ async function remote(operation, message, signal, codes = {}) {
21
+ try {
22
+ return await nativeRequest(operation, signal);
23
+ }
24
+ catch (cause) {
25
+ const error = databaseError(cause, message);
26
+ if (error.status !== undefined && codes[error.status] !== undefined)
27
+ error.code = codes[error.status];
28
+ throw error;
65
29
  }
66
- else
67
- requireInput(nonempty(request.query) && request.query.trim() !== '*:*', 'query must be nonempty text other than the exact match-all expression *:*.');
68
- requireInput(request.context === undefined || typeof request.context === 'string', 'context must be text.');
69
- requireInput(request.recentDialogue === undefined || (Array.isArray(request.recentDialogue)
70
- && request.recentDialogue.every(message => keys(message, ['role', 'content'])
71
- && typeof message.role === 'string' && ['user', 'assistant'].includes(message.role) && typeof message.content === 'string')), 'recentDialogue must contain role-labelled user/assistant text.');
72
- requireInput(request.rerank === undefined || typeof request.rerank === 'boolean', 'rerank must be a boolean.');
73
- requireInput(request.excludeIds === undefined || (Array.isArray(request.excludeIds)
74
- && request.excludeIds.every(nonempty) && new Set(request.excludeIds).size === request.excludeIds.length), 'excludeIds must contain distinct canonical IDs.');
75
- const limit = request.limit ?? 10;
76
- requireInput(typeof limit === 'number' && Number.isSafeInteger(limit) && limit >= 1 && limit <= 1000, 'limit must be between 1 and 1000.');
77
- validateFilter(request.filter, schema);
78
- return { ...structuredClone(request), limit };
79
- }
80
- export function contextualQuery(request) {
81
- if (!request.recentDialogue?.length && !request.context)
82
- return request.query;
83
- return JSON.stringify({ question: request.query,
84
- ...(request.recentDialogue?.length ? { recent_dialogue: request.recentDialogue } : {}),
85
- ...(request.context ? { context: request.context } : {}) });
86
30
  }
87
- function recallQuery(request, schema, textSearch, embedding) {
88
- if (embedding.mode === 'external')
89
- return { size: request.limit, query: { knn: {
90
- field: 'embedding', queryVector: request.queryVector, k: request.limit,
91
- filter: buildSearchFilter([request.filter], request.excludeIds ?? [], [], schema),
92
- } } };
93
- const context = contextualQuery(request);
94
- // Native text-query input bound, not a silent SDK context truncation policy.
95
- requireInput(new TextEncoder().encode(request.query).length <= 8192 && new TextEncoder().encode(context).length <= 8192, 'The contextual search query exceeds the native 8 KiB limit.');
96
- const filter = buildSearchFilter([request.filter], request.excludeIds ?? [], [], schema);
97
- const candidates = Math.max(200, request.limit);
98
- const semantic = { knn: { field: 'embedding', queryText: context, k: candidates, filter } };
99
- const query = textSearch ? { bayesian: [semantic,
100
- { bool: [{ ...filter, occur: 'filter' },
101
- { queryString: { query: request.query, defaultField: 'content', skipSyntax: true }, occur: 'must' }] },
102
- ] } : semantic;
103
- return { size: request.limit, query, ...(request.rerank === false ? (textSearch ? { candidateSize: candidates } : {}) : {
104
- rerank: { provider: 'typesafe', model: 'jev-1.13.0', queryText: context,
105
- fields: ['content'], candidateSize: candidates, onFailure: 'error' },
106
- }) };
31
+ const branchRead = (branch) => ({
32
+ ref: { kind: 'branch', name: branch }, consistentRead: true, includeVectors: false,
33
+ });
34
+ const kindClause = { queryString: { query: '"file"', defaultField: 'kind' }, occur: 'filter' };
35
+ const pathClause = (path) => ({ queryString: { query: JSON.stringify(path), defaultField: 'path' } });
36
+ function pathQuery(paths) {
37
+ return { bool: [
38
+ kindClause,
39
+ paths.length === 1 ? { ...pathClause(paths[0]), occur: 'filter' }
40
+ : { bool: paths.map(path => ({ ...pathClause(path), occur: 'should' })), occur: 'filter' },
41
+ ] };
107
42
  }
108
- async function validatedHits(response, request, schema, name, max, embedding) {
109
- if (response?.isDocsInline === false || !Array.isArray(response?.docs) || response.docs.length > max)
110
- throw new MemDriveError('INVALID_RESULT', 'Search returned an invalid document envelope.');
111
- const seen = new Set();
112
- return Promise.all(response.docs.map(async (hit) => {
113
- if (hit.collection !== undefined && hit.collection !== name)
114
- throw new MemDriveError('INVALID_RESULT', 'Search returned a different collection.');
115
- let mem;
116
- try {
117
- mem = await (embedding.mode === 'external' ? vectorMatch(hit.doc, schema) : validateChunk(hit.doc, schema));
43
+ function writeBatches(records, branch) {
44
+ const envelope = bytes({ docs: [], branch });
45
+ const batches = [];
46
+ let batch = [];
47
+ let inputBytes = 0, wireBytes = envelope;
48
+ const flush = () => {
49
+ if (batch.length)
50
+ batches.push(batch);
51
+ batch = [];
52
+ inputBytes = 0;
53
+ wireBytes = envelope;
54
+ };
55
+ const fits = (docs) => batch.length + docs.length <= maximumRequestDocuments
56
+ && inputBytes + docs.reduce((sum, doc) => sum + doc.inputBytes, 0) <= maximumInputBytes
57
+ && wireBytes + docs.reduce((sum, doc) => sum + doc.wireBytes, 0) <= requestMaxBytes;
58
+ const append = (docs) => {
59
+ batch.push(...docs);
60
+ for (const doc of docs) {
61
+ inputBytes += doc.inputBytes;
62
+ wireBytes += doc.wireBytes;
118
63
  }
119
- catch (cause) {
120
- throw new MemDriveError('INVALID_RESULT', 'Search returned invalid Mem evidence.', { cause });
64
+ };
65
+ for (const { docs } of records) {
66
+ if (!fits(docs))
67
+ flush();
68
+ if (fits(docs))
69
+ append(docs);
70
+ else {
71
+ // Keep each ordinary file together. For a large file, stage its
72
+ // chunks first and include the original only in the final request.
73
+ for (const doc of docs) {
74
+ const next = [doc];
75
+ if (!fits(next))
76
+ flush();
77
+ requireInput(fits(next), 'A file record exceeds the limit for a native write.');
78
+ append(next);
79
+ }
121
80
  }
122
- if (seen.has(mem.id) || request.excludeIds?.includes(mem.memId) || !matchesFilter({ ...mem, id: mem.memId }, request.filter, schema))
123
- throw new MemDriveError('INVALID_RESULT', 'Search returned duplicate, excluded or filtered-out evidence.');
124
- seen.add(mem.id);
125
- return mem;
126
- }));
127
- }
128
- function verifyRerank(response, body) {
129
- const result = response.rerank;
130
- const same = result?.provider === body.rerank.provider && result?.model === body.rerank.model;
131
- const applied = result?.status === 'applied' && Number.isSafeInteger(result.candidateCount)
132
- && result.scoredCount === result.candidateCount && result.candidateCount !== undefined && result.candidateCount >= response.docs.length
133
- && result.candidateCount <= body.rerank.candidateSize
134
- && response.docs.every(hit => typeof hit.score === 'number' && Number.isFinite(hit.score) && hit.score >= 0 && hit.score <= 1);
135
- const empty = result?.status === 'skipped' && result.reason === 'noCandidates'
136
- && result.candidateCount === 0 && result.scoredCount === 0 && response.docs.length === 0;
137
- if (!same || (!applied && !empty))
138
- throw new MemDriveError('RERANK_FAILED', 'Native reranking was not confirmed.');
81
+ }
82
+ flush();
83
+ return batches;
139
84
  }
140
- function makeDataHandle(backend, options, queue, recallQueue) {
141
- const counter = createValueCounter({ describe: options => backend.describe(options), query: (body, options) => backend.query(body, options),
142
- metadataSchema: () => backend.metadataSchema });
143
- let generation = backend.generation;
144
- const invalidate = () => { generation = backend.generation; counter.invalidate(); };
145
- const inspect = async (operation) => {
146
- backend.assertActive();
147
- if (generation !== backend.generation)
148
- invalidate();
149
- try {
150
- const result = await operation();
151
- backend.assertActive();
152
- return result;
153
- }
154
- finally {
155
- if (generation !== backend.generation)
156
- invalidate();
157
- }
158
- };
159
- const mutation = async (operation) => {
160
- try {
161
- return await operation();
85
+ function store(handle, description) {
86
+ const { name, metadataSchema } = description;
87
+ const forks = new Map();
88
+ async function describe(options) {
89
+ const { signal } = operationOptions(options);
90
+ checkAbort(signal);
91
+ return structuredClone(description);
92
+ }
93
+ async function fetchFiles(branch, fileIds, signal) {
94
+ const response = await remote(() => handle.docs.fetch({ ids: fileIds.map(originalId), ...branchRead(branch) }, nativeOptions(signal)), 'Could not read file originals.', signal);
95
+ checkAbort(signal);
96
+ const files = new Map();
97
+ const expected = new Set(fileIds);
98
+ for (const doc of resultDocs(response, name, fileIds.length)) {
99
+ const file = decodeFile(doc, metadataSchema);
100
+ if (!expected.has(file.fileId) || files.has(file.fileId))
101
+ throw new MemDriveError('INVALID_RESULT', 'Read returned unexpected or duplicate file originals.');
102
+ files.set(file.fileId, file);
162
103
  }
163
- finally {
164
- invalidate();
104
+ return files;
105
+ }
106
+ function reader(branch) {
107
+ async function read(request, options) {
108
+ const { signal } = operationOptions(options);
109
+ checkAbort(signal);
110
+ requireInput(keysOnly(request, ['fileId', 'path', 'paths']) && Object.keys(request).length === 1, 'Read requires exactly one of fileId, path or paths.');
111
+ if ('fileId' in request) {
112
+ const fileId = request.fileId;
113
+ requireInput(validFileId(fileId), 'Provide a fileId returned by MemDrive.');
114
+ return (await fetchFiles(branch, [fileId], signal)).get(fileId) ?? null;
115
+ }
116
+ const multi = 'paths' in request;
117
+ const value = multi ? request.paths : [request.path];
118
+ requireInput(Array.isArray(value) && value.length >= 1 && value.length <= writeBatchLimit && [...value].every(validPath)
119
+ && new Set(value).size === value.length, 'Provide 1–100 distinct valid absolute file paths.');
120
+ const paths = [...value];
121
+ const response = await remote(() => handle.query({ size: paths.length * 2, ...branchRead(branch), query: pathQuery(paths) }, nativeOptions(signal)), 'Could not read files by path.', signal);
122
+ checkAbort(signal);
123
+ const expected = new Set(paths), files = new Map();
124
+ for (const doc of resultDocs(response, name, paths.length)) {
125
+ const file = decodeFile(doc, metadataSchema);
126
+ if (!expected.has(file.path) || files.has(file.path))
127
+ throw new MemDriveError('INVALID_RESULT', 'Read returned unexpected or duplicate paths.');
128
+ files.set(file.path, file);
129
+ }
130
+ return multi ? paths.flatMap(path => files.has(path) ? [files.get(path)] : []) : files.get(paths[0]) ?? null;
165
131
  }
166
- };
167
- const executeRecall = async (input, start, requestIndex, signal) => {
168
- const usage = { elapsedMs: 0, databaseRequests: 0 };
169
- const hook = (callback) => async (event) => {
132
+ return read;
133
+ }
134
+ function searcher(branch) {
135
+ return async (request, options) => {
136
+ const { signal } = operationOptions(options);
170
137
  checkAbort(signal);
171
- await callback?.(requestIndex === undefined ? event : { ...event, requestIndex });
138
+ const body = searchQuery(request, metadataSchema);
139
+ const response = await remote(() => handle.query({ ...body, ...branchRead(branch),
140
+ fields: { include: ['id', 'kind', 'fileId', 'path', 'modifiedAt', 'content', 'start', 'end'] } }, nativeOptions(signal)), 'File search failed.', signal);
172
141
  checkAbort(signal);
142
+ const docs = resultDocs(response, name, body.size);
143
+ const reranked = validateReranking(response, body);
144
+ const fileIds = new Set(), chunkIds = new Set();
145
+ const chunks = docs.map(doc => {
146
+ if (doc.kind !== 'chunk' || !validFileId(doc.fileId) || typeof doc.id !== 'string'
147
+ || !doc.id.startsWith(`chunk:${doc.fileId}:`) || chunkIds.has(doc.id) || !validPath(doc.path)
148
+ || typeof doc.content !== 'string' || !doc.content.trim() || /\p{Surrogate}/u.test(doc.content))
149
+ throw new MemDriveError('INVALID_RESULT', 'Search returned an invalid or duplicate chunk.');
150
+ fileIds.add(doc.fileId);
151
+ chunkIds.add(doc.id);
152
+ return { fileId: doc.fileId, path: doc.path, modifiedAt: doc.modifiedAt, content: doc.content,
153
+ start: doc.start, end: doc.end };
154
+ });
155
+ if (!chunks.length)
156
+ return { hits: [], reranked };
157
+ const files = await fetchFiles(branch, [...fileIds], signal);
158
+ const hits = [];
159
+ for (const chunk of chunks) {
160
+ const file = files.get(chunk.fileId);
161
+ // An orphan or stale chunk must not expose body text from another file or revision.
162
+ if (!file || file.path !== chunk.path || file.modifiedAt !== chunk.modifiedAt)
163
+ continue;
164
+ const { start, end } = chunk;
165
+ const verified = typeof start === 'number' && typeof end === 'number'
166
+ && Number.isSafeInteger(start) && Number.isSafeInteger(end) && start >= 0 && end > start && end <= file.content.length
167
+ && file.content.slice(start, end) === chunk.content;
168
+ hits.push({ ...file, content: chunk.content, ...(verified ? { range: { start, end } } : {}) });
169
+ }
170
+ return { hits, reranked };
173
171
  };
174
- const record = hook(options.record);
175
- const observe = hook(options.observe);
176
- const executeDb = (operation) => queue(async () => {
177
- backend.assertActive();
172
+ }
173
+ function working(fork) {
174
+ const existing = forks.get(fork);
175
+ if (existing)
176
+ return existing;
177
+ const branch = prefix + fork;
178
+ let writes = Promise.resolve();
179
+ const unconfirmed = new Map();
180
+ async function write(request, options) {
181
+ const { signal } = operationOptions(options);
178
182
  checkAbort(signal);
179
- usage.databaseRequests++;
180
- try {
181
- const result = await operation({ signal });
183
+ const multi = Array.isArray(request);
184
+ const operations = multi ? [...request] : [request];
185
+ requireInput(operations.length >= 1 && operations.length <= writeBatchLimit, 'Submit 1–100 file create operations.');
186
+ const prepared = Promise.all(operations.map(operation => fileRecords(operation, metadataSchema)));
187
+ // Validation and hashing begin immediately. Attach the queue now so overlapping writes keep call order.
188
+ void prepared.catch(() => { });
189
+ const write = writes.then(async () => {
182
190
  checkAbort(signal);
183
- return result;
184
- }
185
- catch (cause) {
186
- const failure = abortError(cause, signal);
187
- if (failure instanceof MemDriveError)
188
- throw failure;
189
- const error = new MemDriveError('DATABASE_ERROR', 'MemDrive database request failed.', { cause: failure });
190
- const remote = failure;
191
- error.status = remote.statusCode ?? remote.status;
192
- throw error;
193
- }
194
- }, signal);
195
- try {
196
- checkAbort(signal);
197
- backend.assertActive();
198
- if (generation !== backend.generation)
199
- invalidate();
200
- const schema = () => backend.metadataSchema;
201
- const request = recallInput(input, schema(), backend.embedding);
202
- requireInput(request.rerank !== true || backend.embedding.mode === 'managed', 'rerank: true requires managed embeddings.');
203
- const query = async (body) => {
204
- const response = await executeDb(options => backend.query(body, options));
205
- const mems = await validatedHits(response, request, schema(), options.name, body.size ?? 10, backend.embedding);
206
- return { ...response, docs: response.docs.map((hit, i) => ({ ...hit, doc: mems[i] })) };
207
- };
208
- const body = recallQuery(request, schema(), backend.textSearch, backend.embedding);
209
- await record({ phase: 'query', request: structuredClone(body) });
210
- const response = await query(body);
211
- if (body.rerank)
212
- verifyRerank(response, body);
213
- const mems = response.docs.map(hit => hit.doc);
214
- await record({ phase: 'query_result', response: structuredClone(response) });
215
- await observe({ type: 'retrieved', ids: mems.map(mem => mem.id), matches: mems.map(publicMatch) });
216
- backend.assertActive();
217
- checkAbort(signal);
218
- usage.elapsedMs = performance.now() - start;
219
- return { matches: mems.map(publicMatch), usage };
220
- }
221
- catch (cause) {
222
- const failure = abortError(cause, signal);
223
- usage.elapsedMs = performance.now() - start;
224
- const error = failure instanceof MemDriveError ? failure
225
- : new MemDriveError('RECALL_FAILED', 'MemDrive retrieval failed.', { cause: failure });
226
- error.usage = structuredClone(usage);
227
- throw error;
228
- }
229
- };
230
- const snapshot = (input) => {
231
- const start = performance.now();
232
- try {
233
- return { input: structuredClone(input), start };
234
- }
235
- catch (cause) {
236
- const error = new MemDriveError('INVALID_INPUT', 'Recall input must be cloneable data.', { cause });
237
- error.usage = { elapsedMs: 0, databaseRequests: 0 };
238
- return { error };
239
- }
240
- };
241
- const submit = async (prepared, requestIndex, signal) => {
242
- if (prepared.error)
243
- throw prepared.error;
244
- try {
245
- return await recallQueue(() => executeRecall(prepared.input, prepared.start, requestIndex, signal), signal);
246
- }
247
- catch (cause) {
248
- // Queue cancellation and executeRecall both reject with MemDriveError.
249
- const error = cause;
250
- error.usage ??= { elapsedMs: performance.now() - prepared.start, databaseRequests: 0 };
251
- throw error;
252
- }
253
- };
254
- async function recall(input, options) {
255
- const { signal } = operationOptions(options);
256
- if (input !== null && typeof input === 'object' && Object.hasOwn(input, 'requests')) {
257
- requireInput(keys(input, ['requests']) && Array.isArray(input.requests) && input.requests.length > 0, 'Batch recall requires only a nonempty requests array.');
258
- // Snapshot every item before any operation can yield or mutate caller data.
259
- const prepared = Array.from(input.requests, snapshot);
260
- const results = await Promise.all(prepared.map(async (item, requestIndex) => {
261
- try {
262
- return await submit(item, requestIndex, signal);
191
+ const records = await prepared;
192
+ const paths = records.map(record => record.file.path);
193
+ const expectedPaths = new Set(paths);
194
+ requireInput(expectedPaths.size === paths.length, 'Create paths must be distinct within one write.');
195
+ const batches = writeBatches(records, branch);
196
+ const response = await remote(() => handle.query({ size: 2 * paths.length, ...branchRead(branch),
197
+ query: pathQuery(paths), fields: { include: ['id', 'kind', 'fileId', 'path'] } }, nativeOptions(signal)), 'Could not check create destinations.', signal);
198
+ checkAbort(signal);
199
+ const occupied = new Set();
200
+ for (const doc of resultDocs(response, name, 2 * paths.length)) {
201
+ if (doc.kind !== 'file' || !validFileId(doc.fileId) || doc.id !== originalId(doc.fileId)
202
+ || typeof doc.path !== 'string' || !expectedPaths.has(doc.path) || occupied.has(doc.path))
203
+ throw new MemDriveError('INVALID_RESULT', 'Destination lookup returned an unexpected or duplicate file.');
204
+ occupied.add(doc.path);
205
+ unconfirmed.delete(doc.path);
206
+ }
207
+ if (occupied.size)
208
+ throw new MemDriveError('PATH_EXISTS', 'A file already exists at a requested path.', { details: { paths: [...occupied] } });
209
+ for (const path of paths) {
210
+ const fileId = unconfirmed.get(path);
211
+ if (fileId)
212
+ throw new MemDriveError('WRITE_UNCONFIRMED', 'An earlier create at this path is still unconfirmed.', { details: { fileId, path } });
263
213
  }
264
- catch (cause) {
265
- const error = cause;
266
- return { error: { code: error.code, message: error.message,
267
- ...(Number.isInteger(error.status) ? { status: error.status } : {}) },
268
- usage: structuredClone(error.usage) };
214
+ const completed = [];
215
+ const staged = new Map();
216
+ const filesById = new Map(records.map(({ file }) => [file.fileId, file]));
217
+ const details = () => ({
218
+ completedFileIds: completed.map(file => file.fileId),
219
+ incompleteTargets: [...staged].map(([fileId, path]) => ({ fileId, path })),
220
+ });
221
+ for (const batch of batches) {
222
+ const docs = batch.map(record => record.doc);
223
+ const ids = new Set(docs.map(doc => doc.id));
224
+ const targets = [...new Map(docs.map(({ fileId, path }) => [fileId, { fileId, path }])).values()];
225
+ const uncertain = (cause) => {
226
+ for (const { kind, fileId, path } of docs)
227
+ if (kind === 'file')
228
+ unconfirmed.set(path, fileId);
229
+ return new MemDriveError('WRITE_UNCONFIRMED', 'The create may have been accepted. Inspect the files on this fork.', {
230
+ cause, details: { ...(targets.length === 1 ? targets[0] : {}), targets, ...details() },
231
+ });
232
+ };
233
+ try {
234
+ checkAbort(signal);
235
+ }
236
+ catch (cause) {
237
+ throw new MemDriveError('ABORTED', 'Write aborted before the next request.', { cause, details: details() });
238
+ }
239
+ try {
240
+ await nativeRequest(() => handle.docs.upsert({ docs, branch }, nativeOptions(signal)), signal);
241
+ }
242
+ catch (cause) {
243
+ const error = databaseError(cause, 'The file create was rejected.');
244
+ if ([400, 401, 403, 404, 413, 422, 429].includes(error.status ?? 0)) {
245
+ if (completed.length || staged.size) {
246
+ const partial = new MemDriveError(error.code, error.message, { cause: error, details: details() });
247
+ partial.status = error.status;
248
+ throw partial;
249
+ }
250
+ throw error;
251
+ }
252
+ throw uncertain(cause);
253
+ }
254
+ try {
255
+ const confirmation = await nativeRequest(() => handle.docs.fetch({ ids: [...ids], ...branchRead(branch),
256
+ fields: { include: ['id'] } }, nativeOptions(signal)), signal);
257
+ checkAbort(signal);
258
+ const found = resultDocs(confirmation, name, ids.size);
259
+ if (found.some(doc => typeof doc.id !== 'string' || !ids.delete(doc.id)) || ids.size)
260
+ throw new MemDriveError('INVALID_RESULT', 'The original and its complete chunk set were not confirmed.');
261
+ }
262
+ catch (cause) {
263
+ throw uncertain(cause);
264
+ }
265
+ for (const { fileId, kind, path } of docs) {
266
+ if (kind === 'file') {
267
+ staged.delete(fileId);
268
+ completed.push(filesById.get(fileId));
269
+ }
270
+ else
271
+ staged.set(fileId, path);
272
+ }
269
273
  }
270
- }));
271
- return { results };
274
+ return multi ? completed : completed[0];
275
+ });
276
+ writes = write.then(() => undefined, () => undefined);
277
+ return write;
272
278
  }
273
- return submit(snapshot(input), undefined, signal);
279
+ const drive = Object.freeze({
280
+ name, at: Object.freeze({ kind: 'fork', name: fork }), read: reader(branch), search: searcher(branch), describe, write,
281
+ });
282
+ forks.set(fork, drive);
283
+ return drive;
274
284
  }
275
- return Object.freeze({
276
- remember: (request, options) => mutation(() => backend.remember(request, options)),
277
- forget: (request, options) => mutation(() => backend.forget(request, options)),
278
- read: (request, options) => backend.read(request, undefined, options),
279
- list: (request, options) => backend.list(request, options),
280
- embedding: Object.freeze(structuredClone(backend.embedding)),
281
- recall,
282
- async countValues(request, options) {
285
+ const mainView = Object.freeze({
286
+ name, at: Object.freeze({ kind: 'main' }), read: reader(main), search: searcher(main), describe,
287
+ async fork(request, options) {
283
288
  const { signal } = operationOptions(options);
284
289
  checkAbort(signal);
285
- return inspect(() => counter.countValues(request, operation => queue(async () => {
286
- backend.assertActive();
287
- checkAbort(signal);
288
- const result = await operation({ signal });
289
- backend.assertActive();
290
- checkAbort(signal);
291
- return result;
292
- }, signal), signal));
290
+ requireInput(keysOnly(request, ['name']) && validForkName(request.name), 'Fork name must be 3–47 letters, digits, underscores or hyphens and cannot be main.');
291
+ const fork = request.name;
292
+ const branch = prefix + fork;
293
+ const result = await remote(() => handle.branches.create({ branchName: branch, source: { kind: 'branch', name: main } }, nativeOptions(signal)), 'Could not create the working fork.', signal, { 409: 'BRANCH_CONFLICT' });
294
+ checkAbort(signal);
295
+ if (result?.branch?.name !== branch)
296
+ throw new MemDriveError('INVALID_RESULT', 'Fork creation returned an invalid branch.');
297
+ return working(fork);
293
298
  },
294
299
  });
295
- }
296
- function makeDrive(backend, options) {
297
- const concurrency = options.maxConcurrentRequests ?? 5;
298
- const queue = requestQueue(concurrency), recallQueue = requestQueue(concurrency);
299
- const at = (ref) => {
300
- requireInput(keys(ref, ['branch']) && Object.hasOwn(ref, 'branch'), 'Select a branch with { branch }.');
301
- return makeDataHandle(backend.at(ref.branch), options, queue, recallQueue);
300
+ return {
301
+ main: mainView,
302
+ async openFork(fork, signal) {
303
+ const cached = forks.get(fork);
304
+ if (cached)
305
+ return cached;
306
+ const response = await remote(() => handle.branches.list(nativeOptions(signal)), 'Could not find the working fork.', signal);
307
+ checkAbort(signal);
308
+ if (!Array.isArray(response?.branches) || !response.branches.every(branch => typeof branch?.name === 'string'))
309
+ throw new MemDriveError('INVALID_RESULT', 'Fork lookup returned invalid branches.');
310
+ if (!response.branches.some(branch => branch.name === prefix + fork))
311
+ throw new MemDriveError('BRANCH_NOT_FOUND', 'The working fork does not exist.');
312
+ return working(fork);
313
+ },
302
314
  };
303
- return Object.freeze({
304
- ...at({ branch: options.branch ?? 'main' }),
305
- at,
306
- branches: Object.freeze({
307
- create: (request, options) => backend.branches.create(request, options),
308
- list: (options) => backend.branches.list(options),
309
- delete: (name, options) => backend.branches.delete(name, options),
310
- }),
311
- configure: (request, options) => backend.configure(request, options),
312
- destroy: (options) => backend.destroy(options),
313
- describe: (options) => backend.describeDescriptor(options),
314
- });
315
+ }
316
+ function storesFor(client) {
317
+ const existing = clients.get(client);
318
+ if (existing)
319
+ return existing;
320
+ const stores = new Map();
321
+ clients.set(client, stores);
322
+ return stores;
315
323
  }
316
324
  export async function create(options, requestOptions) {
317
- requestOptions = operationOptions(requestOptions);
318
- checkAbort(requestOptions.signal);
319
- options = validateOptions(options, true);
320
- const backend = await createBackend({ client: options.client, name: options.name, metadataSchema: options.metadataSchema, textSearch: options.textSearch, embedding: options.embedding, labels: options.labels,
321
- description: options.description }, requestOptions);
322
- return makeDrive(backend, options);
325
+ const { signal } = operationOptions(requestOptions);
326
+ checkAbort(signal);
327
+ validateConnection(options, ['client', 'name', 'labels', 'textSearch', 'metadataSchema']);
328
+ const { client, name } = options;
329
+ requireInput(typeof client.createCollection === 'function', 'Client must support collection creation.');
330
+ const { indexConfigs, tags, description } = storeConfiguration(options);
331
+ await remote(() => client.createCollection({ collectionName: name, indexConfigs, tags }, nativeOptions(signal)), 'Could not create the file store.', signal, { 409: 'STORE_EXISTS' });
332
+ checkAbort(signal);
333
+ const stores = storesFor(client);
334
+ const created = stores.get(name) ?? store(client.collection(name), description);
335
+ stores.set(name, created);
336
+ return created.main;
323
337
  }
324
338
  export async function open(options, requestOptions) {
325
- requestOptions = operationOptions(requestOptions);
326
- checkAbort(requestOptions.signal);
327
- options = validateOptions(options, false);
328
- const backend = await openBackend({ client: options.client, name: options.name }, requestOptions);
329
- if (options.branch !== undefined && options.branch !== 'main'
330
- && !(await backend.branches.list(requestOptions)).some(branch => branch.name === options.branch))
331
- throw new MemDriveError('BRANCH_NOT_FOUND', 'The selected MemDrive branch does not exist.');
332
- return makeDrive(backend, options);
339
+ const { signal } = operationOptions(requestOptions);
340
+ checkAbort(signal);
341
+ validateConnection(options, ['client', 'name', 'at']);
342
+ const { client, name, at } = options;
343
+ let fork;
344
+ if (at !== undefined) {
345
+ requireInput(keysOnly(at, ['fork']) && validForkName(at.fork), 'Select a working fork by its name.');
346
+ fork = at.fork;
347
+ }
348
+ const stores = storesFor(client);
349
+ let selected = stores.get(name);
350
+ if (!selected) {
351
+ const handle = client.collection(name);
352
+ const response = await remote(() => handle.get(nativeOptions(signal)), 'Could not inspect the file store.', signal, { 404: 'STORE_NOT_FOUND' });
353
+ checkAbort(signal);
354
+ const description = parseStore(response?.collection, name);
355
+ selected = stores.get(name) ?? store(handle, description);
356
+ stores.set(name, selected);
357
+ }
358
+ return fork === undefined ? selected.main : selected.openFork(fork, signal);
333
359
  }
334
- export const list = (request, options) => listBackends(request, options);
360
+ export const MemDrive = Object.freeze({ create, open });
335
361
  //# sourceMappingURL=index.js.map