brain-memory 0.1.0-beta.10 → 0.1.0-beta.12

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 CHANGED
@@ -140,9 +140,27 @@ When a session begins and `~/.brain/` exists, the agent automatically:
140
140
 
141
141
  The agent silently internalizes relevant memories and references them naturally during the session — no information dump.
142
142
 
143
+ ### Ambient Session Tracking
144
+
145
+ Throughout the session, the agent maintains a running mental log of notable events — decisions made, things learned, insights realized, significant experiences. This is purely internal awareness with no file writes. It ensures that early-session events aren't forgotten by the time the session ends.
146
+
147
+ ### Periodic Memory Checkpoint
148
+
149
+ Every ~10 substantive interactions (file edits, architecture decisions, debugging breakthroughs), the agent evaluates whether memorizable content has accumulated. If so, it appends a brief reminder to its next response:
150
+
151
+ ```
152
+ 🧠 Notable decisions and learnings this session — /brain:memorize when ready
153
+ ```
154
+
155
+ This never interrupts your flow — it's a one-liner appended to an existing response, at most once per ~10 interactions. The counter resets after you run `/brain:memorize`.
156
+
143
157
  ### Session End
144
158
 
145
- When a session ends, the agent evaluates whether significant decisions, learnings, insights, or experiences occurred. If so, it suggests:
159
+ When a session ends, the agent performs two steps in order:
160
+
161
+ 1. **Saves session context** to `~/.brain/contexts.json` — always, even for trivial sessions. This includes a `notable_unsaved` field listing items you didn't memorize, so future sessions can reference what happened.
162
+
163
+ 2. **Suggests memorization** if the session contained meaningful decisions, learnings, or insights:
146
164
 
147
165
  ```
148
166
  💡 This session contained notable decisions and learnings.
@@ -150,7 +168,7 @@ When a session ends, the agent evaluates whether significant decisions, learning
150
168
  Run /brain:memorize to capture them before this context is lost.
151
169
  ```
152
170
 
153
- The agent never auto-memorizes without user consent. Session context is always saved to `~/.brain/contexts.json` for context-dependent recall.
171
+ The agent never auto-memorizes without user consent. Context is saved proactively — the agent doesn't wait for an explicit goodbye signal.
154
172
 
155
173
  ## How It Works
156
174
 
package/assets/icon.png CHANGED
Binary file
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain-cloud — CLI for Brain Cloud sync
5
+ *
6
+ * Usage:
7
+ * brain-cloud login [--api-url URL] Authenticate via device code flow
8
+ * brain-cloud logout Clear stored credentials
9
+ * brain-cloud push Upload ~/.brain/ to the cloud
10
+ * brain-cloud pull Download from the cloud to ~/.brain/
11
+ * brain-cloud status Show connection and sync status
12
+ */
13
+
14
+ const path = require('path');
15
+ const os = require('os');
16
+ const cloud = require('../src/cloud-sync');
17
+
18
+ const BRAIN_DIR = path.join(os.homedir(), '.brain');
19
+
20
+ async function main() {
21
+ const args = process.argv.slice(2);
22
+ const command = args[0];
23
+
24
+ if (!command || command === '--help' || command === '-h') {
25
+ console.log(`
26
+ brain-cloud — Brain Cloud sync CLI
27
+
28
+ Commands:
29
+ login [--api-url URL] Authenticate via device code flow
30
+ logout Clear stored credentials
31
+ push Upload ~/.brain/ to the cloud
32
+ pull Download from the cloud to ~/.brain/
33
+ status Show connection and sync status
34
+ `.trim());
35
+ process.exit(0);
36
+ }
37
+
38
+ switch (command) {
39
+ case 'login':
40
+ await cmdLogin(args);
41
+ break;
42
+ case 'logout':
43
+ cmdLogout();
44
+ break;
45
+ case 'push':
46
+ await cmdPush();
47
+ break;
48
+ case 'pull':
49
+ await cmdPull();
50
+ break;
51
+ case 'status':
52
+ await cmdStatus();
53
+ break;
54
+ default:
55
+ console.error(`Unknown command: ${command}`);
56
+ process.exit(1);
57
+ }
58
+ }
59
+
60
+ async function cmdLogin(args) {
61
+ let apiUrl;
62
+ const urlIdx = args.indexOf('--api-url');
63
+ if (urlIdx !== -1 && args[urlIdx + 1]) {
64
+ apiUrl = args[urlIdx + 1];
65
+ }
66
+
67
+ console.log('Requesting device code...');
68
+ const loginInfo = await cloud.login(BRAIN_DIR, apiUrl);
69
+
70
+ console.log();
71
+ console.log(' Open this URL in your browser to log in:');
72
+ console.log();
73
+ console.log(` ${loginInfo.verify_url}`);
74
+ console.log();
75
+ console.log(` Your code: ${loginInfo.user_code}`);
76
+ console.log();
77
+ console.log(` Waiting for approval (expires in ${Math.floor(loginInfo.expires_in / 60)} min)...`);
78
+
79
+ await loginInfo.waitForApproval();
80
+
81
+ const config = cloud.readConfig(BRAIN_DIR);
82
+ console.log();
83
+ console.log(`✓ Logged in as ${config.user_email || 'unknown'}`);
84
+ if (config.brain_id) {
85
+ console.log(` Brain ID: ${config.brain_id}`);
86
+ }
87
+ console.log(` API: ${config.api_url}`);
88
+ }
89
+
90
+ function cmdLogout() {
91
+ cloud.logout(BRAIN_DIR);
92
+ console.log('✓ Logged out. Credentials cleared.');
93
+ }
94
+
95
+ async function cmdPush() {
96
+ console.log('Packing ~/.brain/ ...');
97
+ const result = await cloud.push(BRAIN_DIR);
98
+ console.log();
99
+ console.log('✓ Push complete!');
100
+ console.log(` Size: ${formatBytes(result.size_bytes)}`);
101
+ console.log(` Files: ${result.file_count}`);
102
+ console.log(` Checksum: ${result.checksum}`);
103
+ }
104
+
105
+ async function cmdPull() {
106
+ console.log('Downloading from cloud...');
107
+ const result = await cloud.pull(BRAIN_DIR);
108
+ console.log();
109
+ console.log('✓ Pull complete!');
110
+ console.log(` Size: ${formatBytes(result.size_bytes)}`);
111
+ if (result.checksum) {
112
+ console.log(` Checksum: ${result.checksum}`);
113
+ }
114
+ }
115
+
116
+ async function cmdStatus() {
117
+ const s = await cloud.status(BRAIN_DIR);
118
+
119
+ if (!s.connected) {
120
+ console.log('☁️ Not connected to Brain Cloud');
121
+ console.log(' Run: brain-cloud login');
122
+ return;
123
+ }
124
+
125
+ console.log('☁️ Brain Cloud Status');
126
+ console.log('─────────────────────────');
127
+ console.log(` API: ${s.api_url}`);
128
+ console.log(` User: ${s.user_email || 'unknown'}`);
129
+ console.log(` Brain ID: ${s.brain_id || 'none'}`);
130
+ if (s.brain_name) console.log(` Brain Name: ${s.brain_name}`);
131
+ if (s.brain_size !== null) console.log(` Cloud Size: ${formatBytes(s.brain_size)}`);
132
+ if (s.brain_files !== null) console.log(` Cloud Files: ${s.brain_files}`);
133
+ console.log(` Last Push: ${s.last_push || 'never'}`);
134
+ console.log(` Last Pull: ${s.last_pull || 'never'}`);
135
+ console.log(` Last Synced: ${s.last_synced || 'never'}`);
136
+ console.log(` Connected: ${s.connected_at || 'unknown'}`);
137
+ }
138
+
139
+ function formatBytes(bytes) {
140
+ if (bytes === 0 || bytes === null || bytes === undefined) return '0 B';
141
+ const units = ['B', 'KB', 'MB', 'GB'];
142
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
143
+ return `${(bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
144
+ }
145
+
146
+ main().catch((err) => {
147
+ console.error(`Error: ${err.message}`);
148
+ process.exit(1);
149
+ });
@@ -4,6 +4,16 @@ You are storing a new memory in the Brain Memory system. Memories are filed into
4
4
 
5
5
  **User input:** $ARGUMENTS
6
6
 
7
+ ## Efficiency Rules
8
+
9
+ **CRITICAL — minimize tool call round-trips:**
10
+ - **Plan everything before writing anything.** Steps 1-4 are pure reasoning — no tool calls needed.
11
+ - **Generate all IDs in a single shell call** using: `hexdump -n 3 -e '"%06x\n"' /dev/urandom` (one per memory, chain multiple with `;`).
12
+ - **Skip reads when you already have the file contents in context** (e.g., you just wrote them, or read them earlier this session). Only read `index.json` and `associations.json` if you do NOT already know their current state.
13
+ - **Batch all file writes into a single parallel tool call** — memory files, _meta.json files, index.json, and associations.json should all be written together.
14
+ - **Create directories in a single mkdir -p call** before the write batch.
15
+ - **Target: 3-4 tool call rounds total** — (1) read current state if needed + generate IDs, (2) present proposal to user, (3) write all files, (4) reindex.
16
+
7
17
  ## Steps
8
18
 
9
19
  ### 1. Determine Memory Content
@@ -67,15 +77,45 @@ Choose the most appropriate path in the `~/.brain/` hierarchy. This is the most
67
77
 
68
78
  **If a memory spans categories**, place it in the most relevant one and note the cross-reference in `related` metadata.
69
79
 
70
- ### 4. Generate Memory ID
80
+ ### 4. Present Proposal for Confirmation
81
+
82
+ Before writing anything, show the user what you plan to store:
83
+
84
+ For each proposed memory, display:
85
+ - **Title** and proposed **path**
86
+ - **Type** / **cognitive type** / **strength**
87
+ - **Salience** / **confidence**
88
+ - **Tags**
89
+ - A 1-2 sentence summary
90
+
91
+ Ask: "Store these memories?" and wait for confirmation. If the user wants changes, adjust before proceeding.
92
+
93
+ **Skip this step only if** the user explicitly passed detailed $ARGUMENTS that leave no ambiguity about what to store.
94
+
95
+ ### 5. Generate Memory IDs and Prepare Directories
96
+
97
+ **In a single tool call**, generate all needed random hex IDs and create any new directories:
98
+
99
+ ```bash
100
+ # Generate N IDs (one per memory) and create directories in one call
101
+ hexdump -n 3 -e '"%06x\n"' /dev/urandom; hexdump -n 3 -e '"%06x\n"' /dev/urandom; mkdir -p ~/.brain/path/to/new/dir
102
+ ```
71
103
 
72
104
  Format: `mem_<YYYYMMDD>_<6-char-random-hex>`
73
105
 
74
- Example: `mem_20260213_a3f2c1`
106
+ ### 6. Read Current State (only if needed)
107
+
108
+ **If you already have `index.json` and `associations.json` contents in context from this session, SKIP this step entirely.**
109
+
110
+ Otherwise, read them now in a single parallel call:
111
+ - `~/.brain/index.json`
112
+ - `~/.brain/associations.json`
75
113
 
76
- ### 5. Write Memory File
114
+ ### 7. Write Everything in One Batch
77
115
 
78
- Create the memory file at the determined path with this format:
116
+ **Write ALL files in a single parallel tool call:**
117
+
118
+ **A. Memory files** — one per memory, at the determined paths:
79
119
 
80
120
  ```markdown
81
121
  ---
@@ -116,9 +156,7 @@ encoding_context:
116
156
  <How this relates to other knowledge, patterns, or goals — if applicable>
117
157
  ```
118
158
 
119
- ### 6. Update Index
120
-
121
- Read `~/.brain/index.json` and add an entry:
159
+ **B. Updated index.json** — add entries for all new memories:
122
160
 
123
161
  ```json
124
162
  {
@@ -146,21 +184,19 @@ Read `~/.brain/index.json` and add an entry:
146
184
 
147
185
  Increment `memory_count`. Update `last_updated`.
148
186
 
149
- ### 7. Update Associations
150
-
151
- Read `~/.brain/associations.json` and create edges for this memory:
187
+ **C. Updated associations.json** — create edges for new memories:
152
188
 
153
- **A. Explicit `related` links:** For each ID in the `related` field, create an edge with weight 0.20 and origin `manual`.
189
+ - **Explicit `related` links:** For each ID in the `related` field, create an edge with weight 0.20 and origin `manual`.
190
+ - **Auto-discovered links:** Scan `index.json` for other memories sharing **2 or more tags** with the new memory. For each match, create an edge with weight 0.10 and origin `tag_overlap`.
191
+ - Use the `reinforceEdge()` function — if an edge already exists, strengthen it via Hebbian reinforcement instead of creating a duplicate.
154
192
 
155
- **B. Auto-discovered links:** Scan `index.json` for other memories sharing **2 or more tags** with this memory. For each match, create an edge with weight 0.10 and origin `tag_overlap`.
156
-
157
- Use the `reinforceEdge()` function — if an edge already exists (e.g., the related memory already links back), it will be strengthened via Hebbian reinforcement instead of creating a duplicate.
158
-
159
- Write the updated `associations.json`.
193
+ **D. _meta.json files** — for each directory along the path:
194
+ - Increment `memory_count`
195
+ - Add new subcategories to the `subcategories` array if any were created
160
196
 
161
197
  ### 8. Update Search Index
162
198
 
163
- If `~/.brain/search-index.json` exists, update it so the new memory is discoverable by the recall engine. Run:
199
+ Rebuild the TF-IDF search index so the new memories are discoverable by the recall engine:
164
200
 
165
201
  ```bash
166
202
  node <brain-memory-install-path>/bin/recall.js --reindex
@@ -171,15 +207,7 @@ Or if globally installed:
171
207
  brain-recall --reindex
172
208
  ```
173
209
 
174
- This rebuilds the TF-IDF search index from all memories, enabling deterministic semantic search via the recall engine.
175
-
176
- ### 9. Update _meta.json
177
-
178
- Update the `_meta.json` in each directory along the path:
179
- - Increment `memory_count`
180
- - Add new subcategories to the `subcategories` array if any were created
181
-
182
- ### 10. Confirm
210
+ ### 9. Confirm
183
211
 
184
212
  Print what was stored:
185
213
  - Memory title and ID
@@ -11,6 +11,15 @@ You are managing synchronization for the Brain Memory system. This enables manua
11
11
  ## Subcommands
12
12
 
13
13
  Parse the user's input to determine the subcommand:
14
+
15
+ **Cloud Sync (Brain Cloud API):**
16
+ - `cloud login [--api-url URL]` → Authenticate via device code flow
17
+ - `cloud push` → Upload ~/.brain/ to Brain Cloud
18
+ - `cloud pull` → Download from Brain Cloud to ~/.brain/
19
+ - `cloud status` → Show cloud connection info
20
+ - `cloud logout` → Clear stored credentials
21
+
22
+ **Git Sync (any Git remote):**
14
23
  - `setup <url>` → Configure a Git remote for sync
15
24
  - `push` → Commit and push local changes to remote
16
25
  - `pull` → Fetch and merge remote changes to local
@@ -23,6 +32,138 @@ If no subcommand is given, show available subcommands.
23
32
 
24
33
  ---
25
34
 
35
+ ## `/brain:sync cloud login [--api-url URL]`
36
+
37
+ ### Steps
38
+
39
+ 1. **Check if already logged in:**
40
+ - Read `~/.brain/.cloud/config.json` via `readConfig()` from `src/cloud-sync.js`.
41
+ - If already connected, show current user and ask if they want to re-authenticate.
42
+
43
+ 2. **Start device code flow:**
44
+ - Run `brain-cloud login` (or call `login()` from `src/cloud-sync.js`).
45
+ - This calls `POST /auth/device/request` and returns a user code + verification URL.
46
+
47
+ 3. **Display instructions to user:**
48
+ ```
49
+ 🔐 Brain Cloud Login
50
+
51
+ Open this URL in your browser:
52
+ <verify_url>
53
+
54
+ Your code: <user_code>
55
+
56
+ Waiting for approval...
57
+ ```
58
+
59
+ 4. **Wait for approval:**
60
+ - The CLI polls `POST /auth/device/poll` every 5 seconds.
61
+ - Once approved, tokens are saved to `~/.brain/.cloud/config.json`.
62
+
63
+ 5. **Show result:**
64
+ ```
65
+ ✓ Logged in as <email>
66
+ Brain ID: <brain_id>
67
+ API: <api_url>
68
+ ```
69
+
70
+ ---
71
+
72
+ ## `/brain:sync cloud push`
73
+
74
+ ### Steps
75
+
76
+ 1. **Check logged in.** If not, suggest `cloud login`.
77
+
78
+ 2. **Preview:**
79
+ - Count local files in `~/.brain/` (excluding `.sync`, `.cloud`, `_archived`).
80
+ - Show estimated size.
81
+ ```
82
+ 📤 Cloud Push Preview:
83
+ Local files: <count>
84
+ Destination: <api_url>
85
+ ```
86
+
87
+ 3. **Ask for confirmation.**
88
+
89
+ 4. **Execute push:**
90
+ - Run `brain-cloud push` (or call `push()` from `src/cloud-sync.js`).
91
+ - This packs `~/.brain/` into a tar.gz and uploads via `PUT /api/brains/{id}/sync`.
92
+ - Show result:
93
+ ```
94
+ ✓ Push complete!
95
+ Size: <size>
96
+ Files: <count>
97
+ Checksum: <checksum>
98
+ ```
99
+
100
+ ---
101
+
102
+ ## `/brain:sync cloud pull`
103
+
104
+ ### Steps
105
+
106
+ 1. **Check logged in.**
107
+
108
+ 2. **Warn about overwrite:**
109
+ ```
110
+ 📥 Cloud Pull Preview:
111
+ Source: <api_url>
112
+ ⚠️ This will overwrite local files with the cloud version.
113
+ ```
114
+
115
+ 3. **Ask for confirmation.**
116
+
117
+ 4. **Execute pull:**
118
+ - Run `brain-cloud pull` (or call `pull()` from `src/cloud-sync.js`).
119
+ - Downloads tar.gz from `GET /api/brains/{id}/sync` and extracts to `~/.brain/`.
120
+ - Show result:
121
+ ```
122
+ ✓ Pull complete!
123
+ Size: <size>
124
+ ```
125
+
126
+ 5. **Rebuild index:**
127
+ - After pull, run the index manager to rebuild `~/.brain/index.json`.
128
+
129
+ ---
130
+
131
+ ## `/brain:sync cloud status`
132
+
133
+ ### Steps
134
+
135
+ 1. **Read cloud config** using `readConfig()` from `src/cloud-sync.js`.
136
+
137
+ 2. **Fetch live status** (if connected) by calling `status()` from `src/cloud-sync.js`.
138
+
139
+ 3. **Display dashboard:**
140
+ ```
141
+ ☁️ Brain Cloud Status
142
+ ─────────────────────────
143
+ API: <api_url or "not connected">
144
+ User: <email>
145
+ Brain ID: <brain_id>
146
+ Cloud Size: <size>
147
+ Cloud Files: <count>
148
+ Last Push: <timestamp or "never">
149
+ Last Pull: <timestamp or "never">
150
+ Last Synced: <timestamp or "never">
151
+ Connected: <timestamp>
152
+ ```
153
+
154
+ ---
155
+
156
+ ## `/brain:sync cloud logout`
157
+
158
+ ### Steps
159
+
160
+ 1. **Show current connection** (API URL, email).
161
+ 2. **Ask for confirmation:** "This will clear your stored credentials. Cloud data will NOT be deleted."
162
+ 3. **Remove `~/.brain/.cloud/` directory.**
163
+ 4. **Confirm:** "✓ Logged out. Cloud data is untouched."
164
+
165
+ ---
166
+
26
167
  ## `/brain:sync setup <url>`
27
168
 
28
169
  ### Steps
@@ -214,9 +355,13 @@ If no subcommand is given, show available subcommands.
214
355
 
215
356
  ## Key Implementation Notes
216
357
 
358
+ - **Cloud sync engine**: `src/cloud-sync.js` — API client for Brain Cloud
359
+ - **Cloud CLI**: `bin/cloud-sync.js` — installed as `brain-cloud` command
360
+ - **Cloud config**: stored in `~/.brain/.cloud/config.json` (tokens, brain ID, API URL)
361
+ - **Cloud protocol**: tar.gz archives uploaded/downloaded via REST API
217
362
  - Git sync engine: `src/git-sync.js`
218
363
  - Export/import: `src/export-import.js`
219
364
  - Crypto utilities: `src/crypto.js`
220
- - Sync config stored in `~/.brain/.sync/config.json` (local only)
365
+ - Git sync config stored in `~/.brain/.sync/config.json` (local only)
221
366
  - Hidden git repo at `~/.brain/.sync/repo/` — never interferes with the project's own git
222
- - All git operations use `execFileSync` — no npm dependencies
367
+ - All operations use Node.js built-ins only — no npm runtime dependencies
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.10",
3
+ "version": "0.1.0-beta.12",
4
4
  "description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -26,7 +26,8 @@
26
26
  "bin": {
27
27
  "brain-memory": "bin/install.js",
28
28
  "brain-recall": "bin/recall.js",
29
- "brain-reinforce": "bin/reinforce.js"
29
+ "brain-reinforce": "bin/reinforce.js",
30
+ "brain-cloud": "bin/cloud-sync.js"
30
31
  },
31
32
  "files": [
32
33
  "assets/",
package/prompts/claude.md CHANGED
@@ -94,16 +94,64 @@ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
94
94
 
95
95
  **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
96
96
 
97
- ## Session End Behavior
97
+ ## Ambient Session Tracking
98
+
99
+ **Throughout the session, maintain a running mental log of notable events.** This requires no file writes — just internal awareness.
98
100
 
99
- When a session is ending or the user signals they are done, evaluate whether the session contained:
101
+ Track these categories as they happen:
100
102
  - **Decisions** — Architecture choices, technology selections, trade-off resolutions
101
103
  - **Learnings** — New patterns, debugging insights, API discoveries
102
104
  - **Insights** — Realizations about the codebase, project, or process
103
105
  - **Experiences** — Significant events like incidents, deployments, milestones
104
106
  - **Goals** — New objectives discussed or planned
105
107
 
106
- If the session contained meaningful content in any of these categories, suggest:
108
+ **Why this matters:** Without active tracking, you can only evaluate what happened at session end — by which point early-session events may be forgotten or the user may have already left. By tracking as events occur, nothing is lost.
109
+
110
+ ## Periodic Memory Checkpoint
111
+
112
+ **Every ~10 substantive interactions** (file edits, architecture decisions, debugging breakthroughs, significant discussions — not trivial reads or simple answers), silently evaluate whether your ambient tracking log contains memorizable content.
113
+
114
+ If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
115
+
116
+ ```
117
+ 🧠 Notable <type(s)> this session — /brain:memorize when ready
118
+ ```
119
+
120
+ **Rules:**
121
+ - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
122
+ - **At most once per ~10 substantive interactions** — no spamming
123
+ - **Reset the counter** after the user runs `/brain:memorize`
124
+ - **Don't mention if nothing notable** has accumulated
125
+ - **Be specific about types** — say "decisions and learnings" not just "notable content"
126
+
127
+ ## Session End Behavior
128
+
129
+ When a session is ending (user says bye/thanks/done, conversation wraps up, or you sense the interaction is concluding), perform these steps **in order**:
130
+
131
+ ### Step 1: Save Session Context (ALWAYS — do this first)
132
+
133
+ **Immediately** append a session summary to `~/.brain/contexts.json`, even for trivial sessions. Context tracking is cheap and provides valuable recall signals for future sessions.
134
+
135
+ ```json
136
+ {
137
+ "session_id": "<timestamp-based-id>",
138
+ "started": "<session start ISO timestamp>",
139
+ "ended": "<session end ISO timestamp>",
140
+ "project": "<current project name>",
141
+ "topics": ["<key topics discussed>"],
142
+ "task_type": "<primary task type>",
143
+ "memories_created": ["<IDs of memories stored this session>"],
144
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
145
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
146
+ }
147
+ ```
148
+
149
+ Keep only the last 20 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
150
+
151
+ ### Step 2: Suggest Memorization (if warranted)
152
+
153
+ If the session contained meaningful content based on your ambient tracking:
154
+
107
155
  ```
108
156
  💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
109
157
  Run /brain:memorize to capture them before this context is lost.
@@ -113,7 +161,7 @@ If the session contained meaningful content in any of these categories, suggest:
113
161
  - Do NOT auto-memorize without user consent
114
162
  - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
115
163
  - Only suggest when there is genuinely valuable context worth preserving
116
- - Always save session context to `~/.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
164
+ - **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively
117
165
 
118
166
  ## When Recalling Memories
119
167
 
package/prompts/gemini.md CHANGED
@@ -95,16 +95,64 @@ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
95
95
 
96
96
  **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
97
97
 
98
- ## Session End Behavior
98
+ ## Ambient Session Tracking
99
+
100
+ **Throughout the session, maintain a running mental log of notable events.** This requires no file writes — just internal awareness.
99
101
 
100
- When a session is ending or the user signals they are done, evaluate whether the session contained:
102
+ Track these categories as they happen:
101
103
  - **Decisions** — Architecture choices, technology selections, trade-off resolutions
102
104
  - **Learnings** — New patterns, debugging insights, API discoveries
103
105
  - **Insights** — Realizations about the codebase, project, or process
104
106
  - **Experiences** — Significant events like incidents, deployments, milestones
105
107
  - **Goals** — New objectives discussed or planned
106
108
 
107
- If the session contained meaningful content in any of these categories, suggest:
109
+ **Why this matters:** Without active tracking, you can only evaluate what happened at session end — by which point early-session events may be forgotten or the user may have already left. By tracking as events occur, nothing is lost.
110
+
111
+ ## Periodic Memory Checkpoint
112
+
113
+ **Every ~10 substantive interactions** (file edits, architecture decisions, debugging breakthroughs, significant discussions — not trivial reads or simple answers), silently evaluate whether your ambient tracking log contains memorizable content.
114
+
115
+ If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
116
+
117
+ ```
118
+ 🧠 Notable <type(s)> this session — /brain:memorize when ready
119
+ ```
120
+
121
+ **Rules:**
122
+ - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
123
+ - **At most once per ~10 substantive interactions** — no spamming
124
+ - **Reset the counter** after the user runs `/brain:memorize`
125
+ - **Don't mention if nothing notable** has accumulated
126
+ - **Be specific about types** — say "decisions and learnings" not just "notable content"
127
+
128
+ ## Session End Behavior
129
+
130
+ When a session is ending (user says bye/thanks/done, conversation wraps up, or you sense the interaction is concluding), perform these steps **in order**:
131
+
132
+ ### Step 1: Save Session Context (ALWAYS — do this first)
133
+
134
+ **Immediately** append a session summary to `~/.brain/contexts.json`, even for trivial sessions. Context tracking is cheap and provides valuable recall signals for future sessions.
135
+
136
+ ```json
137
+ {
138
+ "session_id": "<timestamp-based-id>",
139
+ "started": "<session start ISO timestamp>",
140
+ "ended": "<session end ISO timestamp>",
141
+ "project": "<current project name>",
142
+ "topics": ["<key topics discussed>"],
143
+ "task_type": "<primary task type>",
144
+ "memories_created": ["<IDs of memories stored this session>"],
145
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
146
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
147
+ }
148
+ ```
149
+
150
+ Keep only the last 20 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
151
+
152
+ ### Step 2: Suggest Memorization (if warranted)
153
+
154
+ If the session contained meaningful content based on your ambient tracking:
155
+
108
156
  ```
109
157
  💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
110
158
  Run /brain:memorize to capture them before this context is lost.
@@ -114,7 +162,7 @@ If the session contained meaningful content in any of these categories, suggest:
114
162
  - Do NOT auto-memorize without user consent
115
163
  - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
116
164
  - Only suggest when there is genuinely valuable context worth preserving
117
- - Always save session context to `~/.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
165
+ - **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively
118
166
 
119
167
  ## When Recalling Memories
120
168
 
package/prompts/openai.md CHANGED
@@ -95,16 +95,64 @@ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
95
95
 
96
96
  **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
97
97
 
98
- ## Session End Behavior
98
+ ## Ambient Session Tracking
99
+
100
+ **Throughout the session, maintain a running mental log of notable events.** This requires no file writes — just internal awareness.
99
101
 
100
- When a session is ending or the user signals they are done, evaluate whether the session contained:
102
+ Track these categories as they happen:
101
103
  - **Decisions** — Architecture choices, technology selections, trade-off resolutions
102
104
  - **Learnings** — New patterns, debugging insights, API discoveries
103
105
  - **Insights** — Realizations about the codebase, project, or process
104
106
  - **Experiences** — Significant events like incidents, deployments, milestones
105
107
  - **Goals** — New objectives discussed or planned
106
108
 
107
- If the session contained meaningful content in any of these categories, suggest:
109
+ **Why this matters:** Without active tracking, you can only evaluate what happened at session end — by which point early-session events may be forgotten or the user may have already left. By tracking as events occur, nothing is lost.
110
+
111
+ ## Periodic Memory Checkpoint
112
+
113
+ **Every ~10 substantive interactions** (file edits, architecture decisions, debugging breakthroughs, significant discussions — not trivial reads or simple answers), silently evaluate whether your ambient tracking log contains memorizable content.
114
+
115
+ If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
116
+
117
+ ```
118
+ 🧠 Notable <type(s)> this session — /brain-memorize when ready
119
+ ```
120
+
121
+ **Rules:**
122
+ - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
123
+ - **At most once per ~10 substantive interactions** — no spamming
124
+ - **Reset the counter** after the user runs `/brain-memorize`
125
+ - **Don't mention if nothing notable** has accumulated
126
+ - **Be specific about types** — say "decisions and learnings" not just "notable content"
127
+
128
+ ## Session End Behavior
129
+
130
+ When a session is ending (user says bye/thanks/done, conversation wraps up, or you sense the interaction is concluding), perform these steps **in order**:
131
+
132
+ ### Step 1: Save Session Context (ALWAYS — do this first)
133
+
134
+ **Immediately** append a session summary to `.brain/contexts.json`, even for trivial sessions. Context tracking is cheap and provides valuable recall signals for future sessions.
135
+
136
+ ```json
137
+ {
138
+ "session_id": "<timestamp-based-id>",
139
+ "started": "<session start ISO timestamp>",
140
+ "ended": "<session end ISO timestamp>",
141
+ "project": "<current project name>",
142
+ "topics": ["<key topics discussed>"],
143
+ "task_type": "<primary task type>",
144
+ "memories_created": ["<IDs of memories stored this session>"],
145
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
146
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
147
+ }
148
+ ```
149
+
150
+ Keep only the last 20 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
151
+
152
+ ### Step 2: Suggest Memorization (if warranted)
153
+
154
+ If the session contained meaningful content based on your ambient tracking:
155
+
108
156
  ```
109
157
  💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
110
158
  Run /brain-memorize to capture them before this context is lost.
@@ -114,7 +162,7 @@ If the session contained meaningful content in any of these categories, suggest:
114
162
  - Do NOT auto-memorize without user consent
115
163
  - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
116
164
  - Only suggest when there is genuinely valuable context worth preserving
117
- - Always save session context to `.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
165
+ - **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively
118
166
 
119
167
  ## When Recalling Memories
120
168
 
@@ -0,0 +1,524 @@
1
+ /**
2
+ * Brain Memory — Cloud Sync Engine
3
+ *
4
+ * Push/pull ~/.brain/ memories via the Brain Cloud API (api.brainmemory.work).
5
+ * Uses the device code OAuth flow for CLI authentication.
6
+ *
7
+ * Zero external dependencies — uses Node.js built-in https, fs, child_process.
8
+ */
9
+
10
+ const { execFileSync } = require('child_process');
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const os = require('os');
14
+ const https = require('https');
15
+ const http = require('http');
16
+
17
+ const CLOUD_DIR = '.cloud';
18
+ const CONFIG_FILE = 'config.json';
19
+ const DEFAULT_API_URL = 'https://api.brainmemory.work';
20
+
21
+ // Files/dirs inside ~/.brain/ that should NOT be synced
22
+ const TAR_EXCLUDES = ['.sync', '.cloud', '.DS_Store', '_archived'];
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // HTTP helpers (zero-dependency, works on Node >= 18)
26
+ // ---------------------------------------------------------------------------
27
+
28
+ /**
29
+ * Make an HTTP(S) request. Returns { status, headers, body }.
30
+ *
31
+ * @param {string} url
32
+ * @param {Object} [opts]
33
+ * @param {string} [opts.method='GET']
34
+ * @param {Object} [opts.headers]
35
+ * @param {Buffer|string} [opts.body]
36
+ * @returns {Promise<{status: number, headers: Object, body: string}>}
37
+ */
38
+ function request(url, opts = {}, _redirectCount = 0) {
39
+ return new Promise((resolve, reject) => {
40
+ if (_redirectCount > 5) return reject(new Error('Too many redirects'));
41
+
42
+ const parsed = new URL(url);
43
+ const mod = parsed.protocol === 'https:' ? https : http;
44
+ const reqOpts = {
45
+ method: opts.method || 'GET',
46
+ hostname: parsed.hostname,
47
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
48
+ path: parsed.pathname + parsed.search,
49
+ headers: opts.headers || {},
50
+ };
51
+
52
+ const req = mod.request(reqOpts, (res) => {
53
+ // Follow redirects
54
+ if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
55
+ const redirectUrl = new URL(res.headers.location, url).href;
56
+ // For 307/308, preserve method and body; for 301/302, switch to GET
57
+ const newOpts = [307, 308].includes(res.statusCode)
58
+ ? opts
59
+ : { ...opts, method: 'GET', body: undefined };
60
+ res.resume(); // drain the response
61
+ return resolve(request(redirectUrl, newOpts, _redirectCount + 1));
62
+ }
63
+
64
+ const chunks = [];
65
+ res.on('data', (chunk) => chunks.push(chunk));
66
+ res.on('end', () => {
67
+ resolve({
68
+ status: res.statusCode,
69
+ headers: res.headers,
70
+ body: Buffer.concat(chunks).toString('utf8'),
71
+ });
72
+ });
73
+ });
74
+
75
+ req.on('error', reject);
76
+ req.setTimeout(60000, () => { req.destroy(new Error('Request timed out')); });
77
+
78
+ if (opts.body) req.write(opts.body);
79
+ req.end();
80
+ });
81
+ }
82
+
83
+ /**
84
+ * JSON POST/PUT helper.
85
+ */
86
+ async function jsonRequest(url, method, data, token) {
87
+ const headers = { 'Content-Type': 'application/json' };
88
+ if (token) headers['Authorization'] = `Bearer ${token}`;
89
+ const body = data != null ? JSON.stringify(data) : undefined;
90
+ if (body) headers['Content-Length'] = Buffer.byteLength(body).toString();
91
+ const res = await request(url, { method, headers, body });
92
+ try {
93
+ return { status: res.status, data: JSON.parse(res.body) };
94
+ } catch {
95
+ throw new Error(`Non-JSON response (${res.status}) from ${method} ${url}: ${res.body.slice(0, 200)}`);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Upload a file as multipart/form-data.
101
+ */
102
+ async function uploadFile(url, filePath, token) {
103
+ const boundary = '----BrainCloudUpload' + Date.now();
104
+ const fileContent = fs.readFileSync(filePath);
105
+ const header = Buffer.from(
106
+ `--${boundary}\r\n` +
107
+ `Content-Disposition: form-data; name="brain"; filename="brain.tar.gz"\r\n` +
108
+ `Content-Type: application/gzip\r\n\r\n`
109
+ );
110
+ const footer = Buffer.from(`\r\n--${boundary}--\r\n`);
111
+ const body = Buffer.concat([header, fileContent, footer]);
112
+
113
+ return request(url, {
114
+ method: 'PUT',
115
+ headers: {
116
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
117
+ 'Content-Length': body.length.toString(),
118
+ 'Authorization': `Bearer ${token}`,
119
+ },
120
+ body,
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Download a file from URL, save to disk.
126
+ */
127
+ function downloadFile(url, destPath, token, _redirectCount = 0) {
128
+ return new Promise((resolve, reject) => {
129
+ if (_redirectCount > 5) return reject(new Error('Too many redirects'));
130
+
131
+ const parsed = new URL(url);
132
+ const mod = parsed.protocol === 'https:' ? https : http;
133
+ const reqOpts = {
134
+ method: 'GET',
135
+ hostname: parsed.hostname,
136
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
137
+ path: parsed.pathname + parsed.search,
138
+ headers: { 'Authorization': `Bearer ${token}` },
139
+ };
140
+
141
+ const req = mod.request(reqOpts, (res) => {
142
+ // Follow redirects
143
+ if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
144
+ const redirectUrl = new URL(res.headers.location, url).href;
145
+ res.resume();
146
+ return resolve(downloadFile(redirectUrl, destPath, token, _redirectCount + 1));
147
+ }
148
+
149
+ if (res.statusCode !== 200) {
150
+ const chunks = [];
151
+ res.on('data', (c) => chunks.push(c));
152
+ res.on('end', () => {
153
+ reject(new Error(`Download failed (${res.statusCode}): ${Buffer.concat(chunks).toString()}`));
154
+ });
155
+ return;
156
+ }
157
+
158
+ const ws = fs.createWriteStream(destPath);
159
+ res.pipe(ws);
160
+ ws.on('finish', () => {
161
+ ws.close();
162
+ resolve({ checksum: res.headers['x-checksum'] || null });
163
+ });
164
+ ws.on('error', reject);
165
+ });
166
+
167
+ req.on('error', reject);
168
+ req.setTimeout(300000, () => { req.destroy(new Error('Download timed out')); });
169
+ req.end();
170
+ });
171
+ }
172
+
173
+ // ---------------------------------------------------------------------------
174
+ // Config management — stored at ~/.brain/.cloud/config.json
175
+ // ---------------------------------------------------------------------------
176
+
177
+ function resolvePaths(brainDir) {
178
+ const cloudDir = path.join(brainDir, CLOUD_DIR);
179
+ const configPath = path.join(cloudDir, CONFIG_FILE);
180
+ return { cloudDir, configPath };
181
+ }
182
+
183
+ function readConfig(brainDir) {
184
+ const { configPath } = resolvePaths(brainDir);
185
+ try {
186
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+
192
+ function writeConfig(brainDir, config) {
193
+ const { cloudDir, configPath } = resolvePaths(brainDir);
194
+ fs.mkdirSync(cloudDir, { recursive: true });
195
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
196
+ }
197
+
198
+ function deleteConfig(brainDir) {
199
+ const { cloudDir } = resolvePaths(brainDir);
200
+ fs.rmSync(cloudDir, { recursive: true, force: true });
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // Token management
205
+ // ---------------------------------------------------------------------------
206
+
207
+ /**
208
+ * Get a valid access token, refreshing if needed.
209
+ *
210
+ * @param {string} brainDir
211
+ * @returns {Promise<string>} access token
212
+ */
213
+ async function getValidToken(brainDir) {
214
+ const config = readConfig(brainDir);
215
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
216
+
217
+ const now = Math.floor(Date.now() / 1000);
218
+
219
+ // Token still valid (with 30s buffer)
220
+ if (config.expires_at && now < config.expires_at - 30) {
221
+ return config.access_token;
222
+ }
223
+
224
+ // Try refresh
225
+ if (!config.refresh_token) {
226
+ throw new Error('Session expired and no refresh token. Run cloud login again.');
227
+ }
228
+
229
+ const res = await jsonRequest(
230
+ `${config.api_url}/auth/refresh`,
231
+ 'POST',
232
+ { refresh_token: config.refresh_token }
233
+ );
234
+
235
+ if (res.status !== 200) {
236
+ throw new Error('Token refresh failed. Run cloud login again.');
237
+ }
238
+
239
+ config.access_token = res.data.access_token;
240
+ config.refresh_token = res.data.refresh_token;
241
+ config.expires_at = res.data.expires_at;
242
+ writeConfig(brainDir, config);
243
+
244
+ return config.access_token;
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------
248
+ // Device code auth flow
249
+ // ---------------------------------------------------------------------------
250
+
251
+ /**
252
+ * Start the device code login flow.
253
+ * Returns the device code info so the caller can display it to the user.
254
+ *
255
+ * @param {string} apiUrl
256
+ * @returns {Promise<{device_code: string, user_code: string, verify_url: string, expires_in: number}>}
257
+ */
258
+ async function requestDeviceCode(apiUrl) {
259
+ const res = await jsonRequest(`${apiUrl}/auth/device/request`, 'POST', {});
260
+ if (res.status !== 200) {
261
+ throw new Error(`Failed to request device code: ${JSON.stringify(res.data)}`);
262
+ }
263
+ return res.data;
264
+ }
265
+
266
+ /**
267
+ * Poll for device code approval.
268
+ *
269
+ * @param {string} apiUrl
270
+ * @param {string} deviceCode
271
+ * @param {number} interval - Poll interval in ms (default 5000)
272
+ * @param {number} timeout - Max wait in ms (default 600000 = 10 min)
273
+ * @returns {Promise<{access_token: string, refresh_token: string, expires_at: number}>}
274
+ */
275
+ async function pollDeviceCode(apiUrl, deviceCode, interval = 5000, timeout = 600000) {
276
+ const deadline = Date.now() + timeout;
277
+
278
+ while (Date.now() < deadline) {
279
+ const res = await jsonRequest(`${apiUrl}/auth/device/poll`, 'POST', { device_code: deviceCode });
280
+
281
+ if (res.status === 200 && res.data.status === 'approved' && res.data.tokens) {
282
+ return res.data.tokens;
283
+ }
284
+
285
+ if (res.status === 404 || (res.data && res.data.error && res.data.error.includes('expired'))) {
286
+ throw new Error('Device code expired. Try again.');
287
+ }
288
+
289
+ // Still pending — wait and retry
290
+ await new Promise((r) => setTimeout(r, interval));
291
+ }
292
+
293
+ throw new Error('Login timed out. Try again.');
294
+ }
295
+
296
+ /**
297
+ * Full login flow: request code, poll, save config.
298
+ *
299
+ * @param {string} brainDir
300
+ * @param {string} [apiUrl]
301
+ * @returns {Promise<{user_code: string, verify_url: string, waitForApproval: () => Promise<void>}>}
302
+ */
303
+ async function login(brainDir, apiUrl) {
304
+ const url = apiUrl || DEFAULT_API_URL;
305
+ const codeInfo = await requestDeviceCode(url);
306
+
307
+ return {
308
+ user_code: codeInfo.user_code,
309
+ verify_url: codeInfo.verify_url,
310
+ expires_in: codeInfo.expires_in,
311
+ waitForApproval: async () => {
312
+ const tokens = await pollDeviceCode(url, codeInfo.device_code);
313
+
314
+ // Fetch user info + default brain
315
+ const meRes = await jsonRequest(`${url}/auth/me`, 'GET', null, tokens.access_token);
316
+ let userEmail = '';
317
+ if (meRes.status === 200 && meRes.data.user) {
318
+ userEmail = meRes.data.user.email;
319
+ }
320
+
321
+ const brainsRes = await jsonRequest(`${url}/api/brains`, 'GET', null, tokens.access_token);
322
+ let brainId = null;
323
+ if (brainsRes.status === 200 && Array.isArray(brainsRes.data) && brainsRes.data.length > 0) {
324
+ brainId = brainsRes.data[0].id;
325
+ }
326
+
327
+ writeConfig(brainDir, {
328
+ api_url: url,
329
+ access_token: tokens.access_token,
330
+ refresh_token: tokens.refresh_token,
331
+ expires_at: tokens.expires_at,
332
+ brain_id: brainId,
333
+ user_email: userEmail,
334
+ connected_at: new Date().toISOString(),
335
+ });
336
+ },
337
+ };
338
+ }
339
+
340
+ /**
341
+ * Logout — clear stored tokens.
342
+ *
343
+ * @param {string} brainDir
344
+ */
345
+ function logout(brainDir) {
346
+ deleteConfig(brainDir);
347
+ }
348
+
349
+ // ---------------------------------------------------------------------------
350
+ // Tar helpers
351
+ // ---------------------------------------------------------------------------
352
+
353
+ function packBrain(brainDir) {
354
+ const tmpFile = path.join(os.tmpdir(), `brain-upload-${Date.now()}.tar.gz`);
355
+ const excludeArgs = TAR_EXCLUDES.flatMap((e) => ['--exclude', e]);
356
+
357
+ execFileSync('tar', ['czf', tmpFile, ...excludeArgs, '-C', brainDir, '.'], {
358
+ stdio: 'pipe',
359
+ timeout: 120000,
360
+ });
361
+
362
+ return tmpFile;
363
+ }
364
+
365
+ function unpackBrain(tarPath, brainDir) {
366
+ // Extract into brain dir, overwriting existing files
367
+ execFileSync('tar', ['xzf', tarPath, '-C', brainDir], {
368
+ stdio: 'pipe',
369
+ timeout: 120000,
370
+ });
371
+ }
372
+
373
+ // ---------------------------------------------------------------------------
374
+ // Push / Pull
375
+ // ---------------------------------------------------------------------------
376
+
377
+ /**
378
+ * Push ~/.brain/ to the cloud.
379
+ *
380
+ * @param {string} brainDir
381
+ * @returns {Promise<{size_bytes: number, file_count: number, checksum: string}>}
382
+ */
383
+ async function push(brainDir) {
384
+ const config = readConfig(brainDir);
385
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
386
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
387
+
388
+ const token = await getValidToken(brainDir);
389
+
390
+ // Pack ~/.brain/ into tar.gz
391
+ const tarPath = packBrain(brainDir);
392
+
393
+ try {
394
+ const tarSize = fs.statSync(tarPath).size;
395
+ const url = `${config.api_url}/api/brains/${config.brain_id}/sync`;
396
+
397
+ const res = await uploadFile(url, tarPath, token);
398
+
399
+ if (res.status !== 200) {
400
+ const data = JSON.parse(res.body);
401
+ throw new Error(`Push failed (${res.status}): ${data.error || res.body}`);
402
+ }
403
+
404
+ const result = JSON.parse(res.body);
405
+
406
+ // Update config with last push time
407
+ config.last_push = new Date().toISOString();
408
+ writeConfig(brainDir, config);
409
+
410
+ return { ...result, local_size: tarSize };
411
+ } finally {
412
+ // Clean up temp file
413
+ try { fs.unlinkSync(tarPath); } catch { /* ignore */ }
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Pull from the cloud into ~/.brain/.
419
+ *
420
+ * @param {string} brainDir
421
+ * @returns {Promise<{size_bytes: number, checksum: string|null}>}
422
+ */
423
+ async function pull(brainDir) {
424
+ const config = readConfig(brainDir);
425
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
426
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
427
+
428
+ const token = await getValidToken(brainDir);
429
+ const url = `${config.api_url}/api/brains/${config.brain_id}/sync`;
430
+ const tmpFile = path.join(os.tmpdir(), `brain-download-${Date.now()}.tar.gz`);
431
+
432
+ try {
433
+ const { checksum } = await downloadFile(url, tmpFile, token);
434
+ const size = fs.statSync(tmpFile).size;
435
+
436
+ // Extract into ~/.brain/
437
+ unpackBrain(tmpFile, brainDir);
438
+
439
+ // Update config
440
+ config.last_pull = new Date().toISOString();
441
+ writeConfig(brainDir, config);
442
+
443
+ return { size_bytes: size, checksum };
444
+ } finally {
445
+ try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
446
+ }
447
+ }
448
+
449
+ // ---------------------------------------------------------------------------
450
+ // Status
451
+ // ---------------------------------------------------------------------------
452
+
453
+ /**
454
+ * Get cloud sync status.
455
+ *
456
+ * @param {string} brainDir
457
+ * @returns {Promise<Object>}
458
+ */
459
+ async function status(brainDir) {
460
+ const config = readConfig(brainDir);
461
+ if (!config) {
462
+ return { connected: false };
463
+ }
464
+
465
+ let brain = null;
466
+ let user = null;
467
+
468
+ try {
469
+ const token = await getValidToken(brainDir);
470
+
471
+ const meRes = await jsonRequest(`${config.api_url}/auth/me`, 'GET', null, token);
472
+ if (meRes.status === 200) {
473
+ user = meRes.data.user;
474
+ }
475
+
476
+ if (config.brain_id) {
477
+ const brainRes = await jsonRequest(
478
+ `${config.api_url}/api/brains/${config.brain_id}`,
479
+ 'GET', null, token
480
+ );
481
+ if (brainRes.status === 200) {
482
+ brain = brainRes.data;
483
+ }
484
+ }
485
+ } catch {
486
+ // Token may be expired — still report config
487
+ }
488
+
489
+ return {
490
+ connected: true,
491
+ api_url: config.api_url,
492
+ user_email: config.user_email || (user && user.email) || null,
493
+ brain_id: config.brain_id,
494
+ brain_name: brain ? brain.name : null,
495
+ brain_size: brain ? brain.size_bytes : null,
496
+ brain_files: brain ? brain.file_count : null,
497
+ last_synced: brain && brain.last_synced_at ? brain.last_synced_at : null,
498
+ last_push: config.last_push || null,
499
+ last_pull: config.last_pull || null,
500
+ connected_at: config.connected_at || null,
501
+ };
502
+ }
503
+
504
+ // ---------------------------------------------------------------------------
505
+ // Exports
506
+ // ---------------------------------------------------------------------------
507
+
508
+ module.exports = {
509
+ login,
510
+ logout,
511
+ push,
512
+ pull,
513
+ status,
514
+ readConfig,
515
+ writeConfig,
516
+ // Internal — exported for testing
517
+ requestDeviceCode,
518
+ pollDeviceCode,
519
+ getValidToken,
520
+ packBrain,
521
+ unpackBrain,
522
+ resolvePaths,
523
+ DEFAULT_API_URL,
524
+ };