brain-memory 0.1.0-beta.9 → 0.2.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 (82) hide show
  1. package/CHANGELOG.md +632 -0
  2. package/README.md +390 -84
  3. package/SECURITY.md +100 -0
  4. package/assets/brand/README.md +28 -0
  5. package/assets/brand/icon-dark.svg +19 -0
  6. package/assets/brand/icon-light.svg +20 -0
  7. package/assets/brand/linkedin_cover.png +0 -0
  8. package/assets/brand/linkedin_cover_light.png +0 -0
  9. package/assets/brand/mark-dark.svg +19 -0
  10. package/assets/brand/mark-light.svg +20 -0
  11. package/assets/brand/png/icon-dark-1024.png +0 -0
  12. package/assets/brand/png/icon-dark-128.png +0 -0
  13. package/assets/brand/png/icon-dark-256.png +0 -0
  14. package/assets/brand/png/icon-dark-512.png +0 -0
  15. package/assets/brand/png/icon-dark-64.png +0 -0
  16. package/assets/brand/png/icon-light-1024.png +0 -0
  17. package/assets/brand/png/icon-light-128.png +0 -0
  18. package/assets/brand/png/icon-light-256.png +0 -0
  19. package/assets/brand/png/icon-light-512.png +0 -0
  20. package/assets/brand/png/icon-light-64.png +0 -0
  21. package/assets/brand/png/mark-dark-1024.png +0 -0
  22. package/assets/brand/png/mark-light-1024.png +0 -0
  23. package/assets/icon.png +0 -0
  24. package/assets/icon.svg +19 -0
  25. package/bin/audit.js +93 -0
  26. package/bin/brain.js +132 -0
  27. package/bin/cloud-sync.js +150 -0
  28. package/bin/forget.js +172 -0
  29. package/bin/import.js +132 -0
  30. package/bin/install.js +63 -31
  31. package/bin/memorize.js +670 -0
  32. package/bin/pin.js +44 -0
  33. package/bin/recall.js +319 -0
  34. package/bin/reinforce.js +191 -0
  35. package/bin/restore.js +122 -0
  36. package/bin/session-start.js +352 -0
  37. package/bin/skill.js +67 -0
  38. package/bin/unpin.js +38 -0
  39. package/bin/verify.js +186 -0
  40. package/commands/brain/forget.md +243 -13
  41. package/commands/brain/import.md +125 -0
  42. package/commands/brain/memorize.md +108 -130
  43. package/commands/brain/pin.md +79 -0
  44. package/commands/brain/remember.md +59 -100
  45. package/commands/brain/skills.md +60 -0
  46. package/commands/brain/sleep.md +93 -6
  47. package/commands/brain/status.md +15 -6
  48. package/commands/brain/sync.md +181 -17
  49. package/commands/brain/verify.md +63 -0
  50. package/integrations/README.md +29 -0
  51. package/integrations/agentskills/brain-memory/SKILL.md +115 -0
  52. package/integrations/agentskills/brain-memory/scripts/session-start.mjs +34 -0
  53. package/package.json +19 -7
  54. package/prompts/antigravity.md +222 -0
  55. package/prompts/claude.md +128 -40
  56. package/prompts/copilot.md +224 -0
  57. package/prompts/kilo.md +223 -0
  58. package/prompts/openai.md +133 -45
  59. package/prompts/opencode.md +221 -0
  60. package/src/anomaly.js +260 -0
  61. package/src/audit.js +71 -0
  62. package/src/cloud-sync.js +672 -0
  63. package/src/content-lint.js +118 -0
  64. package/src/export-import.js +45 -7
  65. package/src/git-sync.js +170 -11
  66. package/src/harvest.js +562 -0
  67. package/src/index-manager.js +250 -11
  68. package/src/installer.js +250 -29
  69. package/src/pinning.js +146 -0
  70. package/src/provenance.js +79 -0
  71. package/src/quarantine.js +111 -0
  72. package/src/receipt.js +87 -0
  73. package/src/scorer.js +137 -12
  74. package/src/skills.js +208 -0
  75. package/src/temporal.js +228 -0
  76. package/src/tfidf.js +520 -0
  77. package/commands/brain/consolidate.md +0 -153
  78. package/commands/brain/explore.md +0 -79
  79. package/commands/brain/init.md +0 -149
  80. package/commands/brain/review.md +0 -130
  81. package/commands/brain/sunshine.md +0 -337
  82. package/prompts/gemini.md +0 -134
@@ -0,0 +1,670 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain memorize — Store memories from AI agent input
5
+ *
6
+ * Accepts a JSON payload via stdin with memory definitions.
7
+ * Handles all plumbing: ID generation, directory creation, file writing,
8
+ * index updates, association edges, search index, and optional sync.
9
+ *
10
+ * Usage:
11
+ * brain memorize [--sync] <<'EOF'
12
+ * { "memories": [{ "title": "...", "type": "learning", ... }] }
13
+ * EOF
14
+ *
15
+ * The AI agent decides WHAT to remember. This CLI handles HOW to write it.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { execSync, execFileSync } = require('child_process');
21
+ const {
22
+ getBrainDir,
23
+ readIndex,
24
+ writeIndex,
25
+ addMemory,
26
+ generateId,
27
+ readMeta,
28
+ writeMeta,
29
+ readAssociations,
30
+ writeAssociations,
31
+ reinforceEdge,
32
+ readPinned,
33
+ writePinned,
34
+ readConfig,
35
+ atomicWriteSync,
36
+ validateBrainPath,
37
+ } = require('../src/index-manager');
38
+ const { addDocument, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
39
+ const { appendAudit } = require('../src/audit');
40
+ const { lintMemoryContent } = require('../src/content-lint');
41
+ const { quarantineDecision } = require('../src/quarantine');
42
+ const {
43
+ validateValidity,
44
+ supersessionInstant,
45
+ applySupersession,
46
+ } = require('../src/temporal');
47
+
48
+ // Best-effort detection of the host AI agent, recorded on each memory's
49
+ // encoding_context for "where your brain is used" analytics. An explicit
50
+ // BRAIN_AGENT env var always wins (a per-agent install can set it); otherwise we
51
+ // sniff known markers. Unrecognized hosts record "unknown" (the cloud tolerates
52
+ // it). The non-Claude markers are best-effort.
53
+ function detectAgent() {
54
+ const e = process.env;
55
+ if (e.BRAIN_AGENT) return e.BRAIN_AGENT;
56
+ if (e.CLAUDECODE || e.CLAUDE_CODE_ENTRYPOINT) return 'claude-code';
57
+ if (e.GEMINI_CLI || e.GEMINI_CLI_VERSION) return 'gemini-cli';
58
+ if (e.CODEX_HOME || e.CODEX_SANDBOX) return 'codex';
59
+ if (e.OPENCODE || e.OPENCODE_BIN) return 'opencode';
60
+ return 'unknown';
61
+ }
62
+ const HOST_AGENT = detectAgent();
63
+
64
+ // --- Type defaults ---
65
+
66
+ const TYPE_DEFAULTS = {
67
+ decision: { strength: 0.85, decay_rate: 0.995 },
68
+ insight: { strength: 0.90, decay_rate: 0.997 },
69
+ goal: { strength: 0.80, decay_rate: 0.993 },
70
+ experience: { strength: 0.75, decay_rate: 0.985 },
71
+ learning: { strength: 0.70, decay_rate: 0.990 },
72
+ relationship: { strength: 0.70, decay_rate: 0.997 },
73
+ preference: { strength: 0.60, decay_rate: 0.998 },
74
+ observation: { strength: 0.40, decay_rate: 0.950 },
75
+ };
76
+
77
+ const COGNITIVE_ADJUSTMENTS = {
78
+ episodic: { strength_delta: +0.10, decay_multiplier: 0.995 },
79
+ semantic: { strength_delta: 0, decay_multiplier: 1.0 },
80
+ procedural: { strength_delta: -0.10, decay_multiplier: 1.003 },
81
+ };
82
+
83
+ // --- Provenance (OWASP ASI06: memory poisoning) ---
84
+ //
85
+ // Where a memory came from decides how much it is allowed to entrench itself.
86
+ // The policy table lives in src/provenance.js (shared with the recall-side
87
+ // trust weighting in src/scorer.js). The pin/stable restriction is the part
88
+ // that holds regardless of caller honesty: entrenchment is simply not
89
+ // reachable from this path without an explicit user origin.
90
+ const { ORIGIN_POLICY, DEFAULT_ORIGIN } = require('../src/provenance');
91
+
92
+ // --- Args ---
93
+
94
+ function parseArgs(argv) {
95
+ const args = { sync: false };
96
+ for (const arg of argv) {
97
+ if (arg === '--sync') args.sync = true;
98
+ }
99
+ return args;
100
+ }
101
+
102
+ // --- Helpers ---
103
+
104
+ /**
105
+ * Resolve a memory's origin and clamp its trust-bearing fields to what that
106
+ * origin is permitted to claim.
107
+ *
108
+ * Returns `{ origin, policy, mem, clamps }` where `mem` is a sanitized copy and
109
+ * `clamps` lists every explicit over-ask the policy lowered — surfaced in the
110
+ * CLI output so a downgrade is never silent. Returns `{ error }` for requests
111
+ * that have no benign reading.
112
+ */
113
+ function applyOriginPolicy(mem) {
114
+ const origin = mem.origin || DEFAULT_ORIGIN;
115
+ const policy = ORIGIN_POLICY[origin];
116
+ if (!policy) {
117
+ return { error: `Unknown origin "${origin}" (expected one of: ${Object.keys(ORIGIN_POLICY).join(', ')})` };
118
+ }
119
+
120
+ // Entrenchment — loading into every session, or exemption from decay — is a
121
+ // capability, not a magnitude. Tool output and inbound email have no benign
122
+ // reason to request it, so this is refused loudly rather than quietly capped.
123
+ if (!policy.allow_entrench && (mem.pinned || mem.stable)) {
124
+ const asked = [mem.pinned && 'pinned', mem.stable && 'stable'].filter(Boolean).join(' + ');
125
+ return {
126
+ error: `Origin "${origin}" may not set ${asked}. Entrenching a memory requires origin ` +
127
+ `"user" — or pin it deliberately afterwards with \`brain pin <id>\`.`,
128
+ };
129
+ }
130
+
131
+ const clamps = [];
132
+ const clamp = (field, requested, fallback, max) => {
133
+ const value = requested ?? fallback;
134
+ if (value <= max) return value;
135
+ // Only report a downgrade the caller actually asked for. A lowered default
136
+ // is the policy working as designed, not a rejected claim.
137
+ if (requested != null) clamps.push({ field, requested, allowed: max, origin });
138
+ return max;
139
+ };
140
+
141
+ return {
142
+ origin,
143
+ policy,
144
+ clamps,
145
+ mem: {
146
+ ...mem,
147
+ salience: clamp('salience', mem.salience, 0.5, policy.max_salience),
148
+ confidence: clamp('confidence', mem.confidence, 0.7, policy.max_confidence),
149
+ // A non-user origin may lower a memory's base strength but never raise it.
150
+ strength_adjustment: clamp(
151
+ 'strength_adjustment', mem.strength_adjustment, 0,
152
+ policy.allow_entrench ? Infinity : 0
153
+ ),
154
+ },
155
+ };
156
+ }
157
+
158
+ function computeStrengthAndDecay(type, cognitiveType, strengthAdjustment = 0, originDecayMultiplier = 1.0) {
159
+ const typeDefaults = TYPE_DEFAULTS[type] || TYPE_DEFAULTS.observation;
160
+ const cogAdj = COGNITIVE_ADJUSTMENTS[cognitiveType] || COGNITIVE_ADJUSTMENTS.semantic;
161
+
162
+ const strength = Math.max(0, Math.min(1.0,
163
+ typeDefaults.strength + cogAdj.strength_delta + strengthAdjustment
164
+ ));
165
+ // Cap strictly below 1.0. Procedural memories are meant to decay *slowly*, but
166
+ // a multiplier that pushed decay_rate >= 1.0 would make effective strength GROW
167
+ // over time (strength * decay_rate^days) — inverted decay. 0.9999/day is
168
+ // "extremely slow" (a memory loses ~3% of its strength per year) without ever
169
+ // inverting.
170
+ // The origin multiplier rides on top: memory sourced from untrusted content
171
+ // fades faster, so a planted fact loses to a genuine one over time even if
172
+ // nothing ever detects it as an attack.
173
+ const decay_rate = Math.min(
174
+ 0.9999,
175
+ typeDefaults.decay_rate * cogAdj.decay_multiplier * originDecayMultiplier
176
+ );
177
+
178
+ return { strength: Math.round(strength * 100) / 100, decay_rate };
179
+ }
180
+
181
+ function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier, quarantine) {
182
+ const { strength, decay_rate } = computeStrengthAndDecay(
183
+ mem.type, mem.cognitive_type, mem.strength_adjustment, originDecayMultiplier
184
+ );
185
+
186
+ const fmLines = [
187
+ '---',
188
+ `id: ${id}`,
189
+ `type: ${mem.type}`,
190
+ `cognitive_type: ${mem.cognitive_type || 'semantic'}`,
191
+ `created: "${now}"`,
192
+ `last_accessed: "${now}"`,
193
+ `access_count: 0`,
194
+ `recall_history: []`,
195
+ `strength: ${strength}`,
196
+ `decay_rate: ${decay_rate}`,
197
+ `salience: ${mem.salience ?? 0.5}`,
198
+ `confidence: ${mem.confidence ?? 0.7}`,
199
+ ];
200
+ // CoALA Phase 1: pinned (always-loaded) and stable (decay-exempt) are emitted
201
+ // only when set, so ordinary memories keep their existing frontmatter shape.
202
+ if (mem.pinned) {
203
+ fmLines.push('pinned: true');
204
+ fmLines.push(`pin_scope: "${mem.pin_scope || 'global'}"`);
205
+ fmLines.push(`pin_priority: ${mem.pin_priority || 0}`);
206
+ }
207
+ if (mem.stable) fmLines.push('stable: true');
208
+ // ASI06 quarantine: pending-verification state travels with the memory —
209
+ // same conditional-field pattern as pinned/stable, so it syncs and restores
210
+ // with the file and syncs via the index entry.
211
+ if (quarantine && quarantine.quarantined) {
212
+ fmLines.push('quarantined: true');
213
+ fmLines.push(`quarantine_reasons: [${quarantine.reasons.map((r) => `"${r}"`).join(', ')}]`);
214
+ fmLines.push(`quarantine_flagged: "${now}"`);
215
+ }
216
+ // Temporal invalidation: record which memories this one replaces. The
217
+ // reciprocal `superseded_by` is stamped on those targets in main().
218
+ if (mem.supersedes && mem.supersedes.length) {
219
+ fmLines.push(`supersedes: [${mem.supersedes.map((s) => `"${s}"`).join(', ')}]`);
220
+ }
221
+ // Bitemporal valid time — when the fact was true, as opposed to `created`
222
+ // (when it was recorded). Emitted only when the author bounded it.
223
+ if (mem.valid_from) fmLines.push(`valid_from: "${mem.valid_from}"`);
224
+ if (mem.valid_until) fmLines.push(`valid_until: "${mem.valid_until}"`);
225
+ fmLines.push(
226
+ `tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
227
+ `related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
228
+ `origin: "${origin}"`,
229
+ `source: "${mem.source || ''}"`,
230
+ `encoding_context:`,
231
+ ` project: "${(mem.encoding_context && mem.encoding_context.project) || ''}"`,
232
+ ` topics: [${((mem.encoding_context && mem.encoding_context.topics) || []).map(t => `"${t}"`).join(', ')}]`,
233
+ ` task_type: "${(mem.encoding_context && mem.encoding_context.task_type) || ''}"`,
234
+ ` agent: "${HOST_AGENT}"`,
235
+ '---',
236
+ '',
237
+ );
238
+ const frontmatter = fmLines.join('\n');
239
+
240
+ return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
241
+ }
242
+
243
+ function buildIndexEntry(mem, id, strength, decayRate, now, origin, quarantine) {
244
+ const entry = {
245
+ title: mem.title,
246
+ path: mem.path,
247
+ type: mem.type,
248
+ cognitive_type: mem.cognitive_type || 'semantic',
249
+ created: now,
250
+ last_accessed: now,
251
+ access_count: 0,
252
+ strength,
253
+ decay_rate: decayRate,
254
+ // Provenance travels with the index entry so recall can weigh and flag it
255
+ // without having to open every memory file.
256
+ origin,
257
+ salience: mem.salience ?? 0.5,
258
+ confidence: mem.confidence ?? 0.7,
259
+ tags: mem.tags || [],
260
+ related: mem.related || [],
261
+ encoding_context: { ...(mem.encoding_context || {}), agent: HOST_AGENT },
262
+ // CoALA Phase 0: cheap chars/4 token estimate for working-memory budgeting.
263
+ token_estimate: Math.ceil((mem.content || '').length / 4),
264
+ };
265
+ // CoALA Phase 1: only set when present — keeps existing index entries lean.
266
+ if (mem.pinned) {
267
+ entry.pinned = true;
268
+ entry.pin_scope = mem.pin_scope || 'global';
269
+ entry.pin_priority = mem.pin_priority || 0;
270
+ }
271
+ if (mem.stable) entry.stable = true;
272
+ if (quarantine && quarantine.quarantined) {
273
+ entry.quarantined = true;
274
+ entry.quarantine_reasons = quarantine.reasons;
275
+ entry.quarantine_flagged = now;
276
+ }
277
+ if (mem.supersedes && mem.supersedes.length) entry.supersedes = mem.supersedes;
278
+ if (mem.valid_from) entry.valid_from = mem.valid_from;
279
+ if (mem.valid_until) entry.valid_until = mem.valid_until;
280
+ return entry;
281
+ }
282
+
283
+ function updateMetaFiles(brainDir, memPath) {
284
+ const parts = memPath.split('/');
285
+ // Walk up the directory chain, updating _meta.json at each level
286
+ for (let i = 1; i <= parts.length - 1; i++) {
287
+ const dirParts = parts.slice(0, i);
288
+ const categoryPath = dirParts.join('/');
289
+ const fullDir = path.join(brainDir, categoryPath);
290
+
291
+ if (!fs.existsSync(fullDir)) continue;
292
+
293
+ const metaPath = path.join(fullDir, '_meta.json');
294
+ let meta;
295
+ try {
296
+ meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
297
+ } catch {
298
+ meta = { description: categoryPath, memory_count: 0, subcategories: [] };
299
+ }
300
+
301
+ meta.memory_count = (meta.memory_count || 0) + 1;
302
+
303
+ // Add subcategory if this isn't the leaf directory
304
+ if (i < parts.length - 1) {
305
+ const subcat = parts[i];
306
+ if (!meta.subcategories) meta.subcategories = [];
307
+ if (!meta.subcategories.includes(subcat)) {
308
+ meta.subcategories.push(subcat);
309
+ }
310
+ }
311
+
312
+ atomicWriteSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
313
+ }
314
+ }
315
+
316
+ function findTagOverlaps(index, newTags, newId, minOverlap = 2) {
317
+ const overlaps = [];
318
+ if (!newTags || newTags.length < minOverlap) return overlaps;
319
+
320
+ const newTagSet = new Set(newTags);
321
+ for (const [id, entry] of Object.entries(index.memories)) {
322
+ if (id === newId) continue;
323
+ const entryTags = entry.tags || [];
324
+ const shared = entryTags.filter(t => newTagSet.has(t));
325
+ if (shared.length >= minOverlap) {
326
+ overlaps.push(id);
327
+ }
328
+ }
329
+ return overlaps;
330
+ }
331
+
332
+ function trySync() {
333
+ const brainDir = getBrainDir();
334
+
335
+ // Try cloud sync first
336
+ const cloudConfig = path.join(brainDir, '.cloud', 'config.json');
337
+ if (fs.existsSync(cloudConfig)) {
338
+ try {
339
+ execSync('brain cloud push', { stdio: 'pipe', timeout: 30000 });
340
+ return { method: 'cloud', success: true };
341
+ } catch (err) {
342
+ return { method: 'cloud', success: false, error: err.message };
343
+ }
344
+ }
345
+
346
+ // Try git sync
347
+ const gitConfig = path.join(brainDir, '.sync', 'config.json');
348
+ if (fs.existsSync(gitConfig)) {
349
+ try {
350
+ // push() is async; run it in a child so this CLI can stay synchronous.
351
+ // Paths travel as argv — never interpolated into a shell string, where a
352
+ // quote in $BRAIN_DIR would break out of it.
353
+ execFileSync(
354
+ process.execPath,
355
+ [
356
+ '-e',
357
+ "require(process.argv[1]).push(process.argv[2]).then(() => process.exit(0)).catch(() => process.exit(1))",
358
+ path.join(__dirname, '..', 'src', 'git-sync.js'),
359
+ brainDir,
360
+ ],
361
+ { stdio: 'pipe', timeout: 30000 }
362
+ );
363
+ return { method: 'git', success: true };
364
+ } catch (err) {
365
+ return { method: 'git', success: false, error: err.message };
366
+ }
367
+ }
368
+
369
+ return { method: 'none', success: false, error: 'No sync configured (cloud or git)' };
370
+ }
371
+
372
+ // --- Main ---
373
+
374
+ async function main() {
375
+ const args = parseArgs(process.argv.slice(2));
376
+
377
+ // Read JSON from stdin
378
+ let inputData = '';
379
+ if (process.stdin.isTTY) {
380
+ console.error(JSON.stringify({ error: 'No input provided. Pipe JSON via stdin.' }));
381
+ process.exit(1);
382
+ }
383
+
384
+ // Read from fd 0 rather than the '/dev/stdin' path: the path form fails with
385
+ // ENXIO on Linux CI runners and doesn't exist on Windows, whereas fd 0 reads
386
+ // piped stdin portably across Linux, macOS, and Windows.
387
+ inputData = fs.readFileSync(0, 'utf-8');
388
+
389
+ let input;
390
+ try {
391
+ input = JSON.parse(inputData);
392
+ } catch (err) {
393
+ console.error(JSON.stringify({ error: `Invalid JSON input: ${err.message}` }));
394
+ process.exit(1);
395
+ }
396
+
397
+ if (!input.memories || !Array.isArray(input.memories) || input.memories.length === 0) {
398
+ console.error(JSON.stringify({ error: 'Input must have a non-empty "memories" array' }));
399
+ process.exit(1);
400
+ }
401
+
402
+ const brainDir = getBrainDir();
403
+
404
+ // Validate brain exists
405
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
406
+ console.error(JSON.stringify({ error: `Brain not initialized. Run brain install first.` }));
407
+ process.exit(1);
408
+ }
409
+
410
+ // Read current state
411
+ let index;
412
+ try {
413
+ index = readIndex();
414
+ } catch (err) {
415
+ console.error(JSON.stringify({
416
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
417
+ }));
418
+ process.exit(1);
419
+ }
420
+
421
+ let associations;
422
+ try {
423
+ associations = readAssociations() || { version: 1, edges: {} };
424
+ } catch (err) {
425
+ console.error(JSON.stringify({
426
+ error: `Corrupt associations.json in ~/.brain/ — ${err.message}`,
427
+ }));
428
+ process.exit(1);
429
+ }
430
+
431
+ let searchIndex;
432
+ try {
433
+ searchIndex = readSearchIndex(brainDir) || createSearchIndex();
434
+ } catch (err) {
435
+ // Search index is non-critical — rebuild from scratch
436
+ searchIndex = createSearchIndex();
437
+ }
438
+
439
+ const now = new Date().toISOString();
440
+ // Quarantine mode ('off' | 'flag' | 'enforce', default 'flag') — read once;
441
+ // readConfig tolerates a missing/corrupt config.json by falling back to defaults.
442
+ const config = readConfig();
443
+ const results = [];
444
+ const newIds = [];
445
+ const pinnedToAdd = [];
446
+ const clampsReported = [];
447
+ const auditErrors = [];
448
+
449
+ for (const rawMem of input.memories) {
450
+ // Validate required fields
451
+ if (!rawMem.title || !rawMem.type || !rawMem.path || !rawMem.content) {
452
+ console.error(JSON.stringify({
453
+ error: `Memory missing required fields (title, type, path, content): ${JSON.stringify(rawMem.title || 'untitled')}`,
454
+ }));
455
+ process.exit(1);
456
+ }
457
+
458
+ if (!TYPE_DEFAULTS[rawMem.type]) {
459
+ console.error(JSON.stringify({ error: `Unknown memory type: ${rawMem.type}` }));
460
+ process.exit(1);
461
+ }
462
+
463
+ // Bitemporal window, if the author bounded one. Rejected at write time
464
+ // rather than stored: an inverted window makes the memory invisible to
465
+ // every as-of query, which is far harder to notice than a failed write.
466
+ const validity = validateValidity(rawMem);
467
+ if (validity) {
468
+ console.error(JSON.stringify({ error: `${validity.error} — memory: ${JSON.stringify(rawMem.title)}` }));
469
+ process.exit(1);
470
+ }
471
+
472
+ // Provenance gate (ASI06) — decide what this origin is allowed to claim
473
+ // before anything reaches disk.
474
+ const policy = applyOriginPolicy(rawMem);
475
+ if (policy.error) {
476
+ console.error(JSON.stringify({ error: `${policy.error} — memory: ${JSON.stringify(rawMem.title)}` }));
477
+ process.exit(1);
478
+ }
479
+ const { origin } = policy;
480
+ const mem = policy.mem;
481
+ for (const c of policy.clamps) clampsReported.push({ ...c, title: rawMem.title });
482
+
483
+ // ASI06 content lint + quarantine decision. Lint runs for every origin
484
+ // (cheap, and the flags feed forensics even when nothing is quarantined);
485
+ // the decision flags low-trust origins and injection-shaped content.
486
+ const lint = lintMemoryContent(mem);
487
+ const quarantine = quarantineDecision({ origin, lintResult: lint, config });
488
+
489
+ // Generate ID
490
+ const id = generateId();
491
+ newIds.push(id);
492
+
493
+ // Compute strength/decay
494
+ const { fileContent, strength, decay_rate } = buildMemoryFileContent(
495
+ mem, id, now, origin, policy.policy.decay_multiplier, quarantine
496
+ );
497
+
498
+ // Create directories
499
+ const fullPath = path.join(brainDir, mem.path);
500
+ validateBrainPath(fullPath, brainDir);
501
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
502
+
503
+ // Write memory file
504
+ atomicWriteSync(fullPath, fileContent);
505
+
506
+ // Record the write before reporting success. An audit failure is surfaced
507
+ // rather than thrown: the memory is already on disk, and silently dropping
508
+ // the trail would be the worse outcome of the two.
509
+ try {
510
+ appendAudit(brainDir, {
511
+ ts: now,
512
+ event: 'memorize',
513
+ id,
514
+ origin,
515
+ agent: HOST_AGENT,
516
+ type: mem.type,
517
+ path: mem.path,
518
+ title: mem.title,
519
+ salience: mem.salience ?? 0.5,
520
+ confidence: mem.confidence ?? 0.7,
521
+ decay_rate,
522
+ entrenched: Boolean(mem.pinned || mem.stable),
523
+ clamped: policy.clamps.map((c) => c.field),
524
+ ...(lint.flags.length ? { lint: lint.flags.map((f) => f.rule) } : {}),
525
+ ...(quarantine.quarantined ? { quarantined: true, quarantine_reasons: quarantine.reasons } : {}),
526
+ });
527
+ } catch (err) {
528
+ auditErrors.push({ id, error: err.message });
529
+ }
530
+
531
+ // Update index
532
+ const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now, origin, quarantine);
533
+ addMemory(index, id, indexEntry);
534
+
535
+ // CoALA Phase 1: register a born-pinned memory in the pinned manifest
536
+ if (mem.pinned) {
537
+ pinnedToAdd.push({
538
+ id,
539
+ scope: mem.pin_scope || 'global',
540
+ priority: mem.pin_priority || 0,
541
+ token_estimate: indexEntry.token_estimate,
542
+ });
543
+ }
544
+
545
+ // Temporal invalidation: stamp `superseded_by` on each memory this one
546
+ // replaces (index + frontmatter), plus the valid-time boundary the
547
+ // replacement implies. The scorer strongly demotes a superseded memory so
548
+ // the successor wins, without dropping it — "this was true until now"
549
+ // stays answerable. Unknown target ids are skipped silently (they may have
550
+ // been forgotten).
551
+ //
552
+ // ASI06: a quarantined write must NOT demote anything yet. Supersession is
553
+ // a write against *existing, already-trusted* memory — a poisoned external
554
+ // page claiming "the deploy target changed" would otherwise knock the real
555
+ // memory down 4x at recall before any human looked at it, which is the
556
+ // whole harm quarantine exists to prevent. The intent is recorded on the
557
+ // pending memory and applied by `brain verify approve`.
558
+ const targets = mem.supersedes || [];
559
+ const deferSupersede = targets.length > 0 && quarantine.quarantined;
560
+ let supersededNow = [];
561
+
562
+ if (targets.length > 0 && !deferSupersede) {
563
+ supersededNow = applySupersession(brainDir, index, id, targets, {
564
+ validUntil: supersessionInstant({ valid_from: mem.valid_from, created: now }),
565
+ });
566
+ for (const t of supersededNow) reinforceEdge(associations, id, t.id, 'manual', 0.20);
567
+ }
568
+
569
+ // Update associations — explicit related links
570
+ for (const relatedId of (mem.related || [])) {
571
+ if (index.memories[relatedId]) {
572
+ reinforceEdge(associations, id, relatedId, 'manual', 0.20);
573
+ }
574
+ }
575
+
576
+ // Update associations — tag overlaps
577
+ const tagOverlaps = findTagOverlaps(index, mem.tags, id);
578
+ for (const overlapId of tagOverlaps) {
579
+ reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
580
+ }
581
+
582
+ // Tier B §10.2: surface potential contradictions with pinned/stable memories
583
+ // (high tag overlap) so the agent can adjudicate — never auto-resolved here.
584
+ const potentialConflicts = tagOverlaps
585
+ .filter((oid) => {
586
+ const e = index.memories[oid];
587
+ return e && (e.pinned || e.stable);
588
+ })
589
+ .map((oid) => ({ id: oid, title: index.memories[oid].title }));
590
+
591
+ // Update search index
592
+ addDocument(searchIndex, id, {
593
+ title: mem.title,
594
+ tags: mem.tags,
595
+ body: mem.content,
596
+ });
597
+
598
+ // Update _meta.json files
599
+ updateMetaFiles(brainDir, mem.path);
600
+
601
+ const edgesCreated = (mem.related || []).filter(r => index.memories[r]).length + tagOverlaps.length;
602
+
603
+ results.push({
604
+ id,
605
+ title: mem.title,
606
+ path: mem.path,
607
+ type: mem.type,
608
+ cognitive_type: mem.cognitive_type || 'semantic',
609
+ strength,
610
+ decay_rate,
611
+ origin,
612
+ salience: mem.salience ?? 0.5,
613
+ confidence: mem.confidence ?? 0.7,
614
+ tags: mem.tags || [],
615
+ edges_created: edgesCreated,
616
+ ...(potentialConflicts.length ? { potential_conflicts: potentialConflicts } : {}),
617
+ // Surfaced so the agent can tell the user a write went to pending
618
+ // verification (and why) — mirrors provenance_clamps reporting.
619
+ ...(quarantine.quarantined
620
+ ? { quarantine_pending: true, quarantine_reasons: quarantine.reasons }
621
+ : {}),
622
+ ...(lint.flags.length ? { lint_flags: lint.flags.map((f) => f.rule) } : {}),
623
+ ...(supersededNow.length ? { superseded: supersededNow } : {}),
624
+ // Held back until verification — surfaced so the agent can tell the user
625
+ // the replacement it asked for has not taken effect yet.
626
+ ...(deferSupersede ? { supersede_pending: targets } : {}),
627
+ ...(mem.valid_from ? { valid_from: mem.valid_from } : {}),
628
+ ...(mem.valid_until ? { valid_until: mem.valid_until } : {}),
629
+ });
630
+ }
631
+
632
+ // Write all updated state
633
+ writeIndex(index);
634
+ writeAssociations(associations);
635
+ writeSearchIndex(brainDir, searchIndex);
636
+
637
+ // CoALA Phase 1: persist any born-pinned memories to the pinned manifest
638
+ if (pinnedToAdd.length > 0) {
639
+ const pinned = readPinned();
640
+ for (const p of pinnedToAdd) {
641
+ pinned.pins = pinned.pins.filter((x) => x.id !== p.id);
642
+ pinned.pins.push(p);
643
+ }
644
+ writePinned(pinned);
645
+ }
646
+
647
+ // Build output
648
+ const output = {
649
+ stored: results,
650
+ total: results.length,
651
+ index_count: index.memory_count,
652
+ // Only present when the provenance policy actually lowered something, so
653
+ // the agent can tell the user a claim was downgraded and why.
654
+ ...(clampsReported.length ? { provenance_clamps: clampsReported } : {}),
655
+ ...(auditErrors.length ? { audit_errors: auditErrors } : {}),
656
+ };
657
+
658
+ // Sync if requested
659
+ if (args.sync || input.auto_sync) {
660
+ const syncResult = trySync();
661
+ output.sync = syncResult;
662
+ }
663
+
664
+ console.log(JSON.stringify(output, null, 2));
665
+ }
666
+
667
+ main().catch((err) => {
668
+ console.error(JSON.stringify({ error: err.message }));
669
+ process.exit(1);
670
+ });