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.
@@ -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.2.0",
3
+ "version": "0.3.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",
@@ -31,6 +31,7 @@
31
31
  "assets/",
32
32
  "bin/",
33
33
  "commands/",
34
+ "hooks/",
34
35
  "prompts/",
35
36
  "templates/",
36
37
  "src/",
@@ -45,7 +46,7 @@
45
46
  "url": "git+https://github.com/omelas-tech/brain.git"
46
47
  },
47
48
  "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",
49
+ "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",
49
50
  "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
51
  "test:integrations:agentskills": "node --test integrations/agentskills/test/*.test.mjs",
51
52
  "test:integrations:openclaw": "node --test integrations/openclaw/test/*.test.mjs",
@@ -58,7 +59,8 @@
58
59
  "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
60
  "release:patch": "npm version patch && npm publish",
60
61
  "release:minor": "npm version minor && npm publish",
61
- "release:major": "npm version major && npm publish"
62
+ "release:major": "npm version major && npm publish",
63
+ "version": "node scripts/sync-plugin-version.mjs && git add .claude-plugin/plugin.json .claude-plugin/marketplace.json .codex-plugin/plugin.json"
62
64
  },
63
65
  "license": "MIT",
64
66
  "engines": {
@@ -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
 
@@ -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
 
package/prompts/openai.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
 
@@ -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/src/anomaly.js CHANGED
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  const { isLowTrust } = require('./provenance');
22
+ const { detectContentDrift } = require('./integrity');
22
23
  const { readAudit } = require('./audit');
23
24
  const { listPending, applyQuarantine } = require('./quarantine');
24
25
 
@@ -204,11 +205,16 @@ function runAudit(brainDir, deps, opts = {}) {
204
205
  ...detectWriteBursts(auditEvents, { windowHours }),
205
206
  ...detectLowTrustCliques(index, associations),
206
207
  ...detectReinforcedLowTrust(index),
208
+ // Store-phase tamper detection. Advisory only — legitimate edits (sleep
209
+ // consolidation, a user fixing a typo) also move the hash, so these
210
+ // findings are reported but never fed to the --apply quarantine path.
211
+ ...detectContentDrift(brainDir, index),
207
212
  ];
208
213
 
209
214
  const memories = (index && index.memories) || {};
210
215
  const proposed = new Set();
211
216
  for (const f of findings) {
217
+ if (f.advisory) continue; // integrity drift is reported, never auto-quarantined
212
218
  for (const id of f.ids || (f.id ? [f.id] : [])) {
213
219
  const e = memories[id];
214
220
  if (!e) continue;
@@ -253,6 +259,7 @@ function runAudit(brainDir, deps, opts = {}) {
253
259
 
254
260
  module.exports = {
255
261
  detectWriteBursts,
262
+ detectContentDrift,
256
263
  detectLowTrustCliques,
257
264
  detectReinforcedLowTrust,
258
265
  runAudit,
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Brain Memory — Contradiction Proposals (bitemporal boundary suggestions)
3
+ *
4
+ * A brain that only ever appends accumulates contradictions. "We deploy to
5
+ * Fly.io" recorded in June and "we deploy to Render" recorded in August are not
6
+ * two competing facts — they are one fact with a boundary. src/temporal.js can
7
+ * already represent that (`valid_until`, stamped automatically when B
8
+ * supersedes A). What was missing is anyone NOTICING that a new write implies
9
+ * such a boundary.
10
+ *
11
+ * Until now the boundary was only drawn when the agent explicitly passed
12
+ * `supersedes`. Nothing prompted it to. So the common path — user states a new
13
+ * decision that quietly replaces an old one, without saying "this replaces X" —
14
+ * left both memories live, unbounded, and equally recallable. That is exactly
15
+ * the "memory staleness" failure competitors report as unsolved: a
16
+ * high-relevance fact that is now confidently wrong.
17
+ *
18
+ * This module looks at the memories a new write overlaps and proposes which of
19
+ * them it probably ended, and when.
20
+ *
21
+ * ── It proposes; it never applies ────────────────────────────────────────
22
+ * Deciding that B replaces A is a semantic judgement this code cannot make —
23
+ * "use Postgres for analytics" does not contradict "use Postgres for sessions"
24
+ * however many tags they share. So the output is a SUGGESTION carried back to
25
+ * the agent, which has the conversation and can ask. Auto-stamping
26
+ * `valid_until` on a tag heuristic would silently expire correct memories,
27
+ * which is a worse failure than leaving a stale one live.
28
+ *
29
+ * ── Why these filters ────────────────────────────────────────────────────
30
+ * Tag overlap alone is a relatedness signal, not a contradiction signal. Three
31
+ * additional filters cut the noise to something worth showing a user:
32
+ *
33
+ * same type A `decision` can end a `decision`. An `observation` that
34
+ * shares tags with a decision is context, not a reversal.
35
+ * not already bounded A memory with an explicit `valid_until` has an author's
36
+ * window; never second-guess it.
37
+ * not already superseded Already resolved — proposing again is noise.
38
+ *
39
+ * Pinned and stable memories are surfaced regardless of type, preserving the
40
+ * pre-existing behaviour: those carry the most authority, so a possible
41
+ * conflict with one is worth a look even when the heuristic is unsure.
42
+ */
43
+
44
+ const { supersessionInstant } = require('./temporal');
45
+
46
+ /**
47
+ * Rank how much authority a memory carries, so the most consequential possible
48
+ * contradiction is the first thing the agent reads.
49
+ */
50
+ function authorityOf(entry) {
51
+ if (entry.pinned) return 'pinned';
52
+ if (entry.stable) return 'stable';
53
+ return 'same-type';
54
+ }
55
+
56
+ const AUTHORITY_RANK = { pinned: 3, stable: 2, 'same-type': 1 };
57
+
58
+ /**
59
+ * Propose which existing memories a new write may have ended, and when.
60
+ *
61
+ * @param {Object} index - Live brain index
62
+ * @param {Object} newMem - The incoming memory (needs type, valid_from/created)
63
+ * @param {string[]} overlapIds - Candidate ids (from findTagOverlaps)
64
+ * @param {Object} [opts]
65
+ * @param {string} [opts.now] - ISO instant the successor starts at, when the
66
+ * memory carries neither `valid_from` nor `created` yet
67
+ * @returns {Array<Object>} proposals, highest authority first
68
+ */
69
+ function proposeSupersessions(index, newMem, overlapIds, opts = {}) {
70
+ const memories = (index && index.memories) || {};
71
+ const newTags = new Set(newMem.tags || []);
72
+ const boundary = supersessionInstant(newMem) || opts.now || null;
73
+
74
+ const proposals = [];
75
+ for (const id of overlapIds || []) {
76
+ const entry = memories[id];
77
+ if (!entry) continue;
78
+
79
+ // Already resolved, or the author drew their own window — leave both alone.
80
+ if (entry.superseded_by) continue;
81
+ if (entry.valid_until) continue;
82
+
83
+ const authority = authorityOf(entry);
84
+ // Beyond pinned/stable, only a like-for-like memory is a plausible
85
+ // reversal. An observation sharing tags with a decision is context.
86
+ if (authority === 'same-type' && entry.type !== newMem.type) continue;
87
+
88
+ proposals.push({
89
+ id,
90
+ title: entry.title,
91
+ type: entry.type,
92
+ authority,
93
+ shared_tags: (entry.tags || []).filter((t) => newTags.has(t)),
94
+ // What `brain memorize --supersedes <id>` would stamp if confirmed.
95
+ proposed_valid_until: boundary,
96
+ });
97
+ }
98
+
99
+ return proposals.sort(
100
+ (a, b) => (AUTHORITY_RANK[b.authority] - AUTHORITY_RANK[a.authority])
101
+ || (b.shared_tags.length - a.shared_tags.length)
102
+ || (a.id < b.id ? -1 : 1),
103
+ );
104
+ }
105
+
106
+ module.exports = { proposeSupersessions, AUTHORITY_RANK };
package/src/harvest.js CHANGED
@@ -57,6 +57,10 @@ const STRIP_PATTERNS = [
57
57
  /<local-command-stdout>[\s\S]*?<\/local-command-stdout>/g,
58
58
  /<local-command-stderr>[\s\S]*?<\/local-command-stderr>/g,
59
59
  /<user-prompt-submit-hook>[\s\S]*?<\/user-prompt-submit-hook>/g,
60
+ // Brain's own hook injections (hooks/*.mjs) — recalled memories must never be
61
+ // harvested back into new memories.
62
+ /<brain-session-context>[\s\S]*?<\/brain-session-context>/g,
63
+ /<brain-context>[\s\S]*?<\/brain-context>/g,
60
64
  /\[Image #\d+\]/g,
61
65
  /\[Request interrupted[^\]]*\]/g,
62
66
  ];
@@ -257,7 +261,174 @@ function slugToPathGuess(slug) {
257
261
  return '/' + slug.slice(1).replace(/-/g, '/');
258
262
  }
259
263
 
260
- const SOURCES = { [claudeCode.id]: claudeCode };
264
+ /**
265
+ * OpenAI Codex CLI — one JSONL "rollout" per thread under
266
+ * `$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<ts>-<thread>[_<rollout>].jsonl`
267
+ * (verified against openai/codex 0.153, codex-rs/rollout/). Every line is
268
+ * `{timestamp, ordinal?, type, payload}`; the user's prompts are
269
+ * `response_item` messages with `role: "user"`.
270
+ *
271
+ * Codex also injects context *as user-role messages* (AGENTS.md, the
272
+ * environment block, turn-aborted notices, hook output). Since 0.148 genuine
273
+ * prompts carry `internal_chat_message_metadata_passthrough.content_item_kinds`
274
+ * containing `user.*`, which is the reliable discriminator; older rollouts lack
275
+ * it, so the wrapper markers Codex renders are the fallback.
276
+ */
277
+ const CODEX_INJECTED_MARKERS = [
278
+ /^\s*# AGENTS\.md instructions/i,
279
+ /^\s*<user_instructions>/i,
280
+ /^\s*<environment_context>/i,
281
+ /^\s*<turn_aborted>/i,
282
+ /^\s*<user_shell_command>/i,
283
+ /^\s*<subagent_notification>/i,
284
+ /^\s*<codex_internal_context/i,
285
+ /^\s*<goal_context>/i,
286
+ /^\s*<hook_prompt/i,
287
+ /^\s*<brain-/i,
288
+ ];
289
+
290
+ // rollout-YYYY-MM-DDTHH-MM-SS-<thread>[_<rollout>].jsonl → the id token
291
+ const CODEX_ROLLOUT_NAME = /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-(.+)\.jsonl$/;
292
+
293
+ // Threads Codex runs for itself (subagents, guardian reviews, memory
294
+ // consolidation) contain no user speech.
295
+ const CODEX_BACKGROUND_THREADS = new Set(['subagent', 'guardian_review', 'memory_consolidation']);
296
+
297
+ function codexHome() {
298
+ return process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
299
+ }
300
+
301
+ function codexInputText(payload) {
302
+ const content = Array.isArray(payload.content) ? payload.content : [];
303
+ return content
304
+ .filter((block) => block && block.type === 'input_text' && typeof block.text === 'string')
305
+ .map((block) => block.text)
306
+ .join('\n');
307
+ }
308
+
309
+ function codexIsUserAuthored(payload) {
310
+ const meta = payload.internal_chat_message_metadata_passthrough;
311
+ const kinds = meta && Array.isArray(meta.content_item_kinds) ? meta.content_item_kinds : [];
312
+ if (kinds.length > 0) {
313
+ return kinds.some((k) => typeof k === 'string' && (k.startsWith('user.') || k === 'unknown'));
314
+ }
315
+ return !CODEX_INJECTED_MARKERS.some((marker) => marker.test(codexInputText(payload)));
316
+ }
317
+
318
+ function codexIsBackgroundThread(meta) {
319
+ if (meta.parent_thread_id) return true;
320
+ if (typeof meta.thread_source === 'string' && CODEX_BACKGROUND_THREADS.has(meta.thread_source)) return true;
321
+ const source = meta.source;
322
+ return Boolean(source && typeof source === 'object' && ('subagent' in source || 'internal' in source));
323
+ }
324
+
325
+ /**
326
+ * User-assigned thread names from `$CODEX_HOME/session_index.jsonl` (last
327
+ * entry per id wins). Cached per home dir — one read per harvest.
328
+ */
329
+ const codexThreadNames = new Map();
330
+ function codexThreadName(home, threadId) {
331
+ if (!codexThreadNames.has(home)) {
332
+ const names = new Map();
333
+ for (const entry of readJsonl(path.join(home, 'session_index.jsonl'))) {
334
+ if (entry && typeof entry.id === 'string' && typeof entry.thread_name === 'string') {
335
+ names.set(entry.id, entry.thread_name);
336
+ }
337
+ }
338
+ codexThreadNames.set(home, names);
339
+ }
340
+ return codexThreadNames.get(home).get(threadId) || null;
341
+ }
342
+
343
+ const codex = {
344
+ id: 'codex',
345
+ label: 'OpenAI Codex CLI',
346
+ root: () => path.join(codexHome(), 'sessions'),
347
+
348
+ listFiles(root) {
349
+ // Exactly sessions/<year>/<month>/<day>/rollout-*.jsonl. Compressed
350
+ // rollouts (`.jsonl.zst`, an opt-in Codex feature) are skipped.
351
+ const files = [];
352
+ const walk = (dir, depth) => {
353
+ let entries;
354
+ try {
355
+ entries = fs.readdirSync(dir, { withFileTypes: true });
356
+ } catch (_) {
357
+ return;
358
+ }
359
+ for (const entry of entries) {
360
+ const full = path.join(dir, entry.name);
361
+ if (entry.isDirectory() && depth < 3 && /^\d+$/.test(entry.name)) walk(full, depth + 1);
362
+ else if (entry.isFile() && depth === 3 && CODEX_ROLLOUT_NAME.test(entry.name)) files.push(full);
363
+ }
364
+ };
365
+ walk(root, 0);
366
+ return files.sort();
367
+ },
368
+
369
+ /** Session id = the id token in the filename (unique per rollout file). */
370
+ sessionIdFor(file) {
371
+ const match = path.basename(file).match(CODEX_ROLLOUT_NAME);
372
+ return match ? match[1] : path.basename(file, '.jsonl');
373
+ },
374
+
375
+ parse(file) {
376
+ const records = readJsonl(file);
377
+ if (records.length === 0) return null;
378
+
379
+ const sessionId = codex.sessionIdFor(file);
380
+ const session = {
381
+ source: 'codex',
382
+ session_id: sessionId,
383
+ title: null,
384
+ cwd: null,
385
+ git_branch: null,
386
+ started: null,
387
+ ended: null,
388
+ models: new Set(),
389
+ prompts: [],
390
+ files_touched: new Set(),
391
+ turns: 0,
392
+ };
393
+
394
+ for (const record of records) {
395
+ if (!record || typeof record !== 'object') continue;
396
+ const payload = record.payload && typeof record.payload === 'object' ? record.payload : {};
397
+ if (record.timestamp) {
398
+ if (!session.started || record.timestamp < session.started) session.started = record.timestamp;
399
+ if (!session.ended || record.timestamp > session.ended) session.ended = record.timestamp;
400
+ }
401
+
402
+ if (record.type === 'session_meta') {
403
+ if (codexIsBackgroundThread(payload)) return null;
404
+ if (payload.cwd) session.cwd = payload.cwd;
405
+ if (payload.git && payload.git.branch) session.git_branch = payload.git.branch;
406
+ } else if (record.type === 'turn_context') {
407
+ if (payload.model) session.models.add(payload.model);
408
+ if (payload.cwd && !session.cwd) session.cwd = payload.cwd;
409
+ } else if (record.type === 'response_item') {
410
+ if (payload.type === 'message' && payload.role === 'user') {
411
+ if (!codexIsUserAuthored(payload)) continue;
412
+ const text = cleanPromptText(codexInputText(payload));
413
+ if (text) session.prompts.push(text);
414
+ } else if (payload.type === 'message' && payload.role === 'assistant') {
415
+ session.turns++;
416
+ } else if (payload.type === 'custom_tool_call' && payload.name === 'apply_patch' && typeof payload.input === 'string') {
417
+ for (const match of payload.input.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)) {
418
+ session.files_touched.add(match[1].trim());
419
+ }
420
+ }
421
+ }
422
+ }
423
+
424
+ // <home>/sessions/YYYY/MM/DD/<file> → <home>; names are keyed by thread id.
425
+ const home = path.resolve(path.dirname(file), '..', '..', '..', '..');
426
+ session.title = codexThreadName(home, sessionId.split('_')[0]);
427
+ return session;
428
+ },
429
+ };
430
+
431
+ const SOURCES = { [claudeCode.id]: claudeCode, [codex.id]: codex };
261
432
 
262
433
  /** Sources that actually have a history store on this machine. */
263
434
  function availableSources() {
@@ -327,7 +498,8 @@ function markImported(sourceId, sessionIds, projectRoot, knownIds) {
327
498
  if (adapter) {
328
499
  const root = adapter.root();
329
500
  if (fs.existsSync(root)) {
330
- known = new Set(adapter.listFiles(root).map((f) => path.basename(f, '.jsonl')));
501
+ known = new Set(adapter.listFiles(root).map((f) =>
502
+ (adapter.sessionIdFor ? adapter.sessionIdFor(f) : path.basename(f, '.jsonl'))));
331
503
  }
332
504
  }
333
505
  }
@@ -29,6 +29,14 @@ const DEFAULT_CONFIG = {
29
29
  pin_budget_tokens: 1500,
30
30
  skills_index_budget_tokens: 800,
31
31
  recall_budget_tokens: 700,
32
+ // Prompt-time recall (UserPromptSubmit hook): memories injected alongside a
33
+ // user prompt. Small on purpose — it fires on every substantive prompt.
34
+ prompt_recall_top: 3,
35
+ prompt_recall_budget_tokens: 600,
36
+ // Sensitive-topic consent (see src/sensitivity.js). Off by default: writes
37
+ // classified `sensitive` are quarantined and hidden until the user opts in
38
+ // here or approves them one by one with `brain verify approve`.
39
+ sensitive_topics: false,
32
40
  // ASI06 quarantine for low-trust writes: 'off' (never flag), 'flag'
33
41
  // (recallable but marked + surfaced for verification — the default), or
34
42
  // 'enforce' (excluded from recall/session-start until approved). Exclusion