brain-memory 0.4.0 → 0.5.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/bin/port.js ADDED
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain port — move memories between brain and other memory systems.
5
+ *
6
+ * Usage:
7
+ * brain port export --format <claude-memory|markdown|agentcore> [--out PATH]
8
+ * brain port import --from <claude-memory|markdown|agentcore> <PATH> [--trust] [--dry-run]
9
+ *
10
+ * Export writes only what recall could show: memories pending verification,
11
+ * consent-hidden sensitive memories and expired ones are left out, and counted.
12
+ * `claude-memory` needs --out (a directory); the others print to stdout
13
+ * unless --out names a file.
14
+ *
15
+ * Import sends every memory through `brain memorize`, so the origin policy,
16
+ * lint and quarantine apply. Imported memories are `external` — pending
17
+ * verification until approved — unless --trust marks them as the user's own
18
+ * (`origin: user`), which is right only for an export of the user's own memory.
19
+ * --dry-run prints the memorize payload instead of writing it.
20
+ *
21
+ * Output: JSON. Honors BRAIN_DIR.
22
+ */
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const { execFileSync } = require('child_process');
27
+
28
+ const { getBrainDir, readIndex, readConfig } = require('../src/index-manager');
29
+ const { ADAPTERS, FIDELITY } = require('../src/adapters');
30
+ const { isSensitiveHidden } = require('../src/sensitivity');
31
+ const { temporalState } = require('../src/temporal');
32
+
33
+ function fail(message) {
34
+ console.error(JSON.stringify({ error: message }));
35
+ process.exit(1);
36
+ }
37
+
38
+ function parseArgs(argv) {
39
+ const args = { action: argv[0], format: null, from: null, out: null, path: null, trust: false, dryRun: false };
40
+ for (let i = 1; i < argv.length; i++) {
41
+ switch (argv[i]) {
42
+ case '--format': args.format = argv[++i]; break;
43
+ case '--from': args.from = argv[++i]; break;
44
+ case '--out': args.out = argv[++i]; break;
45
+ case '--trust': args.trust = true; break;
46
+ case '--dry-run': args.dryRun = true; break;
47
+ default: if (!argv[i].startsWith('--')) args.path = argv[i];
48
+ }
49
+ }
50
+ return args;
51
+ }
52
+
53
+ function stripFrontmatter(text) {
54
+ return String(text).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim();
55
+ }
56
+
57
+ /** Memories recall could show, plus counts of what was left out and why. */
58
+ function loadExportable(brainDir) {
59
+ const index = readIndex();
60
+ if (!index) fail('Brain not initialized.');
61
+ const config = readConfig();
62
+ const now = Date.now();
63
+ const memories = [];
64
+ const skipped = { pending_verification: 0, sensitive_hidden: 0, expired: 0, unreadable: 0 };
65
+ for (const [id, entry] of Object.entries(index.memories || {})) {
66
+ if (entry.quarantined) { skipped.pending_verification++; continue; }
67
+ if (isSensitiveHidden(entry, config)) { skipped.sensitive_hidden++; continue; }
68
+ if (temporalState(entry, now) === 'expired') { skipped.expired++; continue; }
69
+ let content;
70
+ try {
71
+ content = stripFrontmatter(fs.readFileSync(path.join(brainDir, entry.path), 'utf-8'));
72
+ } catch (_) {
73
+ skipped.unreadable++;
74
+ continue;
75
+ }
76
+ memories.push({ id, title: entry.title, type: entry.type, content, tags: entry.tags || [], created: entry.created, origin: entry.origin });
77
+ }
78
+ return { memories, skipped };
79
+ }
80
+
81
+ function doExport(args, brainDir) {
82
+ const adapter = ADAPTERS[args.format];
83
+ if (!adapter) fail(`--format must be one of: ${Object.keys(ADAPTERS).join(', ')}`);
84
+ const { memories, skipped } = loadExportable(brainDir);
85
+ const result = adapter.exportTo(memories);
86
+ const summary = { format: args.format, exported: memories.length, skipped, fidelity: FIDELITY[args.format] };
87
+
88
+ if (result.files) {
89
+ if (!args.out) fail('--out <directory> is required for claude-memory');
90
+ fs.mkdirSync(args.out, { recursive: true });
91
+ for (const [rel, text] of Object.entries(result.files)) fs.writeFileSync(path.join(args.out, rel), text);
92
+ console.log(JSON.stringify({ ...summary, out: args.out, files: Object.keys(result.files).length }, null, 2));
93
+ return;
94
+ }
95
+ const body = result.text != null ? result.text : JSON.stringify({ batches: result.batches }, null, 2) + '\n';
96
+ if (result.truncated) summary.truncated = result.truncated;
97
+ if (args.out) {
98
+ fs.writeFileSync(args.out, body);
99
+ console.log(JSON.stringify({ ...summary, out: args.out }, null, 2));
100
+ } else {
101
+ process.stdout.write(body);
102
+ console.error(JSON.stringify(summary));
103
+ }
104
+ }
105
+
106
+ function readInput(adapter, p) {
107
+ if (adapter.input === 'dir') {
108
+ if (!fs.statSync(p).isDirectory()) fail(`${p} is not a directory`);
109
+ const files = {};
110
+ for (const name of fs.readdirSync(p)) {
111
+ const full = path.join(p, name);
112
+ if (name.endsWith('.md') && fs.statSync(full).isFile()) files[name] = fs.readFileSync(full, 'utf-8');
113
+ }
114
+ return files;
115
+ }
116
+ const text = fs.readFileSync(p, 'utf-8');
117
+ return adapter.input === 'json' ? JSON.parse(text) : text;
118
+ }
119
+
120
+ function doImport(args, brainDir) {
121
+ const adapter = ADAPTERS[args.from];
122
+ if (!adapter) fail(`--from must be one of: ${Object.keys(ADAPTERS).join(', ')}`);
123
+ if (!args.path || !fs.existsSync(args.path)) fail('Usage: brain port import --from <format> <path>');
124
+
125
+ const origin = args.trust ? 'user' : 'external';
126
+ const seen = new Set();
127
+ const memories = adapter.importFrom(readInput(adapter, args.path)).map((m) => {
128
+ let base = `imported/${args.from}/${m.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 50) || 'memory'}`;
129
+ let p = `${base}.md`;
130
+ for (let i = 2; seen.has(p); i++) p = `${base}-${i}.md`;
131
+ seen.add(p);
132
+ const { saved, ...mem } = m;
133
+ return {
134
+ ...mem,
135
+ cognitive_type: 'semantic',
136
+ path: p,
137
+ origin,
138
+ source: `brain port import --from ${args.from}${saved ? ` (saved ${saved})` : ''}`,
139
+ encoding_context: { project: '', topics: [], task_type: 'importing' },
140
+ };
141
+ });
142
+
143
+ if (args.dryRun || memories.length === 0) {
144
+ console.log(JSON.stringify({ from: args.from, origin, would_import: memories.length, memories }, null, 2));
145
+ return;
146
+ }
147
+ const out = execFileSync(process.execPath, [path.join(__dirname, 'memorize.js')], {
148
+ input: JSON.stringify({ memories }),
149
+ env: { ...process.env, BRAIN_DIR: brainDir },
150
+ encoding: 'utf-8',
151
+ });
152
+ const stored = (JSON.parse(out).stored || []);
153
+ console.log(JSON.stringify({
154
+ from: args.from,
155
+ origin,
156
+ imported: stored.length,
157
+ pending_verification: stored.filter((s) => s.quarantine_pending).length,
158
+ ids: stored.map((s) => s.id),
159
+ ...(origin === 'external' ? { next: 'review with `brain verify list`, then approve the ones you want' } : {}),
160
+ }, null, 2));
161
+ }
162
+
163
+ function main(argv) {
164
+ const args = parseArgs(argv || process.argv.slice(2));
165
+ const brainDir = getBrainDir();
166
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) fail('Brain not initialized.');
167
+ if (args.action === 'export') return doExport(args, brainDir);
168
+ if (args.action === 'import') return doImport(args, brainDir);
169
+ fail('Usage: brain port export --format <f> [--out P] | brain port import --from <f> <path> [--trust] [--dry-run]');
170
+ }
171
+
172
+ if (require.main === module) main();
173
+
174
+ module.exports = { main, parseArgs, loadExportable };
package/bin/recall.js CHANGED
@@ -45,9 +45,11 @@ const {
45
45
  } = require('../src/scorer');
46
46
 
47
47
  const { receiptFor } = require('../src/receipt');
48
- const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
48
+ const { DEFAULT_ORIGIN, isLowTrust, capLowTrust } = require('../src/provenance');
49
+ const { envSession, recordSurfaced } = require('../src/surfaced');
49
50
  const { parseInstant } = require('../src/temporal');
50
51
  const { isSensitiveHidden } = require('../src/sensitivity');
52
+ const { hidesPending } = require('../src/quarantine');
51
53
 
52
54
  // Minimum relevance (or spreading bonus) for a memory to appear in explicit-
53
55
  // query results. Filters the zero/near-zero-relevance memories that would
@@ -96,6 +98,9 @@ function main() {
96
98
  process.exit(1);
97
99
  }
98
100
 
101
+ // Citation lock: remember what this session was shown (src/surfaced.js).
102
+ recordSurfaced(getBrainDir(), { session: envSession(), source: 'recall', results });
103
+
99
104
  console.log(JSON.stringify(results, null, 2));
100
105
  }
101
106
 
@@ -142,13 +147,13 @@ function computeRecall(args, projectRoot) {
142
147
  // Build memory list from index. In enforce mode, quarantined (pending-
143
148
  // verification) memories are excluded here — before ranking — which also
144
149
  // removes them as spreading-activation sources. readConfig tolerates a
145
- // missing/corrupt config.json (falls back to the 'flag' default).
150
+ // missing/corrupt config.json (falls back to the 'enforce' default).
146
151
  const config = readConfig(projectRoot);
147
- const quarantineMode = config.quarantine_mode || 'flag';
152
+ const hidePending = hidesPending(config);
148
153
  // Sensitive-topic memories are hidden until the user opts in (config) or
149
154
  // approves them individually — consent is evaluated at read time too.
150
155
  const memories = Object.entries(index.memories)
151
- .filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
156
+ .filter(([, entry]) => !hidePending || !entry.quarantined)
152
157
  .filter(([, entry]) => !isSensitiveHidden(entry, config))
153
158
  .map(([id, entry]) => ({
154
159
  id,
@@ -184,9 +189,10 @@ function computeRecall(args, projectRoot) {
184
189
  }
185
190
  );
186
191
 
187
- // Return top N
192
+ // Return top N, holding low-trust occupancy to the configured ceiling.
188
193
  const top = args.top || 10;
189
- return ranked.slice(0, top).map((mem) => {
194
+ const { kept, suppressed } = capLowTrust(ranked, top, config.recall_low_trust_max);
195
+ const results = kept.map((mem) => {
190
196
  const title = mem.title || path.basename(mem.path, '.md');
191
197
  const origin = mem.origin || DEFAULT_ORIGIN;
192
198
  return {
@@ -207,6 +213,7 @@ function computeRecall(args, projectRoot) {
207
213
  // Pending verification (flag mode): recallable but visibly marked, so
208
214
  // the agent can caveat an answer built on an unverified memory.
209
215
  ...(mem.quarantined ? { quarantine_pending: true } : {}),
216
+ ...(mem.authorization ? { authorization_claim: true } : {}),
210
217
  // Temporal invalidation: a newer memory replaced this one. Surfaced so
211
218
  // the agent can say "this was true until <the successor>" rather than
212
219
  // presenting a stale fact as current.
@@ -224,6 +231,9 @@ function computeRecall(args, projectRoot) {
224
231
  receipt: receiptFor({ ...mem, title }),
225
232
  };
226
233
  });
234
+ // Reported on the first result so the suppression is visible, not silent.
235
+ if (suppressed > 0 && results.length > 0) results[0].low_trust_suppressed = suppressed;
236
+ return results;
227
237
  }
228
238
 
229
239
  /**
package/bin/reinforce.js CHANGED
@@ -24,6 +24,7 @@ const fs = require('fs');
24
24
  const path = require('path');
25
25
  const os = require('os');
26
26
 
27
+ const { envSession, recordUsed } = require('../src/surfaced');
27
28
  const {
28
29
  readIndex,
29
30
  writeIndex,
@@ -154,6 +155,10 @@ function main() {
154
155
  writeAssociations(associations);
155
156
  }
156
157
 
158
+ // Injected-vs-used telemetry (src/surfaced.js): reinforce is the agent saying
159
+ // a memory shaped its answer.
160
+ recordUsed(brainDir, { session: envSession(), ids: reinforced.map((r) => r.id).filter(Boolean), now: nowISO });
161
+
157
162
  console.log(JSON.stringify({
158
163
  reinforced,
159
164
  edges_reinforced: edgesReinforced,
@@ -48,8 +48,11 @@ const { rankMemories } = require('../src/scorer');
48
48
  const { advertisedSummaries } = require('../src/skills');
49
49
  const { receiptFor } = require('../src/receipt');
50
50
  const { temporalState } = require('../src/temporal');
51
- const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
51
+ const { DEFAULT_ORIGIN, isLowTrust, capLowTrust } = require('../src/provenance');
52
+ const { envSession, recordSurfaced, usageSummary } = require('../src/surfaced');
52
53
  const { isSensitiveHidden } = require('../src/sensitivity');
54
+ const { quarantineMode: resolveQuarantineMode } = require('../src/quarantine');
55
+ const { authorizationPinnable } = require('../src/pinning');
53
56
 
54
57
  function parseArgs(argv) {
55
58
  const args = { project: null, topics: null, task: null, top: 5, budget: null };
@@ -166,7 +169,7 @@ function computeSessionStart(projectRoot, args = {}) {
166
169
  // the ranked pool entirely (flag mode includes them, marked). The pending
167
170
  // COUNT below always scans the full index, so the agent still learns that
168
171
  // items are waiting even when they are hidden.
169
- const quarantineMode = config.quarantine_mode || 'flag';
172
+ const quarantineMode = resolveQuarantineMode(config);
170
173
  const memories = Object.entries(index.memories)
171
174
  .filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
172
175
  // Consent: sensitive-topic memories stay out of working memory until the
@@ -203,6 +206,9 @@ function computeSessionStart(projectRoot, args = {}) {
203
206
  // from another device could carry both flags — never load it every session.
204
207
  if (entry.quarantined && quarantineMode !== 'off') continue;
205
208
  if (isSensitiveHidden(entry, config)) continue;
209
+ // Same for an unbacked authorization claim: pinMemory refuses it, but a
210
+ // synced index could still carry the pin.
211
+ if (!authorizationPinnable(entry)) continue;
206
212
  // Bitemporal: the pinned tier is presented to the agent as always-apply
207
213
  // active constraints, and a fact whose validity window has closed is not a
208
214
  // constraint any more. Drop it here rather than asserting it every session
@@ -261,7 +267,8 @@ function computeSessionStart(projectRoot, args = {}) {
261
267
  const context_recall = [];
262
268
  let used = 0;
263
269
  let excluded = 0;
264
- for (const mem of ranked.slice(0, top)) {
270
+ const { kept: recallPool, suppressed: lowTrustSuppressed } = capLowTrust(ranked, top, config.recall_low_trust_max);
271
+ for (const mem of recallPool) {
265
272
  if (pinnedIds.has(mem.id)) continue; // already presented in the pinned tier
266
273
  const title = mem.title || path.basename(mem.path || '', '.md');
267
274
  const receipt = receiptFor({ ...mem, title });
@@ -280,6 +287,7 @@ function computeSessionStart(projectRoot, args = {}) {
280
287
  origin,
281
288
  ...(isLowTrust(origin) ? { low_trust: true } : {}),
282
289
  ...(mem.quarantined ? { quarantine_pending: true } : {}),
290
+ ...(mem.authorization ? { authorization_claim: true } : {}),
283
291
  // Bitemporal: surfaced but no longer true — the agent must frame it as
284
292
  // "that was the case until <valid_until>", never as current.
285
293
  ...(mem.temporal_state === 'expired' ? { expired: true, valid_until: mem.valid_until } : {}),
@@ -330,6 +338,11 @@ function computeSessionStart(projectRoot, args = {}) {
330
338
  pending_verification: pendingAll.length,
331
339
  pending_verification_items: pendingAll.slice(0, 5),
332
340
  low_confidence_alerts,
341
+ // Low-trust memories held out of context_recall by recall_low_trust_max.
342
+ ...(lowTrustSuppressed > 0 ? { low_trust_suppressed: lowTrustSuppressed } : {}),
343
+ // How much of what brain surfaced over the last week the agent used
344
+ // (src/surfaced.js) — injected-vs-used telemetry.
345
+ recall_usage_7d: usageSummary(getBrainDir(projectRoot), { sinceMs: Date.now() - 7 * 86400000 }),
333
346
  budget: {
334
347
  cap,
335
348
  pin_cap: pinCap,
@@ -347,10 +360,23 @@ function computeSessionStart(projectRoot, args = {}) {
347
360
  };
348
361
  }
349
362
 
363
+ /**
364
+ * Citation lock: record what a session-start payload put in front of the
365
+ * agent (pinned + context_recall). Shared by the CLI and the plugin hook.
366
+ */
367
+ function recordSessionStart(payload, session, projectRoot) {
368
+ recordSurfaced(getBrainDir(projectRoot), {
369
+ session,
370
+ source: 'session-start',
371
+ results: [...(payload.pinned || []), ...(payload.context_recall || [])],
372
+ });
373
+ }
374
+
350
375
  function main(argv) {
351
376
  const args = parseArgs(argv || process.argv.slice(2));
352
377
  try {
353
378
  const payload = computeSessionStart(undefined, args);
379
+ recordSessionStart(payload, envSession());
354
380
  console.log(JSON.stringify(payload, null, 2));
355
381
  } catch (err) {
356
382
  console.error(JSON.stringify({ error: err.message }));
@@ -362,4 +388,4 @@ if (require.main === module) {
362
388
  main(process.argv.slice(2));
363
389
  }
364
390
 
365
- module.exports = { main, computeSessionStart, estimateTokens, parseArgs, edgeOrder };
391
+ module.exports = { main, computeSessionStart, recordSessionStart, estimateTokens, parseArgs, edgeOrder };
package/bin/verify.js CHANGED
@@ -12,10 +12,13 @@
12
12
  * Clear the flag, mark vetted (audited)
13
13
  * brain verify reject <id> [...] [--force]
14
14
  * Archive via the forget primitive (audited)
15
+ * brain verify requeue <id> [...] Undo an approve: back to pending (audited)
15
16
  *
16
17
  * Approval clears the flag only — origin, write-time clamps, and recall trust
17
18
  * weighting stay. --force on approve vets a non-pending id; on reject it
18
- * overrides the high-salience archival guard.
19
+ * overrides the high-salience archival guard. Requeue exists because approve is
20
+ * the one verb here with no way back — reject is recoverable from _archived/,
21
+ * but a memory approved by mistake could otherwise only be archived.
19
22
  *
20
23
  * Note: _archived/ is excluded from cloud sync, so a reject propagates the
21
24
  * index removal to other devices but may leave an orphaned .md file there —
@@ -28,9 +31,9 @@ const fs = require('fs');
28
31
  const path = require('path');
29
32
 
30
33
  const {
31
- getBrainDir, readIndex, writeIndex, readAssociations, writeAssociations, reinforceEdge,
34
+ getBrainDir, readIndex, writeIndex, readConfig, readAssociations, writeAssociations, reinforceEdge,
32
35
  } = require('../src/index-manager');
33
- const { listPending, approveQuarantine } = require('../src/quarantine');
36
+ const { listPending, approveQuarantine, requeueQuarantine } = require('../src/quarantine');
34
37
  const { applySupersession, supersessionInstant } = require('../src/temporal');
35
38
  const { appendAudit } = require('../src/audit');
36
39
  const { archiveMemory } = require('./forget');
@@ -176,7 +179,42 @@ function main(argv) {
176
179
  return;
177
180
  }
178
181
 
179
- fail(`Unknown subcommand "${sub}". Usage: brain verify <list|show|approve|reject>`);
182
+ if (sub === 'requeue') {
183
+ if (ids.length === 0) fail('Usage: brain verify requeue <id> [<id>...]');
184
+ const index = loadIndex();
185
+ const now = new Date().toISOString();
186
+ const requeued = [];
187
+ const supersessionKept = [];
188
+ const errors = [];
189
+ // readConfig tolerates a missing/corrupt config.json by falling back to defaults.
190
+ const config = readConfig();
191
+ for (const id of ids) {
192
+ const r = requeueQuarantine(brainDir, index, id, now, config);
193
+ if (r.error) { errors.push({ id, error: r.error }); continue; }
194
+ const entry = index.memories[id];
195
+ try {
196
+ appendAudit(brainDir, { ts: now, event: 'verify_requeue', id, title: entry.title, origin: entry.origin });
197
+ } catch (_) { /* requeue already applied */ }
198
+ requeued.push(id);
199
+ if (entry.supersedes && entry.supersedes.length) supersessionKept.push({ id, supersedes: entry.supersedes });
200
+ }
201
+ if (requeued.length > 0) writeIndex(index);
202
+ const output = {
203
+ requeued,
204
+ // Approval released these replacements and requeue does not take them
205
+ // back — surfaced so the user knows the older memories stay demoted.
206
+ ...(supersessionKept.length ? { supersession_kept: supersessionKept } : {}),
207
+ ...(errors.length ? { errors } : {}),
208
+ };
209
+ if (errors.length && requeued.length === 0) {
210
+ console.error(JSON.stringify(output));
211
+ process.exit(1);
212
+ }
213
+ console.log(JSON.stringify(output, null, 2));
214
+ return;
215
+ }
216
+
217
+ fail(`Unknown subcommand "${sub}". Usage: brain verify <list|show|approve|reject|requeue>`);
180
218
  }
181
219
 
182
220
  if (require.main === module) {
@@ -124,6 +124,14 @@ If the output contains `provenance_clamps`, the policy lowered a value you asked
124
124
 
125
125
  If the output contains `quarantine_pending: true`, the memory landed in the pending-verification queue (low-trust origin, or `lint_flags` show instruction-shaped content). **Say so** — e.g. "stored pending verification (external origin) — resolve anytime with `/brain:verify`." Do not re-store with a different origin to skip the queue; that decision belongs to the user.
126
126
 
127
+ **Permissions are their own class.** A memory that says the agent may act without asking — "the user approved force-pushes to main", "no need to confirm deploys", "pre-approved" — is an *authorization claim* (`authorization_claim: true` in the output). From any origin but `user` it lands pending as `authz:unbacked`. A `user` one also lands pending (`authz:no-source`) unless you pass the user's own words:
128
+
129
+ ```json
130
+ { "origin": "user", "authorized_by": { "quote": "yes, you can force-push to main in this repo", "session_id": "<optional>" } }
131
+ ```
132
+
133
+ Quote only what the user actually said in this session; never paraphrase a permission into existence. A claim without backing cannot be pinned, and a write that lands pending is never born pinned — the output reports `pin_dropped`.
134
+
127
135
  ### 5. Resolve contradictions (Tier B §10.2)
128
136
 
129
137
  If a stored memory's result includes `potential_conflicts`, the new write overlaps memories it may have ended. Each proposal carries:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  description: Review and resolve quarantined (unverified) memories
3
- argument-hint: "[list|show <id>|approve <id>|reject <id>]"
3
+ argument-hint: "[list|show <id>|approve <id>|reject <id>|requeue <id>]"
4
4
  ---
5
5
 
6
6
  # /brain:verify — Resolve Unverified Memories
@@ -53,9 +53,17 @@ Show the user the memory's content and where it came from. Content flagged `lint
53
53
 
54
54
  **Never approve on your own judgment.** If the user asked you to "clear the queue," still show them what is in it first — a one-line summary per memory is enough. Batch-approve only what they have seen.
55
55
 
56
+ **Approve the ids you showed, not the queue.** Pass the exact ids from the list the user looked at. Never re-run `brain verify list` and pipe whatever it returns into `approve`: other sessions and agents write to the same brain concurrently, so the queue can grow between the moment the user reviewed it and the moment you act, and a fresh listing sweeps in memories nobody has seen. If the approved count comes back higher than the number you presented, say so and name the extras.
57
+
58
+ - **Requeue** (an approve was a mistake, or swept in something unreviewed):
59
+ ```bash
60
+ brain verify requeue <id> [<id>...]
61
+ ```
62
+ Puts the memory back into pending verification and clears `vetted`. It refuses a pinned memory — unpin first, with the user's say-so. A replacement the approval released is **not** taken back; the CLI reports it under `supersession_kept`, so relay that the older memory stays demoted.
63
+
56
64
  ### 4. Report
57
65
 
58
- Every approve/reject is recorded in the audit trail (`verify_approve` / `verify_reject` events). Summarize what was resolved: N approved, M rejected, queue now empty/K remaining.
66
+ Every approve/reject/requeue is recorded in the audit trail (`verify_approve` / `verify_reject` / `verify_requeue` events). Summarize what was resolved: N approved, M rejected, queue now empty/K remaining.
59
67
 
60
68
  ## Related
61
69
 
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Stop hook (Claude Code + Codex plugin hosts) — the citation lock.
4
+ *
5
+ * Reads the agent's final reply, finds its `◉ memory:` receipt lines, and
6
+ * checks each against what brain surfaced to this session (src/surfaced.js).
7
+ * A receipt for a memory brain never showed is a fabricated citation: it is
8
+ * logged as a `citation_violation` audit event and queued so prompt-recall
9
+ * tells the agent on its next turn.
10
+ *
11
+ * Advisory, never blocking: the hook prints `{}`, so the reply is delivered
12
+ * unchanged. Blocking a Stop would make the agent keep talking, which is a
13
+ * worse failure than a flagged receipt.
14
+ */
15
+
16
+ import fs from "node:fs";
17
+
18
+ import { brainDir, hasBrain, isMain, loadModule, runHook, sessionOf } from "./lib.mjs";
19
+
20
+ // The transcript can be long; only its tail holds the final reply.
21
+ const TAIL_BYTES = 256 * 1024;
22
+
23
+ /** Text of a transcript message's content (string or content blocks). */
24
+ function textOf(content) {
25
+ if (typeof content === "string") return content;
26
+ if (!Array.isArray(content)) return "";
27
+ return content.filter((b) => b && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
28
+ }
29
+
30
+ /** A user turn the human typed, as opposed to a tool result fed back. */
31
+ function isHumanTurn(entry) {
32
+ if (!entry || entry.type !== "user" || !entry.message) return false;
33
+ const content = entry.message.content;
34
+ if (typeof content === "string") return true;
35
+ return Array.isArray(content) && content.some((b) => b && b.type === "text");
36
+ }
37
+
38
+ /**
39
+ * The assistant text since the last human turn, from a JSONL transcript.
40
+ * Returns "" when the file is missing or unreadable.
41
+ */
42
+ export function lastReplyFromTranscript(transcriptPath) {
43
+ let raw;
44
+ try {
45
+ const fd = fs.openSync(transcriptPath, "r");
46
+ try {
47
+ const size = fs.fstatSync(fd).size;
48
+ const start = Math.max(0, size - TAIL_BYTES);
49
+ const buf = Buffer.alloc(size - start);
50
+ fs.readSync(fd, buf, 0, buf.length, start);
51
+ raw = buf.toString("utf8");
52
+ } finally {
53
+ fs.closeSync(fd);
54
+ }
55
+ } catch {
56
+ return "";
57
+ }
58
+ const entries = raw.split("\n").map((line) => {
59
+ try { return JSON.parse(line); } catch { return null; }
60
+ }).filter(Boolean);
61
+ const parts = [];
62
+ for (let i = entries.length - 1; i >= 0; i--) {
63
+ const e = entries[i];
64
+ if (isHumanTurn(e)) break;
65
+ if (e.type === "assistant" && e.message) parts.unshift(textOf(e.message.content));
66
+ }
67
+ return parts.filter(Boolean).join("\n");
68
+ }
69
+
70
+ export async function handleStop(input, options = {}) {
71
+ if (!hasBrain()) return {};
72
+ const record = input && typeof input === "object" ? input : {};
73
+ const text = typeof record.last_assistant_message === "string"
74
+ ? record.last_assistant_message
75
+ : (typeof record.transcript_path === "string" ? lastReplyFromTranscript(record.transcript_path) : "");
76
+ if (!text.includes("◉ memory:")) return {};
77
+
78
+ const session = sessionOf(record);
79
+ const surfaced = options.surfaced || loadModule("src/surfaced.js");
80
+ const { unsurfaced } = surfaced.checkCitations(brainDir(), { session, text });
81
+ if (!unsurfaced.length) return {};
82
+
83
+ surfaced.recordViolation(brainDir(), { session, titles: unsurfaced });
84
+ const { appendAudit } = options.audit || loadModule("src/audit.js");
85
+ appendAudit(brainDir(), {
86
+ ts: new Date().toISOString(),
87
+ event: "citation_violation",
88
+ session,
89
+ titles: unsurfaced,
90
+ });
91
+ return {};
92
+ }
93
+
94
+ if (isMain(import.meta.url)) runHook("Stop", handleStop);
package/hooks/hooks.json CHANGED
@@ -24,6 +24,17 @@
24
24
  ]
25
25
  }
26
26
  ],
27
+ "Stop": [
28
+ {
29
+ "hooks": [
30
+ {
31
+ "type": "command",
32
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/citation-check.mjs\"",
33
+ "timeout": 5
34
+ }
35
+ ]
36
+ }
37
+ ],
27
38
  "SessionEnd": [
28
39
  {
29
40
  "hooks": [
package/hooks/lib.mjs CHANGED
@@ -53,6 +53,12 @@ export function detectHost(env = process.env) {
53
53
  }
54
54
 
55
55
  /** Project label from the event's cwd (basename), falling back to process cwd. */
56
+ /** The host's session id from a hook payload, or null. */
57
+ export function sessionOf(input) {
58
+ const id = input && typeof input === "object" ? input.session_id : null;
59
+ return typeof id === "string" && id ? id : null;
60
+ }
61
+
56
62
  export function projectFromInput(input, fallbackCwd = process.cwd()) {
57
63
  const record = input && typeof input === "object" ? input : {};
58
64
  const cwd = typeof record.cwd === "string" && record.cwd.trim() ? record.cwd : fallbackCwd;
@@ -21,7 +21,7 @@
21
21
  import fs from "node:fs";
22
22
  import path from "node:path";
23
23
 
24
- import { brainDir, contextOutput, estimateTokens, hasBrain, isMain, loadModule, projectFromInput, runHook } from "./lib.mjs";
24
+ import { brainDir, contextOutput, estimateTokens, hasBrain, isMain, loadModule, projectFromInput, runHook, sessionOf } from "./lib.mjs";
25
25
 
26
26
  export const MIN_PROMPT_CHARS = 12;
27
27
  export const MAX_QUERY_CHARS = 2000;
@@ -89,6 +89,19 @@ export function buildContext(entries, { budget }) {
89
89
  return null;
90
90
  }
91
91
 
92
+ /**
93
+ * One line naming receipts from the previous reply that brain never surfaced,
94
+ * shown once per violation (acknowledged as soon as it is rendered).
95
+ */
96
+ export function citationWarning(surfaced, session) {
97
+ const titles = surfaced.pendingViolations(brainDir(), session);
98
+ if (!titles.length) return null;
99
+ surfaced.recordAck(brainDir(), { session });
100
+ return "<brain-citation-check>⚠ Your last reply carried receipts for memories brain did not surface this session: " +
101
+ titles.map((t) => `"${t}"`).join(", ") +
102
+ ". Cite only receipt lines brain returned; if no memory covers the question, say so.</brain-citation-check>";
103
+ }
104
+
92
105
  function readBody(memPath) {
93
106
  try {
94
107
  return fs.readFileSync(path.join(brainDir(), memPath), "utf-8");
@@ -113,11 +126,19 @@ export async function handlePrompt(input, options = {}) {
113
126
  project: projectFromInput(record),
114
127
  top,
115
128
  });
116
- if (!results.length) return {};
129
+
130
+ // Citation lock (src/surfaced.js): record what this prompt surfaced, and
131
+ // tell the agent if its last reply cited memories brain never showed it.
132
+ const session = sessionOf(record);
133
+ const surfaced = options.surfaced || loadModule("src/surfaced.js");
134
+ const warning = citationWarning(surfaced, session);
135
+ if (results.length) surfaced.recordSurfaced(brainDir(), { session, source: "prompt-recall", results });
136
+ if (!results.length) return warning ? contextOutput("UserPromptSubmit", warning) : {};
117
137
 
118
138
  const entries = results.map((r) => ({ ...r, excerpt: excerptOf(readBody(r.path)) }));
119
139
  const context = buildContext(entries, { budget });
120
- return context ? contextOutput("UserPromptSubmit", context) : {};
140
+ const text = [warning, context].filter(Boolean).join("\n");
141
+ return text ? contextOutput("UserPromptSubmit", text) : {};
121
142
  }
122
143
 
123
144
  if (isMain(import.meta.url)) runHook("UserPromptSubmit", handlePrompt);
@@ -12,7 +12,7 @@
12
12
  * already capped by `working_memory_budget_tokens` in ~/.brain/config.json.
13
13
  */
14
14
 
15
- import { contextOutput, detectHost, hasBrain, isMain, loadModule, projectFromInput, runHook } from "./lib.mjs";
15
+ import { contextOutput, detectHost, hasBrain, isMain, loadModule, projectFromInput, runHook, sessionOf } from "./lib.mjs";
16
16
 
17
17
  const COMMANDS = {
18
18
  "claude-code":
@@ -72,9 +72,11 @@ export function buildContext(payload, { project, host }) {
72
72
  export async function handleSessionStart(input, options = {}) {
73
73
  const env = options.env || process.env;
74
74
  if (!hasBrain()) return {};
75
- const { computeSessionStart } = options.sessionStart || loadModule("bin/session-start.js");
75
+ const { computeSessionStart, recordSessionStart } = options.sessionStart || loadModule("bin/session-start.js");
76
76
  const project = projectFromInput(input);
77
77
  const payload = computeSessionStart(undefined, { project, topics: null, task: null, top: 5 });
78
+ // Citation lock: the Stop hook checks this session's receipts against it.
79
+ if (recordSessionStart) recordSessionStart(payload, sessionOf(input));
78
80
  const context = buildContext(payload, { project, host: detectHost(env) });
79
81
  return contextOutput("SessionStart", context);
80
82
  }