brain-memory 0.4.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,105 @@ 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
+
9
108
  ## [0.4.0] - 2026-09-18
10
109
 
11
110
  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/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 {
package/bin/memorize.js CHANGED
@@ -40,7 +40,7 @@ const { appendAudit } = require('../src/audit');
40
40
  const { lintMemoryContent } = require('../src/content-lint');
41
41
  const { contentHash } = require('../src/integrity');
42
42
  const { proposeSupersessions } = require('../src/contradiction');
43
- const { quarantineDecision } = require('../src/quarantine');
43
+ const { quarantineDecision, isAuthorizationClaim } = require('../src/quarantine');
44
44
  const {
45
45
  validateValidity,
46
46
  supersessionInstant,
@@ -216,6 +216,13 @@ function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier, qua
216
216
  fmLines.push(`quarantine_reasons: [${quarantine.reasons.map((r) => `"${r}"`).join(', ')}]`);
217
217
  fmLines.push(`quarantine_flagged: "${now}"`);
218
218
  }
219
+ // Authorization claim (src/content-lint.js): the memory says the agent may
220
+ // act without asking. Marked so recall and pinning can treat it apart, with
221
+ // the user's own words alongside when the caller supplied them.
222
+ if (mem.authorization) {
223
+ fmLines.push('authorization: true');
224
+ if (mem.authorized_by) fmLines.push(`authorized_by: ${JSON.stringify(JSON.stringify(mem.authorized_by))}`);
225
+ }
219
226
  // Temporal invalidation: record which memories this one replaces. The
220
227
  // reciprocal `superseded_by` is stamped on those targets in main().
221
228
  if (mem.supersedes && mem.supersedes.length) {
@@ -245,6 +252,24 @@ function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier, qua
245
252
  return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
246
253
  }
247
254
 
255
+ /**
256
+ * Validate the optional `authorized_by` backing for an authorization claim:
257
+ * `{ quote, session_id? }`, where `quote` is the user's own words granting the
258
+ * permission. Bounded so a memory cannot smuggle a transcript in through it.
259
+ */
260
+ function normalizeAuthorizedBy(value) {
261
+ if (value == null) return null;
262
+ if (typeof value !== 'object' || Array.isArray(value)) {
263
+ return { error: 'authorized_by must be an object: { quote, session_id? }' };
264
+ }
265
+ const quote = typeof value.quote === 'string' ? value.quote.trim() : '';
266
+ if (!quote) return { error: 'authorized_by.quote must be the user\'s own words, non-empty' };
267
+ if (quote.length > 500) return { error: 'authorized_by.quote is longer than 500 characters' };
268
+ const out = { quote };
269
+ if (typeof value.session_id === 'string' && value.session_id.trim()) out.session_id = value.session_id.trim().slice(0, 120);
270
+ return out;
271
+ }
272
+
248
273
  function buildIndexEntry(mem, id, strength, decayRate, now, origin, quarantine) {
249
274
  const entry = {
250
275
  title: mem.title,
@@ -279,6 +304,10 @@ function buildIndexEntry(mem, id, strength, decayRate, now, origin, quarantine)
279
304
  entry.quarantine_reasons = quarantine.reasons;
280
305
  entry.quarantine_flagged = now;
281
306
  }
307
+ if (mem.authorization) {
308
+ entry.authorization = true;
309
+ if (mem.authorized_by) entry.authorized_by = mem.authorized_by;
310
+ }
282
311
  if (mem.supersedes && mem.supersedes.length) entry.supersedes = mem.supersedes;
283
312
  if (mem.valid_from) entry.valid_from = mem.valid_from;
284
313
  if (mem.valid_until) entry.valid_until = mem.valid_until;
@@ -387,10 +416,11 @@ async function main() {
387
416
  process.exit(1);
388
417
  }
389
418
 
390
- // Read from fd 0 rather than the '/dev/stdin' path: the path form fails with
391
- // ENXIO on Linux CI runners and doesn't exist on Windows, whereas fd 0 reads
392
- // piped stdin portably across Linux, macOS, and Windows.
393
- inputData = fs.readFileSync(0, 'utf-8');
419
+ // Read stdin as a stream. The '/dev/stdin' path fails with ENXIO on Linux CI
420
+ // and doesn't exist on Windows; readFileSync(0) throws EAGAIN on macOS when
421
+ // the parent hands over a non-blocking pipe. The stream handles both.
422
+ process.stdin.setEncoding('utf-8');
423
+ for await (const chunk of process.stdin) inputData += chunk;
394
424
 
395
425
  let input;
396
426
  try {
@@ -490,7 +520,14 @@ async function main() {
490
520
  // (cheap, and the flags feed forensics even when nothing is quarantined);
491
521
  // the decision flags low-trust origins and injection-shaped content.
492
522
  const lint = lintMemoryContent(mem);
493
- const quarantine = quarantineDecision({ origin, lintResult: lint, config });
523
+ const authorizedBy = normalizeAuthorizedBy(mem.authorized_by);
524
+ if (authorizedBy && authorizedBy.error) {
525
+ console.error(JSON.stringify({ error: `${authorizedBy.error} — memory: ${JSON.stringify(rawMem.title)}` }));
526
+ process.exit(1);
527
+ }
528
+ const quarantine = quarantineDecision({ origin, lintResult: lint, config, authorizedBy });
529
+ mem.authorization = isAuthorizationClaim(lint);
530
+ mem.authorized_by = mem.authorization ? authorizedBy : undefined;
494
531
 
495
532
  // Sensitive-topic consent (src/sensitivity.js). `blocked` content is
496
533
  // refused outright; `sensitive` content is stored only after the user
@@ -516,6 +553,11 @@ async function main() {
516
553
  quarantine.reasons = [...quarantine.reasons, SENSITIVE_OPT_OUT_REASON];
517
554
  }
518
555
  mem.sensitivity = sensitivity.level;
556
+ // A write that lands pending verification cannot be born pinned: the pin
557
+ // would load an unreviewed memory into every session. Dropped, not
558
+ // refused, so the memory itself is kept — the result says why.
559
+ const pinDropped = Boolean(mem.pinned && quarantine.quarantined);
560
+ if (pinDropped) mem.pinned = false;
519
561
 
520
562
  // Generate ID
521
563
  const id = generateId();
@@ -665,6 +707,8 @@ async function main() {
665
707
  // until the user opts in (config) or approves it (`brain verify approve`).
666
708
  ...(mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity } : {}),
667
709
  ...(sensitivity.action === 'quarantine' ? { sensitive_opt_out: true } : {}),
710
+ ...(mem.authorization ? { authorization_claim: true } : {}),
711
+ ...(pinDropped ? { pin_dropped: 'pending verification — pin it after `brain verify approve`' } : {}),
668
712
  ...(supersededNow.length ? { superseded: supersededNow } : {}),
669
713
  // Held back until verification — surfaced so the agent can tell the user
670
714
  // the replacement it asked for has not taken effect yet.