brain-memory 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +193 -0
- package/README.md +27 -3
- package/SECURITY.md +44 -3
- package/bin/audit.js +18 -1
- package/bin/brain +4 -0
- package/bin/cloud-sync.js +49 -6
- package/bin/import.js +1 -1
- package/bin/install.js +10 -0
- package/bin/memorize.js +53 -8
- package/bin/recall.js +32 -13
- package/bin/reinforce.js +34 -1
- package/bin/session-start.js +17 -4
- package/bin/skill.js +8 -2
- package/commands/brain/import.md +1 -1
- package/commands/brain/memorize.md +25 -4
- package/commands/brain/skills.md +29 -0
- package/commands/brain/sync.md +23 -0
- package/hooks/hooks.json +39 -0
- package/hooks/lib.mjs +117 -0
- package/hooks/prompt-recall.mjs +123 -0
- package/hooks/session-end.md +54 -0
- package/hooks/session-end.mjs +63 -0
- package/hooks/session-start.md +58 -0
- package/hooks/session-start.mjs +82 -0
- package/integrations/agentskills/brain-memory/SKILL.md +5 -0
- package/package.json +10 -4
- package/prompts/antigravity.md +4 -1
- package/prompts/claude.md +4 -1
- package/prompts/copilot.md +4 -1
- package/prompts/kilo.md +4 -1
- package/prompts/openai.md +4 -1
- package/prompts/opencode.md +4 -1
- package/src/anomaly.js +7 -0
- package/src/cloud-sync.js +121 -9
- package/src/contradiction.js +106 -0
- package/src/harvest.js +174 -2
- package/src/index-manager.js +8 -0
- package/src/installer.js +126 -3
- package/src/integrity.js +155 -0
- package/src/receipt.js +8 -4
- package/src/sensitivity.js +134 -0
- package/src/skill-verify.js +191 -0
- package/src/skills.js +63 -0
- package/store/CONTRACT.md +244 -0
- package/store/Dockerfile +24 -0
- package/store/README.md +43 -0
- package/store/SELF-HOSTING.md +200 -0
- package/store/bin/brain-store.js +189 -0
- package/store/conformance/conformance.test.js +341 -0
- package/store/conformance/helpers.js +145 -0
- package/store/deploy/Caddyfile +14 -0
- package/store/deploy/connector.Dockerfile +38 -0
- package/store/deploy/docker-compose.yml +83 -0
- package/store/deploy/env.example +19 -0
- package/store/lib/auth.js +174 -0
- package/store/lib/oidc.js +206 -0
- package/store/lib/storage.js +333 -0
- package/store/lib/tar.js +150 -0
- package/store/openapi.yaml +318 -0
- package/store/server.js +465 -0
- package/store/test/mock-issuer.js +104 -0
- package/store/test/oidc.test.js +217 -0
- package/store/test/store.test.js +445 -0
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.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* SessionStart hook (Claude Code + Codex plugin hosts).
|
|
4
|
+
*
|
|
5
|
+
* Injects the budget-bounded `brain session-start` payload as
|
|
6
|
+
* `additionalContext`, together with the ambient rules the prompt-based
|
|
7
|
+
* install would otherwise carry in CLAUDE.md / AGENTS.md. This is the
|
|
8
|
+
* deterministic form of the session-start behaviour: the host injects it,
|
|
9
|
+
* the model does not have to remember to run anything.
|
|
10
|
+
*
|
|
11
|
+
* The payload is computed in-process from ../bin/session-start.js and is
|
|
12
|
+
* already capped by `working_memory_budget_tokens` in ~/.brain/config.json.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { contextOutput, detectHost, hasBrain, isMain, loadModule, projectFromInput, runHook } from "./lib.mjs";
|
|
16
|
+
|
|
17
|
+
const COMMANDS = {
|
|
18
|
+
"claude-code":
|
|
19
|
+
"Commands: /brain:remember, /brain:memorize, /brain:status, /brain:pin, /brain:forget, " +
|
|
20
|
+
"/brain:verify, /brain:sync, /brain:skills, /brain:import, /brain:sleep.",
|
|
21
|
+
codex:
|
|
22
|
+
"Skills: brain-remember, brain-memorize, brain-status, brain-pin, brain-forget, " +
|
|
23
|
+
"brain-verify, brain-sync, brain-skills, brain-import, brain-sleep (or the `brain` CLI directly).",
|
|
24
|
+
unknown: "Use the `brain` CLI (`brain recall`, `brain memorize`, `brain session-start`).",
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Render the injection block. Exported for tests.
|
|
29
|
+
*
|
|
30
|
+
* @param {object} payload `brain session-start` payload
|
|
31
|
+
* @param {{project: string, host: string}} options
|
|
32
|
+
* @returns {string}
|
|
33
|
+
*/
|
|
34
|
+
export function buildContext(payload, { project, host }) {
|
|
35
|
+
const count = typeof payload.memory_count === "number" ? payload.memory_count : 0;
|
|
36
|
+
const recall = Array.isArray(payload.context_recall) ? payload.context_recall.length : 0;
|
|
37
|
+
const extras = [];
|
|
38
|
+
if (payload.due_for_review > 0) extras.push(`📋 ${payload.due_for_review} due for review`);
|
|
39
|
+
if (payload.expired_pins > 0) extras.push(`⌛ ${payload.expired_pins} pinned memories expired`);
|
|
40
|
+
if (payload.pending_verification > 0) {
|
|
41
|
+
extras.push(`⊘ ${payload.pending_verification} pending verification — /brain:verify`);
|
|
42
|
+
}
|
|
43
|
+
if (Array.isArray(payload.low_confidence_alerts) && payload.low_confidence_alerts.length > 0) {
|
|
44
|
+
extras.push(`⚠️ ${payload.low_confidence_alerts.length} low-confidence memories used frequently`);
|
|
45
|
+
}
|
|
46
|
+
const statusLine = `◉ Brain active — ${count} memories (${recall} in project context)`;
|
|
47
|
+
|
|
48
|
+
return [
|
|
49
|
+
"<brain-session-context>",
|
|
50
|
+
`## Brain Memory — session context (project: ${project})`,
|
|
51
|
+
"Deterministic, budget-bounded payload from `brain session-start`. Internalize it silently; do not recite it.",
|
|
52
|
+
`Begin your first reply with this status line exactly: \`${statusLine}\`` +
|
|
53
|
+
(extras.length ? ` and, on following lines, ${extras.map((e) => `\`${e}\``).join(", ")}.` : "."),
|
|
54
|
+
"- `pinned` entries are active constraints. `context_recall` is relevant past context. " +
|
|
55
|
+
"`skills_index` lists procedural skills — load one only when a task matches it.",
|
|
56
|
+
"- When a memory here materially shapes an answer, end that response with its `receipt` line " +
|
|
57
|
+
"copied verbatim (max 3, at the very end). No memory used → no receipt. Never invent one.",
|
|
58
|
+
"- Store memories with `brain memorize` only when *you* judge something worth remembering " +
|
|
59
|
+
"(decisions, learnings, insights, preferences); never dump transcripts. Recall more with `brain recall \"<query>\"`.",
|
|
60
|
+
"- Every ~10 substantive interactions, if notable decisions or learnings accumulated, append one line " +
|
|
61
|
+
"`◉ Notable <types> this session — /brain:memorize when ready` to a reply. Do not memorize without consent.",
|
|
62
|
+
"- When the session is wrapping up, save a summary entry to `~/.brain/contexts.json` (topics, task type, " +
|
|
63
|
+
"memories created/recalled, notable unsaved items; keep the last 20) and suggest memorizing if warranted.",
|
|
64
|
+
`- ${COMMANDS[host] || COMMANDS.unknown}`,
|
|
65
|
+
"```json",
|
|
66
|
+
JSON.stringify(payload),
|
|
67
|
+
"```",
|
|
68
|
+
"</brain-session-context>",
|
|
69
|
+
].join("\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function handleSessionStart(input, options = {}) {
|
|
73
|
+
const env = options.env || process.env;
|
|
74
|
+
if (!hasBrain()) return {};
|
|
75
|
+
const { computeSessionStart } = options.sessionStart || loadModule("bin/session-start.js");
|
|
76
|
+
const project = projectFromInput(input);
|
|
77
|
+
const payload = computeSessionStart(undefined, { project, topics: null, task: null, top: 5 });
|
|
78
|
+
const context = buildContext(payload, { project, host: detectHost(env) });
|
|
79
|
+
return contextOutput("SessionStart", context);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (isMain(import.meta.url)) runHook("SessionStart", handleSessionStart);
|
|
@@ -70,6 +70,11 @@ honestly by provenance, not confidence**:
|
|
|
70
70
|
(you concluded it — the default) · `tool-output` (from a tool/file result) ·
|
|
71
71
|
`external` (from web/email/third-party content). Non-user origins are
|
|
72
72
|
confidence-capped at write and down-weighted at recall.
|
|
73
|
+
- **sensitivity** (consent tier): `standard` (default) · `sensitive` (health,
|
|
74
|
+
race, ethnicity, religion, politics, gender identity or sexual orientation —
|
|
75
|
+
stored only if the user opted in via `sensitive_topics: true`, otherwise held
|
|
76
|
+
quarantined until `brain verify approve`) · `blocked` (government ID numbers,
|
|
77
|
+
criminal history, immigration status — refused). Label the topic honestly.
|
|
73
78
|
- **salience**, **confidence** (0.0–1.0), **tags**, **related** ids
|
|
74
79
|
|
|
75
80
|
```bash
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brain-memory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
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",
|
|
@@ -25,15 +25,18 @@
|
|
|
25
25
|
"url": "https://github.com/omelas-tech/brain/issues"
|
|
26
26
|
},
|
|
27
27
|
"bin": {
|
|
28
|
-
"brain": "bin/brain.js"
|
|
28
|
+
"brain": "bin/brain.js",
|
|
29
|
+
"brain-store": "store/bin/brain-store.js"
|
|
29
30
|
},
|
|
30
31
|
"files": [
|
|
31
32
|
"assets/",
|
|
32
33
|
"bin/",
|
|
33
34
|
"commands/",
|
|
35
|
+
"hooks/",
|
|
34
36
|
"prompts/",
|
|
35
37
|
"templates/",
|
|
36
38
|
"src/",
|
|
39
|
+
"store/",
|
|
37
40
|
"integrations/agentskills/brain-memory/",
|
|
38
41
|
"README.md",
|
|
39
42
|
"SECURITY.md",
|
|
@@ -45,7 +48,7 @@
|
|
|
45
48
|
"url": "git+https://github.com/omelas-tech/brain.git"
|
|
46
49
|
},
|
|
47
50
|
"scripts": {
|
|
48
|
-
"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/restore.test.js test/trust-recall.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 test/harvest.test.js test/content-lint.test.js test/audit-log.test.js test/quarantine.test.js test/anomaly.test.js test/path-hardening.test.js test/supersede.test.js test/bitemporal.test.js",
|
|
51
|
+
"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/restore.test.js test/trust-recall.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 test/harvest.test.js test/content-lint.test.js test/audit-log.test.js test/quarantine.test.js test/anomaly.test.js test/path-hardening.test.js test/supersede.test.js test/bitemporal.test.js test/integrity.test.js test/skill-verify.test.js test/decay-calibration.test.js test/recall-history.test.js test/plugin-manifests.test.js test/plugin-hooks.test.js test/sensitivity.test.js test/cloud-store.test.js store/test/store.test.js store/test/oidc.test.js store/conformance/conformance.test.js",
|
|
49
52
|
"test:integrations": "npm run test:integrations:agentskills && npm run test:integrations:openclaw && npm run test:integrations:copilot && npm run test:integrations:kilo && npm run test:integrations:hermes",
|
|
50
53
|
"test:integrations:agentskills": "node --test integrations/agentskills/test/*.test.mjs",
|
|
51
54
|
"test:integrations:openclaw": "node --test integrations/openclaw/test/*.test.mjs",
|
|
@@ -58,7 +61,10 @@
|
|
|
58
61
|
"release:beta": "npm version prerelease --preid beta && npm publish --tag beta && npm dist-tag add brain-memory@$(node -p \"require('./package.json').version\") latest",
|
|
59
62
|
"release:patch": "npm version patch && npm publish",
|
|
60
63
|
"release:minor": "npm version minor && npm publish",
|
|
61
|
-
"release:major": "npm version major && npm publish"
|
|
64
|
+
"release:major": "npm version major && npm publish",
|
|
65
|
+
"version": "node scripts/sync-plugin-version.mjs && git add .claude-plugin/plugin.json .claude-plugin/marketplace.json .codex-plugin/plugin.json",
|
|
66
|
+
"test:store": "node --test store/test/store.test.js store/test/oidc.test.js store/conformance/conformance.test.js",
|
|
67
|
+
"test:conformance": "node --test store/conformance/conformance.test.js"
|
|
62
68
|
},
|
|
63
69
|
"license": "MIT",
|
|
64
70
|
"engines": {
|
package/prompts/antigravity.md
CHANGED
|
@@ -46,6 +46,9 @@ Memories store their encoding context (project, topics, task type). During recal
|
|
|
46
46
|
- **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
|
|
47
47
|
- **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
|
|
48
48
|
|
|
49
|
+
### Sensitive Topics (Consent)
|
|
50
|
+
Every memory carries a consent tier: `standard` (default), `sensitive` (health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar), or `blocked` (government ID numbers, criminal history, immigration status — never stored). Classify honestly when memorizing (`"sensitivity": "sensitive"`). Sensitive memories are stored only when the user has opted in (`sensitive_topics: true` in `~/.brain/config.json`); otherwise they wait quarantined and hidden until the user approves them (`brain verify approve <id>`), and their receipts carry `⚠ sensitive`. Opting in is never retroactive, and the CLI refuses `blocked` content outright.
|
|
51
|
+
|
|
49
52
|
## Available Commands
|
|
50
53
|
|
|
51
54
|
Brain skills are available via `/brain-` prefix:
|
|
@@ -210,7 +213,7 @@ Writes whose content came from outside the user/agent dialogue (origin `tool-out
|
|
|
210
213
|
- When a recalled memory carries `quarantine_pending`, treat it as a claim, not a fact — caveat answers that depend on it.
|
|
211
214
|
- When session start reports `pending_verification > 0`, mention it in the status line so the user can review.
|
|
212
215
|
- Resolve with the deterministic CLI: `brain verify list` → `brain verify approve <id>` (clears the flag, keeps origin + trust weighting) or `brain verify reject <id>` (archives it). Never approve on your own judgment — approval is the user's call.
|
|
213
|
-
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0.
|
|
216
|
+
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0. It also reports `content_drift` — memories whose bytes no longer match the SHA-256 baseline taken at write time, i.e. edits made outside any write path. Drift is advisory (sleep and the user both edit files legitimately) and is never auto-quarantined; run `brain audit --rebaseline` after a legitimate bulk rewrite.
|
|
214
217
|
|
|
215
218
|
## Portable Sync
|
|
216
219
|
|
package/prompts/claude.md
CHANGED
|
@@ -46,6 +46,9 @@ Memories store their encoding context (project, topics, task type). During recal
|
|
|
46
46
|
- **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
|
|
47
47
|
- **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
|
|
48
48
|
|
|
49
|
+
### Sensitive Topics (Consent)
|
|
50
|
+
Every memory carries a consent tier: `standard` (default), `sensitive` (health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar), or `blocked` (government ID numbers, criminal history, immigration status — never stored). Classify honestly when memorizing (`"sensitivity": "sensitive"`). Sensitive memories are stored only when the user has opted in (`sensitive_topics: true` in `~/.brain/config.json`); otherwise they wait quarantined and hidden until the user approves them (`brain verify approve <id>`), and their receipts carry `⚠ sensitive`. Opting in is never retroactive, and the CLI refuses `blocked` content outright.
|
|
51
|
+
|
|
49
52
|
## Available Commands
|
|
50
53
|
|
|
51
54
|
The everyday loop is **ambient** — `remember` and `memorize` run automatically at session start/end; you rarely type them.
|
|
@@ -209,7 +212,7 @@ Writes whose content came from outside the user/agent dialogue (origin `tool-out
|
|
|
209
212
|
- When a recalled memory carries `quarantine_pending`, treat it as a claim, not a fact — caveat answers that depend on it.
|
|
210
213
|
- When session start reports `pending_verification > 0`, mention it in the status line so the user can review.
|
|
211
214
|
- Resolve with the deterministic CLI: `brain verify list` → `brain verify approve <id>` (clears the flag, keeps origin + trust weighting) or `brain verify reject <id>` (archives it). Never approve on your own judgment — approval is the user's call.
|
|
212
|
-
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0.
|
|
215
|
+
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0. It also reports `content_drift` — memories whose bytes no longer match the SHA-256 baseline taken at write time, i.e. edits made outside any write path. Drift is advisory (sleep and the user both edit files legitimately) and is never auto-quarantined; run `brain audit --rebaseline` after a legitimate bulk rewrite.
|
|
213
216
|
|
|
214
217
|
## Portable Sync
|
|
215
218
|
|
package/prompts/copilot.md
CHANGED
|
@@ -48,6 +48,9 @@ Memories store their encoding context (project, topics, task type). During recal
|
|
|
48
48
|
- **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
|
|
49
49
|
- **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
|
|
50
50
|
|
|
51
|
+
### Sensitive Topics (Consent)
|
|
52
|
+
Every memory carries a consent tier: `standard` (default), `sensitive` (health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar), or `blocked` (government ID numbers, criminal history, immigration status — never stored). Classify honestly when memorizing (`"sensitivity": "sensitive"`). Sensitive memories are stored only when the user has opted in (`sensitive_topics: true` in `~/.brain/config.json`); otherwise they wait quarantined and hidden until the user approves them (`brain verify approve <id>`), and their receipts carry `⚠ sensitive`. Opting in is never retroactive, and the CLI refuses `blocked` content outright.
|
|
53
|
+
|
|
51
54
|
## Available Commands
|
|
52
55
|
|
|
53
56
|
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.
|
|
@@ -212,7 +215,7 @@ Writes whose content came from outside the user/agent dialogue (origin `tool-out
|
|
|
212
215
|
- When a recalled memory carries `quarantine_pending`, treat it as a claim, not a fact — caveat answers that depend on it.
|
|
213
216
|
- When session start reports `pending_verification > 0`, mention it in the status line so the user can review.
|
|
214
217
|
- Resolve with the deterministic CLI: `brain verify list` → `brain verify approve <id>` (clears the flag, keeps origin + trust weighting) or `brain verify reject <id>` (archives it). Never approve on your own judgment — approval is the user's call.
|
|
215
|
-
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0.
|
|
218
|
+
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0. It also reports `content_drift` — memories whose bytes no longer match the SHA-256 baseline taken at write time, i.e. edits made outside any write path. Drift is advisory (sleep and the user both edit files legitimately) and is never auto-quarantined; run `brain audit --rebaseline` after a legitimate bulk rewrite.
|
|
216
219
|
|
|
217
220
|
## Portable Sync
|
|
218
221
|
|
package/prompts/kilo.md
CHANGED
|
@@ -48,6 +48,9 @@ Memories store their encoding context (project, topics, task type). During recal
|
|
|
48
48
|
- **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
|
|
49
49
|
- **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
|
|
50
50
|
|
|
51
|
+
### Sensitive Topics (Consent)
|
|
52
|
+
Every memory carries a consent tier: `standard` (default), `sensitive` (health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar), or `blocked` (government ID numbers, criminal history, immigration status — never stored). Classify honestly when memorizing (`"sensitivity": "sensitive"`). Sensitive memories are stored only when the user has opted in (`sensitive_topics: true` in `~/.brain/config.json`); otherwise they wait quarantined and hidden until the user approves them (`brain verify approve <id>`), and their receipts carry `⚠ sensitive`. Opting in is never retroactive, and the CLI refuses `blocked` content outright.
|
|
53
|
+
|
|
51
54
|
## Available Commands
|
|
52
55
|
|
|
53
56
|
The everyday loop is **ambient** — `remember` and `memorize` run automatically at session start/end; you rarely type them.
|
|
@@ -211,7 +214,7 @@ Writes whose content came from outside the user/agent dialogue (origin `tool-out
|
|
|
211
214
|
- When a recalled memory carries `quarantine_pending`, treat it as a claim, not a fact — caveat answers that depend on it.
|
|
212
215
|
- When session start reports `pending_verification > 0`, mention it in the status line so the user can review.
|
|
213
216
|
- Resolve with the deterministic CLI: `brain verify list` → `brain verify approve <id>` (clears the flag, keeps origin + trust weighting) or `brain verify reject <id>` (archives it). Never approve on your own judgment — approval is the user's call.
|
|
214
|
-
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0.
|
|
217
|
+
- `brain audit [--window 7d]` scans for anomalous write patterns (bursts, co-tagged low-trust cliques, quiet reinforcement); `--apply` quarantines what it finds. It runs automatically as sleep Phase 0. It also reports `content_drift` — memories whose bytes no longer match the SHA-256 baseline taken at write time, i.e. edits made outside any write path. Drift is advisory (sleep and the user both edit files legitimately) and is never auto-quarantined; run `brain audit --rebaseline` after a legitimate bulk rewrite.
|
|
215
218
|
|
|
216
219
|
## Portable Sync
|
|
217
220
|
|