@context-vault/core 2.8.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Felix Hellstrom
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@context-vault/core",
3
+ "version": "2.8.3",
4
+ "type": "module",
5
+ "description": "Shared core: capture, index, retrieve, tools, and utilities for context-vault",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./capture": "./src/capture/index.js",
10
+ "./capture/formatters": "./src/capture/formatters.js",
11
+ "./capture/file-ops": "./src/capture/file-ops.js",
12
+ "./index/db": "./src/index/db.js",
13
+ "./index/embed": "./src/index/embed.js",
14
+ "./index": "./src/index/index.js",
15
+ "./retrieve": "./src/retrieve/index.js",
16
+ "./server/tools": "./src/server/tools.js",
17
+ "./server/helpers": "./src/server/helpers.js",
18
+ "./core/categories": "./src/core/categories.js",
19
+ "./core/config": "./src/core/config.js",
20
+ "./core/files": "./src/core/files.js",
21
+ "./core/frontmatter": "./src/core/frontmatter.js",
22
+ "./core/status": "./src/core/status.js",
23
+ "./capture/importers": "./src/capture/importers.js",
24
+ "./capture/import-pipeline": "./src/capture/import-pipeline.js",
25
+ "./capture/ingest-url": "./src/capture/ingest-url.js",
26
+ "./sync": "./src/sync/sync.js",
27
+ "./constants": "./src/constants.js"
28
+ },
29
+ "files": [
30
+ "src/"
31
+ ],
32
+ "license": "MIT",
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
36
+ "author": "Felix Hellstrom",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/fellanH/context-vault.git",
40
+ "directory": "packages/core"
41
+ },
42
+ "homepage": "https://github.com/fellanH/context-vault",
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "dependencies": {
47
+ "@huggingface/transformers": "^3.0.0",
48
+ "@modelcontextprotocol/sdk": "^1.26.0",
49
+ "better-sqlite3": "^12.6.2",
50
+ "sqlite-vec": "^0.1.0"
51
+ }
52
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * file-ops.js — Capture-specific file operations
3
+ *
4
+ * Writes markdown entry files with frontmatter to the vault directory.
5
+ */
6
+
7
+ import { mkdirSync, writeFileSync } from "node:fs";
8
+ import { resolve, relative } from "node:path";
9
+ import { formatFrontmatter } from "../core/frontmatter.js";
10
+ import { slugify, kindToPath } from "../core/files.js";
11
+ import { formatBody } from "./formatters.js";
12
+
13
+ export function safeFolderPath(vaultDir, kind, folder) {
14
+ const base = resolve(vaultDir, kindToPath(kind));
15
+ if (!folder) return base;
16
+ const resolved = resolve(base, folder);
17
+ const rel = relative(base, resolved);
18
+ if (rel.startsWith("..") || resolve(base, rel) !== resolved) {
19
+ throw new Error(`Folder path escapes vault: "${folder}"`);
20
+ }
21
+ return resolved;
22
+ }
23
+
24
+ export function writeEntryFile(
25
+ vaultDir,
26
+ kind,
27
+ {
28
+ id,
29
+ title,
30
+ body,
31
+ meta,
32
+ tags,
33
+ source,
34
+ createdAt,
35
+ folder,
36
+ category,
37
+ identity_key,
38
+ expires_at,
39
+ },
40
+ ) {
41
+ // P5: folder is now a top-level param; also accept from meta for backward compat
42
+ const resolvedFolder = folder || meta?.folder || "";
43
+ const dir = safeFolderPath(vaultDir, kind, resolvedFolder);
44
+
45
+ try {
46
+ mkdirSync(dir, { recursive: true });
47
+ } catch (e) {
48
+ throw new Error(`Failed to create directory "${dir}": ${e.message}`);
49
+ }
50
+
51
+ const created = createdAt || new Date().toISOString();
52
+ const fmFields = { id };
53
+
54
+ // Add kind-specific meta fields to frontmatter (flattened, not nested)
55
+ if (meta) {
56
+ for (const [k, v] of Object.entries(meta)) {
57
+ if (k === "folder") continue;
58
+ if (v !== null && v !== undefined) fmFields[k] = v;
59
+ }
60
+ }
61
+
62
+ if (identity_key) fmFields.identity_key = identity_key;
63
+ if (expires_at) fmFields.expires_at = expires_at;
64
+ fmFields.tags = tags || [];
65
+ fmFields.source = source || "claude-code";
66
+ fmFields.created = created;
67
+
68
+ const mdBody = formatBody(kind, { title, body, meta });
69
+
70
+ // Entity kinds: deterministic filename from identity_key (no ULID suffix)
71
+ let filename;
72
+ if (category === "entity" && identity_key) {
73
+ const identitySlug = slugify(identity_key);
74
+ filename = identitySlug
75
+ ? `${identitySlug}.md`
76
+ : `${id.slice(-8).toLowerCase()}.md`;
77
+ } else {
78
+ const slug = slugify((title || body).slice(0, 40));
79
+ const shortId = id.slice(-8).toLowerCase();
80
+ filename = slug ? `${slug}-${shortId}.md` : `${shortId}.md`;
81
+ }
82
+
83
+ const filePath = resolve(dir, filename);
84
+ const md = formatFrontmatter(fmFields) + mdBody;
85
+
86
+ try {
87
+ writeFileSync(filePath, md);
88
+ } catch (e) {
89
+ throw new Error(`Failed to write entry file "${filePath}": ${e.message}`);
90
+ }
91
+
92
+ return filePath;
93
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * formatters.js — Kind-specific markdown body templates
3
+ *
4
+ * Maps entry kinds to their markdown body format.
5
+ * Default formatter used for unknown kinds.
6
+ */
7
+
8
+ const FORMATTERS = {
9
+ insight: ({ body }) => "\n" + body + "\n",
10
+
11
+ decision: ({ title, body }) => {
12
+ const t = title || body.slice(0, 80);
13
+ return "\n## Decision\n\n" + t + "\n\n## Rationale\n\n" + body + "\n";
14
+ },
15
+
16
+ pattern: ({ title, body, meta }) => {
17
+ const t = title || body.slice(0, 80);
18
+ const lang = meta?.language || "";
19
+ return "\n# " + t + "\n\n```" + lang + "\n" + body + "\n```\n";
20
+ },
21
+ };
22
+
23
+ const DEFAULT_FORMATTER = ({ title, body }) =>
24
+ title ? "\n# " + title + "\n\n" + body + "\n" : "\n" + body + "\n";
25
+
26
+ export function formatBody(kind, { title, body, meta }) {
27
+ const fn = FORMATTERS[kind] || DEFAULT_FORMATTER;
28
+ return fn({ title, body, meta });
29
+ }
@@ -0,0 +1,46 @@
1
+ import { captureAndIndex } from "./index.js";
2
+
3
+ export async function importEntries(ctx, entries, opts = {}) {
4
+ const { onProgress, source } = opts;
5
+ let imported = 0;
6
+ let failed = 0;
7
+ const errors = [];
8
+
9
+ for (let i = 0; i < entries.length; i++) {
10
+ const entry = entries[i];
11
+
12
+ if (onProgress) {
13
+ onProgress(i + 1, entries.length);
14
+ }
15
+
16
+ try {
17
+ if (!entry.body?.trim()) {
18
+ failed++;
19
+ errors.push({ index: i, title: entry.title, error: "Empty body" });
20
+ continue;
21
+ }
22
+
23
+ await captureAndIndex(ctx, {
24
+ kind: entry.kind || "insight",
25
+ title: entry.title || null,
26
+ body: entry.body,
27
+ meta: entry.meta,
28
+ tags: entry.tags,
29
+ source: entry.source || source || "import",
30
+ identity_key: entry.identity_key,
31
+ expires_at: entry.expires_at,
32
+ userId: ctx.userId || null,
33
+ });
34
+ imported++;
35
+ } catch (err) {
36
+ failed++;
37
+ errors.push({
38
+ index: i,
39
+ title: entry.title || null,
40
+ error: err.message,
41
+ });
42
+ }
43
+ }
44
+
45
+ return { imported, failed, errors };
46
+ }
@@ -0,0 +1,387 @@
1
+ /**
2
+ * importers.js — Format detection + parsers for bulk import
3
+ *
4
+ * Detects and parses markdown, CSV/TSV, JSON, and plain text files into
5
+ * the EntryData shape that captureAndIndex() accepts.
6
+ *
7
+ * No external dependencies — CSV parsed with split + quote handling,
8
+ * markdown uses existing parseFrontmatter().
9
+ */
10
+
11
+ import { readdirSync, readFileSync, statSync } from "node:fs";
12
+ import { join, extname, basename } from "node:path";
13
+ import {
14
+ parseFrontmatter,
15
+ parseEntryFromMarkdown,
16
+ } from "../core/frontmatter.js";
17
+ import { dirToKind } from "../core/files.js";
18
+
19
+ /**
20
+ * Detect the format of a file by extension and content heuristics.
21
+ * @param {string} filePath
22
+ * @param {string} [content]
23
+ * @returns {"markdown"|"csv"|"tsv"|"json"|"text"}
24
+ */
25
+ export function detectFormat(filePath, content) {
26
+ const ext = extname(filePath).toLowerCase();
27
+
28
+ if (ext === ".md" || ext === ".markdown") return "markdown";
29
+ if (ext === ".csv") return "csv";
30
+ if (ext === ".tsv") return "tsv";
31
+ if (ext === ".json" || ext === ".jsonl") return "json";
32
+
33
+ // Content-based heuristics if extension is ambiguous
34
+ if (content) {
35
+ const trimmed = content.trimStart();
36
+ if (trimmed.startsWith("---\n")) return "markdown";
37
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) return "json";
38
+ }
39
+
40
+ return "text";
41
+ }
42
+
43
+ /**
44
+ * Parse a CSV line respecting quoted fields.
45
+ * @param {string} line
46
+ * @param {string} delimiter
47
+ * @returns {string[]}
48
+ */
49
+ function parseCsvLine(line, delimiter) {
50
+ const fields = [];
51
+ let current = "";
52
+ let inQuotes = false;
53
+
54
+ for (let i = 0; i < line.length; i++) {
55
+ const ch = line[i];
56
+ if (inQuotes) {
57
+ if (ch === '"') {
58
+ if (i + 1 < line.length && line[i + 1] === '"') {
59
+ current += '"';
60
+ i++;
61
+ } else {
62
+ inQuotes = false;
63
+ }
64
+ } else {
65
+ current += ch;
66
+ }
67
+ } else if (ch === '"') {
68
+ inQuotes = true;
69
+ } else if (ch === delimiter) {
70
+ fields.push(current.trim());
71
+ current = "";
72
+ } else {
73
+ current += ch;
74
+ }
75
+ }
76
+ fields.push(current.trim());
77
+ return fields;
78
+ }
79
+
80
+ const KNOWN_COLUMNS = new Set([
81
+ "kind",
82
+ "title",
83
+ "body",
84
+ "tags",
85
+ "source",
86
+ "identity_key",
87
+ "expires_at",
88
+ ]);
89
+
90
+ /**
91
+ * Parse a markdown file into EntryData.
92
+ * Reuses parseFrontmatter + parseEntryFromMarkdown from core.
93
+ *
94
+ * @param {string} content
95
+ * @param {{ kind?: string, source?: string }} [opts]
96
+ * @returns {import("./import-pipeline.js").EntryData[]}
97
+ */
98
+ export function parseMarkdown(content, opts = {}) {
99
+ const { meta: fmMeta, body: rawBody } = parseFrontmatter(content);
100
+
101
+ // Derive kind from frontmatter or option
102
+ const kind = fmMeta.kind || opts.kind || "insight";
103
+ const parsed = parseEntryFromMarkdown(kind, rawBody, fmMeta);
104
+
105
+ return [
106
+ {
107
+ kind,
108
+ title: parsed.title || fmMeta.title || null,
109
+ body: parsed.body || rawBody,
110
+ tags: Array.isArray(fmMeta.tags) ? fmMeta.tags : undefined,
111
+ meta: parsed.meta || undefined,
112
+ source: fmMeta.source || opts.source || "import",
113
+ identity_key: fmMeta.identity_key || undefined,
114
+ expires_at: fmMeta.expires_at || undefined,
115
+ },
116
+ ];
117
+ }
118
+
119
+ /**
120
+ * Parse a CSV or TSV file into EntryData[].
121
+ * Header row required. Recognized columns map directly; unknown → meta.
122
+ * Tags column is comma-separated within field.
123
+ *
124
+ * @param {string} content
125
+ * @param {string} delimiter - "," for CSV, "\t" for TSV
126
+ * @param {{ kind?: string, source?: string }} [opts]
127
+ * @returns {import("./import-pipeline.js").EntryData[]}
128
+ */
129
+ export function parseCsv(content, delimiter, opts = {}) {
130
+ const lines = content.split(/\r?\n/).filter((l) => l.trim());
131
+ if (lines.length < 2) return [];
132
+
133
+ const headers = parseCsvLine(lines[0], delimiter).map((h) =>
134
+ h.toLowerCase().trim(),
135
+ );
136
+ const entries = [];
137
+
138
+ for (let i = 1; i < lines.length; i++) {
139
+ const values = parseCsvLine(lines[i], delimiter);
140
+ if (values.every((v) => !v)) continue; // skip empty rows
141
+
142
+ const entry = {
143
+ kind: opts.kind || "insight",
144
+ body: "",
145
+ source: opts.source || "csv-import",
146
+ };
147
+ const meta = {};
148
+
149
+ for (let j = 0; j < headers.length; j++) {
150
+ const col = headers[j];
151
+ const val = values[j] || "";
152
+
153
+ if (col === "kind" && val) {
154
+ entry.kind = val;
155
+ } else if (col === "title" && val) {
156
+ entry.title = val;
157
+ } else if (col === "body" && val) {
158
+ entry.body = val;
159
+ } else if (col === "tags" && val) {
160
+ entry.tags = val
161
+ .split(",")
162
+ .map((t) => t.trim())
163
+ .filter(Boolean);
164
+ } else if (col === "source" && val) {
165
+ entry.source = val;
166
+ } else if (col === "identity_key" && val) {
167
+ entry.identity_key = val;
168
+ } else if (col === "expires_at" && val) {
169
+ entry.expires_at = val;
170
+ } else if (val && !KNOWN_COLUMNS.has(col)) {
171
+ meta[col] = val;
172
+ }
173
+ }
174
+
175
+ if (!entry.body) continue; // skip rows with no body
176
+ if (Object.keys(meta).length) entry.meta = meta;
177
+ entries.push(entry);
178
+ }
179
+
180
+ return entries;
181
+ }
182
+
183
+ /**
184
+ * Parse a JSON file into EntryData[].
185
+ * Supports: array-of-entries, {entries:[...]}, or ChatGPT export format.
186
+ *
187
+ * @param {string} content
188
+ * @param {{ kind?: string, source?: string }} [opts]
189
+ * @returns {import("./import-pipeline.js").EntryData[]}
190
+ */
191
+ export function parseJson(content, opts = {}) {
192
+ let data;
193
+ try {
194
+ data = JSON.parse(content);
195
+ } catch {
196
+ return [];
197
+ }
198
+
199
+ // Detect format
200
+ let rawEntries;
201
+
202
+ if (Array.isArray(data)) {
203
+ // Array-of-entries OR ChatGPT export format
204
+ if (
205
+ data.length > 0 &&
206
+ data[0].mapping &&
207
+ data[0].create_time !== undefined
208
+ ) {
209
+ return parseChatGptExport(data, opts);
210
+ }
211
+ rawEntries = data;
212
+ } else if (data && Array.isArray(data.entries)) {
213
+ rawEntries = data.entries;
214
+ } else {
215
+ // Single entry object
216
+ rawEntries = [data];
217
+ }
218
+
219
+ return rawEntries
220
+ .filter((e) => e && typeof e === "object" && e.body)
221
+ .map((e) => ({
222
+ kind: e.kind || opts.kind || "insight",
223
+ title: e.title || null,
224
+ body: e.body,
225
+ tags: Array.isArray(e.tags) ? e.tags : undefined,
226
+ meta: e.meta && typeof e.meta === "object" ? e.meta : undefined,
227
+ source: e.source || opts.source || "json-import",
228
+ identity_key: e.identity_key || undefined,
229
+ expires_at: e.expires_at || undefined,
230
+ }));
231
+ }
232
+
233
+ /**
234
+ * Parse ChatGPT export format (array of conversations with mapping + create_time).
235
+ */
236
+ function parseChatGptExport(conversations, opts = {}) {
237
+ const entries = [];
238
+
239
+ for (const conv of conversations) {
240
+ if (!conv.title || !conv.mapping) continue;
241
+
242
+ // Extract all assistant messages from the mapping
243
+ const messages = Object.values(conv.mapping)
244
+ .filter(
245
+ (m) =>
246
+ m.message?.author?.role === "assistant" &&
247
+ m.message.content?.parts?.length,
248
+ )
249
+ .map((m) => m.message.content.parts.join("\n"))
250
+ .filter(Boolean);
251
+
252
+ if (!messages.length) continue;
253
+
254
+ const body = messages.join("\n\n---\n\n");
255
+ const created = conv.create_time
256
+ ? new Date(conv.create_time * 1000).toISOString()
257
+ : undefined;
258
+
259
+ entries.push({
260
+ kind: opts.kind || "conversation",
261
+ title: conv.title,
262
+ body,
263
+ tags: ["chatgpt-import"],
264
+ meta: { conversation_id: conv.id, created_at_original: created },
265
+ source: opts.source || "chatgpt-export",
266
+ });
267
+ }
268
+
269
+ return entries;
270
+ }
271
+
272
+ /**
273
+ * Parse a plain text file into a single EntryData.
274
+ *
275
+ * @param {string} content
276
+ * @param {string} filePath
277
+ * @param {{ kind?: string, source?: string }} [opts]
278
+ * @returns {import("./import-pipeline.js").EntryData[]}
279
+ */
280
+ export function parseText(content, filePath, opts = {}) {
281
+ const trimmed = content.trim();
282
+ if (!trimmed) return [];
283
+
284
+ const name = basename(filePath, extname(filePath));
285
+ const title = name
286
+ .replace(/[-_]/g, " ")
287
+ .replace(/\b\w/g, (c) => c.toUpperCase());
288
+
289
+ return [
290
+ {
291
+ kind: opts.kind || "insight",
292
+ title,
293
+ body: trimmed,
294
+ source: opts.source || "text-import",
295
+ },
296
+ ];
297
+ }
298
+
299
+ /**
300
+ * Parse a single file (auto-detect format).
301
+ *
302
+ * @param {string} filePath
303
+ * @param {string} content
304
+ * @param {{ kind?: string, source?: string }} [opts]
305
+ * @returns {import("./import-pipeline.js").EntryData[]}
306
+ */
307
+ export function parseFile(filePath, content, opts = {}) {
308
+ const format = detectFormat(filePath, content);
309
+
310
+ switch (format) {
311
+ case "markdown":
312
+ return parseMarkdown(content, opts);
313
+ case "csv":
314
+ return parseCsv(content, ",", opts);
315
+ case "tsv":
316
+ return parseCsv(content, "\t", opts);
317
+ case "json":
318
+ return parseJson(content, opts);
319
+ case "text":
320
+ return parseText(content, filePath, opts);
321
+ default:
322
+ return [];
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Recursively parse a directory of files.
328
+ * Walks subdirectories, filters by extension, infers kind from directory name.
329
+ *
330
+ * @param {string} dirPath
331
+ * @param {{ kind?: string, source?: string, extensions?: string[] }} [opts]
332
+ * @returns {import("./import-pipeline.js").EntryData[]}
333
+ */
334
+ export function parseDirectory(dirPath, opts = {}) {
335
+ const extensions = opts.extensions || [
336
+ ".md",
337
+ ".markdown",
338
+ ".csv",
339
+ ".tsv",
340
+ ".json",
341
+ ".txt",
342
+ ];
343
+ const entries = [];
344
+
345
+ function walk(dir, inferredKind) {
346
+ let items;
347
+ try {
348
+ items = readdirSync(dir, { withFileTypes: true });
349
+ } catch {
350
+ return;
351
+ }
352
+
353
+ for (const item of items) {
354
+ if (item.name.startsWith(".") || item.name.startsWith("_")) continue;
355
+
356
+ const fullPath = join(dir, item.name);
357
+
358
+ if (item.isDirectory()) {
359
+ // Try to infer kind from directory name
360
+ const kind =
361
+ dirToKind(item.name) !== item.name
362
+ ? dirToKind(item.name)
363
+ : inferredKind;
364
+ walk(fullPath, kind);
365
+ } else if (item.isFile()) {
366
+ const ext = extname(item.name).toLowerCase();
367
+ if (!extensions.includes(ext)) continue;
368
+
369
+ try {
370
+ const content = readFileSync(fullPath, "utf-8");
371
+ const fileOpts = { ...opts };
372
+ if (inferredKind && !fileOpts.kind) fileOpts.kind = inferredKind;
373
+ const parsed = parseFile(fullPath, content, fileOpts);
374
+ entries.push(...parsed);
375
+ } catch {
376
+ // Skip unreadable files
377
+ }
378
+ }
379
+ }
380
+ }
381
+
382
+ // Infer kind from the top-level directory name
383
+ const topKind = opts.kind || undefined;
384
+ walk(dirPath, topKind);
385
+
386
+ return entries;
387
+ }