brain-memory 0.1.0-beta.8 → 0.1.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 (81) hide show
  1. package/CHANGELOG.md +555 -0
  2. package/README.md +411 -61
  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 +163 -0
  29. package/bin/import.js +132 -0
  30. package/bin/install.js +63 -31
  31. package/bin/memorize.js +637 -0
  32. package/bin/pin.js +44 -0
  33. package/bin/recall.js +287 -0
  34. package/bin/reinforce.js +191 -0
  35. package/bin/restore.js +122 -0
  36. package/bin/session-start.js +337 -0
  37. package/bin/skill.js +67 -0
  38. package/bin/unpin.js +38 -0
  39. package/bin/verify.js +154 -0
  40. package/commands/brain/forget.md +243 -13
  41. package/commands/brain/import.md +125 -0
  42. package/commands/brain/memorize.md +95 -137
  43. package/commands/brain/pin.md +79 -0
  44. package/commands/brain/remember.md +53 -103
  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 +57 -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 +20 -7
  54. package/prompts/antigravity.md +201 -0
  55. package/prompts/claude.md +107 -40
  56. package/prompts/copilot.md +203 -0
  57. package/prompts/kilo.md +202 -0
  58. package/prompts/openai.md +112 -45
  59. package/prompts/opencode.md +200 -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 +81 -0
  73. package/src/scorer.js +69 -12
  74. package/src/skills.js +208 -0
  75. package/src/tfidf.js +520 -0
  76. package/commands/brain/consolidate.md +0 -153
  77. package/commands/brain/explore.md +0 -79
  78. package/commands/brain/init.md +0 -149
  79. package/commands/brain/review.md +0 -130
  80. package/commands/brain/sunshine.md +0 -337
  81. 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,81 @@
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. User/agent-inferred, vetted receipts are
17
+ * byte-identical to the base format.
18
+ *
19
+ * Age is derived from the memory's `created` timestamp (falling back to
20
+ * `last_accessed`; omitted entirely when neither parses):
21
+ * today | yesterday | <N>d ago (2-30 days) | <N>mo ago (31-364 days,
22
+ * nearest month, min 1) | <N>y ago (365+ days, nearest year, min 1)
23
+ *
24
+ * Deterministic: `now` is injectable for tests.
25
+ */
26
+
27
+ const { isLowTrust } = require('./provenance');
28
+
29
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
30
+ const DAYS_PER_MONTH = 30.44; // mean Gregorian month
31
+ const DAYS_PER_YEAR = 365.25;
32
+ const MAX_TITLE_CHARS = 80;
33
+
34
+ /**
35
+ * Human age label for a timestamp, relative to `now`.
36
+ *
37
+ * @param {string|Date} timestamp - ISO timestamp (memory `created`)
38
+ * @param {Date} now - Reference time
39
+ * @returns {string|null} Age label, or null when the timestamp is invalid
40
+ */
41
+ function ageLabel(timestamp, now) {
42
+ const then = new Date(timestamp);
43
+ if (Number.isNaN(then.getTime())) return null;
44
+ const days = Math.floor((now.getTime() - then.getTime()) / MS_PER_DAY);
45
+ if (days <= 0) return 'today';
46
+ if (days === 1) return 'yesterday';
47
+ if (days <= 30) return `${days}d ago`;
48
+ if (days <= 364) return `${Math.max(1, Math.round(days / DAYS_PER_MONTH))}mo ago`;
49
+ return `${Math.max(1, Math.round(days / DAYS_PER_YEAR))}y ago`;
50
+ }
51
+
52
+ /**
53
+ * Mint the receipt line for a memory-like object ({title, type, created,
54
+ * last_accessed}). Title is used as-is (truncated at 77 chars + "…" only
55
+ * when longer than 80); `created` falls back to `last_accessed`, and the
56
+ * age segment is omitted when neither parses.
57
+ *
58
+ * @param {Object} memoryLike - Object with title/type/created/last_accessed
59
+ * @param {Function} [nowFn] - Injectable clock for deterministic tests
60
+ * @returns {string} The receipt line
61
+ */
62
+ function receiptFor(memoryLike, nowFn) {
63
+ const mem = memoryLike || {};
64
+ const now = (nowFn || (() => new Date()))();
65
+
66
+ let title = typeof mem.title === 'string' && mem.title ? mem.title : 'memory';
67
+ if (title.length > MAX_TITLE_CHARS) title = title.slice(0, 77) + '…';
68
+
69
+ const type = typeof mem.type === 'string' && mem.type ? mem.type : 'memory';
70
+ const age = ageLabel(mem.created ?? mem.last_accessed ?? NaN, now);
71
+ const trust = isLowTrust(mem.origin) ? `, ⚠ ${mem.origin}` : '';
72
+ // Pending verification (quarantine flag mode): the receipt is the visible
73
+ // channel, so an unverified memory is marked wherever it fires.
74
+ const pending = mem.quarantined ? ', ⊘ unverified' : '';
75
+
76
+ return age
77
+ ? `◉ memory: "${title}" (${type}, ${age}${trust}${pending})`
78
+ : `◉ memory: "${title}" (${type}${trust}${pending})`;
79
+ }
80
+
81
+ module.exports = { receiptFor, ageLabel };
package/src/scorer.js CHANGED
@@ -7,15 +7,26 @@
7
7
  * by external tools.
8
8
  */
9
9
 
10
+ const { trustFactor } = require('./provenance');
11
+
12
+ // Temporal invalidation: multiplier applied to a memory that a newer one has
13
+ // explicitly superseded. Low enough that the successor reliably outranks it,
14
+ // high enough that the superseded fact still surfaces when nothing else is
15
+ // relevant (so "this was true until X" remains answerable).
16
+ const SUPERSEDED_PENALTY = 0.25;
17
+
10
18
  /**
11
19
  * Compute the effective (decayed) strength of a memory.
12
20
  *
13
21
  * @param {number} baseStrength - Original strength (0.0-1.0)
14
22
  * @param {number} decayRate - Daily decay factor (e.g., 0.995)
15
23
  * @param {string|Date} lastAccessed - ISO timestamp of last access
24
+ * @param {boolean} [exempt=false] - CoALA Phase 1: pinned/stable memories are
25
+ * decay-exempt — their strength never fades (semantic "stable" property).
16
26
  * @returns {number} Effective strength after decay
17
27
  */
18
- function computeDecayedStrength(baseStrength, decayRate, lastAccessed) {
28
+ function computeDecayedStrength(baseStrength, decayRate, lastAccessed, exempt = false) {
29
+ if (exempt) return baseStrength;
19
30
  const lastDate = new Date(lastAccessed);
20
31
  const now = new Date();
21
32
  const daysElapsed = (now - lastDate) / (1000 * 60 * 60 * 24);
@@ -290,6 +301,8 @@ function improveDecayRate(decayRate) {
290
301
  * @returns {number} Consolidated strength (capped at 1.0)
291
302
  */
292
303
  function computeConsolidatedStrength(sourceStrengths) {
304
+ // No sources to consolidate — Math.max(...[]) is -Infinity, so guard explicitly.
305
+ if (!Array.isArray(sourceStrengths) || sourceStrengths.length === 0) return 0;
293
306
  const maxStrength = Math.max(...sourceStrengths);
294
307
  return Math.min(1.0, maxStrength + 0.15);
295
308
  }
@@ -357,18 +370,30 @@ function computeSpreadingActivationBatch(scoredMemories, associations, maxDepth
357
370
  * @param {Object} [options] - Optional scoring parameters
358
371
  * @param {Object} [options.associations] - Associations graph for spreading activation
359
372
  * @param {Object} [options.recallContext] - Current session context for context matching
373
+ * @param {number} [options.relevanceFloor] - Drop memories whose relevance AND
374
+ * spreading_bonus are both below this floor. Without it, zero-relevance
375
+ * memories pad the results purely on strength/recency/salience — a query
376
+ * about things the brain doesn't know still returns confident-looking hits.
377
+ * Memories rescued by spreading activation survive the floor (associative
378
+ * recall of low-relevance neighbors is a feature, not noise).
360
379
  * @returns {Object[]} Scored and sorted memories (highest first)
361
380
  */
362
381
  function rankMemories(memories, relevanceFn, options = {}) {
382
+ // Guard every term against NaN (e.g. a missing/invalid last_accessed or
383
+ // strength) — a single NaN score sorts non-deterministically and can outrank
384
+ // valid results.
385
+ const fin = (x) => (Number.isFinite(x) ? x : 0);
386
+
363
387
  // First pass: compute base scores
364
388
  const scored = memories.map((mem) => {
365
- const decayedStrength = computeDecayedStrength(
389
+ const decayedStrength = fin(computeDecayedStrength(
366
390
  mem.strength,
367
391
  mem.decay_rate,
368
- mem.last_accessed
369
- );
370
- const recencyBonus = computeRecencyBonus(mem.last_accessed);
371
- const relevance = relevanceFn(mem);
392
+ mem.last_accessed,
393
+ !!(mem.stable || mem.pinned) // pinned ⇒ implicitly stable (decay-exempt)
394
+ ));
395
+ const recencyBonus = fin(computeRecencyBonus(mem.last_accessed));
396
+ const relevance = fin(relevanceFn(mem));
372
397
 
373
398
  return {
374
399
  ...mem,
@@ -382,9 +407,22 @@ function rankMemories(memories, relevanceFn, options = {}) {
382
407
 
383
408
  // Second pass: spreading activation (batch — single traversal for all memories)
384
409
  if (options.associations) {
385
- const scoredSummary = scored.map((m) => ({
410
+ // With a relevanceFloor set (query mode), only query-relevant memories may
411
+ // act as activation SOURCES — matching the cognitive model (the cue
412
+ // activates matching memories, activation spreads along associations).
413
+ // Without it, a strong-but-irrelevant memory spreads on strength/recency
414
+ // alone and its whole clique rescues itself past the floor below.
415
+ const sources = options.relevanceFloor != null
416
+ ? scored.filter((m) => m.relevance >= options.relevanceFloor)
417
+ : scored;
418
+ // Source strength is damped by origin trust: a clique of co-tagged
419
+ // low-trust memories (planted writes auto-link via tag_overlap edges)
420
+ // must not self-amplify past trusted memories through activation alone.
421
+ const scoredSummary = sources.map((m) => ({
386
422
  id: m.id,
387
- score: 0.55 * m.relevance + 0.30 * m.decayed_strength + 0.15 * m.recency_bonus,
423
+ score:
424
+ (0.55 * m.relevance + 0.30 * m.decayed_strength + 0.15 * m.recency_bonus) *
425
+ trustFactor(m.origin),
388
426
  }));
389
427
 
390
428
  const bonuses = computeSpreadingActivationBatch(
@@ -406,20 +444,37 @@ function rankMemories(memories, relevanceFn, options = {}) {
406
444
  }
407
445
  }
408
446
 
447
+ // Relevance floor: gate BEFORE final scoring so strength/salience can't
448
+ // carry an unrelated memory into the results (uses raw, unrounded terms).
449
+ const floor = options.relevanceFloor;
450
+ const gated = floor != null
451
+ ? scored.filter((mem) => mem.relevance >= floor || mem.spreading_bonus >= floor)
452
+ : scored;
453
+
409
454
  // Final score
410
- return scored
455
+ return gated
411
456
  .map((mem) => {
412
457
  const extras = {};
413
458
  if (mem.spreading_bonus > 0) extras.spreadingBonus = mem.spreading_bonus;
414
459
  if (mem.context_match > 0) extras.contextMatch = mem.context_match;
415
460
  if (mem.salience != null) extras.salience = mem.salience;
416
461
 
417
- const score = computeRecallScore(
462
+ // Origin trust multiplies the composite: trust bounds entrenchment and
463
+ // volume, not relevance — a clearly more relevant low-trust memory can
464
+ // still win, but it can't win on bulk. Missing origin weighs as the
465
+ // memorize default, so legacy memories keep their relative order.
466
+ // Temporal invalidation: a memory explicitly superseded by a newer one
467
+ // (via `superseded_by`) is strongly demoted — not excluded, so an agent
468
+ // can still surface "this was true until X" — but it must never outrank
469
+ // the memory that replaced it. Demote, don't drop; the successor wins.
470
+ const supersededPenalty = mem.superseded_by ? SUPERSEDED_PENALTY : 1;
471
+
472
+ const score = fin(computeRecallScore(
418
473
  mem.relevance,
419
474
  mem.decayed_strength,
420
475
  mem.recency_bonus,
421
476
  extras
422
- );
477
+ )) * trustFactor(mem.origin) * supersededPenalty;
423
478
 
424
479
  return {
425
480
  ...mem,
@@ -431,7 +486,9 @@ function rankMemories(memories, relevanceFn, options = {}) {
431
486
  score: Math.round(score * 1000) / 1000,
432
487
  };
433
488
  })
434
- .sort((a, b) => b.score - a.score);
489
+ // Deterministic order: score desc, then id asc to break ties (scores are
490
+ // rounded to 3dp, which manufactures ties at scale).
491
+ .sort((a, b) => (b.score - a.score) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
435
492
  }
436
493
 
437
494
  module.exports = {
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
+ };