@persql/context 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/README.md +89 -0
- package/dist/chunk-RMG66FDI.js +339 -0
- package/dist/chunk-RMG66FDI.js.map +1 -0
- package/dist/core.cjs +384 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.cts +188 -0
- package/dist/core.d.ts +188 -0
- package/dist/core.js +49 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +549 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +87 -0
- package/dist/index.d.ts +87 -0
- package/dist/index.js +210 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
ContextStore: () => ContextStore,
|
|
24
|
+
EXTRACTION_JSON_SCHEMA: () => EXTRACTION_JSON_SCHEMA,
|
|
25
|
+
EXTRACTION_SYSTEM_PROMPT: () => EXTRACTION_SYSTEM_PROMPT,
|
|
26
|
+
SCHEMA_SQL: () => SCHEMA_SQL,
|
|
27
|
+
SCHEMA_VERSION: () => SCHEMA_VERSION,
|
|
28
|
+
TABLE_PREFIX: () => TABLE_PREFIX,
|
|
29
|
+
buildByTag: () => buildByTag,
|
|
30
|
+
buildEdgesAmong: () => buildEdgesAmong,
|
|
31
|
+
buildExtractionMessages: () => buildExtractionMessages,
|
|
32
|
+
buildForget: () => buildForget,
|
|
33
|
+
buildGet: () => buildGet,
|
|
34
|
+
buildInit: () => buildInit,
|
|
35
|
+
buildNeighborEntities: () => buildNeighborEntities,
|
|
36
|
+
buildRecall: () => buildRecall,
|
|
37
|
+
buildRecent: () => buildRecent,
|
|
38
|
+
buildRemember: () => buildRemember,
|
|
39
|
+
buildStats: () => buildStats,
|
|
40
|
+
buildSupersede: () => buildSupersede,
|
|
41
|
+
buildUpsertEdge: () => buildUpsertEdge,
|
|
42
|
+
buildUpsertEntity: () => buildUpsertEntity,
|
|
43
|
+
context: () => context,
|
|
44
|
+
entityId: () => entityId,
|
|
45
|
+
normalizeTags: () => normalizeTags,
|
|
46
|
+
toFtsQuery: () => toFtsQuery
|
|
47
|
+
});
|
|
48
|
+
module.exports = __toCommonJS(index_exports);
|
|
49
|
+
|
|
50
|
+
// src/core.ts
|
|
51
|
+
var SCHEMA_VERSION = 1;
|
|
52
|
+
var TABLE_PREFIX = "ctx_";
|
|
53
|
+
var T = TABLE_PREFIX;
|
|
54
|
+
var SCHEMA_SQL = [
|
|
55
|
+
`CREATE TABLE IF NOT EXISTS ${T}memory (
|
|
56
|
+
id TEXT PRIMARY KEY,
|
|
57
|
+
kind TEXT NOT NULL DEFAULT 'fact',
|
|
58
|
+
topic TEXT,
|
|
59
|
+
body TEXT NOT NULL,
|
|
60
|
+
tags TEXT,
|
|
61
|
+
source TEXT,
|
|
62
|
+
created_at INTEGER NOT NULL,
|
|
63
|
+
superseded_by TEXT
|
|
64
|
+
)`,
|
|
65
|
+
`CREATE INDEX IF NOT EXISTS ${T}memory_kind ON ${T}memory(kind)`,
|
|
66
|
+
`CREATE INDEX IF NOT EXISTS ${T}memory_created ON ${T}memory(created_at)`,
|
|
67
|
+
`CREATE INDEX IF NOT EXISTS ${T}memory_superseded ON ${T}memory(superseded_by)`,
|
|
68
|
+
// External-content FTS index: body text is not duplicated, only indexed.
|
|
69
|
+
// Porter stemmer so "invoice" recalls "invoicing" without embeddings.
|
|
70
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS ${T}memory_fts USING fts5(
|
|
71
|
+
topic, body, tags,
|
|
72
|
+
content='${T}memory', content_rowid='rowid',
|
|
73
|
+
tokenize='porter unicode61'
|
|
74
|
+
)`,
|
|
75
|
+
`CREATE TRIGGER IF NOT EXISTS ${T}memory_ai AFTER INSERT ON ${T}memory BEGIN
|
|
76
|
+
INSERT INTO ${T}memory_fts(rowid, topic, body, tags)
|
|
77
|
+
VALUES (new.rowid, new.topic, new.body, new.tags);
|
|
78
|
+
END`,
|
|
79
|
+
`CREATE TRIGGER IF NOT EXISTS ${T}memory_ad AFTER DELETE ON ${T}memory BEGIN
|
|
80
|
+
INSERT INTO ${T}memory_fts(${T}memory_fts, rowid, topic, body, tags)
|
|
81
|
+
VALUES ('delete', old.rowid, old.topic, old.body, old.tags);
|
|
82
|
+
END`,
|
|
83
|
+
`CREATE TRIGGER IF NOT EXISTS ${T}memory_au AFTER UPDATE ON ${T}memory BEGIN
|
|
84
|
+
INSERT INTO ${T}memory_fts(${T}memory_fts, rowid, topic, body, tags)
|
|
85
|
+
VALUES ('delete', old.rowid, old.topic, old.body, old.tags);
|
|
86
|
+
INSERT INTO ${T}memory_fts(rowid, topic, body, tags)
|
|
87
|
+
VALUES (new.rowid, new.topic, new.body, new.tags);
|
|
88
|
+
END`,
|
|
89
|
+
`CREATE TABLE IF NOT EXISTS ${T}entity (
|
|
90
|
+
id TEXT PRIMARY KEY,
|
|
91
|
+
name TEXT NOT NULL,
|
|
92
|
+
kind TEXT,
|
|
93
|
+
body TEXT,
|
|
94
|
+
created_at INTEGER NOT NULL
|
|
95
|
+
)`,
|
|
96
|
+
`CREATE TABLE IF NOT EXISTS ${T}edge (
|
|
97
|
+
id TEXT PRIMARY KEY,
|
|
98
|
+
src TEXT NOT NULL,
|
|
99
|
+
rel TEXT NOT NULL,
|
|
100
|
+
dst TEXT NOT NULL,
|
|
101
|
+
source TEXT,
|
|
102
|
+
created_at INTEGER NOT NULL
|
|
103
|
+
)`,
|
|
104
|
+
`CREATE INDEX IF NOT EXISTS ${T}edge_src ON ${T}edge(src)`,
|
|
105
|
+
`CREATE INDEX IF NOT EXISTS ${T}edge_dst ON ${T}edge(dst)`
|
|
106
|
+
];
|
|
107
|
+
function buildInit() {
|
|
108
|
+
return SCHEMA_SQL.map((sql) => ({ sql, params: [] }));
|
|
109
|
+
}
|
|
110
|
+
var FTS_OPERATORS = /* @__PURE__ */ new Set(["and", "or", "not", "near"]);
|
|
111
|
+
function normalizeTags(tags) {
|
|
112
|
+
if (!tags) return null;
|
|
113
|
+
const arr = Array.isArray(tags) ? tags : String(tags).split(/[,\s]+/);
|
|
114
|
+
const norm = Array.from(
|
|
115
|
+
new Set(arr.map((t) => t.trim().toLowerCase()).filter(Boolean))
|
|
116
|
+
);
|
|
117
|
+
return norm.length ? norm.join(" ") : null;
|
|
118
|
+
}
|
|
119
|
+
function toFtsQuery(input, opts = {}) {
|
|
120
|
+
if (opts.mode === "raw") return input.trim() || null;
|
|
121
|
+
const tokens = (input.match(/[\p{L}\p{N}_]+/gu) ?? []).filter(
|
|
122
|
+
(t) => !FTS_OPERATORS.has(t.toLowerCase())
|
|
123
|
+
);
|
|
124
|
+
if (!tokens.length) return null;
|
|
125
|
+
const joiner = opts.operator === "and" ? " AND " : " OR ";
|
|
126
|
+
return tokens.map((t) => `"${t}"`).join(joiner);
|
|
127
|
+
}
|
|
128
|
+
function slugId(prefix, s) {
|
|
129
|
+
const base = s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 96);
|
|
130
|
+
return prefix + (base || "x");
|
|
131
|
+
}
|
|
132
|
+
function entityId(name) {
|
|
133
|
+
return slugId("e_", name);
|
|
134
|
+
}
|
|
135
|
+
function resolveEntityRef(ref) {
|
|
136
|
+
return ref.startsWith("e_") ? ref : entityId(ref);
|
|
137
|
+
}
|
|
138
|
+
function edgeId(srcId, rel, dstId) {
|
|
139
|
+
return slugId("x_", `${srcId}|${rel}|${dstId}`);
|
|
140
|
+
}
|
|
141
|
+
var MEMORY_COLS = "id, kind, topic, body, tags, source, created_at AS createdAt, superseded_by AS supersededBy";
|
|
142
|
+
function buildRemember(input, now, id) {
|
|
143
|
+
return {
|
|
144
|
+
sql: `INSERT INTO ${T}memory (id, kind, topic, body, tags, source, created_at, superseded_by)
|
|
145
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`,
|
|
146
|
+
params: [
|
|
147
|
+
id,
|
|
148
|
+
input.kind ?? "fact",
|
|
149
|
+
input.topic ?? null,
|
|
150
|
+
input.body,
|
|
151
|
+
normalizeTags(input.tags),
|
|
152
|
+
input.source ?? null,
|
|
153
|
+
now
|
|
154
|
+
]
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function buildSupersede(oldId, newId) {
|
|
158
|
+
return {
|
|
159
|
+
sql: `UPDATE ${T}memory SET superseded_by = ? WHERE id = ? AND superseded_by IS NULL`,
|
|
160
|
+
params: [newId, oldId]
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function buildForget(id) {
|
|
164
|
+
return { sql: `DELETE FROM ${T}memory WHERE id = ?`, params: [id] };
|
|
165
|
+
}
|
|
166
|
+
function buildGet(id) {
|
|
167
|
+
return {
|
|
168
|
+
sql: `SELECT ${MEMORY_COLS} FROM ${T}memory WHERE id = ?`,
|
|
169
|
+
params: [id]
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function buildRecall(query, opts = {}) {
|
|
173
|
+
const match = toFtsQuery(query, { operator: opts.operator, mode: opts.mode });
|
|
174
|
+
if (!match) return null;
|
|
175
|
+
const where = [`${T}memory_fts MATCH ?`];
|
|
176
|
+
const params = [match];
|
|
177
|
+
if (!opts.includeSuperseded) where.push("m.superseded_by IS NULL");
|
|
178
|
+
if (opts.kind) {
|
|
179
|
+
where.push("m.kind = ?");
|
|
180
|
+
params.push(opts.kind);
|
|
181
|
+
}
|
|
182
|
+
if (opts.sinceMs != null) {
|
|
183
|
+
where.push("m.created_at >= ?");
|
|
184
|
+
params.push(opts.sinceMs);
|
|
185
|
+
}
|
|
186
|
+
params.push(opts.limit ?? 8);
|
|
187
|
+
return {
|
|
188
|
+
sql: `SELECT m.id, m.kind, m.topic, m.body, m.tags, m.source,
|
|
189
|
+
m.created_at AS createdAt, m.superseded_by AS supersededBy
|
|
190
|
+
FROM ${T}memory_fts
|
|
191
|
+
JOIN ${T}memory m ON m.rowid = ${T}memory_fts.rowid
|
|
192
|
+
WHERE ${where.join(" AND ")}
|
|
193
|
+
ORDER BY ${T}memory_fts.rank
|
|
194
|
+
LIMIT ?`,
|
|
195
|
+
params
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
function buildRecent(opts = {}) {
|
|
199
|
+
const where = [];
|
|
200
|
+
const params = [];
|
|
201
|
+
if (!opts.includeSuperseded) where.push("superseded_by IS NULL");
|
|
202
|
+
if (opts.kind) {
|
|
203
|
+
where.push("kind = ?");
|
|
204
|
+
params.push(opts.kind);
|
|
205
|
+
}
|
|
206
|
+
params.push(opts.limit ?? 20);
|
|
207
|
+
return {
|
|
208
|
+
sql: `SELECT ${MEMORY_COLS} FROM ${T}memory
|
|
209
|
+
${where.length ? "WHERE " + where.join(" AND ") : ""}
|
|
210
|
+
ORDER BY created_at DESC
|
|
211
|
+
LIMIT ?`,
|
|
212
|
+
params
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
function buildByTag(tag, opts = {}) {
|
|
216
|
+
const t = tag.trim().toLowerCase();
|
|
217
|
+
const where = ["(' ' || COALESCE(tags, '') || ' ') LIKE ?"];
|
|
218
|
+
const params = [`% ${t} %`];
|
|
219
|
+
if (!opts.includeSuperseded) where.push("superseded_by IS NULL");
|
|
220
|
+
if (opts.kind) {
|
|
221
|
+
where.push("kind = ?");
|
|
222
|
+
params.push(opts.kind);
|
|
223
|
+
}
|
|
224
|
+
params.push(opts.limit ?? 20);
|
|
225
|
+
return {
|
|
226
|
+
sql: `SELECT ${MEMORY_COLS} FROM ${T}memory
|
|
227
|
+
WHERE ${where.join(" AND ")}
|
|
228
|
+
ORDER BY created_at DESC
|
|
229
|
+
LIMIT ?`,
|
|
230
|
+
params
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
function buildStats() {
|
|
234
|
+
return {
|
|
235
|
+
sql: `SELECT
|
|
236
|
+
(SELECT count(*) FROM ${T}memory WHERE superseded_by IS NULL) AS facts,
|
|
237
|
+
(SELECT count(*) FROM ${T}memory) AS facts_total,
|
|
238
|
+
(SELECT count(*) FROM ${T}entity) AS entities,
|
|
239
|
+
(SELECT count(*) FROM ${T}edge) AS edges`,
|
|
240
|
+
params: []
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
function buildUpsertEntity(e, now) {
|
|
244
|
+
const id = e.id ?? entityId(e.name);
|
|
245
|
+
return {
|
|
246
|
+
sql: `INSERT INTO ${T}entity (id, name, kind, body, created_at)
|
|
247
|
+
VALUES (?, ?, ?, ?, ?)
|
|
248
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
249
|
+
name = excluded.name,
|
|
250
|
+
kind = COALESCE(excluded.kind, ${T}entity.kind),
|
|
251
|
+
body = COALESCE(excluded.body, ${T}entity.body)`,
|
|
252
|
+
params: [id, e.name, e.kind ?? null, e.body ?? null, now]
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function buildUpsertEdge(e, now) {
|
|
256
|
+
const srcId = resolveEntityRef(e.src);
|
|
257
|
+
const dstId = resolveEntityRef(e.dst);
|
|
258
|
+
const id = edgeId(srcId, e.rel, dstId);
|
|
259
|
+
return {
|
|
260
|
+
sql: `INSERT INTO ${T}edge (id, src, rel, dst, source, created_at)
|
|
261
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
262
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
263
|
+
source = COALESCE(excluded.source, ${T}edge.source)`,
|
|
264
|
+
params: [id, srcId, e.rel, dstId, e.source ?? null, now]
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
function buildNeighborEntities(seedId, depth, limit) {
|
|
268
|
+
return {
|
|
269
|
+
sql: `WITH RECURSIVE reach(id, depth) AS (
|
|
270
|
+
SELECT ?, 0
|
|
271
|
+
UNION
|
|
272
|
+
SELECT CASE WHEN e.src = reach.id THEN e.dst ELSE e.src END,
|
|
273
|
+
reach.depth + 1
|
|
274
|
+
FROM reach
|
|
275
|
+
JOIN ${T}edge e ON (e.src = reach.id OR e.dst = reach.id)
|
|
276
|
+
WHERE reach.depth < ?
|
|
277
|
+
)
|
|
278
|
+
SELECT en.id, en.name, en.kind, en.body,
|
|
279
|
+
en.created_at AS createdAt, MIN(reach.depth) AS depth
|
|
280
|
+
FROM reach
|
|
281
|
+
JOIN ${T}entity en ON en.id = reach.id
|
|
282
|
+
WHERE reach.depth > 0 AND en.id <> ?
|
|
283
|
+
GROUP BY en.id
|
|
284
|
+
ORDER BY depth, en.name
|
|
285
|
+
LIMIT ?`,
|
|
286
|
+
// The seed reappears at depth >0 via a round-trip on undirected edges;
|
|
287
|
+
// exclude it explicitly so it isn't listed as its own neighbor.
|
|
288
|
+
params: [seedId, depth, seedId, limit]
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function buildEdgesAmong(ids) {
|
|
292
|
+
if (!ids.length) {
|
|
293
|
+
return { sql: `SELECT id, src, rel, dst, source, created_at AS createdAt FROM ${T}edge WHERE 0`, params: [] };
|
|
294
|
+
}
|
|
295
|
+
const ph = ids.map(() => "?").join(", ");
|
|
296
|
+
return {
|
|
297
|
+
sql: `SELECT id, src, rel, dst, source, created_at AS createdAt
|
|
298
|
+
FROM ${T}edge
|
|
299
|
+
WHERE src IN (${ph}) AND dst IN (${ph})`,
|
|
300
|
+
params: [...ids, ...ids]
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
var EXTRACTION_SYSTEM_PROMPT = `You extract durable, shareable context from raw text for a team of AI agents that will read it later by keyword.
|
|
304
|
+
|
|
305
|
+
Return JSON: { "facts": [...], "entities": [...], "edges": [...] }.
|
|
306
|
+
- facts: atomic, self-contained statements worth remembering across sessions \u2014 decisions, conventions, constraints, identifiers, preferences. Each: { "body": string, "topic"?: string, "tags"?: string[] }. Prefer specific and stable over transient chatter.
|
|
307
|
+
- entities: named things \u2014 services, people, tables, repos, concepts. Each: { "name": string, "kind"?: string, "body"?: short description }.
|
|
308
|
+
- edges: relationships between entities, referencing entity names. Each: { "src": name, "rel": string, "dst": name }.
|
|
309
|
+
|
|
310
|
+
Be conservative: omit anything ephemeral or low-value. Use lowercase tags. If nothing is worth keeping, return empty arrays.`;
|
|
311
|
+
function buildExtractionMessages(raw, opts = {}) {
|
|
312
|
+
return [
|
|
313
|
+
{ role: "system", content: EXTRACTION_SYSTEM_PROMPT },
|
|
314
|
+
{
|
|
315
|
+
role: "user",
|
|
316
|
+
content: (opts.hint ? `Context: ${opts.hint}
|
|
317
|
+
|
|
318
|
+
` : "") + raw
|
|
319
|
+
}
|
|
320
|
+
];
|
|
321
|
+
}
|
|
322
|
+
var EXTRACTION_JSON_SCHEMA = {
|
|
323
|
+
type: "object",
|
|
324
|
+
properties: {
|
|
325
|
+
facts: {
|
|
326
|
+
type: "array",
|
|
327
|
+
items: {
|
|
328
|
+
type: "object",
|
|
329
|
+
properties: {
|
|
330
|
+
body: { type: "string" },
|
|
331
|
+
topic: { type: "string" },
|
|
332
|
+
tags: { type: "array", items: { type: "string" } }
|
|
333
|
+
},
|
|
334
|
+
required: ["body"]
|
|
335
|
+
}
|
|
336
|
+
},
|
|
337
|
+
entities: {
|
|
338
|
+
type: "array",
|
|
339
|
+
items: {
|
|
340
|
+
type: "object",
|
|
341
|
+
properties: {
|
|
342
|
+
name: { type: "string" },
|
|
343
|
+
kind: { type: "string" },
|
|
344
|
+
body: { type: "string" }
|
|
345
|
+
},
|
|
346
|
+
required: ["name"]
|
|
347
|
+
}
|
|
348
|
+
},
|
|
349
|
+
edges: {
|
|
350
|
+
type: "array",
|
|
351
|
+
items: {
|
|
352
|
+
type: "object",
|
|
353
|
+
properties: {
|
|
354
|
+
src: { type: "string" },
|
|
355
|
+
rel: { type: "string" },
|
|
356
|
+
dst: { type: "string" }
|
|
357
|
+
},
|
|
358
|
+
required: ["src", "rel", "dst"]
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
// src/index.ts
|
|
365
|
+
function uid(prefix) {
|
|
366
|
+
const g = globalThis;
|
|
367
|
+
const r = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.floor(Math.random() * 1e9).toString(36)}`;
|
|
368
|
+
return prefix + r;
|
|
369
|
+
}
|
|
370
|
+
var ContextStore = class {
|
|
371
|
+
constructor(db, opts = {}) {
|
|
372
|
+
this.db = db;
|
|
373
|
+
this.opts = opts;
|
|
374
|
+
}
|
|
375
|
+
/** Create the schema (idempotent). Run once before first use. */
|
|
376
|
+
async init() {
|
|
377
|
+
await this.db.batch(buildInit());
|
|
378
|
+
}
|
|
379
|
+
// --- writes -------------------------------------------------------------
|
|
380
|
+
/** Store one structured fact/episode/artifact. Returns its id. */
|
|
381
|
+
async remember(input) {
|
|
382
|
+
const id = input.id ?? uid("m_");
|
|
383
|
+
const now = Date.now();
|
|
384
|
+
const stmts = [
|
|
385
|
+
buildRemember({ ...input, source: input.source ?? this.opts.source }, now, id)
|
|
386
|
+
];
|
|
387
|
+
const sup = input.supersedes ? Array.isArray(input.supersedes) ? input.supersedes : [input.supersedes] : [];
|
|
388
|
+
for (const old of sup) stmts.push(buildSupersede(old, id));
|
|
389
|
+
await this.db.transaction(stmts);
|
|
390
|
+
return id;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Extract durable context from raw text and store it. The LLM runs on the
|
|
394
|
+
* write path; pass `extract` here or to the constructor (or use the hosted
|
|
395
|
+
* Context MCP, which runs extraction server-side and meters it).
|
|
396
|
+
*/
|
|
397
|
+
async rememberRaw(raw, opts = {}) {
|
|
398
|
+
const extract = opts.extract ?? this.opts.extract;
|
|
399
|
+
if (!extract) {
|
|
400
|
+
throw new Error(
|
|
401
|
+
"ContextStore.rememberRaw needs an extractor: pass { extract } here or to the constructor, or use the hosted PerSQL Context MCP."
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
const extracted = await extract(raw, { hint: opts.hint });
|
|
405
|
+
return this.write(extracted, { source: opts.source });
|
|
406
|
+
}
|
|
407
|
+
/** Persist an already-extracted bundle of facts, entities, and edges. */
|
|
408
|
+
async write(extracted, opts = {}) {
|
|
409
|
+
const now = Date.now();
|
|
410
|
+
const source = opts.source ?? this.opts.source;
|
|
411
|
+
const stmts = [];
|
|
412
|
+
const memoryIds = [];
|
|
413
|
+
const entityIds = /* @__PURE__ */ new Set();
|
|
414
|
+
for (const f of extracted.facts ?? []) {
|
|
415
|
+
const id = uid("m_");
|
|
416
|
+
memoryIds.push(id);
|
|
417
|
+
stmts.push(buildRemember({ ...f, source }, now, id));
|
|
418
|
+
}
|
|
419
|
+
for (const e of extracted.entities ?? []) {
|
|
420
|
+
stmts.push(buildUpsertEntity(e, now));
|
|
421
|
+
entityIds.add(e.id ?? entityId(e.name));
|
|
422
|
+
}
|
|
423
|
+
for (const ed of extracted.edges ?? []) {
|
|
424
|
+
stmts.push(buildUpsertEntity({ name: ed.src }, now));
|
|
425
|
+
stmts.push(buildUpsertEntity({ name: ed.dst }, now));
|
|
426
|
+
stmts.push(buildUpsertEdge({ ...ed, source: ed.source ?? source }, now));
|
|
427
|
+
entityIds.add(entityId(ed.src));
|
|
428
|
+
entityIds.add(entityId(ed.dst));
|
|
429
|
+
}
|
|
430
|
+
if (stmts.length) await this.db.transaction(stmts);
|
|
431
|
+
return {
|
|
432
|
+
memoryIds,
|
|
433
|
+
entityIds: [...entityIds],
|
|
434
|
+
edgeCount: (extracted.edges ?? []).length
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
/** Mark older memory rows as replaced by `newId` (filtered out of recall). */
|
|
438
|
+
async supersede(oldIds, newId) {
|
|
439
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
440
|
+
await this.db.transaction(ids.map((o) => buildSupersede(o, newId)));
|
|
441
|
+
}
|
|
442
|
+
/** Hard-delete a memory row. */
|
|
443
|
+
async forget(id) {
|
|
444
|
+
const s = buildForget(id);
|
|
445
|
+
await this.db.query(s.sql, s.params);
|
|
446
|
+
}
|
|
447
|
+
/** Add a relationship between two entities (created if absent). */
|
|
448
|
+
async link(src, rel, dst, opts = {}) {
|
|
449
|
+
const now = Date.now();
|
|
450
|
+
await this.db.transaction([
|
|
451
|
+
buildUpsertEntity({ name: src }, now),
|
|
452
|
+
buildUpsertEntity({ name: dst }, now),
|
|
453
|
+
buildUpsertEdge(
|
|
454
|
+
{ src, rel, dst, source: opts.source ?? this.opts.source },
|
|
455
|
+
now
|
|
456
|
+
)
|
|
457
|
+
]);
|
|
458
|
+
}
|
|
459
|
+
// --- reads (no AI, pure lexical SQL) ------------------------------------
|
|
460
|
+
/** Keyword recall, BM25-ranked, most relevant first. */
|
|
461
|
+
async recall(query, opts = {}) {
|
|
462
|
+
const resolved = { ...opts };
|
|
463
|
+
if (opts.withinDays != null && opts.sinceMs == null) {
|
|
464
|
+
resolved.sinceMs = Date.now() - opts.withinDays * 864e5;
|
|
465
|
+
}
|
|
466
|
+
const s = buildRecall(query, resolved);
|
|
467
|
+
if (!s) return [];
|
|
468
|
+
const { data } = await this.db.query(s.sql, s.params);
|
|
469
|
+
return data;
|
|
470
|
+
}
|
|
471
|
+
/** Most recent memory rows. */
|
|
472
|
+
async recent(opts = {}) {
|
|
473
|
+
const s = buildRecent(opts);
|
|
474
|
+
const { data } = await this.db.query(s.sql, s.params);
|
|
475
|
+
return data;
|
|
476
|
+
}
|
|
477
|
+
/** Memory rows carrying a given tag. */
|
|
478
|
+
async byTag(tag, opts = {}) {
|
|
479
|
+
const s = buildByTag(tag, opts);
|
|
480
|
+
const { data } = await this.db.query(s.sql, s.params);
|
|
481
|
+
return data;
|
|
482
|
+
}
|
|
483
|
+
/** Fetch one memory row by id, or null. */
|
|
484
|
+
async get(id) {
|
|
485
|
+
const s = buildGet(id);
|
|
486
|
+
const { data } = await this.db.query(s.sql, s.params);
|
|
487
|
+
return data[0] ?? null;
|
|
488
|
+
}
|
|
489
|
+
/** The subgraph around an entity: reachable entities + the edges among them. */
|
|
490
|
+
async neighbors(name, opts = {}) {
|
|
491
|
+
const seed = name.startsWith("e_") ? name : entityId(name);
|
|
492
|
+
const depth = Math.min(Math.max(opts.depth ?? 1, 1), 4);
|
|
493
|
+
const entStmt = buildNeighborEntities(seed, depth, opts.limit ?? 50);
|
|
494
|
+
const { data: entities } = await this.db.query(
|
|
495
|
+
entStmt.sql,
|
|
496
|
+
entStmt.params
|
|
497
|
+
);
|
|
498
|
+
const ids = [seed, ...entities.map((e) => e.id)];
|
|
499
|
+
const edgeStmt = buildEdgesAmong(ids);
|
|
500
|
+
const { data: edges } = await this.db.query(
|
|
501
|
+
edgeStmt.sql,
|
|
502
|
+
edgeStmt.params
|
|
503
|
+
);
|
|
504
|
+
return { entities, edges };
|
|
505
|
+
}
|
|
506
|
+
/** Counts: current facts, total facts, entities, edges. */
|
|
507
|
+
async stats() {
|
|
508
|
+
const s = buildStats();
|
|
509
|
+
const { data } = await this.db.query(s.sql, s.params);
|
|
510
|
+
const r = data[0];
|
|
511
|
+
return {
|
|
512
|
+
facts: r?.facts ?? 0,
|
|
513
|
+
factsTotal: r?.facts_total ?? 0,
|
|
514
|
+
entities: r?.entities ?? 0,
|
|
515
|
+
edges: r?.edges ?? 0
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
function context(db, opts) {
|
|
520
|
+
return new ContextStore(db, opts);
|
|
521
|
+
}
|
|
522
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
523
|
+
0 && (module.exports = {
|
|
524
|
+
ContextStore,
|
|
525
|
+
EXTRACTION_JSON_SCHEMA,
|
|
526
|
+
EXTRACTION_SYSTEM_PROMPT,
|
|
527
|
+
SCHEMA_SQL,
|
|
528
|
+
SCHEMA_VERSION,
|
|
529
|
+
TABLE_PREFIX,
|
|
530
|
+
buildByTag,
|
|
531
|
+
buildEdgesAmong,
|
|
532
|
+
buildExtractionMessages,
|
|
533
|
+
buildForget,
|
|
534
|
+
buildGet,
|
|
535
|
+
buildInit,
|
|
536
|
+
buildNeighborEntities,
|
|
537
|
+
buildRecall,
|
|
538
|
+
buildRecent,
|
|
539
|
+
buildRemember,
|
|
540
|
+
buildStats,
|
|
541
|
+
buildSupersede,
|
|
542
|
+
buildUpsertEdge,
|
|
543
|
+
buildUpsertEntity,
|
|
544
|
+
context,
|
|
545
|
+
entityId,
|
|
546
|
+
normalizeTags,
|
|
547
|
+
toFtsQuery
|
|
548
|
+
});
|
|
549
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/core.ts"],"sourcesContent":["/**\n * @persql/context — shared, structured agent context on the PerSQL substrate.\n *\n * One store, readable and writable from every agent surface PerSQL speaks\n * (SDK, MCP, published endpoints, CLI). Reads and structured writes are plain\n * SQL over `@persql/sdk` — cheap, exact, lexical (FTS5). The raw-dump extract\n * path puts the LLM on the *write* side: file once, recall by keyword forever.\n */\n\nimport type { PerSQLDatabase } from \"@persql/sdk\";\nimport {\n buildInit,\n buildRemember,\n buildSupersede,\n buildForget,\n buildGet,\n buildRecall,\n buildRecent,\n buildByTag,\n buildStats,\n buildUpsertEntity,\n buildUpsertEdge,\n buildNeighborEntities,\n buildEdgesAmong,\n entityId,\n type RememberInput,\n type RecallOptions,\n type ListOptions,\n type MemoryRow,\n type EntityInput,\n type Edge,\n type Entity,\n type ExtractedContext,\n type SqlStatement,\n} from \"./core\";\n\nexport * from \"./core\";\n\n/** Bring-your-own-LLM extractor, or use the hosted PerSQL Context worker. */\nexport type Extractor = (\n raw: string,\n ctx: { hint?: string }\n) => Promise<ExtractedContext>;\n\nexport interface ContextStoreOptions {\n /** Default extractor for `rememberRaw` (model-agnostic; you supply it). */\n extract?: Extractor;\n /** Default provenance label stamped on writes (e.g. \"claude-code\"). */\n source?: string;\n}\n\nexport interface WriteResult {\n memoryIds: string[];\n entityIds: string[];\n edgeCount: number;\n}\n\nexport interface ContextStats {\n facts: number;\n factsTotal: number;\n entities: number;\n edges: number;\n}\n\nfunction uid(prefix: string): string {\n const g = globalThis as { crypto?: { randomUUID?: () => string } };\n const r =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.floor(Math.random() * 1e9).toString(36)}`;\n return prefix + r;\n}\n\nexport class ContextStore {\n constructor(\n private readonly db: PerSQLDatabase,\n private readonly opts: ContextStoreOptions = {}\n ) {}\n\n /** Create the schema (idempotent). Run once before first use. */\n async init(): Promise<void> {\n await this.db.batch(buildInit());\n }\n\n // --- writes -------------------------------------------------------------\n\n /** Store one structured fact/episode/artifact. Returns its id. */\n async remember(input: RememberInput): Promise<string> {\n const id = input.id ?? uid(\"m_\");\n const now = Date.now();\n const stmts: SqlStatement[] = [\n buildRemember({ ...input, source: input.source ?? this.opts.source }, now, id),\n ];\n const sup = input.supersedes\n ? Array.isArray(input.supersedes)\n ? input.supersedes\n : [input.supersedes]\n : [];\n for (const old of sup) stmts.push(buildSupersede(old, id));\n await this.db.transaction(stmts);\n return id;\n }\n\n /**\n * Extract durable context from raw text and store it. The LLM runs on the\n * write path; pass `extract` here or to the constructor (or use the hosted\n * Context MCP, which runs extraction server-side and meters it).\n */\n async rememberRaw(\n raw: string,\n opts: { extract?: Extractor; hint?: string; source?: string } = {}\n ): Promise<WriteResult> {\n const extract = opts.extract ?? this.opts.extract;\n if (!extract) {\n throw new Error(\n \"ContextStore.rememberRaw needs an extractor: pass { extract } here or to the constructor, or use the hosted PerSQL Context MCP.\"\n );\n }\n const extracted = await extract(raw, { hint: opts.hint });\n return this.write(extracted, { source: opts.source });\n }\n\n /** Persist an already-extracted bundle of facts, entities, and edges. */\n async write(\n extracted: ExtractedContext,\n opts: { source?: string } = {}\n ): Promise<WriteResult> {\n const now = Date.now();\n const source = opts.source ?? this.opts.source;\n const stmts: SqlStatement[] = [];\n const memoryIds: string[] = [];\n const entityIds = new Set<string>();\n\n for (const f of extracted.facts ?? []) {\n const id = uid(\"m_\");\n memoryIds.push(id);\n stmts.push(buildRemember({ ...f, source }, now, id));\n }\n for (const e of extracted.entities ?? []) {\n stmts.push(buildUpsertEntity(e, now));\n entityIds.add(e.id ?? entityId(e.name));\n }\n for (const ed of extracted.edges ?? []) {\n // Ensure both endpoints exist before linking them.\n stmts.push(buildUpsertEntity({ name: ed.src }, now));\n stmts.push(buildUpsertEntity({ name: ed.dst }, now));\n stmts.push(buildUpsertEdge({ ...ed, source: ed.source ?? source }, now));\n entityIds.add(entityId(ed.src));\n entityIds.add(entityId(ed.dst));\n }\n\n if (stmts.length) await this.db.transaction(stmts);\n return {\n memoryIds,\n entityIds: [...entityIds],\n edgeCount: (extracted.edges ?? []).length,\n };\n }\n\n /** Mark older memory rows as replaced by `newId` (filtered out of recall). */\n async supersede(oldIds: string | string[], newId: string): Promise<void> {\n const ids = Array.isArray(oldIds) ? oldIds : [oldIds];\n await this.db.transaction(ids.map((o) => buildSupersede(o, newId)));\n }\n\n /** Hard-delete a memory row. */\n async forget(id: string): Promise<void> {\n const s = buildForget(id);\n await this.db.query(s.sql, s.params);\n }\n\n /** Add a relationship between two entities (created if absent). */\n async link(\n src: string,\n rel: string,\n dst: string,\n opts: { source?: string } = {}\n ): Promise<void> {\n const now = Date.now();\n await this.db.transaction([\n buildUpsertEntity({ name: src }, now),\n buildUpsertEntity({ name: dst }, now),\n buildUpsertEdge(\n { src, rel, dst, source: opts.source ?? this.opts.source },\n now\n ),\n ]);\n }\n\n // --- reads (no AI, pure lexical SQL) ------------------------------------\n\n /** Keyword recall, BM25-ranked, most relevant first. */\n async recall(query: string, opts: RecallOptions = {}): Promise<MemoryRow[]> {\n const resolved: RecallOptions = { ...opts };\n if (opts.withinDays != null && opts.sinceMs == null) {\n resolved.sinceMs = Date.now() - opts.withinDays * 86_400_000;\n }\n const s = buildRecall(query, resolved);\n if (!s) return [];\n const { data } = await this.db.query<MemoryRow>(s.sql, s.params);\n return data;\n }\n\n /** Most recent memory rows. */\n async recent(opts: ListOptions = {}): Promise<MemoryRow[]> {\n const s = buildRecent(opts);\n const { data } = await this.db.query<MemoryRow>(s.sql, s.params);\n return data;\n }\n\n /** Memory rows carrying a given tag. */\n async byTag(tag: string, opts: ListOptions = {}): Promise<MemoryRow[]> {\n const s = buildByTag(tag, opts);\n const { data } = await this.db.query<MemoryRow>(s.sql, s.params);\n return data;\n }\n\n /** Fetch one memory row by id, or null. */\n async get(id: string): Promise<MemoryRow | null> {\n const s = buildGet(id);\n const { data } = await this.db.query<MemoryRow>(s.sql, s.params);\n return data[0] ?? null;\n }\n\n /** The subgraph around an entity: reachable entities + the edges among them. */\n async neighbors(\n name: string,\n opts: { depth?: number; limit?: number } = {}\n ): Promise<{ entities: Entity[]; edges: Edge[] }> {\n const seed = name.startsWith(\"e_\") ? name : entityId(name);\n const depth = Math.min(Math.max(opts.depth ?? 1, 1), 4);\n const entStmt = buildNeighborEntities(seed, depth, opts.limit ?? 50);\n const { data: entities } = await this.db.query<Entity>(\n entStmt.sql,\n entStmt.params\n );\n const ids = [seed, ...entities.map((e) => e.id)];\n const edgeStmt = buildEdgesAmong(ids);\n const { data: edges } = await this.db.query<Edge>(\n edgeStmt.sql,\n edgeStmt.params\n );\n return { entities, edges };\n }\n\n /** Counts: current facts, total facts, entities, edges. */\n async stats(): Promise<ContextStats> {\n const s = buildStats();\n const { data } = await this.db.query<{\n facts: number;\n facts_total: number;\n entities: number;\n edges: number;\n }>(s.sql, s.params);\n const r = data[0];\n return {\n facts: r?.facts ?? 0,\n factsTotal: r?.facts_total ?? 0,\n entities: r?.entities ?? 0,\n edges: r?.edges ?? 0,\n };\n }\n}\n\n/** Wrap a PerSQL database handle as a shared context store. */\nexport function context(\n db: PerSQLDatabase,\n opts?: ContextStoreOptions\n): ContextStore {\n return new ContextStore(db, opts);\n}\n","/**\n * @persql/context/core — zero-runtime-dependency engine.\n *\n * Schema DDL, SQL builders, and the extraction/compaction contracts shared by\n * the `@persql/context` SDK (client-side, over `@persql/sdk`) and the hosted\n * PerSQL Context worker (server-side, over `@persql/ai`). Keeping both sides on\n * the same builders means client-recall and server-recall can never drift.\n *\n * Retrieval is lexical: FTS5 with the porter stemmer, BM25-ranked. No vectors.\n */\n\nexport const SCHEMA_VERSION = 1;\nexport const TABLE_PREFIX = \"ctx_\";\nconst T = TABLE_PREFIX;\n\nexport type MemoryKind = \"fact\" | \"episode\" | \"artifact\";\n\nexport interface MemoryRow {\n id: string;\n kind: MemoryKind;\n topic: string | null;\n body: string;\n tags: string | null;\n source: string | null;\n createdAt: number;\n supersededBy: string | null;\n}\n\nexport interface Entity {\n id: string;\n name: string;\n kind: string | null;\n body: string | null;\n createdAt: number;\n}\n\nexport interface Edge {\n id: string;\n src: string;\n rel: string;\n dst: string;\n source: string | null;\n createdAt: number;\n}\n\nexport interface RememberInput {\n body: string;\n topic?: string;\n kind?: MemoryKind;\n tags?: string[] | string;\n source?: string;\n supersedes?: string | string[];\n id?: string;\n}\n\nexport interface EntityInput {\n name: string;\n kind?: string;\n body?: string;\n id?: string;\n}\n\nexport interface EdgeInput {\n src: string;\n rel: string;\n dst: string;\n source?: string;\n}\n\nexport interface RecallOptions {\n limit?: number;\n kind?: MemoryKind;\n operator?: \"or\" | \"and\";\n mode?: \"terms\" | \"raw\";\n sinceMs?: number;\n withinDays?: number;\n includeSuperseded?: boolean;\n}\n\nexport interface ListOptions {\n limit?: number;\n kind?: MemoryKind;\n includeSuperseded?: boolean;\n}\n\n/** The shape an extractor (LLM or the hosted worker) returns from raw text. */\nexport interface ExtractedContext {\n facts?: Array<{ body: string; topic?: string; tags?: string[]; kind?: MemoryKind }>;\n entities?: EntityInput[];\n edges?: EdgeInput[];\n}\n\nexport interface SqlStatement {\n sql: string;\n params: unknown[];\n}\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nexport const SCHEMA_SQL: string[] = [\n `CREATE TABLE IF NOT EXISTS ${T}memory (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL DEFAULT 'fact',\n topic TEXT,\n body TEXT NOT NULL,\n tags TEXT,\n source TEXT,\n created_at INTEGER NOT NULL,\n superseded_by TEXT\n )`,\n `CREATE INDEX IF NOT EXISTS ${T}memory_kind ON ${T}memory(kind)`,\n `CREATE INDEX IF NOT EXISTS ${T}memory_created ON ${T}memory(created_at)`,\n `CREATE INDEX IF NOT EXISTS ${T}memory_superseded ON ${T}memory(superseded_by)`,\n // External-content FTS index: body text is not duplicated, only indexed.\n // Porter stemmer so \"invoice\" recalls \"invoicing\" without embeddings.\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${T}memory_fts USING fts5(\n topic, body, tags,\n content='${T}memory', content_rowid='rowid',\n tokenize='porter unicode61'\n )`,\n `CREATE TRIGGER IF NOT EXISTS ${T}memory_ai AFTER INSERT ON ${T}memory BEGIN\n INSERT INTO ${T}memory_fts(rowid, topic, body, tags)\n VALUES (new.rowid, new.topic, new.body, new.tags);\n END`,\n `CREATE TRIGGER IF NOT EXISTS ${T}memory_ad AFTER DELETE ON ${T}memory BEGIN\n INSERT INTO ${T}memory_fts(${T}memory_fts, rowid, topic, body, tags)\n VALUES ('delete', old.rowid, old.topic, old.body, old.tags);\n END`,\n `CREATE TRIGGER IF NOT EXISTS ${T}memory_au AFTER UPDATE ON ${T}memory BEGIN\n INSERT INTO ${T}memory_fts(${T}memory_fts, rowid, topic, body, tags)\n VALUES ('delete', old.rowid, old.topic, old.body, old.tags);\n INSERT INTO ${T}memory_fts(rowid, topic, body, tags)\n VALUES (new.rowid, new.topic, new.body, new.tags);\n END`,\n `CREATE TABLE IF NOT EXISTS ${T}entity (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n kind TEXT,\n body TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS ${T}edge (\n id TEXT PRIMARY KEY,\n src TEXT NOT NULL,\n rel TEXT NOT NULL,\n dst TEXT NOT NULL,\n source TEXT,\n created_at INTEGER NOT NULL\n )`,\n `CREATE INDEX IF NOT EXISTS ${T}edge_src ON ${T}edge(src)`,\n `CREATE INDEX IF NOT EXISTS ${T}edge_dst ON ${T}edge(dst)`,\n];\n\nexport function buildInit(): SqlStatement[] {\n return SCHEMA_SQL.map((sql) => ({ sql, params: [] }));\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst FTS_OPERATORS = new Set([\"and\", \"or\", \"not\", \"near\"]);\n\nexport function normalizeTags(tags?: string[] | string | null): string | null {\n if (!tags) return null;\n const arr = Array.isArray(tags) ? tags : String(tags).split(/[,\\s]+/);\n const norm = Array.from(\n new Set(arr.map((t) => t.trim().toLowerCase()).filter(Boolean))\n );\n return norm.length ? norm.join(\" \") : null;\n}\n\n/**\n * Turn arbitrary user text into a safe FTS5 MATCH expression. `terms` mode\n * (default) extracts word tokens, drops bare boolean operators, and ORs the\n * rest as quoted terms — so a caller can paste \"invoice OR billing\" or just\n * \"invoice billing\" and neither crashes the parser nor injects FTS syntax.\n * `raw` mode passes a hand-written FTS expression through untouched.\n */\nexport function toFtsQuery(\n input: string,\n opts: { operator?: \"or\" | \"and\"; mode?: \"terms\" | \"raw\" } = {}\n): string | null {\n if (opts.mode === \"raw\") return input.trim() || null;\n const tokens = (input.match(/[\\p{L}\\p{N}_]+/gu) ?? []).filter(\n (t) => !FTS_OPERATORS.has(t.toLowerCase())\n );\n if (!tokens.length) return null;\n const joiner = opts.operator === \"and\" ? \" AND \" : \" OR \";\n return tokens.map((t) => `\"${t}\"`).join(joiner);\n}\n\nfunction slugId(prefix: string, s: string): string {\n const base = s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 96);\n return prefix + (base || \"x\");\n}\n\n/** Deterministic id for an entity, keyed on its name (case-insensitive). */\nexport function entityId(name: string): string {\n return slugId(\"e_\", name);\n}\n\nfunction resolveEntityRef(ref: string): string {\n return ref.startsWith(\"e_\") ? ref : entityId(ref);\n}\n\nfunction edgeId(srcId: string, rel: string, dstId: string): string {\n return slugId(\"x_\", `${srcId}|${rel}|${dstId}`);\n}\n\nconst MEMORY_COLS =\n \"id, kind, topic, body, tags, source, created_at AS createdAt, superseded_by AS supersededBy\";\n\n// ---------------------------------------------------------------------------\n// Memory builders\n// ---------------------------------------------------------------------------\n\nexport function buildRemember(\n input: RememberInput,\n now: number,\n id: string\n): SqlStatement {\n return {\n sql: `INSERT INTO ${T}memory (id, kind, topic, body, tags, source, created_at, superseded_by)\n VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`,\n params: [\n id,\n input.kind ?? \"fact\",\n input.topic ?? null,\n input.body,\n normalizeTags(input.tags),\n input.source ?? null,\n now,\n ],\n };\n}\n\nexport function buildSupersede(oldId: string, newId: string): SqlStatement {\n return {\n sql: `UPDATE ${T}memory SET superseded_by = ? WHERE id = ? AND superseded_by IS NULL`,\n params: [newId, oldId],\n };\n}\n\nexport function buildForget(id: string): SqlStatement {\n return { sql: `DELETE FROM ${T}memory WHERE id = ?`, params: [id] };\n}\n\nexport function buildGet(id: string): SqlStatement {\n return {\n sql: `SELECT ${MEMORY_COLS} FROM ${T}memory WHERE id = ?`,\n params: [id],\n };\n}\n\nexport function buildRecall(\n query: string,\n opts: RecallOptions = {}\n): SqlStatement | null {\n const match = toFtsQuery(query, { operator: opts.operator, mode: opts.mode });\n if (!match) return null;\n const where: string[] = [`${T}memory_fts MATCH ?`];\n const params: unknown[] = [match];\n if (!opts.includeSuperseded) where.push(\"m.superseded_by IS NULL\");\n if (opts.kind) {\n where.push(\"m.kind = ?\");\n params.push(opts.kind);\n }\n if (opts.sinceMs != null) {\n where.push(\"m.created_at >= ?\");\n params.push(opts.sinceMs);\n }\n params.push(opts.limit ?? 8);\n return {\n sql: `SELECT m.id, m.kind, m.topic, m.body, m.tags, m.source,\n m.created_at AS createdAt, m.superseded_by AS supersededBy\n FROM ${T}memory_fts\n JOIN ${T}memory m ON m.rowid = ${T}memory_fts.rowid\n WHERE ${where.join(\" AND \")}\n ORDER BY ${T}memory_fts.rank\n LIMIT ?`,\n params,\n };\n}\n\nexport function buildRecent(opts: ListOptions = {}): SqlStatement {\n const where: string[] = [];\n const params: unknown[] = [];\n if (!opts.includeSuperseded) where.push(\"superseded_by IS NULL\");\n if (opts.kind) {\n where.push(\"kind = ?\");\n params.push(opts.kind);\n }\n params.push(opts.limit ?? 20);\n return {\n sql: `SELECT ${MEMORY_COLS} FROM ${T}memory\n ${where.length ? \"WHERE \" + where.join(\" AND \") : \"\"}\n ORDER BY created_at DESC\n LIMIT ?`,\n params,\n };\n}\n\nexport function buildByTag(tag: string, opts: ListOptions = {}): SqlStatement {\n const t = tag.trim().toLowerCase();\n const where: string[] = [\"(' ' || COALESCE(tags, '') || ' ') LIKE ?\"];\n const params: unknown[] = [`% ${t} %`];\n if (!opts.includeSuperseded) where.push(\"superseded_by IS NULL\");\n if (opts.kind) {\n where.push(\"kind = ?\");\n params.push(opts.kind);\n }\n params.push(opts.limit ?? 20);\n return {\n sql: `SELECT ${MEMORY_COLS} FROM ${T}memory\n WHERE ${where.join(\" AND \")}\n ORDER BY created_at DESC\n LIMIT ?`,\n params,\n };\n}\n\nexport function buildStats(): SqlStatement {\n return {\n sql: `SELECT\n (SELECT count(*) FROM ${T}memory WHERE superseded_by IS NULL) AS facts,\n (SELECT count(*) FROM ${T}memory) AS facts_total,\n (SELECT count(*) FROM ${T}entity) AS entities,\n (SELECT count(*) FROM ${T}edge) AS edges`,\n params: [],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Graph builders\n// ---------------------------------------------------------------------------\n\nexport function buildUpsertEntity(e: EntityInput, now: number): SqlStatement {\n const id = e.id ?? entityId(e.name);\n return {\n sql: `INSERT INTO ${T}entity (id, name, kind, body, created_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n name = excluded.name,\n kind = COALESCE(excluded.kind, ${T}entity.kind),\n body = COALESCE(excluded.body, ${T}entity.body)`,\n params: [id, e.name, e.kind ?? null, e.body ?? null, now],\n };\n}\n\nexport function buildUpsertEdge(e: EdgeInput, now: number): SqlStatement {\n const srcId = resolveEntityRef(e.src);\n const dstId = resolveEntityRef(e.dst);\n const id = edgeId(srcId, e.rel, dstId);\n return {\n sql: `INSERT INTO ${T}edge (id, src, rel, dst, source, created_at)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n source = COALESCE(excluded.source, ${T}edge.source)`,\n params: [id, srcId, e.rel, dstId, e.source ?? null, now],\n };\n}\n\n/** Entities reachable from a seed within `depth` hops (seed excluded). */\nexport function buildNeighborEntities(\n seedId: string,\n depth: number,\n limit: number\n): SqlStatement {\n return {\n sql: `WITH RECURSIVE reach(id, depth) AS (\n SELECT ?, 0\n UNION\n SELECT CASE WHEN e.src = reach.id THEN e.dst ELSE e.src END,\n reach.depth + 1\n FROM reach\n JOIN ${T}edge e ON (e.src = reach.id OR e.dst = reach.id)\n WHERE reach.depth < ?\n )\n SELECT en.id, en.name, en.kind, en.body,\n en.created_at AS createdAt, MIN(reach.depth) AS depth\n FROM reach\n JOIN ${T}entity en ON en.id = reach.id\n WHERE reach.depth > 0 AND en.id <> ?\n GROUP BY en.id\n ORDER BY depth, en.name\n LIMIT ?`,\n // The seed reappears at depth >0 via a round-trip on undirected edges;\n // exclude it explicitly so it isn't listed as its own neighbor.\n params: [seedId, depth, seedId, limit],\n };\n}\n\nexport function buildEdgesAmong(ids: string[]): SqlStatement {\n if (!ids.length) {\n return { sql: `SELECT id, src, rel, dst, source, created_at AS createdAt FROM ${T}edge WHERE 0`, params: [] };\n }\n const ph = ids.map(() => \"?\").join(\", \");\n return {\n sql: `SELECT id, src, rel, dst, source, created_at AS createdAt\n FROM ${T}edge\n WHERE src IN (${ph}) AND dst IN (${ph})`,\n params: [...ids, ...ids],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Extraction / compaction contracts (used by the hosted worker + documented\n// for bring-your-own-LLM callers; kept here so the prompt is versioned with\n// the schema it has to populate).\n// ---------------------------------------------------------------------------\n\nexport const EXTRACTION_SYSTEM_PROMPT = `You extract durable, shareable context from raw text for a team of AI agents that will read it later by keyword.\n\nReturn JSON: { \"facts\": [...], \"entities\": [...], \"edges\": [...] }.\n- facts: atomic, self-contained statements worth remembering across sessions — decisions, conventions, constraints, identifiers, preferences. Each: { \"body\": string, \"topic\"?: string, \"tags\"?: string[] }. Prefer specific and stable over transient chatter.\n- entities: named things — services, people, tables, repos, concepts. Each: { \"name\": string, \"kind\"?: string, \"body\"?: short description }.\n- edges: relationships between entities, referencing entity names. Each: { \"src\": name, \"rel\": string, \"dst\": name }.\n\nBe conservative: omit anything ephemeral or low-value. Use lowercase tags. If nothing is worth keeping, return empty arrays.`;\n\nexport function buildExtractionMessages(\n raw: string,\n opts: { hint?: string } = {}\n): Array<{ role: \"system\" | \"user\"; content: string }> {\n return [\n { role: \"system\", content: EXTRACTION_SYSTEM_PROMPT },\n {\n role: \"user\",\n content: (opts.hint ? `Context: ${opts.hint}\\n\\n` : \"\") + raw,\n },\n ];\n}\n\nexport const EXTRACTION_JSON_SCHEMA = {\n type: \"object\",\n properties: {\n facts: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n body: { type: \"string\" },\n topic: { type: \"string\" },\n tags: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"body\"],\n },\n },\n entities: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n kind: { type: \"string\" },\n body: { type: \"string\" },\n },\n required: [\"name\"],\n },\n },\n edges: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n src: { type: \"string\" },\n rel: { type: \"string\" },\n dst: { type: \"string\" },\n },\n required: [\"src\", \"rel\", \"dst\"],\n },\n },\n },\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,iBAAiB;AACvB,IAAM,eAAe;AAC5B,IAAM,IAAI;AAwFH,IAAM,aAAuB;AAAA,EAClC,8BAA8B,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU/B,8BAA8B,CAAC,kBAAkB,CAAC;AAAA,EAClD,8BAA8B,CAAC,qBAAqB,CAAC;AAAA,EACrD,8BAA8B,CAAC,wBAAwB,CAAC;AAAA;AAAA;AAAA,EAGxD,sCAAsC,CAAC;AAAA;AAAA,gBAEzB,CAAC;AAAA;AAAA;AAAA,EAGf,gCAAgC,CAAC,6BAA6B,CAAC;AAAA,mBAC9C,CAAC;AAAA;AAAA;AAAA,EAGlB,gCAAgC,CAAC,6BAA6B,CAAC;AAAA,mBAC9C,CAAC,cAAc,CAAC;AAAA;AAAA;AAAA,EAGjC,gCAAgC,CAAC,6BAA6B,CAAC;AAAA,mBAC9C,CAAC,cAAc,CAAC;AAAA;AAAA,mBAEhB,CAAC;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