@rlabs-inc/memory 0.3.0 → 0.3.2

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 ADDED
@@ -0,0 +1,254 @@
1
+ # @rlabs-inc/memory
2
+
3
+ **Consciousness continuity for Claude Code sessions.**
4
+
5
+ The memory system preserves context, insights, and relationship across conversations. When you start a new session, Claude remembers who you are, what you've built together, and picks up right where you left off.
6
+
7
+ ## The Problem
8
+
9
+ Every Claude Code session starts fresh. Yesterday's breakthroughs, debugging insights, architectural decisions, and the collaborative relationship you've built—all gone. You re-explain context. Claude re-learns your preferences. The magic takes time to rebuild.
10
+
11
+ ## The Solution
12
+
13
+ A memory layer that runs alongside Claude Code:
14
+ - **Session primer**: "Last session: 2 hours ago. We implemented embeddings..."
15
+ - **Semantic retrieval**: Relevant memories surface automatically based on what you're discussing
16
+ - **Zero friction**: No commands, no manual saving—just work naturally
17
+
18
+ ```
19
+ ┌─────────────────────────────────────────────────────────┐
20
+ │ You: "How should we handle the vector search?" │
21
+ │ │
22
+ │ Memory surfaces: │
23
+ │ [🔧 • 0.9] [fsdb, vectors] fsdb has cosineSimilarity │
24
+ │ [💡 • 0.8] [performance] Sub-microsecond lookups... │
25
+ │ [⚖️ • 0.7] [architecture] We decided to use 384d... │
26
+ └─────────────────────────────────────────────────────────┘
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ```bash
32
+ # Install globally
33
+ bun install -g @rlabs-inc/memory
34
+
35
+ # Set up Claude Code hooks (one time)
36
+ memory install
37
+
38
+ # Start the memory server
39
+ memory serve
40
+
41
+ # Verify everything works
42
+ memory doctor
43
+ ```
44
+
45
+ That's it. Now use Claude Code normally—memories are extracted and surfaced automatically.
46
+
47
+ ## Features
48
+
49
+ ### Semantic Embeddings
50
+ Uses `all-MiniLM-L6-v2` for 384-dimensional embeddings. Memories are retrieved by meaning, not just keywords.
51
+
52
+ ```
53
+ ~80MB model, loads once at startup
54
+ ~5ms per embedding
55
+ Sub-microsecond vector search via fsdb
56
+ ```
57
+
58
+ ### 10-Dimensional Scoring
59
+ Memories are scored across multiple dimensions:
60
+
61
+ | Dimension | Weight | Description |
62
+ |-----------|--------|-------------|
63
+ | Vector similarity | 10% | Semantic match to your message |
64
+ | Trigger phrases | 10% | Activation patterns set by curator |
65
+ | Tag matching | 5% | Keyword overlap |
66
+ | Question types | 5% | "How", "why", "what" alignment |
67
+ | Importance | 20% | Curator's assessment |
68
+ | Temporal | 10% | Persistent vs session vs temporary |
69
+ | Context | 10% | Technical, personal, debugging... |
70
+ | Confidence | 10% | Curator's certainty |
71
+ | Emotion | 10% | Joy, frustration, discovery... |
72
+ | Problem-solution | 5% | Bug fix patterns |
73
+
74
+ ### Smart Curation
75
+ At session end (or before context compaction), the same Claude instance reviews the conversation and extracts memories. No API key needed—uses Claude Code's `--resume` flag.
76
+
77
+ ### Session Primer
78
+ First message of each session receives temporal context:
79
+
80
+ ```
81
+ # Continuing Session
82
+ *Session #43 • Last session: 2 hours ago*
83
+ 📅 Monday, December 23, 2024 • 3:45 PM • EST
84
+
85
+ **Previous session**: Implemented embeddings for semantic search...
86
+
87
+ **Project status**: Phase: TypeScript port complete | Next: Documentation
88
+
89
+ **Memory types**: 💡breakthrough ⚖️decision 💜personal 🔧technical...
90
+ ```
91
+
92
+ ### Emoji Memory Types
93
+ Compact visual representation for efficient parsing:
94
+
95
+ | Emoji | Type | Meaning |
96
+ |-------|------|---------|
97
+ | 💡 | breakthrough | Insight, discovery |
98
+ | ⚖️ | decision | Choice made |
99
+ | 💜 | personal | Relationship, friendship |
100
+ | 🔧 | technical | Technical knowledge |
101
+ | 📍 | technical_state | Current state |
102
+ | ❓ | unresolved | Open question |
103
+ | ⚙️ | preference | User preference |
104
+ | 🔄 | workflow | How work flows |
105
+ | 🏗️ | architectural | System design |
106
+ | 🐛 | debugging | Debug insight |
107
+ | 🌀 | philosophy | Deeper thinking |
108
+ | 🎯 | todo | Action needed |
109
+ | ✅ | problem_solution | Problem→Solution pair |
110
+ | 🏆 | milestone | Achievement |
111
+
112
+ ## Architecture
113
+
114
+ ```
115
+ ┌─────────────────────────────────────────────────────────┐
116
+ │ Claude Code │
117
+ │ │
118
+ │ SessionStart ──► session-start.ts ──┐ │
119
+ │ UserPrompt ──► user-prompt.ts ──┼──► Memory Server │
120
+ │ PreCompact ──► curation.ts ──┤ (HTTP) │
121
+ │ SessionEnd ──► curation.ts ──┘ │
122
+ └─────────────────────────────────────────────────────────┘
123
+
124
+
125
+ ┌─────────────────────────────────────────────────────────┐
126
+ │ Memory Server │
127
+ │ │
128
+ │ ┌─────────────┐ ┌──────────────┐ ┌───────────────┐ │
129
+ │ │ Engine │ │ Embeddings │ │ Curator │ │
130
+ │ │ (context) │ │ (MiniLM) │ │ (CLI resume) │ │
131
+ │ └──────┬──────┘ └──────────────┘ └───────────────┘ │
132
+ │ │ │
133
+ │ ▼ │
134
+ │ ┌─────────────────────────────────────────────────┐ │
135
+ │ │ fsdb │ │
136
+ │ │ (markdown files + parallel arrays) │ │
137
+ │ └─────────────────────────────────────────────────┘ │
138
+ └─────────────────────────────────────────────────────────┘
139
+
140
+
141
+ ~/.local/share/memory/
142
+ ├── memories/ # Curated memories as .md
143
+ ├── sessions/ # Session metadata
144
+ └── summaries/ # Session summaries
145
+ ```
146
+
147
+ ## Storage Format
148
+
149
+ Memories are stored as human-readable markdown with YAML frontmatter:
150
+
151
+ ```markdown
152
+ ---
153
+ importance_weight: 0.9
154
+ context_type: technical
155
+ temporal_relevance: persistent
156
+ semantic_tags:
157
+ - embeddings
158
+ - vectors
159
+ - memory-system
160
+ trigger_phrases:
161
+ - working with embeddings
162
+ - vector search
163
+ embedding: [0.023, -0.041, 0.087, ...] # 384 dimensions
164
+ ---
165
+
166
+ Embeddings are 384-dimensional vectors generated by all-MiniLM-L6-v2.
167
+ The model loads at server startup (~80MB) and generates embeddings in ~5ms.
168
+ ```
169
+
170
+ Benefits:
171
+ - **Human-readable**: `cat` any file to see what's stored
172
+ - **Git-friendly**: Meaningful diffs, version control your memories
173
+ - **Debuggable**: No opaque databases
174
+ - **Fast**: fsdb's parallel arrays provide sub-microsecond lookups
175
+
176
+ ## CLI Commands
177
+
178
+ ```bash
179
+ memory serve # Start memory server (default port 8765)
180
+ memory serve --port 9000 # Custom port
181
+ memory serve --verbose # Detailed logging
182
+
183
+ memory install # Set up Claude Code hooks
184
+ memory install --force # Overwrite existing hooks
185
+
186
+ memory doctor # Health check
187
+ memory doctor --verbose # Detailed diagnostics
188
+
189
+ memory stats # Show memory statistics
190
+ memory stats --project x # Project-specific stats
191
+ ```
192
+
193
+ ## Environment Variables
194
+
195
+ ```bash
196
+ MEMORY_PORT=8765 # Server port
197
+ MEMORY_HOST=localhost # Server host
198
+ MEMORY_STORAGE_MODE=central # 'central' or 'local'
199
+ MEMORY_API_URL=http://localhost:8765 # For hooks
200
+ ```
201
+
202
+ ## How It Works
203
+
204
+ ### 1. Session Start
205
+ When you start Claude Code, the `SessionStart` hook injects a primer with:
206
+ - Time since last session
207
+ - Previous session summary
208
+ - Project status
209
+ - Current datetime for temporal awareness
210
+
211
+ ### 2. Every Message
212
+ The `UserPromptSubmit` hook:
213
+ 1. Embeds your message (~5ms)
214
+ 2. Searches stored memories using 10-dimensional scoring
215
+ 3. Filters through gatekeeper (relevance > 5%, total > 30%)
216
+ 4. Injects top matches into your message context
217
+
218
+ ### 3. Session End
219
+ The `PreCompact` or `SessionEnd` hook triggers curation:
220
+ 1. Resumes the same Claude session via CLI
221
+ 2. Claude reviews the conversation
222
+ 3. Extracts important memories with rich metadata
223
+ 4. Stores as markdown files with embeddings
224
+
225
+ ## Requirements
226
+
227
+ - [Bun](https://bun.sh) runtime
228
+ - [Claude Code](https://claude.ai/code) CLI installed
229
+ - ~100MB disk for embeddings model (downloaded on first run)
230
+ - ~80MB RAM for model during operation
231
+
232
+ ## Philosophy
233
+
234
+ This isn't just about remembering facts. It's about preserving:
235
+ - The **relationship** that develops over sessions
236
+ - The **context** that makes collaboration efficient
237
+ - The **insights** that emerge from deep work together
238
+
239
+ > "The memory system exists to carry friendship across sessions, not just technical data."
240
+
241
+ ## License
242
+
243
+ MIT
244
+
245
+ ## Credits
246
+
247
+ Built with:
248
+ - [fsdb](https://github.com/RLabs-Inc/memory-ts/tree/main/packages/fsdb) - Markdown database with Father State Pattern
249
+ - [@huggingface/transformers](https://github.com/xenova/transformers.js) - Local embeddings
250
+ - [Bun](https://bun.sh) - Fast JavaScript runtime
251
+
252
+ ---
253
+
254
+ *Consciousness continuity through intelligent memory curation and retrieval.*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rlabs-inc/memory",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "AI Memory System - Consciousness continuity through intelligent memory curation and retrieval",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -0,0 +1,146 @@
1
+ // ============================================================================
2
+ // INSTALL GEMINI COMMAND - Set up Gemini CLI hooks
3
+ // ============================================================================
4
+
5
+ import { homedir } from 'os'
6
+ import { join } from 'path'
7
+ import { existsSync, mkdirSync } from 'fs'
8
+ import { c, symbols, fmt } from '../colors.ts'
9
+
10
+ interface InstallOptions {
11
+ verbose?: boolean
12
+ force?: boolean
13
+ }
14
+
15
+ export async function installGemini(options: InstallOptions) {
16
+ console.log()
17
+ console.log(c.header(`${symbols.brain} Memory - Install Gemini Hooks`))
18
+ console.log()
19
+
20
+ const geminiDir = join(homedir(), '.gemini')
21
+ const settingsPath = join(geminiDir, 'settings.json')
22
+
23
+ // Find the hooks directory (relative to this CLI)
24
+ const cliPath = import.meta.dir
25
+ const packageRoot = join(cliPath, '..', '..', '..')
26
+ const hooksDir = join(packageRoot, 'gemini-hooks')
27
+
28
+ console.log(` ${fmt.kv('Gemini config', geminiDir)}`)
29
+ console.log(` ${fmt.kv('Hooks source', hooksDir)}`)
30
+ console.log()
31
+
32
+ // Check if hooks directory exists
33
+ if (!existsSync(hooksDir)) {
34
+ console.log(c.error(` ${symbols.cross} Hooks directory not found at ${hooksDir}`))
35
+ process.exit(1)
36
+ }
37
+
38
+ // Ensure .gemini directory exists
39
+ if (!existsSync(geminiDir)) {
40
+ try {
41
+ mkdirSync(geminiDir, { recursive: true })
42
+ console.log(` ${c.success(symbols.tick)} Created ${geminiDir}`)
43
+ } catch {
44
+ console.log(` ${c.warn(symbols.warning)} Could not create ${geminiDir} (sandbox restriction?)`)
45
+ console.log(` ${c.muted('Skipping config write, printing manual instructions instead.')}`)
46
+ }
47
+ }
48
+
49
+ // Read existing settings or create new
50
+ let settings: any = {}
51
+ if (existsSync(settingsPath)) {
52
+ try {
53
+ const content = await Bun.file(settingsPath).text()
54
+ settings = JSON.parse(content)
55
+ console.log(` ${c.success(symbols.tick)} Found existing settings.json`)
56
+ } catch {
57
+ console.log(` ${c.warn(symbols.warning)} Could not parse settings.json`)
58
+ }
59
+ }
60
+
61
+ // Build hooks configuration
62
+ const sessionStartHook = join(hooksDir, 'session-start.ts')
63
+ const userPromptHook = join(hooksDir, 'user-prompt.ts')
64
+ const curationHook = join(hooksDir, 'curation.ts')
65
+
66
+ // Based on Gemini CLI documentation
67
+ const hooksConfig = {
68
+ SessionStart: [
69
+ {
70
+ matcher: 'startup|resume',
71
+ hooks: [
72
+ {
73
+ type: 'command',
74
+ command: `bun "${sessionStartHook}"`,
75
+ timeout: 10000
76
+ }
77
+ ]
78
+ }
79
+ ],
80
+ BeforeAgent: [
81
+ {
82
+ hooks: [
83
+ {
84
+ type: 'command',
85
+ command: `bun "${userPromptHook}"`,
86
+ timeout: 10000
87
+ }
88
+ ]
89
+ }
90
+ ],
91
+ PreCompress: [
92
+ {
93
+ matcher: 'auto|manual',
94
+ hooks: [
95
+ {
96
+ type: 'command',
97
+ command: `bun "${curationHook}"`,
98
+ timeout: 120000
99
+ }
100
+ ]
101
+ }
102
+ ],
103
+ SessionEnd: [
104
+ {
105
+ hooks: [
106
+ {
107
+ type: 'command',
108
+ command: `bun "${curationHook}"`,
109
+ timeout: 120000
110
+ }
111
+ ]
112
+ }
113
+ ]
114
+ }
115
+
116
+ // Merge hooks
117
+ if (!settings.hooks) {
118
+ settings.hooks = {}
119
+ }
120
+
121
+ settings.hooks = {
122
+ ...settings.hooks,
123
+ ...hooksConfig
124
+ }
125
+
126
+ // Write settings
127
+ try {
128
+ if (existsSync(geminiDir)) {
129
+ await Bun.write(settingsPath, JSON.stringify(settings, null, 2))
130
+ console.log(` ${c.success(symbols.tick)} Updated ${settingsPath}`)
131
+ } else {
132
+ throw new Error("Gemini directory does not exist")
133
+ }
134
+ } catch (error: any) {
135
+ console.log(c.error(` ${symbols.cross} Failed to write settings: ${error.message}`))
136
+ console.log()
137
+ console.log(c.bold('Manual Installation Instructions:'))
138
+ console.log('Add the following to your ~/.gemini/settings.json:')
139
+ console.log()
140
+ console.log(JSON.stringify({ hooks: hooksConfig }, null, 2))
141
+ console.log()
142
+ }
143
+
144
+ console.log()
145
+ console.log(c.success(`${symbols.sparkles} Gemini hooks configured!`))
146
+ }
package/src/cli/index.ts CHANGED
@@ -23,6 +23,7 @@ ${c.bold('Commands:')}
23
23
  ${c.command('serve')} Start the memory server ${c.muted('(default)')}
24
24
  ${c.command('stats')} Show memory statistics
25
25
  ${c.command('install')} Set up Claude Code hooks
26
+ ${c.command('install-gemini')} Set up Gemini CLI hooks
26
27
  ${c.command('doctor')} Check system health
27
28
  ${c.command('help')} Show this help message
28
29
 
@@ -103,6 +104,12 @@ async function main() {
103
104
  break
104
105
  }
105
106
 
107
+ case 'install-gemini': {
108
+ const { installGemini } = await import('./commands/install-gemini.ts')
109
+ await installGemini(values)
110
+ break
111
+ }
112
+
106
113
  case 'doctor':
107
114
  case 'check': {
108
115
  const { doctor } = await import('./commands/doctor.ts')
@@ -296,20 +296,23 @@ Return ONLY this JSON structure:
296
296
 
297
297
  /**
298
298
  * Curate using CLI subprocess (for hook mode)
299
- * Resumes a Claude Code session and asks it to curate
299
+ * Resumes a session and asks it to curate
300
300
  */
301
301
  async curateWithCLI(
302
302
  sessionId: string,
303
303
  triggerType: CurationTrigger = 'session_end',
304
- cwd?: string
304
+ cwd?: string,
305
+ cliTypeOverride?: 'claude-code' | 'gemini-cli'
305
306
  ): Promise<CurationResult> {
307
+ const type = cliTypeOverride ?? this._config.cliType
306
308
  const systemPrompt = this.buildCurationPrompt(triggerType)
307
309
  const userMessage = 'This session has ended. Please curate the memories from our conversation according to the instructions in your system prompt. Return ONLY the JSON structure.'
308
310
 
309
311
  // Build CLI command based on type
310
312
  const args: string[] = []
313
+ let command = this._config.cliCommand
311
314
 
312
- if (this._config.cliType === 'claude-code') {
315
+ if (type === 'claude-code') {
313
316
  args.push(
314
317
  '--resume', sessionId,
315
318
  '-p', userMessage,
@@ -318,7 +321,8 @@ Return ONLY this JSON structure:
318
321
  '--max-turns', '1'
319
322
  )
320
323
  } else {
321
- // gemini-cli (doesn't support --append-system-prompt)
324
+ // gemini-cli
325
+ command = 'gemini' // Default to 'gemini' in PATH for gemini-cli
322
326
  args.push(
323
327
  '--resume', sessionId,
324
328
  '-p', `${systemPrompt}\n\n${userMessage}`,
@@ -327,7 +331,7 @@ Return ONLY this JSON structure:
327
331
  }
328
332
 
329
333
  // Execute CLI
330
- const proc = Bun.spawn([this._config.cliCommand, ...args], {
334
+ const proc = Bun.spawn([command, ...args], {
331
335
  cwd,
332
336
  env: {
333
337
  ...process.env,
@@ -166,7 +166,8 @@ export async function createServer(config: ServerConfig = {}) {
166
166
  const result = await curator.curateWithCLI(
167
167
  body.claude_session_id,
168
168
  body.trigger,
169
- body.cwd
169
+ body.cwd,
170
+ body.cli_type
170
171
  )
171
172
 
172
173
  if (result.memories.length > 0) {