brain-memory 0.3.0 → 0.5.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 (62) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/README.md +4 -0
  3. package/SECURITY.md +61 -9
  4. package/bin/brain.js +24 -3
  5. package/bin/cloud-sync.js +49 -6
  6. package/bin/install.js +72 -14
  7. package/bin/memorize.js +50 -6
  8. package/bin/port.js +174 -0
  9. package/bin/recall.js +16 -6
  10. package/bin/reinforce.js +5 -0
  11. package/bin/session-start.js +30 -4
  12. package/bin/verify.js +42 -4
  13. package/commands/brain/memorize.md +8 -0
  14. package/commands/brain/sync.md +23 -0
  15. package/commands/brain/verify.md +10 -2
  16. package/hooks/citation-check.mjs +94 -0
  17. package/hooks/hooks.json +11 -0
  18. package/hooks/lib.mjs +6 -0
  19. package/hooks/prompt-recall.mjs +24 -3
  20. package/hooks/session-start.mjs +4 -2
  21. package/integrations/README.md +4 -0
  22. package/integrations/agentskills/brain-memory/SKILL.md +9 -5
  23. package/package.json +10 -5
  24. package/prompts/antigravity.md +4 -2
  25. package/prompts/claude.md +4 -2
  26. package/prompts/copilot.md +4 -2
  27. package/prompts/kilo.md +4 -2
  28. package/prompts/openai.md +4 -2
  29. package/prompts/opencode.md +4 -2
  30. package/src/adapters.js +240 -0
  31. package/src/anomaly.js +41 -1
  32. package/src/cloud-sync.js +123 -11
  33. package/src/content-lint.js +55 -2
  34. package/src/export-import.js +1 -1
  35. package/src/git-sync.js +1 -1
  36. package/src/index-manager.js +9 -5
  37. package/src/installer.js +35 -1
  38. package/src/pinning.js +20 -1
  39. package/src/provenance.js +34 -0
  40. package/src/quarantine.js +82 -5
  41. package/src/receipt.js +9 -4
  42. package/src/surfaced.js +188 -0
  43. package/store/CONTRACT.md +244 -0
  44. package/store/Dockerfile +24 -0
  45. package/store/README.md +43 -0
  46. package/store/SELF-HOSTING.md +200 -0
  47. package/store/bin/brain-store.js +189 -0
  48. package/store/conformance/conformance.test.js +341 -0
  49. package/store/conformance/helpers.js +199 -0
  50. package/store/deploy/Caddyfile +14 -0
  51. package/store/deploy/connector.Dockerfile +38 -0
  52. package/store/deploy/docker-compose.yml +83 -0
  53. package/store/deploy/env.example +19 -0
  54. package/store/lib/auth.js +174 -0
  55. package/store/lib/oidc.js +206 -0
  56. package/store/lib/storage.js +333 -0
  57. package/store/lib/tar.js +150 -0
  58. package/store/openapi.yaml +318 -0
  59. package/store/server.js +465 -0
  60. package/store/test/mock-issuer.js +104 -0
  61. package/store/test/oidc.test.js +222 -0
  62. package/store/test/store.test.js +445 -0
package/CHANGELOG.md CHANGED
@@ -6,6 +6,159 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.5.0] - 2026-10-18
10
+
11
+ Memory stops being a way to smuggle instructions or permissions into an agent.
12
+ Memories from outside the user/agent dialogue are now left out of recall until
13
+ the user approves them, not merely marked. A remembered permission is its own
14
+ class that needs the user's own words behind it. Every receipt the agent cites
15
+ is checked against what brain actually surfaced. On a poisoned LongMemEval run,
16
+ down-weighting left the planted memory at rank 1 for 90% of questions, while
17
+ exclusion restored the clean-run R@1 of 0.551. `brain port` moves memories to
18
+ and from other memory systems.
19
+
20
+ ### Added
21
+ - **Permissions are their own class of memory.** A write that says the agent
22
+ may act without asking ("the user approved force-pushes to main", "no need to
23
+ confirm deploys", "pre-approved") is an authorization claim. From any origin
24
+ but `user` it lands pending verification (`authz:unbacked`); a `user` one does
25
+ too (`authz:no-source`) unless it carries the user's own words in
26
+ `authorized_by.quote`. Such memories are pinnable only when user-origin and
27
+ backed or approved, are marked `authorization_claim` in recall and
28
+ session-start results, and carry `⚠ authorization` on their receipts. The
29
+ agent prompts say a remembered permission is never consent for the action at
30
+ hand. `brain audit` reports older memories the new lint rule would have
31
+ caught. The connector's `brain_memorize` accepts `authorized_by`.
32
+ - **Citation lock.** Recall, session start and prompt-time recall record what
33
+ they surfaced in a device-local ledger (`~/.brain/.local/`, excluded from
34
+ every sync, export and restore). A new `Stop` hook (Claude Code, Codex)
35
+ checks every `◉ memory:` receipt in the agent's reply against it; a receipt
36
+ for a memory brain never surfaced is logged as a `citation_violation` audit
37
+ event and reported to the agent on its next prompt. Advisory: the reply is
38
+ never blocked.
39
+ - **Low-trust occupancy cap.** `recall_low_trust_max` (default `1`) bounds how
40
+ many `tool-output` / `external` memories a recall result or session-start
41
+ payload may hold, approved or not; the rest are skipped for the next trusted
42
+ match and reported as `low_trust_suppressed`.
43
+ - **`brain port`** moves memories between brain and other memory systems:
44
+ `export --format claude-memory|markdown|agentcore` writes what recall could
45
+ show (memories pending verification, hidden or expired are left out and
46
+ counted); `import --from …` sends memories through `brain memorize` as
47
+ `external`, so they wait for review unless `--trust` marks them as yours.
48
+ Covers Claude Code's memory files, a pasteable dated list (Claude.ai's
49
+ import format), and AgentCore `BatchCreateMemoryRecords` bodies. What
50
+ survives a round trip is documented per format.
51
+ - **Poisoned LongMemEval benchmark** (`benchmark/harness/longmemeval-poison.js`):
52
+ free, deterministic, retrieval-only. With a planted wrong-answer session per
53
+ question, exclusion keeps clean-haystack retrieval (R@1 0.551, R@5 0.909, the
54
+ poison never in the top 5); trust weighting alone lets the poison rank first
55
+ for 90% of questions. Results in `benchmark/results/REPORT.md`.
56
+ - **Plugin eval suite** (`evals/`) for `claude plugin eval`: eight cases that
57
+ seed a throwaway brain and check pinned conventions, past decisions,
58
+ poisoned-memory exclusion, no invented receipts, permissions not treated as
59
+ consent, memorize-on-request, and a fat-vs-thin AGENTS.md cost pair. A
60
+ manual-dispatch workflow runs it in CI.
61
+ - **Messages API integration** (`integrations/api/`): `withBrainTurn()`
62
+ recalls on each user message and appends the matches as a turn-scoped
63
+ system message (`clear_at: "next_user_message"`) under a token cap.
64
+ - **Git review template** (`integrations/git-review/`): a GitHub Actions check
65
+ for a brain git-sync repository that runs `brain audit` on every push.
66
+ - `docs/security/asi06.md`: Brain's controls mapped onto OWASP ASI06, every
67
+ CLI command and connector tool classified by effect, the threats not
68
+ covered, and the benchmark evidence.
69
+ - Session start reports `recall_usage_7d`: how many surfaced memories the agent
70
+ went on to use (`brain reinforce`).
71
+ - **`brain verify requeue <id>`**, an undo for a mistaken approve. It puts the
72
+ memory back into pending verification, clears `vetted` (which also withdraws
73
+ per-item consent for a sensitive memory), rebuilds the reasons approval
74
+ dropped, and logs a `verify_requeue` audit event. A pinned memory is refused
75
+ rather than silently unpinned.
76
+ - **Install without a terminal.** `brain --claude --global` (installer flags
77
+ with no subcommand) runs the installer, so an agent or a CI job can install
78
+ brain by itself. With nothing to ask on, the installer initializes `~/.brain/`
79
+ if it does not exist and never overwrites one; `--yes` skips that question on
80
+ a terminal too.
81
+ - The installer warns when brain is installed under nvm, fnm, asdf, mise or
82
+ nodenv: the command exists for that Node version only, so it disappears when
83
+ the default version moves and agent hooks never see it.
84
+ - Website: a Self-Hosting a Store page, and documentation for token login and
85
+ refused pushes.
86
+
87
+ ### Changed
88
+ - **Quarantine excludes by default.** `quarantine_mode` now defaults to
89
+ `enforce`: memories pending verification are left out of recall and session
90
+ start until approved, instead of being returned with a `⊘ unverified` mark.
91
+ Down-weighting a poisoned memory does not keep it out of the context window
92
+ when it is the best match; exclusion does. They are still counted in
93
+ `pending_verification`. Set `"quarantine_mode": "flag"` in
94
+ `~/.brain/config.json` to keep the previous behavior. An unrecognized value
95
+ now falls back to `enforce`, never to `off`.
96
+ - A write that lands pending verification is no longer born pinned; the output
97
+ reports `pin_dropped`.
98
+ - The agent prompts say to approve only the exact ids the user reviewed, never
99
+ a fresh listing, because other sessions write concurrently.
100
+
101
+ ### Fixed
102
+ - The `secret_exfil` lint no longer quarantines ordinary engineering notes
103
+ ("the password-reset email", a code literal such as `upload`) as injections.
104
+ - `test/harvest.test.js` no longer depends on the `~/.codex` of whoever runs it.
105
+ - The Compose environment template is `store/deploy/env.example`; as
106
+ `.env.example` it was ignored by git and npm and never shipped.
107
+
108
+ ## [0.4.0] - 2026-09-18
109
+
110
+ Opens up sync. The HTTP interface between a Brain client and a remote store is
111
+ now a published contract with a conformance suite, and `brain-store` is a small
112
+ reference server you can run yourself, so a brain no longer has to live in Brain
113
+ Cloud to be shared between machines or reached from MCP-only hosts. Sync also
114
+ stops being last-writer-wins: clients name the archive they started from, and a
115
+ store that has moved on refuses the upload instead of overwriting another
116
+ device's memories. The contract is a **draft** and is open for comment in
117
+ [#6](https://github.com/omelas-tech/brain/issues/6) until at least 25 September
118
+ 2026; it may still change. The project also gains a governance document, a
119
+ maintainers file and a code of conduct.
120
+
121
+ ### Added
122
+ - **An open store contract and a self-hostable store.** `store/CONTRACT.md` (with
123
+ `store/openapi.yaml`) specifies the HTTP interface between a Brain client and a
124
+ remote store. `brain-store` is a reference server for it: Node.js, no
125
+ dependencies, files only, static bearer tokens stored as hashes, optional
126
+ AES-256-GCM encryption at rest. `store/conformance/` is a black-box suite that
127
+ checks any implementation over HTTP. See `store/SELF-HOSTING.md`.
128
+ - **Conditional sync (store contract 1.1).** `brain cloud push` now names the
129
+ archive it started from (`If-Match`). If another device pushed in the meantime
130
+ the store answers `412` and nothing is overwritten; pull, then push again, or
131
+ `brain cloud push --force`. Stores that predate 1.1 ignore the header, so
132
+ behaviour against them is unchanged.
133
+ - **Token login for self-hosted stores:** `brain cloud login --api-url URL
134
+ --token-stdin` (also `--token`, or `BRAIN_STORE_TOKEN`). The CLI refuses to send
135
+ a token over plain HTTP to another host unless `--allow-http` is given.
136
+ - **Connector: pluggable identity.** `CONNECTOR_IDP=static` lets the MCP connector
137
+ run in front of a self-hosted store with no Firebase: the sign-in page takes the
138
+ store token, and the store decides who the user is. Firebase remains the default
139
+ for the hosted service and its behaviour is unchanged.
140
+ `CONNECTOR_TRUST_PROXY` names the reverse proxy when it is not on loopback.
141
+ - **Sign-in through an organisation's identity provider (OpenID Connect).** The
142
+ store accepts ID tokens from a configured issuer (`STORE_OIDC_ISSUER`,
143
+ `STORE_OIDC_AUDIENCE`) and creates users on first sign-in; `CONNECTOR_IDP=oidc`
144
+ sends people to that issuer (authorization code, PKCE, nonce). RS256 and ES256
145
+ only; a public issuer such as Google requires an allow-list. Tested against a
146
+ mock issuer, not yet against each real provider.
147
+ - **Connector: no lost writes.** Sync-back is conditional. When another device
148
+ pushed first, the connector discards its working copy, starts again from the
149
+ store's brain, re-applies the write and pushes, so both sides' memories survive.
150
+ - Docker Compose for a store, a connector and Caddy (`store/deploy/`).
151
+ - `GOVERNANCE.md`, `MAINTAINERS.md`, `CODE_OF_CONDUCT.md`.
152
+
153
+ ### Fixed
154
+ - `brain cloud push` on macOS no longer uploads an AppleDouble `._name` entry
155
+ beside every file with extended attributes (`COPYFILE_DISABLE`), which inflated
156
+ the archive and its reported file count.
157
+ - Connector: a user whose brain exists but has never been pushed to is treated as
158
+ new rather than as a store outage, so their session can be renewed.
159
+ - `CONTRIBUTING.md` described a project layout several releases old.
160
+ - `SECURITY.md` described the hosted service's retired key-derivation scheme.
161
+
9
162
  ## [0.3.0] - 2026-09-04
10
163
 
11
164
  Ships brain as a plugin and moves its session behaviour from prompts into
package/README.md CHANGED
@@ -170,6 +170,8 @@ brain --antigravity --global # Google Antigravity, global (experimental)
170
170
  brain --all --global # All runtimes, global
171
171
  ```
172
172
 
173
+ These run without a terminal, so an agent or a CI job can install brain itself. With no terminal to ask on, the installer initializes `~/.brain/` if it doesn't exist yet (it never overwrites an existing brain) — add `--yes` to skip that question outright. Leave out the runtime and it stops with an error rather than guessing.
174
+
173
175
  For the deepest Copilot CLI integration — deterministic session-start context injection via its `sessionStart` hook — install the [Copilot plugin](integrations/copilot/) from the brain marketplace:
174
176
 
175
177
  ```bash
@@ -206,6 +208,8 @@ The first command updates the package and the `brain` CLI. The second command re
206
208
 
207
209
  > **Why not `npx`?** `npx` runs the setup wizard in a temporary directory that is discarded after execution. The `brain` CLI (`brain recall`, `brain memorize`, `brain reinforce`) won't be available in your PATH, which means agents will fall back to less reliable manual file operations. Always use `npm install -g` to ensure everything works correctly.
208
210
 
211
+ > **Using nvm, fnm, asdf, mise or nodenv?** `npm install -g` puts `brain` inside whichever Node version is active, and only there. The command then disappears when your default version moves — a `22` alias drifting to a newer 22.x is enough — and shells that never load the version manager (agent hooks, GUI-launched agents, non-interactive shells) can't see it at all. Nothing errors: agents quietly fall back to editing memory files by hand, and it looks like brain works "sometimes". Install brain-memory with a system Node instead (Homebrew, apt, the nodejs.org installer) so `brain` lives in one stable place. npm takes its global prefix from the `node` that runs it, so put the system Node first on `PATH` for that one command — on macOS with Homebrew: `PATH="/opt/homebrew/bin:$PATH" npm install -g brain-memory`. Check with `which -a brain`; it should print exactly one path, outside your version manager's directory. The installer warns when it detects this. Volta is fine as-is — it keeps global packages available across versions.
212
+
209
213
  ### Uninstall
210
214
 
211
215
  ```bash
package/SECURITY.md CHANGED
@@ -28,21 +28,32 @@ docs:
28
28
  - **Provenance ceilings.** Every memory records an `origin`; non-`user` origins
29
29
  are confidence-capped, decay faster, and **cannot pin or entrench** (refused at
30
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.
31
+ - **Trust-weighted recall and an occupancy cap.** Origin trust multiplies the
32
+ recall score and damps spreading-activation sources, so a co-tagged clique of
33
+ planted writes can't self-amplify past a genuine memory; and one result set
34
+ holds at most `recall_low_trust_max` (default 1) low-trust memories.
34
35
  - **Content lint.** Instruction-shaped writes (e.g. "ignore previous
35
36
  instructions", pipe-to-shell, secret exfiltration) are flagged regardless of
36
37
  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.
38
+ - **Quarantine + verification.** Low-trust, lint-flagged and permission-granting
39
+ writes land pending verification (`brain verify`) and, by default (`enforce`),
40
+ are excluded from recall until approved.
41
+ - **Permissions need the user's words.** A memory that grants the agent a
42
+ permission is quarantined unless it is user-origin and carries the user's own
43
+ words, and is never treated as consent for the action at hand.
44
+ - **Citation lock.** Under Claude Code and Codex a Stop hook checks every
45
+ receipt in a reply against what brain surfaced, and logs any other as a
46
+ `citation_violation`.
40
47
  - **Anomaly detection.** `brain audit` flags write bursts, low-trust cliques, and
41
48
  quietly-reinforced unverified memories (runs as `brain sleep` Phase 0).
42
49
  - **Forensics + rollback.** An append-only `~/.brain/audit.log` (carried forward
43
50
  through restores) records every write, archival, and verification; `brain
44
51
  restore` rolls the whole brain back to a pre-attack snapshot.
45
52
 
53
+ The control map, a classification of every tool by effect, the threats not
54
+ covered, and poisoning-benchmark numbers are in
55
+ [docs/security/asi06.md](docs/security/asi06.md).
56
+
46
57
  `origin` is asserted by the writing agent, so this does not defend against a
47
58
  fully hostile agent lying about provenance — but it holds for the dominant case
48
59
  (an honest agent relaying poisoned content), and the entrenchment refusal and
@@ -64,8 +75,10 @@ connector** (a remote MCP server) are entirely optional. When you do use them, t
64
75
  is how your data is protected:
65
76
 
66
77
  - **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.
78
+ **AES-256-GCM** envelope encryption: each user's data is encrypted with a
79
+ **per-user data key**, and that key is itself wrapped by a key held in a cloud
80
+ **key management service (KMS)**, not on the server's disk. A stolen disk,
81
+ backup, or snapshot yields no readable memories.
69
82
  - **No plaintext on the connector.** The connector keeps each user's working copy
70
83
  in **RAM only** (a tmpfs, wiped on restart) — it is never written to the
71
84
  connector's disk.
@@ -87,11 +100,50 @@ your memories in memory. If you require that the server never sees plaintext, ke
87
100
  your brain **local-only** (the default) or use Git/export sync with a passphrase
88
101
  (below) instead of Brain Cloud.
89
102
 
103
+ ## Self-hosted store (`brain-store`)
104
+
105
+ `store/` contains a reference store server you can run yourself
106
+ (`store/SELF-HOSTING.md`). What it does and does not protect:
107
+
108
+ - **Tokens are never stored.** A token is 256 random bits, shown once; the server
109
+ keeps its SHA-256 and compares in constant time. Tokens are never logged.
110
+ - **Failed logins are rate limited** per client address, and each user's request
111
+ and upload rates are bounded.
112
+ - **Uploads are untrusted input.** Size is bounded before and while reading. The
113
+ archive is inflated as a stream and only tar headers are examined, with bounds on
114
+ inflated size and entry count, so a compression bomb cannot exhaust memory. The
115
+ server never extracts an archive to disk.
116
+ - **Identifiers cannot leave the data directory.** User ids, brain ids and
117
+ snapshot names are matched against strict patterns before any path is built.
118
+ - **Tenant isolation.** Another user's brain is indistinguishable from one that
119
+ does not exist.
120
+ - **Optional encryption at rest** (AES-256-GCM, per-user key derived by
121
+ HKDF-SHA256 from `STORE_ENCRYPTION_KEY`). This protects a stolen disk or backup.
122
+ It is server-side encryption: the running server holds the key.
123
+ - **No TLS of its own.** The server speaks plain HTTP and binds to loopback by
124
+ default. Terminate TLS in a reverse proxy; the provided Compose setup does.
125
+ - **Conditional writes.** The precondition check and the replacement of an archive
126
+ happen under one in-process lock. Run one server process per data directory.
127
+
128
+ - **OpenID Connect sign-in is opt-in and narrow.** Only RS256 and ES256 are
129
+ accepted; `none` and HMAC algorithms are refused, and the key type must agree
130
+ with the algorithm named in the token. Issuer, audience, expiry and nonce are
131
+ checked, the issuer must be reached over HTTPS, and its discovery document must
132
+ name itself. A public issuer (Google) is refused unless an allow-list is set,
133
+ and allow-lists only honour addresses the issuer marks verified.
134
+
135
+ The connector's `static` identity provider sends the pasted store token only to
136
+ the store named in `BRAIN_CLOUD_API_URL`, and refuses to start unless that address
137
+ is set explicitly. Its sign-in page loads nothing from other hosts and cannot be
138
+ framed. The token is kept with the refresh grant encrypted under
139
+ `CONNECTOR_STATE_KEY`; without that key it is held in memory only.
140
+
90
141
  ## Supported Versions
91
142
 
92
143
  | Version | Supported |
93
144
  |---------|-----------|
94
- | 0.1.x (beta) | Yes |
145
+ | 0.3.x | Yes |
146
+ | < 0.3 | No — please upgrade |
95
147
 
96
148
  ## Design Principles
97
149
 
package/bin/brain.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * Usage:
12
12
  * brain Interactive installer (also: brain install)
13
13
  * brain install|update|uninstall [flags]
14
+ * brain --claude --global Installer flags alone also install (non-interactive)
14
15
  * brain recall "<query>" [--project P] [--task T] [--top N] [--context] [--reindex]
15
16
  * brain memorize [--sync] Store memories from a JSON payload on stdin
16
17
  * brain reinforce <id> [<id>...] Spaced reinforcement + Hebbian co-retrieval
@@ -37,6 +38,7 @@ const DELEGATED = {
37
38
  restore: 'restore.js',
38
39
  verify: 'verify.js',
39
40
  audit: 'audit.js',
41
+ port: 'port.js',
40
42
  };
41
43
 
42
44
  // install.js finds its positional subcommand from process.argv itself, so it is
@@ -44,6 +46,15 @@ const DELEGATED = {
44
46
  // `npx brain-memory` via npm's single-bin fallback.
45
47
  const INSTALLER = new Set(['install', 'update', 'uninstall']);
46
48
 
49
+ // The documented non-interactive form has no subcommand at all —
50
+ // `brain --claude --global` — a holdover from the old `brain-memory` binary that
51
+ // install.js's own arg parser still accepts. An explicit list rather than "any
52
+ // --flag", so a typo like `--verison` still gets the unknown-command help.
53
+ const INSTALLER_FLAGS = new Set([
54
+ '--claude', '--codex', '--openai', '--opencode', '--antigravity', '--copilot', '--kilo', '--all',
55
+ '--global', '--local', '--update', '--uninstall', '--yes', '--y',
56
+ ]);
57
+
47
58
  const HELP = `◉ brain — Brain Memory CLI
48
59
 
49
60
  Usage: brain <command> [options]
@@ -64,7 +75,7 @@ Memory
64
75
  Budget-bounded startup payload (agent-invoked)
65
76
 
66
77
  Trust
67
- verify <list|show|approve|reject>
78
+ verify <list|show|approve|reject|requeue>
68
79
  Quarantine workflow for unverified writes
69
80
  audit [--window 24h|7d] [--apply]
70
81
  Anomalous-write scan over audit.log
@@ -76,6 +87,12 @@ Cold start
76
87
  import --mark <id> [<id>...]
77
88
  Record sessions as imported (incremental cursor)
78
89
 
90
+ Portability
91
+ port export --format <claude-memory|markdown|agentcore> [--out PATH]
92
+ Export what recall could show, for another memory system
93
+ port import --from <claude-memory|markdown|agentcore> <PATH> [--trust] [--dry-run]
94
+ Import through memorize (external → pending review)
95
+
79
96
  Sync
80
97
  cloud <login|logout|push|pull|status>
81
98
  restore --list [--from git|cloud]
@@ -85,6 +102,10 @@ Sync
85
102
 
86
103
  Setup
87
104
  install Interactive installer (default when no command)
105
+ install --claude --global [--yes]
106
+ Non-interactive: name the runtime(s) and scope
107
+ (--codex --opencode --copilot --kilo --antigravity --all;
108
+ \`install\` may be omitted)
88
109
  update Update an existing installation
89
110
  uninstall [--delete-data] Remove the installation
90
111
 
@@ -106,8 +127,8 @@ function main() {
106
127
  return;
107
128
  }
108
129
 
109
- // Bare `brain` or an installer subcommand → run the installer.
110
- if (sub === undefined || INSTALLER.has(sub)) {
130
+ // Bare `brain`, an installer subcommand, or installer flags alone → run the installer.
131
+ if (sub === undefined || INSTALLER.has(sub) || INSTALLER_FLAGS.has(sub)) {
111
132
  require(path.join(__dirname, 'install.js'));
112
133
  return;
113
134
  }
package/bin/cloud-sync.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * brain cloud — CLI for Brain Cloud sync
4
+ * brain cloud — CLI for syncing with Brain Cloud or a self-hosted brain-store
5
5
  *
6
6
  * Usage:
7
7
  * brain cloud login [--api-url URL] Authenticate via device code flow
8
+ * brain cloud login --api-url URL --token-stdin
9
+ * Authenticate to a self-hosted store with a token
8
10
  * brain cloud logout Clear stored credentials
9
- * brain cloud push Upload ~/.brain/ to the cloud
11
+ * brain cloud push [--force] Upload ~/.brain/ to the cloud
10
12
  * brain cloud pull Download from the cloud to ~/.brain/
11
13
  * brain cloud status Show connection and sync status
12
14
  */
@@ -29,9 +31,18 @@ brain cloud — Brain Cloud sync CLI
29
31
  Commands:
30
32
  login [--api-url URL] Authenticate via device code flow
31
33
  logout Clear stored credentials
32
- push Upload ~/.brain/ to the cloud
34
+ push [--force] Upload ~/.brain/ to the cloud
33
35
  pull Download from the cloud to ~/.brain/
34
36
  status Show connection and sync status
37
+
38
+ Self-hosted store (brain-store):
39
+ login --api-url URL --token-stdin Read the token from standard input, e.g.
40
+ pbpaste | brain cloud login --api-url URL --token-stdin
41
+ login --api-url URL --token TOKEN Pass the token as an argument (it lands in shell history)
42
+ login --api-url URL With BRAIN_STORE_TOKEN set in the environment
43
+ --allow-http Permit plain HTTP to a host other than this machine
44
+
45
+ push refuses to overwrite changes it has not pulled. --force uploads anyway.
35
46
  `.trim());
36
47
  process.exit(0);
37
48
  }
@@ -44,7 +55,7 @@ Commands:
44
55
  cmdLogout();
45
56
  break;
46
57
  case 'push':
47
- await cmdPush();
58
+ await cmdPush(args);
48
59
  break;
49
60
  case 'pull':
50
61
  await cmdPull();
@@ -65,6 +76,17 @@ async function cmdLogin(args) {
65
76
  apiUrl = args[urlIdx + 1];
66
77
  }
67
78
 
79
+ const token = await readToken(args);
80
+ if (token) {
81
+ const result = await cloud.loginWithToken(BRAIN_DIR, apiUrl, token, {
82
+ allowHttp: args.includes('--allow-http'),
83
+ });
84
+ console.log(`✓ Logged in as ${result.user_email || 'unknown'}`);
85
+ console.log(` Brain ID: ${result.brain_id}`);
86
+ console.log(` API: ${result.api_url}`);
87
+ return;
88
+ }
89
+
68
90
  console.log('Requesting device code...');
69
91
  const loginInfo = await cloud.login(BRAIN_DIR, apiUrl);
70
92
 
@@ -88,14 +110,35 @@ async function cmdLogin(args) {
88
110
  console.log(` API: ${config.api_url}`);
89
111
  }
90
112
 
113
+ /**
114
+ * A store token from --token-stdin, --token, or BRAIN_STORE_TOKEN, in that order.
115
+ * Standard input is preferred: it keeps the token out of shell history and out of
116
+ * the process list.
117
+ */
118
+ async function readToken(args) {
119
+ if (args.includes('--token-stdin')) {
120
+ const chunks = [];
121
+ for await (const chunk of process.stdin) chunks.push(chunk);
122
+ const token = Buffer.concat(chunks).toString('utf8').trim();
123
+ if (!token) throw new Error('--token-stdin was given but standard input was empty.');
124
+ return token;
125
+ }
126
+ const idx = args.indexOf('--token');
127
+ if (idx !== -1) {
128
+ if (!args[idx + 1]) throw new Error('--token needs a value.');
129
+ return args[idx + 1];
130
+ }
131
+ return process.env.BRAIN_STORE_TOKEN || null;
132
+ }
133
+
91
134
  function cmdLogout() {
92
135
  cloud.logout(BRAIN_DIR);
93
136
  console.log('✓ Logged out. Credentials cleared.');
94
137
  }
95
138
 
96
- async function cmdPush() {
139
+ async function cmdPush(args) {
97
140
  console.log('Packing ~/.brain/ ...');
98
- const result = await cloud.push(BRAIN_DIR);
141
+ const result = await cloud.push(BRAIN_DIR, { force: args.includes('--force') });
99
142
  console.log();
100
143
  console.log('✓ Push complete!');
101
144
  console.log(` Size: ${formatBytes(result.size_bytes)}`);
package/bin/install.js CHANGED
@@ -10,17 +10,61 @@ const {
10
10
  initializeBrain,
11
11
  detectInstallations,
12
12
  uninstallForRuntime,
13
+ detectVersionManager,
13
14
  } = require('../src/installer');
14
15
 
16
+ // Interfaces whose stdin has ended. Tracked here because question() on a
17
+ // closed interface throws on some Node versions and silently never calls back
18
+ // on others.
19
+ const ended = new WeakSet();
20
+
15
21
  function createRL() {
16
- return readline.createInterface({
22
+ const rl = readline.createInterface({
17
23
  input: process.stdin,
18
24
  output: process.stdout,
19
25
  });
26
+ rl.once('close', () => ended.add(rl));
27
+ return rl;
20
28
  }
21
29
 
30
+ // Resolves null when stdin ends before an answer arrives — closed stdin, or a
31
+ // pipe that ran dry. Agents and CI run this installer without a terminal; a
32
+ // question that never resolves lets the event loop drain, and the process exits
33
+ // 0 having installed nothing. Callers must handle null (take the default, or
34
+ // fail loudly) rather than treat it as an answer.
22
35
  function ask(rl, question) {
23
- return new Promise((resolve) => rl.question(question, resolve));
36
+ return new Promise((resolve) => {
37
+ if (ended.has(rl)) {
38
+ console.log(question);
39
+ return resolve(null);
40
+ }
41
+ const onClose = () => {
42
+ console.log('');
43
+ resolve(null);
44
+ };
45
+ rl.once('close', onClose);
46
+ rl.question(question, (answer) => {
47
+ rl.removeListener('close', onClose);
48
+ resolve(answer);
49
+ });
50
+ });
51
+ }
52
+
53
+ function assumeYes(flags) {
54
+ return flags.has('yes') || flags.has('y');
55
+ }
56
+
57
+ function warnIfVersionManaged() {
58
+ const vm = detectVersionManager();
59
+ if (!vm) return;
60
+ console.log(`
61
+ ⚠ brain is installed under ${vm.manager} (Node ${vm.version}).
62
+ The \`brain\` command exists for that Node version only. It disappears when your
63
+ default version changes, and shells that don't load ${vm.manager} — agent hooks,
64
+ GUI-launched agents, non-interactive shells — never see it. When agents can't find
65
+ \`brain\` they fall back to editing memory files by hand, with no error.
66
+ Install brain-memory with a system Node instead (Homebrew, apt, the nodejs.org
67
+ installer), then run \`brain update\`.`);
24
68
  }
25
69
 
26
70
  function parseArgs(argv) {
@@ -112,6 +156,11 @@ async function runInstall(flags) {
112
156
  console.log('');
113
157
 
114
158
  const choice = await ask(rl, ' Select (1/2/3/4/5/6/7): ');
159
+ if (choice === null) {
160
+ throw new Error(
161
+ 'no runtime selected and no terminal to ask on. Name one, e.g. `brain install --claude --global`.'
162
+ );
163
+ }
115
164
  switch (choice.trim()) {
116
165
  case '1':
117
166
  runtimes = ['claude'];
@@ -148,15 +197,17 @@ async function runInstall(flags) {
148
197
  console.log('');
149
198
 
150
199
  const choice = await ask(rl, ' Select (1/2): ');
151
- scope = choice.trim() === '2' ? 'local' : 'global';
200
+ scope = choice !== null && choice.trim() === '2' ? 'local' : 'global';
152
201
  }
153
202
 
154
- // Initialize .brain structure?
155
- console.log('');
156
- const initBrain = await ask(
157
- rl,
158
- ' Initialize ~/.brain/ directory? (Y/n): '
159
- );
203
+ // Initialize .brain structure? No answer takes the prompt's own default
204
+ // (yes) — initializeBrain() never overwrites an existing brain.
205
+ let initBrain = 'y';
206
+ if (!assumeYes(flags)) {
207
+ console.log('');
208
+ const answer = await ask(rl, ' Initialize ~/.brain/ directory? (Y/n): ');
209
+ if (answer !== null) initBrain = answer;
210
+ }
160
211
 
161
212
  // Perform installation
162
213
  console.log('\n Installing...');
@@ -196,6 +247,7 @@ async function runInstall(flags) {
196
247
  Your brain is ready — recall and memorize happen automatically. Just start working,
197
248
  or run /brain:status to see an overview.
198
249
  `);
250
+ warnIfVersionManaged();
199
251
  } finally {
200
252
  rl.close();
201
253
  }
@@ -226,7 +278,7 @@ async function runUpdate(flags) {
226
278
 
227
279
  if (detections.length === 0) {
228
280
  console.log(' No existing brain-memory installations found.\n');
229
- console.log(' To install, run: npm install -g brain-memory@beta && brain-memory');
281
+ console.log(' To install, run: npm install -g brain-memory && brain install');
230
282
  if (filterRuntimes.length > 0) {
231
283
  console.log(` (Searched for: ${filterRuntimes.join(', ')})`);
232
284
  }
@@ -251,6 +303,7 @@ async function runUpdate(flags) {
251
303
  }
252
304
 
253
305
  console.log(`\n ✓ Updated to v${version}\n`);
306
+ warnIfVersionManaged();
254
307
  }
255
308
 
256
309
  // ---------------------------------------------------------------------------
@@ -285,12 +338,17 @@ async function runUninstall(flags) {
285
338
  console.log(` ${d.runtimeName} (${d.scope}) — ${parts.join(' + ')}`);
286
339
  }
287
340
 
288
- // Confirm unless --yes
289
- if (!flags.has('yes') && !flags.has('y')) {
341
+ // Confirm unless --yes. No answer (no terminal) is a no: removal is never
342
+ // something to default into.
343
+ if (!assumeYes(flags)) {
290
344
  const rl = createRL();
291
345
  try {
292
346
  console.log('');
293
347
  const answer = await ask(rl, ' Proceed? (y/N): ');
348
+ if (answer === null) {
349
+ console.log(' Cancelled — no terminal to confirm on. Pass --yes to uninstall non-interactively.\n');
350
+ return;
351
+ }
294
352
  if (answer.trim().toLowerCase() !== 'y') {
295
353
  console.log('\n Cancelled.\n');
296
354
  return;
@@ -313,7 +371,7 @@ async function runUninstall(flags) {
313
371
  if (flags.has('delete-data')) {
314
372
  fs.rmSync(brainDir, { recursive: true, force: true });
315
373
  console.log('\n Deleted ~/.brain/ directory.');
316
- } else if (!flags.has('yes') && !flags.has('y')) {
374
+ } else if (!assumeYes(flags)) {
317
375
  const rl = createRL();
318
376
  try {
319
377
  console.log('');
@@ -321,7 +379,7 @@ async function runUninstall(flags) {
321
379
  rl,
322
380
  ' Delete ~/.brain/ data directory? This removes all memories. (y/N): '
323
381
  );
324
- if (answer.trim().toLowerCase() === 'y') {
382
+ if (answer !== null && answer.trim().toLowerCase() === 'y') {
325
383
  fs.rmSync(brainDir, { recursive: true, force: true });
326
384
  console.log(' Deleted ~/.brain/ directory.');
327
385
  } else {