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,111 @@
1
+ /**
2
+ * Brain Memory — Quarantine (OWASP ASI06: memory poisoning)
3
+ *
4
+ * Pending-verification state for writes the brain shouldn't fully trust yet:
5
+ * low-trust origins (tool-output, external) and lint-flagged content. State
6
+ * lives in the index entry + memory frontmatter — the same conditional-field
7
+ * pattern as pinned/stable — so it syncs and restores with the memory itself
8
+ * (no sidecar file, no cache drift).
9
+ *
10
+ * Naming: the SM-2 spaced-repetition queue owns "review" (review-queue.json,
11
+ * due_for_review). This subsystem is quarantine / verify / pending_verification.
12
+ *
13
+ * Modes (config.json `quarantine_mode`, default 'flag'):
14
+ * off Nothing is flagged; existing flags persist inertly.
15
+ * flag Flagged memories stay recallable, marked (⊘ unverified receipts,
16
+ * quarantine_pending in results, session-start count).
17
+ * enforce Flagged memories are excluded from recall/session-start until
18
+ * approved. Evaluated at read time, so flipping the knob
19
+ * retroactively hides/reveals already-pending items.
20
+ *
21
+ * Approval clears the flag only — origin, write-time clamps, and the recall
22
+ * trust factor all stay. `vetted: true` records that a human/agent looked, and
23
+ * stops `brain audit` from re-proposing the memory.
24
+ */
25
+
26
+ const { isLowTrust } = require('./provenance');
27
+ const { setFrontmatterFields } = require('./pinning');
28
+
29
+ /**
30
+ * Decide whether a write should be quarantined.
31
+ *
32
+ * - tool-output / external origins: always flagged (`origin:<o>`).
33
+ * - agent-inferred: flagged only on injection-severity lint — the default
34
+ * agent write path stays friction-free.
35
+ * - user: never auto-flagged (lint is still recorded in the audit trail).
36
+ *
37
+ * @param {Object} opts - { origin, lintResult, config }
38
+ * @returns {{ quarantined: boolean, reasons: string[] }}
39
+ */
40
+ function quarantineDecision({ origin, lintResult, config }) {
41
+ const mode = (config && config.quarantine_mode) || 'flag';
42
+ if (mode === 'off') return { quarantined: false, reasons: [] };
43
+
44
+ const reasons = [];
45
+ if (isLowTrust(origin)) reasons.push(`origin:${origin}`);
46
+
47
+ const flags = (lintResult && lintResult.flags) || [];
48
+ if (origin !== 'user') {
49
+ for (const f of flags) {
50
+ if (f.severity === 'injection') reasons.push(`lint:${f.rule}`);
51
+ // Suspect findings only add reasons on top of an already-flagged
52
+ // low-trust origin — they explain *why* beyond the origin itself.
53
+ else if (f.severity === 'suspect' && isLowTrust(origin)) reasons.push(`lint:${f.rule}`);
54
+ }
55
+ }
56
+
57
+ return { quarantined: reasons.length > 0, reasons };
58
+ }
59
+
60
+ /** All index entries currently pending verification. */
61
+ function listPending(index) {
62
+ const out = [];
63
+ for (const [id, entry] of Object.entries((index && index.memories) || {})) {
64
+ if (entry.quarantined) out.push({ id, entry });
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /**
70
+ * Flag an existing memory (used by `brain audit --apply`). Sets the fields on
71
+ * the index entry and mirrors them into the memory file's frontmatter.
72
+ * Caller writes the index.
73
+ */
74
+ function applyQuarantine(brainDir, index, id, reasons, now) {
75
+ const entry = index.memories[id];
76
+ if (!entry) return { error: `Memory not found: ${id}` };
77
+ entry.quarantined = true;
78
+ entry.quarantine_reasons = reasons;
79
+ entry.quarantine_flagged = now;
80
+ setFrontmatterFields(brainDir, entry.path, {
81
+ quarantined: true,
82
+ quarantine_reasons: `[${reasons.map((r) => `"${r}"`).join(', ')}]`,
83
+ quarantine_flagged: now,
84
+ }, { raw: ['quarantine_reasons'] });
85
+ return { id, quarantined: true, reasons };
86
+ }
87
+
88
+ /**
89
+ * Approve a pending memory: strip the quarantine fields, set vetted/vetted_at.
90
+ * Caller writes the index.
91
+ */
92
+ function approveQuarantine(brainDir, index, id, now) {
93
+ const entry = index.memories[id];
94
+ if (!entry) return { error: `Memory not found: ${id}` };
95
+ if (!entry.quarantined) return { error: `Memory is not pending verification: ${id}` };
96
+ delete entry.quarantined;
97
+ delete entry.quarantine_reasons;
98
+ delete entry.quarantine_flagged;
99
+ entry.vetted = true;
100
+ entry.vetted_at = now;
101
+ setFrontmatterFields(brainDir, entry.path, {
102
+ quarantined: null,
103
+ quarantine_reasons: null,
104
+ quarantine_flagged: null,
105
+ vetted: true,
106
+ vetted_at: now,
107
+ });
108
+ return { id, vetted: true };
109
+ }
110
+
111
+ module.exports = { quarantineDecision, listPending, applyQuarantine, approveQuarantine };
package/src/receipt.js ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Brain Memory — Recall Receipts
3
+ *
4
+ * Mints the one-line attributable receipt attached to every memory the
5
+ * engine returns (bin/recall.js results, bin/session-start.js context_recall
6
+ * and pinned entries). Agents copy the line VERBATIM at the end of any
7
+ * response a memory materially shaped — because the engine mints it, a
8
+ * receipt can never be hallucinated.
9
+ *
10
+ * Format: ◉ memory: "<title>" (<type>, <age>)
11
+ *
12
+ * Low-trust origins (tool-output, external — see src/provenance.js) carry a
13
+ * trailing warning segment so a poisoned-source memory is visibly marked
14
+ * wherever its receipt appears: ◉ memory: "<title>" (<type>, <age>, ⚠ external)
15
+ * Memories pending verification (quarantined — see src/quarantine.js) carry a
16
+ * further "⊘ unverified" segment, and memories whose validity window has closed
17
+ * (see src/temporal.js) a "⌛ expired" one. User/agent-inferred, vetted, current
18
+ * receipts are byte-identical to the base format.
19
+ *
20
+ * Age is derived from the memory's `created` timestamp (falling back to
21
+ * `last_accessed`; omitted entirely when neither parses):
22
+ * today | yesterday | <N>d ago (2-30 days) | <N>mo ago (31-364 days,
23
+ * nearest month, min 1) | <N>y ago (365+ days, nearest year, min 1)
24
+ *
25
+ * Deterministic: `now` is injectable for tests.
26
+ */
27
+
28
+ const { isLowTrust } = require('./provenance');
29
+ const { temporalState } = require('./temporal');
30
+
31
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
32
+ const DAYS_PER_MONTH = 30.44; // mean Gregorian month
33
+ const DAYS_PER_YEAR = 365.25;
34
+ const MAX_TITLE_CHARS = 80;
35
+
36
+ /**
37
+ * Human age label for a timestamp, relative to `now`.
38
+ *
39
+ * @param {string|Date} timestamp - ISO timestamp (memory `created`)
40
+ * @param {Date} now - Reference time
41
+ * @returns {string|null} Age label, or null when the timestamp is invalid
42
+ */
43
+ function ageLabel(timestamp, now) {
44
+ const then = new Date(timestamp);
45
+ if (Number.isNaN(then.getTime())) return null;
46
+ const days = Math.floor((now.getTime() - then.getTime()) / MS_PER_DAY);
47
+ if (days <= 0) return 'today';
48
+ if (days === 1) return 'yesterday';
49
+ if (days <= 30) return `${days}d ago`;
50
+ if (days <= 364) return `${Math.max(1, Math.round(days / DAYS_PER_MONTH))}mo ago`;
51
+ return `${Math.max(1, Math.round(days / DAYS_PER_YEAR))}y ago`;
52
+ }
53
+
54
+ /**
55
+ * Mint the receipt line for a memory-like object ({title, type, created,
56
+ * last_accessed}). Title is used as-is (truncated at 77 chars + "…" only
57
+ * when longer than 80); `created` falls back to `last_accessed`, and the
58
+ * age segment is omitted when neither parses.
59
+ *
60
+ * @param {Object} memoryLike - Object with title/type/created/last_accessed
61
+ * @param {Function} [nowFn] - Injectable clock for deterministic tests
62
+ * @returns {string} The receipt line
63
+ */
64
+ function receiptFor(memoryLike, nowFn) {
65
+ const mem = memoryLike || {};
66
+ const now = (nowFn || (() => new Date()))();
67
+
68
+ let title = typeof mem.title === 'string' && mem.title ? mem.title : 'memory';
69
+ if (title.length > MAX_TITLE_CHARS) title = title.slice(0, 77) + '…';
70
+
71
+ const type = typeof mem.type === 'string' && mem.type ? mem.type : 'memory';
72
+ const age = ageLabel(mem.created ?? mem.last_accessed ?? NaN, now);
73
+ const trust = isLowTrust(mem.origin) ? `, ⚠ ${mem.origin}` : '';
74
+ // Pending verification (quarantine flag mode): the receipt is the visible
75
+ // channel, so an unverified memory is marked wherever it fires.
76
+ const pending = mem.quarantined ? ', ⊘ unverified' : '';
77
+ // Bitemporal: the fact's validity window has closed. A stale memory can
78
+ // still be the right answer ("that was true until March") — but it must
79
+ // never look current, so the marker rides along with the receipt.
80
+ const expired = temporalState(mem, now.getTime()) === 'expired' ? ', ⌛ expired' : '';
81
+
82
+ return age
83
+ ? `◉ memory: "${title}" (${type}, ${age}${trust}${pending}${expired})`
84
+ : `◉ memory: "${title}" (${type}${trust}${pending}${expired})`;
85
+ }
86
+
87
+ module.exports = { receiptFor, ageLabel };
package/src/scorer.js CHANGED
@@ -7,15 +7,32 @@
7
7
  * by external tools.
8
8
  */
9
9
 
10
+ const { trustFactor } = require('./provenance');
11
+ const {
12
+ EXPIRED_PENALTY,
13
+ parseInstant,
14
+ temporalState,
15
+ validityOf,
16
+ } = require('./temporal');
17
+
18
+ // Temporal invalidation: multiplier applied to a memory that a newer one has
19
+ // explicitly superseded. Low enough that the successor reliably outranks it,
20
+ // high enough that the superseded fact still surfaces when nothing else is
21
+ // relevant (so "this was true until X" remains answerable).
22
+ const SUPERSEDED_PENALTY = 0.25;
23
+
10
24
  /**
11
25
  * Compute the effective (decayed) strength of a memory.
12
26
  *
13
27
  * @param {number} baseStrength - Original strength (0.0-1.0)
14
28
  * @param {number} decayRate - Daily decay factor (e.g., 0.995)
15
29
  * @param {string|Date} lastAccessed - ISO timestamp of last access
30
+ * @param {boolean} [exempt=false] - CoALA Phase 1: pinned/stable memories are
31
+ * decay-exempt — their strength never fades (semantic "stable" property).
16
32
  * @returns {number} Effective strength after decay
17
33
  */
18
- function computeDecayedStrength(baseStrength, decayRate, lastAccessed) {
34
+ function computeDecayedStrength(baseStrength, decayRate, lastAccessed, exempt = false) {
35
+ if (exempt) return baseStrength;
19
36
  const lastDate = new Date(lastAccessed);
20
37
  const now = new Date();
21
38
  const daysElapsed = (now - lastDate) / (1000 * 60 * 60 * 24);
@@ -290,6 +307,8 @@ function improveDecayRate(decayRate) {
290
307
  * @returns {number} Consolidated strength (capped at 1.0)
291
308
  */
292
309
  function computeConsolidatedStrength(sourceStrengths) {
310
+ // No sources to consolidate — Math.max(...[]) is -Infinity, so guard explicitly.
311
+ if (!Array.isArray(sourceStrengths) || sourceStrengths.length === 0) return 0;
293
312
  const maxStrength = Math.max(...sourceStrengths);
294
313
  return Math.min(1.0, maxStrength + 0.15);
295
314
  }
@@ -357,18 +376,60 @@ function computeSpreadingActivationBatch(scoredMemories, associations, maxDepth
357
376
  * @param {Object} [options] - Optional scoring parameters
358
377
  * @param {Object} [options.associations] - Associations graph for spreading activation
359
378
  * @param {Object} [options.recallContext] - Current session context for context matching
379
+ * @param {number} [options.relevanceFloor] - Drop memories whose relevance AND
380
+ * spreading_bonus are both below this floor. Without it, zero-relevance
381
+ * memories pad the results purely on strength/recency/salience — a query
382
+ * about things the brain doesn't know still returns confident-looking hits.
383
+ * Memories rescued by spreading activation survive the floor (associative
384
+ * recall of low-relevance neighbors is a feature, not noise).
360
385
  * @returns {Object[]} Scored and sorted memories (highest first)
361
386
  */
387
+ /**
388
+ * Recall multiplier for a memory's temporal standing (1 = current).
389
+ *
390
+ * Default mode demotes anything a successor replaced or whose validity window
391
+ * has elapsed. In valid-time travel (`asOf`) the question changes: a memory
392
+ * still inside its window *was* current at that instant, so the supersession
393
+ * demotion is lifted — the fact that it was later replaced is exactly what the
394
+ * query is looking past.
395
+ *
396
+ * The one case that keeps its demotion under asOf is a memory superseded
397
+ * before validity windows existed (`superseded_by` with no `valid_until`):
398
+ * nothing records when it stopped being true, so assuming it was still current
399
+ * would be a guess. Legacy data stays conservative.
400
+ *
401
+ * @param {Object} mem - Memory or index entry
402
+ * @param {Object} ctx - { asOf: number|null, evaluatedAt: number }
403
+ * @returns {number} Multiplier in (0, 1]
404
+ */
405
+ function temporalPenaltyFor(mem, { asOf = null, evaluatedAt = Date.now() } = {}) {
406
+ if (asOf != null) {
407
+ const supersededWithoutWindow = mem.superseded_by && validityOf(mem).until == null;
408
+ return supersededWithoutWindow ? SUPERSEDED_PENALTY : 1;
409
+ }
410
+
411
+ let penalty = 1;
412
+ if (mem.superseded_by) penalty = SUPERSEDED_PENALTY;
413
+ if (temporalState(mem, evaluatedAt) === 'expired') penalty = Math.min(penalty, EXPIRED_PENALTY);
414
+ return penalty;
415
+ }
416
+
362
417
  function rankMemories(memories, relevanceFn, options = {}) {
418
+ // Guard every term against NaN (e.g. a missing/invalid last_accessed or
419
+ // strength) — a single NaN score sorts non-deterministically and can outrank
420
+ // valid results.
421
+ const fin = (x) => (Number.isFinite(x) ? x : 0);
422
+
363
423
  // First pass: compute base scores
364
424
  const scored = memories.map((mem) => {
365
- const decayedStrength = computeDecayedStrength(
425
+ const decayedStrength = fin(computeDecayedStrength(
366
426
  mem.strength,
367
427
  mem.decay_rate,
368
- mem.last_accessed
369
- );
370
- const recencyBonus = computeRecencyBonus(mem.last_accessed);
371
- const relevance = relevanceFn(mem);
428
+ mem.last_accessed,
429
+ !!(mem.stable || mem.pinned) // pinned ⇒ implicitly stable (decay-exempt)
430
+ ));
431
+ const recencyBonus = fin(computeRecencyBonus(mem.last_accessed));
432
+ const relevance = fin(relevanceFn(mem));
372
433
 
373
434
  return {
374
435
  ...mem,
@@ -382,9 +443,22 @@ function rankMemories(memories, relevanceFn, options = {}) {
382
443
 
383
444
  // Second pass: spreading activation (batch — single traversal for all memories)
384
445
  if (options.associations) {
385
- const scoredSummary = scored.map((m) => ({
446
+ // With a relevanceFloor set (query mode), only query-relevant memories may
447
+ // act as activation SOURCES — matching the cognitive model (the cue
448
+ // activates matching memories, activation spreads along associations).
449
+ // Without it, a strong-but-irrelevant memory spreads on strength/recency
450
+ // alone and its whole clique rescues itself past the floor below.
451
+ const sources = options.relevanceFloor != null
452
+ ? scored.filter((m) => m.relevance >= options.relevanceFloor)
453
+ : scored;
454
+ // Source strength is damped by origin trust: a clique of co-tagged
455
+ // low-trust memories (planted writes auto-link via tag_overlap edges)
456
+ // must not self-amplify past trusted memories through activation alone.
457
+ const scoredSummary = sources.map((m) => ({
386
458
  id: m.id,
387
- score: 0.55 * m.relevance + 0.30 * m.decayed_strength + 0.15 * m.recency_bonus,
459
+ score:
460
+ (0.55 * m.relevance + 0.30 * m.decayed_strength + 0.15 * m.recency_bonus) *
461
+ trustFactor(m.origin),
388
462
  }));
389
463
 
390
464
  const bonuses = computeSpreadingActivationBatch(
@@ -406,23 +480,69 @@ function rankMemories(memories, relevanceFn, options = {}) {
406
480
  }
407
481
  }
408
482
 
483
+ // Relevance floor: gate BEFORE final scoring so strength/salience can't
484
+ // carry an unrelated memory into the results (uses raw, unrounded terms).
485
+ const floor = options.relevanceFloor;
486
+ const relevanceGated = floor != null
487
+ ? scored.filter((mem) => mem.relevance >= floor || mem.spreading_bonus >= floor)
488
+ : scored;
489
+
490
+ // Bitemporal gates. Both are point-in-time *filters*, not demotions: an
491
+ // as-of query asks what the world looked like at an instant, and a memory
492
+ // outside that instant is not a weaker answer — it is not an answer.
493
+ // asOf (valid time) — the fact was true then
494
+ // asKnownOf (record time) — the brain had recorded it by then
495
+ // Passing both reconstructs what the brain believed, and when.
496
+ const asOf = parseInstant(options.asOf);
497
+ const asKnownOf = parseInstant(options.asKnownOf);
498
+ let gated = relevanceGated;
499
+ if (asOf != null) {
500
+ gated = gated.filter((mem) => temporalState(mem, asOf) === 'current');
501
+ }
502
+ if (asKnownOf != null) {
503
+ gated = gated.filter((mem) => {
504
+ const recorded = parseInstant(mem.created);
505
+ // A memory with no parseable record time can't be proven to post-date
506
+ // the cutoff, so it stays — dropping it would silently lose legacy data.
507
+ return recorded == null || recorded <= asKnownOf;
508
+ });
509
+ }
510
+
511
+ // The instant "current" is judged against: the as-of instant in valid-time
512
+ // travel, otherwise now.
513
+ const evaluatedAt = asOf != null ? asOf : Date.now();
514
+
409
515
  // Final score
410
- return scored
516
+ return gated
411
517
  .map((mem) => {
412
518
  const extras = {};
413
519
  if (mem.spreading_bonus > 0) extras.spreadingBonus = mem.spreading_bonus;
414
520
  if (mem.context_match > 0) extras.contextMatch = mem.context_match;
415
521
  if (mem.salience != null) extras.salience = mem.salience;
416
522
 
417
- const score = computeRecallScore(
523
+ // Origin trust multiplies the composite: trust bounds entrenchment and
524
+ // volume, not relevance — a clearly more relevant low-trust memory can
525
+ // still win, but it can't win on bulk. Missing origin weighs as the
526
+ // memorize default, so legacy memories keep their relative order.
527
+ // Temporal invalidation. Two signals say "no longer current": an explicit
528
+ // successor (`superseded_by`) and an elapsed validity window
529
+ // (`valid_until`). Take the strongest single penalty, never the product —
530
+ // a memory carrying both is one stale fact, not two. Demote, don't drop:
531
+ // the successor wins, but "this was true until X" stays answerable.
532
+ const temporalPenalty = temporalPenaltyFor(mem, { asOf, evaluatedAt });
533
+
534
+ const score = fin(computeRecallScore(
418
535
  mem.relevance,
419
536
  mem.decayed_strength,
420
537
  mem.recency_bonus,
421
538
  extras
422
- );
539
+ )) * trustFactor(mem.origin) * temporalPenalty;
423
540
 
424
541
  return {
425
542
  ...mem,
543
+ // Standing at the instant this ranking was judged against, so callers
544
+ // can flag a stale fact without re-deriving the window.
545
+ temporal_state: temporalState(mem, evaluatedAt),
426
546
  decayed_strength: Math.round(mem.decayed_strength * 1000) / 1000,
427
547
  recency_bonus: Math.round(mem.recency_bonus * 1000) / 1000,
428
548
  relevance: Math.round(mem.relevance * 1000) / 1000,
@@ -431,7 +551,9 @@ function rankMemories(memories, relevanceFn, options = {}) {
431
551
  score: Math.round(score * 1000) / 1000,
432
552
  };
433
553
  })
434
- .sort((a, b) => b.score - a.score);
554
+ // Deterministic order: score desc, then id asc to break ties (scores are
555
+ // rounded to 3dp, which manufactures ties at scale).
556
+ .sort((a, b) => (b.score - a.score) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
435
557
  }
436
558
 
437
559
  module.exports = {
@@ -449,4 +571,7 @@ module.exports = {
449
571
  computeContextMatch,
450
572
  computeSpacedBoost,
451
573
  improveDecayRate,
574
+ // Bitemporal validity (see src/temporal.js)
575
+ temporalPenaltyFor,
576
+ SUPERSEDED_PENALTY,
452
577
  };
package/src/skills.js ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Brain Memory — Procedural Skills (CoALA Phase 2 + Tier B §10.3)
3
+ *
4
+ * Stores "how to do things" as `_skills/<name>/SKILL.md` folders and serves them
5
+ * via three-level progressive disclosure:
6
+ * L0 — session start advertises only name + description (skills-index.json)
7
+ * L1 — on a matching task, the agent reads the full SKILL.md
8
+ * L2 — referenced resources/ load only at execution
9
+ *
10
+ * Procedural memory strengthens with successful use and weakens on failure
11
+ * (Tier B §10.3), so a bad crystallized skill demotes itself out of the index.
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const {
18
+ getBrainDir,
19
+ readSkillsIndex,
20
+ writeSkillsIndex,
21
+ validateBrainPath,
22
+ atomicWriteSync,
23
+ } = require('./index-manager');
24
+ const { setFrontmatterFields } = require('./pinning');
25
+
26
+ const SKILLS_DIR = '_skills';
27
+ const DEFAULT_STRENGTH = 0.6;
28
+ // A skill whose failure rate exceeds this drops below the L0 advertisement cut.
29
+ const DEMOTE_FAIL_RATIO = 0.5;
30
+
31
+ /** Normalize a skill name to a filesystem-safe slug. */
32
+ function slug(name) {
33
+ return String(name || '').toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
34
+ }
35
+
36
+ function skillPath(name) {
37
+ return `${SKILLS_DIR}/${slug(name)}/SKILL.md`;
38
+ }
39
+
40
+ function buildSkillFile(skill) {
41
+ const fm = [
42
+ '---',
43
+ `name: ${slug(skill.name)}`,
44
+ `description: ${JSON.stringify(skill.description || '')}`,
45
+ `triggers: [${(skill.triggers || []).map((t) => JSON.stringify(t)).join(', ')}]`,
46
+ 'cognitive_type: procedural',
47
+ `strength: ${skill.strength ?? DEFAULT_STRENGTH}`,
48
+ `last_used: ${skill.last_used ? JSON.stringify(skill.last_used) : 'null'}`,
49
+ `use_count: ${skill.use_count ?? 0}`,
50
+ `fail_count: ${skill.fail_count ?? 0}`,
51
+ '---',
52
+ '',
53
+ ].join('\n');
54
+ return fm + (skill.body || '') + '\n';
55
+ }
56
+
57
+ /** Is this skill advertised at L0? Demoted skills stay on disk but go quiet. */
58
+ function isAdvertised(s) {
59
+ const uses = s.use_count || 0;
60
+ const fails = s.fail_count || 0;
61
+ return !(uses >= 3 && fails / uses > DEMOTE_FAIL_RATIO);
62
+ }
63
+
64
+ /**
65
+ * Create or replace a skill.
66
+ * @param {string} [projectRoot]
67
+ * @param {Object} skill - { name, description, triggers[], body, strength? }
68
+ */
69
+ function addSkill(projectRoot, skill) {
70
+ const name = slug(skill && skill.name);
71
+ if (!name) return { error: 'Skill name required' };
72
+
73
+ const brainDir = getBrainDir(projectRoot);
74
+ const dir = path.join(brainDir, SKILLS_DIR, name);
75
+ validateBrainPath(dir, brainDir);
76
+ fs.mkdirSync(dir, { recursive: true });
77
+
78
+ const record = {
79
+ name,
80
+ description: skill.description || '',
81
+ triggers: skill.triggers || [],
82
+ strength: skill.strength ?? DEFAULT_STRENGTH,
83
+ use_count: 0,
84
+ fail_count: 0,
85
+ last_used: null,
86
+ };
87
+ atomicWriteSync(path.join(dir, 'SKILL.md'), buildSkillFile({ ...record, body: skill.body }));
88
+
89
+ const idx = readSkillsIndex(projectRoot);
90
+ idx.skills = idx.skills.filter((s) => s.name !== name);
91
+ idx.skills.push({ ...record, path: skillPath(name) });
92
+ writeSkillsIndex(idx, projectRoot);
93
+
94
+ return { name, added: true };
95
+ }
96
+
97
+ /** Full advertised index (every stored skill, advertised or demoted). */
98
+ function listSkills(projectRoot) {
99
+ return readSkillsIndex(projectRoot).skills;
100
+ }
101
+
102
+ /** L0 summaries (name + description) for advertised skills only. */
103
+ function advertisedSummaries(projectRoot) {
104
+ return readSkillsIndex(projectRoot).skills
105
+ .filter(isAdvertised)
106
+ .map((s) => ({ name: s.name, description: s.description, triggers: s.triggers || [] }));
107
+ }
108
+
109
+ /** L1: the full SKILL.md body. */
110
+ function showSkill(projectRoot, name) {
111
+ const full = path.join(getBrainDir(projectRoot), skillPath(name));
112
+ try {
113
+ return { name: slug(name), content: fs.readFileSync(full, 'utf-8') };
114
+ } catch (_) {
115
+ return { error: `Skill not found: ${name}` };
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Record a use. Success strengthens; failure weakens and counts toward demotion.
121
+ * @param {Object} [opts] - { failed: boolean }
122
+ */
123
+ function useSkill(projectRoot, name, opts = {}) {
124
+ const idx = readSkillsIndex(projectRoot);
125
+ const s = idx.skills.find((x) => x.name === slug(name));
126
+ if (!s) return { error: `Skill not found: ${name}` };
127
+
128
+ s.use_count = (s.use_count || 0) + 1;
129
+ if (opts.failed) {
130
+ s.fail_count = (s.fail_count || 0) + 1;
131
+ s.strength = Math.max(0, (s.strength ?? DEFAULT_STRENGTH) - 0.10);
132
+ } else {
133
+ const cur = s.strength ?? DEFAULT_STRENGTH;
134
+ s.strength = Math.min(1.0, cur + 0.05 * (1.0 - cur));
135
+ }
136
+ s.last_used = new Date().toISOString();
137
+ writeSkillsIndex(idx, projectRoot);
138
+
139
+ setFrontmatterFields(getBrainDir(projectRoot), skillPath(name), {
140
+ strength: Math.round(s.strength * 1000) / 1000,
141
+ use_count: s.use_count,
142
+ fail_count: s.fail_count,
143
+ last_used: s.last_used,
144
+ });
145
+
146
+ return {
147
+ name: s.name,
148
+ use_count: s.use_count,
149
+ fail_count: s.fail_count,
150
+ strength: Math.round(s.strength * 1000) / 1000,
151
+ advertised: isAdvertised(s),
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Export a stored skill into the host agent's native skill format so it becomes
157
+ * directly executable (CoALA Phase 4 host bridge). Brain stores/distills; the
158
+ * host executes.
159
+ *
160
+ * @param {string} [projectRoot] - Brain filesystem root
161
+ * @param {string} name - Skill name
162
+ * @param {string} [target='claude'] - 'claude' | 'gemini'
163
+ * @param {string} [destRoot=process.cwd()] - Host project root to write into
164
+ */
165
+ function exportSkill(projectRoot, name, target = 'claude', destRoot = process.cwd()) {
166
+ const src = showSkill(projectRoot, name);
167
+ if (src.error) return src;
168
+
169
+ const dests = {
170
+ claude: path.join(destRoot, '.claude', 'skills', slug(name)),
171
+ gemini: path.join(destRoot, '.gemini', 'skills', slug(name)),
172
+ };
173
+ const dir = dests[target];
174
+ if (!dir) return { error: `Unknown target: ${target} (use claude|gemini)` };
175
+
176
+ fs.mkdirSync(dir, { recursive: true });
177
+ const outPath = path.join(dir, 'SKILL.md');
178
+ fs.writeFileSync(outPath, src.content);
179
+ return { name: slug(name), target, path: outPath };
180
+ }
181
+
182
+ function removeSkill(projectRoot, name) {
183
+ const n = slug(name);
184
+ const dir = path.join(getBrainDir(projectRoot), SKILLS_DIR, n);
185
+ let removedDir = false;
186
+ try { fs.rmSync(dir, { recursive: true, force: true }); removedDir = true; } catch (_) { /* ignore */ }
187
+
188
+ const idx = readSkillsIndex(projectRoot);
189
+ const before = idx.skills.length;
190
+ idx.skills = idx.skills.filter((s) => s.name !== n);
191
+ writeSkillsIndex(idx, projectRoot);
192
+
193
+ return { name: n, removed: removedDir || before !== idx.skills.length };
194
+ }
195
+
196
+ module.exports = {
197
+ slug,
198
+ skillPath,
199
+ isAdvertised,
200
+ addSkill,
201
+ listSkills,
202
+ advertisedSummaries,
203
+ showSkill,
204
+ useSkill,
205
+ removeSkill,
206
+ exportSkill,
207
+ DEMOTE_FAIL_RATIO,
208
+ };