@oortmem/store-sqlite 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # @oortmem/store-sqlite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The local Oort store: SQLite with FTS5 for keywords, sqlite-vec for vectors, and zstd blobs for the cold tier.
4
+
5
+ ```sh
6
+ npm install @oortmem/store-sqlite
7
+ ```
8
+
9
+ ```ts
10
+ import { openSqliteStore } from '@oortmem/store-sqlite';
11
+
12
+ const store = await openSqliteStore({ path: './oort.db', coldDir: './cold', dimension: 512 });
13
+ ```
14
+
15
+ Directories it creates are owner-only.
16
+
17
+ Part of [Oort](https://github.com/oortmem/oort), open-source memory for AI agents. See the [main README](https://github.com/oortmem/oort#readme) for how the pieces fit. Apache-2.0.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The file layer under the SQLite store: owner-only directories and files,
3
+ * atomic unique-per-write cold blobs, and the crash-leftover sweep. No SQL here.
4
+ */
5
+ export type Log = (message: string) => void;
6
+ export declare function unlinkQuietly(file: string): void;
7
+ /**
8
+ * Returns `original`, the error the caller must see, with any cleanup
9
+ * failures attached as its `cause` (an `AggregateError`; a cause it already
10
+ * had becomes that error's cause). A non-Error is returned unchanged.
11
+ */
12
+ export declare function withCleanupFailures(original: unknown, failures: readonly unknown[]): unknown;
13
+ export declare function chmodIfExists(file: string, mode: number): void;
14
+ /**
15
+ * The database's directory. One the store creates is owner-only. An existing
16
+ * one (often a project root) is the caller's: it is never chmodded, only
17
+ * warned about when group or others can read it.
18
+ */
19
+ export declare function prepareDbDir(dir: string, log: Log): void;
20
+ /**
21
+ * Runs `fn` with umask 077 so files SQLite creates (`-wal`, `-shm`) are
22
+ * owner-only. The umask is process-global: while `fn` runs (synchronously),
23
+ * files created by other threads of this process also get 077. Worker threads
24
+ * cannot set it at all; there the explicit chmods after open are the only guard.
25
+ */
26
+ export declare function withPrivateUmask<T>(fn: () => T): T;
27
+ export interface BlobDir {
28
+ /**
29
+ * Writes a new uniquely named blob per item: temp files written with bounded
30
+ * parallelism, then all renamed, then one directory fsync. The files
31
+ * themselves are not fsynced (see the durability note above).
32
+ * Returns the file names in input order. On any failure every file this call
33
+ * created is removed and the error is rethrown.
34
+ */
35
+ writeMany(items: readonly {
36
+ id: string;
37
+ data: Uint8Array;
38
+ }[]): Promise<string[]>;
39
+ /** The blob's bytes, or null when it is missing or `name` is not a blob name. */
40
+ read(name: string): Buffer | null;
41
+ /** Removes a blob; missing files and non-blob names are ignored. */
42
+ remove(name: string): void;
43
+ /**
44
+ * `remove` for every name, best effort: one failing unlink does not stop the
45
+ * rest. Returns the failures (empty when all went).
46
+ */
47
+ removeAll(names: readonly string[]): unknown[];
48
+ /**
49
+ * Removes crash leftovers: blob temp files older than an hour, and blobs not
50
+ * in `referenced` older than a minute. Only when the directory carries the
51
+ * marker, and only files matching the blob-name pattern. Logs counts only.
52
+ */
53
+ sweep(referenced: ReadonlySet<string>): void;
54
+ }
55
+ /**
56
+ * Opens the cold directory, creating it owner-only (or tightening it). The
57
+ * marker is written when the directory is new or empty; a populated directory
58
+ * without one is not swept, so a misconfigured shared directory loses nothing.
59
+ */
60
+ export declare function openBlobDir(dir: string, log: Log): BlobDir;
package/dist/blobs.js ADDED
@@ -0,0 +1,265 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as fsp from 'node:fs/promises';
4
+ import * as path from 'node:path';
5
+ import { ensurePrivateDir } from '@oortmem/core';
6
+ /** A `.zst.tmp` older than this is a crashed write. */
7
+ const STALE_TMP_MS = 60 * 60 * 1000;
8
+ /**
9
+ * An unreferenced blob younger than this may belong to another process's
10
+ * `coldPut` that has renamed it but not yet committed (the commit can wait up
11
+ * to the 5 s busy timeout), so the sweep leaves it for a later open.
12
+ */
13
+ const ORPHAN_GRACE_MS = 60 * 1000;
14
+ /** Marks a directory as an Oort cold directory; the sweep never runs without it. */
15
+ const MARKER = '.oort-cold';
16
+ /**
17
+ * `<safeId>.<pid>-<rand>.zst`, optionally `.tmp`. Unique per write, so one
18
+ * `coldPut` never overwrites, and a sweep or unlink never hits, another
19
+ * write's file. The sweep touches nothing that does not match.
20
+ */
21
+ const BLOB_NAME = /^(?:[a-z0-9_-]{1,128}|~[0-9a-f]{64})\.\d+-[0-9a-f]{8}\.zst(\.tmp)?$/;
22
+ /** Ids that are safe, case-insensitive-unique file names are used as is; anything else is hashed. */
23
+ function safeId(id) {
24
+ return /^[a-z0-9_-]{1,128}$/.test(id) ? id : `~${createHash('sha256').update(id).digest('hex')}`;
25
+ }
26
+ export function unlinkQuietly(file) {
27
+ try {
28
+ fs.unlinkSync(file);
29
+ }
30
+ catch (e) {
31
+ if (e.code !== 'ENOENT')
32
+ throw e;
33
+ }
34
+ }
35
+ /** Runs every unlink, best effort; returns the failures (missing files are not failures). */
36
+ function unlinkEach(files) {
37
+ const failures = [];
38
+ for (const file of files) {
39
+ try {
40
+ unlinkQuietly(file);
41
+ }
42
+ catch (e) {
43
+ failures.push(e);
44
+ }
45
+ }
46
+ return failures;
47
+ }
48
+ /**
49
+ * Returns `original`, the error the caller must see, with any cleanup
50
+ * failures attached as its `cause` (an `AggregateError`; a cause it already
51
+ * had becomes that error's cause). A non-Error is returned unchanged.
52
+ */
53
+ export function withCleanupFailures(original, failures) {
54
+ if (failures.length === 0 || !(original instanceof Error))
55
+ return original;
56
+ const previous = original.cause;
57
+ original.cause = new AggregateError(failures, `cold blob cleanup: ${failures.length} unlink(s) failed`, previous === undefined ? undefined : { cause: previous });
58
+ return original;
59
+ }
60
+ export function chmodIfExists(file, mode) {
61
+ try {
62
+ fs.chmodSync(file, mode);
63
+ }
64
+ catch (e) {
65
+ if (e.code !== 'ENOENT')
66
+ throw e;
67
+ }
68
+ }
69
+ /**
70
+ * The database's directory. One the store creates is owner-only. An existing
71
+ * one (often a project root) is the caller's: it is never chmodded, only
72
+ * warned about when group or others can read it.
73
+ */
74
+ export function prepareDbDir(dir, log) {
75
+ if (!fs.existsSync(dir)) {
76
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
77
+ return;
78
+ }
79
+ if (process.platform !== 'win32' && (fs.statSync(dir).mode & 0o077) !== 0) {
80
+ log(`oort: ${dir} is readable by group/others; memory files inside are 0600`);
81
+ }
82
+ }
83
+ /**
84
+ * Runs `fn` with umask 077 so files SQLite creates (`-wal`, `-shm`) are
85
+ * owner-only. The umask is process-global: while `fn` runs (synchronously),
86
+ * files created by other threads of this process also get 077. Worker threads
87
+ * cannot set it at all; there the explicit chmods after open are the only guard.
88
+ */
89
+ export function withPrivateUmask(fn) {
90
+ let previous;
91
+ try {
92
+ previous = process.umask(0o077);
93
+ }
94
+ catch {
95
+ previous = undefined;
96
+ }
97
+ try {
98
+ return fn();
99
+ }
100
+ finally {
101
+ if (previous !== undefined)
102
+ process.umask(previous);
103
+ }
104
+ }
105
+ /** Opens a new owner-only file exclusively; a leftover file at `file` is removed and the open retried once. */
106
+ async function openExclusive(file) {
107
+ try {
108
+ return await fsp.open(file, 'wx', 0o600);
109
+ }
110
+ catch (e) {
111
+ if (e.code !== 'EEXIST')
112
+ throw e;
113
+ unlinkQuietly(file);
114
+ return await fsp.open(file, 'wx', 0o600);
115
+ }
116
+ }
117
+ /**
118
+ * Durability note. Blob files are NOT fsynced individually; the rename and one
119
+ * directory fsync per batch are kept. Per-file fsync cost about 12 ms each and
120
+ * made the first consolidate of 10k memories take 60 s (25 s even with 8
121
+ * fsyncs in parallel). A cold blob holds the embedding and a snapshot only:
122
+ * the database row keeps text, stub and entities. After a power loss a blob
123
+ * may be torn or empty; the v2 frame's CRC32 detects that, `coldGet` returns
124
+ * null (logged), and recall falls back to the live row. Worst case the
125
+ * embedding is lost: nothing re-derives it yet, so the memory stays cold
126
+ * without one and is found lexically only (stub, entities).
127
+ * TODO(Phase 2): re-embed on hydration when an embedder is present.
128
+ * A process crash loses nothing
129
+ * (the page cache survives it). The database itself keeps its WAL durability.
130
+ */
131
+ /** Blobs written at once: bounds open file handles. */
132
+ const WRITE_CONCURRENCY = 8;
133
+ /** Runs `fn` over `items` with at most `limit` in flight; every started task settles before this does. */
134
+ async function mapBounded(items, limit, fn) {
135
+ const out = Array.from({ length: items.length });
136
+ let next = 0;
137
+ const worker = async () => {
138
+ while (next < items.length) {
139
+ const i = next++;
140
+ try {
141
+ out[i] = { status: 'fulfilled', value: await fn(items[i], i) };
142
+ }
143
+ catch (reason) {
144
+ out[i] = { status: 'rejected', reason };
145
+ }
146
+ }
147
+ };
148
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
149
+ return out;
150
+ }
151
+ /** Best-effort fsync of a directory so a rename survives a crash (not supported everywhere). */
152
+ function fsyncDir(dir) {
153
+ try {
154
+ const fd = fs.openSync(dir, 'r');
155
+ try {
156
+ fs.fsyncSync(fd);
157
+ }
158
+ finally {
159
+ fs.closeSync(fd);
160
+ }
161
+ }
162
+ catch {
163
+ // Windows cannot open directories; the rename is still atomic.
164
+ }
165
+ }
166
+ /**
167
+ * Opens the cold directory, creating it owner-only (or tightening it). The
168
+ * marker is written when the directory is new or empty; a populated directory
169
+ * without one is not swept, so a misconfigured shared directory loses nothing.
170
+ */
171
+ export function openBlobDir(dir, log) {
172
+ if (ensurePrivateDir(dir))
173
+ log('oort store: tightened permissions to 0700 on the cold directory');
174
+ const marker = path.join(dir, MARKER);
175
+ if (!fs.existsSync(marker)) {
176
+ if (fs.readdirSync(dir).length === 0)
177
+ fs.closeSync(fs.openSync(marker, 'a', 0o600));
178
+ else
179
+ log(`oort: ${dir} has no ${MARKER} marker; orphan cold blob sweep disabled`);
180
+ }
181
+ return {
182
+ async writeMany(items) {
183
+ const names = items.map(({ id }) => `${safeId(id)}.${process.pid}-${randomBytes(4).toString('hex')}.zst`);
184
+ const tmpOf = (name) => path.join(dir, `${name}.tmp`);
185
+ const renamed = [];
186
+ // Best effort over every file this call created; never masks the original error.
187
+ const cleanup = () => unlinkEach(names.flatMap((name) => renamed.includes(name) ? [tmpOf(name), path.join(dir, name)] : [tmpOf(name)]));
188
+ try {
189
+ const written = await mapBounded(items, WRITE_CONCURRENCY, async ({ data }, i) => {
190
+ const fh = await openExclusive(tmpOf(names[i]));
191
+ try {
192
+ await fh.writeFile(data);
193
+ }
194
+ finally {
195
+ await fh.close();
196
+ }
197
+ });
198
+ for (const r of written)
199
+ if (r.status === 'rejected')
200
+ throw r.reason;
201
+ for (const name of names) {
202
+ await fsp.rename(tmpOf(name), path.join(dir, name));
203
+ renamed.push(name);
204
+ }
205
+ fsyncDir(dir);
206
+ }
207
+ catch (e) {
208
+ throw withCleanupFailures(e, cleanup());
209
+ }
210
+ return names;
211
+ },
212
+ read(name) {
213
+ if (!BLOB_NAME.test(name) || name.endsWith('.tmp'))
214
+ return null;
215
+ try {
216
+ return fs.readFileSync(path.join(dir, name));
217
+ }
218
+ catch (e) {
219
+ if (e.code === 'ENOENT')
220
+ return null;
221
+ throw e;
222
+ }
223
+ },
224
+ remove(name) {
225
+ if (BLOB_NAME.test(name))
226
+ unlinkQuietly(path.join(dir, name));
227
+ },
228
+ removeAll(names) {
229
+ return unlinkEach(names.filter((n) => BLOB_NAME.test(n)).map((n) => path.join(dir, n)));
230
+ },
231
+ sweep(referenced) {
232
+ if (!fs.existsSync(marker))
233
+ return;
234
+ const now = Date.now();
235
+ let tmps = 0;
236
+ let orphans = 0;
237
+ for (const name of fs.readdirSync(dir)) {
238
+ const m = BLOB_NAME.exec(name);
239
+ if (m === null)
240
+ continue;
241
+ const isTmp = m[1] !== undefined;
242
+ if (!isTmp && referenced.has(name))
243
+ continue;
244
+ let age;
245
+ try {
246
+ age = now - fs.statSync(path.join(dir, name)).mtimeMs;
247
+ }
248
+ catch {
249
+ continue;
250
+ }
251
+ if (age < (isTmp ? STALE_TMP_MS : ORPHAN_GRACE_MS))
252
+ continue;
253
+ unlinkQuietly(path.join(dir, name));
254
+ if (isTmp)
255
+ tmps++;
256
+ else
257
+ orphans++;
258
+ }
259
+ if (tmps + orphans > 0) {
260
+ log(`oort store: removed ${orphans} orphan cold blob(s) and ${tmps} stale temp file(s)`);
261
+ }
262
+ },
263
+ };
264
+ }
265
+ //# sourceMappingURL=blobs.js.map
package/dist/cold.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ import type { Memory } from '@oortmem/core';
2
+ /**
3
+ * Serialises a full memory (embedding included, so hydration never re-embeds)
4
+ * into a cold blob. Dictionary support is a Phase 2 extension; it gets its own
5
+ * frame version.
6
+ */
7
+ export interface ColdCodec {
8
+ encode(m: Memory): Uint8Array;
9
+ /** Throws `ColdBlobCorruptError` for anything that is not an intact frame. */
10
+ decode(b: Uint8Array): Memory;
11
+ }
12
+ /** A cold blob that is truncated, bit-flipped, of an unknown version, or of the wrong dimension. */
13
+ export declare class ColdBlobCorruptError extends Error {
14
+ constructor(message: string, options?: {
15
+ cause?: unknown;
16
+ });
17
+ }
18
+ export interface ColdCodecOptions {
19
+ /** When set, `decode` rejects a blob whose embedding has another length. */
20
+ dimension?: number;
21
+ }
22
+ /**
23
+ * Frame version 2 (written):
24
+ *
25
+ * u8 version (0x02)
26
+ * u32 big-endian length of the compressed JSON
27
+ * zstd (level 19) of the UTF-8 JSON of the memory without its embedding
28
+ * u32 big-endian embedding length (0 when absent)
29
+ * raw int8 embedding bytes, uncompressed
30
+ * u32 big-endian CRC32 of every byte before it
31
+ *
32
+ * Only the JSON is compressed. Quantised int8 embeddings are near-incompressible
33
+ * (a full-range 512-d vector grows under zstd), so compressing them costs CPU
34
+ * and frame overhead; and mixing them into the JSON's zstd block makes that
35
+ * block share one literal Huffman table between English and noise, which
36
+ * measurably hurts the text's compression too. The CRC and the explicit
37
+ * length make a truncated or bit-flipped blob fail loudly instead of decoding
38
+ * into a memory with a short embedding.
39
+ *
40
+ * Frame version 1 (read only): u8 0x01, u32 JSON length, zstd JSON, u8
41
+ * embedding flag, raw bytes. It has no checksum, so its embedding length is
42
+ * checked against `dimension` when known.
43
+ */
44
+ export declare function createColdCodec(opts?: ColdCodecOptions): ColdCodec;