beans-memory 0.0.0-stage → 0.1.5

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/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
+ }