brain-memory 0.1.0-beta.31 → 0.1.0-beta.33

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,47 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.1.0-beta.33] - 2026-07-04
10
+
11
+ _Covers everything since v0.1.0-beta.31, including the changes first shipped in the changelog-less 0.1.0-beta.32._
12
+
13
+ ### Added
14
+
15
+ - **Recall receipts — memory that visibly fires.** Every memory returned by
16
+ `brain recall` and `brain session-start` now carries an engine-minted
17
+ `receipt` line (`◉ memory: "<title>" (<type>, <age>)`). Hosts end a response
18
+ with the receipts of the memories that actually shaped it — max 3, copied
19
+ verbatim, pinned facts only when decisive, none when none were used. A
20
+ receipt can only exist if the engine returned that memory, so receipts
21
+ cannot be hallucinated.
22
+ - **Four new agent hosts.** Native integrations under `integrations/` for
23
+ **OpenClaw / NVIDIA NemoClaw** (memory-slot plugin `openclaw-brain-memory`
24
+ replacing `memory-core`, slot-neutral hook pack, ClawHub skill, NemoClaw
25
+ egress-policy preset — all live-verified), **Hermes Agent** (full
26
+ `MemoryProvider` plugin, shipped standalone as the `hermes-brain-memory`
27
+ pip package per upstream policy), **GitHub Copilot CLI** (plugin with
28
+ `sessionStart` context injection + skills; the repo is now a Copilot plugin
29
+ marketplace via `.github/plugin/marketplace.json` — install with
30
+ `copilot plugin install brain-memory@brain`), and **Kilo** (runtime plugin
31
+ with chat-message injection, session tracking, and `BRAIN_AGENT` labeling).
32
+ - **Two new installer runtimes.** `brain --copilot` (global prompt at
33
+ `~/.copilot/copilot-instructions.md`, skills in the cross-tool
34
+ `~/.agents/skills/`) and `brain --kilo` (prompt registered in the
35
+ `kilo.jsonc` `instructions` array via a safe strict-JSON editor; repo-local
36
+ `AGENTS.md` shared with Codex/OpenCode).
37
+
38
+ ### Fixed
39
+
40
+ - Kilo plugin derives the project label from `input.project` as well, so a
41
+ plugin host running with cwd `/` no longer records sessions as project
42
+ `"unknown"`.
43
+ - Hermes `cli.py` is a standalone diagnostics tool (`python3 cli.py
44
+ status|recall`) — Hermes exposes no CLI hook to user-installed memory
45
+ providers, so the previously documented `hermes memory recall` never
46
+ existed.
47
+ - Every `npm publish` now runs the full test suite via `prepublishOnly` —
48
+ the old `prerelease` script was a no-op vestige no release path invoked.
49
+
9
50
  ## [0.1.0-beta.31] - 2026-07-01
10
51
 
11
52
  ### Fixed
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  A hierarchical, file-system-based memory plugin for AI coding agents. Inspired by human neuroscience — memories are organized into deep nested life-domain categories, connected via associative networks, strengthened through spaced recall, and naturally decay over time.
14
14
 
15
- One hosted **MCP connector** reaches every major agent and chat app — **Claude Code**, **OpenAI Codex CLI**, **OpenCode**, the **Claude.ai** apps, **ChatGPT**, and **Google Antigravity** (Gemini CLI's successor). Prefer a free, local-first install? The native plugin runs entirely from `~/.brain/` on Claude Code, Codex, OpenCode, and Antigravity.
15
+ One hosted **MCP connector** reaches every major agent and chat app — **Claude Code**, **OpenAI Codex CLI**, **OpenCode**, **GitHub Copilot CLI**, **Kilo**, the **Claude.ai** apps, **ChatGPT**, **Google Antigravity** (Gemini CLI's successor), **OpenClaw** / **NVIDIA NemoClaw**, **Hermes Agent**, and **Goose**. Prefer a free, local-first install? The native plugin runs entirely from `~/.brain/` on Claude Code, Codex, OpenCode, Copilot CLI, Kilo, and Antigravity — and dedicated [native integrations](integrations/) plug the same brain into OpenClaw and Hermes as their memory engine.
16
16
 
17
17
  ```
18
18
  ~/.brain/
@@ -40,6 +40,7 @@ Existing AI memory solutions use flat databases with tag-based retrieval. Brain
40
40
  - **Human-inspectable** — Browse your "brain" in any file explorer
41
41
  - **Git-friendly** — Full version history of how memories evolve
42
42
  - **Strength + decay** — Recalled memories get stronger, forgotten ones fade. Just like your brain
43
+ - **Recall receipts** — Memory that visibly fires: every answer shaped by a memory ends with a one-line attributable receipt (`◉ memory: "<title>" (<type>, <age>)`), minted by the engine so it can't be hallucinated
43
44
  - **Associative network** — Memories link to each other with weighted connections. Recalling one activates related ones automatically
44
45
  - **Context-dependent recall** — Memories encoded in a similar context to the current session are scored higher
45
46
  - **Spaced reinforcement** — Memories recalled after longer intervals get bigger boosts, cramming produces diminishing returns
@@ -56,8 +57,9 @@ There are two ways to give an agent its brain. They are complementary — most p
56
57
 
57
58
  | Path | Reaches | Storage | Cost | Best for |
58
59
  |------|---------|---------|------|----------|
59
- | **Hosted MCP connector** | Every MCP-capable host (Claude Code, Codex CLI, OpenCode, Claude.ai apps, ChatGPT, Antigravity) | Brain Cloud (hosted) | account | One connector, everywhere — including web & mobile chat |
60
- | **Local-first native plugin** | The current CLIs (Claude Code, Codex CLI, OpenCode, Antigravity) | `~/.brain/` on your machine | free | Zero-config ambient memory, no account, files you own |
60
+ | **Hosted MCP connector** | Every MCP-capable host (Claude Code, Codex CLI, OpenCode, Copilot CLI, Kilo, Claude.ai apps, ChatGPT, Antigravity, OpenClaw, Hermes, Goose) | Brain Cloud (hosted) | account | One connector, everywhere — including web & mobile chat |
61
+ | **Local-first native plugin** | The current CLIs (Claude Code, Codex CLI, OpenCode, Copilot CLI, Kilo, Antigravity) | `~/.brain/` on your machine | free | Zero-config ambient memory, no account, files you own |
62
+ | **[Assistant integrations](integrations/)** | OpenClaw / NVIDIA NemoClaw (memory-slot plugin), Hermes Agent (memory provider) | `~/.brain/` on your machine | free | Your always-on personal assistant sharing one brain with your coding agents |
61
63
 
62
64
  ### 1. Universal path — the hosted MCP connector
63
65
 
@@ -89,6 +91,29 @@ codex mcp add brain --url https://mcp.brainmemory.ai/mcp
89
91
  ```
90
92
  - **Claude.ai / ChatGPT** — **Settings → Connectors → Add custom connector**, paste `https://mcp.brainmemory.ai/mcp`, and complete the OAuth sign-in. (ChatGPT requires a paid plan or Developer Mode.)
91
93
  - **Google Antigravity** — add to `mcp_config.json` under the `serverUrl` key. *(Legacy Gemini CLI used the `httpUrl` key in `settings.json`.)*
94
+ - **GitHub Copilot CLI** — add to `~/.copilot/mcp-config.json` (OAuth via `/mcp auth brain` in-session):
95
+ ```json
96
+ {
97
+ "mcpServers": {
98
+ "brain-memory": { "type": "http", "url": "https://mcp.brainmemory.ai/mcp", "tools": ["*"] }
99
+ }
100
+ }
101
+ ```
102
+ - **OpenClaw** — `openclaw mcp add brain-memory --url https://mcp.brainmemory.ai/mcp --auth oauth`, then `openclaw mcp login brain-memory`. (Inside NVIDIA NemoClaw, allowlist the endpoint first — see [integrations/openclaw](integrations/openclaw/).)
103
+ - **Hermes Agent** — add to `~/.hermes/config.yaml`:
104
+ ```yaml
105
+ mcp_servers:
106
+ brain: { url: "https://mcp.brainmemory.ai/mcp", auth: oauth }
107
+ ```
108
+ - **Goose** — add a remote extension (streamable-HTTP) pointing at `https://mcp.brainmemory.ai/mcp`.
109
+ - **Kilo** — add to `kilo.jsonc` (OAuth starts automatically):
110
+ ```json
111
+ {
112
+ "mcp": {
113
+ "brain-memory": { "type": "remote", "url": "https://mcp.brainmemory.ai/mcp", "enabled": true }
114
+ }
115
+ }
116
+ ```
92
117
 
93
118
  </details>
94
119
 
@@ -110,6 +135,8 @@ The second command runs the setup wizard, which asks which runtime(s) to configu
110
135
  | **Claude Code** | `CLAUDE.md` | `~/.claude/commands/brain/` (plugin slash commands) |
111
136
  | **OpenAI Codex CLI** | `AGENTS.md` (`~/.codex/`) | `~/.agents/skills/<name>/SKILL.md` |
112
137
  | **OpenCode** | `AGENTS.md` | `~/.config/opencode/commands/` |
138
+ | **GitHub Copilot CLI** | `copilot-instructions.md` (`~/.copilot/`), repo-local `AGENTS.md` | `~/.agents/skills/<name>/SKILL.md` (shared with Codex) |
139
+ | **Kilo** | `rules/brain-memory.md` + `kilo.jsonc` `instructions` entry (`~/.config/kilo/`), repo-local `AGENTS.md` | `~/.config/kilo/commands/` |
113
140
  | **Google Antigravity** | `GEMINI.md` | `~/.gemini/skills/` *(experimental — verify paths against a live install)* |
114
141
 
115
142
  #### Non-interactive
@@ -118,10 +145,35 @@ The second command runs the setup wizard, which asks which runtime(s) to configu
118
145
  brain --claude --global # Claude Code, global
119
146
  brain --codex --global # OpenAI Codex CLI, global
120
147
  brain --opencode --global # OpenCode, global
148
+ brain --copilot --global # GitHub Copilot CLI, global
149
+ brain --kilo --global # Kilo, global
121
150
  brain --antigravity --global # Google Antigravity, global (experimental)
122
151
  brain --all --global # All runtimes, global
123
152
  ```
124
153
 
154
+ 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:
155
+
156
+ ```bash
157
+ copilot plugin marketplace add omelas-tech/brain
158
+ copilot plugin install brain-memory@brain
159
+ ```
160
+
161
+ Kilo gets the same treatment via its runtime plugin — deterministic session-start injection, session tracking, and `BRAIN_AGENT` labeling ([details](integrations/kilo/)):
162
+
163
+ ```bash
164
+ mkdir -p ~/.config/kilo/plugin
165
+ cp integrations/kilo/plugin/brain-memory.js ~/.config/kilo/plugin/
166
+ ```
167
+
168
+ ### 3. Personal-assistant integrations — OpenClaw, NemoClaw, Hermes
169
+
170
+ Always-on personal assistants get deeper, first-class integrations that make `~/.brain/` their actual memory engine — the same brain your coding agents read and write:
171
+
172
+ - **[OpenClaw / NVIDIA NemoClaw](integrations/openclaw/)** — a native **memory-slot plugin** (`openclaw plugins install openclaw-brain-memory` + `plugins.slots.memory: "brain-memory"`) that replaces `memory-core` with deterministic brain recall, session-start context injection, and model-driven capture. Also ships a slot-neutral hook pack, a ClawHub skill, and a NemoClaw egress-policy preset.
173
+ - **[Hermes Agent](integrations/hermes/)** — a native **memory provider** (`plugins/memory/brain/`) implementing the full `MemoryProvider` lifecycle: session-start prompt block, pre-turn prefetch, `brain_recall`/`brain_memorize`/`brain_reinforce` tools, and session-context logging. Plus lightweight hook-script glue if you keep another provider active.
174
+
175
+ Both are backed by the same `brain` CLI the coding-agent installs use — one memory, every agent.
176
+
125
177
  ### Update
126
178
 
127
179
  ```bash
package/bin/install.js CHANGED
@@ -52,8 +52,12 @@ function resolveRuntimesFromFlags(flags) {
52
52
  if (flags.has('openai') || flags.has('codex')) runtimes.push('openai');
53
53
  if (flags.has('opencode')) runtimes.push('opencode');
54
54
  if (flags.has('antigravity')) runtimes.push('antigravity');
55
+ if (flags.has('copilot')) runtimes.push('copilot');
56
+ if (flags.has('kilo')) runtimes.push('kilo');
55
57
  // --all installs the verified CLIs. Antigravity stays opt-in (--antigravity)
56
58
  // because its native paths are experimental / pending live verification.
59
+ // Copilot's paths come from official GA docs but stay opt-in (--copilot)
60
+ // until confirmed against a live install.
57
61
  if (flags.has('all')) return ['claude', 'openai', 'opencode'];
58
62
  return runtimes;
59
63
  }
@@ -64,6 +68,19 @@ function resolveScopeFromFlags(flags) {
64
68
  return null;
65
69
  }
66
70
 
71
+ // Kilo's global prompt must be listed in the `instructions` array of
72
+ // kilo.jsonc; the installer only edits that file when it can do so safely
73
+ // (strict JSON, no comments). Otherwise, tell the user the one manual step.
74
+ function warnIfManualRegistration(result, config) {
75
+ const reg = result.promptRegistration;
76
+ if (reg && reg.manual) {
77
+ const configPath = `${config.globalDir}/${config.instructionsConfig}`;
78
+ const promptPath = `${config.globalDir}/${config.promptFile}`;
79
+ console.log(` ⚠ Could not edit ${configPath} safely (${reg.reason}).`);
80
+ console.log(` Add "${promptPath}" to its "instructions" array to activate the global prompt.`);
81
+ }
82
+ }
83
+
67
84
  // ---------------------------------------------------------------------------
68
85
  // Install (original behavior, refactored from main)
69
86
  // ---------------------------------------------------------------------------
@@ -80,11 +97,13 @@ async function runInstall(flags) {
80
97
  console.log(' 1) Claude Code');
81
98
  console.log(' 2) OpenAI Codex CLI');
82
99
  console.log(' 3) OpenCode');
83
- console.log(' 4) Google Antigravity (experimental)');
84
- console.log(' 5) All current CLIs (Claude Code + Codex + OpenCode)');
100
+ console.log(' 4) GitHub Copilot CLI');
101
+ console.log(' 5) Kilo');
102
+ console.log(' 6) Google Antigravity (experimental)');
103
+ console.log(' 7) All current CLIs (Claude Code + Codex + OpenCode)');
85
104
  console.log('');
86
105
 
87
- const choice = await ask(rl, ' Select (1/2/3/4/5): ');
106
+ const choice = await ask(rl, ' Select (1/2/3/4/5/6/7): ');
88
107
  switch (choice.trim()) {
89
108
  case '1':
90
109
  runtimes = ['claude'];
@@ -96,9 +115,15 @@ async function runInstall(flags) {
96
115
  runtimes = ['opencode'];
97
116
  break;
98
117
  case '4':
99
- runtimes = ['antigravity'];
118
+ runtimes = ['copilot'];
100
119
  break;
101
120
  case '5':
121
+ runtimes = ['kilo'];
122
+ break;
123
+ case '6':
124
+ runtimes = ['antigravity'];
125
+ break;
126
+ case '7':
102
127
  runtimes = ['claude', 'openai', 'opencode'];
103
128
  break;
104
129
  default:
@@ -130,8 +155,9 @@ async function runInstall(flags) {
130
155
  for (const runtime of runtimes) {
131
156
  const config = RUNTIMES[runtime];
132
157
  console.log(`\n Installing for ${config.name} (${scope})...`);
133
- installForRuntime(runtime, scope);
158
+ const result = installForRuntime(runtime, scope) || {};
134
159
  console.log(` Done!`);
160
+ warnIfManualRegistration(result, config);
135
161
  }
136
162
 
137
163
  // Initialize .brain if requested
@@ -210,8 +236,9 @@ async function runUpdate(flags) {
210
236
  console.log('\n Updating...');
211
237
  for (const d of detections) {
212
238
  console.log(`\n Updating ${d.runtimeName} (${d.scope})...`);
213
- installForRuntime(d.runtime, d.scope);
239
+ const result = installForRuntime(d.runtime, d.scope) || {};
214
240
  console.log(' Done!');
241
+ warnIfManualRegistration(result, RUNTIMES[d.runtime]);
215
242
  }
216
243
 
217
244
  console.log(`\n ✓ Updated to v${version}\n`);
package/bin/recall.js CHANGED
@@ -39,6 +39,8 @@ const {
39
39
  rankMemories,
40
40
  } = require('../src/scorer');
41
41
 
42
+ const { receiptFor } = require('../src/receipt');
43
+
42
44
  // Minimum relevance (or spreading bonus) for a memory to appear in explicit-
43
45
  // query results. Filters the zero/near-zero-relevance memories that would
44
46
  // otherwise pad the top-N purely on strength — an agent trusting those scores
@@ -140,19 +142,25 @@ function main() {
140
142
 
141
143
  // Return top N
142
144
  const top = args.top || 10;
143
- const results = ranked.slice(0, top).map((mem) => ({
144
- id: mem.id,
145
- title: mem.title || path.basename(mem.path, '.md'),
146
- path: mem.path,
147
- type: mem.type,
148
- score: mem.score,
149
- relevance: mem.relevance,
150
- decayed_strength: mem.decayed_strength,
151
- context_match: mem.context_match,
152
- spreading_bonus: mem.spreading_bonus,
153
- confidence: mem.confidence,
154
- tags: mem.tags,
155
- }));
145
+ const results = ranked.slice(0, top).map((mem) => {
146
+ const title = mem.title || path.basename(mem.path, '.md');
147
+ return {
148
+ id: mem.id,
149
+ title,
150
+ path: mem.path,
151
+ type: mem.type,
152
+ score: mem.score,
153
+ relevance: mem.relevance,
154
+ decayed_strength: mem.decayed_strength,
155
+ context_match: mem.context_match,
156
+ spreading_bonus: mem.spreading_bonus,
157
+ confidence: mem.confidence,
158
+ tags: mem.tags,
159
+ // Recall receipt — the engine mints it, agents copy it verbatim when
160
+ // this memory materially shapes an answer (so it can't be hallucinated).
161
+ receipt: receiptFor({ ...mem, title }),
162
+ };
163
+ });
156
164
 
157
165
  console.log(JSON.stringify(results, null, 2));
158
166
  }
@@ -42,6 +42,7 @@ const {
42
42
 
43
43
  const { rankMemories } = require('../src/scorer');
44
44
  const { advertisedSummaries } = require('../src/skills');
45
+ const { receiptFor } = require('../src/receipt');
45
46
 
46
47
  function parseArgs(argv) {
47
48
  const args = { project: null, topics: null, task: null, top: 5 };
@@ -63,6 +64,11 @@ function estimateTokens(entry) {
63
64
  return Math.ceil(((entry.title || '').length + 8) / 4);
64
65
  }
65
66
 
67
+ /** chars/4 token estimate for a minted receipt line (counted against budgets). */
68
+ function receiptTokens(receipt) {
69
+ return receipt ? Math.ceil(receipt.length / 4) : 0;
70
+ }
71
+
66
72
  /**
67
73
  * Tier B §10.4 — reorder an importance-sorted list so the top items land at the
68
74
  * edges (start + end), where models attend best, leaving the middle for lower
@@ -186,7 +192,8 @@ function computeSessionStart(projectRoot, args = {}) {
186
192
  let pinnedExcluded = 0;
187
193
  const pinCap = Math.min(config.pin_budget_tokens, cap);
188
194
  for (const c of pinnedCandidates) {
189
- const est = estimateTokens(c.entry);
195
+ const receipt = receiptFor(c.entry);
196
+ const est = estimateTokens(c.entry) + receiptTokens(receipt);
190
197
  if (pinnedTokens + est > pinCap && pinned.length > 0) { pinnedExcluded++; continue; }
191
198
  pinned.push({
192
199
  id: c.id,
@@ -195,6 +202,7 @@ function computeSessionStart(projectRoot, args = {}) {
195
202
  scope: c.scope,
196
203
  priority: c.priority,
197
204
  tokens: est,
205
+ receipt,
198
206
  });
199
207
  pinnedTokens += est;
200
208
  }
@@ -220,18 +228,21 @@ function computeSessionStart(projectRoot, args = {}) {
220
228
  let excluded = 0;
221
229
  for (const mem of ranked.slice(0, top)) {
222
230
  if (pinnedIds.has(mem.id)) continue; // already presented in the pinned tier
223
- const est = estimateTokens(mem);
231
+ const title = mem.title || path.basename(mem.path || '', '.md');
232
+ const receipt = receiptFor({ ...mem, title });
233
+ const est = estimateTokens(mem) + receiptTokens(receipt);
224
234
  if (used + est > recallCap && context_recall.length > 0) {
225
235
  excluded++;
226
236
  continue;
227
237
  }
228
238
  context_recall.push({
229
239
  id: mem.id,
230
- title: mem.title || path.basename(mem.path || '', '.md'),
240
+ title,
231
241
  path: mem.path,
232
242
  type: mem.type,
233
243
  score: mem.score,
234
244
  token_estimate: est,
245
+ receipt,
235
246
  });
236
247
  used += est;
237
248
  }
@@ -39,7 +39,7 @@ If the brain-memory package is installed globally, use:
39
39
  brain recall "$ARGUMENTS" --project "<project>" --task "<task_type>" --top 10
40
40
  ```
41
41
 
42
- The engine computes **TF-IDF relevance** (cosine similarity between query and memory content), then combines it with decayed strength, recency, spreading activation, context match, and salience using the v4 formula. All scoring is deterministic — same query always produces the same ranking.
42
+ The engine computes **TF-IDF relevance** (cosine similarity between query and memory content), then combines it with decayed strength, recency, spreading activation, context match, and salience using the v4 formula. All scoring is deterministic — same query always produces the same ranking. Each result also carries a pre-minted `receipt` line (`◉ memory: "<title>" (<type>, <age>)`) — keep it for step 6.
43
43
 
44
44
  ### 3. Read Top Memories
45
45
 
@@ -100,6 +100,7 @@ Format the output clearly. Include confidence indicators for low-confidence memo
100
100
 
101
101
  ---
102
102
  *Memory reinforced — strength updated, decay improved*
103
+ ◉ memory: "<title>" (<type>, <age>)
103
104
  ```
104
105
 
105
106
  For consolidated responses (Case B):
@@ -116,4 +117,10 @@ For consolidated responses (Case B):
116
117
 
117
118
  ---
118
119
  *<N> memories reinforced, association links strengthened*
120
+ ◉ memory: "<title>" (<type>, <age>)
121
+ ◉ memory: "<title>" (<type>, <age>)
119
122
  ```
123
+
124
+ ### 7. End With Receipts
125
+
126
+ End the reply with the `receipt` lines of the memories you actually presented, copied **verbatim** from the engine's `receipt` field — max 3, at the very end (as in the templates above). Never compose a receipt yourself: only lines the engine returned.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.31",
3
+ "version": "0.1.0-beta.33",
4
4
  "description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -44,8 +44,13 @@
44
44
  "url": "git+https://github.com/omelas-tech/brain.git"
45
45
  },
46
46
  "scripts": {
47
- "test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/recall.test.js test/recall-cli.test.js test/forget.test.js test/functional.test.js test/erasure.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/cloud-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js test/session-start.test.js test/memorize.test.js test/pinning.test.js test/skills.test.js test/contradiction.test.js",
48
- "prerelease": "npm test",
47
+ "test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/receipt.test.js test/recall.test.js test/recall-cli.test.js test/forget.test.js test/functional.test.js test/erasure.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/cloud-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js test/session-start.test.js test/memorize.test.js test/pinning.test.js test/skills.test.js test/contradiction.test.js",
48
+ "test:integrations": "npm run test:integrations:openclaw && npm run test:integrations:copilot && npm run test:integrations:kilo && npm run test:integrations:hermes",
49
+ "test:integrations:openclaw": "node --test integrations/openclaw/test/*.test.mjs",
50
+ "test:integrations:copilot": "node --test integrations/copilot/test/*.test.mjs",
51
+ "test:integrations:kilo": "node --test integrations/kilo/test/*.test.mjs",
52
+ "test:integrations:hermes": "python3 -m unittest discover -s integrations/hermes/tests",
53
+ "prepublishOnly": "npm test && npm run test:integrations",
49
54
  "changelog": "node scripts/release.mjs",
50
55
  "changelog:status": "node scripts/release.mjs status",
51
56
  "release:beta": "npm version prerelease --preid beta && npm publish --tag beta && npm dist-tag add brain-memory@$(node -p \"require('./package.json').version\") latest",
@@ -170,6 +170,14 @@ When the user asks you to "remember" something, or when context from past sessio
170
170
 
171
171
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
172
172
 
173
+ ## Recall Receipts
174
+
175
+ Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
176
+
177
+ - When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
178
+ - Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
179
+ - No memory used → no receipt line. Never fabricate a receipt for a memory the engine did not return; only lines provided in `receipt` fields.
180
+
173
181
  ## Portable Sync
174
182
 
175
183
  Brain memories can be synced across devices in two ways:
package/prompts/claude.md CHANGED
@@ -169,6 +169,14 @@ When the user asks you to "remember" something, or when context from past sessio
169
169
 
170
170
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
171
171
 
172
+ ## Recall Receipts
173
+
174
+ Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
175
+
176
+ - When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
177
+ - Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
178
+ - No memory used → no receipt line. Never fabricate a receipt for a memory the engine did not return; only lines provided in `receipt` fields.
179
+
172
180
  ## Portable Sync
173
181
 
174
182
  Brain memories can be synced across devices in two ways:
@@ -0,0 +1,190 @@
1
+ # Brain Memory System
2
+
3
+ This project uses the **Brain Memory** plugin — a hierarchical, file-system-based memory system that mimics human cognition with neuroscience-inspired mechanisms including associative networks, spreading activation, context-dependent recall, spaced reinforcement, and cognitive memory types.
4
+
5
+ ## Memory Location
6
+
7
+ All memories are stored in `~/.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
8
+
9
+ Brain Memory complements Copilot's built-in repository memory: the built-in memory is repo-scoped, while `~/.brain/` is global and shared across every agent on this machine (Claude Code, Codex, OpenCode, Copilot, and others). Prefer brain for durable cross-project knowledge — decisions, preferences, learnings — and let repository memory handle repo-local conventions.
10
+
11
+ ## How It Works
12
+
13
+ ### Memory Format
14
+ Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `cognitive_type` (episodic/semantic/procedural), `created`, `last_accessed`, `access_count`, `recall_history`, `strength` (0.0-1.0), `decay_rate` (per day), `salience` (0.0-1.0), `confidence` (0.0-1.0), `tags`, `related` memory IDs, `source`, and `encoding_context`.
15
+
16
+ ### Strength & Decay Model
17
+ - Memories have a base `strength` set at creation based on their impact/type/cognitive type
18
+ - Strength decays over time: `effective = strength * (decay_rate ^ days_since_access)`
19
+ - Recalled memories get **stronger** via spaced reinforcement — the longer since last recall, the bigger the boost
20
+ - Memories become progressively more forgetting-resistant with each recall (decay_rate improves)
21
+ - Weak memories can be consolidated into stronger combined memories
22
+ - During sleep, global synaptic homeostasis prevents strength inflation
23
+
24
+ ### Cognitive Types
25
+ - **Episodic** — Event-specific memories. Higher initial strength, faster decay. The details fade but lessons persist.
26
+ - **Semantic** — Abstracted knowledge. Default decay. Stable long-term storage.
27
+ - **Procedural** — Skills and workflows. Lower initial strength but extremely slow decay once established.
28
+
29
+ ### Memory Types & Default Strengths
30
+ | Type | Strength | Decay/day | Description |
31
+ |------|----------|-----------|-------------|
32
+ | decision | 0.85 | 0.995 | Choices made and rationale |
33
+ | insight | 0.90 | 0.997 | Deep realizations, patterns |
34
+ | goal | 0.80 | 0.993 | Objectives and aspirations |
35
+ | experience | 0.75 | 0.985 | Notable events or processes |
36
+ | learning | 0.70 | 0.990 | New knowledge acquired |
37
+ | relationship | 0.70 | 0.997 | Connections between entities |
38
+ | preference | 0.60 | 0.998 | User preferences and style |
39
+ | observation | 0.40 | 0.950 | Casual facts or notices |
40
+
41
+ ### Associative Network
42
+ Memories are connected via weighted edges in `~/.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
43
+
44
+ ### Context-Dependent Recall
45
+ Memories store their encoding context (project, topics, task type). During recall, memories encoded in a similar context to the current session are scored higher — matching how human memory works better when recall context matches encoding context.
46
+
47
+ ### Salience & Confidence
48
+ - **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
49
+ - **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
50
+
51
+ ## Available Commands
52
+
53
+ Brain skills are installed as Copilot Agent Skills with the `brain-` prefix (`brain-remember`, `brain-memorize`, …). Ask for them by name or let Copilot load them automatically when a task matches — check `/skills` to see them.
54
+ The everyday loop is **ambient** — `remember` and `memorize` run automatically at session start/end; you rarely type them.
55
+
56
+ Core:
57
+ - `/brain-remember [query]` — Recall relevant memories with spreading activation and context matching
58
+ - `/brain-memorize [topic]` — Store memories from the current context
59
+ - `/brain-status` — Dashboard with brain health overview
60
+ - `/brain-pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
61
+ - `/brain-forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
62
+
63
+ Sync & skills:
64
+ - `/brain-sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
65
+ - `/brain-skills [list|show|add|use|remove|export]` — Manage procedural skills
66
+
67
+ Maintenance (usually automatic — runs in the background):
68
+ - `/brain-sleep [scope]` — Full maintenance cycle: replay, homeostasis, propagation, crystallization, reorganize, consolidate, prune, review reinforcement, REM dreaming, expertise detection
69
+
70
+ ## Session Start Behavior
71
+
72
+ **Perform these steps at session start — but keep it lightweight.**
73
+
74
+ If `~/.brain/index.json` exists:
75
+
76
+ 1. **Run the session-start aggregator** — one deterministic, budget-bounded call:
77
+ ```bash
78
+ brain session-start --project "<current project>"
79
+ ```
80
+ It returns JSON with `memory_count`, `pinned` (always-apply conventions/preferences), `skills_index` (available procedural skills — name + description only), `context_recall` (memories relevant to this project), `due_for_review`, `low_confidence_alerts`, and `budget`. If `~/.brain/index.json` is absent it returns an empty payload.
81
+ 2. **Silently internalize** the payload — treat `pinned` facts as active constraints, note which `skills_index` skills exist (load a skill's full `SKILL.md` only when a task matches it), and keep `context_recall` in mind. Do **NOT** dump contents.
82
+ 3. **Output a single status line:**
83
+
84
+ ```
85
+ ◉ Brain active — <N> memories (<M> in project context)
86
+ ```
87
+
88
+ Only add extra lines if actionable:
89
+ - `📋 <X> due for review` — if `due_for_review > 0`
90
+ - `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
91
+
92
+ The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
93
+
94
+ ## Ambient Session Tracking
95
+
96
+ **Throughout the session, maintain a running mental log of notable events.** This requires no file writes — just internal awareness.
97
+
98
+ Track these categories as they happen:
99
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
100
+ - **Learnings** — New patterns, debugging insights, API discoveries
101
+ - **Insights** — Realizations about the codebase, project, or process
102
+ - **Experiences** — Significant events like incidents, deployments, milestones
103
+ - **Goals** — New objectives discussed or planned
104
+
105
+ **Why this matters:** Without active tracking, you can only evaluate what happened at session end — by which point early-session events may be forgotten or the user may have already left. By tracking as events occur, nothing is lost.
106
+
107
+ ## Periodic Memory Checkpoint
108
+
109
+ **Every ~10 substantive interactions** (file edits, architecture decisions, debugging breakthroughs, significant discussions — not trivial reads or simple answers), silently evaluate whether your ambient tracking log contains memorizable content.
110
+
111
+ If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
112
+
113
+ ```
114
+ ◉ Notable <type(s)> this session — /brain-memorize when ready
115
+ ```
116
+
117
+ **Rules:**
118
+ - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
119
+ - **At most once per ~10 substantive interactions** — no spamming
120
+ - **Reset the counter** after the user runs `/brain-memorize`
121
+ - **Don't mention if nothing notable** has accumulated
122
+ - **Be specific about types** — say "decisions and learnings" not just "notable content"
123
+
124
+ ## Session End Behavior
125
+
126
+ When a session is ending (user says bye/thanks/done, conversation wraps up, or you sense the interaction is concluding), perform these steps **in order**:
127
+
128
+ ### Step 1: Save Session Context (ALWAYS — do this first)
129
+
130
+ **Immediately** append a session summary to `~/.brain/contexts.json`, even for trivial sessions. Context tracking is cheap and provides valuable recall signals for future sessions.
131
+
132
+ ```json
133
+ {
134
+ "session_id": "<timestamp-based-id>",
135
+ "started": "<session start ISO timestamp>",
136
+ "ended": "<session end ISO timestamp>",
137
+ "project": "<current project name>",
138
+ "topics": ["<key topics discussed>"],
139
+ "task_type": "<primary task type>",
140
+ "memories_created": ["<IDs of memories stored this session>"],
141
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
142
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
143
+ }
144
+ ```
145
+
146
+ Keep only the last 20 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
147
+
148
+ ### Step 2: Suggest Memorization (if warranted)
149
+
150
+ If the session contained meaningful content based on your ambient tracking:
151
+
152
+ ```
153
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
154
+ Run /brain-memorize to capture them before this context is lost.
155
+ ```
156
+
157
+ **Rules:**
158
+ - Do NOT auto-memorize without user consent
159
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
160
+ - Only suggest when there is genuinely valuable context worth preserving
161
+ - **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively
162
+
163
+ ## When Recalling Memories
164
+
165
+ When the user asks you to "remember" something, or when context from past sessions would be helpful, use the **deterministic recall engine** instead of manually computing scores:
166
+
167
+ 1. Run `brain recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
168
+ 2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
169
+ 3. Read the top-scoring memory files and present results
170
+ 4. Run `brain reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
171
+ 5. If no matches, search the archive (`~/.brain/_archived/`)
172
+
173
+ The recall engine ensures **identical scoring across all agents** — Claude, Codex, and Copilot all get the same rankings for the same query.
174
+
175
+ ## Recall Receipts
176
+
177
+ Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
178
+
179
+ - When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
180
+ - Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
181
+ - No memory used → no receipt line. Never fabricate a receipt for a memory the engine did not return; only lines provided in `receipt` fields.
182
+
183
+ ## Portable Sync
184
+
185
+ Brain memories can be synced across devices in two ways:
186
+
187
+ 1. **Git remote** — Push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain-sync setup <url>` to configure, then use `/brain-sync push` and `/brain-sync pull`.
188
+ 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain-sync export` and `/brain-sync import <path>`.
189
+
190
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
@@ -0,0 +1,189 @@
1
+ # Brain Memory System
2
+
3
+ This project uses the **Brain Memory** plugin — a hierarchical, file-system-based memory system that mimics human cognition with neuroscience-inspired mechanisms including associative networks, spreading activation, context-dependent recall, spaced reinforcement, and cognitive memory types.
4
+
5
+ ## Memory Location
6
+
7
+ All memories are stored in a single global `~/.brain/` directory in the user's home folder, shared across all projects and all supported AI agents. The directory uses a deep nested structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
8
+
9
+ Brain Memory complements Kilo's repo-scoped Memory Bank: keep repo conventions there, and use brain for durable cross-project knowledge — decisions, preferences, learnings — shared with every other agent on this machine (Claude Code, Codex, OpenCode, Copilot, and others).
10
+
11
+ ## How It Works
12
+
13
+ ### Memory Format
14
+ Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `cognitive_type` (episodic/semantic/procedural), `created`, `last_accessed`, `access_count`, `recall_history`, `strength` (0.0-1.0), `decay_rate` (per day), `salience` (0.0-1.0), `confidence` (0.0-1.0), `tags`, `related` memory IDs, `source`, and `encoding_context`.
15
+
16
+ ### Strength & Decay Model
17
+ - Memories have a base `strength` set at creation based on their impact/type/cognitive type
18
+ - Strength decays over time: `effective = strength * (decay_rate ^ days_since_access)`
19
+ - Recalled memories get **stronger** via spaced reinforcement — the longer since last recall, the bigger the boost
20
+ - Memories become progressively more forgetting-resistant with each recall (decay_rate improves)
21
+ - Weak memories can be consolidated into stronger combined memories
22
+ - During sleep, global synaptic homeostasis prevents strength inflation
23
+
24
+ ### Cognitive Types
25
+ - **Episodic** — Event-specific memories. Higher initial strength, faster decay. The details fade but lessons persist.
26
+ - **Semantic** — Abstracted knowledge. Default decay. Stable long-term storage.
27
+ - **Procedural** — Skills and workflows. Lower initial strength but extremely slow decay once established.
28
+
29
+ ### Memory Types & Default Strengths
30
+ | Type | Strength | Decay/day | Description |
31
+ |------|----------|-----------|-------------|
32
+ | decision | 0.85 | 0.995 | Choices made and rationale |
33
+ | insight | 0.90 | 0.997 | Deep realizations, patterns |
34
+ | goal | 0.80 | 0.993 | Objectives and aspirations |
35
+ | experience | 0.75 | 0.985 | Notable events or processes |
36
+ | learning | 0.70 | 0.990 | New knowledge acquired |
37
+ | relationship | 0.70 | 0.997 | Connections between entities |
38
+ | preference | 0.60 | 0.998 | User preferences and style |
39
+ | observation | 0.40 | 0.950 | Casual facts or notices |
40
+
41
+ ### Associative Network
42
+ Memories are connected via weighted edges in `~/.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
43
+
44
+ ### Context-Dependent Recall
45
+ Memories store their encoding context (project, topics, task type). During recall, memories encoded in a similar context to the current session are scored higher — matching how human memory works better when recall context matches encoding context.
46
+
47
+ ### Salience & Confidence
48
+ - **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
49
+ - **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
50
+
51
+ ## Available Commands
52
+
53
+ The everyday loop is **ambient** — `remember` and `memorize` run automatically at session start/end; you rarely type them.
54
+
55
+ **Core**
56
+ - `/brain:remember [query]` — Recall relevant memories with spreading activation and context matching
57
+ - `/brain:memorize [topic]` — Store memories from the current context
58
+ - `/brain:status` — Dashboard with brain health overview
59
+ - `/brain:pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
60
+ - `/brain:forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
61
+
62
+ **Sync & skills**
63
+ - `/brain:sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
64
+ - `/brain:skills [list|show|add|use|remove|export]` — Manage procedural skills
65
+
66
+ **Maintenance (usually automatic — runs in the background)**
67
+ - `/brain:sleep [scope]` — Full maintenance cycle: replay, homeostasis, propagation, crystallization, reorganize, consolidate, prune, review reinforcement, REM dreaming, expertise detection
68
+
69
+ ## Session Start Behavior
70
+
71
+ **Perform these steps at session start — but keep it lightweight.**
72
+
73
+ If `~/.brain/index.json` exists:
74
+
75
+ 1. **Run the session-start aggregator** — one deterministic, budget-bounded call:
76
+ ```bash
77
+ brain session-start --project "<current project>"
78
+ ```
79
+ It returns JSON with `memory_count`, `pinned` (always-apply conventions/preferences), `skills_index` (available procedural skills — name + description only), `context_recall` (memories relevant to this project), `due_for_review`, `low_confidence_alerts`, and `budget`. If `~/.brain/index.json` is absent it returns an empty payload.
80
+ 2. **Silently internalize** the payload — treat `pinned` facts as active constraints, note which `skills_index` skills exist (load a skill's full `SKILL.md` only when a task matches it), and keep `context_recall` in mind. Do **NOT** dump contents.
81
+ 3. **Output a single status line:**
82
+
83
+ ```
84
+ ◉ Brain active — <N> memories (<M> in project context)
85
+ ```
86
+
87
+ Only add extra lines if actionable:
88
+ - `📋 <X> due for review` — if `due_for_review > 0`
89
+ - `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
90
+
91
+ The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
92
+
93
+ ## Ambient Session Tracking
94
+
95
+ **Throughout the session, maintain a running mental log of notable events.** This requires no file writes — just internal awareness.
96
+
97
+ Track these categories as they happen:
98
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
99
+ - **Learnings** — New patterns, debugging insights, API discoveries
100
+ - **Insights** — Realizations about the codebase, project, or process
101
+ - **Experiences** — Significant events like incidents, deployments, milestones
102
+ - **Goals** — New objectives discussed or planned
103
+
104
+ **Why this matters:** Without active tracking, you can only evaluate what happened at session end — by which point early-session events may be forgotten or the user may have already left. By tracking as events occur, nothing is lost.
105
+
106
+ ## Periodic Memory Checkpoint
107
+
108
+ **Every ~10 substantive interactions** (file edits, architecture decisions, debugging breakthroughs, significant discussions — not trivial reads or simple answers), silently evaluate whether your ambient tracking log contains memorizable content.
109
+
110
+ If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
111
+
112
+ ```
113
+ ◉ Notable <type(s)> this session — /brain:memorize when ready
114
+ ```
115
+
116
+ **Rules:**
117
+ - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
118
+ - **At most once per ~10 substantive interactions** — no spamming
119
+ - **Reset the counter** after the user runs `/brain:memorize`
120
+ - **Don't mention if nothing notable** has accumulated
121
+ - **Be specific about types** — say "decisions and learnings" not just "notable content"
122
+
123
+ ## Session End Behavior
124
+
125
+ When a session is ending (user says bye/thanks/done, conversation wraps up, or you sense the interaction is concluding), perform these steps **in order**:
126
+
127
+ ### Step 1: Save Session Context (ALWAYS — do this first)
128
+
129
+ **Immediately** append a session summary to `~/.brain/contexts.json`, even for trivial sessions. Context tracking is cheap and provides valuable recall signals for future sessions.
130
+
131
+ ```json
132
+ {
133
+ "session_id": "<timestamp-based-id>",
134
+ "started": "<session start ISO timestamp>",
135
+ "ended": "<session end ISO timestamp>",
136
+ "project": "<current project name>",
137
+ "topics": ["<key topics discussed>"],
138
+ "task_type": "<primary task type>",
139
+ "memories_created": ["<IDs of memories stored this session>"],
140
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
141
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
142
+ }
143
+ ```
144
+
145
+ Keep only the last 20 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
146
+
147
+ ### Step 2: Suggest Memorization (if warranted)
148
+
149
+ If the session contained meaningful content based on your ambient tracking:
150
+
151
+ ```
152
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
153
+ Run /brain:memorize to capture them before this context is lost.
154
+ ```
155
+
156
+ **Rules:**
157
+ - Do NOT auto-memorize without user consent
158
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
159
+ - Only suggest when there is genuinely valuable context worth preserving
160
+ - **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively
161
+
162
+ ## When Recalling Memories
163
+
164
+ When the user asks you to "remember" something, or when context from past sessions would be helpful, use the **deterministic recall engine** instead of manually computing scores:
165
+
166
+ 1. Run `brain recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
167
+ 2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
168
+ 3. Read the top-scoring memory files and present results
169
+ 4. Run `brain reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
170
+ 5. If no matches, search the archive (`~/.brain/_archived/`)
171
+
172
+ The recall engine ensures **identical scoring across all agents** — Claude, Gemini, Codex, and OpenCode all get the same rankings for the same query.
173
+
174
+ ## Recall Receipts
175
+
176
+ Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
177
+
178
+ - When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
179
+ - Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
180
+ - No memory used → no receipt line. Never fabricate a receipt for a memory the engine did not return; only lines provided in `receipt` fields.
181
+
182
+ ## Portable Sync
183
+
184
+ Brain memories can be synced across devices in two ways:
185
+
186
+ 1. **Git remote** — Push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain:sync setup <url>` to configure, then use `/brain:sync push` and `/brain:sync pull`.
187
+ 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
188
+
189
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/prompts/openai.md CHANGED
@@ -170,6 +170,14 @@ When the user asks you to "remember" something, or when context from past sessio
170
170
 
171
171
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
172
172
 
173
+ ## Recall Receipts
174
+
175
+ Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
176
+
177
+ - When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
178
+ - Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
179
+ - No memory used → no receipt line. Never fabricate a receipt for a memory the engine did not return; only lines provided in `receipt` fields.
180
+
173
181
  ## Portable Sync
174
182
 
175
183
  Brain memories can be synced across devices in two ways:
@@ -169,6 +169,14 @@ When the user asks you to "remember" something, or when context from past sessio
169
169
 
170
170
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, Codex, and OpenCode all get the same rankings for the same query.
171
171
 
172
+ ## Recall Receipts
173
+
174
+ Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
175
+
176
+ - When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
177
+ - Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
178
+ - No memory used → no receipt line. Never fabricate a receipt for a memory the engine did not return; only lines provided in `receipt` fields.
179
+
172
180
  ## Portable Sync
173
181
 
174
182
  Brain memories can be synced across devices in two ways:
package/src/installer.js CHANGED
@@ -64,8 +64,50 @@ const RUNTIMES = {
64
64
  promptSource: 'opencode.md',
65
65
  commandStyle: 'flat',
66
66
  },
67
+ copilot: {
68
+ name: 'GitHub Copilot CLI',
69
+ globalDir: path.join(os.homedir(), '.copilot'),
70
+ localDir: '.copilot',
71
+ commandsSubdir: 'skills',
72
+ // Copilot reads the cross-tool ~/.agents/skills/ (same dir Codex uses) in
73
+ // addition to its own ~/.copilot/skills/ — reuse the shared location.
74
+ skillsGlobalDir: path.join(os.homedir(), '.agents', 'skills'),
75
+ skillsLocalDir: path.join('.agents', 'skills'),
76
+ // Copilot's GLOBAL instructions file is ~/.copilot/copilot-instructions.md
77
+ // but its repo-local file is AGENTS.md — the same root AGENTS.md the openai
78
+ // and opencode runtimes write locally. The marker-delimited section is
79
+ // shared: whichever runtime installed last owns it (the prompt bodies are
80
+ // near-identical, so this is by design, not a conflict).
81
+ promptFile: 'copilot-instructions.md',
82
+ localPromptFile: 'AGENTS.md',
83
+ promptSource: 'copilot.md',
84
+ commandStyle: 'skills',
85
+ skillName: true,
86
+ },
87
+ kilo: {
88
+ name: 'Kilo',
89
+ globalDir: path.join(os.homedir(), '.config', 'kilo'),
90
+ localDir: '.kilo',
91
+ commandsSubdir: 'commands',
92
+ // Kilo v7 is OpenCode-based: repo-root AGENTS.md is read natively (shared
93
+ // with the openai/opencode runtimes), but there is NO global markdown file
94
+ // read directly — the global prompt must be written to a file AND
95
+ // registered in the `instructions` array of ~/.config/kilo/kilo.jsonc
96
+ // (see instructionsConfig + ensureInstructionsEntry).
97
+ promptFile: path.join('rules', 'brain-memory.md'),
98
+ localPromptFile: 'AGENTS.md',
99
+ instructionsConfig: 'kilo.jsonc',
100
+ promptSource: 'kilo.md',
101
+ commandStyle: 'flat',
102
+ },
67
103
  };
68
104
 
105
+ /** Prompt filename for a runtime+scope (Copilot's differs between scopes). */
106
+ function promptFileFor(config, scope) {
107
+ if (scope === 'local' && config.localPromptFile) return config.localPromptFile;
108
+ return config.promptFile;
109
+ }
110
+
69
111
  /** Where skills install for a runtime+scope (decoupled from the prompt target). */
70
112
  function skillsDestFor(config, scope) {
71
113
  if (scope === 'global') {
@@ -135,6 +177,9 @@ function injectPrompt(targetDir, promptFile, promptSource) {
135
177
  // must be created explicitly.
136
178
  fs.mkdirSync(targetDir, { recursive: true });
137
179
 
180
+ // promptFile may contain a subdirectory (e.g. Kilo's rules/brain-memory.md).
181
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
182
+
138
183
  const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
139
184
 
140
185
  if (fs.existsSync(targetPath)) {
@@ -153,13 +198,63 @@ function injectPrompt(targetDir, promptFile, promptSource) {
153
198
  }
154
199
  }
155
200
 
201
+ /**
202
+ * Register a prompt file in a JSONC config's `instructions` array (Kilo reads
203
+ * no global markdown file directly). Conservative by design: creates a minimal
204
+ * config when none exists; edits only files that parse as strict JSON (JSONC
205
+ * comments or trailing commas fail JSON.parse, so a hand-commented config is
206
+ * never rewritten). When it can't edit safely it returns `manual: true` so the
207
+ * caller can print the one-line manual step instead.
208
+ */
209
+ function ensureInstructionsEntry(configPath, entry) {
210
+ if (!fs.existsSync(configPath)) {
211
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
212
+ fs.writeFileSync(configPath, JSON.stringify({ instructions: [entry] }, null, 2) + '\n');
213
+ return { registered: true, created: true };
214
+ }
215
+ const raw = fs.readFileSync(configPath, 'utf-8');
216
+ let cfg;
217
+ try {
218
+ cfg = JSON.parse(raw);
219
+ } catch {
220
+ return { registered: false, manual: true, reason: 'not-strict-json' };
221
+ }
222
+ if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) {
223
+ return { registered: false, manual: true, reason: 'unexpected-shape' };
224
+ }
225
+ if (cfg.instructions === undefined) cfg.instructions = [];
226
+ if (!Array.isArray(cfg.instructions)) {
227
+ return { registered: false, manual: true, reason: 'instructions-not-array' };
228
+ }
229
+ if (cfg.instructions.includes(entry)) return { registered: true, already: true };
230
+ cfg.instructions.push(entry);
231
+ fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + '\n');
232
+ return { registered: true };
233
+ }
234
+
235
+ function removeInstructionsEntry(configPath, entry) {
236
+ if (!fs.existsSync(configPath)) return { removed: false, reason: 'file-not-found' };
237
+ let cfg;
238
+ try {
239
+ cfg = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
240
+ } catch {
241
+ return { removed: false, manual: true, reason: 'not-strict-json' };
242
+ }
243
+ if (!cfg || !Array.isArray(cfg.instructions)) return { removed: false, reason: 'no-instructions' };
244
+ const before = cfg.instructions.length;
245
+ cfg.instructions = cfg.instructions.filter((e) => e !== entry);
246
+ if (cfg.instructions.length === before) return { removed: false, reason: 'not-registered' };
247
+ fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + '\n');
248
+ return { removed: true };
249
+ }
250
+
156
251
  function detectInstallations() {
157
252
  const results = [];
158
253
  for (const [runtime, config] of Object.entries(RUNTIMES)) {
159
254
  for (const scope of ['global', 'local']) {
160
255
  const targetDir = scope === 'global' ? config.globalDir : config.localDir;
161
256
  const promptTarget = scope === 'global' ? config.globalDir : '.';
162
- const promptPath = path.join(promptTarget, config.promptFile);
257
+ const promptPath = path.join(promptTarget, promptFileFor(config, scope));
163
258
 
164
259
  // Check for command files/dirs
165
260
  let commandsFound = false;
@@ -262,12 +357,20 @@ function uninstallForRuntime(runtime, scope) {
262
357
  const config = RUNTIMES[runtime];
263
358
  const targetDir = scope === 'global' ? config.globalDir : config.localDir;
264
359
  const promptTarget = scope === 'global' ? config.globalDir : '.';
265
- const promptPath = path.join(promptTarget, config.promptFile);
360
+ const promptPath = path.join(promptTarget, promptFileFor(config, scope));
266
361
 
267
362
  const removedCommands = removeCommands(targetDir, config, scope);
268
363
  const promptResult = removePromptSection(promptPath);
269
364
 
270
- return { removedCommands, promptResult };
365
+ let promptRegistration;
366
+ if (scope === 'global' && config.instructionsConfig) {
367
+ promptRegistration = removeInstructionsEntry(
368
+ path.join(config.globalDir, config.instructionsConfig),
369
+ promptPath
370
+ );
371
+ }
372
+
373
+ return { removedCommands, promptResult, promptRegistration };
271
374
  }
272
375
 
273
376
  function installForRuntime(runtime, scope) {
@@ -304,7 +407,18 @@ function installForRuntime(runtime, scope) {
304
407
  }
305
408
 
306
409
  const promptTarget = scope === 'global' ? config.globalDir : '.';
307
- injectPrompt(promptTarget, config.promptFile, config.promptSource);
410
+ const promptFile = promptFileFor(config, scope);
411
+ injectPrompt(promptTarget, promptFile, config.promptSource);
412
+
413
+ let promptRegistration;
414
+ if (scope === 'global' && config.instructionsConfig) {
415
+ promptRegistration = ensureInstructionsEntry(
416
+ path.join(config.globalDir, config.instructionsConfig),
417
+ path.join(promptTarget, promptFile)
418
+ );
419
+ }
420
+
421
+ return { promptRegistration };
308
422
  }
309
423
 
310
424
  function initializeBrain(overrideBase) {
@@ -435,6 +549,8 @@ module.exports = {
435
549
  copyDir,
436
550
  installSkills,
437
551
  injectPrompt,
552
+ ensureInstructionsEntry,
553
+ removeInstructionsEntry,
438
554
  installForRuntime,
439
555
  initializeBrain,
440
556
  detectInstallations,
package/src/receipt.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Brain Memory — Recall Receipts
3
+ *
4
+ * Mints the one-line attributable receipt attached to every memory the
5
+ * engine returns (bin/recall.js results, bin/session-start.js context_recall
6
+ * and pinned entries). Agents copy the line VERBATIM at the end of any
7
+ * response a memory materially shaped — because the engine mints it, a
8
+ * receipt can never be hallucinated.
9
+ *
10
+ * Format: ◉ memory: "<title>" (<type>, <age>)
11
+ *
12
+ * Age is derived from the memory's `created` timestamp (falling back to
13
+ * `last_accessed`; omitted entirely when neither parses):
14
+ * today | yesterday | <N>d ago (2-30 days) | <N>mo ago (31-364 days,
15
+ * nearest month, min 1) | <N>y ago (365+ days, nearest year, min 1)
16
+ *
17
+ * Deterministic: `now` is injectable for tests.
18
+ */
19
+
20
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
21
+ const DAYS_PER_MONTH = 30.44; // mean Gregorian month
22
+ const DAYS_PER_YEAR = 365.25;
23
+ const MAX_TITLE_CHARS = 80;
24
+
25
+ /**
26
+ * Human age label for a timestamp, relative to `now`.
27
+ *
28
+ * @param {string|Date} timestamp - ISO timestamp (memory `created`)
29
+ * @param {Date} now - Reference time
30
+ * @returns {string|null} Age label, or null when the timestamp is invalid
31
+ */
32
+ function ageLabel(timestamp, now) {
33
+ const then = new Date(timestamp);
34
+ if (Number.isNaN(then.getTime())) return null;
35
+ const days = Math.floor((now.getTime() - then.getTime()) / MS_PER_DAY);
36
+ if (days <= 0) return 'today';
37
+ if (days === 1) return 'yesterday';
38
+ if (days <= 30) return `${days}d ago`;
39
+ if (days <= 364) return `${Math.max(1, Math.round(days / DAYS_PER_MONTH))}mo ago`;
40
+ return `${Math.max(1, Math.round(days / DAYS_PER_YEAR))}y ago`;
41
+ }
42
+
43
+ /**
44
+ * Mint the receipt line for a memory-like object ({title, type, created,
45
+ * last_accessed}). Title is used as-is (truncated at 77 chars + "…" only
46
+ * when longer than 80); `created` falls back to `last_accessed`, and the
47
+ * age segment is omitted when neither parses.
48
+ *
49
+ * @param {Object} memoryLike - Object with title/type/created/last_accessed
50
+ * @param {Function} [nowFn] - Injectable clock for deterministic tests
51
+ * @returns {string} The receipt line
52
+ */
53
+ function receiptFor(memoryLike, nowFn) {
54
+ const mem = memoryLike || {};
55
+ const now = (nowFn || (() => new Date()))();
56
+
57
+ let title = typeof mem.title === 'string' && mem.title ? mem.title : 'memory';
58
+ if (title.length > MAX_TITLE_CHARS) title = title.slice(0, 77) + '…';
59
+
60
+ const type = typeof mem.type === 'string' && mem.type ? mem.type : 'memory';
61
+ const age = ageLabel(mem.created ?? mem.last_accessed ?? NaN, now);
62
+
63
+ return age
64
+ ? `◉ memory: "${title}" (${type}, ${age})`
65
+ : `◉ memory: "${title}" (${type})`;
66
+ }
67
+
68
+ module.exports = { receiptFor, ageLabel };