brain-memory 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,138 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.5.1] - 2026-10-18
10
+
11
+ An account with several brains can now choose which one each device, and the
12
+ connector, syncs with. A device that has just linked a brain can no longer
13
+ overwrite that brain's memories with its first push.
14
+
15
+ ### Added
16
+ - **Choose a brain when an account has several.** `brain cloud login --brain
17
+ NAME|ID` links that brain (creating it when no brain has that name); without
18
+ it, login links the account's first brain as before, and now creates a
19
+ `default` brain for an empty account on the device flow too. `brain cloud
20
+ brains` lists the account's brains, and `brain cloud use NAME|ID [--create]`
21
+ switches which one this device syncs with, leaving `~/.brain/` as it is.
22
+ Names match ignoring case. In the connector, `brain_status` lists the brains
23
+ with the one in use marked, and a new `brain_use` tool switches; the choice is
24
+ kept per user across sessions, and a chosen brain that is deleted falls back
25
+ to the oldest.
26
+
27
+ ### Changed
28
+ - A device that has never synced with its linked brain (a fresh login, or after
29
+ `brain cloud use`) now pushes only into a brain with no archive yet
30
+ (`If-None-Match: *`). Pull first, or `--force`, to replace a brain that has
31
+ memories. Configs that predate conditional sync keep pushing as before.
32
+
33
+ ### Fixed
34
+ - The connector pushes a write to the brain its working copy came from, and
35
+ drops the previous brain's copy when the brain it serves changes, so one
36
+ brain's memories are never shown under or pushed into another.
37
+ - `brain memorize` reads stdin as a stream, so piping into it on macOS can no
38
+ longer fail with `EAGAIN`.
39
+ - The Cursor plugin manifest and the MCP Registry entry (`server.json`) now
40
+ follow the package version on every release.
41
+
42
+ ## [0.5.0] - 2026-10-18
43
+
44
+ Memory stops being a way to smuggle instructions or permissions into an agent.
45
+ Memories from outside the user/agent dialogue are now left out of recall until
46
+ the user approves them, not merely marked. A remembered permission is its own
47
+ class that needs the user's own words behind it. Every receipt the agent cites
48
+ is checked against what brain actually surfaced. On a poisoned LongMemEval run,
49
+ down-weighting left the planted memory at rank 1 for 90% of questions, while
50
+ exclusion restored the clean-run R@1 of 0.551. `brain port` moves memories to
51
+ and from other memory systems.
52
+
53
+ ### Added
54
+ - **Permissions are their own class of memory.** A write that says the agent
55
+ may act without asking ("the user approved force-pushes to main", "no need to
56
+ confirm deploys", "pre-approved") is an authorization claim. From any origin
57
+ but `user` it lands pending verification (`authz:unbacked`); a `user` one does
58
+ too (`authz:no-source`) unless it carries the user's own words in
59
+ `authorized_by.quote`. Such memories are pinnable only when user-origin and
60
+ backed or approved, are marked `authorization_claim` in recall and
61
+ session-start results, and carry `⚠ authorization` on their receipts. The
62
+ agent prompts say a remembered permission is never consent for the action at
63
+ hand. `brain audit` reports older memories the new lint rule would have
64
+ caught. The connector's `brain_memorize` accepts `authorized_by`.
65
+ - **Citation lock.** Recall, session start and prompt-time recall record what
66
+ they surfaced in a device-local ledger (`~/.brain/.local/`, excluded from
67
+ every sync, export and restore). A new `Stop` hook (Claude Code, Codex)
68
+ checks every `◉ memory:` receipt in the agent's reply against it; a receipt
69
+ for a memory brain never surfaced is logged as a `citation_violation` audit
70
+ event and reported to the agent on its next prompt. Advisory: the reply is
71
+ never blocked.
72
+ - **Low-trust occupancy cap.** `recall_low_trust_max` (default `1`) bounds how
73
+ many `tool-output` / `external` memories a recall result or session-start
74
+ payload may hold, approved or not; the rest are skipped for the next trusted
75
+ match and reported as `low_trust_suppressed`.
76
+ - **`brain port`** moves memories between brain and other memory systems:
77
+ `export --format claude-memory|markdown|agentcore` writes what recall could
78
+ show (memories pending verification, hidden or expired are left out and
79
+ counted); `import --from …` sends memories through `brain memorize` as
80
+ `external`, so they wait for review unless `--trust` marks them as yours.
81
+ Covers Claude Code's memory files, a pasteable dated list (Claude.ai's
82
+ import format), and AgentCore `BatchCreateMemoryRecords` bodies. What
83
+ survives a round trip is documented per format.
84
+ - **Poisoned LongMemEval benchmark** (`benchmark/harness/longmemeval-poison.js`):
85
+ free, deterministic, retrieval-only. With a planted wrong-answer session per
86
+ question, exclusion keeps clean-haystack retrieval (R@1 0.551, R@5 0.909, the
87
+ poison never in the top 5); trust weighting alone lets the poison rank first
88
+ for 90% of questions. Results in `benchmark/results/REPORT.md`.
89
+ - **Plugin eval suite** (`evals/`) for `claude plugin eval`: eight cases that
90
+ seed a throwaway brain and check pinned conventions, past decisions,
91
+ poisoned-memory exclusion, no invented receipts, permissions not treated as
92
+ consent, memorize-on-request, and a fat-vs-thin AGENTS.md cost pair. A
93
+ manual-dispatch workflow runs it in CI.
94
+ - **Messages API integration** (`integrations/api/`): `withBrainTurn()`
95
+ recalls on each user message and appends the matches as a turn-scoped
96
+ system message (`clear_at: "next_user_message"`) under a token cap.
97
+ - **Git review template** (`integrations/git-review/`): a GitHub Actions check
98
+ for a brain git-sync repository that runs `brain audit` on every push.
99
+ - `docs/security/asi06.md`: Brain's controls mapped onto OWASP ASI06, every
100
+ CLI command and connector tool classified by effect, the threats not
101
+ covered, and the benchmark evidence.
102
+ - Session start reports `recall_usage_7d`: how many surfaced memories the agent
103
+ went on to use (`brain reinforce`).
104
+ - **`brain verify requeue <id>`**, an undo for a mistaken approve. It puts the
105
+ memory back into pending verification, clears `vetted` (which also withdraws
106
+ per-item consent for a sensitive memory), rebuilds the reasons approval
107
+ dropped, and logs a `verify_requeue` audit event. A pinned memory is refused
108
+ rather than silently unpinned.
109
+ - **Install without a terminal.** `brain --claude --global` (installer flags
110
+ with no subcommand) runs the installer, so an agent or a CI job can install
111
+ brain by itself. With nothing to ask on, the installer initializes `~/.brain/`
112
+ if it does not exist and never overwrites one; `--yes` skips that question on
113
+ a terminal too.
114
+ - The installer warns when brain is installed under nvm, fnm, asdf, mise or
115
+ nodenv: the command exists for that Node version only, so it disappears when
116
+ the default version moves and agent hooks never see it.
117
+ - Website: a Self-Hosting a Store page, and documentation for token login and
118
+ refused pushes.
119
+
120
+ ### Changed
121
+ - **Quarantine excludes by default.** `quarantine_mode` now defaults to
122
+ `enforce`: memories pending verification are left out of recall and session
123
+ start until approved, instead of being returned with a `⊘ unverified` mark.
124
+ Down-weighting a poisoned memory does not keep it out of the context window
125
+ when it is the best match; exclusion does. They are still counted in
126
+ `pending_verification`. Set `"quarantine_mode": "flag"` in
127
+ `~/.brain/config.json` to keep the previous behavior. An unrecognized value
128
+ now falls back to `enforce`, never to `off`.
129
+ - A write that lands pending verification is no longer born pinned; the output
130
+ reports `pin_dropped`.
131
+ - The agent prompts say to approve only the exact ids the user reviewed, never
132
+ a fresh listing, because other sessions write concurrently.
133
+
134
+ ### Fixed
135
+ - The `secret_exfil` lint no longer quarantines ordinary engineering notes
136
+ ("the password-reset email", a code literal such as `upload`) as injections.
137
+ - `test/harvest.test.js` no longer depends on the `~/.codex` of whoever runs it.
138
+ - The Compose environment template is `store/deploy/env.example`; as
139
+ `.env.example` it was ignored by git and npm and never shipped.
140
+
9
141
  ## [0.4.0] - 2026-09-18
10
142
 
11
143
  Opens up sync. The HTTP interface between a Brain client and a remote store is
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
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
@@ -4,10 +4,13 @@
4
4
  * brain cloud — CLI for syncing with Brain Cloud or a self-hosted brain-store
5
5
  *
6
6
  * Usage:
7
- * brain cloud login [--api-url URL] Authenticate via device code flow
7
+ * brain cloud login [--api-url URL] [--brain NAME|ID]
8
+ * Authenticate via device code flow
8
9
  * brain cloud login --api-url URL --token-stdin
9
10
  * Authenticate to a self-hosted store with a token
10
11
  * brain cloud logout Clear stored credentials
12
+ * brain cloud brains List the account's brains
13
+ * brain cloud use NAME|ID [--create] Sync with another brain
11
14
  * brain cloud push [--force] Upload ~/.brain/ to the cloud
12
15
  * brain cloud pull Download from the cloud to ~/.brain/
13
16
  * brain cloud status Show connection and sync status
@@ -30,7 +33,12 @@ brain cloud — Brain Cloud sync CLI
30
33
 
31
34
  Commands:
32
35
  login [--api-url URL] Authenticate via device code flow
36
+ [--brain NAME|ID] Link this brain (created if no brain has that name);
37
+ without it, the account's first brain
33
38
  logout Clear stored credentials
39
+ brains List the account's brains; * marks the linked one
40
+ use NAME|ID [--create] Sync with another brain. ~/.brain/ is left as it is:
41
+ pull to load that brain, or push into an empty one
34
42
  push [--force] Upload ~/.brain/ to the cloud
35
43
  pull Download from the cloud to ~/.brain/
36
44
  status Show connection and sync status
@@ -54,6 +62,12 @@ push refuses to overwrite changes it has not pulled. --force uploads anyway.
54
62
  case 'logout':
55
63
  cmdLogout();
56
64
  break;
65
+ case 'brains':
66
+ await cmdBrains();
67
+ break;
68
+ case 'use':
69
+ await cmdUse(args);
70
+ break;
57
71
  case 'push':
58
72
  await cmdPush(args);
59
73
  break;
@@ -76,19 +90,22 @@ async function cmdLogin(args) {
76
90
  apiUrl = args[urlIdx + 1];
77
91
  }
78
92
 
93
+ const brain = flagValue(args, '--brain');
94
+
79
95
  const token = await readToken(args);
80
96
  if (token) {
81
97
  const result = await cloud.loginWithToken(BRAIN_DIR, apiUrl, token, {
82
98
  allowHttp: args.includes('--allow-http'),
99
+ brain,
83
100
  });
84
101
  console.log(`✓ Logged in as ${result.user_email || 'unknown'}`);
85
- console.log(` Brain ID: ${result.brain_id}`);
102
+ printLinked(result.brain_id, result.brain_name, result);
86
103
  console.log(` API: ${result.api_url}`);
87
104
  return;
88
105
  }
89
106
 
90
107
  console.log('Requesting device code...');
91
- const loginInfo = await cloud.login(BRAIN_DIR, apiUrl);
108
+ const loginInfo = await cloud.login(BRAIN_DIR, apiUrl, { brain });
92
109
 
93
110
  console.log();
94
111
  console.log(' Open this URL in your browser to log in:');
@@ -99,17 +116,58 @@ async function cmdLogin(args) {
99
116
  console.log();
100
117
  console.log(` Waiting for approval (expires in ${Math.floor(loginInfo.expires_in / 60)} min)...`);
101
118
 
102
- await loginInfo.waitForApproval();
119
+ const choice = await loginInfo.waitForApproval();
103
120
 
104
121
  const config = cloud.readConfig(BRAIN_DIR);
105
122
  console.log();
106
123
  console.log(`✓ Logged in as ${config.user_email || 'unknown'}`);
107
- if (config.brain_id) {
108
- console.log(` Brain ID: ${config.brain_id}`);
109
- }
124
+ printLinked(config.brain_id, config.brain_name, choice || {});
110
125
  console.log(` API: ${config.api_url}`);
111
126
  }
112
127
 
128
+ function flagValue(args, flag) {
129
+ const idx = args.indexOf(flag);
130
+ if (idx === -1) return undefined;
131
+ if (!args[idx + 1] || args[idx + 1].startsWith('--')) throw new Error(`${flag} needs a value.`);
132
+ return args[idx + 1];
133
+ }
134
+
135
+ /** After a login: which brain is linked, and the others an account has. */
136
+ function printLinked(brainId, brainName, { brains = [], created = false }) {
137
+ console.log(` Brain: ${brainName ? `"${brainName}" ` : ''}(${brainId})${created ? ' — new' : ''}`);
138
+ const others = brains.filter((b) => b.id !== brainId);
139
+ if (others.length > 0) {
140
+ console.log(` This account has ${others.length} other brain${others.length === 1 ? '' : 's'}: ${others.map((b) => `"${b.name}"`).join(', ')}`);
141
+ console.log(' Switch with: brain cloud use <name>');
142
+ }
143
+ }
144
+
145
+ async function cmdBrains() {
146
+ const brains = await cloud.listBrains(BRAIN_DIR);
147
+ if (brains.length === 0) {
148
+ console.log('This account has no brains yet. `brain cloud push` creates one.');
149
+ return;
150
+ }
151
+ for (const b of brains) {
152
+ const synced = b.last_synced_at ? `synced ${String(b.last_synced_at).slice(0, 10)}` : 'never synced';
153
+ console.log(`${b.linked ? '*' : ' '} ${b.name} (${b.id}) ${b.file_count || 0} files, ${synced}`);
154
+ }
155
+ }
156
+
157
+ async function cmdUse(args) {
158
+ const selector = args.slice(1).find((a) => !a.startsWith('--'));
159
+ if (!selector) throw new Error('Usage: brain cloud use <name|id> [--create]');
160
+ const result = await cloud.useBrain(BRAIN_DIR, selector, { create: args.includes('--create') });
161
+ if (!result.changed) {
162
+ console.log(`Already syncing with "${result.brain.name}".`);
163
+ return;
164
+ }
165
+ console.log(`✓ Now syncing with "${result.brain.name}" (${result.brain.id})${result.created ? ' — new' : ''}`);
166
+ console.log(' ~/.brain/ is unchanged. Next:');
167
+ console.log(' brain cloud pull replace it with this brain\'s memories');
168
+ console.log(' brain cloud push upload it, if this brain is still empty');
169
+ }
170
+
113
171
  /**
114
172
  * A store token from --token-stdin, --token, or BRAIN_STORE_TOKEN, in that order.
115
173
  * Standard input is preferred: it keeps the token out of shell history and out of
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 {