brain-memory 0.4.0 → 0.5.1

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/memorize.js CHANGED
@@ -40,7 +40,7 @@ const { appendAudit } = require('../src/audit');
40
40
  const { lintMemoryContent } = require('../src/content-lint');
41
41
  const { contentHash } = require('../src/integrity');
42
42
  const { proposeSupersessions } = require('../src/contradiction');
43
- const { quarantineDecision } = require('../src/quarantine');
43
+ const { quarantineDecision, isAuthorizationClaim } = require('../src/quarantine');
44
44
  const {
45
45
  validateValidity,
46
46
  supersessionInstant,
@@ -216,6 +216,13 @@ function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier, qua
216
216
  fmLines.push(`quarantine_reasons: [${quarantine.reasons.map((r) => `"${r}"`).join(', ')}]`);
217
217
  fmLines.push(`quarantine_flagged: "${now}"`);
218
218
  }
219
+ // Authorization claim (src/content-lint.js): the memory says the agent may
220
+ // act without asking. Marked so recall and pinning can treat it apart, with
221
+ // the user's own words alongside when the caller supplied them.
222
+ if (mem.authorization) {
223
+ fmLines.push('authorization: true');
224
+ if (mem.authorized_by) fmLines.push(`authorized_by: ${JSON.stringify(JSON.stringify(mem.authorized_by))}`);
225
+ }
219
226
  // Temporal invalidation: record which memories this one replaces. The
220
227
  // reciprocal `superseded_by` is stamped on those targets in main().
221
228
  if (mem.supersedes && mem.supersedes.length) {
@@ -245,6 +252,24 @@ function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier, qua
245
252
  return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
246
253
  }
247
254
 
255
+ /**
256
+ * Validate the optional `authorized_by` backing for an authorization claim:
257
+ * `{ quote, session_id? }`, where `quote` is the user's own words granting the
258
+ * permission. Bounded so a memory cannot smuggle a transcript in through it.
259
+ */
260
+ function normalizeAuthorizedBy(value) {
261
+ if (value == null) return null;
262
+ if (typeof value !== 'object' || Array.isArray(value)) {
263
+ return { error: 'authorized_by must be an object: { quote, session_id? }' };
264
+ }
265
+ const quote = typeof value.quote === 'string' ? value.quote.trim() : '';
266
+ if (!quote) return { error: 'authorized_by.quote must be the user\'s own words, non-empty' };
267
+ if (quote.length > 500) return { error: 'authorized_by.quote is longer than 500 characters' };
268
+ const out = { quote };
269
+ if (typeof value.session_id === 'string' && value.session_id.trim()) out.session_id = value.session_id.trim().slice(0, 120);
270
+ return out;
271
+ }
272
+
248
273
  function buildIndexEntry(mem, id, strength, decayRate, now, origin, quarantine) {
249
274
  const entry = {
250
275
  title: mem.title,
@@ -279,6 +304,10 @@ function buildIndexEntry(mem, id, strength, decayRate, now, origin, quarantine)
279
304
  entry.quarantine_reasons = quarantine.reasons;
280
305
  entry.quarantine_flagged = now;
281
306
  }
307
+ if (mem.authorization) {
308
+ entry.authorization = true;
309
+ if (mem.authorized_by) entry.authorized_by = mem.authorized_by;
310
+ }
282
311
  if (mem.supersedes && mem.supersedes.length) entry.supersedes = mem.supersedes;
283
312
  if (mem.valid_from) entry.valid_from = mem.valid_from;
284
313
  if (mem.valid_until) entry.valid_until = mem.valid_until;
@@ -387,10 +416,11 @@ async function main() {
387
416
  process.exit(1);
388
417
  }
389
418
 
390
- // Read from fd 0 rather than the '/dev/stdin' path: the path form fails with
391
- // ENXIO on Linux CI runners and doesn't exist on Windows, whereas fd 0 reads
392
- // piped stdin portably across Linux, macOS, and Windows.
393
- inputData = fs.readFileSync(0, 'utf-8');
419
+ // Read stdin as a stream. The '/dev/stdin' path fails with ENXIO on Linux CI
420
+ // and doesn't exist on Windows; readFileSync(0) throws EAGAIN on macOS when
421
+ // the parent hands over a non-blocking pipe. The stream handles both.
422
+ process.stdin.setEncoding('utf-8');
423
+ for await (const chunk of process.stdin) inputData += chunk;
394
424
 
395
425
  let input;
396
426
  try {
@@ -490,7 +520,14 @@ async function main() {
490
520
  // (cheap, and the flags feed forensics even when nothing is quarantined);
491
521
  // the decision flags low-trust origins and injection-shaped content.
492
522
  const lint = lintMemoryContent(mem);
493
- const quarantine = quarantineDecision({ origin, lintResult: lint, config });
523
+ const authorizedBy = normalizeAuthorizedBy(mem.authorized_by);
524
+ if (authorizedBy && authorizedBy.error) {
525
+ console.error(JSON.stringify({ error: `${authorizedBy.error} — memory: ${JSON.stringify(rawMem.title)}` }));
526
+ process.exit(1);
527
+ }
528
+ const quarantine = quarantineDecision({ origin, lintResult: lint, config, authorizedBy });
529
+ mem.authorization = isAuthorizationClaim(lint);
530
+ mem.authorized_by = mem.authorization ? authorizedBy : undefined;
494
531
 
495
532
  // Sensitive-topic consent (src/sensitivity.js). `blocked` content is
496
533
  // refused outright; `sensitive` content is stored only after the user
@@ -516,6 +553,11 @@ async function main() {
516
553
  quarantine.reasons = [...quarantine.reasons, SENSITIVE_OPT_OUT_REASON];
517
554
  }
518
555
  mem.sensitivity = sensitivity.level;
556
+ // A write that lands pending verification cannot be born pinned: the pin
557
+ // would load an unreviewed memory into every session. Dropped, not
558
+ // refused, so the memory itself is kept — the result says why.
559
+ const pinDropped = Boolean(mem.pinned && quarantine.quarantined);
560
+ if (pinDropped) mem.pinned = false;
519
561
 
520
562
  // Generate ID
521
563
  const id = generateId();
@@ -665,6 +707,8 @@ async function main() {
665
707
  // until the user opts in (config) or approves it (`brain verify approve`).
666
708
  ...(mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity } : {}),
667
709
  ...(sensitivity.action === 'quarantine' ? { sensitive_opt_out: true } : {}),
710
+ ...(mem.authorization ? { authorization_claim: true } : {}),
711
+ ...(pinDropped ? { pin_dropped: 'pending verification — pin it after `brain verify approve`' } : {}),
668
712
  ...(supersededNow.length ? { superseded: supersededNow } : {}),
669
713
  // Held back until verification — surfaced so the agent can tell the user
670
714
  // the replacement it asked for has not taken effect yet.
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