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/src/cli.ts ADDED
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env bun
2
+ import { basename } from "node:path";
3
+ import { openDb, resolveDbPath } from "./db";
4
+ import {
5
+ addObservation,
6
+ getObservations,
7
+ recentObservations,
8
+ searchObservations,
9
+ stats,
10
+ } from "./repo";
11
+ import { localDate, localStamp } from "./time";
12
+
13
+ type Parsed = {
14
+ positional: string[];
15
+ flags: Record<string, string | boolean>;
16
+ };
17
+
18
+ function parse(argv: string[]): Parsed {
19
+ const positional: string[] = [];
20
+ const flags: Record<string, string | boolean> = {};
21
+ for (let index = 0; index < argv.length; index += 1) {
22
+ const token = argv[index];
23
+ if (token === undefined) {
24
+ continue;
25
+ }
26
+ if (!token.startsWith("--")) {
27
+ positional.push(token);
28
+ continue;
29
+ }
30
+ const [rawKey, inline] = token.slice(2).split("=", 2);
31
+ const key = (rawKey ?? "").trim();
32
+ const next = argv[index + 1];
33
+ if (inline !== undefined) {
34
+ flags[key] = inline;
35
+ } else if (next !== undefined && !next.startsWith("--")) {
36
+ flags[key] = next;
37
+ index += 1;
38
+ } else {
39
+ flags[key] = true;
40
+ }
41
+ }
42
+ return { positional, flags };
43
+ }
44
+
45
+ function list(value: string | boolean | undefined): string[] {
46
+ if (typeof value !== "string" || !value.trim()) return [];
47
+ return value
48
+ .split(",")
49
+ .map((item) => item.trim())
50
+ .filter(Boolean);
51
+ }
52
+
53
+ function usage(): never {
54
+ console.error(
55
+ [
56
+ "Usage:",
57
+ " beans-memory search <query> [--limit=N] [--type=T] [--json]",
58
+ " beans-memory get <id...> [--json]",
59
+ " beans-memory note --title <title> (--body <text> | --stdin) [--type=T] [--files a,b] [--concepts x,y]",
60
+ " beans-memory recent [--limit=N] [--json]",
61
+ " beans-memory stats [--json]",
62
+ " beans-memory projects [--json]",
63
+ "",
64
+ "Global: --db <path>, --project <name>",
65
+ "Env: MEMORY_DB, MEMORY_PROJECT",
66
+ ].join("\n"),
67
+ );
68
+ process.exit(1);
69
+ }
70
+
71
+ async function readStdin(): Promise<string> {
72
+ const chunks: Buffer[] = [];
73
+ for await (const chunk of Bun.stdin.stream()) {
74
+ chunks.push(Buffer.from(chunk));
75
+ }
76
+ return Buffer.concat(chunks).toString("utf8");
77
+ }
78
+
79
+ const { positional, flags } = parse(process.argv.slice(2));
80
+ const command = positional.shift();
81
+
82
+ if (!command) usage();
83
+
84
+ const dbPath = typeof flags.db === "string" ? flags.db : resolveDbPath();
85
+ const project =
86
+ (typeof flags.project === "string" ? flags.project : "") ||
87
+ process.env.MEMORY_PROJECT ||
88
+ basename(process.cwd());
89
+ const json = flags.json === true;
90
+ const limit = Number(typeof flags.limit === "string" ? flags.limit : 10);
91
+
92
+ const db = openDb(dbPath);
93
+
94
+ function print(value: unknown): void {
95
+ console.log(JSON.stringify(value, null, 2));
96
+ }
97
+
98
+ try {
99
+ if (command === "search") {
100
+ const query = positional.join(" ").trim();
101
+ if (!query) usage();
102
+ const rows = searchObservations(db, {
103
+ project,
104
+ query,
105
+ limit,
106
+ type: typeof flags.type === "string" ? flags.type : undefined,
107
+ });
108
+ if (json) print(rows);
109
+ else if (rows.length === 0) console.log("Tidak ada catatan yang cocok.");
110
+ else
111
+ for (const row of rows) {
112
+ const snippet = row.snip ? ` | ${row.snip.replace(/\s+/g, " ").slice(0, 160)}` : "";
113
+ console.log(`#${row.id} · ${localDate(row.created_at)} · ${row.type} · ${row.title}${snippet}`);
114
+ }
115
+ } else if (command === "get") {
116
+ const ids = positional.map((id) => Number(id)).filter(Number.isFinite);
117
+ if (ids.length === 0) usage();
118
+ const rows = getObservations(db, ids);
119
+ if (json) print(rows);
120
+ else if (rows.length === 0) console.log("Catatan tidak ditemukan.");
121
+ else
122
+ for (const row of rows) {
123
+ console.log(`# ${row.title} (#${row.id})`);
124
+ console.log(`Tanggal: ${localStamp(row.created_at)} · Tipe: ${row.type}`);
125
+ if (row.files.length > 0) console.log(`File: ${row.files.join(", ")}`);
126
+ console.log("");
127
+ console.log(row.body);
128
+ console.log("");
129
+ }
130
+ } else if (command === "note") {
131
+ const title = typeof flags.title === "string" ? flags.title : "";
132
+ if (!title) usage();
133
+ const body = flags.stdin === true ? await readStdin() : typeof flags.body === "string" ? flags.body : "";
134
+ const result = addObservation(db, {
135
+ project,
136
+ title,
137
+ body,
138
+ type: typeof flags.type === "string" ? flags.type : "note",
139
+ files: list(flags.files),
140
+ concepts: list(flags.concepts),
141
+ source: "agent",
142
+ });
143
+ if (json) print(result);
144
+ else
145
+ console.log(
146
+ result.inserted
147
+ ? `Catatan tersimpan sebagai #${result.id}.`
148
+ : `Catatan identik sudah ada sebagai #${result.id}.`,
149
+ );
150
+ } else if (command === "recent") {
151
+ const rows = recentObservations(db, project, limit);
152
+ if (json) print(rows);
153
+ else if (rows.length === 0) console.log("Belum ada catatan.");
154
+ else
155
+ for (const row of rows) {
156
+ console.log(`#${row.id} · ${localDate(row.created_at)} · ${row.type} · ${row.title}`);
157
+ }
158
+ } else if (command === "stats") {
159
+ const value = stats(db, project);
160
+ if (json) print(value);
161
+ else
162
+ console.log(
163
+ `Project ${project}: ${value.observations} catatan, ${value.prompts} prompt, ${value.sessions} sesi. Catatan terakhir: ${
164
+ value.lastObservation ? localStamp(value.lastObservation) : "belum ada"
165
+ }.`,
166
+ );
167
+ } else if (command === "projects") {
168
+ const rows = db
169
+ .query<{ project: string; n: number }, []>(
170
+ "SELECT project, count(*) AS n FROM observations GROUP BY project ORDER BY n DESC",
171
+ )
172
+ .all();
173
+ if (json) print(rows);
174
+ else for (const row of rows) console.log(`${row.project}\t${row.n}`);
175
+ } else {
176
+ usage();
177
+ }
178
+ } catch (error) {
179
+ console.error(error instanceof Error ? error.message : String(error));
180
+ process.exitCode = 1;
181
+ } finally {
182
+ db.close();
183
+ }
package/src/db.ts ADDED
@@ -0,0 +1,136 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync, existsSync, mkdirSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+
6
+ export function resolveDbPath(_directory: string = process.cwd(), home: string = homedir()): string {
7
+ const override = process.env.MEMORY_DB;
8
+ if (override) {
9
+ mkdirSync(dirname(override), { recursive: true, mode: 0o700 });
10
+ return resolve(override);
11
+ }
12
+ const folder = join(home, ".local", "share", "beans-memory");
13
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
14
+ const current = join(folder, "memory.db");
15
+ const legacy = join(home, ".local", "share", "agent-memory", "memory.db");
16
+ if (!existsSync(current) && existsSync(legacy)) {
17
+ try {
18
+ const old = new Database(legacy, { readonly: true });
19
+ old.run("VACUUM INTO ?", [current]);
20
+ old.close();
21
+ } catch {
22
+ // leave the legacy database untouched if the copy fails
23
+ }
24
+ }
25
+ return current;
26
+ }
27
+
28
+ function secure(path: string): void {
29
+ if (path === ":memory:" || path.startsWith("file::memory:")) return;
30
+ try {
31
+ chmodSync(path, 0o600);
32
+ } catch (error) {
33
+ throw error instanceof Error ? error : new Error(String(error));
34
+ }
35
+ for (const file of [`${path}-wal`, `${path}-shm`]) {
36
+ try {
37
+ chmodSync(file, 0o600);
38
+ } catch {
39
+ // sidecar may not exist yet
40
+ }
41
+ }
42
+ }
43
+
44
+ export function openDb(path: string = resolveDbPath()): Database {
45
+ const db = new Database(path, { create: true });
46
+ secure(path);
47
+ db.run("PRAGMA journal_mode = WAL");
48
+ db.run("PRAGMA busy_timeout = 5000");
49
+ db.run("PRAGMA foreign_keys = ON");
50
+ migrate(db);
51
+ secure(path);
52
+ return db;
53
+ }
54
+
55
+ function migrate(db: Database): void {
56
+ db.run(`
57
+ CREATE TABLE IF NOT EXISTS sessions (
58
+ id TEXT PRIMARY KEY,
59
+ project TEXT NOT NULL,
60
+ directory TEXT,
61
+ title TEXT,
62
+ files TEXT NOT NULL DEFAULT '[]',
63
+ started_at TEXT NOT NULL,
64
+ ended_at TEXT
65
+ )
66
+ `);
67
+
68
+ db.run(`
69
+ CREATE TABLE IF NOT EXISTS prompts (
70
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
71
+ session_id TEXT NOT NULL,
72
+ project TEXT NOT NULL,
73
+ body TEXT NOT NULL,
74
+ created_at TEXT NOT NULL,
75
+ created_at_epoch INTEGER NOT NULL
76
+ )
77
+ `);
78
+
79
+ db.run(`
80
+ CREATE TABLE IF NOT EXISTS observations (
81
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
82
+ session_id TEXT,
83
+ project TEXT NOT NULL,
84
+ type TEXT NOT NULL DEFAULT 'note',
85
+ title TEXT NOT NULL,
86
+ body TEXT,
87
+ files TEXT NOT NULL DEFAULT '[]',
88
+ concepts TEXT NOT NULL DEFAULT '[]',
89
+ source TEXT NOT NULL DEFAULT 'agent',
90
+ content_hash TEXT NOT NULL UNIQUE,
91
+ created_at TEXT NOT NULL,
92
+ created_at_epoch INTEGER NOT NULL
93
+ )
94
+ `);
95
+
96
+ db.run(`
97
+ CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
98
+ title,
99
+ body,
100
+ files,
101
+ content='observations',
102
+ content_rowid='id',
103
+ tokenize='unicode61'
104
+ )
105
+ `);
106
+
107
+ db.run(`
108
+ CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
109
+ INSERT INTO observations_fts(rowid, title, body, files)
110
+ VALUES (new.id, new.title, coalesce(new.body, ''), new.files);
111
+ END
112
+ `);
113
+
114
+ db.run(`
115
+ CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
116
+ INSERT INTO observations_fts(observations_fts, rowid, title, body, files)
117
+ VALUES ('delete', old.id, old.title, coalesce(old.body, ''), old.files);
118
+ END
119
+ `);
120
+
121
+ db.run(`
122
+ CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
123
+ INSERT INTO observations_fts(observations_fts, rowid, title, body, files)
124
+ VALUES ('delete', old.id, old.title, coalesce(old.body, ''), old.files);
125
+ INSERT INTO observations_fts(rowid, title, body, files)
126
+ VALUES (new.id, new.title, coalesce(new.body, ''), new.files);
127
+ END
128
+ `);
129
+
130
+ db.run(
131
+ "CREATE INDEX IF NOT EXISTS idx_observations_project_date ON observations(project, created_at_epoch DESC)",
132
+ );
133
+ db.run(
134
+ "CREATE INDEX IF NOT EXISTS idx_prompts_project_date ON prompts(project, created_at_epoch DESC)",
135
+ );
136
+ }
@@ -0,0 +1,125 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { openDb, resolveDbPath } from "./db";
5
+ import { addObservation, stats } from "./repo";
6
+
7
+ const args = process.argv.slice(2);
8
+ function arg(name: string, fallback: string): string {
9
+ const index = args.indexOf(`--${name}`);
10
+ const value = args[index + 1];
11
+ return index >= 0 && value ? value : fallback;
12
+ }
13
+
14
+ const sourcePath = arg("source", join(homedir(), ".claude-mem", "claude-mem.db"));
15
+ const dbPath = arg("db", resolveDbPath());
16
+ const onlyProject = arg("project", "");
17
+ const includeDiscovery = args.includes("--include-discovery");
18
+ const dryRun = args.includes("--dry-run");
19
+
20
+ const KEEP_TYPES = new Set([
21
+ "decision",
22
+ "bugfix",
23
+ "feature",
24
+ "change",
25
+ "refactor",
26
+ "security_note",
27
+ "sensitive",
28
+ "test-coverage",
29
+ ]);
30
+
31
+ function normalizeProject(project: string): string {
32
+ const trimmed = project.trim();
33
+ if (trimmed.startsWith("sinarmas-api/")) return "sinarmas-api";
34
+ return trimmed;
35
+ }
36
+
37
+ function parseArray(value: string | null): string[] {
38
+ if (!value) return [];
39
+ try {
40
+ const parsed = JSON.parse(value);
41
+ return Array.isArray(parsed) ? parsed.map(String) : [];
42
+ } catch {
43
+ return [];
44
+ }
45
+ }
46
+
47
+ const source = new Database(sourcePath, { readonly: true });
48
+ source.run("PRAGMA busy_timeout = 5000");
49
+
50
+ const rows = source
51
+ .query<
52
+ {
53
+ project: string;
54
+ type: string;
55
+ title: string | null;
56
+ subtitle: string | null;
57
+ narrative: string | null;
58
+ facts: string | null;
59
+ concepts: string | null;
60
+ files_modified: string | null;
61
+ created_at: string;
62
+ },
63
+ []
64
+ >(
65
+ `SELECT project, type, title, subtitle, narrative, facts, concepts, files_modified, created_at
66
+ FROM observations ORDER BY created_at`,
67
+ )
68
+ .all();
69
+
70
+ const db = dryRun ? null : openDb(dbPath);
71
+ const perProject = new Map<string, { inserted: number; dup: number; skipped: number }>();
72
+
73
+ for (const row of rows) {
74
+ const project = normalizeProject(row.project);
75
+ if (onlyProject && project !== onlyProject) continue;
76
+
77
+ const entry = perProject.get(project) ?? { inserted: 0, dup: 0, skipped: 0 };
78
+ perProject.set(project, entry);
79
+
80
+ const type = (row.type ?? "note").toLowerCase();
81
+ if (!KEEP_TYPES.has(type) && !(includeDiscovery && type === "discovery")) {
82
+ entry.skipped += 1;
83
+ continue;
84
+ }
85
+
86
+ const facts = parseArray(row.facts);
87
+ const body = [
88
+ row.narrative ?? "",
89
+ facts.length > 0 ? facts.map((fact) => `- ${fact}`).join("\n") : "",
90
+ ]
91
+ .filter(Boolean)
92
+ .join("\n\n")
93
+ .trim();
94
+
95
+ if (dryRun || !db) {
96
+ entry.inserted += 1;
97
+ continue;
98
+ }
99
+
100
+ const result = addObservation(db, {
101
+ project,
102
+ type,
103
+ title: row.title ?? row.subtitle ?? "Tanpa judul",
104
+ body,
105
+ files: parseArray(row.files_modified),
106
+ concepts: parseArray(row.concepts),
107
+ source: "import",
108
+ createdAt: row.created_at,
109
+ });
110
+ if (result.inserted) entry.inserted += 1;
111
+ else entry.dup += 1;
112
+ }
113
+
114
+ source.close();
115
+
116
+ const report: Record<string, unknown> = { db: dbPath, dryRun, totalRows: rows.length, projects: {} };
117
+ for (const [project, value] of [...perProject.entries()].sort((a, b) => b[1].inserted - a[1].inserted)) {
118
+ (report.projects as Record<string, unknown>)[project] = {
119
+ ...value,
120
+ stats: db ? stats(db, project) : null,
121
+ };
122
+ }
123
+
124
+ console.log(JSON.stringify(report, null, 2));
125
+ if (db) db.close();
@@ -0,0 +1,162 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { openDb, resolveDbPath } from "./db";
5
+ import { addObservation, stats } from "./repo";
6
+
7
+ const args = process.argv.slice(2);
8
+ function arg(name: string, fallback: string): string {
9
+ const index = args.indexOf(`--${name}`);
10
+ const value = args[index + 1];
11
+ return index >= 0 && value ? value : fallback;
12
+ }
13
+
14
+ const sourcePath = arg("source", join(homedir(), ".claude-mem", "claude-mem.db"));
15
+ const dbPath = arg("db", resolveDbPath());
16
+ const dryRun = args.includes("--dry-run");
17
+
18
+ function normalizeProject(project: string): string {
19
+ const trimmed = project.trim();
20
+ if (trimmed.startsWith("sinarmas-api/")) return "sinarmas-api";
21
+ return trimmed;
22
+ }
23
+
24
+ function clip(value: string | null, limit: number): string {
25
+ const text = (value ?? "").trim();
26
+ if (!text) return "";
27
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
28
+ }
29
+
30
+ const source = new Database(sourcePath, { readonly: true });
31
+ source.run("PRAGMA busy_timeout = 5000");
32
+ const db = dryRun ? null : openDb(dbPath);
33
+
34
+ const summaries = source
35
+ .query<
36
+ {
37
+ project: string;
38
+ request: string | null;
39
+ investigated: string | null;
40
+ learned: string | null;
41
+ completed: string | null;
42
+ next_steps: string | null;
43
+ created_at: string;
44
+ },
45
+ []
46
+ >(
47
+ `SELECT project, request, investigated, learned, completed, next_steps, created_at
48
+ FROM session_summaries ORDER BY created_at`,
49
+ )
50
+ .all();
51
+
52
+ let summaryInserted = 0;
53
+ let summaryDup = 0;
54
+
55
+ for (const row of summaries) {
56
+ const project = normalizeProject(row.project);
57
+ const title = clip(row.request, 140) || "Ringkasan sesi";
58
+ const body = [
59
+ clip(row.request, 1200) ? `Request: ${clip(row.request, 1200)}` : "",
60
+ clip(row.investigated, 1200) ? `Investigasi: ${clip(row.investigated, 1200)}` : "",
61
+ clip(row.learned, 1500) ? `Dipelajari: ${clip(row.learned, 1500)}` : "",
62
+ clip(row.completed, 1200) ? `Selesai: ${clip(row.completed, 1200)}` : "",
63
+ clip(row.next_steps, 600) ? `Berikutnya: ${clip(row.next_steps, 600)}` : "",
64
+ ]
65
+ .filter(Boolean)
66
+ .join("\n\n");
67
+
68
+ if (!body) continue;
69
+ if (dryRun || !db) {
70
+ summaryInserted += 1;
71
+ continue;
72
+ }
73
+
74
+ const result = addObservation(db, {
75
+ project,
76
+ type: "session_summary",
77
+ title,
78
+ body,
79
+ source: "import_summary",
80
+ createdAt: row.created_at,
81
+ });
82
+ if (result.inserted) summaryInserted += 1;
83
+ else summaryDup += 1;
84
+ }
85
+
86
+ const prompts = source
87
+ .query<
88
+ {
89
+ project: string;
90
+ session_id: string;
91
+ body: string;
92
+ created_at: string;
93
+ created_at_epoch: number;
94
+ },
95
+ []
96
+ >(
97
+ `SELECT coalesce(s.project, 'unknown') AS project,
98
+ p.content_session_id AS session_id,
99
+ p.prompt_text AS body,
100
+ p.created_at,
101
+ p.created_at_epoch
102
+ FROM user_prompts p
103
+ LEFT JOIN sdk_sessions s ON s.id = p.session_db_id
104
+ ORDER BY p.created_at_epoch`,
105
+ )
106
+ .all();
107
+
108
+ let promptInserted = 0;
109
+ let promptDup = 0;
110
+
111
+ for (const row of prompts) {
112
+ const project = normalizeProject(row.project);
113
+ const body = row.body.trim().slice(0, 8000);
114
+ if (!body) continue;
115
+
116
+ if (dryRun || !db) {
117
+ promptInserted += 1;
118
+ continue;
119
+ }
120
+
121
+ const exists = db
122
+ .query<{ id: number }, [string, number, string]>(
123
+ "SELECT id FROM prompts WHERE session_id = ? AND created_at_epoch = ? AND body = ? LIMIT 1",
124
+ )
125
+ .get(row.session_id, row.created_at_epoch, body);
126
+ if (exists) {
127
+ promptDup += 1;
128
+ continue;
129
+ }
130
+
131
+ db.run(
132
+ "INSERT INTO prompts (session_id, project, body, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?)",
133
+ [row.session_id, project, body, row.created_at, row.created_at_epoch],
134
+ );
135
+ promptInserted += 1;
136
+ }
137
+
138
+ source.close();
139
+
140
+ const projectStats: Record<string, unknown> = {};
141
+ if (db) {
142
+ const projects = db
143
+ .query<{ project: string }, []>("SELECT DISTINCT project FROM observations ORDER BY project")
144
+ .all();
145
+ for (const { project } of projects) projectStats[project] = stats(db, project);
146
+ }
147
+
148
+ console.log(
149
+ JSON.stringify(
150
+ {
151
+ db: dbPath,
152
+ dryRun,
153
+ summaries: { total: summaries.length, inserted: summaryInserted, dup: summaryDup },
154
+ prompts: { total: prompts.length, inserted: promptInserted, dup: promptDup },
155
+ projects: projectStats,
156
+ },
157
+ null,
158
+ 2,
159
+ ),
160
+ );
161
+
162
+ if (db) db.close();