beans-memory 0.0.0-stage → 0.1.4
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 +21 -0
- package/README.id.md +354 -0
- package/README.md +353 -2
- package/docs/wordmark.svg +36 -0
- package/examples/claude-code.mcp.json +8 -0
- package/examples/codex.config.toml +8 -0
- package/examples/gemini.settings.json +10 -0
- package/examples/memory-instructions.md +19 -0
- package/package.json +45 -4
- package/skills/beans-memory/SKILL.md +56 -0
- package/src/cli.ts +183 -0
- package/src/db.ts +136 -0
- package/src/import-claude-mem-db.ts +125 -0
- package/src/import-claude-mem-extras.ts +162 -0
- package/src/import-claude-mem.ts +137 -0
- package/src/mcp.ts +230 -0
- package/src/migrate-legacy-db.ts +72 -0
- package/src/plugin.ts +335 -0
- package/src/redact-prompts.ts +27 -0
- package/src/redact.ts +26 -0
- package/src/rehash.ts +45 -0
- package/src/repo.ts +245 -0
- package/src/time.ts +18 -0
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
import { localDate, localStamp } from "./time";
|
|
3
|
+
import { openDb, resolveDbPath } from "./db";
|
|
4
|
+
import {
|
|
5
|
+
addObservation,
|
|
6
|
+
addPrompt,
|
|
7
|
+
ensureSession,
|
|
8
|
+
getObservations,
|
|
9
|
+
recentObservations,
|
|
10
|
+
searchObservations,
|
|
11
|
+
stats,
|
|
12
|
+
touchSessionFiles,
|
|
13
|
+
} from "./repo";
|
|
14
|
+
|
|
15
|
+
type AnyContext = {
|
|
16
|
+
location?: { directory?: string; workspaceID?: string };
|
|
17
|
+
event?: { subscribe(options: { signal: AbortSignal }): AsyncIterable<any> };
|
|
18
|
+
session?: { hook(name: string, handler: (event: any) => unknown): Promise<unknown> };
|
|
19
|
+
tool?: {
|
|
20
|
+
transform(callback: (editor: any) => void): Promise<unknown>;
|
|
21
|
+
hook?(name: string, handler: (event: any) => unknown): Promise<unknown>;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const EDIT_TOOLS = new Set(["edit", "write", "patch", "multiedit", "apply_patch"]);
|
|
26
|
+
|
|
27
|
+
function collectFiles(input: unknown): string[] {
|
|
28
|
+
if (!input || typeof input !== "object") return [];
|
|
29
|
+
const record = input as Record<string, unknown>;
|
|
30
|
+
const files: string[] = [];
|
|
31
|
+
for (const key of ["filePath", "file_path", "path", "filename"]) {
|
|
32
|
+
const value = record[key];
|
|
33
|
+
if (typeof value === "string" && value.length > 0) files.push(value);
|
|
34
|
+
}
|
|
35
|
+
if (Array.isArray(record.edits)) {
|
|
36
|
+
for (const edit of record.edits) {
|
|
37
|
+
if (edit && typeof edit === "object") {
|
|
38
|
+
const value = (edit as Record<string, unknown>).filePath;
|
|
39
|
+
if (typeof value === "string" && value.length > 0) files.push(value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return [...new Set(files)];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function formatContext(project: string, rows: ReturnType<typeof recentObservations>): string {
|
|
47
|
+
if (rows.length === 0) return "";
|
|
48
|
+
const lines = rows.map((row) => {
|
|
49
|
+
let files: string[] = [];
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(row.files);
|
|
52
|
+
if (Array.isArray(parsed)) files = parsed.map((file) => basename(String(file))).slice(0, 3);
|
|
53
|
+
} catch {
|
|
54
|
+
files = [];
|
|
55
|
+
}
|
|
56
|
+
const suffix = files.length > 0 ? ` — ${files.join(", ")}` : "";
|
|
57
|
+
return `- ${localDate(row.created_at)} [${row.type}] ${row.title}${suffix}`;
|
|
58
|
+
});
|
|
59
|
+
return [
|
|
60
|
+
`<memory project="${project}">`,
|
|
61
|
+
"Catatan tersimpan dari sesi sebelumnya. Pakai memory_search untuk mencari, memory_get untuk teks lengkap.",
|
|
62
|
+
...lines,
|
|
63
|
+
"</memory>",
|
|
64
|
+
].join("\n");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export default {
|
|
68
|
+
id: "memory",
|
|
69
|
+
async setup(ctx: AnyContext) {
|
|
70
|
+
const directory = ctx.location?.directory ?? process.cwd();
|
|
71
|
+
const project = process.env.MEMORY_PROJECT || basename(directory);
|
|
72
|
+
|
|
73
|
+
let db: ReturnType<typeof openDb>;
|
|
74
|
+
try {
|
|
75
|
+
db = openDb(resolveDbPath(directory));
|
|
76
|
+
} catch (error) {
|
|
77
|
+
console.error("[memory] gagal membuka database:", error);
|
|
78
|
+
return () => {};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const delivered = new Set<string>();
|
|
82
|
+
const controller = new AbortController();
|
|
83
|
+
|
|
84
|
+
const safe = async <T>(label: string, run: () => T | Promise<T>, fallback: T): Promise<T> => {
|
|
85
|
+
try {
|
|
86
|
+
return await run();
|
|
87
|
+
} catch (error) {
|
|
88
|
+
console.error(`[memory] ${label}:`, error);
|
|
89
|
+
return fallback;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
if (ctx.tool?.transform && process.env.MEMORY_TOOLS !== "off") {
|
|
94
|
+
const registered = await safe<unknown>(
|
|
95
|
+
"register tools",
|
|
96
|
+
() =>
|
|
97
|
+
ctx.tool!.transform((editor) => {
|
|
98
|
+
editor.add({
|
|
99
|
+
name: "memory_note",
|
|
100
|
+
description:
|
|
101
|
+
"Simpan catatan permanen untuk project ini: keputusan, bugfix, aturan bisnis, atau temuan wiring. Tulis singkat dan spesifik. Panggil setelah tugas selesai atau saat menemukan hal yang layak diingat sesi berikutnya.",
|
|
102
|
+
input: {
|
|
103
|
+
type: "object",
|
|
104
|
+
properties: {
|
|
105
|
+
title: { type: "string", description: "Judul satu baris, maksimal 120 karakter." },
|
|
106
|
+
body: {
|
|
107
|
+
type: "string",
|
|
108
|
+
description: "Penjelasan: masalah, keputusan, alasan, dan file terkait.",
|
|
109
|
+
},
|
|
110
|
+
type: {
|
|
111
|
+
type: "string",
|
|
112
|
+
enum: [
|
|
113
|
+
"decision",
|
|
114
|
+
"bugfix",
|
|
115
|
+
"feature",
|
|
116
|
+
"refactor",
|
|
117
|
+
"security_note",
|
|
118
|
+
"note",
|
|
119
|
+
],
|
|
120
|
+
description: "Jenis catatan. Default note.",
|
|
121
|
+
},
|
|
122
|
+
files: {
|
|
123
|
+
type: "array",
|
|
124
|
+
items: { type: "string" },
|
|
125
|
+
description: "Path file yang relevan.",
|
|
126
|
+
},
|
|
127
|
+
concepts: {
|
|
128
|
+
type: "array",
|
|
129
|
+
items: { type: "string" },
|
|
130
|
+
description: "Tag konsep singkat.",
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
required: ["title", "body"],
|
|
134
|
+
additionalProperties: false,
|
|
135
|
+
},
|
|
136
|
+
execute: async (input: any) => {
|
|
137
|
+
const result = addObservation(db, {
|
|
138
|
+
project,
|
|
139
|
+
title: String(input?.title ?? ""),
|
|
140
|
+
body: String(input?.body ?? ""),
|
|
141
|
+
type: typeof input?.type === "string" ? input.type : "note",
|
|
142
|
+
files: Array.isArray(input?.files) ? input.files.map(String) : [],
|
|
143
|
+
concepts: Array.isArray(input?.concepts) ? input.concepts.map(String) : [],
|
|
144
|
+
source: "agent",
|
|
145
|
+
});
|
|
146
|
+
return {
|
|
147
|
+
content: result.inserted
|
|
148
|
+
? `Catatan tersimpan sebagai #${result.id}.`
|
|
149
|
+
: `Catatan identik sudah ada sebagai #${result.id}.`,
|
|
150
|
+
};
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
editor.add({
|
|
155
|
+
name: "memory_search",
|
|
156
|
+
description:
|
|
157
|
+
"Cari catatan memory project ini dengan FTS. Mengembalikan index ringkas berisi id, tanggal, tipe, dan judul. Pakai memory_get untuk isi lengkap.",
|
|
158
|
+
input: {
|
|
159
|
+
type: "object",
|
|
160
|
+
properties: {
|
|
161
|
+
query: { type: "string", description: "Kata kunci pencarian." },
|
|
162
|
+
limit: { type: "number", description: "Jumlah hasil, default 10, maksimal 50." },
|
|
163
|
+
type: {
|
|
164
|
+
type: "string",
|
|
165
|
+
description: "Filter tipe, misalnya decision atau bugfix.",
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
required: ["query"],
|
|
169
|
+
additionalProperties: false,
|
|
170
|
+
},
|
|
171
|
+
execute: async (input: any) => {
|
|
172
|
+
const rows = searchObservations(db, {
|
|
173
|
+
project,
|
|
174
|
+
query: String(input?.query ?? ""),
|
|
175
|
+
limit: Number(input?.limit ?? 10),
|
|
176
|
+
type: typeof input?.type === "string" ? input.type : undefined,
|
|
177
|
+
});
|
|
178
|
+
if (rows.length === 0) return { content: "Tidak ada catatan yang cocok." };
|
|
179
|
+
const lines = rows.map((row) => {
|
|
180
|
+
const snip = row.snip ? ` | ${row.snip.replace(/\s+/g, " ").slice(0, 160)}` : "";
|
|
181
|
+
return `#${row.id} · ${localDate(row.created_at)} · ${row.type} · ${row.title}${snip}`;
|
|
182
|
+
});
|
|
183
|
+
return { content: lines.join("\n") };
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
editor.add({
|
|
188
|
+
name: "memory_get",
|
|
189
|
+
description:
|
|
190
|
+
"Ambil isi lengkap satu atau beberapa catatan memory berdasarkan id hasil memory_search.",
|
|
191
|
+
input: {
|
|
192
|
+
type: "object",
|
|
193
|
+
properties: {
|
|
194
|
+
ids: {
|
|
195
|
+
type: "array",
|
|
196
|
+
items: { type: "number" },
|
|
197
|
+
description: "Daftar id catatan.",
|
|
198
|
+
},
|
|
199
|
+
},
|
|
200
|
+
required: ["ids"],
|
|
201
|
+
additionalProperties: false,
|
|
202
|
+
},
|
|
203
|
+
execute: async (input: any) => {
|
|
204
|
+
const ids = Array.isArray(input?.ids)
|
|
205
|
+
? input.ids.map((id: unknown) => Number(id)).filter(Number.isFinite)
|
|
206
|
+
: [];
|
|
207
|
+
const rows = getObservations(db, ids);
|
|
208
|
+
if (rows.length === 0) return { content: "Catatan tidak ditemukan." };
|
|
209
|
+
const blocks = rows.map((row) =>
|
|
210
|
+
[
|
|
211
|
+
`# ${row.title} (#${row.id})`,
|
|
212
|
+
`Tanggal: ${localStamp(row.created_at)} · Tipe: ${row.type}`,
|
|
213
|
+
row.files.length > 0 ? `File: ${row.files.join(", ")}` : "",
|
|
214
|
+
"",
|
|
215
|
+
row.body,
|
|
216
|
+
]
|
|
217
|
+
.filter(Boolean)
|
|
218
|
+
.join("\n"),
|
|
219
|
+
);
|
|
220
|
+
return { content: blocks.join("\n\n---\n\n") };
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
editor.add({
|
|
225
|
+
name: "memory_stats",
|
|
226
|
+
description: "Ringkasan isi memory project ini: jumlah catatan, prompt, sesi, dan tanggal catatan terakhir.",
|
|
227
|
+
input: { type: "object", properties: {}, additionalProperties: false },
|
|
228
|
+
execute: async () => {
|
|
229
|
+
const value = stats(db, project);
|
|
230
|
+
return {
|
|
231
|
+
content: `Project ${project}: ${value.observations} catatan, ${value.prompts} prompt, ${value.sessions} sesi. Catatan terakhir: ${value.lastObservation ? localStamp(value.lastObservation) : "belum ada"}.`,
|
|
232
|
+
};
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
}),
|
|
236
|
+
null,
|
|
237
|
+
);
|
|
238
|
+
if (registered === null) {
|
|
239
|
+
try {
|
|
240
|
+
db.close();
|
|
241
|
+
} catch {
|
|
242
|
+
// ignore
|
|
243
|
+
}
|
|
244
|
+
return () => {};
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (ctx.session?.hook) {
|
|
249
|
+
await safe(
|
|
250
|
+
"context hook",
|
|
251
|
+
() =>
|
|
252
|
+
ctx.session!.hook("context", async (event: any) => {
|
|
253
|
+
const sessionID = String(event?.sessionID ?? "");
|
|
254
|
+
if (!sessionID || delivered.has(sessionID)) return;
|
|
255
|
+
try {
|
|
256
|
+
const rows = recentObservations(db, project, 8);
|
|
257
|
+
const text = formatContext(project, rows);
|
|
258
|
+
if (!text || !Array.isArray(event.system)) return;
|
|
259
|
+
event.system.push({ type: "text", text });
|
|
260
|
+
delivered.add(sessionID);
|
|
261
|
+
} catch (error) {
|
|
262
|
+
console.error("[memory] context gagal:", error);
|
|
263
|
+
}
|
|
264
|
+
}),
|
|
265
|
+
null,
|
|
266
|
+
);
|
|
267
|
+
|
|
268
|
+
await safe(
|
|
269
|
+
"prompt hook",
|
|
270
|
+
() =>
|
|
271
|
+
ctx.session!.hook("prompt", async (event: any) => {
|
|
272
|
+
const sessionID = String(event?.sessionID ?? "");
|
|
273
|
+
const text = typeof event?.prompt?.text === "string" ? event.prompt.text : "";
|
|
274
|
+
if (!sessionID || !text) return;
|
|
275
|
+
try {
|
|
276
|
+
ensureSession(db, { id: sessionID, project, directory });
|
|
277
|
+
addPrompt(db, { sessionID, project, body: text });
|
|
278
|
+
} catch (error) {
|
|
279
|
+
console.error("[memory] prompt gagal:", error);
|
|
280
|
+
}
|
|
281
|
+
}),
|
|
282
|
+
null,
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (ctx.tool?.hook) {
|
|
287
|
+
await safe(
|
|
288
|
+
"tool hook",
|
|
289
|
+
() =>
|
|
290
|
+
ctx.tool!.hook!("execute.after", async (event: any) => {
|
|
291
|
+
const sessionID = String(event?.sessionID ?? "");
|
|
292
|
+
if (!sessionID || event?.status !== "completed") return;
|
|
293
|
+
const tool = String(event?.tool ?? "");
|
|
294
|
+
if (!EDIT_TOOLS.has(tool)) return;
|
|
295
|
+
try {
|
|
296
|
+
const files = collectFiles(event?.input);
|
|
297
|
+
touchSessionFiles(db, sessionID, files);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
console.error("[memory] tool hook gagal:", error);
|
|
300
|
+
}
|
|
301
|
+
}),
|
|
302
|
+
null,
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (ctx.event?.subscribe) {
|
|
307
|
+
void (async () => {
|
|
308
|
+
try {
|
|
309
|
+
for await (const event of ctx.event!.subscribe({ signal: controller.signal })) {
|
|
310
|
+
const sessionID = event?.data?.sessionID;
|
|
311
|
+
if (typeof sessionID !== "string" || !sessionID) continue;
|
|
312
|
+
if (event.type === "session.created") {
|
|
313
|
+
ensureSession(db, { id: sessionID, project, directory });
|
|
314
|
+
} else if (event.type === "session.deleted") {
|
|
315
|
+
delivered.delete(sessionID);
|
|
316
|
+
} else if (event.type === "session.compaction.ended" || event.type === "session.compacted") {
|
|
317
|
+
delivered.delete(sessionID);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
} catch {
|
|
321
|
+
// stream closed; nothing to do
|
|
322
|
+
}
|
|
323
|
+
})();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return () => {
|
|
327
|
+
controller.abort();
|
|
328
|
+
try {
|
|
329
|
+
db.close();
|
|
330
|
+
} catch {
|
|
331
|
+
// ignore
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
},
|
|
335
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { openDb, resolveDbPath } from "./db";
|
|
2
|
+
import { redactSecrets } from "./redact";
|
|
3
|
+
|
|
4
|
+
const db = openDb(process.argv[2] ?? resolveDbPath());
|
|
5
|
+
|
|
6
|
+
const rows = db
|
|
7
|
+
.query<{ id: number; body: string }, []>("SELECT id, body FROM prompts")
|
|
8
|
+
.all();
|
|
9
|
+
|
|
10
|
+
let updated = 0;
|
|
11
|
+
db.transaction(() => {
|
|
12
|
+
for (const row of rows) {
|
|
13
|
+
const next = redactSecrets(row.body);
|
|
14
|
+
if (next === row.body) continue;
|
|
15
|
+
db.run("UPDATE prompts SET body = ? WHERE id = ?", [next, row.id]);
|
|
16
|
+
updated += 1;
|
|
17
|
+
}
|
|
18
|
+
})();
|
|
19
|
+
|
|
20
|
+
console.log(
|
|
21
|
+
JSON.stringify(
|
|
22
|
+
{ db: process.argv[2] ?? resolveDbPath(), scanned: rows.length, redacted: updated },
|
|
23
|
+
null,
|
|
24
|
+
2,
|
|
25
|
+
),
|
|
26
|
+
);
|
|
27
|
+
db.close();
|
package/src/redact.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const PATTERNS: Array<[RegExp, string]> = [
|
|
2
|
+
[/sk-[A-Za-z0-9_-]{20,}/g, "sk-***"],
|
|
3
|
+
[/gh[pousr]_[A-Za-z0-9]{20,}/g, "gh*_***"],
|
|
4
|
+
[/AKIA[0-9A-Z]{16}/g, "AKIA***"],
|
|
5
|
+
[/https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/]+/g, "https://hooks.slack.com/services/***"],
|
|
6
|
+
[/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g, "https://discord.com/api/webhooks/***"],
|
|
7
|
+
[/xox[baprs]-[A-Za-z0-9-]+/g, "xox*-***"],
|
|
8
|
+
[/AIza[0-9A-Za-z_-]{35}/g, "AIza***"],
|
|
9
|
+
[/Authorization:\s*Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Authorization: Bearer ***"],
|
|
10
|
+
[
|
|
11
|
+
/(\b[A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|ACCESS_KEY|PRIVATE_KEY)[A-Z0-9_]*\s*[:=]\s*["']?)[^\s"',]{6,}/gi,
|
|
12
|
+
"$1***",
|
|
13
|
+
],
|
|
14
|
+
[
|
|
15
|
+
/(?<=\b(password|passwd|secret|token|api[_-]?key)\b\s*[:=]\s*["']?)[^\s"',]{6,}/gi,
|
|
16
|
+
"***",
|
|
17
|
+
],
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
export function redactSecrets(text: string): string {
|
|
21
|
+
let value = text;
|
|
22
|
+
for (const [pattern, replacement] of PATTERNS) {
|
|
23
|
+
value = value.replace(pattern, replacement);
|
|
24
|
+
}
|
|
25
|
+
return value;
|
|
26
|
+
}
|
package/src/rehash.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { openDb, resolveDbPath } from "./db";
|
|
3
|
+
|
|
4
|
+
const db = openDb(process.argv[2] ?? resolveDbPath());
|
|
5
|
+
|
|
6
|
+
function hashOf(project: string, title: string, body: string): string {
|
|
7
|
+
return createHash("sha256")
|
|
8
|
+
.update(JSON.stringify([project, title, body]))
|
|
9
|
+
.digest("hex");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const rows = db
|
|
13
|
+
.query<
|
|
14
|
+
{ id: number; project: string; title: string; body: string; content_hash: string },
|
|
15
|
+
[]
|
|
16
|
+
>("SELECT id, project, title, coalesce(body, '') AS body, content_hash FROM observations")
|
|
17
|
+
.all();
|
|
18
|
+
|
|
19
|
+
let updated = 0;
|
|
20
|
+
let removed = 0;
|
|
21
|
+
|
|
22
|
+
db.transaction(() => {
|
|
23
|
+
for (const row of rows) {
|
|
24
|
+
const next = hashOf(row.project, row.title, row.body);
|
|
25
|
+
if (next === row.content_hash) continue;
|
|
26
|
+
|
|
27
|
+
const clash = db
|
|
28
|
+
.query<{ id: number }, [string, number]>(
|
|
29
|
+
"SELECT id FROM observations WHERE content_hash = ? AND id <> ?",
|
|
30
|
+
)
|
|
31
|
+
.get(next, row.id);
|
|
32
|
+
|
|
33
|
+
if (clash) {
|
|
34
|
+
db.run("DELETE FROM observations WHERE id = ?", [row.id]);
|
|
35
|
+
removed += 1;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
db.run("UPDATE observations SET content_hash = ? WHERE id = ?", [next, row.id]);
|
|
40
|
+
updated += 1;
|
|
41
|
+
}
|
|
42
|
+
})();
|
|
43
|
+
|
|
44
|
+
console.log(JSON.stringify({ db: process.argv[2] ?? resolveDbPath(), scanned: rows.length, updated, removed }, null, 2));
|
|
45
|
+
db.close();
|
package/src/repo.ts
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { redactSecrets } from "./redact";
|
|
4
|
+
|
|
5
|
+
export type ObservationInput = {
|
|
6
|
+
sessionID?: string | null;
|
|
7
|
+
project: string;
|
|
8
|
+
type?: string;
|
|
9
|
+
title: string;
|
|
10
|
+
body?: string;
|
|
11
|
+
files?: string[];
|
|
12
|
+
concepts?: string[];
|
|
13
|
+
source?: "agent" | "capture" | "import" | "import_summary";
|
|
14
|
+
createdAt?: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type ObservationRow = {
|
|
18
|
+
id: number;
|
|
19
|
+
created_at: string;
|
|
20
|
+
type: string;
|
|
21
|
+
title: string;
|
|
22
|
+
files: string;
|
|
23
|
+
snip?: string;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function hashOf(project: string, title: string, body: string): string {
|
|
27
|
+
return createHash("sha256")
|
|
28
|
+
.update(JSON.stringify([project, title, body]))
|
|
29
|
+
.digest("hex");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function json(value: string[] | undefined): string {
|
|
33
|
+
return JSON.stringify(value ?? []);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function ensureSession(
|
|
37
|
+
db: Database,
|
|
38
|
+
input: { id: string; project: string; directory?: string; title?: string },
|
|
39
|
+
): void {
|
|
40
|
+
const now = new Date().toISOString();
|
|
41
|
+
db.run(
|
|
42
|
+
`INSERT INTO sessions (id, project, directory, title, started_at)
|
|
43
|
+
VALUES (?, ?, ?, ?, ?)
|
|
44
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
45
|
+
title = coalesce(excluded.title, sessions.title)`,
|
|
46
|
+
[input.id, input.project, input.directory ?? null, input.title ?? null, now],
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function touchSessionFiles(db: Database, sessionID: string, files: string[]): void {
|
|
51
|
+
if (!sessionID || files.length === 0) return;
|
|
52
|
+
const row = db
|
|
53
|
+
.query<{ files: string }, [string]>("SELECT files FROM sessions WHERE id = ?")
|
|
54
|
+
.get(sessionID);
|
|
55
|
+
if (!row) return;
|
|
56
|
+
let existing: string[] = [];
|
|
57
|
+
try {
|
|
58
|
+
existing = JSON.parse(row.files);
|
|
59
|
+
} catch {
|
|
60
|
+
existing = [];
|
|
61
|
+
}
|
|
62
|
+
const merged = [...new Set([...existing, ...files])].slice(-200);
|
|
63
|
+
db.run("UPDATE sessions SET files = ? WHERE id = ?", [JSON.stringify(merged), sessionID]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function addPrompt(
|
|
67
|
+
db: Database,
|
|
68
|
+
input: { sessionID: string; project: string; body: string },
|
|
69
|
+
): void {
|
|
70
|
+
const body = redactSecrets(input.body).trim().slice(0, 8000);
|
|
71
|
+
if (!body) return;
|
|
72
|
+
const now = new Date();
|
|
73
|
+
db.run(
|
|
74
|
+
"INSERT INTO prompts (session_id, project, body, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?)",
|
|
75
|
+
[input.sessionID, input.project, body, now.toISOString(), now.getTime()],
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function addObservation(
|
|
80
|
+
db: Database,
|
|
81
|
+
input: ObservationInput,
|
|
82
|
+
): { id: number; inserted: boolean } {
|
|
83
|
+
const title = input.title.trim().slice(0, 300);
|
|
84
|
+
const body = (input.body ?? "").trim().slice(0, 20000);
|
|
85
|
+
if (!title) throw new Error("title is required");
|
|
86
|
+
const created = input.createdAt ? new Date(input.createdAt) : new Date();
|
|
87
|
+
const hash = hashOf(input.project, title, body);
|
|
88
|
+
|
|
89
|
+
const existing = db
|
|
90
|
+
.query<{ id: number }, [string]>("SELECT id FROM observations WHERE content_hash = ?")
|
|
91
|
+
.get(hash);
|
|
92
|
+
if (existing) return { id: existing.id, inserted: false };
|
|
93
|
+
|
|
94
|
+
db.run(
|
|
95
|
+
`INSERT INTO observations
|
|
96
|
+
(session_id, project, type, title, body, files, concepts, source, content_hash, created_at, created_at_epoch)
|
|
97
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
98
|
+
ON CONFLICT(content_hash) DO NOTHING`,
|
|
99
|
+
[
|
|
100
|
+
input.sessionID ?? null,
|
|
101
|
+
input.project,
|
|
102
|
+
input.type ?? "note",
|
|
103
|
+
title,
|
|
104
|
+
body,
|
|
105
|
+
json(input.files),
|
|
106
|
+
json(input.concepts),
|
|
107
|
+
input.source ?? "agent",
|
|
108
|
+
hash,
|
|
109
|
+
created.toISOString(),
|
|
110
|
+
created.getTime(),
|
|
111
|
+
],
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
const changed = db.query<{ n: number }, []>("SELECT changes() AS n").get()?.n ?? 0;
|
|
115
|
+
const row = db
|
|
116
|
+
.query<{ id: number }, [string]>("SELECT id FROM observations WHERE content_hash = ?")
|
|
117
|
+
.get(hash);
|
|
118
|
+
return { id: row?.id ?? 0, inserted: changed > 0 };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function recentObservations(
|
|
122
|
+
db: Database,
|
|
123
|
+
project: string,
|
|
124
|
+
limit = 8,
|
|
125
|
+
): ObservationRow[] {
|
|
126
|
+
return db
|
|
127
|
+
.query<ObservationRow, [string, number]>(
|
|
128
|
+
`SELECT id, created_at, type, title, files
|
|
129
|
+
FROM observations
|
|
130
|
+
WHERE project = ? AND source <> 'import_summary'
|
|
131
|
+
ORDER BY created_at_epoch DESC
|
|
132
|
+
LIMIT ?`,
|
|
133
|
+
)
|
|
134
|
+
.all(project, limit);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function tokensOf(query: string): string[] {
|
|
138
|
+
return (query.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []).slice(0, 8);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function searchObservations(
|
|
142
|
+
db: Database,
|
|
143
|
+
input: { project: string; query: string; limit?: number; type?: string },
|
|
144
|
+
): ObservationRow[] {
|
|
145
|
+
const limit = Math.min(Math.max(input.limit ?? 10, 1), 50);
|
|
146
|
+
const tokens = tokensOf(input.query);
|
|
147
|
+
if (tokens.length === 0) return recentObservations(db, input.project, limit);
|
|
148
|
+
|
|
149
|
+
const typeFilter = input.type ? "AND o.type = ?" : "";
|
|
150
|
+
const run = (match: string): ObservationRow[] => {
|
|
151
|
+
const params: (string | number)[] = [match, input.project];
|
|
152
|
+
if (input.type) params.push(input.type);
|
|
153
|
+
params.push(limit);
|
|
154
|
+
try {
|
|
155
|
+
return db
|
|
156
|
+
.query<ObservationRow, (string | number)[]>(
|
|
157
|
+
`SELECT o.id, o.created_at, o.type, o.title, o.files,
|
|
158
|
+
snippet(observations_fts, -1, '[', ']', '…', 12) AS snip
|
|
159
|
+
FROM observations_fts
|
|
160
|
+
JOIN observations o ON o.id = observations_fts.rowid
|
|
161
|
+
WHERE observations_fts MATCH ? AND o.project = ? ${typeFilter}
|
|
162
|
+
ORDER BY bm25(observations_fts)
|
|
163
|
+
LIMIT ?`,
|
|
164
|
+
)
|
|
165
|
+
.all(...params);
|
|
166
|
+
} catch (error) {
|
|
167
|
+
console.error("[memory] pencarian gagal:", error);
|
|
168
|
+
return [];
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const quoted = tokens.map((token) => `"${token}"*`);
|
|
173
|
+
const precise = run(quoted.join(" "));
|
|
174
|
+
if (precise.length > 0) return precise;
|
|
175
|
+
return run(quoted.join(" OR "));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function getObservations(
|
|
179
|
+
db: Database,
|
|
180
|
+
ids: number[],
|
|
181
|
+
): Array<{
|
|
182
|
+
id: number;
|
|
183
|
+
created_at: string;
|
|
184
|
+
type: string;
|
|
185
|
+
title: string;
|
|
186
|
+
body: string;
|
|
187
|
+
files: string[];
|
|
188
|
+
concepts: string[];
|
|
189
|
+
}> {
|
|
190
|
+
if (ids.length === 0) return [];
|
|
191
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
192
|
+
const rows = db
|
|
193
|
+
.query<
|
|
194
|
+
{
|
|
195
|
+
id: number;
|
|
196
|
+
created_at: string;
|
|
197
|
+
type: string;
|
|
198
|
+
title: string;
|
|
199
|
+
body: string;
|
|
200
|
+
files: string;
|
|
201
|
+
concepts: string;
|
|
202
|
+
},
|
|
203
|
+
number[]
|
|
204
|
+
>(
|
|
205
|
+
`SELECT id, created_at, type, title, coalesce(body, '') AS body, files, concepts
|
|
206
|
+
FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`,
|
|
207
|
+
)
|
|
208
|
+
.all(...ids);
|
|
209
|
+
|
|
210
|
+
return rows.map((row) => ({
|
|
211
|
+
...row,
|
|
212
|
+
files: safeArray(row.files),
|
|
213
|
+
concepts: safeArray(row.concepts),
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function safeArray(value: string): string[] {
|
|
218
|
+
try {
|
|
219
|
+
const parsed = JSON.parse(value);
|
|
220
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
221
|
+
} catch {
|
|
222
|
+
return [];
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function stats(
|
|
227
|
+
db: Database,
|
|
228
|
+
project: string,
|
|
229
|
+
): { observations: number; prompts: number; sessions: number; lastObservation: string | null } {
|
|
230
|
+
const observations = db
|
|
231
|
+
.query<{ n: number }, [string]>("SELECT count(*) AS n FROM observations WHERE project = ?")
|
|
232
|
+
.get(project)?.n ?? 0;
|
|
233
|
+
const prompts = db
|
|
234
|
+
.query<{ n: number }, [string]>("SELECT count(*) AS n FROM prompts WHERE project = ?")
|
|
235
|
+
.get(project)?.n ?? 0;
|
|
236
|
+
const sessions = db
|
|
237
|
+
.query<{ n: number }, [string]>("SELECT count(*) AS n FROM sessions WHERE project = ?")
|
|
238
|
+
.get(project)?.n ?? 0;
|
|
239
|
+
const last = db
|
|
240
|
+
.query<{ created_at: string }, [string]>(
|
|
241
|
+
"SELECT created_at FROM observations WHERE project = ? ORDER BY created_at_epoch DESC LIMIT 1",
|
|
242
|
+
)
|
|
243
|
+
.get(project)?.created_at ?? null;
|
|
244
|
+
return { observations, prompts, sessions, lastObservation: last };
|
|
245
|
+
}
|
package/src/time.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const stamp = new Intl.DateTimeFormat("sv-SE", {
|
|
2
|
+
dateStyle: "short",
|
|
3
|
+
timeStyle: "short",
|
|
4
|
+
});
|
|
5
|
+
|
|
6
|
+
const dateOnly = new Intl.DateTimeFormat("sv-SE", { dateStyle: "short" });
|
|
7
|
+
|
|
8
|
+
export function localStamp(iso: string): string {
|
|
9
|
+
const value = new Date(iso);
|
|
10
|
+
if (Number.isNaN(value.getTime())) return iso.slice(0, 16).replace("T", " ");
|
|
11
|
+
return stamp.format(value);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function localDate(iso: string): string {
|
|
15
|
+
const value = new Date(iso);
|
|
16
|
+
if (Number.isNaN(value.getTime())) return iso.slice(0, 10);
|
|
17
|
+
return dateOnly.format(value);
|
|
18
|
+
}
|