brain-memory 0.1.0-beta.2 → 0.1.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +270 -72
  2. package/assets/icon.png +0 -0
  3. package/assets/icon.svg +27 -0
  4. package/bin/brain.js +111 -0
  5. package/bin/cloud-sync.js +149 -0
  6. package/bin/install.js +217 -242
  7. package/bin/memorize.js +433 -0
  8. package/bin/pin.js +44 -0
  9. package/bin/recall.js +237 -0
  10. package/bin/reinforce.js +187 -0
  11. package/bin/session-start.js +292 -0
  12. package/bin/skill.js +67 -0
  13. package/bin/unpin.js +38 -0
  14. package/commands/brain/consolidate.md +7 -2
  15. package/commands/brain/explore.md +7 -2
  16. package/commands/brain/forget.md +7 -2
  17. package/commands/brain/init.md +8 -12
  18. package/commands/brain/memorize.md +76 -144
  19. package/commands/brain/pin.md +37 -0
  20. package/commands/brain/remember.md +48 -105
  21. package/commands/brain/review.md +7 -2
  22. package/commands/brain/skills.md +60 -0
  23. package/commands/brain/sleep.md +68 -27
  24. package/commands/brain/status.md +19 -5
  25. package/commands/brain/sunshine.md +18 -13
  26. package/commands/brain/sync.md +360 -0
  27. package/commands/brain/unpin.md +26 -0
  28. package/package.json +18 -8
  29. package/prompts/claude.md +115 -12
  30. package/prompts/gemini.md +115 -12
  31. package/prompts/openai.md +113 -10
  32. package/prompts/opencode.md +178 -0
  33. package/src/cloud-sync.js +524 -0
  34. package/src/crypto.js +130 -0
  35. package/src/export-import.js +185 -0
  36. package/src/git-sync.js +444 -0
  37. package/src/index-manager.js +205 -18
  38. package/src/installer.js +384 -0
  39. package/src/pinning.js +124 -0
  40. package/src/scorer.js +6 -2
  41. package/src/skills.js +208 -0
  42. package/src/tfidf.js +408 -0
  43. package/hooks/session-end.md +0 -48
  44. package/hooks/session-start.md +0 -48
@@ -1,6 +1,11 @@
1
+ ---
2
+ description: Full maintenance cycle: replay, homeostasis, consolidation, pruning, dreaming
3
+ argument-hint: "[scope]"
4
+ ---
5
+
1
6
  # /brain:sleep — Overnight Memory Reorganization
2
7
 
3
- You are performing a **sleep cycle** on the Brain Memory system. Just like the human brain during sleep — where the hippocampus replays recent experiences and the neocortex reorganizes them into long-term structured knowledge — this command restructures, consolidates, prunes, and deepens the `.brain/` hierarchy.
8
+ You are performing a **sleep cycle** on the Brain Memory system. Just like the human brain during sleep — where the hippocampus replays recent experiences and the neocortex reorganizes them into long-term structured knowledge — this command restructures, consolidates, prunes, and deepens the `~/.brain/` hierarchy.
4
9
 
5
10
  **Scope:** $ARGUMENTS
6
11
 
@@ -12,37 +17,20 @@ Sleep performs nine phases, mimicking real neuroscience:
12
17
  2. **Synaptic Homeostasis** — Proportionally scale down all strengths to prevent inflation (Tononi & Cirelli SHY)
13
18
  3. **Knowledge Propagation** — Evaluate recent memories against the hierarchy and update related memories
14
19
  4. **Semantic Crystallization** — Extract generalizable knowledge from frequently-recalled episodic memories
20
+ - **4b. Procedural Crystallization** — Distill repeated procedures into reusable skills (CoALA Phase 3)
15
21
  5. **Reorganize** — Detect flat clusters and restructure into deeper sub-categories
16
22
  6. **Consolidate** — Merge weak related memories into stronger combined knowledge
17
- 7. **Prune** — Archive memories that have decayed beyond recovery
23
+ 7. **Prune** — Archive memories that have decayed beyond recovery, including context-shift obsolescence (Tier B §10.1)
18
24
  8. **REM Dreaming** — Discover creative cross-domain associations via analogical reasoning
19
25
  9. **Expertise Detection** — Identify dense knowledge areas and generate expertise profiles
20
26
 
21
- ### Migration Phase (Phase 0)
22
-
23
- If the brain's `index.json` has `version: 1` (pre-v2), run migration first:
24
-
25
- 1. Create `associations.json` from existing `related` fields — for each memory with `related` entries, create edges with weight 0.20 and origin `manual`
26
- 2. Auto-discover associations: for any two memories sharing 2+ tags, create edges with weight 0.10 and origin `tag_overlap`
27
- 3. Create `contexts.json` with `{"version": 1, "sessions": []}`
28
- 4. Create `review-queue.json` with `{"version": 1, "items": []}`
29
- 5. Create `_archived/index.json` if not present with `{"version": 1, "archived_count": 0, "memories": {}}`
30
- 6. For each memory: backfill `recall_history` from `access_count` (if `access_count > 0`, set `recall_history: [last_accessed]`; otherwise `recall_history: []`)
31
- 7. Set defaults for missing fields: `cognitive_type: "semantic"`, `salience: 0.5`, `confidence: 0.8`
32
- 8. Update both memory files (frontmatter) and `index.json` entries
33
- 9. Set `index.json` version to 2
34
-
35
- Present migration summary, then proceed to Phase 1.
36
-
37
- ---
38
-
39
27
  ## Phase 1: Replay (Hippocampal Scan)
40
28
 
41
29
  During sleep, the hippocampus replays the day's events. Here, we scan and assess the full brain state.
42
30
 
43
31
  ### Steps
44
32
 
45
- 1. Read `.brain/index.json` to load all memories
33
+ 1. Read `~/.brain/index.json` to load all memories
46
34
  2. If $ARGUMENTS specifies a category path, limit scope to that subtree. Otherwise, process the entire brain.
47
35
  3. For **every** memory, compute the current decayed strength:
48
36
 
@@ -51,6 +39,8 @@ days_elapsed = (now - last_accessed) / (1000 * 60 * 60 * 24)
51
39
  decayed_strength = strength * (decay_rate ^ days_elapsed)
52
40
  ```
53
41
 
42
+ **Decay-exempt memories (CoALA Phase 1):** if a memory is `pinned` or `stable`, its `decayed_strength` equals its raw `strength` (it never fades). Treat such memories as **Strong** regardless of elapsed time.
43
+
54
44
  4. Categorize each memory into tiers:
55
45
  - **Strong** (decayed_strength >= 0.6) — healthy, no action needed
56
46
  - **Moderate** (0.3 <= decayed_strength < 0.6) — consolidation candidates
@@ -96,7 +86,7 @@ Based on Tononi & Cirelli's **Synaptic Homeostasis Hypothesis (SHY)** — during
96
86
  scaling_factor = max(0.85, 0.5 / mean_effective_strength)
97
87
  ```
98
88
 
99
- 3. For every memory: `strength = strength * scaling_factor`
89
+ 3. For every memory: `strength = strength * scaling_factor` — **except** `pinned` or `stable` memories, which are exempt from homeostatic downscaling (their strength is never altered).
100
90
 
101
91
  4. Selectively re-boost important memories:
102
92
  - **High salience** (salience >= 0.7): +0.05
@@ -282,6 +272,47 @@ Approve crystallizations? [all / select / skip]
282
272
 
283
273
  ---
284
274
 
275
+ ## Phase 4b: Procedural Crystallization (Episodic → Procedural) — CoALA Phase 3
276
+
277
+ Beyond abstracting *principles* (Phase 4), the brain also turns repeated *procedures* into skills. When the same kind of task has been solved the same way several times, distill it into a reusable `SKILL.md` — Brain's genuine value-add over CoALA, which only describes hand-authored skills.
278
+
279
+ ### Steps
280
+
281
+ 1. Cluster `procedural`/`experience` memories by tag overlap + association edges (the same clustering used elsewhere). Look for a recurring *task-solving procedure* represented across **≥ N similar memories** (default N = 3).
282
+
283
+ 2. For each qualifying cluster, evaluate: **is there a repeatable, step-by-step procedure here that would help on a future task?**
284
+
285
+ 3. If yes, draft a skill (do not write silently — propose it):
286
+ - `name`: a short kebab-case slug
287
+ - `description`: one matchable line (~100 tokens) — the L0 advertisement
288
+ - `triggers`: phrases that should surface it
289
+ - body: the step-by-step instructions, drawn from the source memories
290
+ - Create it with `brain skill add` once approved.
291
+
292
+ 4. Link the new skill to its source memories (note the skill name in their `related`/notes).
293
+
294
+ **Example:**
295
+ - 3× episodic: "set up Cloudflare Worker + D1 for project X / Y / Z" solved the same way
296
+ - → Skill `deploy-cloudflare-worker-d1`: the distilled step list.
297
+
298
+ Present proposals for user approval (never auto-create):
299
+
300
+ ```
301
+ ## Phase 4b: Procedural Crystallization
302
+
303
+ Found <N> recurring procedures ready to become skills:
304
+
305
+ 🛠️ Pattern seen 3× across {projX, projY, projZ}
306
+ → Proposed skill: "deploy-cloudflare-worker-d1"
307
+ Triggers: "deploy worker", "set up D1"
308
+
309
+ Approve skill creation? [all / select / skip]
310
+ ```
311
+
312
+ These crystallized skills are *hypotheses*: their strength/demotion feedback (`brain skill use [--failed]`) validates or retires them over time.
313
+
314
+ ---
315
+
285
316
  ## Phase 5: Reorganize (Neocortical Restructuring)
286
317
 
287
318
  During sleep, the brain transfers memories from the hippocampus to the neocortex, organizing them into structured long-term storage. This phase detects **flat clusters** — directories with many memories that should be organized into deeper sub-categories.
@@ -345,7 +376,7 @@ During deep sleep, the brain merges related experiences into generalized knowled
345
376
 
346
377
  5. For approved consolidations:
347
378
  - Write consolidated memory files using the standard format with `type: consolidated`
348
- - Archive source memories to `.brain/_archived/` and add them to `_archived/index.json`
379
+ - Archive source memories to `~/.brain/_archived/` and add them to `_archived/index.json`
349
380
  - Transfer association edges from source memories to the consolidated memory in `associations.json`
350
381
  - Update `index.json` and `_meta.json` files
351
382
 
@@ -355,21 +386,32 @@ During deep sleep, the brain merges related experiences into generalized knowled
355
386
 
356
387
  During sleep, the brain prunes weak synaptic connections to maintain efficiency. Here, we archive memories that have faded beyond usefulness.
357
388
 
389
+ ### Obsolescence / context-shift detection (Tier B §10.1)
390
+
391
+ Decay handles *slow fade*; this catches *abrupt relevance loss*. A memory cluster can become obsolete overnight (the user changed jobs, abandoned a project, switched stacks) while still carrying high strength — so decay alone never retires it.
392
+
393
+ - Read `~/.brain/contexts.json`. Identify any `encoding_context.project` (or role/domain) that appears in older memories but has been **absent from the last N sessions** (default N = 10).
394
+ - Flag the affected cluster (by project + association edges) as **candidate-obsolete** — these become *additional* archive candidates below.
395
+ - **Never** flag `pinned` memories (an explicit, active user choice). `stable` memories *can* be flagged — stability exempts from decay, not from obsolescence (a timeless fact about a former employer is still obsolete).
396
+ - This is reversible: candidates are *archived* (recoverable from `_archived/`), never erased, and only after user confirmation.
397
+
358
398
  ### Steps
359
399
 
360
- 1. Take all **Fading** tier memories (decayed_strength < 0.1) that were NOT already consolidated in Phase 6
400
+ 1. Take all **Fading** tier memories (decayed_strength < 0.1) that were NOT already consolidated in Phase 6 — plus any **candidate-obsolete** clusters from the detection step above
361
401
 
362
402
  2. **Salience protection**: Memories with `salience >= 0.7` are NEVER auto-pruned, regardless of strength. Skip them with a note:
363
403
  ```
364
404
  ⚡ Skipping <title> — high salience (0.8) protects from auto-pruning
365
405
  ```
366
406
 
367
- 3. Present the prune list (excluding salience-protected memories)
407
+ **Pinned/stable protection (CoALA Phase 1):** `pinned` or `stable` memories are also NEVER pruned or archived — they are decay-exempt, so they never reach the Fading tier in the first place. Skip them too.
408
+
409
+ 3. Present the prune list (excluding salience- and pin/stable-protected memories)
368
410
 
369
411
  4. Get user approval (default: archive all)
370
412
 
371
413
  5. Execute:
372
- - Move to `.brain/_archived/`, preserving directory structure
414
+ - Move to `~/.brain/_archived/`, preserving directory structure
373
415
  - Add to `_archived/index.json` with original metadata
374
416
  - Remove from `index.json` and update `_meta.json` files
375
417
  - Remove association edges involving pruned memories from `associations.json`
@@ -532,4 +574,3 @@ After all phases complete, present a comprehensive sleep report:
532
574
  7. **Idempotent expertise** — if `_expertise.md` already exists, update it rather than creating a duplicate.
533
575
  8. **Skip empty phases** — if there's nothing to do in a phase (e.g., no flat clusters to reorganize), briefly note it and move on.
534
576
  9. **Salience protection** — never auto-prune memories with salience >= 0.7.
535
- 10. **Run migration** — if `index.json` version is 1, run Phase 0 migration before proceeding.
@@ -1,3 +1,7 @@
1
+ ---
2
+ description: Dashboard with brain health overview
3
+ ---
4
+
1
5
  # /brain:status — Brain Overview Dashboard
2
6
 
3
7
  You are displaying a comprehensive overview of the Brain Memory system's current state.
@@ -6,12 +10,13 @@ You are displaying a comprehensive overview of the Brain Memory system's current
6
10
 
7
11
  ### 1. Read Brain State
8
12
 
9
- Read `.brain/index.json` to get the full memory inventory. If `.brain/` doesn't exist, inform the user and suggest running `/brain:init`.
13
+ Read `~/.brain/index.json` to get the full memory inventory. If `~/.brain/` doesn't exist, inform the user and suggest running `/brain:init`.
10
14
 
11
15
  Also read (if they exist):
12
- - `.brain/associations.json` — for association network stats
13
- - `.brain/review-queue.json` — for review schedule info
14
- - `.brain/_archived/index.json` — for archive stats
16
+ - `~/.brain/associations.json` — for association network stats
17
+ - `~/.brain/review-queue.json` — for review schedule info
18
+ - `~/.brain/_archived/index.json` — for archive stats
19
+ - `~/.brain/.sync/config.json` — for git sync configuration
15
20
 
16
21
  ### 2. Compute Statistics
17
22
 
@@ -104,6 +109,14 @@ Calculate aggregate stats:
104
109
  + <title> (<path>) — <date>
105
110
  + <title> (<path>) — <date>
106
111
  ...
112
+
113
+ ## Sync
114
+ Remote: <remote URL or "not configured">
115
+ Encryption: <enabled/disabled>
116
+ Last Push: <timestamp or "never">
117
+ Last Pull: <timestamp or "never">
118
+ Ahead: <count> commits
119
+ Behind: <count> commits
107
120
  ```
108
121
 
109
122
  ### 4. Health Check
@@ -119,4 +132,5 @@ Analyze the brain's health and provide recommendations:
119
132
  - **"Needs sleep"** — Multiple flat clusters detected, OR many memories in moderate/weak tiers, OR no `_expertise.md` profiles exist despite having 10+ memories. Suggest `/brain:sleep`
120
133
  - **"Low confidence"** — More than 30% of memories have confidence < 0.5. Suggest reviewing and validating uncertain memories.
121
134
  - **"Review overdue"** — More than 10 memories are past their review date. Suggest `/brain:review`
122
- - **"Needs migration"** — Brain is v1 and needs upgrade. Suggest `/brain:sleep` to trigger migration.
135
+ - **"Sync available"** — Git sync is not configured. Suggest `/brain:sync setup` for cross-device access.
136
+ - **"Sync stale"** — Last push was more than 7 days ago. Suggest `/brain:sync push`.
@@ -1,6 +1,11 @@
1
+ ---
2
+ description: Deep forensic erasure — trace and remove all references to a memory
3
+ argument-hint: "[target]"
4
+ ---
5
+
1
6
  # /brain:sunshine — Deep Forensic Memory Erasure
2
7
 
3
- You are performing **deep forensic erasure** on a memory in the Brain Memory system. Like the procedure in *Eternal Sunshine of the Spotless Mind*, this command doesn't just delete a memory — it traces every ripple that memory left across the entire `.brain/` tree and surgically removes or repairs each one. When complete, it's as if the memory never existed.
8
+ You are performing **deep forensic erasure** on a memory in the Brain Memory system. Like the procedure in *Eternal Sunshine of the Spotless Mind*, this command doesn't just delete a memory — it traces every ripple that memory left across the entire `~/.brain/` tree and surgically removes or repairs each one. When complete, it's as if the memory never existed.
4
9
 
5
10
  Use this for erasing accidentally stored credentials, removing knowledge of a deprecated anti-pattern that leaked into other memories, or cleaning up after a fully reversed technical decision.
6
11
 
@@ -32,12 +37,12 @@ If no target is provided, ask the user what memory they want to erase.
32
37
 
33
38
  Search for the target memory:
34
39
 
35
- 1. Read `.brain/index.json` and search `memories` by:
40
+ 1. Read `~/.brain/index.json` and search `memories` by:
36
41
  - Exact ID match
37
42
  - Title substring match (case-insensitive)
38
43
  - Path substring match
39
- 2. If not found in active memories, check `.brain/_archived/index.json`
40
- 3. If still not found, check `.brain/_erased.json` — if found there, report:
44
+ 2. If not found in active memories, check `~/.brain/_archived/index.json`
45
+ 3. If still not found, check `~/.brain/_erased.json` — if found there, report:
41
46
  ```
42
47
  Memory was previously erased on <date>.
43
48
  Reason: <reason or "unspecified">
@@ -50,10 +55,10 @@ Once located, read the full memory file to capture its ID, title, path, tags, `r
50
55
 
51
56
  ### 3. Trace All References (Blast Radius Scan)
52
57
 
53
- Scan the entire `.brain/` tree for every trace of the target memory. Track 8 reference types:
58
+ Scan the entire `~/.brain/` tree for every trace of the target memory. Track 8 reference types:
54
59
 
55
60
  **3a. `related` arrays in other memories' frontmatter:**
56
- Parse the YAML frontmatter of every `.md` memory file in `.brain/`. For each file whose `related` array contains the target ID, record:
61
+ Parse the YAML frontmatter of every `.md` memory file in `~/.brain/`. For each file whose `related` array contains the target ID, record:
57
62
  - File path
58
63
  - Current `related` array contents
59
64
 
@@ -70,22 +75,22 @@ Among all memory files with `type: consolidated`, check if their `consolidated_f
70
75
  - Number of other sources remaining
71
76
 
72
77
  **3d. Association edges (`associations.json`):**
73
- Read `.brain/associations.json`. Find all edges involving the target ID:
78
+ Read `~/.brain/associations.json`. Find all edges involving the target ID:
74
79
  - Outgoing: `edges[target_id][*]`
75
80
  - Incoming: `edges[*][target_id]`
76
81
  Record each edge with its neighbor, weight, and origin.
77
82
 
78
83
  **3e. Context sessions (`contexts.json`):**
79
- Read `.brain/contexts.json`. Search all sessions for the target ID in:
84
+ Read `~/.brain/contexts.json`. Search all sessions for the target ID in:
80
85
  - `memories_created` arrays
81
86
  - `memories_recalled` arrays
82
87
  Record each session timestamp and which array contained the reference.
83
88
 
84
89
  **3f. Review queue (`review-queue.json`):**
85
- Read `.brain/review-queue.json`. Check if any item has `memory_id` equal to the target ID.
90
+ Read `~/.brain/review-queue.json`. Check if any item has `memory_id` equal to the target ID.
86
91
 
87
92
  **3g. Archive index (`_archived/index.json`):**
88
- Read `.brain/_archived/index.json`. Check if the target ID exists as a key in `memories`.
93
+ Read `~/.brain/_archived/index.json`. Check if the target ID exists as a key in `memories`.
89
94
 
90
95
  **3h. Crystallization comments:**
91
96
  Search all memory files for HTML comments matching the pattern:
@@ -230,13 +235,13 @@ For each directory in the target's path, read the `_meta.json` and decrement `me
230
235
  - Clean up empty parent directories (but never delete top-level category directories)
231
236
 
232
237
  **7g. Remove archived copy:**
233
- If an archived copy exists at `.brain/_archived/<original-path>`, delete it.
238
+ If an archived copy exists at `~/.brain/_archived/<original-path>`, delete it.
234
239
  - If `--sensitive`: overwrite with null bytes before deletion
235
240
  - Clean up empty directories in `_archived/`
236
241
 
237
242
  ### 8. Write Audit Log
238
243
 
239
- Unless `--no-trace` is set, write or append to `.brain/_erased.json`:
244
+ Unless `--no-trace` is set, write or append to `~/.brain/_erased.json`:
240
245
 
241
246
  ```json
242
247
  {
@@ -317,7 +322,7 @@ Print a summary:
317
322
 
318
323
  7. **Empty `related` arrays after cleanup**: Leave as `related: []`. Do not remove the field entirely — it maintains schema consistency.
319
324
 
320
- 8. **Memory referenced by memories outside `.brain/`**: This command only operates within `.brain/`. If external files (e.g., `CLAUDE.md`, project docs) reference the memory, note this limitation in the summary.
325
+ 8. **Memory referenced by memories outside `~/.brain/`**: This command only operates within `~/.brain/`. If external files (e.g., `CLAUDE.md`, project docs) reference the memory, note this limitation in the summary.
321
326
 
322
327
  9. **Multiple memories matching a title substring**: Present all matches with their IDs, paths, and strengths. Ask the user to select the specific memory to erase.
323
328
 
@@ -0,0 +1,360 @@
1
+ ---
2
+ description: Sync memories via Git remote, Brain Cloud, or export/import
3
+ argument-hint: "[subcommand]"
4
+ ---
5
+
6
+ # /brain:sync — Portable Sync
7
+
8
+ 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.
9
+
10
+ **CRITICAL RULES:**
11
+ - NEVER auto-sync — always require explicit user action
12
+ - NEVER silently overwrite files on pull/import — show a preview first
13
+ - NEVER display passphrases or secrets in output
14
+ - Push operations execute immediately (no confirmation) — the user said "push"
15
+ - Pull/import operations warn before overwriting local data
16
+
17
+ ## Subcommands
18
+
19
+ Parse the user's input to determine the subcommand:
20
+
21
+ **Cloud Sync (Brain Cloud API):**
22
+ - `cloud login [--api-url URL]` → Authenticate via device code flow
23
+ - `cloud push` → Upload ~/.brain/ to Brain Cloud
24
+ - `cloud pull` → Download from Brain Cloud to ~/.brain/
25
+ - `cloud status` → Show cloud connection info
26
+ - `cloud logout` → Clear stored credentials
27
+
28
+ **Git Sync (any Git remote):**
29
+ - `setup <url>` → Configure a Git remote for sync
30
+ - `push` → Commit and push local changes to remote
31
+ - `pull` → Fetch and merge remote changes to local
32
+ - `status` → Show sync state (ahead/behind)
33
+ - `export [path]` → Export ~/.brain/ to an encrypted single file
34
+ - `import <path>` → Import from an export file
35
+ - `disconnect` → Remove sync configuration
36
+
37
+ If no subcommand is given, show available subcommands.
38
+
39
+ ---
40
+
41
+ ## `/brain:sync cloud login [--api-url URL]`
42
+
43
+ ### Steps
44
+
45
+ 1. **Check if already logged in:**
46
+ - Read `~/.brain/.cloud/config.json` via `readConfig()` from `src/cloud-sync.js`.
47
+ - If already connected, show current user and ask if they want to re-authenticate.
48
+
49
+ 2. **Start device code flow:**
50
+ - Run `brain cloud login` (or call `login()` from `src/cloud-sync.js`).
51
+ - This calls `POST /auth/device/request` and returns a user code + verification URL.
52
+
53
+ 3. **Display instructions to user:**
54
+ ```
55
+ 🔐 Brain Cloud Login
56
+
57
+ Open this URL in your browser:
58
+ <verify_url>
59
+
60
+ Your code: <user_code>
61
+
62
+ Waiting for approval...
63
+ ```
64
+
65
+ 4. **Wait for approval:**
66
+ - The CLI polls `POST /auth/device/poll` every 5 seconds.
67
+ - Once approved, tokens are saved to `~/.brain/.cloud/config.json`.
68
+
69
+ 5. **Show result:**
70
+ ```
71
+ ✓ Logged in as <email>
72
+ Brain ID: <brain_id>
73
+ API: <api_url>
74
+ ```
75
+
76
+ ---
77
+
78
+ ## `/brain:sync cloud push`
79
+
80
+ ### Prerequisites
81
+
82
+ Check that the `brain` CLI is available (run `brain --version`). If not:
83
+ ```
84
+ brain CLI is not installed. Install it with:
85
+ npm install -g brain-memory
86
+ ```
87
+ Then return — do not attempt the push.
88
+
89
+ ### Steps
90
+
91
+ 1. **Check logged in.** If not, suggest `cloud login`.
92
+
93
+ 2. **Execute push immediately** — no confirmation needed:
94
+ - Run `brain cloud push`.
95
+ - Show result:
96
+ ```
97
+ ✓ Push complete!
98
+ Size: <size>
99
+ Files: <count>
100
+ Checksum: <checksum>
101
+ ```
102
+
103
+ ---
104
+
105
+ ## `/brain:sync cloud pull`
106
+
107
+ ### Steps
108
+
109
+ 1. **Check logged in.**
110
+
111
+ 2. **Warn about overwrite:**
112
+ ```
113
+ 📥 Cloud Pull Preview:
114
+ Source: <api_url>
115
+ ⚠️ This will overwrite local files with the cloud version.
116
+ ```
117
+
118
+ 3. **Ask for confirmation.**
119
+
120
+ 4. **Execute pull:**
121
+ - Run `brain cloud pull` (or call `pull()` from `src/cloud-sync.js`).
122
+ - Downloads tar.gz from `GET /api/brains/{id}/sync` and extracts to `~/.brain/`.
123
+ - Show result:
124
+ ```
125
+ ✓ Pull complete!
126
+ Size: <size>
127
+ ```
128
+
129
+ 5. **Rebuild index:**
130
+ - After pull, run the index manager to rebuild `~/.brain/index.json`.
131
+
132
+ ---
133
+
134
+ ## `/brain:sync cloud status`
135
+
136
+ ### Steps
137
+
138
+ 1. **Read cloud config** using `readConfig()` from `src/cloud-sync.js`.
139
+
140
+ 2. **Fetch live status** (if connected) by calling `status()` from `src/cloud-sync.js`.
141
+
142
+ 3. **Display dashboard:**
143
+ ```
144
+ ☁️ Brain Cloud Status
145
+ ─────────────────────────
146
+ API: <api_url or "not connected">
147
+ User: <email>
148
+ Brain ID: <brain_id>
149
+ Cloud Size: <size>
150
+ Cloud Files: <count>
151
+ Last Push: <timestamp or "never">
152
+ Last Pull: <timestamp or "never">
153
+ Last Synced: <timestamp or "never">
154
+ Connected: <timestamp>
155
+ ```
156
+
157
+ ---
158
+
159
+ ## `/brain:sync cloud logout`
160
+
161
+ ### Steps
162
+
163
+ 1. **Show current connection** (API URL, email).
164
+ 2. **Ask for confirmation:** "This will clear your stored credentials. Cloud data will NOT be deleted."
165
+ 3. **Remove `~/.brain/.cloud/` directory.**
166
+ 4. **Confirm:** "✓ Logged out. Cloud data is untouched."
167
+
168
+ ---
169
+
170
+ ## `/brain:sync setup <url>`
171
+
172
+ ### Steps
173
+
174
+ 1. **Check prerequisites:**
175
+ - Verify `~/.brain/` exists. If not, suggest `/brain:init` first.
176
+ - Verify `git` is available (`checkGitAvailable()` from `src/git-sync.js`).
177
+ - Check if sync is already configured (`~/.brain/.sync/config.json`). If so, ask if they want to reconfigure.
178
+
179
+ 2. **Get remote URL** (if not provided):
180
+ - Ask for the Git remote URL (SSH or HTTPS).
181
+ - Auto-detect `gh` CLI: if available, offer to create a private repo with `gh repo create brain-data --private`.
182
+ - Examples:
183
+ - `git@github.com:user/brain-data.git`
184
+ - `https://github.com/user/brain-data.git`
185
+ - `git@gitlab.com:user/brain-data.git`
186
+
187
+ 3. **Ask about encryption** (optional):
188
+ - "Would you like to encrypt memories before pushing? (recommended for sensitive data)"
189
+ - If yes, ask for a passphrase (will be needed on every push/pull and on other devices).
190
+
191
+ 4. **Initialize sync:**
192
+ - Call `initSyncRepo()` and `configureRemote()` from `src/git-sync.js`.
193
+ - Write config to `~/.brain/.sync/config.json` via `writeSyncConfig()`.
194
+
195
+ 5. **Show result:**
196
+ ```
197
+ ✓ Git sync configured!
198
+ Remote: <remote-url>
199
+ Branch: main
200
+ Encryption: <enabled/disabled>
201
+
202
+ Use /brain:sync push to upload your memories.
203
+ Use /brain:sync pull to download from remote.
204
+ ```
205
+
206
+ ---
207
+
208
+ ## `/brain:sync push`
209
+
210
+ ### Steps
211
+
212
+ 1. **Check sync is configured.** If not, suggest `/brain:sync setup`.
213
+
214
+ 2. **Check status** via `getStatus()`. If behind > 0, warn: "Remote has newer changes. Consider pulling first." and stop.
215
+
216
+ 3. **Execute push immediately** — no confirmation needed:
217
+ - If encryption is enabled, ask for passphrase.
218
+ - Call `push()` from `src/git-sync.js`.
219
+ - Show result:
220
+ ```
221
+ ✓ Push complete!
222
+ Committed: <message>
223
+ Remote: <remote-url>
224
+ ```
225
+
226
+ ---
227
+
228
+ ## `/brain:sync pull`
229
+
230
+ ### Steps
231
+
232
+ 1. **Check sync is configured.**
233
+
234
+ 2. **Preview:**
235
+ - Call `getStatus()` to show ahead/behind count.
236
+ ```
237
+ 📥 Pull Preview:
238
+ Remote: <remote-url>
239
+ Status: <behind> new commits to pull
240
+ ```
241
+
242
+ 3. **Ask for confirmation.**
243
+
244
+ 4. **Execute pull:**
245
+ - If encryption is enabled, ask for passphrase.
246
+ - Call `pull()` from `src/git-sync.js`.
247
+ - Show result:
248
+ ```
249
+ ✓ Pull complete!
250
+ Updated <count> files from remote.
251
+ ```
252
+
253
+ ---
254
+
255
+ ## `/brain:sync status`
256
+
257
+ ### Steps
258
+
259
+ 1. **Read sync config** using `getSyncConfig()` from `src/git-sync.js`.
260
+
261
+ 2. **Display dashboard:**
262
+ ```
263
+ 🔄 Sync Status
264
+ ─────────────────────
265
+ Remote: <remote-url or "not configured">
266
+ Branch: <branch>
267
+ Encryption: <enabled/disabled>
268
+ Last Push: <timestamp or "never">
269
+ Last Pull: <timestamp or "never">
270
+ Ahead: <count> commits
271
+ Behind: <count> commits
272
+ ```
273
+
274
+ ---
275
+
276
+ ## `/brain:sync export [path]`
277
+
278
+ ### Steps
279
+
280
+ 1. **Determine output path:**
281
+ - Default: `.brain-export` in the current directory.
282
+ - User can specify a custom path.
283
+
284
+ 2. **Ask about encryption:**
285
+ - "Would you like to encrypt the export? (recommended)"
286
+ - If yes, ask for a passphrase.
287
+
288
+ 3. **Execute export:**
289
+ - Call `exportBrain()` from `src/export-import.js`.
290
+ - Show result:
291
+ ```
292
+ ✓ Brain exported!
293
+ File: <output-path>
294
+ Memories: <count> files packed
295
+ Encrypted: <yes/no>
296
+ Size: <file-size>
297
+
298
+ Transfer this file to another machine and run /brain:sync import <path>
299
+ ```
300
+
301
+ ---
302
+
303
+ ## `/brain:sync import <path>`
304
+
305
+ ### Steps
306
+
307
+ 1. **Preview the import:**
308
+ - Call `previewImport()` from `src/export-import.js`.
309
+ - Display:
310
+ ```
311
+ 📦 Import Preview:
312
+ File: <path>
313
+ Exported at: <date>
314
+ Total files: <count>
315
+ New: <count> (will be created)
316
+ Existing: <count> (will be overwritten)
317
+ ```
318
+
319
+ 2. **Ask for import mode:**
320
+ - **Overwrite** (default): Replace all matching files with the imported versions.
321
+ - **Merge**: Only import files newer than local versions.
322
+
323
+ 3. **If encrypted, ask for passphrase.**
324
+
325
+ 4. **Ask for confirmation.**
326
+
327
+ 5. **Execute import:**
328
+ - Call `importBrain()` from `src/export-import.js`.
329
+ - Show result:
330
+ ```
331
+ ✓ Import complete!
332
+ Imported: <count> files
333
+ Skipped: <count> (merge mode, local was newer)
334
+ ```
335
+
336
+ ---
337
+
338
+ ## `/brain:sync disconnect`
339
+
340
+ ### Steps
341
+
342
+ 1. **Show current config** (remote URL).
343
+ 2. **Ask for confirmation:** "This will remove sync configuration. Your remote data will NOT be deleted."
344
+ 3. **Remove `~/.brain/.sync/` directory.**
345
+ 4. **Confirm:** "✓ Sync disconnected. Remote repository is untouched."
346
+
347
+ ---
348
+
349
+ ## Key Implementation Notes
350
+
351
+ - **Cloud sync engine**: `src/cloud-sync.js` — API client for Brain Cloud
352
+ - **Cloud CLI**: `bin/cloud-sync.js` — installed as `brain cloud` command
353
+ - **Cloud config**: stored in `~/.brain/.cloud/config.json` (tokens, brain ID, API URL)
354
+ - **Cloud protocol**: tar.gz archives uploaded/downloaded via REST API
355
+ - Git sync engine: `src/git-sync.js`
356
+ - Export/import: `src/export-import.js`
357
+ - Crypto utilities: `src/crypto.js`
358
+ - Git sync config stored in `~/.brain/.sync/config.json` (local only)
359
+ - Hidden git repo at `~/.brain/.sync/repo/` — never interferes with the project's own git
360
+ - All operations use Node.js built-ins only — no npm runtime dependencies