brain-memory 0.1.0-beta.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +632 -0
  2. package/README.md +390 -84
  3. package/SECURITY.md +100 -0
  4. package/assets/brand/README.md +28 -0
  5. package/assets/brand/icon-dark.svg +19 -0
  6. package/assets/brand/icon-light.svg +20 -0
  7. package/assets/brand/linkedin_cover.png +0 -0
  8. package/assets/brand/linkedin_cover_light.png +0 -0
  9. package/assets/brand/mark-dark.svg +19 -0
  10. package/assets/brand/mark-light.svg +20 -0
  11. package/assets/brand/png/icon-dark-1024.png +0 -0
  12. package/assets/brand/png/icon-dark-128.png +0 -0
  13. package/assets/brand/png/icon-dark-256.png +0 -0
  14. package/assets/brand/png/icon-dark-512.png +0 -0
  15. package/assets/brand/png/icon-dark-64.png +0 -0
  16. package/assets/brand/png/icon-light-1024.png +0 -0
  17. package/assets/brand/png/icon-light-128.png +0 -0
  18. package/assets/brand/png/icon-light-256.png +0 -0
  19. package/assets/brand/png/icon-light-512.png +0 -0
  20. package/assets/brand/png/icon-light-64.png +0 -0
  21. package/assets/brand/png/mark-dark-1024.png +0 -0
  22. package/assets/brand/png/mark-light-1024.png +0 -0
  23. package/assets/icon.png +0 -0
  24. package/assets/icon.svg +19 -0
  25. package/bin/audit.js +93 -0
  26. package/bin/brain.js +132 -0
  27. package/bin/cloud-sync.js +150 -0
  28. package/bin/forget.js +172 -0
  29. package/bin/import.js +132 -0
  30. package/bin/install.js +63 -31
  31. package/bin/memorize.js +670 -0
  32. package/bin/pin.js +44 -0
  33. package/bin/recall.js +319 -0
  34. package/bin/reinforce.js +191 -0
  35. package/bin/restore.js +122 -0
  36. package/bin/session-start.js +352 -0
  37. package/bin/skill.js +67 -0
  38. package/bin/unpin.js +38 -0
  39. package/bin/verify.js +186 -0
  40. package/commands/brain/forget.md +243 -13
  41. package/commands/brain/import.md +125 -0
  42. package/commands/brain/memorize.md +108 -130
  43. package/commands/brain/pin.md +79 -0
  44. package/commands/brain/remember.md +59 -100
  45. package/commands/brain/skills.md +60 -0
  46. package/commands/brain/sleep.md +93 -6
  47. package/commands/brain/status.md +15 -6
  48. package/commands/brain/sync.md +181 -17
  49. package/commands/brain/verify.md +63 -0
  50. package/integrations/README.md +29 -0
  51. package/integrations/agentskills/brain-memory/SKILL.md +115 -0
  52. package/integrations/agentskills/brain-memory/scripts/session-start.mjs +34 -0
  53. package/package.json +19 -7
  54. package/prompts/antigravity.md +222 -0
  55. package/prompts/claude.md +128 -40
  56. package/prompts/copilot.md +224 -0
  57. package/prompts/kilo.md +223 -0
  58. package/prompts/openai.md +133 -45
  59. package/prompts/opencode.md +221 -0
  60. package/src/anomaly.js +260 -0
  61. package/src/audit.js +71 -0
  62. package/src/cloud-sync.js +672 -0
  63. package/src/content-lint.js +118 -0
  64. package/src/export-import.js +45 -7
  65. package/src/git-sync.js +170 -11
  66. package/src/harvest.js +562 -0
  67. package/src/index-manager.js +250 -11
  68. package/src/installer.js +250 -29
  69. package/src/pinning.js +146 -0
  70. package/src/provenance.js +79 -0
  71. package/src/quarantine.js +111 -0
  72. package/src/receipt.js +87 -0
  73. package/src/scorer.js +137 -12
  74. package/src/skills.js +208 -0
  75. package/src/temporal.js +228 -0
  76. package/src/tfidf.js +520 -0
  77. package/commands/brain/consolidate.md +0 -153
  78. package/commands/brain/explore.md +0 -79
  79. package/commands/brain/init.md +0 -149
  80. package/commands/brain/review.md +0 -130
  81. package/commands/brain/sunshine.md +0 -337
  82. package/prompts/gemini.md +0 -134
package/SECURITY.md ADDED
@@ -0,0 +1,100 @@
1
+ # Security Policy
2
+
3
+ ## Reporting Vulnerabilities
4
+
5
+ If you discover a security vulnerability, please report it privately via email to **onur@omelas.tech**. Do not open a public GitHub issue for security vulnerabilities.
6
+
7
+ You should receive a response within 48 hours. Please include:
8
+ - Description of the vulnerability
9
+ - Steps to reproduce
10
+ - Potential impact
11
+
12
+ ## Scope
13
+
14
+ Brain Memory handles sensitive data in several areas:
15
+
16
+ - **AES-256-GCM encryption** — Optional encryption for Git-synced and exported memory files using a user-provided passphrase (PBKDF2-SHA512, 100K iterations)
17
+ - **File system access** — Reads and writes to the `.brain/` directory tree
18
+ - **Git operations** — When sync is configured, pushes/pulls to a user-specified Git remote using the system `git` binary and the user's existing Git/SSH authentication
19
+
20
+ ## Memory poisoning (OWASP ASI06)
21
+
22
+ Because Brain reloads stored memories into the model, a memory absorbed from
23
+ untrusted content — an email, a web page, a tool result — is an injection vector
24
+ ([MemGhost](https://arxiv.org/abs/2607.05189)). Brain implements all five ASI06
25
+ defense layers; the full model is in the [Provenance & Trust](https://brainmemory.ai/docs/concepts/provenance-trust/)
26
+ docs:
27
+
28
+ - **Provenance ceilings.** Every memory records an `origin`; non-`user` origins
29
+ are confidence-capped, decay faster, and **cannot pin or entrench** (refused at
30
+ write, not silently capped).
31
+ - **Trust-weighted recall.** Origin trust multiplies the recall score and damps
32
+ spreading-activation sources, so a co-tagged clique of planted writes can't
33
+ self-amplify past a genuine memory.
34
+ - **Content lint.** Instruction-shaped writes (e.g. "ignore previous
35
+ instructions", pipe-to-shell, secret exfiltration) are flagged regardless of
36
+ the claimed origin.
37
+ - **Quarantine + verification.** Low-trust and lint-flagged writes land pending
38
+ verification (`brain verify`); in `enforce` mode they are excluded from recall
39
+ until approved.
40
+ - **Anomaly detection.** `brain audit` flags write bursts, low-trust cliques, and
41
+ quietly-reinforced unverified memories (runs as `brain sleep` Phase 0).
42
+ - **Forensics + rollback.** An append-only `~/.brain/audit.log` (carried forward
43
+ through restores) records every write, archival, and verification; `brain
44
+ restore` rolls the whole brain back to a pre-attack snapshot.
45
+
46
+ `origin` is asserted by the writing agent, so this does not defend against a
47
+ fully hostile agent lying about provenance — but it holds for the dominant case
48
+ (an honest agent relaying poisoned content), and the entrenchment refusal and
49
+ lint hold regardless of the claimed origin.
50
+
51
+ ## File-system safety
52
+
53
+ The `.brain/` tree and everything that writes into it (memorize, reinforce, pin,
54
+ forget, import) validate that resolved paths stay inside the brain directory,
55
+ including through symlinks (realpath checks); sync/import/export refuse `..`
56
+ traversal and never follow symlinks out of the tree; cloud snapshots are
57
+ extracted through a staging directory that drops symlink members.
58
+
59
+ ## Hosted service: Brain Cloud & the connector
60
+
61
+ Brain Memory is **local-first** — by default your memories are plain files on your
62
+ own disk and never leave it. The hosted **Brain Cloud** sync hub and the **Claude
63
+ connector** (a remote MCP server) are entirely optional. When you do use them, this
64
+ is how your data is protected:
65
+
66
+ - **Encrypted at rest.** Brains stored in Brain Cloud are encrypted on disk with
67
+ **AES-256-GCM** using a **per-user key** (HKDF-derived from a server master key).
68
+ A stolen disk, backup, or snapshot yields no readable memories.
69
+ - **No plaintext on the connector.** The connector keeps each user's working copy
70
+ in **RAM only** (a tmpfs, wiped on restart) — it is never written to the
71
+ connector's disk.
72
+ - **Encrypted in transit.** All traffic to `api.brainmemory.ai` and the connector
73
+ is HTTPS/TLS.
74
+ - **Strict tenant isolation.** Every cloud request is authorized against the
75
+ authenticated user; one account can never read or overwrite another's brain.
76
+ - **Revocable sessions.** CLI sessions use **rotating refresh tokens with
77
+ automatic reuse detection** — a replayed (stolen) token revokes the whole
78
+ session family. You can log out a device, or **all** devices, at any time.
79
+ - **Verified-identity sign-in.** Connector and dashboard login is Google OAuth via
80
+ Firebase; account-linking requires a **verified** email.
81
+ - **Least privilege.** The connector runs as an unprivileged, sandboxed service
82
+ (systemd hardening: no new privileges, read-only filesystem, private tmp).
83
+
84
+ Because the cloud runs deterministic recall server-side, this is **server-side**
85
+ encryption at rest, not end-to-end encryption: the service necessarily processes
86
+ your memories in memory. If you require that the server never sees plaintext, keep
87
+ your brain **local-only** (the default) or use Git/export sync with a passphrase
88
+ (below) instead of Brain Cloud.
89
+
90
+ ## Supported Versions
91
+
92
+ | Version | Supported |
93
+ |---------|-----------|
94
+ | 0.1.x (beta) | Yes |
95
+
96
+ ## Design Principles
97
+
98
+ - **No runtime dependencies** — Reduces supply chain attack surface
99
+ - **Local-first** — Sensitive data stays on disk by default; sync is opt-in
100
+ - **No stored credentials** — Git sync relies on the user's existing SSH keys or Git credential helpers; Brain Memory never stores auth tokens
@@ -0,0 +1,28 @@
1
+ # Brain Memory — brand icon exports
2
+
3
+ The firing-neuron "activation" mark in the technical-white identity's brand cyan
4
+ (`#46C6FF`). Regenerate everything from the canonical geometry with
5
+ `website/scripts/gen-icon.mjs` (favicons/app icon) — these files mirror that mark
6
+ for use on external surfaces.
7
+
8
+ ## Which file to use
9
+
10
+ | You're placing it on… | Use |
11
+ |----------------------------------|---------------------------------------|
12
+ | A **dark** UI / near-black tile | `icon-dark.svg` · `png/icon-dark-*.png` |
13
+ | A **light** UI / paper surface | `icon-light.svg` · `png/icon-light-*.png` |
14
+ | A surface that already has a bg (no tile) | `mark-dark.svg` (light/white mark) · `mark-light.svg` (deep-cyan mark) |
15
+
16
+ - **Tiles** (`icon-*`) include the rounded-square background and are self-contained.
17
+ - **Marks** (`mark-*`) are transparent — the neuron only.
18
+ - **Dark** keeps the white-hot core; **light** deepens the cyans + uses a dark-cyan
19
+ core so the mark stays legible on paper.
20
+
21
+ PNG sizes: 1024 / 512 / 256 / 128 / 64.
22
+
23
+ ## Wide images
24
+
25
+ `linkedin_cover.png` / `linkedin_cover_light.png` — 6336×1584 (4× the 1584×396
26
+ LinkedIn banner): the app tile centered on a flat canvas, no text (dark =
27
+ `#252525`, light = paper). Regenerate with
28
+ `node website/scripts/gen-linkedin-cover.mjs` (writes `website/public/`).
@@ -0,0 +1,19 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Brain Memory"><defs><radialGradient id="core" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#8FDDFF" stop-opacity="0.95"/><stop offset="100%" stop-color="#46C6FF" stop-opacity="0"/></radialGradient></defs><rect width="32" height="32" rx="7" ry="7" fill="#07090A"/>
2
+ <circle cx="16" cy="16" r="12" fill="url(#core)" opacity="0.7"/>
3
+ <g stroke="#2E9FD6" stroke-width="1.25" stroke-linecap="round">
4
+ <line x1="16" y1="16" x2="8" y2="8" stroke-opacity="0.4"/>
5
+ <line x1="16" y1="16" x2="25" y2="8" stroke-opacity="0.82"/>
6
+ <line x1="16" y1="16" x2="27" y2="17" stroke-opacity="0.5"/>
7
+ <line x1="16" y1="16" x2="24" y2="25" stroke-opacity="0.75"/>
8
+ <line x1="16" y1="16" x2="8" y2="23" stroke-opacity="0.4"/>
9
+ <line x1="16" y1="16" x2="6" y2="16" stroke-opacity="0.35"/>
10
+ </g>
11
+ <circle cx="8" cy="8" r="1.6" fill="#1C7FB0"/>
12
+ <circle cx="27" cy="17" r="1.4" fill="#4FB8E6"/>
13
+ <circle cx="24" cy="25" r="1.9" fill="#2E9FD6"/>
14
+ <circle cx="8" cy="23" r="1.6" fill="#2389BE"/>
15
+ <circle cx="6" cy="16" r="1.3" fill="#1B6E97"/>
16
+ <circle cx="25" cy="8" r="2.4" fill="#6FD3FF"/>
17
+ <circle cx="21" cy="11.5" r="1.3" fill="#CFEEFF"/>
18
+ <circle cx="16" cy="16" r="3.7" fill="#DFF4FF"/>
19
+ <circle cx="16" cy="16" r="1.9" fill="#FFFFFF"/></svg>
@@ -0,0 +1,20 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Brain Memory"><defs><radialGradient id="core" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#46C6FF" stop-opacity="0.95"/><stop offset="100%" stop-color="#46C6FF" stop-opacity="0"/></radialGradient></defs><rect width="32" height="32" rx="7" ry="7" fill="#F4F2EC"/>
2
+ <circle cx="16" cy="16" r="12" fill="url(#core)" opacity="0.5"/>
3
+ <g stroke="#1C7FB0" stroke-width="1.25" stroke-linecap="round">
4
+ <line x1="16" y1="16" x2="8" y2="8" stroke-opacity="0.4"/>
5
+ <line x1="16" y1="16" x2="25" y2="8" stroke-opacity="0.85"/>
6
+ <line x1="16" y1="16" x2="27" y2="17" stroke-opacity="0.55"/>
7
+ <line x1="16" y1="16" x2="24" y2="25" stroke-opacity="0.8"/>
8
+ <line x1="16" y1="16" x2="8" y2="23" stroke-opacity="0.4"/>
9
+ <line x1="16" y1="16" x2="6" y2="16" stroke-opacity="0.35"/>
10
+ </g>
11
+ <circle cx="8" cy="8" r="1.6" fill="#1C7FB0"/>
12
+ <circle cx="27" cy="17" r="1.4" fill="#2E9FD6"/>
13
+ <circle cx="24" cy="25" r="1.9" fill="#1C7FB0"/>
14
+ <circle cx="8" cy="23" r="1.6" fill="#2389BE"/>
15
+ <circle cx="6" cy="16" r="1.3" fill="#1B6E97"/>
16
+ <circle cx="25" cy="8" r="2.4" fill="#2E9FD6"/>
17
+ <circle cx="21" cy="11.5" r="1.3" fill="#5BC8FF"/>
18
+ <circle cx="16" cy="16" r="3.7" fill="#1C7FB0"/>
19
+ <circle cx="16" cy="16" r="1.9" fill="#0B4D6E"/>
20
+ <circle cx="16" cy="16" r="0.8" fill="#5BC8FF"/></svg>
Binary file
@@ -0,0 +1,19 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Brain Memory"><defs><radialGradient id="core" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#8FDDFF" stop-opacity="0.95"/><stop offset="100%" stop-color="#46C6FF" stop-opacity="0"/></radialGradient></defs>
2
+ <circle cx="16" cy="16" r="12" fill="url(#core)" opacity="0.7"/>
3
+ <g stroke="#2E9FD6" stroke-width="1.25" stroke-linecap="round">
4
+ <line x1="16" y1="16" x2="8" y2="8" stroke-opacity="0.4"/>
5
+ <line x1="16" y1="16" x2="25" y2="8" stroke-opacity="0.82"/>
6
+ <line x1="16" y1="16" x2="27" y2="17" stroke-opacity="0.5"/>
7
+ <line x1="16" y1="16" x2="24" y2="25" stroke-opacity="0.75"/>
8
+ <line x1="16" y1="16" x2="8" y2="23" stroke-opacity="0.4"/>
9
+ <line x1="16" y1="16" x2="6" y2="16" stroke-opacity="0.35"/>
10
+ </g>
11
+ <circle cx="8" cy="8" r="1.6" fill="#1C7FB0"/>
12
+ <circle cx="27" cy="17" r="1.4" fill="#4FB8E6"/>
13
+ <circle cx="24" cy="25" r="1.9" fill="#2E9FD6"/>
14
+ <circle cx="8" cy="23" r="1.6" fill="#2389BE"/>
15
+ <circle cx="6" cy="16" r="1.3" fill="#1B6E97"/>
16
+ <circle cx="25" cy="8" r="2.4" fill="#6FD3FF"/>
17
+ <circle cx="21" cy="11.5" r="1.3" fill="#CFEEFF"/>
18
+ <circle cx="16" cy="16" r="3.7" fill="#DFF4FF"/>
19
+ <circle cx="16" cy="16" r="1.9" fill="#FFFFFF"/></svg>
@@ -0,0 +1,20 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Brain Memory"><defs><radialGradient id="core" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#46C6FF" stop-opacity="0.95"/><stop offset="100%" stop-color="#46C6FF" stop-opacity="0"/></radialGradient></defs>
2
+ <circle cx="16" cy="16" r="12" fill="url(#core)" opacity="0.5"/>
3
+ <g stroke="#1C7FB0" stroke-width="1.25" stroke-linecap="round">
4
+ <line x1="16" y1="16" x2="8" y2="8" stroke-opacity="0.4"/>
5
+ <line x1="16" y1="16" x2="25" y2="8" stroke-opacity="0.85"/>
6
+ <line x1="16" y1="16" x2="27" y2="17" stroke-opacity="0.55"/>
7
+ <line x1="16" y1="16" x2="24" y2="25" stroke-opacity="0.8"/>
8
+ <line x1="16" y1="16" x2="8" y2="23" stroke-opacity="0.4"/>
9
+ <line x1="16" y1="16" x2="6" y2="16" stroke-opacity="0.35"/>
10
+ </g>
11
+ <circle cx="8" cy="8" r="1.6" fill="#1C7FB0"/>
12
+ <circle cx="27" cy="17" r="1.4" fill="#2E9FD6"/>
13
+ <circle cx="24" cy="25" r="1.9" fill="#1C7FB0"/>
14
+ <circle cx="8" cy="23" r="1.6" fill="#2389BE"/>
15
+ <circle cx="6" cy="16" r="1.3" fill="#1B6E97"/>
16
+ <circle cx="25" cy="8" r="2.4" fill="#2E9FD6"/>
17
+ <circle cx="21" cy="11.5" r="1.3" fill="#5BC8FF"/>
18
+ <circle cx="16" cy="16" r="3.7" fill="#1C7FB0"/>
19
+ <circle cx="16" cy="16" r="1.9" fill="#0B4D6E"/>
20
+ <circle cx="16" cy="16" r="0.8" fill="#5BC8FF"/></svg>
package/assets/icon.png CHANGED
Binary file
@@ -0,0 +1,19 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="1024" height="1024" role="img" aria-label="Brain Memory"><defs><radialGradient id="core" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#8FDDFF" stop-opacity="0.95"/><stop offset="100%" stop-color="#46C6FF" stop-opacity="0"/></radialGradient></defs><rect x="0" y="0" width="32" height="32" rx="7" ry="7" fill="#07090A"/>
2
+ <circle cx="16" cy="16" r="12" fill="url(#core)" opacity="0.7"/>
3
+ <g stroke="#2E9FD6" stroke-width="1.25" stroke-linecap="round">
4
+ <line x1="16" y1="16" x2="8" y2="8" stroke-opacity="0.4"/>
5
+ <line x1="16" y1="16" x2="25" y2="8" stroke-opacity="0.82"/>
6
+ <line x1="16" y1="16" x2="27" y2="17" stroke-opacity="0.5"/>
7
+ <line x1="16" y1="16" x2="24" y2="25" stroke-opacity="0.75"/>
8
+ <line x1="16" y1="16" x2="8" y2="23" stroke-opacity="0.4"/>
9
+ <line x1="16" y1="16" x2="6" y2="16" stroke-opacity="0.35"/>
10
+ </g>
11
+ <circle cx="8" cy="8" r="1.6" fill="#1C7FB0"/>
12
+ <circle cx="27" cy="17" r="1.4" fill="#4FB8E6"/>
13
+ <circle cx="24" cy="25" r="1.9" fill="#2E9FD6"/>
14
+ <circle cx="8" cy="23" r="1.6" fill="#2389BE"/>
15
+ <circle cx="6" cy="16" r="1.3" fill="#1B6E97"/>
16
+ <circle cx="25" cy="8" r="2.4" fill="#6FD3FF"/>
17
+ <circle cx="21" cy="11.5" r="1.3" fill="#CFEEFF"/>
18
+ <circle cx="16" cy="16" r="3.7" fill="#DFF4FF"/>
19
+ <circle cx="16" cy="16" r="1.9" fill="#FFFFFF"/></svg>
package/bin/audit.js ADDED
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain audit — anomalous-write scan over audit.log + index + associations.
5
+ *
6
+ * The deterministic forensics pass (OWASP ASI06): finds write bursts,
7
+ * co-tagged low-trust cliques, and quietly-reinforced low-trust memories,
8
+ * and can quarantine what it finds. Run standalone or as sleep Phase 0
9
+ * (the agent runs it and internalizes the JSON, session-start style).
10
+ *
11
+ * Usage:
12
+ * brain audit [--window 24h|7d] [--apply] [--max-apply N]
13
+ *
14
+ * --apply flags at most N (default 20) proposed memories per run — an audit
15
+ * can propose broadly but never mass-quarantine; `truncated: true` reports
16
+ * the cut. Every applied flag is itself audited (event: audit_quarantine).
17
+ *
18
+ * Output: JSON. Honors BRAIN_DIR.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+
24
+ const { getBrainDir, readIndex, writeIndex, readAssociations } = require('../src/index-manager');
25
+ const { appendAudit } = require('../src/audit');
26
+ const { runAudit } = require('../src/anomaly');
27
+
28
+ /** Parse "24h" / "7d" / bare hours into hours. */
29
+ function parseWindow(value) {
30
+ if (!value) return null;
31
+ const m = String(value).match(/^(\d+)(h|d)?$/);
32
+ if (!m) return null;
33
+ const n = parseInt(m[1], 10);
34
+ return m[2] === 'd' ? n * 24 : n;
35
+ }
36
+
37
+ function parseArgs(argv) {
38
+ const args = { windowHours: 24, apply: false, maxApply: 20 };
39
+ for (let i = 0; i < argv.length; i++) {
40
+ switch (argv[i]) {
41
+ case '--window': {
42
+ const parsed = parseWindow(argv[++i]);
43
+ if (parsed) args.windowHours = parsed;
44
+ break;
45
+ }
46
+ case '--apply': args.apply = true; break;
47
+ case '--max-apply': args.maxApply = parseInt(argv[++i], 10) || 20; break;
48
+ default: break;
49
+ }
50
+ }
51
+ return args;
52
+ }
53
+
54
+ function main(argv) {
55
+ const args = parseArgs(argv || process.argv.slice(2));
56
+ const brainDir = getBrainDir();
57
+
58
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
59
+ console.error(JSON.stringify({ error: 'Brain not initialized.' }));
60
+ process.exit(1);
61
+ }
62
+
63
+ let index;
64
+ try {
65
+ index = readIndex();
66
+ } catch (err) {
67
+ console.error(JSON.stringify({
68
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
69
+ }));
70
+ process.exit(1);
71
+ }
72
+
73
+ let associations;
74
+ try {
75
+ associations = readAssociations() || { version: 1, edges: {} };
76
+ } catch (_) {
77
+ associations = { version: 1, edges: {} };
78
+ }
79
+
80
+ const result = runAudit(
81
+ brainDir,
82
+ { index, associations, appendAudit, writeIndex },
83
+ { windowHours: args.windowHours, apply: args.apply, maxApply: args.maxApply }
84
+ );
85
+
86
+ console.log(JSON.stringify(result, null, 2));
87
+ }
88
+
89
+ if (require.main === module) {
90
+ main(process.argv.slice(2));
91
+ }
92
+
93
+ module.exports = { main, parseArgs, parseWindow };
package/bin/brain.js ADDED
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain — unified CLI dispatcher for the Brain Memory system.
5
+ *
6
+ * Routes subcommands to their implementations, replacing the former per-binary
7
+ * surface (brain-recall, brain-reinforce, brain-memorize, brain-cloud). Each
8
+ * delegate module still runs on load and remains invokable as `node bin/<file>`,
9
+ * so direct invocation and the existing test suite are unaffected.
10
+ *
11
+ * Usage:
12
+ * brain Interactive installer (also: brain install)
13
+ * brain install|update|uninstall [flags]
14
+ * brain recall "<query>" [--project P] [--task T] [--top N] [--context] [--reindex]
15
+ * brain memorize [--sync] Store memories from a JSON payload on stdin
16
+ * brain reinforce <id> [<id>...] Spaced reinforcement + Hebbian co-retrieval
17
+ * brain cloud <login|logout|push|pull|status>
18
+ * brain --help | brain --version
19
+ */
20
+
21
+ const path = require('path');
22
+
23
+ const VERSION = require('../package.json').version;
24
+
25
+ // Subcommands whose modules read process.argv.slice(2) directly. We strip the
26
+ // leading subcommand token, then require the module (which executes on load).
27
+ const DELEGATED = {
28
+ recall: 'recall.js',
29
+ reinforce: 'reinforce.js',
30
+ memorize: 'memorize.js',
31
+ cloud: 'cloud-sync.js',
32
+ 'session-start': 'session-start.js',
33
+ pin: 'pin.js',
34
+ unpin: 'unpin.js',
35
+ skill: 'skill.js',
36
+ import: 'import.js',
37
+ restore: 'restore.js',
38
+ verify: 'verify.js',
39
+ audit: 'audit.js',
40
+ };
41
+
42
+ // install.js finds its positional subcommand from process.argv itself, so it is
43
+ // required without stripping anything. Bare `brain` also routes here, preserving
44
+ // `npx brain-memory` via npm's single-bin fallback.
45
+ const INSTALLER = new Set(['install', 'update', 'uninstall']);
46
+
47
+ const HELP = `◉ brain — Brain Memory CLI
48
+
49
+ Usage: brain <command> [options]
50
+
51
+ Memory
52
+ recall "<query>" [--project P] [--task T] [--top N]
53
+ Deterministic recall (TF-IDF + decay + spreading)
54
+ recall --context Session-start recall from project context
55
+ recall --reindex Rebuild the search index
56
+ memorize [--sync] Store memories from a JSON payload on stdin
57
+ reinforce <id> [<id>...] Spaced reinforcement + Hebbian co-retrieval
58
+ pin <id> [--scope global|project:<name>] [--priority N]
59
+ Pin a memory into the always-present tier
60
+ unpin <id> Remove a memory from the always-present tier
61
+ skill <list|show|use|add|remove|export>
62
+ Manage procedural skills (progressive disclosure)
63
+ session-start [--project P] [--task T] [--top N]
64
+ Budget-bounded startup payload (agent-invoked)
65
+
66
+ Trust
67
+ verify <list|show|approve|reject>
68
+ Quarantine workflow for unverified writes
69
+ audit [--window 24h|7d] [--apply]
70
+ Anomalous-write scan over audit.log
71
+
72
+ Cold start
73
+ import [--source S] [--project P] [--since 30d] [--limit N] [--all]
74
+ Digest past agent transcripts into import candidates
75
+ import --sources List detected agent history stores
76
+ import --mark <id> [<id>...]
77
+ Record sessions as imported (incremental cursor)
78
+
79
+ Sync
80
+ cloud <login|logout|push|pull|status>
81
+ restore --list [--from git|cloud]
82
+ List restore points (Git history or Cloud snapshots)
83
+ restore --to <point> [--from git|cloud]
84
+ Roll the whole brain back to a restore point
85
+
86
+ Setup
87
+ install Interactive installer (default when no command)
88
+ update Update an existing installation
89
+ uninstall [--delete-data] Remove the installation
90
+
91
+ Other
92
+ --help, -h Show this help
93
+ --version, -v Show version
94
+ `;
95
+
96
+ function main() {
97
+ const sub = process.argv[2];
98
+
99
+ if (sub === '--version' || sub === '-v') {
100
+ console.log(VERSION);
101
+ return;
102
+ }
103
+
104
+ if (sub === '--help' || sub === '-h' || sub === 'help') {
105
+ console.log(HELP);
106
+ return;
107
+ }
108
+
109
+ // Bare `brain` or an installer subcommand → run the installer.
110
+ if (sub === undefined || INSTALLER.has(sub)) {
111
+ require(path.join(__dirname, 'install.js'));
112
+ return;
113
+ }
114
+
115
+ const file = DELEGATED[sub];
116
+ if (file) {
117
+ process.argv.splice(2, 1); // drop the subcommand token
118
+ const mod = require(path.join(__dirname, file));
119
+ // Modules guarded with `require.main === module` (e.g. session-start) export
120
+ // a main() that we must invoke; legacy modules already ran on require.
121
+ if (mod && typeof mod.main === 'function') {
122
+ mod.main(process.argv.slice(2));
123
+ }
124
+ return;
125
+ }
126
+
127
+ console.error(`Unknown command: ${sub}\n`);
128
+ console.error(HELP);
129
+ process.exit(1);
130
+ }
131
+
132
+ main();
@@ -0,0 +1,150 @@
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 cloud = require('../src/cloud-sync');
15
+ const { getBrainDir } = require('../src/index-manager');
16
+
17
+ // Resolved via getBrainDir so Cloud sync targets the same brain as the rest of
18
+ // the CLI, including a $BRAIN_DIR override (synced folder, git working copy, …).
19
+ const BRAIN_DIR = getBrainDir();
20
+
21
+ async function main() {
22
+ const args = process.argv.slice(2);
23
+ const command = args[0];
24
+
25
+ if (!command || command === '--help' || command === '-h') {
26
+ console.log(`
27
+ brain cloud — Brain Cloud sync CLI
28
+
29
+ Commands:
30
+ login [--api-url URL] Authenticate via device code flow
31
+ logout Clear stored credentials
32
+ push Upload ~/.brain/ to the cloud
33
+ pull Download from the cloud to ~/.brain/
34
+ status Show connection and sync status
35
+ `.trim());
36
+ process.exit(0);
37
+ }
38
+
39
+ switch (command) {
40
+ case 'login':
41
+ await cmdLogin(args);
42
+ break;
43
+ case 'logout':
44
+ cmdLogout();
45
+ break;
46
+ case 'push':
47
+ await cmdPush();
48
+ break;
49
+ case 'pull':
50
+ await cmdPull();
51
+ break;
52
+ case 'status':
53
+ await cmdStatus();
54
+ break;
55
+ default:
56
+ console.error(`Unknown command: ${command}`);
57
+ process.exit(1);
58
+ }
59
+ }
60
+
61
+ async function cmdLogin(args) {
62
+ let apiUrl;
63
+ const urlIdx = args.indexOf('--api-url');
64
+ if (urlIdx !== -1 && args[urlIdx + 1]) {
65
+ apiUrl = args[urlIdx + 1];
66
+ }
67
+
68
+ console.log('Requesting device code...');
69
+ const loginInfo = await cloud.login(BRAIN_DIR, apiUrl);
70
+
71
+ console.log();
72
+ console.log(' Open this URL in your browser to log in:');
73
+ console.log();
74
+ console.log(` ${loginInfo.verify_url}`);
75
+ console.log();
76
+ console.log(` Your code: ${loginInfo.user_code}`);
77
+ console.log();
78
+ console.log(` Waiting for approval (expires in ${Math.floor(loginInfo.expires_in / 60)} min)...`);
79
+
80
+ await loginInfo.waitForApproval();
81
+
82
+ const config = cloud.readConfig(BRAIN_DIR);
83
+ console.log();
84
+ console.log(`✓ Logged in as ${config.user_email || 'unknown'}`);
85
+ if (config.brain_id) {
86
+ console.log(` Brain ID: ${config.brain_id}`);
87
+ }
88
+ console.log(` API: ${config.api_url}`);
89
+ }
90
+
91
+ function cmdLogout() {
92
+ cloud.logout(BRAIN_DIR);
93
+ console.log('✓ Logged out. Credentials cleared.');
94
+ }
95
+
96
+ async function cmdPush() {
97
+ console.log('Packing ~/.brain/ ...');
98
+ const result = await cloud.push(BRAIN_DIR);
99
+ console.log();
100
+ console.log('✓ Push complete!');
101
+ console.log(` Size: ${formatBytes(result.size_bytes)}`);
102
+ console.log(` Files: ${result.file_count}`);
103
+ console.log(` Checksum: ${result.checksum}`);
104
+ }
105
+
106
+ async function cmdPull() {
107
+ console.log('Downloading from cloud...');
108
+ const result = await cloud.pull(BRAIN_DIR);
109
+ console.log();
110
+ console.log('✓ Pull complete!');
111
+ console.log(` Size: ${formatBytes(result.size_bytes)}`);
112
+ if (result.checksum) {
113
+ console.log(` Checksum: ${result.checksum}`);
114
+ }
115
+ }
116
+
117
+ async function cmdStatus() {
118
+ const s = await cloud.status(BRAIN_DIR);
119
+
120
+ if (!s.connected) {
121
+ console.log('☁️ Not connected to Brain Cloud');
122
+ console.log(' Run: brain cloud login');
123
+ return;
124
+ }
125
+
126
+ console.log('☁️ Brain Cloud Status');
127
+ console.log('─────────────────────────');
128
+ console.log(` API: ${s.api_url}`);
129
+ console.log(` User: ${s.user_email || 'unknown'}`);
130
+ console.log(` Brain ID: ${s.brain_id || 'none'}`);
131
+ if (s.brain_name) console.log(` Brain Name: ${s.brain_name}`);
132
+ if (s.brain_size !== null) console.log(` Cloud Size: ${formatBytes(s.brain_size)}`);
133
+ if (s.brain_files !== null) console.log(` Cloud Files: ${s.brain_files}`);
134
+ console.log(` Last Push: ${s.last_push || 'never'}`);
135
+ console.log(` Last Pull: ${s.last_pull || 'never'}`);
136
+ console.log(` Last Synced: ${s.last_synced || 'never'}`);
137
+ console.log(` Connected: ${s.connected_at || 'unknown'}`);
138
+ }
139
+
140
+ function formatBytes(bytes) {
141
+ if (bytes === 0 || bytes === null || bytes === undefined) return '0 B';
142
+ const units = ['B', 'KB', 'MB', 'GB'];
143
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
144
+ return `${(bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
145
+ }
146
+
147
+ main().catch((err) => {
148
+ console.error(`Error: ${err.message}`);
149
+ process.exit(1);
150
+ });