mixgram 1.0.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.
Files changed (40) hide show
  1. package/.mixgram/index.db +0 -0
  2. package/.mixgram/test-esm.db +0 -0
  3. package/.mixgram/test-index.db +0 -0
  4. package/.mixgram/test-stage1.db +0 -0
  5. package/README.md +335 -0
  6. package/bin/mixgram.js +309 -0
  7. package/index.js +9 -0
  8. package/package.json +51 -0
  9. package/projects/castlebravo/memory/decisions/decision--architecture/sqlite-derived-index.md +17 -0
  10. package/projects/test/memory/decisions/decision--architecture/sqlite-derived-index.md +17 -0
  11. package/spec/fixtures/realistic-content.js +97 -0
  12. package/spec/reporter.js +127 -0
  13. package/spec/run-tests-runner.js +40 -0
  14. package/spec/run-tests.js +160 -0
  15. package/spec/scenarios/scenarios.js +520 -0
  16. package/spec/sdd.md +1002 -0
  17. package/spec/tdd.md +1237 -0
  18. package/src/config.js +56 -0
  19. package/src/core/documents/documents.js +207 -0
  20. package/src/core/embeddings/embedder.js +58 -0
  21. package/src/core/embeddings/queue.js +118 -0
  22. package/src/core/embeddings/vectorStore.js +127 -0
  23. package/src/core/embeddings/worker.js +27 -0
  24. package/src/core/indexing/indexer.js +131 -0
  25. package/src/core/indexing/parser.js +78 -0
  26. package/src/core/indexing/reindex.js +101 -0
  27. package/src/core/prompts/prompts.js +15 -0
  28. package/src/core/search/search.js +223 -0
  29. package/src/core/sessions/sessions.js +27 -0
  30. package/src/db/migrations/001_initial.sql +86 -0
  31. package/src/db/sqlite.js +39 -0
  32. package/src/fs/paths.js +79 -0
  33. package/src/fs/watcher.js +49 -0
  34. package/src/mcp/cli-adapter.js +118 -0
  35. package/src/mcp/server.js +47 -0
  36. package/src/mcp/tool-registry.js +138 -0
  37. package/src/mcp/tools.js +159 -0
  38. package/src/utils/hash.js +6 -0
  39. package/src/utils/ids.js +22 -0
  40. package/src/utils/markdown.js +49 -0
@@ -0,0 +1,39 @@
1
+ import Database from 'better-sqlite3';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ let dbInstance = null;
9
+
10
+ export function getDb(config) {
11
+ if (dbInstance) return dbInstance;
12
+ const dbPath = config.sqlitePath;
13
+ const dir = path.dirname(dbPath);
14
+ if (!fs.existsSync(dir)) {
15
+ fs.mkdirSync(dir, { recursive: true });
16
+ }
17
+ dbInstance = new Database(dbPath);
18
+ dbInstance.pragma('journal_mode = WAL');
19
+ runMigrations(dbInstance);
20
+ return dbInstance;
21
+ }
22
+
23
+ function runMigrations(db) {
24
+ const migrationsDir = path.join(__dirname, 'migrations');
25
+ const files = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.sql')).sort();
26
+ for (const file of files) {
27
+ const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
28
+ db.exec(sql);
29
+ }
30
+ }
31
+
32
+ export function closeDb() {
33
+ if (dbInstance) {
34
+ dbInstance.close();
35
+ dbInstance = null;
36
+ }
37
+ }
38
+
39
+ export { runMigrations };
@@ -0,0 +1,79 @@
1
+ import path from 'path';
2
+ import fs from 'fs';
3
+
4
+ const TYPE_TO_DIR = {
5
+ architecture: 'architecture',
6
+ decision: 'decisions',
7
+ decisions: 'decisions',
8
+ bug: 'bugs',
9
+ bugs: 'bugs',
10
+ learning: 'learnings',
11
+ learnings: 'learnings',
12
+ discovery: 'discoveries',
13
+ discoveries: 'discoveries',
14
+ pattern: 'patterns',
15
+ patterns: 'patterns',
16
+ reference: 'reference',
17
+ session_summary: 'sessions',
18
+ sessions: 'sessions',
19
+ prompt: 'prompts',
20
+ prompts: 'prompts',
21
+ generated_note: 'generated',
22
+ generated: 'generated'
23
+ };
24
+
25
+ function slugFromTopicKey(topicKey) {
26
+ if (!topicKey || typeof topicKey !== 'string') return 'note';
27
+ return topicKey
28
+ .replace(/\//g, '-')
29
+ .replace(/[^a-z0-9-]/gi, '-')
30
+ .replace(/-+/g, '-')
31
+ .toLowerCase()
32
+ .replace(/^-|-$/g, '') || 'note';
33
+ }
34
+
35
+ function documentPath(config, { scope, project, type, topic_key, id }) {
36
+ const typeDir = TYPE_TO_DIR[type] || 'generated';
37
+ const slug = slugFromTopicKey(topic_key);
38
+ const baseName = `${type}--${slug}.md`;
39
+
40
+ if (scope === 'home') {
41
+ const root = config.homeMemoryRoot;
42
+ return path.join(root, typeDir, baseName);
43
+ }
44
+
45
+ if (scope === 'project' && project) {
46
+ const root = path.join(config.projectsRoot, project, 'memory');
47
+ return path.join(root, typeDir, baseName);
48
+ }
49
+
50
+ const root = config.projectsRoot;
51
+ return path.join(root, '_default', 'memory', typeDir, baseName);
52
+ }
53
+
54
+ function ensureDir(filePath) {
55
+ const dir = path.dirname(filePath);
56
+ if (!fs.existsSync(dir)) {
57
+ fs.mkdirSync(dir, { recursive: true });
58
+ }
59
+ }
60
+
61
+ function mixgramDir(config) {
62
+ return path.dirname(config.sqlitePath);
63
+ }
64
+
65
+ function ensureMixgramDir(config) {
66
+ const dir = mixgramDir(config);
67
+ if (!fs.existsSync(dir)) {
68
+ fs.mkdirSync(dir, { recursive: true });
69
+ }
70
+ }
71
+
72
+ export {
73
+ documentPath,
74
+ ensureDir,
75
+ mixgramDir,
76
+ ensureMixgramDir,
77
+ TYPE_TO_DIR,
78
+ slugFromTopicKey
79
+ };
@@ -0,0 +1,49 @@
1
+ import path from 'path';
2
+ import chokidar from 'chokidar';
3
+ import fs from 'fs';
4
+ import { indexDocument, removeDocumentFromIndex } from '../core/indexing/indexer.js';
5
+ import { getDocumentIdByPath } from '../core/indexing/reindex.js';
6
+
7
+ /**
8
+ * Start watching home and projects memory roots for .md changes.
9
+ * On add/change: index the file. On unlink: remove from index by path.
10
+ * @param {object} config - resolved config
11
+ * @returns {import('chokidar').FSWatcher} watcher instance (call .close() to stop)
12
+ */
13
+ function startWatcher(config) {
14
+ const homeRoot = config.homeMemoryRoot;
15
+ const projectsRoot = config.projectsRoot;
16
+ const patterns = [];
17
+ if (homeRoot) patterns.push(path.join(homeRoot, '**/*.md'));
18
+ if (projectsRoot) patterns.push(path.join(projectsRoot, '**/memory/**/*.md'));
19
+ if (patterns.length === 0) return null;
20
+
21
+ const watcher = chokidar.watch(patterns, {
22
+ ignoreInitial: true,
23
+ awaitWriteFinish: { stabilityThreshold: 200 }
24
+ });
25
+
26
+ watcher
27
+ .on('add', (filePath) => {
28
+ try {
29
+ const raw = fs.readFileSync(filePath, 'utf8');
30
+ const stat = fs.statSync(filePath);
31
+ indexDocument(config, filePath, raw, stat.mtimeMs);
32
+ } catch (_) {}
33
+ })
34
+ .on('change', (filePath) => {
35
+ try {
36
+ const raw = fs.readFileSync(filePath, 'utf8');
37
+ const stat = fs.statSync(filePath);
38
+ indexDocument(config, filePath, raw, stat.mtimeMs);
39
+ } catch (_) {}
40
+ })
41
+ .on('unlink', (filePath) => {
42
+ const id = getDocumentIdByPath(config, filePath);
43
+ if (id) removeDocumentFromIndex(config, id);
44
+ });
45
+
46
+ return watcher;
47
+ }
48
+
49
+ export { startWatcher };
@@ -0,0 +1,118 @@
1
+ /**
2
+ * CLI adapter: parse argv into tool args using the tool registry's inputSchema,
3
+ * and format help from descriptions/schemas. No duplicate tool definitions.
4
+ */
5
+ import { getToolDefinitions, getToolByName } from './tool-registry.js';
6
+
7
+ /** Unwrap ZodOptional/ZodNullable to get inner type for CLI coercion and help. */
8
+ function unwrapZod(schema) {
9
+ if (!schema || typeof schema !== 'object') return null;
10
+ let s = schema;
11
+ const optional = (s) => s?.constructor?.name === 'ZodOptional' || s?.constructor?.name === 'ZodNullable';
12
+ while (s && optional(s)) {
13
+ s = s._def?.innerType ?? s.unwrap?.() ?? null;
14
+ }
15
+ return s;
16
+ }
17
+
18
+ /** Return per-param meta: type ('string'|'number'|'boolean'|'array'), optional (boolean). */
19
+ function getParamMeta(inputSchema) {
20
+ const meta = {};
21
+ for (const key of Object.keys(inputSchema)) {
22
+ const schema = inputSchema[key];
23
+ const unwrapped = unwrapZod(schema);
24
+ const optional = !unwrapped || (schema?.constructor?.name === 'ZodOptional' || schema?.constructor?.name === 'ZodNullable');
25
+ let type = 'string';
26
+ if (unwrapped) {
27
+ const name = unwrapped.constructor?.name ?? '';
28
+ if (name === 'ZodNumber') type = 'number';
29
+ else if (name === 'ZodBoolean') type = 'boolean';
30
+ else if (name === 'ZodArray') type = 'array';
31
+ }
32
+ meta[key] = { type, optional };
33
+ }
34
+ return meta;
35
+ }
36
+
37
+ /**
38
+ * Parse argv (e.g. ['--query', 'foo', '--limit', '5', '--hardDelete']) into an object
39
+ * matching the tool's inputSchema. Supports --key value, --flag (boolean true), --no-flag (boolean false),
40
+ * and repeated --key v1 --key v2 for arrays.
41
+ */
42
+ function parseToolArgs(toolDef, argv) {
43
+ const meta = getParamMeta(toolDef.inputSchema);
44
+ const result = {};
45
+ const args = [...argv];
46
+
47
+ for (const key of Object.keys(meta)) {
48
+ if (meta[key].type === 'boolean') {
49
+ result[key] = false;
50
+ } else if (meta[key].type === 'array') {
51
+ result[key] = [];
52
+ }
53
+ }
54
+
55
+ for (let i = 0; i < args.length; i++) {
56
+ const a = args[i];
57
+ if (a === '--help' || a === '-h') continue;
58
+ if (!a.startsWith('--')) continue;
59
+ const isNegated = a.startsWith('--no-');
60
+ const paramKey = isNegated ? a.slice(5) : a.slice(2);
61
+ if (!Object.prototype.hasOwnProperty.call(meta, paramKey)) continue;
62
+ const { type } = meta[paramKey];
63
+ if (type === 'boolean') {
64
+ result[paramKey] = !isNegated;
65
+ } else if (type === 'array') {
66
+ const val = args[i + 1];
67
+ if (val !== undefined && !val.startsWith('--')) {
68
+ result[paramKey].push(val);
69
+ i++;
70
+ }
71
+ } else {
72
+ const val = args[i + 1];
73
+ if (val !== undefined && !val.startsWith('--')) {
74
+ if (type === 'number') {
75
+ const n = Number(val);
76
+ result[paramKey] = Number.isNaN(n) ? val : n;
77
+ } else {
78
+ result[paramKey] = val;
79
+ }
80
+ i++;
81
+ }
82
+ }
83
+ }
84
+
85
+ for (const key of Object.keys(meta)) {
86
+ if (result[key] === undefined && meta[key].optional) {
87
+ if (meta[key].type === 'array') result[key] = [];
88
+ else if (meta[key].type === 'boolean') result[key] = false;
89
+ }
90
+ }
91
+
92
+ return result;
93
+ }
94
+
95
+ /** Format help text for a single tool (description + params). */
96
+ function formatToolHelp(toolDef) {
97
+ const meta = getParamMeta(toolDef.inputSchema);
98
+ const lines = [toolDef.description, '', 'Options:'];
99
+ for (const [key, { type, optional }] of Object.entries(meta)) {
100
+ const opt = optional ? ' (optional)' : '';
101
+ if (type === 'boolean') {
102
+ lines.push(` --${key} boolean${opt}`);
103
+ lines.push(` --no-${key}`);
104
+ } else if (type === 'array') {
105
+ lines.push(` --${key} <value> repeat for multiple${opt}`);
106
+ } else {
107
+ lines.push(` --${key} <${type}>${opt}`);
108
+ }
109
+ }
110
+ return lines.join('\n');
111
+ }
112
+
113
+ /** List tool names for main help. */
114
+ function listToolNames() {
115
+ return getToolDefinitions().map((t) => t.name);
116
+ }
117
+
118
+ export { getToolDefinitions, getToolByName, getParamMeta, parseToolArgs, formatToolHelp, listToolNames };
@@ -0,0 +1,47 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { loadConfig } from '../config.js';
4
+ import { createToolHandlers } from './tools.js';
5
+ import { getToolDefinitions } from './tool-registry.js';
6
+
7
+ function createServer(configOverrides = {}, baseDir = null) {
8
+ const config = loadConfig(configOverrides, baseDir);
9
+ const mcpServer = new McpServer(
10
+ { name: 'mixgram', version: '1.0.0' },
11
+ { capabilities: { tools: { listChanged: true } } }
12
+ );
13
+
14
+ const handlers = createToolHandlers(config);
15
+ const definitions = getToolDefinitions();
16
+
17
+ for (const def of definitions) {
18
+ const handler = handlers[def.name];
19
+ if (!handler) continue;
20
+ mcpServer.registerTool(def.name, {
21
+ description: def.description,
22
+ inputSchema: def.inputSchema
23
+ }, async (args) => handler(args));
24
+ }
25
+
26
+ return { mcpServer, config };
27
+ }
28
+
29
+ async function run(configOverrides = {}, baseDir = null) {
30
+ const { mcpServer, config } = createServer(configOverrides, baseDir);
31
+ if (config.indexing?.reindexOnStartup) {
32
+ const { fullReindex } = await import('../core/indexing/reindex.js');
33
+ fullReindex(config);
34
+ }
35
+ if (config.watch) {
36
+ const { startWatcher } = await import('../fs/watcher.js');
37
+ startWatcher(config);
38
+ }
39
+ if (config.embeddings?.enabled) {
40
+ const { startWorker } = await import('../core/embeddings/worker.js');
41
+ startWorker(config);
42
+ }
43
+ const transport = new StdioServerTransport();
44
+ await mcpServer.connect(transport);
45
+ }
46
+
47
+ export { createServer, run };
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Shared MCP tool registry: single source of truth for name, description, and inputSchema.
3
+ * Used by the MCP server (registration) and CLI (subcommands and help).
4
+ */
5
+ import { z } from 'zod';
6
+
7
+ const optionalString = z.string().optional();
8
+ const optionalNumber = z.number().optional();
9
+ const optionalBoolean = z.boolean().optional();
10
+ const optionalArray = z.array(z.string()).optional();
11
+
12
+ /** Tool definitions: name, description, inputSchema (Zod shape). Handlers live in tools.js. */
13
+ const TOOL_DEFINITIONS = [
14
+ {
15
+ name: 'mem_save',
16
+ description: 'Save a memory document (create or update by topic_key)',
17
+ inputSchema: {
18
+ title: optionalString,
19
+ type: optionalString,
20
+ scope: optionalString,
21
+ project: optionalString.nullable(),
22
+ topic_key: optionalString.nullable(),
23
+ content: optionalString,
24
+ session_id: optionalString.nullable(),
25
+ id: optionalString.nullable(),
26
+ tags: optionalArray
27
+ }
28
+ },
29
+ {
30
+ name: 'mem_update',
31
+ description: 'Update an existing document by id',
32
+ inputSchema: {
33
+ id: z.string(),
34
+ title: optionalString,
35
+ content: optionalString,
36
+ tags: optionalArray
37
+ }
38
+ },
39
+ {
40
+ name: 'mem_delete',
41
+ description: 'Soft or hard delete a document by id',
42
+ inputSchema: {
43
+ id: z.string(),
44
+ hardDelete: optionalBoolean
45
+ }
46
+ },
47
+ {
48
+ name: 'mem_suggest_topic_key',
49
+ description: 'Suggest a stable topic key from title/content/type',
50
+ inputSchema: {
51
+ title: optionalString,
52
+ content: optionalString,
53
+ type: optionalString
54
+ }
55
+ },
56
+ {
57
+ name: 'mem_search',
58
+ description: 'Full-text search over memory (project-only, home-only, or merged)',
59
+ inputSchema: {
60
+ query: z.string(),
61
+ scope_mode: optionalString,
62
+ project: optionalString.nullable(),
63
+ limit: optionalNumber
64
+ }
65
+ },
66
+ {
67
+ name: 'mem_context',
68
+ description: 'Get contextual memory for a project (recent or search-based)',
69
+ inputSchema: {
70
+ query: optionalString,
71
+ project: optionalString.nullable(),
72
+ limit: optionalNumber
73
+ }
74
+ },
75
+ {
76
+ name: 'mem_get_observation',
77
+ description: 'Get full document content by id',
78
+ inputSchema: { id: z.string() }
79
+ },
80
+ {
81
+ name: 'mem_stats',
82
+ description: 'Get memory statistics (documents, sessions, prompts)',
83
+ inputSchema: {}
84
+ },
85
+ {
86
+ name: 'mem_timeline',
87
+ description: 'Get before/focus/after observations for an observation in its session',
88
+ inputSchema: { observation_id: z.string() }
89
+ },
90
+ {
91
+ name: 'mem_session_start',
92
+ description: 'Start a new session',
93
+ inputSchema: {
94
+ session_id: optionalString.nullable(),
95
+ project: optionalString.nullable(),
96
+ directory: optionalString.nullable()
97
+ }
98
+ },
99
+ {
100
+ name: 'mem_session_end',
101
+ description: 'End a session',
102
+ inputSchema: { session_id: z.string() }
103
+ },
104
+ {
105
+ name: 'mem_session_summary',
106
+ description: 'Persist a session summary as durable memory',
107
+ inputSchema: {
108
+ session_id: z.string(),
109
+ content: optionalString,
110
+ summary: optionalString,
111
+ title: optionalString
112
+ }
113
+ },
114
+ {
115
+ name: 'mem_save_prompt',
116
+ description: 'Store a prompt for a session (no Markdown file by default)',
117
+ inputSchema: {
118
+ session_id: z.string(),
119
+ project: optionalString.nullable(),
120
+ content: optionalString
121
+ }
122
+ },
123
+ {
124
+ name: 'mem_reindex',
125
+ description: 'Run full or incremental reindex from Markdown files',
126
+ inputSchema: { full: optionalBoolean }
127
+ }
128
+ ];
129
+
130
+ function getToolDefinitions() {
131
+ return TOOL_DEFINITIONS;
132
+ }
133
+
134
+ function getToolByName(name) {
135
+ return TOOL_DEFINITIONS.find((t) => t.name === name) ?? null;
136
+ }
137
+
138
+ export { getToolDefinitions, getToolByName, TOOL_DEFINITIONS };
@@ -0,0 +1,159 @@
1
+ import { slugFromTopicKey } from '../fs/paths.js';
2
+ import { saveDocument, updateDocument, deleteDocument, getObservation, getObservationsBySession } from '../core/documents/documents.js';
3
+ import { search, getRecentContext } from '../core/search/search.js';
4
+ import { getDb } from '../db/sqlite.js';
5
+ import { startSession, endSession, getSession } from '../core/sessions/sessions.js';
6
+ import { savePrompt } from '../core/prompts/prompts.js';
7
+ import { fullReindex, incrementalReindex } from '../core/indexing/reindex.js';
8
+
9
+ const DOC_TYPES = ['architecture', 'decision', 'bug', 'learning', 'discovery', 'pattern', 'reference', 'session_summary', 'prompt', 'generated_note'];
10
+
11
+ function suggestTopicKey(title, content = '', type = 'generated_note') {
12
+ const category = type && DOC_TYPES.includes(type) ? type : 'generated_note';
13
+ const slug = slugFromTopicKey(title || content.slice(0, 80).trim());
14
+ return `${category}/${slug}`;
15
+ }
16
+
17
+ function createToolHandlers(config) {
18
+ return {
19
+ mem_save: async (args) => {
20
+ const result = saveDocument(config, {
21
+ title: args.title,
22
+ type: args.type || 'generated_note',
23
+ scope: args.scope || 'project',
24
+ project: args.project ?? null,
25
+ topic_key: args.topic_key ?? null,
26
+ content: args.content ?? '',
27
+ session_id: args.session_id ?? null,
28
+ id: args.id ?? null,
29
+ tags: args.tags ?? []
30
+ });
31
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, id: result.id, path: result.path, created: result.created }) }] };
32
+ },
33
+
34
+ mem_update: async (args) => {
35
+ const result = updateDocument(config, {
36
+ id: args.id,
37
+ title: args.title,
38
+ content: args.content,
39
+ tags: args.tags
40
+ });
41
+ if (!result) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'Document not found' }) }], isError: true };
42
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, id: result.id }) }] };
43
+ },
44
+
45
+ mem_delete: async (args) => {
46
+ const ok = deleteDocument(config, args.id, { hardDelete: args.hardDelete === true });
47
+ if (!ok) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'Document not found' }) }], isError: true };
48
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true }) }] };
49
+ },
50
+
51
+ mem_suggest_topic_key: async (args) => {
52
+ const topicKey = suggestTopicKey(args.title, args.content, args.type);
53
+ return { content: [{ type: 'text', text: JSON.stringify({ topic_key: topicKey }) }] };
54
+ },
55
+
56
+ mem_search: async (args) => {
57
+ const results = await search(config, {
58
+ query: args.query,
59
+ scopeMode: args.scope_mode || config.search?.defaultScopeMode || 'merged',
60
+ project: args.project ?? null,
61
+ limit: args.limit ?? config.search?.defaultLimit ?? 10
62
+ });
63
+ return { content: [{ type: 'text', text: JSON.stringify({ results }) }] };
64
+ },
65
+
66
+ mem_context: async (args) => {
67
+ const q = (args.query || '').trim();
68
+ const results = q && q !== '*'
69
+ ? await search(config, {
70
+ query: q,
71
+ scopeMode: 'merged',
72
+ project: args.project ?? null,
73
+ limit: args.limit ?? config.search?.defaultLimit ?? 10
74
+ })
75
+ : getRecentContext(config, { project: args.project ?? null, limit: args.limit ?? config.search?.defaultLimit ?? 10 });
76
+ const context = results.map((r) => `[${r.title}] ${r.snippet}`).join('\n\n');
77
+ return { content: [{ type: 'text', text: context || '(no context)' }] };
78
+ },
79
+
80
+ mem_get_observation: async (args) => {
81
+ const obs = getObservation(config, args.id);
82
+ if (!obs) return { content: [{ type: 'text', text: JSON.stringify({ error: 'Observation not found' }) }], isError: true };
83
+ return { content: [{ type: 'text', text: JSON.stringify(obs) }] };
84
+ },
85
+
86
+ mem_stats: async () => {
87
+ const db = getDb(config);
88
+ const docs = db.prepare("SELECT COUNT(*) AS c FROM documents WHERE deleted_at IS NULL").get();
89
+ const sessions = db.prepare('SELECT COUNT(*) AS c FROM sessions').get();
90
+ const prompts = db.prepare('SELECT COUNT(*) AS c FROM prompts').get();
91
+ return {
92
+ content: [{
93
+ type: 'text',
94
+ text: JSON.stringify({
95
+ documents: docs?.c ?? 0,
96
+ sessions: sessions?.c ?? 0,
97
+ prompts: prompts?.c ?? 0,
98
+ embeddings_enabled: config.embeddings?.enabled === true
99
+ })
100
+ }]
101
+ };
102
+ },
103
+
104
+ mem_timeline: async (args) => {
105
+ const focusId = args.observation_id;
106
+ const obs = getObservation(config, focusId);
107
+ if (!obs) return { content: [{ type: 'text', text: JSON.stringify({ error: 'Observation not found' }) }], isError: true };
108
+ const sessionId = obs.session_id;
109
+ if (!sessionId) {
110
+ return { content: [{ type: 'text', text: JSON.stringify({ before: [], focus: obs, after: [] }) }] };
111
+ }
112
+ const ids = getObservationsBySession(config, sessionId);
113
+ const focusIndex = ids.indexOf(focusId);
114
+ const before = focusIndex <= 0 ? [] : ids.slice(0, focusIndex).map((id) => getObservation(config, id)).filter(Boolean);
115
+ const after = focusIndex < 0 || focusIndex >= ids.length - 1 ? [] : ids.slice(focusIndex + 1).map((id) => getObservation(config, id)).filter(Boolean);
116
+ return { content: [{ type: 'text', text: JSON.stringify({ before, focus: obs, after }) }] };
117
+ },
118
+
119
+ mem_session_start: async (args) => {
120
+ const result = startSession(config, { id: args.session_id ?? null, project: args.project ?? '', directory: args.directory ?? null });
121
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, session_id: result.id, started_at: result.started_at }) }] };
122
+ },
123
+
124
+ mem_session_end: async (args) => {
125
+ const result = endSession(config, args.session_id);
126
+ return { content: [{ type: 'text', text: JSON.stringify({ success: result.success, ended_at: result.ended_at }) }] };
127
+ },
128
+
129
+ mem_session_summary: async (args) => {
130
+ const session = getSession(config, args.session_id);
131
+ if (!session) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'Session not found' }) }], isError: true };
132
+ const summaryContent = args.content ?? args.summary ?? '';
133
+ saveDocument(config, {
134
+ title: args.title ?? `Session summary ${args.session_id}`,
135
+ type: 'session_summary',
136
+ scope: 'project',
137
+ project: session.project || null,
138
+ topic_key: `sessions/summary-${args.session_id}`,
139
+ content: summaryContent,
140
+ session_id: args.session_id
141
+ });
142
+ getDb(config).prepare('UPDATE sessions SET summary = ? WHERE id = ?').run(summaryContent.slice(0, 2000), args.session_id);
143
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true }) }] };
144
+ },
145
+
146
+ mem_save_prompt: async (args) => {
147
+ const result = savePrompt(config, { session_id: args.session_id, project: args.project ?? null, content: args.content ?? '' });
148
+ return { content: [{ type: 'text', text: JSON.stringify({ success: true, prompt_id: result.id }) }] };
149
+ },
150
+
151
+ mem_reindex: async (args) => {
152
+ const full = args.full === true;
153
+ const result = full ? fullReindex(config) : incrementalReindex(config);
154
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
155
+ }
156
+ };
157
+ }
158
+
159
+ export { suggestTopicKey, createToolHandlers };
@@ -0,0 +1,6 @@
1
+ import crypto from 'crypto';
2
+
3
+ export function contentHash(content) {
4
+ if (typeof content !== 'string') content = String(content);
5
+ return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
6
+ }
@@ -0,0 +1,22 @@
1
+ import crypto from 'crypto';
2
+
3
+ export function generateId(prefix = 'obs') {
4
+ const hex = crypto.randomBytes(12).toString('hex');
5
+ return `${prefix}_${hex}`;
6
+ }
7
+
8
+ export function observationId() {
9
+ return generateId('obs');
10
+ }
11
+
12
+ export function sessionId() {
13
+ return generateId('sess');
14
+ }
15
+
16
+ export function chunkId(documentId, index) {
17
+ return `${documentId}_chunk_${index}`;
18
+ }
19
+
20
+ export function promptId() {
21
+ return generateId('prompt');
22
+ }