brain-memory 0.1.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +216 -0
  2. package/README.md +34 -5
  3. package/bin/audit.js +18 -1
  4. package/bin/brain +4 -0
  5. package/bin/forget.js +10 -1
  6. package/bin/import.js +1 -1
  7. package/bin/install.js +10 -0
  8. package/bin/memorize.js +99 -21
  9. package/bin/recall.js +64 -13
  10. package/bin/reinforce.js +34 -1
  11. package/bin/session-start.js +32 -4
  12. package/bin/skill.js +8 -2
  13. package/bin/verify.js +35 -3
  14. package/commands/brain/import.md +1 -1
  15. package/commands/brain/memorize.md +45 -4
  16. package/commands/brain/remember.md +10 -1
  17. package/commands/brain/skills.md +29 -0
  18. package/commands/brain/sleep.md +1 -1
  19. package/commands/brain/verify.md +6 -0
  20. package/hooks/hooks.json +39 -0
  21. package/hooks/lib.mjs +117 -0
  22. package/hooks/prompt-recall.mjs +123 -0
  23. package/hooks/session-end.md +54 -0
  24. package/hooks/session-end.mjs +63 -0
  25. package/hooks/session-start.md +58 -0
  26. package/hooks/session-start.mjs +82 -0
  27. package/integrations/agentskills/brain-memory/SKILL.md +5 -0
  28. package/package.json +5 -3
  29. package/prompts/antigravity.md +26 -2
  30. package/prompts/claude.md +26 -2
  31. package/prompts/copilot.md +26 -2
  32. package/prompts/kilo.md +26 -2
  33. package/prompts/openai.md +26 -2
  34. package/prompts/opencode.md +26 -2
  35. package/src/anomaly.js +7 -0
  36. package/src/contradiction.js +106 -0
  37. package/src/harvest.js +174 -2
  38. package/src/index-manager.js +8 -0
  39. package/src/installer.js +126 -3
  40. package/src/integrity.js +155 -0
  41. package/src/receipt.js +14 -4
  42. package/src/scorer.js +75 -7
  43. package/src/sensitivity.js +134 -0
  44. package/src/skill-verify.js +191 -0
  45. package/src/skills.js +63 -0
  46. package/src/temporal.js +228 -0
package/bin/memorize.js CHANGED
@@ -38,8 +38,14 @@ const {
38
38
  const { addDocument, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
39
39
  const { appendAudit } = require('../src/audit');
40
40
  const { lintMemoryContent } = require('../src/content-lint');
41
+ const { contentHash } = require('../src/integrity');
42
+ const { proposeSupersessions } = require('../src/contradiction');
41
43
  const { quarantineDecision } = require('../src/quarantine');
42
- const { setFrontmatterFields } = require('../src/pinning');
44
+ const {
45
+ validateValidity,
46
+ supersessionInstant,
47
+ applySupersession,
48
+ } = require('../src/temporal');
43
49
 
44
50
  // Best-effort detection of the host AI agent, recorded on each memory's
45
51
  // encoding_context for "where your brain is used" analytics. An explicit
@@ -84,6 +90,7 @@ const COGNITIVE_ADJUSTMENTS = {
84
90
  // that holds regardless of caller honesty: entrenchment is simply not
85
91
  // reachable from this path without an explicit user origin.
86
92
  const { ORIGIN_POLICY, DEFAULT_ORIGIN } = require('../src/provenance');
93
+ const { sensitivityDecision, SENSITIVE_OPT_OUT_REASON } = require('../src/sensitivity');
87
94
 
88
95
  // --- Args ---
89
96
 
@@ -214,6 +221,12 @@ function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier, qua
214
221
  if (mem.supersedes && mem.supersedes.length) {
215
222
  fmLines.push(`supersedes: [${mem.supersedes.map((s) => `"${s}"`).join(', ')}]`);
216
223
  }
224
+ // Bitemporal valid time — when the fact was true, as opposed to `created`
225
+ // (when it was recorded). Emitted only when the author bounded it.
226
+ if (mem.valid_from) fmLines.push(`valid_from: "${mem.valid_from}"`);
227
+ if (mem.valid_until) fmLines.push(`valid_until: "${mem.valid_until}"`);
228
+ // Consent tier (src/sensitivity.js) — only non-standard levels are written.
229
+ if (mem.sensitivity && mem.sensitivity !== 'standard') fmLines.push(`sensitivity: "${mem.sensitivity}"`);
217
230
  fmLines.push(
218
231
  `tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
219
232
  `related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
@@ -267,6 +280,9 @@ function buildIndexEntry(mem, id, strength, decayRate, now, origin, quarantine)
267
280
  entry.quarantine_flagged = now;
268
281
  }
269
282
  if (mem.supersedes && mem.supersedes.length) entry.supersedes = mem.supersedes;
283
+ if (mem.valid_from) entry.valid_from = mem.valid_from;
284
+ if (mem.valid_until) entry.valid_until = mem.valid_until;
285
+ if (mem.sensitivity && mem.sensitivity !== 'standard') entry.sensitivity = mem.sensitivity;
270
286
  return entry;
271
287
  }
272
288
 
@@ -450,6 +466,15 @@ async function main() {
450
466
  process.exit(1);
451
467
  }
452
468
 
469
+ // Bitemporal window, if the author bounded one. Rejected at write time
470
+ // rather than stored: an inverted window makes the memory invisible to
471
+ // every as-of query, which is far harder to notice than a failed write.
472
+ const validity = validateValidity(rawMem);
473
+ if (validity) {
474
+ console.error(JSON.stringify({ error: `${validity.error} — memory: ${JSON.stringify(rawMem.title)}` }));
475
+ process.exit(1);
476
+ }
477
+
453
478
  // Provenance gate (ASI06) — decide what this origin is allowed to claim
454
479
  // before anything reaches disk.
455
480
  const policy = applyOriginPolicy(rawMem);
@@ -467,6 +492,31 @@ async function main() {
467
492
  const lint = lintMemoryContent(mem);
468
493
  const quarantine = quarantineDecision({ origin, lintResult: lint, config });
469
494
 
495
+ // Sensitive-topic consent (src/sensitivity.js). `blocked` content is
496
+ // refused outright; `sensitive` content is stored only after the user
497
+ // opted in — otherwise it lands quarantined and hidden, and approving it
498
+ // is the per-item consent. Evaluated after the origin gate so a refusal
499
+ // names the real reason, and before anything reaches disk.
500
+ const sensitivity = sensitivityDecision(mem, config);
501
+ if (sensitivity.error) {
502
+ console.error(JSON.stringify({ error: `${sensitivity.error} — memory: ${JSON.stringify(rawMem.title)}` }));
503
+ process.exit(1);
504
+ }
505
+ if (sensitivity.action === 'refuse') {
506
+ console.error(JSON.stringify({
507
+ error: `Refused: content classified "blocked" (${sensitivity.categories.join(', ') || 'declared by caller'}) — ` +
508
+ `identification numbers, criminal history and immigration status are never stored — memory: ${JSON.stringify(rawMem.title)}`,
509
+ sensitivity: 'blocked',
510
+ categories: sensitivity.categories,
511
+ }));
512
+ process.exit(1);
513
+ }
514
+ if (sensitivity.action === 'quarantine') {
515
+ quarantine.quarantined = true;
516
+ quarantine.reasons = [...quarantine.reasons, SENSITIVE_OPT_OUT_REASON];
517
+ }
518
+ mem.sensitivity = sensitivity.level;
519
+
470
520
  // Generate ID
471
521
  const id = generateId();
472
522
  newIds.push(id);
@@ -504,6 +554,7 @@ async function main() {
504
554
  clamped: policy.clamps.map((c) => c.field),
505
555
  ...(lint.flags.length ? { lint: lint.flags.map((f) => f.rule) } : {}),
506
556
  ...(quarantine.quarantined ? { quarantined: true, quarantine_reasons: quarantine.reasons } : {}),
557
+ ...(mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity, sensitivity_categories: sensitivity.categories } : {}),
507
558
  });
508
559
  } catch (err) {
509
560
  auditErrors.push({ id, error: err.message });
@@ -511,6 +562,12 @@ async function main() {
511
562
 
512
563
  // Update index
513
564
  const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now, origin, quarantine);
565
+ // Integrity baseline (OWASP ASI06, Store phase): record what this memory
566
+ // said the moment the brain agreed with it, hashed from the exact bytes
567
+ // just written. `brain audit` compares against this to catch edits that
568
+ // never came through a write path — the one poisoning route every other
569
+ // defense here is blind to. See src/integrity.js.
570
+ indexEntry.content_hash = contentHash(fileContent);
514
571
  addMemory(index, id, indexEntry);
515
572
 
516
573
  // CoALA Phase 1: register a born-pinned memory in the pinned manifest
@@ -524,18 +581,27 @@ async function main() {
524
581
  }
525
582
 
526
583
  // Temporal invalidation: stamp `superseded_by` on each memory this one
527
- // replaces (index + frontmatter), and link them. The scorer strongly
528
- // demotes a superseded memory so the successor wins, without dropping it —
529
- // "this was true until now" stays answerable. Unknown target ids are
530
- // skipped silently (they may have been forgotten).
531
- const supersededNow = [];
532
- for (const targetId of (mem.supersedes || [])) {
533
- const target = index.memories[targetId];
534
- if (!target) continue;
535
- target.superseded_by = id;
536
- setFrontmatterFields(brainDir, target.path, { superseded_by: id });
537
- reinforceEdge(associations, id, targetId, 'manual', 0.20);
538
- supersededNow.push({ id: targetId, title: target.title });
584
+ // replaces (index + frontmatter), plus the valid-time boundary the
585
+ // replacement implies. The scorer strongly demotes a superseded memory so
586
+ // the successor wins, without dropping it — "this was true until now"
587
+ // stays answerable. Unknown target ids are skipped silently (they may have
588
+ // been forgotten).
589
+ //
590
+ // ASI06: a quarantined write must NOT demote anything yet. Supersession is
591
+ // a write against *existing, already-trusted* memory — a poisoned external
592
+ // page claiming "the deploy target changed" would otherwise knock the real
593
+ // memory down 4x at recall before any human looked at it, which is the
594
+ // whole harm quarantine exists to prevent. The intent is recorded on the
595
+ // pending memory and applied by `brain verify approve`.
596
+ const targets = mem.supersedes || [];
597
+ const deferSupersede = targets.length > 0 && quarantine.quarantined;
598
+ let supersededNow = [];
599
+
600
+ if (targets.length > 0 && !deferSupersede) {
601
+ supersededNow = applySupersession(brainDir, index, id, targets, {
602
+ validUntil: supersessionInstant({ valid_from: mem.valid_from, created: now }),
603
+ });
604
+ for (const t of supersededNow) reinforceEdge(associations, id, t.id, 'manual', 0.20);
539
605
  }
540
606
 
541
607
  // Update associations — explicit related links
@@ -551,14 +617,17 @@ async function main() {
551
617
  reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
552
618
  }
553
619
 
554
- // Tier B §10.2: surface potential contradictions with pinned/stable memories
555
- // (high tag overlap) so the agent can adjudicate — never auto-resolved here.
556
- const potentialConflicts = tagOverlaps
557
- .filter((oid) => {
558
- const e = index.memories[oid];
559
- return e && (e.pinned || e.stable);
560
- })
561
- .map((oid) => ({ id: oid, title: index.memories[oid].title }));
620
+ // Tier B §10.2: surface potential contradictions so the agent can
621
+ // adjudicate — never auto-resolved here. Each proposal carries the
622
+ // `valid_until` a supersede would stamp, so the agent can offer the
623
+ // boundary ("shall I mark the old one as ended on <date>?") instead of
624
+ // leaving two unbounded facts competing in every future recall.
625
+ const potentialConflicts = proposeSupersessions(
626
+ index,
627
+ { ...mem, created: now },
628
+ tagOverlaps,
629
+ { now },
630
+ );
562
631
 
563
632
  // Update search index
564
633
  addDocument(searchIndex, id, {
@@ -592,7 +661,16 @@ async function main() {
592
661
  ? { quarantine_pending: true, quarantine_reasons: quarantine.reasons }
593
662
  : {}),
594
663
  ...(lint.flags.length ? { lint_flags: lint.flags.map((f) => f.rule) } : {}),
664
+ // Consent tier. `sensitive_opt_out` means the memory is stored but hidden
665
+ // until the user opts in (config) or approves it (`brain verify approve`).
666
+ ...(mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity } : {}),
667
+ ...(sensitivity.action === 'quarantine' ? { sensitive_opt_out: true } : {}),
595
668
  ...(supersededNow.length ? { superseded: supersededNow } : {}),
669
+ // Held back until verification — surfaced so the agent can tell the user
670
+ // the replacement it asked for has not taken effect yet.
671
+ ...(deferSupersede ? { supersede_pending: targets } : {}),
672
+ ...(mem.valid_from ? { valid_from: mem.valid_from } : {}),
673
+ ...(mem.valid_until ? { valid_until: mem.valid_until } : {}),
596
674
  });
597
675
  }
598
676
 
package/bin/recall.js CHANGED
@@ -11,6 +11,10 @@
11
11
  * brain recall "database pooling" --project my-app --task implementing --top 5
12
12
  * brain recall --context # Session-start mode: auto-detect context
13
13
  * brain recall --reindex # Rebuild search index from all memories
14
+ * brain recall "deploy target" --as-of 2026-03-01
15
+ * # Valid time: what was TRUE then
16
+ * brain recall "deploy target" --as-known-of 2026-03-01
17
+ * # Record time: what the brain KNEW then
14
18
  *
15
19
  * Output: JSON array of scored results, sorted by score descending.
16
20
  */
@@ -42,6 +46,8 @@ const {
42
46
 
43
47
  const { receiptFor } = require('../src/receipt');
44
48
  const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
49
+ const { parseInstant } = require('../src/temporal');
50
+ const { isSensitiveHidden } = require('../src/sensitivity');
45
51
 
46
52
  // Minimum relevance (or spreading bonus) for a memory to appear in explicit-
47
53
  // query results. Filters the zero/near-zero-relevance memories that would
@@ -65,25 +71,47 @@ function main() {
65
71
  return handleReindex(brainDir);
66
72
  }
67
73
 
74
+ // An unparseable time-travel bound must fail loudly: silently ignoring it
75
+ // would answer a point-in-time question with present-day memories.
76
+ for (const [flag, value] of [['--as-of', args.asOf], ['--as-known-of', args.asKnownOf]]) {
77
+ if (value != null && parseInstant(value) == null) {
78
+ console.error(JSON.stringify({ error: `Invalid ${flag} value: ${JSON.stringify(value)} — expected an ISO date (e.g. 2026-03-01)` }));
79
+ process.exit(1);
80
+ }
81
+ }
82
+
68
83
  // Need a query for search
69
84
  if (!args.query && !args.context) {
70
85
  console.error(JSON.stringify({ error: 'Usage: brain recall "query" or brain recall --context' }));
71
86
  process.exit(1);
72
87
  }
73
88
 
74
- let index;
89
+ let results;
75
90
  try {
76
- index = readIndex();
91
+ results = computeRecall(args);
77
92
  } catch (err) {
78
93
  console.error(JSON.stringify({
79
94
  error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
80
95
  }));
81
96
  process.exit(1);
82
97
  }
83
- if (!index || !index.memories || Object.keys(index.memories).length === 0) {
84
- console.log(JSON.stringify([]));
85
- return;
86
- }
98
+
99
+ console.log(JSON.stringify(results, null, 2));
100
+ }
101
+
102
+ /**
103
+ * Rank memories for a query — the engine behind `brain recall`, callable
104
+ * in-process (plugin hooks, tests) with byte-identical scoring to the CLI.
105
+ * Throws when index.json is corrupt; returns [] for an empty brain.
106
+ *
107
+ * @param {Object} args - { query, project, task, topics, top, context, asOf, asKnownOf }
108
+ * @param {string} [projectRoot] - Filesystem root whose .brain/ to read
109
+ * @returns {Object[]} scored results, best first
110
+ */
111
+ function computeRecall(args, projectRoot) {
112
+ const brainDir = getBrainDir(projectRoot);
113
+ const index = readIndex(projectRoot);
114
+ if (!index || !index.memories || Object.keys(index.memories).length === 0) return [];
87
115
 
88
116
  // Ensure search index exists
89
117
  let searchIndex;
@@ -115,9 +143,13 @@ function main() {
115
143
  // verification) memories are excluded here — before ranking — which also
116
144
  // removes them as spreading-activation sources. readConfig tolerates a
117
145
  // missing/corrupt config.json (falls back to the 'flag' default).
118
- const quarantineMode = readConfig().quarantine_mode || 'flag';
146
+ const config = readConfig(projectRoot);
147
+ const quarantineMode = config.quarantine_mode || 'flag';
148
+ // Sensitive-topic memories are hidden until the user opts in (config) or
149
+ // approves them individually — consent is evaluated at read time too.
119
150
  const memories = Object.entries(index.memories)
120
151
  .filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
152
+ .filter(([, entry]) => !isSensitiveHidden(entry, config))
121
153
  .map(([id, entry]) => ({
122
154
  id,
123
155
  ...entry,
@@ -126,7 +158,7 @@ function main() {
126
158
  // Load associations for spreading activation
127
159
  let associations;
128
160
  try {
129
- associations = readAssociations();
161
+ associations = readAssociations(projectRoot);
130
162
  } catch (_) {
131
163
  associations = null;
132
164
  }
@@ -135,7 +167,7 @@ function main() {
135
167
  const recallContext = {};
136
168
  if (args.project) recallContext.project = args.project;
137
169
  if (args.task) recallContext.task_type = args.task;
138
- if (args.topics) recallContext.topics = args.topics.split(',');
170
+ if (args.topics) recallContext.topics = String(args.topics).split(',');
139
171
 
140
172
  // Rank using scorer.js with TF-IDF as the relevance function
141
173
  const ranked = rankMemories(
@@ -145,12 +177,16 @@ function main() {
145
177
  associations: associations || undefined,
146
178
  recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
147
179
  relevanceFloor: args.context ? undefined : RELEVANCE_FLOOR,
180
+ // Bitemporal travel: --as-of filters on valid time (the fact was true
181
+ // then), --as-known-of on record time (the brain had it by then).
182
+ asOf: args.asOf,
183
+ asKnownOf: args.asKnownOf,
148
184
  }
149
185
  );
150
186
 
151
187
  // Return top N
152
188
  const top = args.top || 10;
153
- const results = ranked.slice(0, top).map((mem) => {
189
+ return ranked.slice(0, top).map((mem) => {
154
190
  const title = mem.title || path.basename(mem.path, '.md');
155
191
  const origin = mem.origin || DEFAULT_ORIGIN;
156
192
  return {
@@ -175,14 +211,19 @@ function main() {
175
211
  // the agent can say "this was true until <the successor>" rather than
176
212
  // presenting a stale fact as current.
177
213
  ...(mem.superseded_by ? { superseded_by: mem.superseded_by } : {}),
214
+ // Bitemporal valid time — when the fact was true, as distinct from
215
+ // `created` (when it was recorded). `expired` means the window has
216
+ // closed: answer with "that was true until <valid_until>", not as fact.
217
+ ...(mem.valid_from ? { valid_from: mem.valid_from } : {}),
218
+ ...(mem.valid_until ? { valid_until: mem.valid_until } : {}),
219
+ ...(mem.temporal_state === 'expired' ? { expired: true } : {}),
220
+ ...(mem.sensitivity && mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity } : {}),
178
221
  tags: mem.tags,
179
222
  // Recall receipt — the engine mints it, agents copy it verbatim when
180
223
  // this memory materially shapes an answer (so it can't be hallucinated).
181
224
  receipt: receiptFor({ ...mem, title }),
182
225
  };
183
226
  });
184
-
185
- console.log(JSON.stringify(results, null, 2));
186
227
  }
187
228
 
188
229
  /**
@@ -245,6 +286,8 @@ function parseArgs(argv) {
245
286
  top: 10,
246
287
  context: false,
247
288
  reindex: false,
289
+ asOf: null,
290
+ asKnownOf: null,
248
291
  };
249
292
 
250
293
  const positional = [];
@@ -269,6 +312,12 @@ function parseArgs(argv) {
269
312
  case '--reindex':
270
313
  args.reindex = true;
271
314
  break;
315
+ case '--as-of':
316
+ args.asOf = argv[++i];
317
+ break;
318
+ case '--as-known-of':
319
+ args.asKnownOf = argv[++i];
320
+ break;
272
321
  default:
273
322
  if (!argv[i].startsWith('--')) {
274
323
  positional.push(argv[i]);
@@ -284,4 +333,6 @@ function parseArgs(argv) {
284
333
  return args;
285
334
  }
286
335
 
287
- main();
336
+ if (require.main === module) main();
337
+
338
+ module.exports = { main, computeRecall, parseArgs, RELEVANCE_FLOOR };
package/bin/reinforce.js CHANGED
@@ -15,6 +15,7 @@
15
15
  * - Spaced reinforcement boost to each memory's strength
16
16
  * - Decay rate improvement (more forgetting-resistant)
17
17
  * - access_count++, last_accessed = now
18
+ * - recall_history entry (timestamp + interval + strength delta), capped
18
19
  * - Hebbian co-retrieval: strengthens association edges between all pairs
19
20
  * - Updates index.json, associations.json, and memory files
20
21
  */
@@ -38,6 +39,10 @@ const {
38
39
  improveDecayRate,
39
40
  } = require('../src/scorer');
40
41
 
42
+ // Recall-history rows kept per memory. Enough to fit an interval curve;
43
+ // small enough that a hot memory's frontmatter stays cheap to parse.
44
+ const RECALL_HISTORY_MAX = 50;
45
+
41
46
  function main() {
42
47
  const args = parseArgs(process.argv.slice(2));
43
48
 
@@ -86,12 +91,35 @@ function main() {
86
91
  entry.last_accessed = nowISO;
87
92
  entry.access_count = accessCount + 1;
88
93
 
94
+ // Recall history: one row per reinforcement, capped.
95
+ //
96
+ // `access_count` says a memory was recalled N times; it cannot say *when*,
97
+ // and the interval is the entire signal. Spaced reinforcement is built on
98
+ // the premise that longer gaps produce larger, more durable boosts — but
99
+ // without the timestamps that premise is unfalsifiable, and the decay
100
+ // constants stay hand-set forever because there is nothing to fit them to.
101
+ // This is the series that makes calibration possible (see
102
+ // benchmark/harness/decay-calibration.js).
103
+ //
104
+ // Bounded at RECALL_HISTORY_MAX: a frequently-recalled memory would
105
+ // otherwise grow an unbounded array inside a file that is read on every
106
+ // recall. Oldest rows drop first; the recent intervals carry the signal.
107
+ const history = Array.isArray(entry.recall_history) ? entry.recall_history : [];
108
+ history.push({
109
+ at: nowISO,
110
+ days_since_last: Math.round(daysSince * 100) / 100,
111
+ strength_before: oldStrength,
112
+ strength_after: entry.strength,
113
+ });
114
+ entry.recall_history = history.slice(-RECALL_HISTORY_MAX);
115
+
89
116
  // Update the memory file's frontmatter on disk
90
117
  updateMemoryFile(brainDir, entry.path, {
91
118
  strength: entry.strength,
92
119
  decay_rate: entry.decay_rate,
93
120
  last_accessed: nowISO,
94
121
  access_count: entry.access_count,
122
+ recall_history: entry.recall_history,
95
123
  });
96
124
 
97
125
  reinforced.push({
@@ -157,7 +185,12 @@ function updateMemoryFile(brainDir, memPath, updates) {
157
185
  // Update each field in the YAML
158
186
  for (const [key, value] of Object.entries(updates)) {
159
187
  const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
160
- const formatted = typeof value === 'string' ? `"${value}"` : String(value);
188
+ // Arrays and objects must be JSON-encoded: `String(value)` renders an
189
+ // array of objects as "[object Object]", which is both lossy and invalid
190
+ // YAML. JSON is a YAML subset, so a flow-style array round-trips cleanly.
191
+ const formatted = typeof value === 'string'
192
+ ? `"${value}"`
193
+ : (value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value));
161
194
  if (regex.test(frontmatter)) {
162
195
  frontmatter = frontmatter.replace(regex, `$1${formatted}`);
163
196
  }
@@ -8,7 +8,11 @@
8
8
  * Brain can never bloat the host's context window.
9
9
  *
10
10
  * Usage:
11
- * brain session-start [--project P] [--topics a,b] [--task T] [--top N]
11
+ * brain session-start [--project P] [--topics a,b] [--task T] [--top N] [--budget TOKENS]
12
+ *
13
+ * --budget lowers the working-memory cap for this call only (never raises it):
14
+ * hosts with a smaller injection window than config.json assumes — Codex caps
15
+ * hook context at ~2,500 tokens — pass the room they actually have.
12
16
  *
13
17
  * Output (JSON):
14
18
  * {
@@ -43,16 +47,19 @@ const {
43
47
  const { rankMemories } = require('../src/scorer');
44
48
  const { advertisedSummaries } = require('../src/skills');
45
49
  const { receiptFor } = require('../src/receipt');
50
+ const { temporalState } = require('../src/temporal');
46
51
  const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
52
+ const { isSensitiveHidden } = require('../src/sensitivity');
47
53
 
48
54
  function parseArgs(argv) {
49
- const args = { project: null, topics: null, task: null, top: 5 };
55
+ const args = { project: null, topics: null, task: null, top: 5, budget: null };
50
56
  for (let i = 0; i < argv.length; i++) {
51
57
  switch (argv[i]) {
52
58
  case '--project': args.project = argv[++i]; break;
53
59
  case '--topics': args.topics = argv[++i]; break;
54
60
  case '--task': args.task = argv[++i]; break;
55
61
  case '--top': args.top = parseInt(argv[++i], 10) || 5; break;
62
+ case '--budget': args.budget = parseInt(argv[++i], 10) || null; break;
56
63
  default: break;
57
64
  }
58
65
  }
@@ -109,14 +116,17 @@ function buildContextQuery(args) {
109
116
  * it is directly unit-testable.
110
117
  *
111
118
  * @param {string} [projectRoot] - Filesystem root whose .brain/ to read
112
- * @param {Object} [args] - { project, topics, task, top }
119
+ * @param {Object} [args] - { project, topics, task, top, budget }
113
120
  * @returns {Object} The session-start payload
114
121
  */
115
122
  function computeSessionStart(projectRoot, args = {}) {
116
123
  const top = args.top || 5;
117
124
  const brainDir = getBrainDir(projectRoot);
118
125
  const config = readConfig(projectRoot);
119
- const cap = config.working_memory_budget_tokens;
126
+ // A caller-supplied budget can only tighten the configured cap.
127
+ const cap = args.budget > 0
128
+ ? Math.min(config.working_memory_budget_tokens, args.budget)
129
+ : config.working_memory_budget_tokens;
120
130
 
121
131
  const empty = {
122
132
  memory_count: 0,
@@ -159,6 +169,9 @@ function computeSessionStart(projectRoot, args = {}) {
159
169
  const quarantineMode = config.quarantine_mode || 'flag';
160
170
  const memories = Object.entries(index.memories)
161
171
  .filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
172
+ // Consent: sensitive-topic memories stay out of working memory until the
173
+ // user opts in or approves them one by one.
174
+ .filter(([, entry]) => !isSensitiveHidden(entry, config))
162
175
  .map(([id, entry]) => ({ id, ...entry }));
163
176
 
164
177
  let associations = null;
@@ -182,11 +195,20 @@ function computeSessionStart(projectRoot, args = {}) {
182
195
  // The index entry is the source of truth (pinned.json is a maintained cache);
183
196
  // scanning the index here avoids manifest/index drift.
184
197
  const pinnedCandidates = [];
198
+ const nowMs = Date.now();
199
+ let expiredPins = 0;
185
200
  for (const [id, entry] of Object.entries(index.memories)) {
186
201
  if (!entry.pinned) continue;
187
202
  // Defensive: pinning a quarantined memory is refused, but state synced
188
203
  // from another device could carry both flags — never load it every session.
189
204
  if (entry.quarantined && quarantineMode !== 'off') continue;
205
+ if (isSensitiveHidden(entry, config)) continue;
206
+ // Bitemporal: the pinned tier is presented to the agent as always-apply
207
+ // active constraints, and a fact whose validity window has closed is not a
208
+ // constraint any more. Drop it here rather than asserting it every session
209
+ // — it stays reachable through ordinary recall, demoted and ⌛-marked, and
210
+ // the count below tells the user to update or unpin it.
211
+ if (temporalState(entry, nowMs) === 'expired') { expiredPins++; continue; }
190
212
  const scope = entry.pin_scope || 'global';
191
213
  if (scope !== 'global') {
192
214
  const scopedProject = scope.startsWith('project:') ? scope.slice('project:'.length) : null;
@@ -258,6 +280,9 @@ function computeSessionStart(projectRoot, args = {}) {
258
280
  origin,
259
281
  ...(isLowTrust(origin) ? { low_trust: true } : {}),
260
282
  ...(mem.quarantined ? { quarantine_pending: true } : {}),
283
+ // Bitemporal: surfaced but no longer true — the agent must frame it as
284
+ // "that was the case until <valid_until>", never as current.
285
+ ...(mem.temporal_state === 'expired' ? { expired: true, valid_until: mem.valid_until } : {}),
261
286
  token_estimate: est,
262
287
  receipt,
263
288
  });
@@ -299,6 +324,9 @@ function computeSessionStart(projectRoot, args = {}) {
299
324
  skills_index,
300
325
  context_recall: edgeOrder(context_recall), // Tier B §10.4: top ranks at the edges
301
326
  due_for_review: dueForReview,
327
+ // Pins whose validity window has closed — held out of the always-apply
328
+ // tier above, and worth telling the user so they can update or unpin.
329
+ expired_pins: expiredPins,
302
330
  pending_verification: pendingAll.length,
303
331
  pending_verification_items: pendingAll.slice(0, 5),
304
332
  low_confidence_alerts,
package/bin/skill.js CHANGED
@@ -8,6 +8,9 @@
8
8
  * brain skill show <name> Full SKILL.md (L1 disclosure)
9
9
  * brain skill use <name> [--failed] Record a use; success strengthens,
10
10
  * --failed weakens (demotion feedback)
11
+ * brain skill verify <name> Check the skill's declared
12
+ * preconditions against the current
13
+ * directory. Read-only, never executes.
11
14
  * brain skill remove <name> Delete a skill
12
15
  * brain skill add Create a skill from JSON on stdin:
13
16
  * { name, description, triggers[], body }
@@ -15,14 +18,14 @@
15
18
 
16
19
  const fs = require('fs');
17
20
  const {
18
- addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill,
21
+ addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill, verifySkillByName,
19
22
  } = require('../src/skills');
20
23
 
21
24
  function emit(obj) { console.log(JSON.stringify(obj, null, 2)); }
22
25
  function fail(obj) { console.error(JSON.stringify(obj)); process.exit(1); }
23
26
  function done(result) { return result && result.error ? fail(result) : emit(result); }
24
27
 
25
- const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|add|remove <name>|export <name> [--target claude|gemini]>';
28
+ const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|verify <name>|add|remove <name>|export <name> [--target claude|gemini]>';
26
29
 
27
30
  function main(argv) {
28
31
  const args = argv || process.argv.slice(2);
@@ -39,6 +42,9 @@ function main(argv) {
39
42
  case 'use':
40
43
  if (!firstName) return fail({ error: USAGE });
41
44
  return done(useSkill(undefined, firstName, { failed: rest.includes('--failed') }));
45
+ case 'verify':
46
+ if (!firstName) return fail({ error: USAGE });
47
+ return done(verifySkillByName(undefined, firstName));
42
48
  case 'remove':
43
49
  if (!firstName) return fail({ error: USAGE });
44
50
  return done(removeSkill(undefined, firstName));
package/bin/verify.js CHANGED
@@ -27,8 +27,11 @@
27
27
  const fs = require('fs');
28
28
  const path = require('path');
29
29
 
30
- const { getBrainDir, readIndex, writeIndex } = require('../src/index-manager');
30
+ const {
31
+ getBrainDir, readIndex, writeIndex, readAssociations, writeAssociations, reinforceEdge,
32
+ } = require('../src/index-manager');
31
33
  const { listPending, approveQuarantine } = require('../src/quarantine');
34
+ const { applySupersession, supersessionInstant } = require('../src/temporal');
32
35
  const { appendAudit } = require('../src/audit');
33
36
  const { archiveMemory } = require('./forget');
34
37
 
@@ -92,6 +95,7 @@ function main(argv) {
92
95
  const index = loadIndex();
93
96
  const now = new Date().toISOString();
94
97
  const approved = [];
98
+ const supersededOnApproval = [];
95
99
  const errors = [];
96
100
  for (const id of ids) {
97
101
  const entry = index.memories[id];
@@ -107,13 +111,41 @@ function main(argv) {
107
111
  entry.vetted = true;
108
112
  entry.vetted_at = now;
109
113
  }
114
+
115
+ // Deferred supersession: memorize withholds the `superseded_by` stamp
116
+ // when a write lands quarantined, so an unverified memory can never
117
+ // demote a trusted one behind the user's back. Approval is the moment
118
+ // that intent takes effect. Re-applying an already-stamped supersession
119
+ // is a no-op, so the --force path is safe too.
120
+ let superseded = [];
121
+ if (entry.supersedes && entry.supersedes.length) {
122
+ superseded = applySupersession(brainDir, index, id, entry.supersedes, {
123
+ validUntil: supersessionInstant(entry),
124
+ });
125
+ if (superseded.length) {
126
+ const assoc = readAssociations() || { version: 1, edges: {} };
127
+ for (const t of superseded) reinforceEdge(assoc, id, t.id, 'manual', 0.20);
128
+ writeAssociations(assoc);
129
+ }
130
+ }
131
+
110
132
  try {
111
- appendAudit(brainDir, { ts: now, event: 'verify_approve', id, title: entry.title, origin: entry.origin, forced: force });
133
+ appendAudit(brainDir, {
134
+ ts: now, event: 'verify_approve', id, title: entry.title, origin: entry.origin, forced: force,
135
+ ...(superseded.length ? { superseded: superseded.map((t) => t.id) } : {}),
136
+ });
112
137
  } catch (_) { /* approval already applied */ }
113
138
  approved.push(id);
139
+ if (superseded.length) supersededOnApproval.push({ id, superseded });
114
140
  }
115
141
  if (approved.length > 0) writeIndex(index);
116
- const output = { approved, ...(errors.length ? { errors } : {}) };
142
+ const output = {
143
+ approved,
144
+ // Replacements the approval released — surfaced so the user sees that
145
+ // approving also demoted something they already trusted.
146
+ ...(supersededOnApproval.length ? { superseded: supersededOnApproval } : {}),
147
+ ...(errors.length ? { errors } : {}),
148
+ };
117
149
  if (errors.length && approved.length === 0) {
118
150
  console.error(JSON.stringify(output));
119
151
  process.exit(1);
@@ -10,7 +10,7 @@ A new brain is empty. But your agents have been keeping transcripts for months
10
10
  **User input:** $ARGUMENTS
11
11
 
12
12
  **Flags** (passed straight through to the CLI):
13
- - `--source <id>` — Which history store to read (default `claude-code`; `--sources` lists what's detected)
13
+ - `--source <id>` — Which history store to read (`claude-code` by default, or `codex` for `~/.codex/sessions/`; `--sources` lists what's detected)
14
14
  - `--project <name>` — Only sessions from one project
15
15
  - `--since <30d|6m|2026-01-01>` — Only sessions since then
16
16
  - `--limit <N>` — Max sessions to consider (default 40)