brain-memory 0.1.0-beta.31 → 0.1.0-beta.32
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/README.md +54 -3
- package/bin/install.js +33 -6
- package/package.json +7 -2
- package/prompts/copilot.md +182 -0
- package/prompts/kilo.md +181 -0
- package/src/installer.js +120 -4
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**,
|
|
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/
|
|
@@ -56,8 +56,9 @@ There are two ways to give an agent its brain. They are complementary — most p
|
|
|
56
56
|
|
|
57
57
|
| Path | Reaches | Storage | Cost | Best for |
|
|
58
58
|
|------|---------|---------|------|----------|
|
|
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 |
|
|
59
|
+
| **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 |
|
|
60
|
+
| **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 |
|
|
61
|
+
| **[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
62
|
|
|
62
63
|
### 1. Universal path — the hosted MCP connector
|
|
63
64
|
|
|
@@ -89,6 +90,29 @@ codex mcp add brain --url https://mcp.brainmemory.ai/mcp
|
|
|
89
90
|
```
|
|
90
91
|
- **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
92
|
- **Google Antigravity** — add to `mcp_config.json` under the `serverUrl` key. *(Legacy Gemini CLI used the `httpUrl` key in `settings.json`.)*
|
|
93
|
+
- **GitHub Copilot CLI** — add to `~/.copilot/mcp-config.json` (OAuth via `/mcp auth brain` in-session):
|
|
94
|
+
```json
|
|
95
|
+
{
|
|
96
|
+
"mcpServers": {
|
|
97
|
+
"brain-memory": { "type": "http", "url": "https://mcp.brainmemory.ai/mcp", "tools": ["*"] }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
- **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/).)
|
|
102
|
+
- **Hermes Agent** — add to `~/.hermes/config.yaml`:
|
|
103
|
+
```yaml
|
|
104
|
+
mcp_servers:
|
|
105
|
+
brain: { url: "https://mcp.brainmemory.ai/mcp", auth: oauth }
|
|
106
|
+
```
|
|
107
|
+
- **Goose** — add a remote extension (streamable-HTTP) pointing at `https://mcp.brainmemory.ai/mcp`.
|
|
108
|
+
- **Kilo** — add to `kilo.jsonc` (OAuth starts automatically):
|
|
109
|
+
```json
|
|
110
|
+
{
|
|
111
|
+
"mcp": {
|
|
112
|
+
"brain-memory": { "type": "remote", "url": "https://mcp.brainmemory.ai/mcp", "enabled": true }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
92
116
|
|
|
93
117
|
</details>
|
|
94
118
|
|
|
@@ -110,6 +134,8 @@ The second command runs the setup wizard, which asks which runtime(s) to configu
|
|
|
110
134
|
| **Claude Code** | `CLAUDE.md` | `~/.claude/commands/brain/` (plugin slash commands) |
|
|
111
135
|
| **OpenAI Codex CLI** | `AGENTS.md` (`~/.codex/`) | `~/.agents/skills/<name>/SKILL.md` |
|
|
112
136
|
| **OpenCode** | `AGENTS.md` | `~/.config/opencode/commands/` |
|
|
137
|
+
| **GitHub Copilot CLI** | `copilot-instructions.md` (`~/.copilot/`), repo-local `AGENTS.md` | `~/.agents/skills/<name>/SKILL.md` (shared with Codex) |
|
|
138
|
+
| **Kilo** | `rules/brain-memory.md` + `kilo.jsonc` `instructions` entry (`~/.config/kilo/`), repo-local `AGENTS.md` | `~/.config/kilo/commands/` |
|
|
113
139
|
| **Google Antigravity** | `GEMINI.md` | `~/.gemini/skills/` *(experimental — verify paths against a live install)* |
|
|
114
140
|
|
|
115
141
|
#### Non-interactive
|
|
@@ -118,10 +144,35 @@ The second command runs the setup wizard, which asks which runtime(s) to configu
|
|
|
118
144
|
brain --claude --global # Claude Code, global
|
|
119
145
|
brain --codex --global # OpenAI Codex CLI, global
|
|
120
146
|
brain --opencode --global # OpenCode, global
|
|
147
|
+
brain --copilot --global # GitHub Copilot CLI, global
|
|
148
|
+
brain --kilo --global # Kilo, global
|
|
121
149
|
brain --antigravity --global # Google Antigravity, global (experimental)
|
|
122
150
|
brain --all --global # All runtimes, global
|
|
123
151
|
```
|
|
124
152
|
|
|
153
|
+
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:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
copilot plugin marketplace add omelas-tech/brain
|
|
157
|
+
copilot plugin install brain-memory@brain
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Kilo gets the same treatment via its runtime plugin — deterministic session-start injection, session tracking, and `BRAIN_AGENT` labeling ([details](integrations/kilo/)):
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
mkdir -p ~/.config/kilo/plugin
|
|
164
|
+
cp integrations/kilo/plugin/brain-memory.js ~/.config/kilo/plugin/
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### 3. Personal-assistant integrations — OpenClaw, NemoClaw, Hermes
|
|
168
|
+
|
|
169
|
+
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:
|
|
170
|
+
|
|
171
|
+
- **[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.
|
|
172
|
+
- **[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.
|
|
173
|
+
|
|
174
|
+
Both are backed by the same `brain` CLI the coding-agent installs use — one memory, every agent.
|
|
175
|
+
|
|
125
176
|
### Update
|
|
126
177
|
|
|
127
178
|
```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)
|
|
84
|
-
console.log(' 5)
|
|
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 = ['
|
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brain-memory",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.32",
|
|
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",
|
|
@@ -45,7 +45,12 @@
|
|
|
45
45
|
},
|
|
46
46
|
"scripts": {
|
|
47
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
|
-
"
|
|
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
|
+
"prerelease": "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",
|
|
@@ -0,0 +1,182 @@
|
|
|
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
|
+
## Portable Sync
|
|
176
|
+
|
|
177
|
+
Brain memories can be synced across devices in two ways:
|
|
178
|
+
|
|
179
|
+
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`.
|
|
180
|
+
2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain-sync export` and `/brain-sync import <path>`.
|
|
181
|
+
|
|
182
|
+
Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
|
package/prompts/kilo.md
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
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
|
+
## Portable Sync
|
|
175
|
+
|
|
176
|
+
Brain memories can be synced across devices in two ways:
|
|
177
|
+
|
|
178
|
+
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`.
|
|
179
|
+
2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
|
|
180
|
+
|
|
181
|
+
Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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,
|