brain-memory 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,11 @@
8
8
  * Brain can never bloat the host's context window.
9
9
  *
10
10
  * Usage:
11
- * brain session-start [--project P] [--topics a,b] [--task T] [--top N]
11
+ * brain session-start [--project P] [--topics a,b] [--task T] [--top N] [--budget TOKENS]
12
+ *
13
+ * --budget lowers the working-memory cap for this call only (never raises it):
14
+ * hosts with a smaller injection window than config.json assumes — Codex caps
15
+ * hook context at ~2,500 tokens — pass the room they actually have.
12
16
  *
13
17
  * Output (JSON):
14
18
  * {
@@ -45,15 +49,17 @@ const { advertisedSummaries } = require('../src/skills');
45
49
  const { receiptFor } = require('../src/receipt');
46
50
  const { temporalState } = require('../src/temporal');
47
51
  const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
52
+ const { isSensitiveHidden } = require('../src/sensitivity');
48
53
 
49
54
  function parseArgs(argv) {
50
- const args = { project: null, topics: null, task: null, top: 5 };
55
+ const args = { project: null, topics: null, task: null, top: 5, budget: null };
51
56
  for (let i = 0; i < argv.length; i++) {
52
57
  switch (argv[i]) {
53
58
  case '--project': args.project = argv[++i]; break;
54
59
  case '--topics': args.topics = argv[++i]; break;
55
60
  case '--task': args.task = argv[++i]; break;
56
61
  case '--top': args.top = parseInt(argv[++i], 10) || 5; break;
62
+ case '--budget': args.budget = parseInt(argv[++i], 10) || null; break;
57
63
  default: break;
58
64
  }
59
65
  }
@@ -110,14 +116,17 @@ function buildContextQuery(args) {
110
116
  * it is directly unit-testable.
111
117
  *
112
118
  * @param {string} [projectRoot] - Filesystem root whose .brain/ to read
113
- * @param {Object} [args] - { project, topics, task, top }
119
+ * @param {Object} [args] - { project, topics, task, top, budget }
114
120
  * @returns {Object} The session-start payload
115
121
  */
116
122
  function computeSessionStart(projectRoot, args = {}) {
117
123
  const top = args.top || 5;
118
124
  const brainDir = getBrainDir(projectRoot);
119
125
  const config = readConfig(projectRoot);
120
- const cap = config.working_memory_budget_tokens;
126
+ // A caller-supplied budget can only tighten the configured cap.
127
+ const cap = args.budget > 0
128
+ ? Math.min(config.working_memory_budget_tokens, args.budget)
129
+ : config.working_memory_budget_tokens;
121
130
 
122
131
  const empty = {
123
132
  memory_count: 0,
@@ -160,6 +169,9 @@ function computeSessionStart(projectRoot, args = {}) {
160
169
  const quarantineMode = config.quarantine_mode || 'flag';
161
170
  const memories = Object.entries(index.memories)
162
171
  .filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
172
+ // Consent: sensitive-topic memories stay out of working memory until the
173
+ // user opts in or approves them one by one.
174
+ .filter(([, entry]) => !isSensitiveHidden(entry, config))
163
175
  .map(([id, entry]) => ({ id, ...entry }));
164
176
 
165
177
  let associations = null;
@@ -190,6 +202,7 @@ function computeSessionStart(projectRoot, args = {}) {
190
202
  // Defensive: pinning a quarantined memory is refused, but state synced
191
203
  // from another device could carry both flags — never load it every session.
192
204
  if (entry.quarantined && quarantineMode !== 'off') continue;
205
+ if (isSensitiveHidden(entry, config)) continue;
193
206
  // Bitemporal: the pinned tier is presented to the agent as always-apply
194
207
  // active constraints, and a fact whose validity window has closed is not a
195
208
  // constraint any more. Drop it here rather than asserting it every session
package/bin/skill.js CHANGED
@@ -8,6 +8,9 @@
8
8
  * brain skill show <name> Full SKILL.md (L1 disclosure)
9
9
  * brain skill use <name> [--failed] Record a use; success strengthens,
10
10
  * --failed weakens (demotion feedback)
11
+ * brain skill verify <name> Check the skill's declared
12
+ * preconditions against the current
13
+ * directory. Read-only, never executes.
11
14
  * brain skill remove <name> Delete a skill
12
15
  * brain skill add Create a skill from JSON on stdin:
13
16
  * { name, description, triggers[], body }
@@ -15,14 +18,14 @@
15
18
 
16
19
  const fs = require('fs');
17
20
  const {
18
- addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill,
21
+ addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill, verifySkillByName,
19
22
  } = require('../src/skills');
20
23
 
21
24
  function emit(obj) { console.log(JSON.stringify(obj, null, 2)); }
22
25
  function fail(obj) { console.error(JSON.stringify(obj)); process.exit(1); }
23
26
  function done(result) { return result && result.error ? fail(result) : emit(result); }
24
27
 
25
- const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|add|remove <name>|export <name> [--target claude|gemini]>';
28
+ const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|verify <name>|add|remove <name>|export <name> [--target claude|gemini]>';
26
29
 
27
30
  function main(argv) {
28
31
  const args = argv || process.argv.slice(2);
@@ -39,6 +42,9 @@ function main(argv) {
39
42
  case 'use':
40
43
  if (!firstName) return fail({ error: USAGE });
41
44
  return done(useSkill(undefined, firstName, { failed: rest.includes('--failed') }));
45
+ case 'verify':
46
+ if (!firstName) return fail({ error: USAGE });
47
+ return done(verifySkillByName(undefined, firstName));
42
48
  case 'remove':
43
49
  if (!firstName) return fail({ error: USAGE });
44
50
  return done(removeSkill(undefined, firstName));
@@ -10,7 +10,7 @@ A new brain is empty. But your agents have been keeping transcripts for months
10
10
  **User input:** $ARGUMENTS
11
11
 
12
12
  **Flags** (passed straight through to the CLI):
13
- - `--source <id>` — Which history store to read (default `claude-code`; `--sources` lists what's detected)
13
+ - `--source <id>` — Which history store to read (`claude-code` by default, or `codex` for `~/.codex/sessions/`; `--sources` lists what's detected)
14
14
  - `--project <name>` — Only sessions from one project
15
15
  - `--since <30d|6m|2026-01-01>` — Only sessions since then
16
16
  - `--limit <N>` — Max sessions to consider (default 40)
@@ -56,6 +56,16 @@ For each memory, determine:
56
56
 
57
57
  Label honestly by **provenance, not confidence**. A fact you are certain about but read in an email is still `external`. Untrusted origins get capped salience/confidence and faster decay, so a planted fact fades instead of hardening — and the CLI reports any value it had to lower.
58
58
 
59
+ **Sensitivity** (consent tier — classify every memory; the CLI has a narrow backstop but you read the conversation):
60
+
61
+ | sensitivity | Use when | What the CLI does |
62
+ |---|---|---|
63
+ | `standard` | Everything else. **Default.** | Stores normally. |
64
+ | `sensitive` | Health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar personal topics. | Stored **only if** `sensitive_topics: true` in `~/.brain/config.json`; otherwise it lands quarantined (`sensitive_opt_out`) and hidden from recall until the user approves it with `brain verify approve <id>`. Receipts carry `⚠ sensitive`. |
65
+ | `blocked` | Government / national ID numbers, criminal history, immigration status. | **Refused.** Never stored, whatever the toggle says. |
66
+
67
+ Label the topic, not the person's wish to remember it: "user is diabetic" is `sensitive` even when the user asked you to remember it. If the CLI reports `sensitive_opt_out: true`, tell the user plainly that the memory is held until they opt in (`sensitive_topics: true`) or approve it, and never re-store it as `standard` to get around the gate. Opting in is never retroactive.
68
+
59
69
  **Pinned & stable** (optional, CoALA Phase 1) — **requires `origin: "user"`; the CLI rejects the write otherwise:**
60
70
  - `pinned: true` — always inject this memory at session start regardless of recall score (and decay-exempt). Optionally `pin_scope: "project:<name>"` (default `"global"`) and `pin_priority: <N>`.
61
71
  - `stable: true` — exempt from decay (never fades) without forcing it to always load — for timeless facts recalled on demand.
@@ -116,12 +126,23 @@ If the output contains `quarantine_pending: true`, the memory landed in the pend
116
126
 
117
127
  ### 5. Resolve contradictions (Tier B §10.2)
118
128
 
119
- If a stored memory's result includes `potential_conflicts`, it shares heavy tag overlap with a **pinned or stable** memory — and pinned/stable facts never decay out of contention, so a stale one is dangerous. **Do not silently keep both.** Inspect the conflicting memory (`brain recall` or read its file) and, if the new memory genuinely contradicts it, propose a resolution to the user:
120
- - **Supersede** — store the new fact with `"supersedes": ["<old_id>"]` (see below).
121
- - **Keep both, scoped** — e.g. pin each to its own project.
129
+ If a stored memory's result includes `potential_conflicts`, the new write overlaps memories it may have ended. Each proposal carries:
130
+
131
+ | Field | Meaning |
132
+ |---|---|
133
+ | `authority` | `pinned` / `stable` / `same-type` — how much weight the older memory carries |
134
+ | `shared_tags` | Why it was surfaced |
135
+ | `proposed_valid_until` | The exact boundary a supersede would stamp on the older memory |
136
+
137
+ `pinned` and `stable` facts never decay out of contention, so a stale one is dangerous. `same-type` means a like-for-like memory (a `decision` that may have replaced a `decision`) — the ordinary "we changed our minds" case, which is precisely the one users never think to flag.
138
+
139
+ **Do not silently keep both.** Inspect the conflicting memory (`brain recall` or read its file) and, if the new memory genuinely contradicts it, propose a resolution — quoting `proposed_valid_until` so the user sees the concrete boundary:
140
+
141
+ - **Supersede** — store the new fact with `"supersedes": ["<old_id>"]`, which stamps the older memory's `valid_until` (see below). Say it plainly: *"Shall I mark 'Deploy to Fly.io' as true until 2026-08-21?"*
142
+ - **Keep both, scoped** — e.g. pin each to its own project. Right when the two facts coexist rather than replace ("Postgres for analytics" vs "Postgres for sessions").
122
143
  - **Reject the new one** — the old fact stands.
123
144
 
124
- Never auto-resolve; surface the conflict and let the user decide.
145
+ Never auto-resolve. Tag overlap is a *relatedness* signal, not a contradiction signal — only the conversation can tell whether B actually ended A, so surface the proposal and let the user decide.
125
146
 
126
147
  ### Superseding an outdated memory (temporal invalidation)
127
148
 
@@ -58,3 +58,32 @@ brain skill export <name> [--target claude|gemini]
58
58
  - Advertise skills with a **crisp, matchable description** — that single line is all the agent sees at L0, so it must convey when to reach for the skill.
59
59
  - Reach for `show` only when a task genuinely matches; don't pre-load skills speculatively.
60
60
  - Always record the outcome with `use` (success or `--failed`) so the strength/demotion feedback loop stays accurate.
61
+
62
+ ### Verifying a skill (`brain skill verify <name>`)
63
+
64
+ A skill is a claim about how a repo works, and repos move. `brain skill verify <name>` checks the skill's declared preconditions against the current directory and answers whether the claim still holds — **without running the agent**:
65
+
66
+ ```bash
67
+ brain skill verify pg-migration
68
+ # → { "status": "passed", "passed": 2, "total": 2 }
69
+ ```
70
+
71
+ Skills declare preconditions as a `verify` array when they are added:
72
+
73
+ ```json
74
+ { "name": "pg-migration", "description": "...", "body": "...",
75
+ "verify": [
76
+ { "file_exists": "migrations/" },
77
+ { "file_contains": { "path": "package.json", "text": "\"migrate\"" } },
78
+ { "command_available": "psql" }
79
+ ] }
80
+ ```
81
+
82
+ Available checks: `file_exists`, `file_absent`, `file_contains`, `command_available`, `env_set`.
83
+
84
+ **Checks are declarative and read-only — nothing is ever executed.** Skills are crystallized automatically, they sync between machines, and they can be imported from other people; a `verify` field holding arbitrary shell would be a memory file that runs code, which is the OWASP ASI06 scenario with the hard part removed. There is deliberately no escape hatch. Paths that escape the working directory fail the check.
85
+
86
+ Outcomes:
87
+ - `passed` — preconditions hold. Strength is **not** raised: applicability is not the same as a good outcome, and a cheap automatic check should not let a skill climb the index.
88
+ - `failed` — demotes exactly like a failed use (`-0.10`), because a skill describing a layout that no longer exists will confidently misdirect the next matching session.
89
+ - `unverifiable` — no `verify` block. Most skills are prose; this is normal and changes nothing.
@@ -0,0 +1,39 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.mjs\"",
9
+ "timeout": 20,
10
+ "statusMessage": "Loading brain memory context"
11
+ }
12
+ ]
13
+ }
14
+ ],
15
+ "UserPromptSubmit": [
16
+ {
17
+ "hooks": [
18
+ {
19
+ "type": "command",
20
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/prompt-recall.mjs\"",
21
+ "timeout": 10,
22
+ "statusMessage": "Recalling brain memories"
23
+ }
24
+ ]
25
+ }
26
+ ],
27
+ "SessionEnd": [
28
+ {
29
+ "hooks": [
30
+ {
31
+ "type": "command",
32
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-end.mjs\"",
33
+ "timeout": 3
34
+ }
35
+ ]
36
+ }
37
+ ]
38
+ }
39
+ }
package/hooks/lib.mjs ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Shared helpers for the plugin hook scripts in this directory.
3
+ *
4
+ * These hooks run under Claude Code and OpenAI Codex plugin hosts. Both pipe
5
+ * the event as JSON on stdin, both accept `hookSpecificOutput.additionalContext`
6
+ * on stdout, and both export `CLAUDE_PLUGIN_ROOT` (Codex sets it for plugin
7
+ * compatibility alongside its own `PLUGIN_ROOT`). The scripts therefore need no
8
+ * host-specific branches beyond the command vocabulary shown to the model.
9
+ *
10
+ * The plugin root is this repository, so the brain engine is loaded in-process
11
+ * from ../src and ../bin — no `brain` binary on PATH is required for hooks.
12
+ *
13
+ * Fail-soft contract: a hook must never break the host session. Every failure
14
+ * path writes one line to stderr, prints `{}` and exits 0.
15
+ */
16
+
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import process from "node:process";
20
+ import { createRequire } from "node:module";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ export const PLUGIN_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
24
+
25
+ const require = createRequire(import.meta.url);
26
+
27
+ /** Load a CommonJS module from the plugin root (e.g. "bin/session-start.js"). */
28
+ export function loadModule(relativePath) {
29
+ return require(path.join(PLUGIN_ROOT, relativePath));
30
+ }
31
+
32
+ /** Resolve the brain directory the same way the CLI does (honors BRAIN_DIR). */
33
+ export function brainDir() {
34
+ return loadModule("src/index-manager.js").getBrainDir();
35
+ }
36
+
37
+ /** True when a brain exists — hooks do nothing at all before first init. */
38
+ export function hasBrain() {
39
+ return fs.existsSync(path.join(brainDir(), "index.json"));
40
+ }
41
+
42
+ /**
43
+ * Which host is running the hook. Codex exports PLUGIN_ROOT for plugin hooks;
44
+ * Claude Code exports CLAUDECODE for every child process. Used only to pick
45
+ * the command vocabulary shown to the model — the hook logic is identical.
46
+ */
47
+ export function detectHost(env = process.env) {
48
+ if (env.CODEX_HOME || env.CODEX_SANDBOX) return "codex";
49
+ if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT) return "claude-code";
50
+ if (env.PLUGIN_ROOT) return "codex";
51
+ if (env.CLAUDE_PLUGIN_ROOT) return "claude-code";
52
+ return "unknown";
53
+ }
54
+
55
+ /** Project label from the event's cwd (basename), falling back to process cwd. */
56
+ export function projectFromInput(input, fallbackCwd = process.cwd()) {
57
+ const record = input && typeof input === "object" ? input : {};
58
+ const cwd = typeof record.cwd === "string" && record.cwd.trim() ? record.cwd : fallbackCwd;
59
+ return path.basename(String(cwd).replace(/[\\/]+$/, "")) || "unknown";
60
+ }
61
+
62
+ /** Read all of stdin; "" when nothing is piped. */
63
+ export function readStdin(stream = process.stdin) {
64
+ if (stream.isTTY) return Promise.resolve("");
65
+ return new Promise((resolve) => {
66
+ let data = "";
67
+ stream.setEncoding("utf8");
68
+ stream.on("data", (chunk) => { data += chunk; });
69
+ stream.on("end", () => resolve(data));
70
+ stream.on("error", () => resolve(data));
71
+ });
72
+ }
73
+
74
+ export function parseHookInput(raw) {
75
+ try {
76
+ return raw && raw.trim() ? JSON.parse(raw) : {};
77
+ } catch {
78
+ return {};
79
+ }
80
+ }
81
+
82
+ /** ~4 chars per token; used only to enforce injection ceilings. */
83
+ export function estimateTokens(text) {
84
+ return Math.ceil(String(text).length / 4);
85
+ }
86
+
87
+ /** The structured hook output both hosts understand. */
88
+ export function contextOutput(hookEventName, additionalContext) {
89
+ return {
90
+ hookSpecificOutput: { hookEventName, additionalContext },
91
+ suppressOutput: true,
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Run a hook handler with the fail-soft contract: parse stdin, call the
97
+ * handler, print its output (or `{}`), never throw, always exit 0.
98
+ */
99
+ export async function runHook(hookEventName, handler) {
100
+ let output = {};
101
+ try {
102
+ const input = parseHookInput(await readStdin());
103
+ output = (await handler(input)) || {};
104
+ } catch (err) {
105
+ process.stderr.write(
106
+ `brain-memory ${hookEventName} hook: ${String(err && err.message ? err.message : err).slice(0, 300)}\n`
107
+ );
108
+ output = {};
109
+ }
110
+ process.stdout.write(JSON.stringify(output));
111
+ process.exitCode = 0;
112
+ }
113
+
114
+ /** True when this file is the process entry point (so tests can import it). */
115
+ export function isMain(metaUrl) {
116
+ return Boolean(process.argv[1]) && path.resolve(process.argv[1]) === fileURLToPath(metaUrl);
117
+ }
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * UserPromptSubmit hook (Claude Code + Codex plugin hosts).
4
+ *
5
+ * Runs the deterministic recall engine against the user's prompt and injects
6
+ * the best matches as `additionalContext` — brain's memories arrive with the
7
+ * prompt instead of waiting for the model to decide to call `brain recall`.
8
+ *
9
+ * Conservative by design, because it fires on every prompt:
10
+ * - explicit-query recall applies the relevance floor, so unrelated prompts
11
+ * inject nothing at all;
12
+ * - `prompt_recall_top` / `prompt_recall_budget_tokens` in ~/.brain/config.json
13
+ * bound the injection (defaults 3 memories, 600 tokens);
14
+ * - short prompts, bare slash commands and yes/no acknowledgements are skipped.
15
+ *
16
+ * Nothing is reinforced here: strength grows only when the model actually
17
+ * uses a memory (`brain reinforce`), never because a hook surfaced it.
18
+ * The block is wrapped in <brain-context> so `brain import` can strip it.
19
+ */
20
+
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+
24
+ import { brainDir, contextOutput, estimateTokens, hasBrain, isMain, loadModule, projectFromInput, runHook } from "./lib.mjs";
25
+
26
+ export const MIN_PROMPT_CHARS = 12;
27
+ export const MAX_QUERY_CHARS = 2000;
28
+ export const EXCERPT_CHARS = 240;
29
+
30
+ const SKIP_PROMPTS = [
31
+ /^\s*\/[a-z0-9:_-]+\s*$/i, // a bare slash command
32
+ /^\s*(y|n|yes|no|ok|okay|k|sure|thanks|thank you|ty|continue|go|go ahead|proceed|yep|yeah|nope)\b[.!]*\s*$/i,
33
+ ];
34
+
35
+ /** Prompts worth a recall pass: long enough, and not a command or an ack. */
36
+ export function shouldRecall(prompt) {
37
+ if (typeof prompt !== "string") return false;
38
+ const text = prompt.trim();
39
+ if (text.length < MIN_PROMPT_CHARS) return false;
40
+ return !SKIP_PROMPTS.some((pattern) => pattern.test(text));
41
+ }
42
+
43
+ /** First EXCERPT_CHARS of a memory body (frontmatter removed), single-line. */
44
+ export function excerptOf(fileContent) {
45
+ let body = String(fileContent || "");
46
+ if (body.startsWith("---")) {
47
+ const end = body.indexOf("\n---", 3);
48
+ if (end !== -1) body = body.slice(end + 4);
49
+ }
50
+ body = body.replace(/^#+\s.*$/m, "").replace(/\s+/g, " ").trim();
51
+ if (body.length <= EXCERPT_CHARS) return body;
52
+ const cut = body.slice(0, EXCERPT_CHARS);
53
+ const space = cut.lastIndexOf(" ");
54
+ return (space > EXCERPT_CHARS * 0.6 ? cut.slice(0, space) : cut).trimEnd() + "…";
55
+ }
56
+
57
+ function flagsOf(result) {
58
+ const flags = [];
59
+ if (result.low_trust) flags.push("⚠ low-trust");
60
+ if (result.quarantine_pending) flags.push("⊘ unverified");
61
+ if (result.expired) flags.push("⌛ expired");
62
+ if (result.superseded_by) flags.push("↪ superseded");
63
+ return flags.length ? ` [${flags.join(", ")}]` : "";
64
+ }
65
+
66
+ /**
67
+ * Render the injection block under a token budget, dropping the weakest
68
+ * matches first. Returns null when nothing fits.
69
+ *
70
+ * @param {Array<{receipt?: string, title?: string, excerpt?: string}>} entries
71
+ * @param {{budget: number}} options
72
+ */
73
+ export function buildContext(entries, { budget }) {
74
+ const header = [
75
+ "<brain-context>",
76
+ "◉ Brain recall for this prompt (deterministic). Use a memory only if it fits; when one shapes your answer, " +
77
+ "end the reply with its receipt line copied verbatim and run `brain reinforce <id>`.",
78
+ ];
79
+ const footer = ["</brain-context>"];
80
+ const items = entries.map((entry) => {
81
+ const label = entry.receipt || `◉ memory: "${entry.title || entry.id}"`;
82
+ return `- ${label}${flagsOf(entry)}${entry.excerpt ? ` — ${entry.excerpt}` : ""} (id ${entry.id})`;
83
+ });
84
+ while (items.length > 0) {
85
+ const text = [...header, ...items, ...footer].join("\n");
86
+ if (estimateTokens(text) <= budget) return text;
87
+ items.pop();
88
+ }
89
+ return null;
90
+ }
91
+
92
+ function readBody(memPath) {
93
+ try {
94
+ return fs.readFileSync(path.join(brainDir(), memPath), "utf-8");
95
+ } catch {
96
+ return "";
97
+ }
98
+ }
99
+
100
+ export async function handlePrompt(input, options = {}) {
101
+ if (!hasBrain()) return {};
102
+ const record = input && typeof input === "object" ? input : {};
103
+ if (!shouldRecall(record.prompt)) return {};
104
+
105
+ const config = (options.indexManager || loadModule("src/index-manager.js")).readConfig();
106
+ const top = Number(config.prompt_recall_top);
107
+ const budget = Number(config.prompt_recall_budget_tokens);
108
+ if (!(top > 0) || !(budget > 0)) return {};
109
+
110
+ const { computeRecall } = options.recall || loadModule("bin/recall.js");
111
+ const results = computeRecall({
112
+ query: record.prompt.trim().slice(0, MAX_QUERY_CHARS),
113
+ project: projectFromInput(record),
114
+ top,
115
+ });
116
+ if (!results.length) return {};
117
+
118
+ const entries = results.map((r) => ({ ...r, excerpt: excerptOf(readBody(r.path)) }));
119
+ const context = buildContext(entries, { budget });
120
+ return context ? contextOutput("UserPromptSubmit", context) : {};
121
+ }
122
+
123
+ if (isMain(import.meta.url)) runHook("UserPromptSubmit", handlePrompt);
@@ -0,0 +1,54 @@
1
+ # Brain Memory — Session End Hook
2
+
3
+ > **Note:** This file is a reference definition. The actual behavior is delivered through the prompt files (`prompts/claude.md`, `prompts/gemini.md`, `prompts/openai.md`) which are injected into each runtime's config file during installation. AI runtimes do not have native session-end hook events — the agent follows these instructions because they are embedded in the prompt it reads at session start.
4
+
5
+ This hook is triggered at the end of a coding session. Its purpose is to prompt the agent to consider storing important memories and to save session context.
6
+
7
+ ## Behavior
8
+
9
+ When a session is ending (user signals they are done, says bye/thanks, or the conversation appears to be wrapping up), perform these steps **in order**:
10
+
11
+ ### Step 1: Save Session Context (ALWAYS — do this first)
12
+
13
+ **Immediately** append a session summary to `.brain/contexts.json`. Do this for ALL sessions, even trivial ones — context tracking is cheap and provides valuable recall signals for future sessions.
14
+
15
+ ```json
16
+ {
17
+ "session_id": "<timestamp-based-id>",
18
+ "started": "<session start ISO timestamp>",
19
+ "ended": "<session end ISO timestamp>",
20
+ "project": "<current project name>",
21
+ "topics": ["<key topics discussed>"],
22
+ "task_type": "<primary task type: debugging|implementing|designing|reviewing|discussing|learning>",
23
+ "memories_created": ["<IDs of memories stored this session>"],
24
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
25
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
26
+ }
27
+ ```
28
+
29
+ Keep only the last 20 session entries in `contexts.json` to prevent unbounded growth. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
30
+
31
+ **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively.
32
+
33
+ ### Step 2: Suggest Memorization (if warranted)
34
+
35
+ Review the ambient tracking log (maintained throughout the session) for notable:
36
+
37
+ 1. **Decisions** — Architecture choices, technology selections, trade-off resolutions
38
+ 2. **Learnings** — New patterns, debugging insights, API discoveries
39
+ 3. **Insights** — Realizations about the codebase, project, or process
40
+ 4. **Experiences** — Significant events like incidents, deployments, milestones
41
+ 5. **Goals** — New objectives discussed or planned
42
+
43
+ If the session contained meaningful content in any of these categories, suggest to the user:
44
+
45
+ ```
46
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
47
+ Run /brain:memorize to capture them before this context is lost.
48
+ ```
49
+
50
+ **Rules:**
51
+ - Do NOT auto-memorize without user consent
52
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
53
+ - Only suggest when there is genuinely valuable context worth preserving
54
+ - Keep the suggestion brief and non-intrusive
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * SessionEnd hook (Claude Code + Codex plugin hosts).
4
+ *
5
+ * Appends a session-boundary entry to ~/.brain/contexts.json so
6
+ * context-dependent recall has a signal even when the model never reached a
7
+ * wrap-up. A hook process only knows the boundary facts (host session id,
8
+ * project, end time); the richer fields (topics, memories created/recalled,
9
+ * notable unsaved) are written by the model itself when it detects a wrap-up.
10
+ *
11
+ * Codex gives SessionEnd hooks one second by default, so this stays in-process
12
+ * and does a single read-modify-write. Output has no effect on the session.
13
+ */
14
+
15
+ import { hasBrain, isMain, loadModule, projectFromInput, runHook } from "./lib.mjs";
16
+
17
+ export const MAX_CONTEXT_ENTRIES = 20;
18
+
19
+ /** Build the entry in the shape the prompt-based session-end contract uses. */
20
+ export function buildContextEntry(input, now = new Date()) {
21
+ const record = input && typeof input === "object" ? input : {};
22
+ const ended = now.toISOString();
23
+ const stamp = ended.replace(/[-:.TZ]/g, "").slice(0, 14);
24
+ const key = typeof record.session_id === "string" && record.session_id
25
+ ? `-${record.session_id.replace(/[^\w.-]+/g, "_")}`
26
+ : "";
27
+ return {
28
+ session_id: `${stamp}${key}`,
29
+ started: ended,
30
+ ended,
31
+ project: projectFromInput(record),
32
+ topics: [],
33
+ task_type: "unknown",
34
+ memories_created: [],
35
+ memories_recalled: [],
36
+ notable_unsaved: [],
37
+ source: "session-end-hook",
38
+ };
39
+ }
40
+
41
+ /** Pure append + trim over either `{sessions: [...]}` or a bare array. */
42
+ export function appendContextEntry(contexts, entry, max = MAX_CONTEXT_ENTRIES) {
43
+ let sessions;
44
+ let wrapped = null;
45
+ if (Array.isArray(contexts)) sessions = contexts.slice();
46
+ else if (contexts && typeof contexts === "object" && Array.isArray(contexts.sessions)) {
47
+ wrapped = contexts;
48
+ sessions = contexts.sessions.slice();
49
+ } else sessions = [];
50
+ sessions.push(entry);
51
+ if (sessions.length > max) sessions = sessions.slice(sessions.length - max);
52
+ return wrapped ? { ...wrapped, sessions } : { version: 1, sessions };
53
+ }
54
+
55
+ export function handleSessionEnd(input, options = {}) {
56
+ if (!hasBrain()) return {};
57
+ const im = options.indexManager || loadModule("src/index-manager.js");
58
+ const entry = buildContextEntry(input, options.now);
59
+ im.writeContexts(appendContextEntry(im.readContexts(), entry));
60
+ return {};
61
+ }
62
+
63
+ if (isMain(import.meta.url)) runHook("SessionEnd", handleSessionEnd);
@@ -0,0 +1,58 @@
1
+ # Brain Memory — Session Start Hook
2
+
3
+ > **Note:** This file is a reference definition. The actual behavior is delivered through the prompt files (`prompts/claude.md`, `prompts/gemini.md`, `prompts/openai.md`) which are injected into each runtime's config file during installation. AI runtimes do not have native session-start hook events — the agent follows these instructions because they are embedded in the prompt it reads at session start.
4
+
5
+ This hook is triggered at the start of a coding session. Its purpose is to load relevant context from the brain memory system and capture session context for context-dependent recall.
6
+
7
+ ## Behavior
8
+
9
+ At session start, if `.brain/index.json` exists, call the budget-bounded aggregator:
10
+
11
+ ```bash
12
+ brain session-start --project "<current project>"
13
+ ```
14
+
15
+ It returns one JSON payload — `memory_count`, `pinned`, `skills_index`, `context_recall`, `due_for_review`, `low_confidence_alerts`, `budget` — capped to the working-memory token budget in `config.json`. Then:
16
+
17
+ 1. **Silently internalize** the payload — apply `pinned` facts as active constraints, note available `skills_index` skills, keep `context_recall` in mind
18
+ 2. **Do NOT dump memories** — do not print contents at session start unless the user asks
19
+
20
+ ### Context Capture
21
+
22
+ Capture the current session context for context-dependent recall:
23
+ - **Project name**: from the current working directory or project config
24
+ - **Topics**: inferred from recent files, open issues, or conversation
25
+ - **Task type**: will be determined as the session progresses
26
+
27
+ This context is used by `/brain:remember` to boost memories that were encoded in a similar context.
28
+
29
+ ### Review Queue Check
30
+
31
+ Read `.brain/review-queue.json` if it exists. If there are memories due for review:
32
+
33
+ ```
34
+ ◉ Brain active — <N> memories loaded (<M> in current project context)
35
+ 📋 <X> memories due for review — reinforced automatically during /brain:sleep
36
+ ```
37
+
38
+ Otherwise:
39
+
40
+ ```
41
+ ◉ Brain active — <N> memories loaded (<M> in current project context)
42
+ ```
43
+
44
+ ### Low-Confidence Alert
45
+
46
+ If any frequently-used memories (access_count >= 3) have confidence < 0.5, briefly note:
47
+
48
+ ```
49
+ ⚠️ <N> frequently-used memories have low confidence — consider verifying
50
+ ```
51
+
52
+ **The goal is ambient awareness** — you should know about important past decisions, learnings, and preferences without explicitly reciting them. If a situation arises where a past memory is relevant, naturally reference it.
53
+
54
+ Keep the status output to 1-3 lines. The user can run `/brain:status` for details.
55
+
56
+ ### Begin Ambient Session Tracking
57
+
58
+ After outputting the status, begin maintaining a running mental log of notable events (decisions, learnings, insights, experiences, goals) as they happen throughout the session. This is purely internal — no file writes needed. The ambient log feeds the Periodic Memory Checkpoint and Session End context save.