brain-memory 0.1.0-beta.5 → 0.1.0-beta.7

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.
@@ -1,87 +1,62 @@
1
- # /brain:sync — Cloud Sync
1
+ # /brain:sync — Portable Sync
2
2
 
3
- You are managing cloud synchronization for the Brain Memory system. This enables manual push/pull of `.brain/` memories to Dropbox, Google Drive, or OneDrive.
3
+ You are managing synchronization for the Brain Memory system. This enables manual push/pull of `.brain/` memories via any Git remote, plus encrypted single-file export/import for portable transfers.
4
4
 
5
5
  **CRITICAL RULES:**
6
6
  - NEVER auto-sync — always require explicit user action
7
7
  - NEVER silently overwrite files — always show a preview first
8
- - NEVER display OAuth tokens, credentials, or secrets in output
9
- - ALWAYS show what will change before executing push/pull
8
+ - NEVER display passphrases or secrets in output
9
+ - ALWAYS show what will change before executing push/pull/import
10
10
 
11
11
  ## Subcommands
12
12
 
13
13
  Parse the user's input to determine the subcommand:
14
- - `login [provider]` → Setup OAuth + configure sync
15
- - `push` → Upload local changes to cloud
16
- - `pull` → Download remote changes to local
17
- - `status` → Show sync state and pending changes
18
- - `logout` → Remove credentials and disconnect
19
- - `resolve [file]` → Resolve a sync conflict
14
+ - `setup <url>` → Configure a Git remote for sync
15
+ - `push` → Commit and push local changes to remote
16
+ - `pull` → Fetch and merge remote changes to local
17
+ - `status` → Show sync state (ahead/behind)
18
+ - `export [path]` → Export .brain/ to an encrypted single file
19
+ - `import <path>` → Import from an export file
20
+ - `disconnect` → Remove sync configuration
20
21
 
21
22
  If no subcommand is given, show available subcommands.
22
23
 
23
24
  ---
24
25
 
25
- ## `/brain:sync login [provider]`
26
+ ## `/brain:sync setup <url>`
26
27
 
27
28
  ### Steps
28
29
 
29
30
  1. **Check prerequisites:**
30
31
  - Verify `.brain/` exists. If not, suggest `/brain:init` first.
32
+ - Verify `git` is available (`checkGitAvailable()` from `src/git-sync.js`).
31
33
  - Check if sync is already configured (`.brain/.sync/config.json`). If so, ask if they want to reconfigure.
32
34
 
33
- 2. **Select provider** (if not specified):
34
- - Present options: `dropbox`, `google-drive`, `onedrive`
35
- - Explain each briefly:
36
- - **Dropbox**: Simplest setup, App Folder isolation
37
- - **Google Drive**: Uses hidden appDataFolder (invisible in Drive UI)
38
- - **OneDrive**: Microsoft Graph API, App Folder isolation
39
-
40
- 3. **Get OAuth Client ID:**
41
- - Explain that Brain Memory requires the user to register their own OAuth app
42
- - Provide provider-specific instructions:
43
-
44
- **Dropbox:**
45
- - Go to https://www.dropbox.com/developers/apps
46
- - Create app → Scoped access → App folder → Name it "BrainMemory"
47
- - Under Permissions, enable: `files.metadata.read`, `files.metadata.write`, `files.content.read`, `files.content.write`
48
- - Copy the App Key (this is the client ID)
49
- - Add `http://127.0.0.1` to Redirect URIs (any port)
50
-
51
- **Google Drive:**
52
- - Go to https://console.cloud.google.com → Create project
53
- - Enable "Google Drive API"
54
- - Create OAuth 2.0 credentials → Desktop app
55
- - Copy the Client ID
56
- - Add `http://127.0.0.1` to Authorized redirect URIs
57
-
58
- **OneDrive:**
59
- - Go to https://portal.azure.com → App registrations
60
- - New registration → Personal Microsoft accounts
61
- - Add redirect URI: `http://localhost` (Mobile and desktop applications)
62
- - Copy Application (client) ID
63
-
64
- 4. **Ask for Client ID** from the user.
65
-
66
- 5. **Ask about encryption** (optional):
67
- - "Would you like to encrypt memories before uploading? (recommended for sensitive data)"
68
- - If yes, ask for a passphrase (will be needed on every push/pull and on other devices)
69
-
70
- 6. **Run OAuth flow:**
71
- - Use `setupSync()` from `src/sync/sync-engine.js`
72
- - This will open the browser for authorization
73
- - If in SSH/headless environment, offer Device Code Flow as alternative
74
-
75
- 7. **Show result:**
76
- ```
77
- ✓ Cloud sync configured!
78
- Provider: [provider]
79
- Account: [email/name]
80
- Encryption: [enabled/disabled]
81
- Remote files: [count]
35
+ 2. **Get remote URL** (if not provided):
36
+ - Ask for the Git remote URL (SSH or HTTPS).
37
+ - Auto-detect `gh` CLI: if available, offer to create a private repo with `gh repo create brain-data --private`.
38
+ - Examples:
39
+ - `git@github.com:user/brain-data.git`
40
+ - `https://github.com/user/brain-data.git`
41
+ - `git@gitlab.com:user/brain-data.git`
42
+
43
+ 3. **Ask about encryption** (optional):
44
+ - "Would you like to encrypt memories before pushing? (recommended for sensitive data)"
45
+ - If yes, ask for a passphrase (will be needed on every push/pull and on other devices).
46
+
47
+ 4. **Initialize sync:**
48
+ - Call `initSyncRepo()` and `configureRemote()` from `src/git-sync.js`.
49
+ - Write config to `.brain/.sync/config.json` via `writeSyncConfig()`.
50
+
51
+ 5. **Show result:**
52
+ ```
53
+ ✓ Git sync configured!
54
+ Remote: <remote-url>
55
+ Branch: main
56
+ Encryption: <enabled/disabled>
82
57
 
83
58
  Use /brain:sync push to upload your memories.
84
- Use /brain:sync pull to download from cloud.
59
+ Use /brain:sync pull to download from remote.
85
60
  ```
86
61
 
87
62
  ---
@@ -90,32 +65,28 @@ If no subcommand is given, show available subcommands.
90
65
 
91
66
  ### Steps
92
67
 
93
- 1. **Check sync is configured.** If not, suggest `/brain:sync login`.
68
+ 1. **Check sync is configured.** If not, suggest `/brain:sync setup`.
94
69
 
95
- 2. **Preview changes** (always show before executing):
96
- - Use `push()` with `{ dryRun: true }` from `src/sync/sync-engine.js`
70
+ 2. **Preview changes:**
71
+ - Call `getStatus()` from `src/git-sync.js`.
97
72
  - Display summary:
98
73
  ```
99
74
  📤 Push Preview:
100
- Upload: [count] files ([new] new, [modified] modified)
101
- Delete: [count] files (deleted locally)
102
- Skip: [count] unchanged
103
- ⚠️ Conflicts: [count] (modified both locally and remotely)
75
+ Remote: <remote-url>
76
+ Status: <ahead> commits ahead, <behind> behind
104
77
  ```
105
- - If there are conflicts, list them and explain options
78
+ - If behind > 0, warn: "Remote has newer changes. Consider pulling first."
106
79
 
107
80
  3. **Ask for confirmation** before proceeding.
108
81
 
109
82
  4. **Execute push:**
110
- - Use `push()` from `src/sync/sync-engine.js`
111
- - Show progress for each file
112
- - Show final results:
83
+ - If encryption is enabled, ask for passphrase.
84
+ - Call `push()` from `src/git-sync.js`.
85
+ - Show result:
113
86
  ```
114
87
  ✓ Push complete!
115
- Uploaded: [count] files
116
- Deleted: [count] files
117
- Conflicts: [count] (use /brain:sync resolve to fix)
118
- Errors: [count]
88
+ Committed: <message>
89
+ Remote: <remote-url>
119
90
  ```
120
91
 
121
92
  ---
@@ -126,28 +97,23 @@ If no subcommand is given, show available subcommands.
126
97
 
127
98
  1. **Check sync is configured.**
128
99
 
129
- 2. **Preview changes** (always show before executing):
130
- - Use `pull()` with `{ dryRun: true }`
131
- - Display summary:
100
+ 2. **Preview:**
101
+ - Call `getStatus()` to show ahead/behind count.
132
102
  ```
133
103
  📥 Pull Preview:
134
- Download: [count] files ([new] new, [modified] modified)
135
- Delete: [count] files (deleted remotely)
136
- Skip: [count] unchanged
137
- ⚠️ Conflicts: [count]
104
+ Remote: <remote-url>
105
+ Status: <behind> new commits to pull
138
106
  ```
139
107
 
140
108
  3. **Ask for confirmation.**
141
109
 
142
110
  4. **Execute pull:**
143
- - Use `pull()` from `src/sync/sync-engine.js`
144
- - Show results:
111
+ - If encryption is enabled, ask for passphrase.
112
+ - Call `pull()` from `src/git-sync.js`.
113
+ - Show result:
145
114
  ```
146
115
  ✓ Pull complete!
147
- Downloaded: [count] files
148
- Deleted: [count] files
149
- Conflicts: [count]
150
- Errors: [count]
116
+ Updated <count> files from remote.
151
117
  ```
152
118
 
153
119
  ---
@@ -156,65 +122,101 @@ If no subcommand is given, show available subcommands.
156
122
 
157
123
  ### Steps
158
124
 
159
- 1. **Read sync status** using `syncStatus()` from `src/sync/sync-engine.js`
125
+ 1. **Read sync config** using `getSyncConfig()` from `src/git-sync.js`.
160
126
 
161
127
  2. **Display dashboard:**
162
128
  ```
163
- ☁️ Cloud Sync Status
129
+ 🔄 Sync Status
164
130
  ─────────────────────
165
- Provider: [provider]
166
- Account: [account]
167
- Connected: [yes/no]
168
- Encryption: [enabled/disabled]
169
- Last Sync: [timestamp or "never"]
170
- Tracked Files: [count]
171
- Pending Changes:[count] local files modified since last sync
172
-
173
- Conflicts: [count]
174
- [list conflict files if any]
131
+ Remote: <remote-url or "not configured">
132
+ Branch: <branch>
133
+ Encryption: <enabled/disabled>
134
+ Last Push: <timestamp or "never">
135
+ Last Pull: <timestamp or "never">
136
+ Ahead: <count> commits
137
+ Behind: <count> commits
175
138
  ```
176
139
 
177
140
  ---
178
141
 
179
- ## `/brain:sync logout`
142
+ ## `/brain:sync export [path]`
180
143
 
181
144
  ### Steps
182
145
 
183
- 1. **Show current config** (provider, account).
184
- 2. **Ask for confirmation:** "This will remove stored credentials. Your cloud data will NOT be deleted."
185
- 3. **Execute:** Use `logout()` from `src/sync/sync-engine.js`
186
- 4. **Confirm:** "✓ Logged out from [provider]. Credentials removed."
146
+ 1. **Determine output path:**
147
+ - Default: `.brain-export` in the current directory.
148
+ - User can specify a custom path.
149
+
150
+ 2. **Ask about encryption:**
151
+ - "Would you like to encrypt the export? (recommended)"
152
+ - If yes, ask for a passphrase.
153
+
154
+ 3. **Execute export:**
155
+ - Call `exportBrain()` from `src/export-import.js`.
156
+ - Show result:
157
+ ```
158
+ ✓ Brain exported!
159
+ File: <output-path>
160
+ Memories: <count> files packed
161
+ Encrypted: <yes/no>
162
+ Size: <file-size>
163
+
164
+ Transfer this file to another machine and run /brain:sync import <path>
165
+ ```
187
166
 
188
167
  ---
189
168
 
190
- ## `/brain:sync resolve [file]`
169
+ ## `/brain:sync import <path>`
191
170
 
192
171
  ### Steps
193
172
 
194
- 1. **List conflicts** if no file specified using `listConflicts()`.
173
+ 1. **Preview the import:**
174
+ - Call `previewImport()` from `src/export-import.js`.
175
+ - Display:
176
+ ```
177
+ 📦 Import Preview:
178
+ File: <path>
179
+ Exported at: <date>
180
+ Total files: <count>
181
+ New: <count> (will be created)
182
+ Existing: <count> (will be overwritten)
183
+ ```
195
184
 
196
- 2. **For a specific file:**
197
- - Show the conflict details (reason, local hash, remote hash)
198
- - Present resolution options:
199
- - **keep-local**: Push your local version (overwrites remote)
200
- - **keep-remote**: Pull the remote version (overwrites local)
201
- - **keep-both**: Save local as `filename.local.ext`, pull remote as `filename.ext`
185
+ 2. **Ask for import mode:**
186
+ - **Overwrite** (default): Replace all matching files with the imported versions.
187
+ - **Merge**: Only import files newer than local versions.
202
188
 
203
- 3. **Execute resolution** using `resolveConflict()` from `src/sync/sync-engine.js`
189
+ 3. **If encrypted, ask for passphrase.**
204
190
 
205
- 4. **Show result:**
191
+ 4. **Ask for confirmation.**
192
+
193
+ 5. **Execute import:**
194
+ - Call `importBrain()` from `src/export-import.js`.
195
+ - Show result:
206
196
  ```
207
- ✓ Conflict resolved for [file]
208
- Action: [description]
197
+ ✓ Import complete!
198
+ Imported: <count> files
199
+ Skipped: <count> (merge mode, local was newer)
209
200
  ```
210
201
 
211
202
  ---
212
203
 
204
+ ## `/brain:sync disconnect`
205
+
206
+ ### Steps
207
+
208
+ 1. **Show current config** (remote URL).
209
+ 2. **Ask for confirmation:** "This will remove sync configuration. Your remote data will NOT be deleted."
210
+ 3. **Remove `.brain/.sync/` directory.**
211
+ 4. **Confirm:** "✓ Sync disconnected. Remote repository is untouched."
212
+
213
+ ---
214
+
213
215
  ## Key Implementation Notes
214
216
 
215
- - All sync functions are in `src/sync/sync-engine.js`
216
- - Crypto utilities in `src/sync/crypto-utils.js`
217
- - OAuth in `src/sync/oauth.js`
218
- - Provider implementations in `src/sync/providers/`
219
- - Sync state stored in `.brain/.sync/` (never synced to cloud)
220
- - Uses three-way diff: local state vs remote state vs last-known sync state
217
+ - Git sync engine: `src/git-sync.js`
218
+ - Export/import: `src/export-import.js`
219
+ - Crypto utilities: `src/crypto.js`
220
+ - Sync config stored in `.brain/.sync/config.json` (local only)
221
+ - Hidden git repo at `.brain/.sync/repo/` — never interferes with the project's own git
222
+ - All git operations use `execFileSync` — no npm dependencies
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.5",
3
+ "version": "0.1.0-beta.7",
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",
@@ -40,7 +40,7 @@
40
40
  "url": "git+https://github.com/onurkarali/brain.git"
41
41
  },
42
42
  "scripts": {
43
- "test": "node --test test/index-manager.test.js test/scorer.test.js test/functional.test.js test/sunshine.test.js test/stress.test.js test/oauth.test.js test/sync-provider.test.js test/sync-engine.test.js test/install.test.js test/prompts.test.js",
43
+ "test": "node --test test/index-manager.test.js test/scorer.test.js test/functional.test.js test/sunshine.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js",
44
44
  "prerelease": "npm test",
45
45
  "release:beta": "npm version prerelease --preid beta && npm publish --tag beta && npm dist-tag add brain-memory@$(node -p \"require('./package.json').version\") latest",
46
46
  "release:patch": "npm version patch && npm publish",
package/prompts/claude.md CHANGED
@@ -58,7 +58,7 @@ Memories store their encoding context (project, topics, task type). During recal
58
58
  - `/brain:sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
59
59
  - `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
60
60
  - `/brain:status` — Dashboard with brain health overview
61
- - `/brain:sync [subcommand]` — Cloud sync: push/pull memories to Dropbox, Google Drive, or OneDrive
61
+ - `/brain:sync [subcommand]` — Sync memories via Git remote or export/import for portability
62
62
 
63
63
  ## Session Start Behavior
64
64
 
@@ -123,6 +123,11 @@ When the user asks you to "remember" something, or when context from past sessio
123
123
  6. Strengthen Hebbian links between co-retrieved memories
124
124
  7. If no active matches, search the archive (`.brain/_archived/`)
125
125
 
126
- ## Cloud Sync
126
+ ## Portable Sync
127
127
 
128
- Brain memories can be synced across devices via `/brain:sync`. Supports Dropbox, Google Drive, and OneDrive with optional AES-256-GCM encryption. Sync is always manual (push/pull) — never automatic. Run `/brain:sync login` to set up, then use `/brain:sync push` and `/brain:sync pull` to keep memories in sync.
128
+ Brain memories can be synced across devices in two ways:
129
+
130
+ 1. **Git remote** — Push/pull `.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain:sync setup <url>` to configure, then use `/brain:sync push` and `/brain:sync pull`.
131
+ 2. **Export/Import** — Pack the entire `.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
132
+
133
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/prompts/gemini.md CHANGED
@@ -59,7 +59,7 @@ Commands are available via `/brain:` prefix:
59
59
  - `/brain:sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
60
60
  - `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
61
61
  - `/brain:status` — Dashboard with brain health overview
62
- - `/brain:sync [subcommand]` — Cloud sync: push/pull memories to Dropbox, Google Drive, or OneDrive
62
+ - `/brain:sync [subcommand]` — Sync memories via Git remote or export/import for portability
63
63
 
64
64
  ## Session Start Behavior
65
65
 
@@ -124,6 +124,11 @@ When the user asks you to "remember" something, or when context from past sessio
124
124
  6. Strengthen Hebbian links between co-retrieved memories
125
125
  7. If no active matches, search the archive (`.brain/_archived/`)
126
126
 
127
- ## Cloud Sync
127
+ ## Portable Sync
128
128
 
129
- Brain memories can be synced across devices via `/brain:sync`. Supports Dropbox, Google Drive, and OneDrive with optional AES-256-GCM encryption. Sync is always manual (push/pull) — never automatic. Run `/brain:sync login` to set up, then use `/brain:sync push` and `/brain:sync pull` to keep memories in sync.
129
+ Brain memories can be synced across devices in two ways:
130
+
131
+ 1. **Git remote** — Push/pull `.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain:sync setup <url>` to configure, then use `/brain:sync push` and `/brain:sync pull`.
132
+ 2. **Export/Import** — Pack the entire `.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
133
+
134
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/prompts/openai.md CHANGED
@@ -59,7 +59,7 @@ Brain skills are available via `/brain-` prefix:
59
59
  - `/brain-sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
60
60
  - `/brain-sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
61
61
  - `/brain-status` — Dashboard with brain health overview
62
- - `/brain-sync [subcommand]` — Cloud sync: push/pull memories to Dropbox, Google Drive, or OneDrive
62
+ - `/brain-sync [subcommand]` — Sync memories via Git remote or export/import for portability
63
63
 
64
64
  ## Session Start Behavior
65
65
 
@@ -124,6 +124,11 @@ When the user asks you to "remember" something, or when context from past sessio
124
124
  6. Strengthen Hebbian links between co-retrieved memories
125
125
  7. If no active matches, search the archive (`.brain/_archived/`)
126
126
 
127
- ## Cloud Sync
127
+ ## Portable Sync
128
128
 
129
- Brain memories can be synced across devices via `/brain-sync`. Supports Dropbox, Google Drive, and OneDrive with optional AES-256-GCM encryption. Sync is always manual (push/pull) — never automatic. Run `/brain-sync login` to set up, then use `/brain-sync push` and `/brain-sync pull` to keep memories in sync.
129
+ Brain memories can be synced across devices in two ways:
130
+
131
+ 1. **Git remote** — Push/pull `.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain-sync setup <url>` to configure, then use `/brain-sync push` and `/brain-sync pull`.
132
+ 2. **Export/Import** — Pack the entire `.brain/` into a single portable file for manual transfer. Run `/brain-sync export` and `/brain-sync import <path>`.
133
+
134
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
@@ -1,18 +1,11 @@
1
1
  /**
2
2
  * Brain Memory — Crypto Utilities
3
3
  *
4
- * AES-256-GCM encryption for sync credentials and file content.
4
+ * AES-256-GCM encryption for memory export/import and encrypted sync.
5
5
  * Zero external dependencies — uses only Node.js built-in crypto.
6
6
  */
7
7
 
8
8
  const crypto = require('crypto');
9
- const fs = require('fs');
10
- const path = require('path');
11
- const os = require('os');
12
- const { getBrainDir } = require('../index-manager');
13
-
14
- const SYNC_DIR = '.sync';
15
- const CREDENTIALS_FILE = 'credentials.enc';
16
9
 
17
10
  const PBKDF2_ITERATIONS = 100000;
18
11
  const PBKDF2_DIGEST = 'sha512';
@@ -32,17 +25,6 @@ function deriveKey(passphrase, salt) {
32
25
  return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
33
26
  }
34
27
 
35
- /**
36
- * Generate a machine-specific identifier (convenience default, not strong security).
37
- * SHA-256 of hostname + username.
38
- *
39
- * @returns {string} Hex-encoded machine identifier
40
- */
41
- function getMachineIdentifier() {
42
- const data = `${os.hostname()}:${os.userInfo().username}`;
43
- return crypto.createHash('sha256').update(data).digest('hex');
44
- }
45
-
46
28
  /**
47
29
  * Encrypt a UTF-8 string with AES-256-GCM.
48
30
  *
@@ -73,7 +55,7 @@ function encrypt(plaintext, passphrase) {
73
55
  * @throws {Error} If passphrase is wrong or data is tampered
74
56
  */
75
57
  function decrypt(encrypted, passphrase) {
76
- if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH + 1) {
58
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
77
59
  throw new Error('Invalid encrypted data: too short');
78
60
  }
79
61
 
@@ -90,11 +72,11 @@ function decrypt(encrypted, passphrase) {
90
72
  }
91
73
 
92
74
  /**
93
- * Encrypt a Buffer with AES-256-GCM (for file content before upload).
75
+ * Encrypt a Buffer with AES-256-GCM.
94
76
  *
95
77
  * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
96
78
  *
97
- * @param {Buffer} buffer - Raw file content
79
+ * @param {Buffer} buffer - Raw buffer to encrypt
98
80
  * @param {string} passphrase - Passphrase
99
81
  * @returns {Buffer} Encrypted buffer
100
82
  */
@@ -135,81 +117,12 @@ function decryptBuffer(encrypted, passphrase) {
135
117
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
136
118
  }
137
119
 
138
- /**
139
- * Get the path to the .sync directory.
140
- *
141
- * @param {string} [projectRoot] - Project root directory
142
- * @returns {string} Absolute path to .brain/.sync/
143
- */
144
- function getSyncDir(projectRoot) {
145
- return path.join(getBrainDir(projectRoot), SYNC_DIR);
146
- }
147
-
148
- /**
149
- * Save OAuth tokens encrypted to .brain/.sync/credentials.enc.
150
- * Sets file permissions to 0600 (owner read/write only).
151
- *
152
- * @param {Object} tokens - OAuth tokens to store
153
- * @param {string} [projectRoot] - Project root directory
154
- * @param {string} [passphrase] - Passphrase (defaults to machine identifier)
155
- */
156
- function saveCredentials(tokens, projectRoot, passphrase) {
157
- const syncDir = getSyncDir(projectRoot);
158
- fs.mkdirSync(syncDir, { recursive: true });
159
-
160
- const pass = passphrase || getMachineIdentifier();
161
- const encrypted = encrypt(JSON.stringify(tokens), pass);
162
- const credPath = path.join(syncDir, CREDENTIALS_FILE);
163
-
164
- fs.writeFileSync(credPath, encrypted);
165
- try {
166
- fs.chmodSync(credPath, 0o600);
167
- } catch {
168
- // chmod may not be supported on all platforms
169
- }
170
- }
171
-
172
- /**
173
- * Load and decrypt OAuth tokens from .brain/.sync/credentials.enc.
174
- *
175
- * @param {string} [projectRoot] - Project root directory
176
- * @param {string} [passphrase] - Passphrase (defaults to machine identifier)
177
- * @returns {Object|null} Decrypted tokens or null if file doesn't exist
178
- * @throws {Error} If passphrase is wrong
179
- */
180
- function loadCredentials(projectRoot, passphrase) {
181
- const credPath = path.join(getSyncDir(projectRoot), CREDENTIALS_FILE);
182
- if (!fs.existsSync(credPath)) return null;
183
-
184
- const pass = passphrase || getMachineIdentifier();
185
- const encrypted = fs.readFileSync(credPath);
186
- return JSON.parse(decrypt(encrypted, pass));
187
- }
188
-
189
- /**
190
- * Delete stored credentials.
191
- *
192
- * @param {string} [projectRoot] - Project root directory
193
- */
194
- function deleteCredentials(projectRoot) {
195
- const credPath = path.join(getSyncDir(projectRoot), CREDENTIALS_FILE);
196
- if (fs.existsSync(credPath)) {
197
- fs.unlinkSync(credPath);
198
- }
199
- }
200
-
201
120
  module.exports = {
202
121
  deriveKey,
203
- getMachineIdentifier,
204
122
  encrypt,
205
123
  decrypt,
206
124
  encryptBuffer,
207
125
  decryptBuffer,
208
- getSyncDir,
209
- saveCredentials,
210
- loadCredentials,
211
- deleteCredentials,
212
- // Expose constants for testing
213
126
  PBKDF2_ITERATIONS,
214
127
  SALT_LENGTH,
215
128
  IV_LENGTH,