hebbian 0.3.0 → 0.3.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/constants.ts","../../src/init.ts","../../src/scanner.ts","../../src/subsumption.ts","../../src/emit.ts","../../src/fire.ts","../../src/similarity.ts","../../src/grow.ts","../../src/rollback.ts","../../src/signal.ts","../../src/decay.ts","../../src/dedup.ts","../../src/snapshot.ts","../../src/watch.ts","../../src/episode.ts","../../src/inbox.ts","../../src/api.ts","../../src/hooks.ts","../../src/digest.ts","../../src/cli.ts"],"sourcesContent":["// hebbian — Constants & Configuration\n//\n// AXIOMS:\n// 1. Folder = Neuron (name is meaning, depth is specificity)\n// 2. File = Firing Trace (N.neuron = counter, dopamineN = reward, bomb = pain)\n// 3. Path = Sentence (brain/cortex/quality/no_hardcoded → \"cortex > quality > no_hardcoded\")\n// 4. Counter = Activation (higher = stronger/myelinated path)\n// 5. AI writes back (counter increment = experience growth)\n\nexport const REGIONS = [\n\t'brainstem',\n\t'limbic',\n\t'hippocampus',\n\t'sensors',\n\t'cortex',\n\t'ego',\n\t'prefrontal',\n] as const;\n\nexport type RegionName = (typeof REGIONS)[number];\n\nexport const REGION_PRIORITY: Record<RegionName, number> = {\n\tbrainstem: 0,\n\tlimbic: 1,\n\thippocampus: 2,\n\tsensors: 3,\n\tcortex: 4,\n\tego: 5,\n\tprefrontal: 6,\n};\n\nexport const REGION_ICONS: Record<RegionName, string> = {\n\tbrainstem: '🛡️',\n\tlimbic: '💓',\n\thippocampus: '📝',\n\tsensors: '👁️',\n\tcortex: '🧠',\n\tego: '🎭',\n\tprefrontal: '🎯',\n};\n\nexport const REGION_KO: Record<RegionName, string> = {\n\tbrainstem: '양심/본능',\n\tlimbic: '감정 필터',\n\thippocampus: '기록/기억',\n\tsensors: '환경 제약',\n\tcortex: '지식/기술',\n\tego: '성향/톤',\n\tprefrontal: '목표/계획',\n};\n\nexport const EMIT_THRESHOLD = 5;\nexport const SPOTLIGHT_DAYS = 7;\nexport const JACCARD_THRESHOLD = 0.6;\nexport const DECAY_DAYS = 30;\nexport const MAX_DEPTH = 6;\n\nexport const EMIT_TARGETS: Record<string, string> = {\n\tgemini: '.gemini/GEMINI.md',\n\tcursor: '.cursorrules',\n\tclaude: 'CLAUDE.md',\n\tcopilot: '.github/copilot-instructions.md',\n\tgeneric: '.neuronrc',\n};\n\nexport const SIGNAL_TYPES = ['dopamine', 'bomb', 'memory'] as const;\nexport type SignalType = (typeof SIGNAL_TYPES)[number];\n\nexport const MARKER_START = '<!-- HEBBIAN:START -->';\nexport const MARKER_END = '<!-- HEBBIAN:END -->';\n\n// Hook ownership marker — used to identify hebbian-managed hooks in settings.local.json\nexport const HOOK_MARKER = '[hebbian]';\n\n// Digest constants\nexport const MAX_CORRECTIONS_PER_SESSION = 10;\nexport const MIN_CORRECTION_LENGTH = 15;\nexport const DIGEST_LOG_DIR = 'hippocampus/digest_log';\n\nimport { resolve } from 'node:path';\nimport { existsSync } from 'node:fs';\n\n/** Resolve brain root path from flag, env var, or defaults */\nexport function resolveBrainRoot(brainFlag?: string): string {\n\tif (brainFlag) return resolve(brainFlag);\n\tif (process.env.HEBBIAN_BRAIN) return resolve(process.env.HEBBIAN_BRAIN);\n\tif (existsSync(resolve('./brain'))) return resolve('./brain');\n\treturn resolve(process.env.HOME || '~', 'hebbian', 'brain');\n}\n","// hebbian — Brain Initialization\n//\n// Creates a brain directory with 7 canonical regions and starter neurons.\n// Each region gets a _rules.md explaining its purpose.\n\nimport { mkdirSync, writeFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { REGIONS, REGION_ICONS, REGION_KO } from './constants';\nimport type { RegionName } from './constants';\n\ninterface RegionTemplate {\n\tdescription: string;\n\tstarters: string[];\n}\n\nconst REGION_TEMPLATES: Record<RegionName, RegionTemplate> = {\n\tbrainstem: {\n\t\tdescription: 'Absolute principles. Immutable. Read-only conscience.\\nP0 — highest priority. bomb here halts EVERYTHING.',\n\t\tstarters: ['NO_fallback', 'DO_execute_not_debate'],\n\t},\n\tlimbic: {\n\t\tdescription: 'Emotional filters and somatic markers.\\nP1 — automatic, influences downstream regions.',\n\t\tstarters: [],\n\t},\n\thippocampus: {\n\t\tdescription: 'Memory and episode recording.\\nP2 — accumulated experience, session logs.',\n\t\tstarters: [],\n\t},\n\tsensors: {\n\t\tdescription: 'Environment constraints and input validation.\\nP3 — read-only, set by environment.',\n\t\tstarters: [],\n\t},\n\tcortex: {\n\t\tdescription: 'Knowledge and skills. The largest region.\\nP4 — learnable, grows with corrections.',\n\t\tstarters: [],\n\t},\n\tego: {\n\t\tdescription: 'Personality, tone, and communication style.\\nP5 — set by user preference.',\n\t\tstarters: [],\n\t},\n\tprefrontal: {\n\t\tdescription: 'Goals, projects, and planning.\\nP6 — lowest priority, longest time horizon.',\n\t\tstarters: [],\n\t},\n};\n\n/**\n * Initialize a new brain directory with 7 regions.\n */\nexport function initBrain(brainPath: string): void {\n\tif (existsSync(brainPath)) {\n\t\tconst entries = readdirSync(brainPath);\n\t\tif (entries.some((e) => (REGIONS as readonly string[]).includes(e))) {\n\t\t\tconsole.log(`\\u{26A0}\\uFE0F Brain already exists at ${brainPath}`);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tmkdirSync(brainPath, { recursive: true });\n\n\tfor (const regionName of REGIONS) {\n\t\tconst regionDir = join(brainPath, regionName);\n\t\tmkdirSync(regionDir, { recursive: true });\n\n\t\tconst template = REGION_TEMPLATES[regionName];\n\t\tconst icon = REGION_ICONS[regionName];\n\t\tconst ko = REGION_KO[regionName];\n\n\t\t// Write _rules.md template\n\t\twriteFileSync(\n\t\t\tjoin(regionDir, '_rules.md'),\n\t\t\t`# ${icon} ${regionName} (${ko})\\n\\n${template.description}\\n`,\n\t\t\t'utf8',\n\t\t);\n\n\t\t// Create starter neurons\n\t\tfor (const starter of template.starters) {\n\t\t\tconst neuronDir = join(regionDir, starter);\n\t\t\tmkdirSync(neuronDir, { recursive: true });\n\t\t\twriteFileSync(join(neuronDir, '1.neuron'), '', 'utf8');\n\t\t}\n\t}\n\n\t// Create _agents inbox\n\tmkdirSync(join(brainPath, '_agents', 'global_inbox'), { recursive: true });\n\n\tconsole.log(`\\u{1F9E0} Brain initialized at ${brainPath}`);\n\tconsole.log(` 7 regions created: ${REGIONS.join(', ')}`);\n\tconsole.log('');\n\tconsole.log(' Next steps:');\n\tconsole.log(` hebbian grow brainstem/NO_your_rule --brain ${brainPath}`);\n\tconsole.log(` hebbian emit claude --brain ${brainPath}`);\n}\n","// hebbian — Brain Filesystem Scanner\n//\n// Walks the brain directory tree and builds a structured representation.\n// Folders = neurons. Files = firing traces. Paths = sentences.\n//\n// Scan order follows subsumption priority (P0 brainstem → P6 prefrontal).\n// Only recognizes the 7 canonical region names at the top level.\n\nimport { readdirSync, statSync, readFileSync, existsSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { REGIONS, REGION_PRIORITY, MAX_DEPTH } from './constants';\nimport type { Neuron, Region, Brain } from './types';\n\n/**\n * Scan a brain directory and return all regions with their neurons.\n */\nexport function scanBrain(brainRoot: string): Brain {\n\tconst regions: Region[] = [];\n\n\tfor (const regionName of REGIONS) {\n\t\tconst regionPath = join(brainRoot, regionName);\n\t\tif (!existsSync(regionPath)) {\n\t\t\tregions.push({\n\t\t\t\tname: regionName,\n\t\t\t\tpriority: REGION_PRIORITY[regionName],\n\t\t\t\tpath: regionPath,\n\t\t\t\tneurons: [],\n\t\t\t\taxons: [],\n\t\t\t\thasBomb: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst neurons = walkRegion(regionPath, regionPath, 0);\n\t\tconst axons = readAxons(regionPath);\n\t\tconst hasBomb = neurons.some((n) => n.hasBomb);\n\n\t\tregions.push({\n\t\t\tname: regionName,\n\t\t\tpriority: REGION_PRIORITY[regionName],\n\t\t\tpath: regionPath,\n\t\t\tneurons,\n\t\t\taxons,\n\t\t\thasBomb,\n\t\t});\n\t}\n\n\treturn { root: brainRoot, regions };\n}\n\n/**\n * Recursively walk a region directory and collect neurons.\n * A neuron is any directory that contains at least one trace file\n * (*.neuron, *.contra, *.dormant, bomb.neuron).\n */\nfunction walkRegion(dir: string, regionRoot: string, depth: number): Neuron[] {\n\tif (depth > MAX_DEPTH) return [];\n\n\tconst neurons: Neuron[] = [];\n\tlet entries;\n\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn [];\n\t}\n\n\t// Parse trace files in this directory\n\tlet counter = 0;\n\tlet contra = 0;\n\tlet dopamine = 0;\n\tlet hasBomb = false;\n\tlet hasMemory = false;\n\tlet isDormant = false;\n\tlet modTime = new Date(0);\n\tlet hasTraceFile = false;\n\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_')) continue;\n\n\t\tif (entry.isFile()) {\n\t\t\tconst name = entry.name;\n\n\t\t\t// N.neuron — excitatory counter\n\t\t\tif (name.endsWith('.neuron') && !name.startsWith('dopamine') && !name.startsWith('memory') && name !== 'bomb.neuron') {\n\t\t\t\tconst n = parseInt(name, 10);\n\t\t\t\tif (!isNaN(n) && n > counter) {\n\t\t\t\t\tcounter = n;\n\t\t\t\t\thasTraceFile = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst st = statSync(join(dir, name));\n\t\t\t\t\t\tif (st.mtime > modTime) modTime = st.mtime;\n\t\t\t\t\t} catch {}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// N.contra — inhibitory counter\n\t\t\tif (name.endsWith('.contra')) {\n\t\t\t\tconst n = parseInt(name, 10);\n\t\t\t\tif (!isNaN(n) && n > contra) {\n\t\t\t\t\tcontra = n;\n\t\t\t\t\thasTraceFile = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// dopamineN.neuron — reward signal\n\t\t\tif (name.startsWith('dopamine') && name.endsWith('.neuron')) {\n\t\t\t\tconst n = parseInt(name.replace('dopamine', ''), 10);\n\t\t\t\tif (!isNaN(n) && n > dopamine) {\n\t\t\t\t\tdopamine = n;\n\t\t\t\t\thasTraceFile = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// bomb.neuron — circuit breaker\n\t\t\tif (name === 'bomb.neuron') {\n\t\t\t\thasBomb = true;\n\t\t\t\thasTraceFile = true;\n\t\t\t}\n\n\t\t\t// memoryN.neuron — memory signal\n\t\t\tif (name.startsWith('memory') && name.endsWith('.neuron')) {\n\t\t\t\thasMemory = true;\n\t\t\t\thasTraceFile = true;\n\t\t\t}\n\n\t\t\t// *.dormant — dormancy marker\n\t\t\tif (name.endsWith('.dormant')) {\n\t\t\t\tisDormant = true;\n\t\t\t\thasTraceFile = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// If this directory has trace files, it's a neuron\n\tif (hasTraceFile) {\n\t\tconst relPath = relative(regionRoot, dir) || '.';\n\t\tconst folderName = dir.split(sep).pop() || '';\n\t\tconst total = counter + contra + dopamine;\n\t\tconst intensity = counter - contra + dopamine;\n\t\tconst polarity = total > 0 ? intensity / total : 0;\n\n\t\tneurons.push({\n\t\t\tname: folderName,\n\t\t\tpath: relPath,\n\t\t\tfullPath: dir,\n\t\t\tcounter,\n\t\t\tcontra,\n\t\t\tdopamine,\n\t\t\tintensity,\n\t\t\tpolarity: Math.round(polarity * 100) / 100,\n\t\t\thasBomb,\n\t\t\thasMemory,\n\t\t\tisDormant,\n\t\t\tdepth,\n\t\t\tmodTime,\n\t\t});\n\t}\n\n\t// Recurse into subdirectories\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_') || entry.name.startsWith('.')) continue;\n\t\tif (entry.isDirectory()) {\n\t\t\tconst subNeurons = walkRegion(join(dir, entry.name), regionRoot, depth + 1);\n\t\t\tneurons.push(...subNeurons);\n\t\t}\n\t}\n\n\treturn neurons;\n}\n\n/**\n * Read .axon file from a region directory.\n */\nfunction readAxons(regionPath: string): string[] {\n\tconst axonPath = join(regionPath, '.axon');\n\tif (!existsSync(axonPath)) return [];\n\ttry {\n\t\tconst content = readFileSync(axonPath, 'utf8').trim();\n\t\treturn content.split(/[\\n,]+/).map((s: string) => s.trim()).filter(Boolean);\n\t} catch {\n\t\treturn [];\n\t}\n}\n","// hebbian — Subsumption Cascade Engine\n//\n// Implements Brooks' subsumption architecture:\n// - Lower priority (P0) always suppresses higher priority (P6)\n// - bomb.neuron in any region halts all downstream regions\n// - Dormant neurons are excluded from activation counts\n//\n// Cascade flow:\n// P0 brainstem → P1 limbic → P2 hippocampus → P3 sensors → P4 cortex → P5 ego → P6 prefrontal\n// If bomb at P(n), all P(n+1)→P6 are BLOCKED.\n\nimport type { Brain, Region, SubsumptionResult } from './types';\n\n/**\n * Run the subsumption cascade on a scanned brain.\n */\nexport function runSubsumption(brain: Brain): SubsumptionResult {\n\tconst activeRegions: Region[] = [];\n\tconst blockedRegions: Region[] = [];\n\tlet bombSource = '';\n\tlet firedNeurons = 0;\n\tlet totalNeurons = 0;\n\tlet totalCounter = 0;\n\tlet blocked = false;\n\n\tfor (const region of brain.regions) {\n\t\ttotalNeurons += region.neurons.length;\n\n\t\tif (blocked) {\n\t\t\tblockedRegions.push(region);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (region.hasBomb) {\n\t\t\tbombSource = region.name;\n\t\t\tblockedRegions.push(region);\n\t\t\tblocked = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tactiveRegions.push(region);\n\n\t\tfor (const neuron of region.neurons) {\n\t\t\tif (!neuron.isDormant) {\n\t\t\t\tfiredNeurons++;\n\t\t\t\ttotalCounter += neuron.counter;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tactiveRegions,\n\t\tblockedRegions,\n\t\tbombSource,\n\t\tfiredNeurons,\n\t\ttotalNeurons,\n\t\ttotalCounter,\n\t};\n}\n","// hebbian — 3-Tier Emit System + Multi-Target Output\n//\n// Tier 1: Bootstrap (~500 tokens) — auto-loaded by AI (CLAUDE.md, .cursorrules, etc.)\n// Tier 2: _index.md — brain overview (AI reads at conversation start)\n// Tier 3: {region}/_rules.md — per-region detail (AI reads on demand)\n//\n// Multi-target: claude, cursor, gemini, copilot, generic, all\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport { scanBrain } from './scanner';\nimport { runSubsumption } from './subsumption';\nimport {\n\tREGIONS, REGION_ICONS, REGION_KO, EMIT_TARGETS,\n\tEMIT_THRESHOLD, SPOTLIGHT_DAYS, MARKER_START, MARKER_END,\n} from './constants';\nimport type { RegionName } from './constants';\nimport type { Neuron, Region, Brain, SubsumptionResult } from './types';\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// TIER 1: Bootstrap (~500 tokens)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Generate Tier 1 bootstrap content.\n */\nexport function emitBootstrap(result: SubsumptionResult, brain: Brain): string {\n\tconst lines: string[] = [];\n\tconst now = new Date().toISOString().replace(/\\.\\d+Z$/, '');\n\n\tlines.push(MARKER_START);\n\tlines.push(`<!-- Generated: ${now} -->`);\n\tlines.push('<!-- Axiom: Folder=Neuron | File=Trace | Path=Sentence -->');\n\tlines.push(`<!-- Active: ${result.firedNeurons}/${result.totalNeurons} neurons | Total activation: ${result.totalCounter} -->`);\n\tlines.push('');\n\n\t// Circuit breaker\n\tif (result.bombSource) {\n\t\tlines.push(`## \\u{1F6A8} CIRCUIT BREAKER: ${result.bombSource}`);\n\t\tlines.push('**ALL OPERATIONS HALTED. REPAIR REQUIRED.**');\n\t\tlines.push('');\n\t\tlines.push(MARKER_END);\n\t\treturn lines.join('\\n');\n\t}\n\n\tlines.push('## hebbian Active Rules');\n\tlines.push('');\n\n\t// Persona (ego region)\n\tlines.push(`### ${REGION_ICONS.ego} Persona`);\n\tfor (const region of result.activeRegions) {\n\t\tif (region.name === 'ego') {\n\t\t\tconst top = sortedActive(region.neurons, 10);\n\t\t\tfor (const n of top) {\n\t\t\t\tlines.push(`- ${pathToSentence(n.path)}`);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tlines.push('');\n\n\t// Subsumption cascade\n\tlines.push('### \\u{1F517} Subsumption Cascade');\n\tlines.push('```');\n\tlines.push('brainstem \\u2190\\u2192 limbic \\u2190\\u2192 hippocampus \\u2190\\u2192 sensors \\u2190\\u2192 cortex \\u2190\\u2192 ego \\u2190\\u2192 prefrontal');\n\tlines.push(' (P0) (P1) (P2) (P3) (P4) (P5) (P6)');\n\tlines.push('```');\n\tlines.push('Lower P always overrides higher P. bomb = full stop.');\n\tlines.push('');\n\n\t// TOP 5 brainstem rules\n\tlines.push(`### ${REGION_ICONS.brainstem} Core Directives TOP 5`);\n\tfor (const region of result.activeRegions) {\n\t\tif (region.name === 'brainstem') {\n\t\t\tconst top = sortedActive(region.neurons, 5);\n\t\t\ttop.forEach((n, i) => {\n\t\t\t\tlines.push(`${i + 1}. **${pathToSentence(n.path)}**`);\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t}\n\tlines.push('');\n\n\t// Active regions summary\n\tlines.push('### Active Regions');\n\tlines.push('| Region | Neurons | Activation |');\n\tlines.push('|--------|---------|------------|');\n\tfor (const region of result.activeRegions) {\n\t\tconst active = region.neurons.filter((n) => !n.isDormant);\n\t\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\t\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\t\tlines.push(`| ${icon} ${region.name} | ${active.length} | ${activation} |`);\n\t}\n\tlines.push('');\n\tlines.push(MARKER_END);\n\n\treturn lines.join('\\n');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// TIER 2: Index (_index.md)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Generate Tier 2 brain index content.\n */\nexport function emitIndex(result: SubsumptionResult, brain: Brain): string {\n\tconst lines: string[] = [];\n\tlines.push('# hebbian Brain Index');\n\tlines.push('');\n\tlines.push(`> ${result.firedNeurons} active / ${result.totalNeurons} total neurons | activation: ${result.totalCounter}`);\n\tlines.push('');\n\n\tif (result.bombSource) {\n\t\tlines.push(`## \\u{1F6A8} CIRCUIT BREAKER: ${result.bombSource}`);\n\t\tlines.push('');\n\t\treturn lines.join('\\n');\n\t}\n\n\t// Top 10 neurons by counter\n\tconst allNeurons = result.activeRegions.flatMap((r) =>\n\t\tr.neurons.filter((n) => !n.isDormant && n.counter >= EMIT_THRESHOLD),\n\t);\n\tallNeurons.sort((a, b) => b.counter - a.counter);\n\n\tlines.push('## Top 10 Active Neurons');\n\tlines.push('| # | Path | Counter | Strength |');\n\tlines.push('|---|------|---------|----------|');\n\tfor (const n of allNeurons.slice(0, 10)) {\n\t\tconst strength = n.counter >= 10 ? '\\u{1F534}' : n.counter >= 5 ? '\\u{1F7E1}' : '\\u26AA';\n\t\tlines.push(`| ${allNeurons.indexOf(n) + 1} | ${n.path} | ${n.counter} | ${strength} |`);\n\t}\n\tlines.push('');\n\n\t// Spotlight: new neurons (< SPOTLIGHT_DAYS old, counter < EMIT_THRESHOLD)\n\tconst cutoff = new Date(Date.now() - SPOTLIGHT_DAYS * 24 * 60 * 60 * 1000);\n\tconst spotlightNeurons = result.activeRegions.flatMap((r) =>\n\t\tr.neurons.filter((n) => !n.isDormant && n.counter < EMIT_THRESHOLD && n.modTime > cutoff),\n\t);\n\tif (spotlightNeurons.length > 0) {\n\t\tlines.push('## Spotlight (Probation)');\n\t\tfor (const n of spotlightNeurons) {\n\t\t\tlines.push(`- ${n.path} (${n.counter}) — new`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\t// Per-region summary\n\tlines.push('## Regions');\n\tlines.push('| Region | Active | Dormant | Activation | Rules |');\n\tlines.push('|--------|--------|---------|------------|-------|');\n\tfor (const region of result.activeRegions) {\n\t\tconst active = region.neurons.filter((n) => !n.isDormant);\n\t\tconst dormant = region.neurons.filter((n) => n.isDormant);\n\t\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\t\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\t\tlines.push(`| ${icon} ${region.name} | ${active.length} | ${dormant.length} | ${activation} | [_rules.md](${region.name}/_rules.md) |`);\n\t}\n\tlines.push('');\n\n\treturn lines.join('\\n');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// TIER 3: Per-region rules ({region}/_rules.md)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Generate Tier 3 per-region rules content.\n */\nexport function emitRegionRules(region: Region): string {\n\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\tconst ko = REGION_KO[region.name as RegionName] || '';\n\tconst active = region.neurons.filter((n) => !n.isDormant);\n\tconst dormant = region.neurons.filter((n) => n.isDormant);\n\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\n\tconst lines: string[] = [];\n\tlines.push(`# ${icon} ${region.name} (${ko})`);\n\tlines.push(`> Active: ${active.length} | Dormant: ${dormant.length} | Activation: ${activation}`);\n\tlines.push('');\n\n\t// Axons\n\tif (region.axons.length > 0) {\n\t\tlines.push('## Connections');\n\t\tfor (const axon of region.axons) {\n\t\t\tlines.push(`- \\u2194 ${axon}`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\t// Neuron tree\n\tif (active.length > 0) {\n\t\tlines.push('## Rules');\n\t\tconst sorted = [...active].sort((a, b) => b.counter - a.counter);\n\t\tfor (const n of sorted) {\n\t\t\tconst indent = ' '.repeat(Math.min(n.depth, 4));\n\t\t\tconst prefix = strengthPrefix(n.counter);\n\t\t\tconst signals: string[] = [];\n\t\t\tif (n.dopamine > 0) signals.push(`\\u{1F7E2}+${n.dopamine}`);\n\t\t\tif (n.hasBomb) signals.push('\\u{1F4A3}');\n\t\t\tif (n.hasMemory) signals.push('\\u{1F4BE}');\n\t\t\tconst signalStr = signals.length > 0 ? ` ${signals.join(' ')}` : '';\n\t\t\tlines.push(`${indent}- ${prefix}${pathToSentence(n.path)} (${n.counter})${signalStr}`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\t// Dormant section\n\tif (dormant.length > 0) {\n\t\tlines.push('## Dormant');\n\t\tfor (const n of dormant) {\n\t\t\tlines.push(`- ~~${pathToSentence(n.path)} (${n.counter})~~`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\treturn lines.join('\\n');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// MULTI-TARGET OUTPUT\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Emit rules to a specific target or all targets.\n */\nexport function emitToTarget(brainRoot: string, target: string): void {\n\tconst brain = scanBrain(brainRoot);\n\tconst result = runSubsumption(brain);\n\tconst content = emitBootstrap(result, brain);\n\n\tif (target === 'all') {\n\t\tfor (const [name, filePath] of Object.entries(EMIT_TARGETS)) {\n\t\t\twriteTarget(filePath, content);\n\t\t\tconsole.log(`\\u{1F4E4} emitted: ${name} → ${filePath}`);\n\t\t}\n\t} else if (EMIT_TARGETS[target]) {\n\t\twriteTarget(EMIT_TARGETS[target], content);\n\t\tconsole.log(`\\u{1F4E4} emitted: ${target} → ${EMIT_TARGETS[target]}`);\n\t} else {\n\t\tthrow new Error(`Unknown target: ${target}. Valid: ${Object.keys(EMIT_TARGETS).join(', ')}, all`);\n\t}\n\n\t// Always write tier 2 + tier 3 into the brain\n\twriteAllTiers(brainRoot, result, brain);\n}\n\n/**\n * Write all 3 tiers into the brain directory.\n */\nexport function writeAllTiers(brainRoot: string, result: SubsumptionResult, brain: Brain): void {\n\t// Tier 2: _index.md\n\tconst indexContent = emitIndex(result, brain);\n\twriteFileSync(join(brainRoot, '_index.md'), indexContent, 'utf8');\n\n\t// Tier 3: per-region _rules.md\n\tfor (const region of result.activeRegions) {\n\t\tif (existsSync(region.path)) {\n\t\t\tconst rulesContent = emitRegionRules(region);\n\t\t\twriteFileSync(join(region.path, '_rules.md'), rulesContent, 'utf8');\n\t\t}\n\t}\n}\n\n/**\n * Write content to a target file, using marker-based injection if file already exists.\n */\nfunction writeTarget(filePath: string, content: string): void {\n\tconst dir = dirname(filePath);\n\tif (dir !== '.' && !existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true });\n\t}\n\n\tif (existsSync(filePath)) {\n\t\t// Marker-based injection: replace between markers, preserve surrounding content\n\t\tconst existing = readFileSync(filePath, 'utf8');\n\t\tconst startIdx = existing.indexOf(MARKER_START);\n\t\tconst endIdx = existing.indexOf(MARKER_END);\n\n\t\tif (startIdx !== -1 && endIdx !== -1) {\n\t\t\tconst before = existing.slice(0, startIdx);\n\t\t\tconst after = existing.slice(endIdx + MARKER_END.length);\n\t\t\twriteFileSync(filePath, before + content + after, 'utf8');\n\t\t\treturn;\n\t\t}\n\t}\n\n\twriteFileSync(filePath, content, 'utf8');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// DIAGNOSTICS (for CLI `hebbian diag` / `hebbian stats`)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Print brain diagnostics to stdout.\n */\nexport function printDiag(brain: Brain, result: SubsumptionResult): void {\n\tconsole.log('');\n\tconsole.log(`\\u{1F9E0} hebbian Brain Diagnostics`);\n\tconsole.log(` Root: ${brain.root}`);\n\tconsole.log(` Neurons: ${result.firedNeurons} active / ${result.totalNeurons} total`);\n\tconsole.log(` Activation: ${result.totalCounter}`);\n\tif (result.bombSource) {\n\t\tconsole.log(` \\u{1F4A3} BOMB: ${result.bombSource} — cascade halted!`);\n\t}\n\tconsole.log('');\n\n\tfor (const region of brain.regions) {\n\t\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\t\tconst active = region.neurons.filter((n) => !n.isDormant);\n\t\tconst dormant = region.neurons.filter((n) => n.isDormant);\n\t\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\t\tconst isBlocked = result.blockedRegions.some((r) => r.name === region.name);\n\t\tconst status = region.hasBomb ? '\\u{1F4A3} BOMB' : isBlocked ? '\\u{1F6AB} BLOCKED' : '\\u2705 ACTIVE';\n\n\t\tconsole.log(` ${icon} ${region.name} [${status}]`);\n\t\tconsole.log(` neurons: ${active.length} active, ${dormant.length} dormant | activation: ${activation}`);\n\n\t\tif (region.axons.length > 0) {\n\t\t\tconsole.log(` axons: ${region.axons.join(', ')}`);\n\t\t}\n\n\t\tconst top3 = sortedActive(region.neurons, 3);\n\t\tfor (const n of top3) {\n\t\t\tconsole.log(` \\u251C ${n.path} (${n.counter})`);\n\t\t}\n\t}\n\tconsole.log('');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// HELPERS\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/** Convert a neuron relative path to a human-readable sentence. */\nfunction pathToSentence(path: string): string {\n\treturn path.replace(/\\//g, ' > ').replace(/_/g, ' ');\n}\n\n/** Sort non-dormant neurons by counter (descending), take first N. */\nfunction sortedActive(neurons: Neuron[], n: number): Neuron[] {\n\treturn [...neurons]\n\t\t.filter((neuron) => !neuron.isDormant)\n\t\t.sort((a, b) => b.counter - a.counter)\n\t\t.slice(0, n);\n}\n\n/** Strength prefix based on counter value. */\nfunction strengthPrefix(counter: number): string {\n\tif (counter >= 10) return '**[ABSOLUTE]** ';\n\tif (counter >= 5) return '**[MUST]** ';\n\treturn '';\n}\n","// hebbian — Fire Neuron (increment counter)\n//\n// Firing = reinforcing a synaptic pathway.\n// The counter file is renamed: N.neuron → (N+1).neuron\n\nimport { readdirSync, renameSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Increment a neuron's counter by 1.\n * If the neuron doesn't exist, auto-grows it with counter=1.\n */\nexport function fireNeuron(brainRoot: string, neuronPath: string): number {\n\tconst fullPath = join(brainRoot, neuronPath);\n\n\t// Auto-grow if neuron doesn't exist\n\tif (!existsSync(fullPath)) {\n\t\tmkdirSync(fullPath, { recursive: true });\n\t\twriteFileSync(join(fullPath, '1.neuron'), '', 'utf8');\n\t\tconsole.log(`\\u{1F331} grew + fired: ${neuronPath} (1)`);\n\t\treturn 1;\n\t}\n\n\t// Find current counter\n\tconst current = getCurrentCounter(fullPath);\n\tconst newCounter = current + 1;\n\n\t// Rename: N.neuron → (N+1).neuron\n\tif (current > 0) {\n\t\trenameSync(join(fullPath, `${current}.neuron`), join(fullPath, `${newCounter}.neuron`));\n\t} else {\n\t\twriteFileSync(join(fullPath, `${newCounter}.neuron`), '', 'utf8');\n\t}\n\n\tconsole.log(`\\u{1F525} fired: ${neuronPath} (${current} → ${newCounter})`);\n\treturn newCounter;\n}\n\n/**\n * Get current counter value from the highest N.neuron file.\n */\nexport function getCurrentCounter(dir: string): number {\n\tlet max = 0;\n\ttry {\n\t\tfor (const entry of readdirSync(dir)) {\n\t\t\tif (entry.endsWith('.neuron') && !entry.startsWith('dopamine') && !entry.startsWith('memory') && entry !== 'bomb.neuron') {\n\t\t\t\tconst n = parseInt(entry, 10);\n\t\t\t\tif (!isNaN(n) && n > max) max = n;\n\t\t\t}\n\t\t}\n\t} catch {}\n\treturn max;\n}\n","// hebbian — Tokenizer, Stemmer, Jaccard Similarity\n//\n// Used by growNeuron() to detect similar existing neurons and merge\n// instead of duplicating. Implements synaptic consolidation.\n//\n// \"Neurons that fire together, wire together.\" — if two folder names\n// express the same concept, fire the existing one instead of creating a duplicate.\n\n/**\n * Tokenize a neuron name into stemmed words.\n * Splits on underscores, hyphens, spaces, and CamelCase boundaries.\n */\nexport function tokenize(name: string): string[] {\n\treturn name\n\t\t.replace(/([a-z])([A-Z])/g, '$1_$2') // camelCase → snake\n\t\t.replace(/[_\\-\\s]+/g, ' ') // normalize separators\n\t\t.toLowerCase()\n\t\t.split(' ')\n\t\t.map(stem)\n\t\t.filter((t) => t.length > 1); // drop single chars\n}\n\n/**\n * Simple suffix stemmer — removes common English suffixes.\n * Not a full Porter stemmer, but sufficient for Jaccard comparison.\n */\nexport function stem(word: string): string {\n\tconst suffixes = ['ing', 'tion', 'sion', 'ness', 'ment', 'able', 'ible', 'ful', 'less', 'ous', 'ive', 'ity', 'ies', 'ed', 'er', 'es', 'ly', 'al', 'en'];\n\tfor (const suffix of suffixes) {\n\t\tif (word.length > suffix.length + 2 && word.endsWith(suffix)) {\n\t\t\treturn word.slice(0, -suffix.length);\n\t\t}\n\t}\n\treturn word;\n}\n\n/**\n * Compute Jaccard similarity between two token sets.\n * |A ∩ B| / |A ∪ B|\n */\nexport function jaccardSimilarity(a: string[], b: string[]): number {\n\tif (a.length === 0 && b.length === 0) return 1.0;\n\tif (a.length === 0 || b.length === 0) return 0.0;\n\n\tconst setA = new Set(a);\n\tconst setB = new Set(b);\n\tlet intersection = 0;\n\n\tfor (const item of setA) {\n\t\tif (setB.has(item)) intersection++;\n\t}\n\n\tconst union = new Set([...setA, ...setB]).size;\n\treturn intersection / union;\n}\n","// hebbian — Grow Neuron (with synaptic consolidation)\n//\n// Creates a new neuron (folder + 1.neuron).\n// Before creating, checks for similar existing neurons via Jaccard similarity.\n// If a match is found (>= 0.6), fires the existing neuron instead.\n// This prevents duplication and strengthens existing pathways.\n//\n// \"Consolidation over duplication.\" — Hebb's principle.\n\nimport { mkdirSync, writeFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { REGIONS, JACCARD_THRESHOLD } from './constants';\nimport { tokenize, jaccardSimilarity } from './similarity';\nimport { fireNeuron } from './fire';\n\nexport interface GrowResult {\n\taction: 'grew' | 'fired';\n\tpath: string;\n\tcounter: number;\n}\n\n/**\n * Grow a new neuron at the given path.\n * If a similar neuron already exists in the same region, fires it instead.\n */\nexport function growNeuron(brainRoot: string, neuronPath: string): GrowResult {\n\tconst fullPath = join(brainRoot, neuronPath);\n\n\t// If neuron already exists, just fire it\n\tif (existsSync(fullPath)) {\n\t\tconst counter = fireNeuron(brainRoot, neuronPath);\n\t\treturn { action: 'fired', path: neuronPath, counter };\n\t}\n\n\t// Extract region name and leaf name\n\tconst parts = neuronPath.split('/');\n\tconst regionName = parts[0]!;\n\tif (!(REGIONS as readonly string[]).includes(regionName)) {\n\t\tthrow new Error(`Invalid region: ${regionName}. Valid: ${REGIONS.join(', ')}`);\n\t}\n\n\tconst leafName = parts[parts.length - 1]!;\n\tconst newTokens = tokenize(leafName);\n\n\t// Search for similar neurons in the same region\n\tconst regionPath = join(brainRoot, regionName);\n\tif (existsSync(regionPath)) {\n\t\tconst match = findSimilar(regionPath, regionPath, newTokens);\n\t\tif (match) {\n\t\t\tconst matchRelPath = regionName + '/' + relative(regionPath, match);\n\t\t\tconsole.log(`\\u{1F504} consolidation: \"${neuronPath}\" ≈ \"${matchRelPath}\" (firing existing)`);\n\t\t\tconst counter = fireNeuron(brainRoot, matchRelPath);\n\t\t\treturn { action: 'fired', path: matchRelPath, counter };\n\t\t}\n\t}\n\n\t// No match — create new neuron\n\tmkdirSync(fullPath, { recursive: true });\n\twriteFileSync(join(fullPath, '1.neuron'), '', 'utf8');\n\tconsole.log(`\\u{1F331} grew: ${neuronPath} (1)`);\n\treturn { action: 'grew', path: neuronPath, counter: 1 };\n}\n\n/**\n * Walk a region and find a neuron whose name is similar to the given tokens.\n */\nfunction findSimilar(dir: string, regionRoot: string, targetTokens: string[]): string | null {\n\tlet entries;\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn null;\n\t}\n\n\t// Check if this directory has .neuron files (is a neuron)\n\tconst hasNeuron = entries.some((e) => e.isFile() && e.name.endsWith('.neuron'));\n\tif (hasNeuron) {\n\t\tconst folderName = dir.split('/').pop() || '';\n\t\tconst existingTokens = tokenize(folderName);\n\t\tconst similarity = jaccardSimilarity(targetTokens, existingTokens);\n\t\tif (similarity >= JACCARD_THRESHOLD) {\n\t\t\treturn dir;\n\t\t}\n\t}\n\n\t// Recurse into subdirectories\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_') || entry.name.startsWith('.')) continue;\n\t\tif (entry.isDirectory()) {\n\t\t\tconst match = findSimilar(join(dir, entry.name), regionRoot, targetTokens);\n\t\t\tif (match) return match;\n\t\t}\n\t}\n\n\treturn null;\n}\n","// hebbian — Rollback Neuron (decrement counter)\n//\n// Undo a firing. Counter cannot go below 1 (minimum activation).\n\nimport { renameSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getCurrentCounter } from './fire';\n\n/**\n * Decrement a neuron's counter by 1. Minimum counter is 1.\n */\nexport function rollbackNeuron(brainRoot: string, neuronPath: string): number {\n\tconst fullPath = join(brainRoot, neuronPath);\n\tconst current = getCurrentCounter(fullPath);\n\n\tif (current === 0) {\n\t\tthrow new Error(`Neuron not found: ${neuronPath}`);\n\t}\n\n\tif (current <= 1) {\n\t\tthrow new Error(`Counter already at minimum (1): ${neuronPath}`);\n\t}\n\n\tconst newCounter = current - 1;\n\trenameSync(join(fullPath, `${current}.neuron`), join(fullPath, `${newCounter}.neuron`));\n\n\tconsole.log(`\\u{23EA} rollback: ${neuronPath} (${current} → ${newCounter})`);\n\treturn newCounter;\n}\n","// hebbian — Signal Neuron (dopamine / bomb / memory)\n//\n// Signals are additional trace files placed in a neuron directory:\n// dopamineN.neuron — reward signal (positive reinforcement)\n// bomb.neuron — circuit breaker (halts downstream regions)\n// memoryN.neuron — memory marker (episodic recording)\n\nimport { writeFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { SIGNAL_TYPES } from './constants';\nimport type { SignalType } from './constants';\n\n/**\n * Add a signal to a neuron.\n */\nexport function signalNeuron(brainRoot: string, neuronPath: string, signalType: SignalType): void {\n\tif (!SIGNAL_TYPES.includes(signalType)) {\n\t\tthrow new Error(`Invalid signal type: ${signalType}. Valid: ${SIGNAL_TYPES.join(', ')}`);\n\t}\n\n\tconst fullPath = join(brainRoot, neuronPath);\n\tif (!existsSync(fullPath)) {\n\t\tthrow new Error(`Neuron not found: ${neuronPath}`);\n\t}\n\n\tswitch (signalType) {\n\t\tcase 'bomb': {\n\t\t\twriteFileSync(join(fullPath, 'bomb.neuron'), '', 'utf8');\n\t\t\tconsole.log(`\\u{1F4A3} bomb planted: ${neuronPath}`);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'dopamine': {\n\t\t\tconst level = getNextSignalLevel(fullPath, 'dopamine');\n\t\t\twriteFileSync(join(fullPath, `dopamine${level}.neuron`), '', 'utf8');\n\t\t\tconsole.log(`\\u{1F7E2} dopamine +${level}: ${neuronPath}`);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'memory': {\n\t\t\tconst level = getNextSignalLevel(fullPath, 'memory');\n\t\t\twriteFileSync(join(fullPath, `memory${level}.neuron`), '', 'utf8');\n\t\t\tconsole.log(`\\u{1F4BE} memory +${level}: ${neuronPath}`);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Get the next signal level (current max + 1).\n */\nfunction getNextSignalLevel(dir: string, prefix: string): number {\n\tlet max = 0;\n\ttry {\n\t\tfor (const entry of readdirSync(dir)) {\n\t\t\tif (entry.startsWith(prefix) && entry.endsWith('.neuron')) {\n\t\t\t\tconst n = parseInt(entry.replace(prefix, ''), 10);\n\t\t\t\tif (!isNaN(n) && n > max) max = n;\n\t\t\t}\n\t\t}\n\t} catch {}\n\treturn max + 1;\n}\n","// hebbian — Decay (dormancy sweep)\n//\n// Neurons that haven't been touched in N days are marked dormant.\n// Dormancy = *.dormant file in the neuron directory.\n// Dormant neurons are excluded from emission and activation counts.\n//\n// \"Most neurons die. Only the repeatedly fired ones survive.\" — Natural selection on OS.\n\nimport { readdirSync, statSync, writeFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { REGIONS, MAX_DEPTH } from './constants';\n\nexport interface DecayResult {\n\tscanned: number;\n\tdecayed: number;\n}\n\n/**\n * Sweep the brain and mark inactive neurons as dormant.\n */\nexport function runDecay(brainRoot: string, days: number): DecayResult {\n\tconst threshold = Date.now() - days * 24 * 60 * 60 * 1000;\n\tlet scanned = 0;\n\tlet decayed = 0;\n\n\tfor (const regionName of REGIONS) {\n\t\tconst regionPath = join(brainRoot, regionName);\n\t\tif (!existsSync(regionPath)) continue;\n\t\tconst result = decayWalk(regionPath, threshold, 0);\n\t\tscanned += result.scanned;\n\t\tdecayed += result.decayed;\n\t}\n\n\tconsole.log(`\\u{1F4A4} decay: scanned ${scanned} neurons, decayed ${decayed} (>${days} days inactive)`);\n\treturn { scanned, decayed };\n}\n\nfunction decayWalk(dir: string, threshold: number, depth: number): DecayResult {\n\tif (depth > MAX_DEPTH) return { scanned: 0, decayed: 0 };\n\n\tlet scanned = 0;\n\tlet decayed = 0;\n\tlet entries;\n\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn { scanned: 0, decayed: 0 };\n\t}\n\n\t// Check if this directory is a neuron (has .neuron files)\n\tlet hasNeuronFile = false;\n\tlet isDormant = false;\n\tlet latestMod = 0;\n\n\tfor (const entry of entries) {\n\t\tif (entry.isFile()) {\n\t\t\tif (entry.name.endsWith('.neuron')) {\n\t\t\t\thasNeuronFile = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst st = statSync(join(dir, entry.name));\n\t\t\t\t\tif (st.mtimeMs > latestMod) latestMod = st.mtimeMs;\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (entry.name.endsWith('.dormant')) {\n\t\t\t\tisDormant = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (hasNeuronFile) {\n\t\tscanned++;\n\t\tif (!isDormant && latestMod < threshold) {\n\t\t\tconst age = Math.floor((Date.now() - latestMod) / (24 * 60 * 60 * 1000));\n\t\t\twriteFileSync(\n\t\t\t\tjoin(dir, 'decay.dormant'),\n\t\t\t\t`Dormant since ${new Date().toISOString()} (${age} days inactive)`,\n\t\t\t\t'utf8',\n\t\t\t);\n\t\t\tdecayed++;\n\t\t}\n\t}\n\n\t// Recurse\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_') || entry.name.startsWith('.')) continue;\n\t\tif (entry.isDirectory()) {\n\t\t\tconst sub = decayWalk(join(dir, entry.name), threshold, depth + 1);\n\t\t\tscanned += sub.scanned;\n\t\t\tdecayed += sub.decayed;\n\t\t}\n\t}\n\n\treturn { scanned, decayed };\n}\n","// hebbian — Batch Deduplication\n//\n// Scans all neurons in a region and merges duplicates via Jaccard similarity.\n// When a match is found (>= threshold), fires the higher-counter neuron\n// and marks the lower-counter one dormant.\n\nimport { writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { JACCARD_THRESHOLD } from './constants';\nimport { tokenize, jaccardSimilarity } from './similarity';\nimport { fireNeuron } from './fire';\nimport { scanBrain } from './scanner';\n\nexport interface DedupResult {\n\tscanned: number;\n\tmerged: number;\n}\n\n/**\n * Run batch deduplication across all regions.\n */\nexport function runDedup(brainRoot: string): DedupResult {\n\tconst brain = scanBrain(brainRoot);\n\tlet scanned = 0;\n\tlet merged = 0;\n\n\tfor (const region of brain.regions) {\n\t\tconst neurons = region.neurons.filter((n) => !n.isDormant);\n\t\tscanned += neurons.length;\n\n\t\t// O(n^2) pairwise comparison within each region\n\t\tconst consumed = new Set<number>();\n\t\tfor (let i = 0; i < neurons.length; i++) {\n\t\t\tif (consumed.has(i)) continue;\n\t\t\tconst ni = neurons[i]!;\n\t\t\tconst tokensI = tokenize(ni.name);\n\n\t\t\tfor (let j = i + 1; j < neurons.length; j++) {\n\t\t\t\tif (consumed.has(j)) continue;\n\t\t\t\tconst nj = neurons[j]!;\n\t\t\t\tconst tokensJ = tokenize(nj.name);\n\t\t\t\tconst sim = jaccardSimilarity(tokensI, tokensJ);\n\n\t\t\t\tif (sim >= JACCARD_THRESHOLD) {\n\t\t\t\t\t// Keep the one with higher counter, mark other dormant\n\t\t\t\t\tconst [keep, drop] = ni.counter >= nj.counter\n\t\t\t\t\t\t? [ni, nj] : [nj, ni];\n\n\t\t\t\t\t// Fire the keeper to absorb the dropped counter\n\t\t\t\t\tconst relKeep = `${region.name}/${keep.path}`;\n\t\t\t\t\tfireNeuron(brainRoot, relKeep);\n\n\t\t\t\t\t// Mark the dropped neuron dormant\n\t\t\t\t\twriteFileSync(\n\t\t\t\t\t\tjoin(drop.fullPath, 'dedup.dormant'),\n\t\t\t\t\t\t`Merged into ${keep.path} on ${new Date().toISOString()}`,\n\t\t\t\t\t\t'utf8',\n\t\t\t\t\t);\n\n\t\t\t\t\tconsumed.add(ni === drop ? i : j);\n\t\t\t\t\tmerged++;\n\t\t\t\t\tconsole.log(`\\u{1F500} merged: \"${drop.path}\" → \"${keep.path}\" (sim=${sim.toFixed(2)})`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tconsole.log(`\\u{1F9F9} dedup: scanned ${scanned} neurons, merged ${merged}`);\n\treturn { scanned, merged };\n}\n","// hebbian — Git Snapshot\n//\n// Creates a git commit of the current brain state for audit trail.\n// Only commits if there are changes.\n\nimport { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Create a git snapshot of the brain directory.\n */\nexport function gitSnapshot(brainRoot: string): boolean {\n\t// Check if brain is inside a git repo\n\tif (!existsSync(join(brainRoot, '.git'))) {\n\t\t// Try parent directories\n\t\ttry {\n\t\t\texecSync('git rev-parse --is-inside-work-tree', { cwd: brainRoot, stdio: 'pipe' });\n\t\t} catch {\n\t\t\tconsole.log('\\u{26A0}\\uFE0F Not a git repository. Run `git init` in the brain directory first.');\n\t\t\treturn false;\n\t\t}\n\t}\n\n\ttry {\n\t\t// Check for changes\n\t\tconst status = execSync('git status --porcelain .', { cwd: brainRoot, encoding: 'utf8' });\n\t\tif (!status.trim()) {\n\t\t\tconsole.log('\\u{2705} No changes to snapshot.');\n\t\t\treturn false;\n\t\t}\n\n\t\t// Stage and commit\n\t\texecSync('git add .', { cwd: brainRoot, stdio: 'pipe' });\n\t\tconst ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);\n\t\texecSync(`git commit -m \"hebbian snapshot ${ts}\"`, { cwd: brainRoot, stdio: 'pipe' });\n\n\t\tconsole.log(`\\u{1F4F8} snapshot: committed brain state at ${ts}`);\n\t\treturn true;\n\t} catch (err: unknown) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tconsole.error(`\\u{274C} snapshot failed: ${message}`);\n\t\treturn false;\n\t}\n}\n","// hebbian — Watch Mode\n//\n// Watches the brain directory for filesystem changes and auto-recompiles\n// all tiers when changes are detected. Uses hash-based change detection\n// to avoid redundant writes.\n\nimport { watch } from 'node:fs';\nimport { scanBrain } from './scanner';\nimport { runSubsumption } from './subsumption';\nimport { writeAllTiers } from './emit';\nimport type { SubsumptionResult } from './types';\n\n/**\n * Start watching a brain directory for changes.\n * Auto-recompiles tiers when neurons are added/modified/removed.\n */\nexport async function startWatch(brainRoot: string): Promise<void> {\n\tlet lastHash = '';\n\tlet debounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n\t/** Scan brain and recompile if state changed. */\n\tfunction recompile(): void {\n\t\tconst brain = scanBrain(brainRoot);\n\t\tconst result = runSubsumption(brain);\n\t\tconst hash = computeHash(result);\n\n\t\tif (hash === lastHash) return;\n\t\tlastHash = hash;\n\n\t\twriteAllTiers(brainRoot, result, brain);\n\t\tconst ts = new Date().toLocaleTimeString();\n\t\tconsole.log(`[${ts}] \\u{1F504} recompiled — ${result.firedNeurons} neurons, activation ${result.totalCounter}${result.bombSource ? ` \\u{1F4A3} BOMB: ${result.bombSource}` : ''}`);\n\t}\n\n\t// Initial compilation\n\trecompile();\n\tconsole.log(`\\u{1F440} watching: ${brainRoot}`);\n\tconsole.log(' Press Ctrl+C to stop.\\n');\n\n\t// Watch for filesystem changes\n\ttry {\n\t\tconst watcher = watch(brainRoot, { recursive: true }, (eventType, filename) => {\n\t\t\tif (!filename) return;\n\t\t\t// Ignore _index.md and _rules.md (our own output)\n\t\t\tif (filename.endsWith('_index.md') || filename.endsWith('_rules.md')) return;\n\t\t\t// Ignore hidden/internal\n\t\t\tif (filename.startsWith('.') || filename.includes('/_') || filename.includes('\\\\_')) return;\n\n\t\t\t// Debounce: wait 200ms after last change before recompiling\n\t\t\tif (debounceTimer) clearTimeout(debounceTimer);\n\t\t\tdebounceTimer = setTimeout(recompile, 200);\n\t\t});\n\n\t\t// Keep process alive\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\twatcher.close();\n\t\t\t\tconsole.log('\\n\\u{1F44B} watch stopped.');\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t} catch (err: unknown) {\n\t\tif (err && typeof err === 'object' && 'code' in err && err.code === 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM') {\n\t\t\tconsole.error('Recursive fs.watch not supported on this platform. Use Node.js >= 22.');\n\t\t} else {\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\n/**\n * Compute a simple hash from the subsumption result for change detection.\n */\nfunction computeHash(result: SubsumptionResult): string {\n\treturn `${result.firedNeurons}:${result.totalCounter}:${result.bombSource}:${result.activeRegions.length}`;\n}\n","// hebbian — Episode Logging (Circular Buffer)\n//\n// Writes events to hippocampus/session_log/ as memoryN.neuron files.\n// Circular buffer: max 100 entries. When full, overwrites oldest.\n//\n// Port from: NeuronFS/runtime/main.go lines 1300-1342\n\nimport { readdirSync, readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst MAX_EPISODES = 100;\nconst SESSION_LOG_DIR = 'hippocampus/session_log';\n\nexport interface Episode {\n\tts: string;\n\ttype: string;\n\tpath: string;\n\tdetail: string;\n}\n\n/**\n * Log an episode to the hippocampus session log.\n * Circular buffer — writes to memoryN.neuron, wraps at MAX_EPISODES.\n */\nexport function logEpisode(brainRoot: string, type: string, path: string, detail: string): void {\n\tconst logDir = join(brainRoot, SESSION_LOG_DIR);\n\tif (!existsSync(logDir)) {\n\t\tmkdirSync(logDir, { recursive: true });\n\t}\n\n\tconst nextSlot = getNextSlot(logDir);\n\tconst episode: Episode = {\n\t\tts: new Date().toISOString(),\n\t\ttype,\n\t\tpath,\n\t\tdetail,\n\t};\n\n\twriteFileSync(\n\t\tjoin(logDir, `memory${nextSlot}.neuron`),\n\t\tJSON.stringify(episode),\n\t\t'utf8',\n\t);\n}\n\n/**\n * Read all episodes from the session log, sorted by timestamp.\n */\nexport function readEpisodes(brainRoot: string): Episode[] {\n\tconst logDir = join(brainRoot, SESSION_LOG_DIR);\n\tif (!existsSync(logDir)) return [];\n\n\tconst episodes: Episode[] = [];\n\tlet entries;\n\ttry {\n\t\tentries = readdirSync(logDir);\n\t} catch {\n\t\treturn [];\n\t}\n\n\tfor (const entry of entries) {\n\t\tif (!entry.startsWith('memory') || !entry.endsWith('.neuron')) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(join(logDir, entry), 'utf8');\n\t\t\tif (content.trim()) {\n\t\t\t\tepisodes.push(JSON.parse(content) as Episode);\n\t\t\t}\n\t\t} catch {\n\t\t\t// skip malformed entries\n\t\t}\n\t}\n\n\tepisodes.sort((a, b) => a.ts.localeCompare(b.ts));\n\treturn episodes;\n}\n\n/**\n * Find the next circular buffer slot (1-based, wraps at MAX_EPISODES).\n */\nfunction getNextSlot(logDir: string): number {\n\tlet maxSlot = 0;\n\ttry {\n\t\tfor (const entry of readdirSync(logDir)) {\n\t\t\tif (entry.startsWith('memory') && entry.endsWith('.neuron')) {\n\t\t\t\tconst n = parseInt(entry.replace('memory', '').replace('.neuron', ''), 10);\n\t\t\t\tif (!isNaN(n) && n > maxSlot) maxSlot = n;\n\t\t\t}\n\t\t}\n\t} catch {}\n\n\tconst next = maxSlot + 1;\n\t// Wrap around: if we exceed max, start overwriting from 1\n\treturn next > MAX_EPISODES ? ((maxSlot % MAX_EPISODES) + 1) : next;\n}\n","// hebbian — Inbox Processing\n//\n// Parses _inbox/corrections.jsonl and auto-creates/fires neurons from\n// AI corrections. Security checks prevent path traversal. Only PM/admin\n// roles can award dopamine (inflation filter).\n//\n// Port from: NeuronFS/runtime/main.go lines 1425-1544\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { REGIONS } from './constants';\nimport { growNeuron } from './grow';\nimport { fireNeuron } from './fire';\nimport { signalNeuron } from './signal';\nimport { logEpisode } from './episode';\n\nconst INBOX_DIR = '_inbox';\nconst CORRECTIONS_FILE = 'corrections.jsonl';\nconst DOPAMINE_ALLOWED_ROLES = ['pm', 'admin', 'lead'];\n\nexport interface Correction {\n\tts: string;\n\ttype: 'correction';\n\ttext: string;\n\tpath: string;\n\tcounter_add: number;\n\tauthor: string;\n\tdopamine?: number;\n}\n\nexport interface InboxResult {\n\tprocessed: number;\n\tskipped: number;\n\terrors: string[];\n}\n\n/**\n * Process the inbox corrections file.\n * Each line is a JSON object describing a correction to apply.\n */\nexport function processInbox(brainRoot: string): InboxResult {\n\tconst inboxPath = join(brainRoot, INBOX_DIR, CORRECTIONS_FILE);\n\n\tif (!existsSync(inboxPath)) {\n\t\treturn { processed: 0, skipped: 0, errors: [] };\n\t}\n\n\tconst content = readFileSync(inboxPath, 'utf8').trim();\n\tif (!content) {\n\t\treturn { processed: 0, skipped: 0, errors: [] };\n\t}\n\n\tconst lines = content.split('\\n').filter(Boolean);\n\tlet processed = 0;\n\tlet skipped = 0;\n\tconst errors: string[] = [];\n\n\tfor (const line of lines) {\n\t\tlet correction: Correction;\n\t\ttry {\n\t\t\tcorrection = JSON.parse(line) as Correction;\n\t\t} catch {\n\t\t\terrors.push(`Malformed JSON: ${line.slice(0, 80)}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Validate required fields\n\t\tif (!correction.path || !correction.type) {\n\t\t\terrors.push(`Missing path or type: ${line.slice(0, 80)}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Security: path traversal check\n\t\tif (!isPathSafe(correction.path)) {\n\t\t\terrors.push(`Path traversal blocked: ${correction.path}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Security: validate region\n\t\tconst region = correction.path.split('/')[0];\n\t\tif (!region || !(REGIONS as readonly string[]).includes(region)) {\n\t\t\terrors.push(`Invalid region in path: ${correction.path}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tapplyCorrection(brainRoot, correction);\n\t\t\tprocessed++;\n\t\t} catch (err) {\n\t\t\terrors.push(`Failed to apply ${correction.path}: ${(err as Error).message}`);\n\t\t\tskipped++;\n\t\t}\n\t}\n\n\t// Clear the inbox file after processing\n\twriteFileSync(inboxPath, '', 'utf8');\n\n\tconsole.log(`📥 inbox: processed ${processed}, skipped ${skipped}`);\n\tif (errors.length > 0) {\n\t\tfor (const err of errors) {\n\t\t\tconsole.log(` ⚠️ ${err}`);\n\t\t}\n\t}\n\n\treturn { processed, skipped, errors };\n}\n\n/**\n * Apply a single correction entry.\n */\nfunction applyCorrection(brainRoot: string, correction: Correction): void {\n\tconst neuronPath = correction.path;\n\tconst fullPath = join(brainRoot, neuronPath);\n\tconst counterAdd = Math.max(1, correction.counter_add || 1);\n\n\tif (existsSync(fullPath)) {\n\t\t// Neuron exists — fire N times\n\t\tfor (let i = 0; i < counterAdd; i++) {\n\t\t\tfireNeuron(brainRoot, neuronPath);\n\t\t}\n\t} else {\n\t\t// Neuron doesn't exist — grow + fire (N-1)\n\t\tgrowNeuron(brainRoot, neuronPath);\n\t\tfor (let i = 1; i < counterAdd; i++) {\n\t\t\tfireNeuron(brainRoot, neuronPath);\n\t\t}\n\t}\n\n\t// Dopamine inflation filter: only allowed roles can award dopamine\n\tif (correction.dopamine && correction.dopamine > 0) {\n\t\tconst author = (correction.author || '').toLowerCase();\n\t\tif (DOPAMINE_ALLOWED_ROLES.includes(author)) {\n\t\t\tsignalNeuron(brainRoot, neuronPath, 'dopamine');\n\t\t}\n\t}\n\n\tlogEpisode(brainRoot, 'inbox', neuronPath, correction.text || '');\n}\n\n/**\n * Security: check path for traversal attacks.\n */\nfunction isPathSafe(path: string): boolean {\n\tif (path.includes('..')) return false;\n\tif (path.startsWith('/')) return false;\n\tif (path.includes('\\\\')) return false;\n\t// Block null bytes\n\tif (path.includes('\\0')) return false;\n\treturn true;\n}\n\n/**\n * Ensure the inbox directory and corrections file exist.\n */\nexport function ensureInbox(brainRoot: string): string {\n\tconst inboxDir = join(brainRoot, INBOX_DIR);\n\tif (!existsSync(inboxDir)) {\n\t\tmkdirSync(inboxDir, { recursive: true });\n\t}\n\tconst filePath = join(inboxDir, CORRECTIONS_FILE);\n\tif (!existsSync(filePath)) {\n\t\twriteFileSync(filePath, '', 'utf8');\n\t}\n\treturn filePath;\n}\n\n/**\n * Append a correction entry to the inbox.\n */\nexport function appendCorrection(brainRoot: string, correction: Correction): void {\n\tconst filePath = ensureInbox(brainRoot);\n\tconst line = JSON.stringify(correction) + '\\n';\n\tconst existing = readFileSync(filePath, 'utf8');\n\twriteFileSync(filePath, existing + line, 'utf8');\n}\n","// hebbian — REST API Server\n//\n// Programmatic brain manipulation via HTTP. Zero dependencies (node:http).\n// Enables external tools (n8n, webhooks, dashboards) to interact with hebbian.\n//\n// Port from: NeuronFS/runtime/main.go lines 2099-2434\n\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport { scanBrain } from './scanner';\nimport { runSubsumption } from './subsumption';\nimport { fireNeuron } from './fire';\nimport { rollbackNeuron } from './rollback';\nimport { growNeuron } from './grow';\nimport { signalNeuron } from './signal';\nimport { runDecay } from './decay';\nimport { runDedup } from './dedup';\nimport { writeAllTiers } from './emit';\nimport { processInbox } from './inbox';\nimport { REGIONS, REGION_ICONS, REGION_KO, type SignalType } from './constants';\nimport type { RegionName } from './constants';\n\nlet lastAPIActivity = Date.now();\n\nexport interface ReportEntry {\n\tts: string;\n\tmessage: string;\n\tpriority: 'low' | 'normal' | 'high' | 'critical';\n}\n\nconst pendingReports: ReportEntry[] = [];\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// JSON Response Builders\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nfunction buildHealthJSON(brainRoot: string) {\n\tconst brain = scanBrain(brainRoot);\n\tconst result = runSubsumption(brain);\n\treturn {\n\t\tstatus: 'ok',\n\t\tbrain: brainRoot,\n\t\tneurons: result.totalNeurons,\n\t\tactiveNeurons: result.firedNeurons,\n\t\ttotalActivation: result.totalCounter,\n\t\tbombSource: result.bombSource || null,\n\t\tlastActivity: new Date(lastAPIActivity).toISOString(),\n\t\tuptime: process.uptime(),\n\t};\n}\n\nfunction buildBrainJSON(brainRoot: string) {\n\tconst brain = scanBrain(brainRoot);\n\tconst result = runSubsumption(brain);\n\treturn {\n\t\troot: brain.root,\n\t\tregions: brain.regions.map((region) => ({\n\t\t\tname: region.name,\n\t\t\ticon: REGION_ICONS[region.name as RegionName] || '',\n\t\t\tko: REGION_KO[region.name as RegionName] || '',\n\t\t\tpriority: region.priority,\n\t\t\thasBomb: region.hasBomb,\n\t\t\tneurons: region.neurons.map((n) => ({\n\t\t\t\tname: n.name,\n\t\t\t\tpath: n.path,\n\t\t\t\tcounter: n.counter,\n\t\t\t\tcontra: n.contra,\n\t\t\t\tdopamine: n.dopamine,\n\t\t\t\thasBomb: n.hasBomb,\n\t\t\t\thasMemory: n.hasMemory,\n\t\t\t\tisDormant: n.isDormant,\n\t\t\t\tdepth: n.depth,\n\t\t\t\tmodTime: n.modTime.getTime(),\n\t\t\t})),\n\t\t\taxons: region.axons,\n\t\t})),\n\t\tbombSource: result.bombSource || null,\n\t\tfiredNeurons: result.firedNeurons,\n\t\ttotalNeurons: result.totalNeurons,\n\t\ttotalCounter: result.totalCounter,\n\t};\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// HTTP Helpers\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nfunction json(res: ServerResponse, data: unknown, status = 200): void {\n\tconst body = JSON.stringify(data);\n\tres.writeHead(status, {\n\t\t'Content-Type': 'application/json',\n\t\t'Access-Control-Allow-Origin': '*',\n\t\t'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n\t\t'Access-Control-Allow-Headers': 'Content-Type',\n\t});\n\tres.end(body);\n}\n\nfunction error(res: ServerResponse, message: string, status = 400): void {\n\tjson(res, { error: message }, status);\n}\n\nasync function readBody(req: IncomingMessage): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks: Buffer[] = [];\n\t\treq.on('data', (chunk: Buffer) => chunks.push(chunk));\n\t\treq.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n\t\treq.on('error', reject);\n\t});\n}\n\nasync function parseJSON(req: IncomingMessage): Promise<Record<string, unknown>> {\n\tconst body = await readBody(req);\n\tif (!body.trim()) return {};\n\treturn JSON.parse(body) as Record<string, unknown>;\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// Route Handlers\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nasync function handleRequest(\n\treq: IncomingMessage,\n\tres: ServerResponse,\n\tbrainRoot: string,\n): Promise<void> {\n\tconst url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);\n\tconst path = url.pathname;\n\tconst method = req.method || 'GET';\n\n\t// CORS preflight\n\tif (method === 'OPTIONS') {\n\t\tjson(res, null, 204);\n\t\treturn;\n\t}\n\n\t// Track activity on mutations\n\tconst isMutation = method === 'POST';\n\tif (isMutation) lastAPIActivity = Date.now();\n\n\ttry {\n\t\t// GET endpoints\n\t\tif (method === 'GET') {\n\t\t\tswitch (path) {\n\t\t\t\tcase '/api/health':\n\t\t\t\t\tjson(res, buildHealthJSON(brainRoot));\n\t\t\t\t\treturn;\n\t\t\t\tcase '/api/brain':\n\t\t\t\t\tjson(res, buildBrainJSON(brainRoot));\n\t\t\t\t\treturn;\n\t\t\t\tcase '/api/read': {\n\t\t\t\t\tconst region = url.searchParams.get('region');\n\t\t\t\t\tif (!region || !(REGIONS as readonly string[]).includes(region)) {\n\t\t\t\t\t\terror(res, `Invalid region. Valid: ${REGIONS.join(', ')}`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst brain = scanBrain(brainRoot);\n\t\t\t\t\tconst result = runSubsumption(brain);\n\t\t\t\t\tconst regionData = result.activeRegions.find((r) => r.name === region);\n\t\t\t\t\tif (!regionData) {\n\t\t\t\t\t\terror(res, `Region \"${region}\" is blocked or empty`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Auto-fire top 3 for RAG retrieval\n\t\t\t\t\tconst top3 = [...regionData.neurons]\n\t\t\t\t\t\t.filter((n) => !n.isDormant)\n\t\t\t\t\t\t.sort((a, b) => b.counter - a.counter)\n\t\t\t\t\t\t.slice(0, 3);\n\t\t\t\t\tfor (const n of top3) {\n\t\t\t\t\t\tfireNeuron(brainRoot, `${region}/${n.path}`);\n\t\t\t\t\t}\n\t\t\t\t\tjson(res, {\n\t\t\t\t\t\tregion: region,\n\t\t\t\t\t\tneurons: regionData.neurons,\n\t\t\t\t\t\tfired: top3.map((n) => n.path),\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/reports':\n\t\t\t\t\tjson(res, { reports: pendingReports });\n\t\t\t\t\treturn;\n\t\t\t\tdefault:\n\t\t\t\t\terror(res, 'Not found', 404);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// POST endpoints\n\t\tif (method === 'POST') {\n\t\t\tconst body = await parseJSON(req);\n\n\t\t\tswitch (path) {\n\t\t\t\tcase '/api/grow': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tif (!neuronPath) { error(res, 'Missing \"path\"'); return; }\n\t\t\t\t\tconst result = growNeuron(brainRoot, neuronPath);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/fire': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tif (!neuronPath) { error(res, 'Missing \"path\"'); return; }\n\t\t\t\t\tconst counter = fireNeuron(brainRoot, neuronPath);\n\t\t\t\t\tjson(res, { path: neuronPath, counter });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/signal': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tconst signalType = body.type as string;\n\t\t\t\t\tif (!neuronPath || !signalType) { error(res, 'Missing \"path\" or \"type\"'); return; }\n\t\t\t\t\tsignalNeuron(brainRoot, neuronPath, signalType as SignalType);\n\t\t\t\t\tjson(res, { path: neuronPath, type: signalType });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/rollback': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tif (!neuronPath) { error(res, 'Missing \"path\"'); return; }\n\t\t\t\t\tconst counter = rollbackNeuron(brainRoot, neuronPath);\n\t\t\t\t\tjson(res, { path: neuronPath, counter });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/decay': {\n\t\t\t\t\tconst days = typeof body.days === 'number' ? body.days : 30;\n\t\t\t\t\tconst result = runDecay(brainRoot, days);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/dedup': {\n\t\t\t\t\tconst result = runDedup(brainRoot);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/inject': {\n\t\t\t\t\tconst brain = scanBrain(brainRoot);\n\t\t\t\t\tconst result = runSubsumption(brain);\n\t\t\t\t\twriteAllTiers(brainRoot, result, brain);\n\t\t\t\t\tjson(res, { injected: true });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/inbox': {\n\t\t\t\t\tconst result = processInbox(brainRoot);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/report': {\n\t\t\t\t\tconst message = body.message as string;\n\t\t\t\t\tconst priority = (body.priority as string) || 'normal';\n\t\t\t\t\tif (!message) { error(res, 'Missing \"message\"'); return; }\n\t\t\t\t\tconst entry: ReportEntry = {\n\t\t\t\t\t\tts: new Date().toISOString(),\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tpriority: priority as ReportEntry['priority'],\n\t\t\t\t\t};\n\t\t\t\t\tpendingReports.push(entry);\n\t\t\t\t\tjson(res, entry);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\terror(res, 'Not found', 404);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\terror(res, 'Method not allowed', 405);\n\t} catch (err) {\n\t\terror(res, (err as Error).message, 500);\n\t}\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// Server\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Start the hebbian REST API server.\n */\nexport function startAPI(brainRoot: string, port = 9090): ReturnType<typeof createServer> {\n\tconst server = createServer((req, res) => {\n\t\thandleRequest(req, res, brainRoot).catch((err) => {\n\t\t\terror(res, (err as Error).message, 500);\n\t\t});\n\t});\n\n\tserver.listen(port, () => {\n\t\tconsole.log(`🧠 hebbian API listening on http://localhost:${port}`);\n\t\tconsole.log(` Brain: ${brainRoot}`);\n\t\tconsole.log('');\n\t\tconsole.log(' Endpoints:');\n\t\tconsole.log(' GET /api/health Process health + brain stats');\n\t\tconsole.log(' GET /api/brain Full brain state JSON');\n\t\tconsole.log(' GET /api/read?region=X Read region (auto-fires top 3)');\n\t\tconsole.log(' GET /api/reports List pending reports');\n\t\tconsole.log(' POST /api/grow {\"path\":\"cortex/...\"}');\n\t\tconsole.log(' POST /api/fire {\"path\":\"cortex/...\"}');\n\t\tconsole.log(' POST /api/signal {\"path\":\"...\",\"type\":\"dopamine\"}');\n\t\tconsole.log(' POST /api/rollback {\"path\":\"cortex/...\"}');\n\t\tconsole.log(' POST /api/decay {\"days\":30}');\n\t\tconsole.log(' POST /api/dedup Batch merge similar neurons');\n\t\tconsole.log(' POST /api/inject Force re-emit all tiers');\n\t\tconsole.log(' POST /api/inbox Process corrections inbox');\n\t\tconsole.log(' POST /api/report {\"message\":\"...\",\"priority\":\"normal\"}');\n\t});\n\n\treturn server;\n}\n\n/**\n * Get the last API activity timestamp.\n */\nexport function getLastActivity(): number {\n\treturn lastAPIActivity;\n}\n\n/**\n * Get pending reports (for external access).\n */\nexport function getPendingReports(): ReportEntry[] {\n\treturn pendingReports;\n}\n\n/**\n * Clear pending reports.\n */\nexport function clearReports(): void {\n\tpendingReports.length = 0;\n}\n","// hebbian — Claude Code Hooks Integration\n//\n// Manages Claude Code hooks in .claude/settings.local.json.\n// Uses [hebbian] statusMessage marker for ownership tracking.\n//\n// SessionStart hook: refreshes CLAUDE.md with latest brain state\n// Stop hook: digests conversation transcript for corrections\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { HOOK_MARKER } from './constants';\n\nconst SETTINGS_DIR = '.claude';\nconst SETTINGS_FILE = 'settings.local.json';\n\nexport interface HookStatus {\n\tinstalled: boolean;\n\tpath: string;\n\tevents: string[];\n}\n\ninterface HookEntry {\n\ttype: string;\n\tcommand: string;\n\ttimeout?: number;\n\tstatusMessage?: string;\n}\n\ninterface HookGroup {\n\tmatcher?: string;\n\thooks: HookEntry[];\n}\n\n/**\n * Install hebbian hooks into .claude/settings.local.json.\n * Deep-merges with existing settings. Uses statusMessage marker for ownership.\n */\nexport function installHooks(brainRoot: string, projectRoot?: string): void {\n\tconst root = projectRoot || process.cwd();\n\tconst settingsDir = join(root, SETTINGS_DIR);\n\tconst settingsPath = join(settingsDir, SETTINGS_FILE);\n\n\t// Determine if we need --brain flag\n\tconst defaultBrain = resolve(root, 'brain');\n\tconst resolvedBrain = resolve(brainRoot);\n\tconst brainFlag = resolvedBrain === defaultBrain ? '' : ` --brain ${resolvedBrain}`;\n\n\t// Read existing settings or start fresh\n\tlet settings: Record<string, unknown> = {};\n\tif (existsSync(settingsPath)) {\n\t\ttry {\n\t\t\tsettings = JSON.parse(readFileSync(settingsPath, 'utf8'));\n\t\t} catch {\n\t\t\tconsole.log(`\\u26A0\\uFE0F settings.local.json was malformed, overwriting`);\n\t\t}\n\t}\n\n\t// Ensure hooks object exists\n\tif (!settings.hooks || typeof settings.hooks !== 'object') {\n\t\tsettings.hooks = {};\n\t}\n\tconst hooks = settings.hooks as Record<string, HookGroup[]>;\n\n\t// Define hebbian hooks\n\tconst hebbianHooks: Array<{ event: string; matcher?: string; entry: HookEntry }> = [\n\t\t{\n\t\t\tevent: 'SessionStart',\n\t\t\tmatcher: 'startup|resume',\n\t\t\tentry: {\n\t\t\t\ttype: 'command',\n\t\t\t\tcommand: `hebbian emit claude${brainFlag}`,\n\t\t\t\ttimeout: 10,\n\t\t\t\tstatusMessage: `${HOOK_MARKER} refreshing brain`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tevent: 'Stop',\n\t\t\tentry: {\n\t\t\t\ttype: 'command',\n\t\t\t\tcommand: `hebbian digest${brainFlag}`,\n\t\t\t\ttimeout: 30,\n\t\t\t\tstatusMessage: `${HOOK_MARKER} digesting session`,\n\t\t\t},\n\t\t},\n\t];\n\n\t// Install each hook\n\tfor (const { event, matcher, entry } of hebbianHooks) {\n\t\tif (!hooks[event]) {\n\t\t\thooks[event] = [];\n\t\t}\n\n\t\t// Find existing hebbian group for this event\n\t\tconst existingIdx = hooks[event]!.findIndex((group) =>\n\t\t\tgroup.hooks.some((h) => h.statusMessage?.startsWith(HOOK_MARKER)),\n\t\t);\n\n\t\tconst group: HookGroup = {\n\t\t\t...(matcher ? { matcher } : {}),\n\t\t\thooks: [entry],\n\t\t};\n\n\t\tif (existingIdx >= 0) {\n\t\t\t// Update existing entry\n\t\t\thooks[event]![existingIdx] = group;\n\t\t} else {\n\t\t\t// Append new entry\n\t\t\thooks[event]!.push(group);\n\t\t}\n\t}\n\n\t// Write back\n\tif (!existsSync(settingsDir)) {\n\t\tmkdirSync(settingsDir, { recursive: true });\n\t}\n\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf8');\n\n\tconsole.log(`\\u2705 hebbian hooks installed at ${settingsPath}`);\n\tconsole.log(` SessionStart \\u2192 hebbian emit claude${brainFlag}`);\n\tconsole.log(` Stop \\u2192 hebbian digest${brainFlag}`);\n}\n\n/**\n * Remove hebbian hooks from .claude/settings.local.json.\n * Preserves non-hebbian hooks and other settings.\n */\nexport function uninstallHooks(projectRoot?: string): void {\n\tconst root = projectRoot || process.cwd();\n\tconst settingsPath = join(root, SETTINGS_DIR, SETTINGS_FILE);\n\n\tif (!existsSync(settingsPath)) {\n\t\tconsole.log('No hooks installed (settings.local.json not found)');\n\t\treturn;\n\t}\n\n\tlet settings: Record<string, unknown>;\n\ttry {\n\t\tsettings = JSON.parse(readFileSync(settingsPath, 'utf8'));\n\t} catch {\n\t\tconsole.log('settings.local.json is malformed, nothing to uninstall');\n\t\treturn;\n\t}\n\n\tif (!settings.hooks || typeof settings.hooks !== 'object') {\n\t\tconsole.log('No hooks found in settings.local.json');\n\t\treturn;\n\t}\n\n\tconst hooks = settings.hooks as Record<string, HookGroup[]>;\n\tlet removed = 0;\n\n\tfor (const event of Object.keys(hooks)) {\n\t\tconst before = hooks[event]!.length;\n\t\thooks[event] = hooks[event]!.filter(\n\t\t\t(group) => !group.hooks.some((h) => h.statusMessage?.startsWith(HOOK_MARKER)),\n\t\t);\n\t\tremoved += before - hooks[event]!.length;\n\n\t\t// Clean up empty event arrays\n\t\tif (hooks[event]!.length === 0) {\n\t\t\tdelete hooks[event];\n\t\t}\n\t}\n\n\t// Clean up empty hooks object\n\tif (Object.keys(hooks).length === 0) {\n\t\tdelete settings.hooks;\n\t}\n\n\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf8');\n\tconsole.log(`\\u2705 removed ${removed} hebbian hook(s) from ${settingsPath}`);\n}\n\n/**\n * Check if hebbian hooks are installed.\n */\nexport function checkHooks(projectRoot?: string): HookStatus {\n\tconst root = projectRoot || process.cwd();\n\tconst settingsPath = join(root, SETTINGS_DIR, SETTINGS_FILE);\n\n\tconst status: HookStatus = {\n\t\tinstalled: false,\n\t\tpath: settingsPath,\n\t\tevents: [],\n\t};\n\n\tif (!existsSync(settingsPath)) {\n\t\tconsole.log(`\\u274C hebbian hooks not installed (${settingsPath} not found)`);\n\t\treturn status;\n\t}\n\n\tlet settings: Record<string, unknown>;\n\ttry {\n\t\tsettings = JSON.parse(readFileSync(settingsPath, 'utf8'));\n\t} catch {\n\t\tconsole.log(`\\u274C settings.local.json is malformed`);\n\t\treturn status;\n\t}\n\n\tif (!settings.hooks || typeof settings.hooks !== 'object') {\n\t\tconsole.log(`\\u274C no hooks in ${settingsPath}`);\n\t\treturn status;\n\t}\n\n\tconst hooks = settings.hooks as Record<string, HookGroup[]>;\n\n\tfor (const event of Object.keys(hooks)) {\n\t\tconst hasHebbian = hooks[event]!.some((group) =>\n\t\t\tgroup.hooks.some((h) => h.statusMessage?.startsWith(HOOK_MARKER)),\n\t\t);\n\t\tif (hasHebbian) {\n\t\t\tstatus.events.push(event);\n\t\t}\n\t}\n\n\tstatus.installed = status.events.length > 0;\n\n\tif (status.installed) {\n\t\tconsole.log(`\\u2705 hebbian hooks installed at ${settingsPath}`);\n\t\tfor (const event of status.events) {\n\t\t\tconsole.log(` ${event} \\u2714`);\n\t\t}\n\t} else {\n\t\tconsole.log(`\\u274C hebbian hooks not found in ${settingsPath}`);\n\t}\n\n\treturn status;\n}\n","// hebbian — Conversation Digest (Correction Extraction)\n//\n// Parses Claude Code conversation transcripts (JSONL) and extracts\n// user corrections via pattern matching. Writes corrections to inbox,\n// auto-processes them, and logs an audit trail.\n//\n// Correction detection is deliberately heuristic — WS3 candidate staging\n// is the quality safety net for false positives.\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join, basename } from 'node:path';\nimport { MAX_CORRECTIONS_PER_SESSION, MIN_CORRECTION_LENGTH, DIGEST_LOG_DIR } from './constants';\nimport { growNeuron } from './grow';\nimport { logEpisode } from './episode';\nimport { tokenize } from './similarity';\n\nexport interface DigestResult {\n\tcorrections: number;\n\tskipped: number;\n\ttranscriptPath: string;\n\tsessionId: string;\n}\n\nexport interface ExtractedCorrection {\n\ttext: string;\n\tpath: string;\n\tprefix: 'NO' | 'DO';\n\tkeywords: string[];\n}\n\ninterface TranscriptLine {\n\ttype?: string;\n\tmessage?: {\n\t\trole?: string;\n\t\tcontent?: string | Array<{ type: string; text?: string }>;\n\t};\n\tsessionId?: string;\n\tuuid?: string;\n}\n\n// Negation patterns — user is telling the AI NOT to do something\nconst NEGATION_PATTERNS = [\n\t/\\bdon[''\\u2019]?t\\b/i,\n\t/\\bdo not\\b/i,\n\t/\\bstop\\s+\\w+ing\\b/i,\n\t/\\bnever\\b/i,\n\t/\\binstead\\b/i,\n\t/^no[,.\\s!]/i,\n\t/\\bdon[''\\u2019]?t\\s+use\\b/i,\n\t/\\bavoid\\b/i,\n\t// Korean negation\n\t/하지\\s*마/,\n\t/안\\s*돼/,\n\t/대신/,\n\t/쓰지\\s*마/,\n\t/않/,\n];\n\n// Affirmation patterns — user is telling the AI TO do something\nconst AFFIRMATION_PATTERNS = [\n\t/\\balways\\b/i,\n\t/\\bmust\\b/i,\n\t/\\bshould\\s+always\\b/i,\n\t/\\buse\\s+\\w+\\s+instead\\b/i,\n\t// Korean affirmation\n\t/항상/,\n\t/반드시/,\n];\n\n/**\n * Parse hook input from stdin to extract transcript path and session ID.\n */\nexport function readHookInput(stdin: string): { transcriptPath: string; sessionId: string } | null {\n\tif (!stdin.trim()) return null;\n\ttry {\n\t\tconst input = JSON.parse(stdin);\n\t\tif (input.transcript_path) {\n\t\t\tconst sessionId = input.session_id || basename(input.transcript_path, '.jsonl');\n\t\t\treturn { transcriptPath: input.transcript_path, sessionId };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Digest a conversation transcript and extract corrections.\n * Auto-processes inbox and writes audit log.\n */\nexport function digestTranscript(brainRoot: string, transcriptPath: string, sessionId?: string): DigestResult {\n\tif (!existsSync(transcriptPath)) {\n\t\tthrow new Error(`Transcript not found: ${transcriptPath}`);\n\t}\n\n\tconst resolvedSessionId = sessionId || basename(transcriptPath, '.jsonl');\n\n\t// Dedup check: skip if already digested\n\tconst logDir = join(brainRoot, DIGEST_LOG_DIR);\n\tconst logPath = join(logDir, `${resolvedSessionId}.jsonl`);\n\tif (existsSync(logPath)) {\n\t\tconsole.log(`\\u23ED already digested session ${resolvedSessionId}, skip`);\n\t\treturn { corrections: 0, skipped: 0, transcriptPath, sessionId: resolvedSessionId };\n\t}\n\n\t// Parse transcript\n\tconst messages = parseTranscript(transcriptPath);\n\n\t// Extract corrections\n\tconst corrections = extractCorrections(messages);\n\n\tif (corrections.length === 0) {\n\t\tconsole.log(`\\uD83D\\uDCDD digest: no corrections found in session ${resolvedSessionId}`);\n\t\t// Write empty audit log to mark as digested\n\t\twriteAuditLog(brainRoot, resolvedSessionId, []);\n\t\treturn { corrections: 0, skipped: messages.length, transcriptPath, sessionId: resolvedSessionId };\n\t}\n\n\t// Apply corrections via growNeuron (handles Jaccard dedup internally)\n\tlet applied = 0;\n\tconst auditEntries: Array<{ correction: ExtractedCorrection; applied: boolean }> = [];\n\n\tfor (const correction of corrections) {\n\t\ttry {\n\t\t\tgrowNeuron(brainRoot, correction.path);\n\t\t\tlogEpisode(brainRoot, 'digest', correction.path, correction.text);\n\t\t\tauditEntries.push({ correction, applied: true });\n\t\t\tapplied++;\n\t\t} catch (err) {\n\t\t\tconsole.log(` \\u26A0\\uFE0F failed to apply: ${correction.path} — ${(err as Error).message}`);\n\t\t\tauditEntries.push({ correction, applied: false });\n\t\t}\n\t}\n\n\t// Write audit log\n\twriteAuditLog(brainRoot, resolvedSessionId, auditEntries);\n\n\tconsole.log(`\\uD83D\\uDCDD digest: ${applied} correction(s) from session ${resolvedSessionId}`);\n\treturn {\n\t\tcorrections: applied,\n\t\tskipped: messages.length - corrections.length,\n\t\ttranscriptPath,\n\t\tsessionId: resolvedSessionId,\n\t};\n}\n\n/**\n * Parse a Claude Code conversation JSONL transcript.\n * Returns user message texts only.\n */\nfunction parseTranscript(transcriptPath: string): string[] {\n\tconst content = readFileSync(transcriptPath, 'utf8');\n\tconst lines = content.split('\\n').filter(Boolean);\n\tconst messages: string[] = [];\n\n\tfor (const line of lines) {\n\t\tlet entry: TranscriptLine;\n\t\ttry {\n\t\t\tentry = JSON.parse(line);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Only process user messages\n\t\tif (entry.type !== 'user') continue;\n\t\tif (!entry.message || entry.message.role !== 'user') continue;\n\n\t\tconst text = extractText(entry.message.content);\n\t\tif (text) messages.push(text);\n\t}\n\n\treturn messages;\n}\n\n/**\n * Extract text from message content (handles string or content block array).\n */\nfunction extractText(content: string | Array<{ type: string; text?: string }> | undefined): string | null {\n\tif (!content) return null;\n\tif (typeof content === 'string') return content;\n\tif (Array.isArray(content)) {\n\t\tconst texts = content\n\t\t\t.filter((block) => block.type === 'text' && block.text)\n\t\t\t.map((block) => block.text!);\n\t\treturn texts.length > 0 ? texts.join('\\n') : null;\n\t}\n\treturn null;\n}\n\n/**\n * Extract corrections from user messages using pattern matching.\n * Returns up to MAX_CORRECTIONS_PER_SESSION corrections.\n */\nexport function extractCorrections(messages: string[]): ExtractedCorrection[] {\n\tconst corrections: ExtractedCorrection[] = [];\n\n\tfor (const text of messages) {\n\t\tif (corrections.length >= MAX_CORRECTIONS_PER_SESSION) break;\n\n\t\t// Skip short messages\n\t\tif (text.length < MIN_CORRECTION_LENGTH) continue;\n\n\t\t// Skip commands (start with / or !)\n\t\tif (/^[\\/!]/.test(text.trim())) continue;\n\n\t\t// Skip questions (end with ?)\n\t\tif (text.trim().endsWith('?')) continue;\n\n\t\t// Check for correction patterns\n\t\tconst correction = detectCorrection(text);\n\t\tif (correction) {\n\t\t\tcorrections.push(correction);\n\t\t}\n\t}\n\n\treturn corrections;\n}\n\n/**\n * Detect if a message is a correction and extract structured data.\n */\nfunction detectCorrection(text: string): ExtractedCorrection | null {\n\tconst isNegation = NEGATION_PATTERNS.some((p) => p.test(text));\n\tconst isAffirmation = AFFIRMATION_PATTERNS.some((p) => p.test(text));\n\n\tif (!isNegation && !isAffirmation) return null;\n\n\tconst prefix = isNegation ? 'NO' : 'DO';\n\tconst keywords = extractKeywords(text);\n\n\tif (keywords.length === 0) return null;\n\n\t// Build neuron path: cortex/{PREFIX}_{keyword1}_{keyword2}\n\tconst pathSegment = `${prefix}_${keywords.slice(0, 4).join('_')}`;\n\tconst path = `cortex/${pathSegment}`;\n\n\treturn { text, path, prefix, keywords };\n}\n\n/**\n * Extract meaningful keywords from correction text.\n * Filters out common stop words and correction-specific words.\n */\nfunction extractKeywords(text: string): string[] {\n\tconst STOP_WORDS = new Set([\n\t\t'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',\n\t\t'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',\n\t\t'should', 'may', 'might', 'shall', 'can', 'need', 'dare', 'ought',\n\t\t'to', 'of', 'in', 'for', 'on', 'with', 'at', 'by', 'from', 'as',\n\t\t'into', 'through', 'during', 'before', 'after', 'above', 'below',\n\t\t'and', 'but', 'or', 'nor', 'not', 'so', 'yet', 'both', 'either',\n\t\t'neither', 'each', 'every', 'all', 'any', 'few', 'more', 'most',\n\t\t'other', 'some', 'such', 'no', 'only', 'own', 'same', 'than',\n\t\t'too', 'very', 'just', 'because', 'until', 'while', 'that', 'this',\n\t\t'these', 'those', 'it', 'its', 'i', 'me', 'my', 'we', 'us', 'you',\n\t\t'your', 'he', 'she', 'they', 'them', 'what', 'which', 'who', 'whom',\n\t\t// Correction-specific stop words\n\t\t'don', 'dont', 'stop', 'never', 'always', 'instead', 'use', 'avoid',\n\t\t'please', 'must', 'should', 'like', 'want', 'think',\n\t]);\n\n\tconst tokens = tokenize(text);\n\treturn tokens.filter((t) => !STOP_WORDS.has(t) && t.length > 2);\n}\n\n/**\n * Write audit log for digest session.\n */\nfunction writeAuditLog(\n\tbrainRoot: string,\n\tsessionId: string,\n\tentries: Array<{ correction: ExtractedCorrection; applied: boolean }>,\n): void {\n\tconst logDir = join(brainRoot, DIGEST_LOG_DIR);\n\tif (!existsSync(logDir)) {\n\t\tmkdirSync(logDir, { recursive: true });\n\t}\n\n\tconst logPath = join(logDir, `${sessionId}.jsonl`);\n\tconst lines = entries.map((e) =>\n\t\tJSON.stringify({\n\t\t\tts: new Date().toISOString(),\n\t\t\tpath: e.correction.path,\n\t\t\ttext: e.correction.text,\n\t\t\tprefix: e.correction.prefix,\n\t\t\tkeywords: e.correction.keywords,\n\t\t\tapplied: e.applied,\n\t\t}),\n\t);\n\n\t// Even if no entries, write empty file as dedup marker\n\twriteFileSync(logPath, lines.join('\\n') + (lines.length > 0 ? '\\n' : ''), 'utf8');\n}\n","// hebbian — Folder-as-Neuron Brain for Any AI Agent\n//\n// \"Neurons that fire together, wire together.\" — Donald Hebb (1949)\n//\n// USAGE:\n// hebbian init <path> Create brain with 7 regions\n// hebbian emit <target> [--brain <path>] Compile rules (claude/cursor/gemini/copilot/generic/all)\n// hebbian fire <neuron-path> Increment neuron counter\n// hebbian grow <neuron-path> Create neuron (with merge detection)\n// hebbian rollback <neuron-path> Decrement counter (min=1)\n// hebbian signal <type> <neuron-path> Add dopamine/bomb/memory signal\n// hebbian decay [--days N] Mark inactive neurons dormant (default 30 days)\n// hebbian watch [--brain <path>] Watch for changes + auto-recompile\n// hebbian claude install|uninstall|status Manage Claude Code hooks\n// hebbian digest [--transcript <path>] Extract corrections from conversation\n// hebbian diag Print brain diagnostics\n// hebbian stats Print brain statistics\n\nimport { parseArgs } from 'node:util';\nimport { resolve } from 'node:path';\nimport type { SignalType } from './constants';\nimport { resolveBrainRoot } from './constants';\n\nconst VERSION = '0.3.0';\n\nconst HELP = `\nhebbian v${VERSION} — Folder-as-neuron brain for any AI agent.\n\n \"Neurons that fire together, wire together.\" — Donald Hebb (1949)\n\nUSAGE:\n hebbian <command> [options]\n\nCOMMANDS:\n init <path> Create brain with 7 regions\n emit <target> [--brain <path>] Compile rules (claude/cursor/gemini/copilot/generic/all)\n fire <neuron-path> Increment neuron counter (+1)\n grow <neuron-path> Create neuron (with merge detection)\n rollback <neuron-path> Decrement neuron counter (min=1)\n signal <type> <neuron-path> Add signal (dopamine/bomb/memory)\n decay [--days N] Mark inactive neurons dormant (default 30)\n dedup Batch merge similar neurons (Jaccard >= 0.6)\n snapshot Git commit current brain state\n watch Watch for changes + auto-recompile\n api [--port N] Start REST API server (default 9090)\n inbox Process corrections inbox\n claude install|uninstall|status Manage Claude Code hooks\n digest [--transcript <path>] Extract corrections from conversation\n diag Print brain diagnostics\n stats Print brain statistics\n\nOPTIONS:\n --brain <path> Brain directory (default: $HEBBIAN_BRAIN or ./brain)\n --help, -h Show this help\n --version, -v Show version\n\nEXAMPLES:\n hebbian init ./my-brain\n hebbian grow cortex/frontend/NO_console_log --brain ./my-brain\n hebbian fire cortex/frontend/NO_console_log --brain ./my-brain\n hebbian emit claude --brain ./my-brain\n hebbian emit all\n`.trim();\n\n/** Read all data from stdin (non-blocking, returns empty string if no data). */\nfunction readStdin(): Promise<string> {\n\treturn new Promise((resolve) => {\n\t\tif (process.stdin.isTTY) {\n\t\t\tresolve('');\n\t\t\treturn;\n\t\t}\n\t\tconst chunks: Buffer[] = [];\n\t\tprocess.stdin.on('data', (chunk: Buffer) => chunks.push(chunk));\n\t\tprocess.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n\t\tprocess.stdin.on('error', () => resolve(''));\n\t\t// Timeout after 1s to avoid hanging\n\t\tsetTimeout(() => {\n\t\t\tprocess.stdin.destroy();\n\t\t\tresolve(Buffer.concat(chunks).toString('utf8'));\n\t\t}, 1000);\n\t});\n}\n\nasync function main(argv: string[]): Promise<void> {\n\tconst { values, positionals } = parseArgs({\n\t\targs: argv,\n\t\toptions: {\n\t\t\tbrain: { type: 'string', short: 'b' },\n\t\t\tdays: { type: 'string', short: 'd' },\n\t\t\tport: { type: 'string', short: 'p' },\n\t\t\ttranscript: { type: 'string', short: 't' },\n\t\t\thelp: { type: 'boolean', short: 'h' },\n\t\t\tversion: { type: 'boolean', short: 'v' },\n\t\t},\n\t\tallowPositionals: true,\n\t\tstrict: false,\n\t});\n\n\tif (values.version) {\n\t\tconsole.log(`hebbian v${VERSION}`);\n\t\treturn;\n\t}\n\n\tconst command = positionals[0];\n\n\tif (values.help || !command) {\n\t\tconsole.log(HELP);\n\t\treturn;\n\t}\n\n\tconst brainRoot = resolveBrainRoot(values.brain as string | undefined);\n\n\tswitch (command) {\n\t\tcase 'init': {\n\t\t\tconst target = positionals[1];\n\t\t\tif (!target) {\n\t\t\t\tconsole.error('Usage: hebbian init <path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { initBrain } = await import('./init');\n\t\t\tawait initBrain(resolve(target));\n\t\t\tbreak;\n\t\t}\n\t\tcase 'emit': {\n\t\t\tconst target = positionals[1];\n\t\t\tif (!target) {\n\t\t\t\tconsole.error('Usage: hebbian emit <target> (claude/cursor/gemini/copilot/generic/all)');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { emitToTarget } = await import('./emit');\n\t\t\tawait emitToTarget(brainRoot, target);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'fire': {\n\t\t\tconst neuronPath = positionals[1];\n\t\t\tif (!neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian fire <neuron-path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { fireNeuron } = await import('./fire');\n\t\t\tawait fireNeuron(brainRoot, neuronPath);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'grow': {\n\t\t\tconst neuronPath = positionals[1];\n\t\t\tif (!neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian grow <neuron-path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { growNeuron } = await import('./grow');\n\t\t\tawait growNeuron(brainRoot, neuronPath);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'rollback': {\n\t\t\tconst neuronPath = positionals[1];\n\t\t\tif (!neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian rollback <neuron-path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { rollbackNeuron } = await import('./rollback');\n\t\t\tawait rollbackNeuron(brainRoot, neuronPath);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'signal': {\n\t\t\tconst signalType = positionals[1];\n\t\t\tconst neuronPath = positionals[2];\n\t\t\tif (!signalType || !neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian signal <type> <neuron-path> (type: dopamine/bomb/memory)');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { signalNeuron } = await import('./signal');\n\t\t\tawait signalNeuron(brainRoot, neuronPath, signalType as SignalType);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'decay': {\n\t\t\tconst days = values.days ? parseInt(values.days as string, 10) : 30;\n\t\t\tconst { runDecay } = await import('./decay');\n\t\t\tawait runDecay(brainRoot, days);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'dedup': {\n\t\t\tconst { runDedup } = await import('./dedup');\n\t\t\trunDedup(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'snapshot': {\n\t\t\tconst { gitSnapshot } = await import('./snapshot');\n\t\t\tgitSnapshot(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'watch': {\n\t\t\tconst { startWatch } = await import('./watch');\n\t\t\tawait startWatch(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'api': {\n\t\t\tconst port = values.port ? parseInt(values.port as string, 10) : 9090;\n\t\t\tconst { startAPI } = await import('./api');\n\t\t\tstartAPI(brainRoot, port);\n\t\t\t// Keep process alive — server handles shutdown\n\t\t\tawait new Promise(() => {});\n\t\t\tbreak;\n\t\t}\n\t\tcase 'inbox': {\n\t\t\tconst { processInbox } = await import('./inbox');\n\t\t\tprocessInbox(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'claude': {\n\t\t\tconst sub = positionals[1];\n\t\t\tconst { installHooks, uninstallHooks, checkHooks } = await import('./hooks');\n\t\t\tswitch (sub) {\n\t\t\t\tcase 'install':\n\t\t\t\t\tinstallHooks(brainRoot);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'uninstall':\n\t\t\t\t\tuninstallHooks();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'status':\n\t\t\t\t\tcheckHooks();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tconsole.error('Usage: hebbian claude <install|uninstall|status>');\n\t\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'digest': {\n\t\t\tconst transcriptFlag = values.transcript as string | undefined;\n\t\t\tconst { digestTranscript, readHookInput } = await import('./digest');\n\t\t\tif (transcriptFlag) {\n\t\t\t\tdigestTranscript(brainRoot, resolve(transcriptFlag));\n\t\t\t} else {\n\t\t\t\t// Read stdin for hook input\n\t\t\t\tconst stdin = await readStdin();\n\t\t\t\tconst hookInput = readHookInput(stdin);\n\t\t\t\tif (hookInput) {\n\t\t\t\t\tdigestTranscript(brainRoot, hookInput.transcriptPath, hookInput.sessionId);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error('Usage: hebbian digest --transcript <path>');\n\t\t\t\t\tconsole.error(' Or pipe hook input via stdin (Claude Code Stop hook)');\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'diag':\n\t\tcase 'stats': {\n\t\t\tconst { scanBrain } = await import('./scanner');\n\t\t\tconst { runSubsumption } = await import('./subsumption');\n\t\t\tconst brain = scanBrain(brainRoot);\n\t\t\tconst result = runSubsumption(brain);\n\t\t\tconst { printDiag } = await import('./emit');\n\t\t\tprintDiag(brain, result);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tconsole.error(`Unknown command: ${command}`);\n\t\t\tconsole.log(HELP);\n\t\t\tprocess.exit(1);\n\t}\n}\n\nmain(process.argv.slice(2)).catch((err: Error) => {\n\tconsole.error(err.message);\n\tprocess.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;AA+EA,SAAS,eAAe;AACxB,SAAS,kBAAkB;AAGpB,SAAS,iBAAiB,WAA4B;AAC5D,MAAI,UAAW,QAAO,QAAQ,SAAS;AACvC,MAAI,QAAQ,IAAI,cAAe,QAAO,QAAQ,QAAQ,IAAI,aAAa;AACvE,MAAI,WAAW,QAAQ,SAAS,CAAC,EAAG,QAAO,QAAQ,SAAS;AAC5D,SAAO,QAAQ,QAAQ,IAAI,QAAQ,KAAK,WAAW,OAAO;AAC3D;AAxFA,IASa,SAYA,iBAUA,cAUA,WAUA,gBACA,gBACA,mBAEA,WAEA,cAQA,cAGA,cACA,YAGA,aAGA,6BACA,uBACA;AA7Eb;AAAA;AAAA;AASO,IAAM,UAAU;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAIO,IAAM,kBAA8C;AAAA,MAC1D,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,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AACC,kBAAQ,MAAM,kDAAkD;AAChE,kBAAQ,KAAK,CAAC;AAAA,MAChB;AACA;AAAA,IACD;AAAA,IACA,KAAK,UAAU;AACd,YAAM,iBAAiB,OAAO;AAC9B,YAAM,EAAE,kBAAAC,mBAAkB,eAAAC,eAAc,IAAI,MAAM;AAClD,UAAI,gBAAgB;AACnB,QAAAD,kBAAiB,WAAWhB,SAAQ,cAAc,CAAC;AAAA,MACpD,OAAO;AAEN,cAAM,QAAQ,MAAM,UAAU;AAC9B,cAAM,YAAYiB,eAAc,KAAK;AACrC,YAAI,WAAW;AACd,UAAAD,kBAAiB,WAAW,UAAU,gBAAgB,UAAU,SAAS;AAAA,QAC1E,OAAO;AACN,kBAAQ,MAAM,2CAA2C;AACzD,kBAAQ,MAAM,wDAAwD;AACtE,kBAAQ,KAAK,CAAC;AAAA,QACf;AAAA,MACD;AACA;AAAA,IACD;AAAA,IACA,KAAK;AAAA,IACL,KAAK,SAAS;AACb,YAAM,EAAE,WAAAE,WAAU,IAAI,MAAM;AAC5B,YAAM,EAAE,gBAAAC,gBAAe,IAAI,MAAM;AACjC,YAAM,QAAQD,WAAU,SAAS;AACjC,YAAM,SAASC,gBAAe,KAAK;AACnC,YAAM,EAAE,WAAAC,WAAU,IAAI,MAAM;AAC5B,MAAAA,WAAU,OAAO,MAAM;AACvB;AAAA,IACD;AAAA,IACA;AACC,cAAQ,MAAM,oBAAoB,OAAO,EAAE;AAC3C,cAAQ,IAAI,IAAI;AAChB,cAAQ,KAAK,CAAC;AAAA,EAChB;AACD;AAEA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,QAAe;AACjD,UAAQ,MAAM,IAAI,OAAO;AACzB,UAAQ,KAAK,CAAC;AACf,CAAC;","names":["existsSync","readdirSync","existsSync","join","existsSync","readFileSync","writeFileSync","mkdirSync","join","readdirSync","writeFileSync","existsSync","mkdirSync","join","mkdirSync","writeFileSync","existsSync","readdirSync","join","relative","renameSync","join","writeFileSync","existsSync","readdirSync","join","readdirSync","statSync","writeFileSync","existsSync","join","writeFileSync","join","existsSync","join","resolve","readdirSync","readFileSync","writeFileSync","mkdirSync","existsSync","join","readFileSync","writeFileSync","existsSync","mkdirSync","join","resolve","readFileSync","writeFileSync","existsSync","mkdirSync","join","resolve","group","readFileSync","writeFileSync","existsSync","mkdirSync","join","resolve","initBrain","emitToTarget","fireNeuron","growNeuron","rollbackNeuron","signalNeuron","runDecay","runDedup","gitSnapshot","startWatch","startAPI","processInbox","installHooks","uninstallHooks","checkHooks","digestTranscript","readHookInput","scanBrain","runSubsumption","printDiag"]}
1
+ {"version":3,"sources":["../../src/constants.ts","../../src/init.ts","../../src/scanner.ts","../../src/subsumption.ts","../../src/emit.ts","../../src/fire.ts","../../src/similarity.ts","../../src/grow.ts","../../src/rollback.ts","../../src/signal.ts","../../src/decay.ts","../../src/dedup.ts","../../src/snapshot.ts","../../src/watch.ts","../../src/episode.ts","../../src/inbox.ts","../../src/api.ts","../../src/hooks.ts","../../src/digest.ts","../../src/cli.ts"],"sourcesContent":["// hebbian — Constants & Configuration\n//\n// AXIOMS:\n// 1. Folder = Neuron (name is meaning, depth is specificity)\n// 2. File = Firing Trace (N.neuron = counter, dopamineN = reward, bomb = pain)\n// 3. Path = Sentence (brain/cortex/quality/no_hardcoded → \"cortex > quality > no_hardcoded\")\n// 4. Counter = Activation (higher = stronger/myelinated path)\n// 5. AI writes back (counter increment = experience growth)\n\nexport const REGIONS = [\n\t'brainstem',\n\t'limbic',\n\t'hippocampus',\n\t'sensors',\n\t'cortex',\n\t'ego',\n\t'prefrontal',\n] as const;\n\nexport type RegionName = (typeof REGIONS)[number];\n\nexport const REGION_PRIORITY: Record<RegionName, number> = {\n\tbrainstem: 0,\n\tlimbic: 1,\n\thippocampus: 2,\n\tsensors: 3,\n\tcortex: 4,\n\tego: 5,\n\tprefrontal: 6,\n};\n\nexport const REGION_ICONS: Record<RegionName, string> = {\n\tbrainstem: '🛡️',\n\tlimbic: '💓',\n\thippocampus: '📝',\n\tsensors: '👁️',\n\tcortex: '🧠',\n\tego: '🎭',\n\tprefrontal: '🎯',\n};\n\nexport const REGION_KO: Record<RegionName, string> = {\n\tbrainstem: '양심/본능',\n\tlimbic: '감정 필터',\n\thippocampus: '기록/기억',\n\tsensors: '환경 제약',\n\tcortex: '지식/기술',\n\tego: '성향/톤',\n\tprefrontal: '목표/계획',\n};\n\nexport const EMIT_THRESHOLD = 5;\nexport const SPOTLIGHT_DAYS = 7;\nexport const JACCARD_THRESHOLD = 0.6;\nexport const DECAY_DAYS = 30;\nexport const MAX_DEPTH = 6;\n\nexport const EMIT_TARGETS: Record<string, string> = {\n\tgemini: '.gemini/GEMINI.md',\n\tcursor: '.cursorrules',\n\tclaude: 'CLAUDE.md',\n\tcopilot: '.github/copilot-instructions.md',\n\tgeneric: '.neuronrc',\n};\n\nexport const SIGNAL_TYPES = ['dopamine', 'bomb', 'memory'] as const;\nexport type SignalType = (typeof SIGNAL_TYPES)[number];\n\nexport const MARKER_START = '<!-- HEBBIAN:START -->';\nexport const MARKER_END = '<!-- HEBBIAN:END -->';\n\n// Hook ownership marker — used to identify hebbian-managed hooks in settings.local.json\nexport const HOOK_MARKER = '[hebbian]';\n\n// Digest constants\nexport const MAX_CORRECTIONS_PER_SESSION = 10;\nexport const MIN_CORRECTION_LENGTH = 15;\nexport const DIGEST_LOG_DIR = 'hippocampus/digest_log';\n\nimport { resolve } from 'node:path';\nimport { existsSync } from 'node:fs';\n\n/** Resolve brain root path from flag, env var, or defaults */\nexport function resolveBrainRoot(brainFlag?: string): string {\n\tif (brainFlag) return resolve(brainFlag);\n\tif (process.env.HEBBIAN_BRAIN) return resolve(process.env.HEBBIAN_BRAIN);\n\tif (existsSync(resolve('./brain'))) return resolve('./brain');\n\treturn resolve(process.env.HOME || '~', 'hebbian', 'brain');\n}\n","// hebbian — Brain Initialization\n//\n// Creates a brain directory with 7 canonical regions and starter neurons.\n// Each region gets a _rules.md explaining its purpose.\n\nimport { mkdirSync, writeFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { REGIONS, REGION_ICONS, REGION_KO } from './constants';\nimport type { RegionName } from './constants';\n\ninterface RegionTemplate {\n\tdescription: string;\n\tstarters: string[];\n}\n\nconst REGION_TEMPLATES: Record<RegionName, RegionTemplate> = {\n\tbrainstem: {\n\t\tdescription: 'Absolute principles. Immutable. Read-only conscience.\\nP0 — highest priority. bomb here halts EVERYTHING.',\n\t\tstarters: ['NO_fallback', 'DO_execute_not_debate'],\n\t},\n\tlimbic: {\n\t\tdescription: 'Emotional filters and somatic markers.\\nP1 — automatic, influences downstream regions.',\n\t\tstarters: [],\n\t},\n\thippocampus: {\n\t\tdescription: 'Memory and episode recording.\\nP2 — accumulated experience, session logs.',\n\t\tstarters: [],\n\t},\n\tsensors: {\n\t\tdescription: 'Environment constraints and input validation.\\nP3 — read-only, set by environment.',\n\t\tstarters: [],\n\t},\n\tcortex: {\n\t\tdescription: 'Knowledge and skills. The largest region.\\nP4 — learnable, grows with corrections.',\n\t\tstarters: [],\n\t},\n\tego: {\n\t\tdescription: 'Personality, tone, and communication style.\\nP5 — set by user preference.',\n\t\tstarters: [],\n\t},\n\tprefrontal: {\n\t\tdescription: 'Goals, projects, and planning.\\nP6 — lowest priority, longest time horizon.',\n\t\tstarters: [],\n\t},\n};\n\n/**\n * Initialize a new brain directory with 7 regions.\n */\nexport function initBrain(brainPath: string): void {\n\tif (existsSync(brainPath)) {\n\t\tconst entries = readdirSync(brainPath);\n\t\tif (entries.some((e) => (REGIONS as readonly string[]).includes(e))) {\n\t\t\tconsole.log(`\\u{26A0}\\uFE0F Brain already exists at ${brainPath}`);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tmkdirSync(brainPath, { recursive: true });\n\n\tfor (const regionName of REGIONS) {\n\t\tconst regionDir = join(brainPath, regionName);\n\t\tmkdirSync(regionDir, { recursive: true });\n\n\t\tconst template = REGION_TEMPLATES[regionName];\n\t\tconst icon = REGION_ICONS[regionName];\n\t\tconst ko = REGION_KO[regionName];\n\n\t\t// Write _rules.md template\n\t\twriteFileSync(\n\t\t\tjoin(regionDir, '_rules.md'),\n\t\t\t`# ${icon} ${regionName} (${ko})\\n\\n${template.description}\\n`,\n\t\t\t'utf8',\n\t\t);\n\n\t\t// Create starter neurons\n\t\tfor (const starter of template.starters) {\n\t\t\tconst neuronDir = join(regionDir, starter);\n\t\t\tmkdirSync(neuronDir, { recursive: true });\n\t\t\twriteFileSync(join(neuronDir, '1.neuron'), '', 'utf8');\n\t\t}\n\t}\n\n\t// Create _agents inbox\n\tmkdirSync(join(brainPath, '_agents', 'global_inbox'), { recursive: true });\n\n\tconsole.log(`\\u{1F9E0} Brain initialized at ${brainPath}`);\n\tconsole.log(` 7 regions created: ${REGIONS.join(', ')}`);\n\tconsole.log('');\n\tconsole.log(' Next steps:');\n\tconsole.log(` hebbian grow brainstem/NO_your_rule --brain ${brainPath}`);\n\tconsole.log(` hebbian emit claude --brain ${brainPath}`);\n}\n","// hebbian — Brain Filesystem Scanner\n//\n// Walks the brain directory tree and builds a structured representation.\n// Folders = neurons. Files = firing traces. Paths = sentences.\n//\n// Scan order follows subsumption priority (P0 brainstem → P6 prefrontal).\n// Only recognizes the 7 canonical region names at the top level.\n\nimport { readdirSync, statSync, readFileSync, existsSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { REGIONS, REGION_PRIORITY, MAX_DEPTH } from './constants';\nimport type { Neuron, Region, Brain } from './types';\n\n/**\n * Scan a brain directory and return all regions with their neurons.\n */\nexport function scanBrain(brainRoot: string): Brain {\n\tconst regions: Region[] = [];\n\n\tfor (const regionName of REGIONS) {\n\t\tconst regionPath = join(brainRoot, regionName);\n\t\tif (!existsSync(regionPath)) {\n\t\t\tregions.push({\n\t\t\t\tname: regionName,\n\t\t\t\tpriority: REGION_PRIORITY[regionName],\n\t\t\t\tpath: regionPath,\n\t\t\t\tneurons: [],\n\t\t\t\taxons: [],\n\t\t\t\thasBomb: false,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst neurons = walkRegion(regionPath, regionPath, 0);\n\t\tconst axons = readAxons(regionPath);\n\t\tconst hasBomb = neurons.some((n) => n.hasBomb);\n\n\t\tregions.push({\n\t\t\tname: regionName,\n\t\t\tpriority: REGION_PRIORITY[regionName],\n\t\t\tpath: regionPath,\n\t\t\tneurons,\n\t\t\taxons,\n\t\t\thasBomb,\n\t\t});\n\t}\n\n\treturn { root: brainRoot, regions };\n}\n\n/**\n * Recursively walk a region directory and collect neurons.\n * A neuron is any directory that contains at least one trace file\n * (*.neuron, *.contra, *.dormant, bomb.neuron).\n */\nfunction walkRegion(dir: string, regionRoot: string, depth: number): Neuron[] {\n\tif (depth > MAX_DEPTH) return [];\n\n\tconst neurons: Neuron[] = [];\n\tlet entries;\n\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn [];\n\t}\n\n\t// Parse trace files in this directory\n\tlet counter = 0;\n\tlet contra = 0;\n\tlet dopamine = 0;\n\tlet hasBomb = false;\n\tlet hasMemory = false;\n\tlet isDormant = false;\n\tlet modTime = new Date(0);\n\tlet hasTraceFile = false;\n\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_')) continue;\n\n\t\tif (entry.isFile()) {\n\t\t\tconst name = entry.name;\n\n\t\t\t// N.neuron — excitatory counter\n\t\t\tif (name.endsWith('.neuron') && !name.startsWith('dopamine') && !name.startsWith('memory') && name !== 'bomb.neuron') {\n\t\t\t\tconst n = parseInt(name, 10);\n\t\t\t\tif (!isNaN(n) && n > counter) {\n\t\t\t\t\tcounter = n;\n\t\t\t\t\thasTraceFile = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst st = statSync(join(dir, name));\n\t\t\t\t\t\tif (st.mtime > modTime) modTime = st.mtime;\n\t\t\t\t\t} catch {}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// N.contra — inhibitory counter\n\t\t\tif (name.endsWith('.contra')) {\n\t\t\t\tconst n = parseInt(name, 10);\n\t\t\t\tif (!isNaN(n) && n > contra) {\n\t\t\t\t\tcontra = n;\n\t\t\t\t\thasTraceFile = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// dopamineN.neuron — reward signal\n\t\t\tif (name.startsWith('dopamine') && name.endsWith('.neuron')) {\n\t\t\t\tconst n = parseInt(name.replace('dopamine', ''), 10);\n\t\t\t\tif (!isNaN(n) && n > dopamine) {\n\t\t\t\t\tdopamine = n;\n\t\t\t\t\thasTraceFile = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// bomb.neuron — circuit breaker\n\t\t\tif (name === 'bomb.neuron') {\n\t\t\t\thasBomb = true;\n\t\t\t\thasTraceFile = true;\n\t\t\t}\n\n\t\t\t// memoryN.neuron — memory signal\n\t\t\tif (name.startsWith('memory') && name.endsWith('.neuron')) {\n\t\t\t\thasMemory = true;\n\t\t\t\thasTraceFile = true;\n\t\t\t}\n\n\t\t\t// *.dormant — dormancy marker\n\t\t\tif (name.endsWith('.dormant')) {\n\t\t\t\tisDormant = true;\n\t\t\t\thasTraceFile = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// If this directory has trace files, it's a neuron\n\tif (hasTraceFile) {\n\t\tconst relPath = relative(regionRoot, dir) || '.';\n\t\tconst folderName = dir.split(sep).pop() || '';\n\t\tconst total = counter + contra + dopamine;\n\t\tconst intensity = counter - contra + dopamine;\n\t\tconst polarity = total > 0 ? intensity / total : 0;\n\n\t\tneurons.push({\n\t\t\tname: folderName,\n\t\t\tpath: relPath,\n\t\t\tfullPath: dir,\n\t\t\tcounter,\n\t\t\tcontra,\n\t\t\tdopamine,\n\t\t\tintensity,\n\t\t\tpolarity: Math.round(polarity * 100) / 100,\n\t\t\thasBomb,\n\t\t\thasMemory,\n\t\t\tisDormant,\n\t\t\tdepth,\n\t\t\tmodTime,\n\t\t});\n\t}\n\n\t// Recurse into subdirectories\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_') || entry.name.startsWith('.')) continue;\n\t\tif (entry.isDirectory()) {\n\t\t\tconst subNeurons = walkRegion(join(dir, entry.name), regionRoot, depth + 1);\n\t\t\tneurons.push(...subNeurons);\n\t\t}\n\t}\n\n\treturn neurons;\n}\n\n/**\n * Read .axon file from a region directory.\n */\nfunction readAxons(regionPath: string): string[] {\n\tconst axonPath = join(regionPath, '.axon');\n\tif (!existsSync(axonPath)) return [];\n\ttry {\n\t\tconst content = readFileSync(axonPath, 'utf8').trim();\n\t\treturn content.split(/[\\n,]+/).map((s: string) => s.trim()).filter(Boolean);\n\t} catch {\n\t\treturn [];\n\t}\n}\n","// hebbian — Subsumption Cascade Engine\n//\n// Implements Brooks' subsumption architecture:\n// - Lower priority (P0) always suppresses higher priority (P6)\n// - bomb.neuron in any region halts all downstream regions\n// - Dormant neurons are excluded from activation counts\n//\n// Cascade flow:\n// P0 brainstem → P1 limbic → P2 hippocampus → P3 sensors → P4 cortex → P5 ego → P6 prefrontal\n// If bomb at P(n), all P(n+1)→P6 are BLOCKED.\n\nimport type { Brain, Region, SubsumptionResult } from './types';\n\n/**\n * Run the subsumption cascade on a scanned brain.\n */\nexport function runSubsumption(brain: Brain): SubsumptionResult {\n\tconst activeRegions: Region[] = [];\n\tconst blockedRegions: Region[] = [];\n\tlet bombSource = '';\n\tlet firedNeurons = 0;\n\tlet totalNeurons = 0;\n\tlet totalCounter = 0;\n\tlet blocked = false;\n\n\tfor (const region of brain.regions) {\n\t\ttotalNeurons += region.neurons.length;\n\n\t\tif (blocked) {\n\t\t\tblockedRegions.push(region);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (region.hasBomb) {\n\t\t\tbombSource = region.name;\n\t\t\tblockedRegions.push(region);\n\t\t\tblocked = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tactiveRegions.push(region);\n\n\t\tfor (const neuron of region.neurons) {\n\t\t\tif (!neuron.isDormant) {\n\t\t\t\tfiredNeurons++;\n\t\t\t\ttotalCounter += neuron.counter;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tactiveRegions,\n\t\tblockedRegions,\n\t\tbombSource,\n\t\tfiredNeurons,\n\t\ttotalNeurons,\n\t\ttotalCounter,\n\t};\n}\n","// hebbian — 3-Tier Emit System + Multi-Target Output\n//\n// Tier 1: Bootstrap (~500 tokens) — auto-loaded by AI (CLAUDE.md, .cursorrules, etc.)\n// Tier 2: _index.md — brain overview (AI reads at conversation start)\n// Tier 3: {region}/_rules.md — per-region detail (AI reads on demand)\n//\n// Multi-target: claude, cursor, gemini, copilot, generic, all\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport { scanBrain } from './scanner';\nimport { runSubsumption } from './subsumption';\nimport {\n\tREGIONS, REGION_ICONS, REGION_KO, EMIT_TARGETS,\n\tEMIT_THRESHOLD, SPOTLIGHT_DAYS, MARKER_START, MARKER_END,\n} from './constants';\nimport type { RegionName } from './constants';\nimport type { Neuron, Region, Brain, SubsumptionResult } from './types';\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// TIER 1: Bootstrap (~500 tokens)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Generate Tier 1 bootstrap content.\n */\nexport function emitBootstrap(result: SubsumptionResult, brain: Brain): string {\n\tconst lines: string[] = [];\n\tconst now = new Date().toISOString().replace(/\\.\\d+Z$/, '');\n\n\tlines.push(MARKER_START);\n\tlines.push(`<!-- Generated: ${now} -->`);\n\tlines.push('<!-- Axiom: Folder=Neuron | File=Trace | Path=Sentence -->');\n\tlines.push(`<!-- Active: ${result.firedNeurons}/${result.totalNeurons} neurons | Total activation: ${result.totalCounter} -->`);\n\tlines.push('');\n\n\t// Circuit breaker\n\tif (result.bombSource) {\n\t\tlines.push(`## \\u{1F6A8} CIRCUIT BREAKER: ${result.bombSource}`);\n\t\tlines.push('**ALL OPERATIONS HALTED. REPAIR REQUIRED.**');\n\t\tlines.push('');\n\t\tlines.push(MARKER_END);\n\t\treturn lines.join('\\n');\n\t}\n\n\tlines.push('## hebbian Active Rules');\n\tlines.push('');\n\n\t// Persona (ego region)\n\tlines.push(`### ${REGION_ICONS.ego} Persona`);\n\tfor (const region of result.activeRegions) {\n\t\tif (region.name === 'ego') {\n\t\t\tconst top = sortedActive(region.neurons, 10);\n\t\t\tfor (const n of top) {\n\t\t\t\tlines.push(`- ${pathToSentence(n.path)}`);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tlines.push('');\n\n\t// Subsumption cascade\n\tlines.push('### \\u{1F517} Subsumption Cascade');\n\tlines.push('```');\n\tlines.push('brainstem \\u2190\\u2192 limbic \\u2190\\u2192 hippocampus \\u2190\\u2192 sensors \\u2190\\u2192 cortex \\u2190\\u2192 ego \\u2190\\u2192 prefrontal');\n\tlines.push(' (P0) (P1) (P2) (P3) (P4) (P5) (P6)');\n\tlines.push('```');\n\tlines.push('Lower P always overrides higher P. bomb = full stop.');\n\tlines.push('');\n\n\t// TOP 5 brainstem rules\n\tlines.push(`### ${REGION_ICONS.brainstem} Core Directives TOP 5`);\n\tfor (const region of result.activeRegions) {\n\t\tif (region.name === 'brainstem') {\n\t\t\tconst top = sortedActive(region.neurons, 5);\n\t\t\ttop.forEach((n, i) => {\n\t\t\t\tlines.push(`${i + 1}. **${pathToSentence(n.path)}**`);\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t}\n\tlines.push('');\n\n\t// Active regions summary\n\tlines.push('### Active Regions');\n\tlines.push('| Region | Neurons | Activation |');\n\tlines.push('|--------|---------|------------|');\n\tfor (const region of result.activeRegions) {\n\t\tconst active = region.neurons.filter((n) => !n.isDormant);\n\t\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\t\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\t\tlines.push(`| ${icon} ${region.name} | ${active.length} | ${activation} |`);\n\t}\n\tlines.push('');\n\tlines.push(MARKER_END);\n\n\treturn lines.join('\\n');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// TIER 2: Index (_index.md)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Generate Tier 2 brain index content.\n */\nexport function emitIndex(result: SubsumptionResult, brain: Brain): string {\n\tconst lines: string[] = [];\n\tlines.push('# hebbian Brain Index');\n\tlines.push('');\n\tlines.push(`> ${result.firedNeurons} active / ${result.totalNeurons} total neurons | activation: ${result.totalCounter}`);\n\tlines.push('');\n\n\tif (result.bombSource) {\n\t\tlines.push(`## \\u{1F6A8} CIRCUIT BREAKER: ${result.bombSource}`);\n\t\tlines.push('');\n\t\treturn lines.join('\\n');\n\t}\n\n\t// Top 10 neurons by counter\n\tconst allNeurons = result.activeRegions.flatMap((r) =>\n\t\tr.neurons.filter((n) => !n.isDormant && n.counter >= EMIT_THRESHOLD),\n\t);\n\tallNeurons.sort((a, b) => b.counter - a.counter);\n\n\tlines.push('## Top 10 Active Neurons');\n\tlines.push('| # | Path | Counter | Strength |');\n\tlines.push('|---|------|---------|----------|');\n\tfor (const n of allNeurons.slice(0, 10)) {\n\t\tconst strength = n.counter >= 10 ? '\\u{1F534}' : n.counter >= 5 ? '\\u{1F7E1}' : '\\u26AA';\n\t\tlines.push(`| ${allNeurons.indexOf(n) + 1} | ${n.path} | ${n.counter} | ${strength} |`);\n\t}\n\tlines.push('');\n\n\t// Spotlight: new neurons (< SPOTLIGHT_DAYS old, counter < EMIT_THRESHOLD)\n\tconst cutoff = new Date(Date.now() - SPOTLIGHT_DAYS * 24 * 60 * 60 * 1000);\n\tconst spotlightNeurons = result.activeRegions.flatMap((r) =>\n\t\tr.neurons.filter((n) => !n.isDormant && n.counter < EMIT_THRESHOLD && n.modTime > cutoff),\n\t);\n\tif (spotlightNeurons.length > 0) {\n\t\tlines.push('## Spotlight (Probation)');\n\t\tfor (const n of spotlightNeurons) {\n\t\t\tlines.push(`- ${n.path} (${n.counter}) — new`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\t// Per-region summary\n\tlines.push('## Regions');\n\tlines.push('| Region | Active | Dormant | Activation | Rules |');\n\tlines.push('|--------|--------|---------|------------|-------|');\n\tfor (const region of result.activeRegions) {\n\t\tconst active = region.neurons.filter((n) => !n.isDormant);\n\t\tconst dormant = region.neurons.filter((n) => n.isDormant);\n\t\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\t\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\t\tlines.push(`| ${icon} ${region.name} | ${active.length} | ${dormant.length} | ${activation} | [_rules.md](${region.name}/_rules.md) |`);\n\t}\n\tlines.push('');\n\n\treturn lines.join('\\n');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// TIER 3: Per-region rules ({region}/_rules.md)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Generate Tier 3 per-region rules content.\n */\nexport function emitRegionRules(region: Region): string {\n\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\tconst ko = REGION_KO[region.name as RegionName] || '';\n\tconst active = region.neurons.filter((n) => !n.isDormant);\n\tconst dormant = region.neurons.filter((n) => n.isDormant);\n\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\n\tconst lines: string[] = [];\n\tlines.push(`# ${icon} ${region.name} (${ko})`);\n\tlines.push(`> Active: ${active.length} | Dormant: ${dormant.length} | Activation: ${activation}`);\n\tlines.push('');\n\n\t// Axons\n\tif (region.axons.length > 0) {\n\t\tlines.push('## Connections');\n\t\tfor (const axon of region.axons) {\n\t\t\tlines.push(`- \\u2194 ${axon}`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\t// Neuron tree\n\tif (active.length > 0) {\n\t\tlines.push('## Rules');\n\t\tconst sorted = [...active].sort((a, b) => b.counter - a.counter);\n\t\tfor (const n of sorted) {\n\t\t\tconst indent = ' '.repeat(Math.min(n.depth, 4));\n\t\t\tconst prefix = strengthPrefix(n.counter);\n\t\t\tconst signals: string[] = [];\n\t\t\tif (n.dopamine > 0) signals.push(`\\u{1F7E2}+${n.dopamine}`);\n\t\t\tif (n.hasBomb) signals.push('\\u{1F4A3}');\n\t\t\tif (n.hasMemory) signals.push('\\u{1F4BE}');\n\t\t\tconst signalStr = signals.length > 0 ? ` ${signals.join(' ')}` : '';\n\t\t\tlines.push(`${indent}- ${prefix}${pathToSentence(n.path)} (${n.counter})${signalStr}`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\t// Dormant section\n\tif (dormant.length > 0) {\n\t\tlines.push('## Dormant');\n\t\tfor (const n of dormant) {\n\t\t\tlines.push(`- ~~${pathToSentence(n.path)} (${n.counter})~~`);\n\t\t}\n\t\tlines.push('');\n\t}\n\n\treturn lines.join('\\n');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// MULTI-TARGET OUTPUT\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Emit rules to a specific target or all targets.\n */\nexport function emitToTarget(brainRoot: string, target: string): void {\n\tconst brain = scanBrain(brainRoot);\n\tconst result = runSubsumption(brain);\n\tconst content = emitBootstrap(result, brain);\n\n\tif (target === 'all') {\n\t\tfor (const [name, filePath] of Object.entries(EMIT_TARGETS)) {\n\t\t\twriteTarget(filePath, content);\n\t\t\tconsole.log(`\\u{1F4E4} emitted: ${name} → ${filePath}`);\n\t\t}\n\t} else if (EMIT_TARGETS[target]) {\n\t\twriteTarget(EMIT_TARGETS[target], content);\n\t\tconsole.log(`\\u{1F4E4} emitted: ${target} → ${EMIT_TARGETS[target]}`);\n\t} else {\n\t\tthrow new Error(`Unknown target: ${target}. Valid: ${Object.keys(EMIT_TARGETS).join(', ')}, all`);\n\t}\n\n\t// Always write tier 2 + tier 3 into the brain\n\twriteAllTiers(brainRoot, result, brain);\n}\n\n/**\n * Write all 3 tiers into the brain directory.\n */\nexport function writeAllTiers(brainRoot: string, result: SubsumptionResult, brain: Brain): void {\n\t// Tier 2: _index.md\n\tconst indexContent = emitIndex(result, brain);\n\twriteFileSync(join(brainRoot, '_index.md'), indexContent, 'utf8');\n\n\t// Tier 3: per-region _rules.md\n\tfor (const region of result.activeRegions) {\n\t\tif (existsSync(region.path)) {\n\t\t\tconst rulesContent = emitRegionRules(region);\n\t\t\twriteFileSync(join(region.path, '_rules.md'), rulesContent, 'utf8');\n\t\t}\n\t}\n}\n\n/**\n * Write content to a target file, using marker-based injection if file already exists.\n */\nfunction writeTarget(filePath: string, content: string): void {\n\tconst dir = dirname(filePath);\n\tif (dir !== '.' && !existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true });\n\t}\n\n\tif (existsSync(filePath)) {\n\t\t// Marker-based injection: replace between markers, preserve surrounding content\n\t\tconst existing = readFileSync(filePath, 'utf8');\n\t\tconst startIdx = existing.indexOf(MARKER_START);\n\t\tconst endIdx = existing.indexOf(MARKER_END);\n\n\t\tif (startIdx !== -1 && endIdx !== -1) {\n\t\t\tconst before = existing.slice(0, startIdx);\n\t\t\tconst after = existing.slice(endIdx + MARKER_END.length);\n\t\t\twriteFileSync(filePath, before + content + after, 'utf8');\n\t\t\treturn;\n\t\t}\n\t}\n\n\twriteFileSync(filePath, content, 'utf8');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// DIAGNOSTICS (for CLI `hebbian diag` / `hebbian stats`)\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Print brain diagnostics to stdout.\n */\nexport function printDiag(brain: Brain, result: SubsumptionResult): void {\n\tconsole.log('');\n\tconsole.log(`\\u{1F9E0} hebbian Brain Diagnostics`);\n\tconsole.log(` Root: ${brain.root}`);\n\tconsole.log(` Neurons: ${result.firedNeurons} active / ${result.totalNeurons} total`);\n\tconsole.log(` Activation: ${result.totalCounter}`);\n\tif (result.bombSource) {\n\t\tconsole.log(` \\u{1F4A3} BOMB: ${result.bombSource} — cascade halted!`);\n\t}\n\tconsole.log('');\n\n\tfor (const region of brain.regions) {\n\t\tconst icon = REGION_ICONS[region.name as RegionName] || '';\n\t\tconst active = region.neurons.filter((n) => !n.isDormant);\n\t\tconst dormant = region.neurons.filter((n) => n.isDormant);\n\t\tconst activation = active.reduce((sum, n) => sum + n.counter, 0);\n\t\tconst isBlocked = result.blockedRegions.some((r) => r.name === region.name);\n\t\tconst status = region.hasBomb ? '\\u{1F4A3} BOMB' : isBlocked ? '\\u{1F6AB} BLOCKED' : '\\u2705 ACTIVE';\n\n\t\tconsole.log(` ${icon} ${region.name} [${status}]`);\n\t\tconsole.log(` neurons: ${active.length} active, ${dormant.length} dormant | activation: ${activation}`);\n\n\t\tif (region.axons.length > 0) {\n\t\t\tconsole.log(` axons: ${region.axons.join(', ')}`);\n\t\t}\n\n\t\tconst top3 = sortedActive(region.neurons, 3);\n\t\tfor (const n of top3) {\n\t\t\tconsole.log(` \\u251C ${n.path} (${n.counter})`);\n\t\t}\n\t}\n\tconsole.log('');\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// HELPERS\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/** Convert a neuron relative path to a human-readable sentence. */\nfunction pathToSentence(path: string): string {\n\treturn path.replace(/\\//g, ' > ').replace(/_/g, ' ');\n}\n\n/** Sort non-dormant neurons by counter (descending), take first N. */\nfunction sortedActive(neurons: Neuron[], n: number): Neuron[] {\n\treturn [...neurons]\n\t\t.filter((neuron) => !neuron.isDormant)\n\t\t.sort((a, b) => b.counter - a.counter)\n\t\t.slice(0, n);\n}\n\n/** Strength prefix based on counter value. */\nfunction strengthPrefix(counter: number): string {\n\tif (counter >= 10) return '**[ABSOLUTE]** ';\n\tif (counter >= 5) return '**[MUST]** ';\n\treturn '';\n}\n","// hebbian — Fire Neuron (increment counter)\n//\n// Firing = reinforcing a synaptic pathway.\n// The counter file is renamed: N.neuron → (N+1).neuron\n\nimport { readdirSync, renameSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Increment a neuron's counter by 1.\n * If the neuron doesn't exist, auto-grows it with counter=1.\n */\nexport function fireNeuron(brainRoot: string, neuronPath: string): number {\n\tconst fullPath = join(brainRoot, neuronPath);\n\n\t// Auto-grow if neuron doesn't exist\n\tif (!existsSync(fullPath)) {\n\t\tmkdirSync(fullPath, { recursive: true });\n\t\twriteFileSync(join(fullPath, '1.neuron'), '', 'utf8');\n\t\tconsole.log(`\\u{1F331} grew + fired: ${neuronPath} (1)`);\n\t\treturn 1;\n\t}\n\n\t// Find current counter\n\tconst current = getCurrentCounter(fullPath);\n\tconst newCounter = current + 1;\n\n\t// Rename: N.neuron → (N+1).neuron\n\tif (current > 0) {\n\t\trenameSync(join(fullPath, `${current}.neuron`), join(fullPath, `${newCounter}.neuron`));\n\t} else {\n\t\twriteFileSync(join(fullPath, `${newCounter}.neuron`), '', 'utf8');\n\t}\n\n\tconsole.log(`\\u{1F525} fired: ${neuronPath} (${current} → ${newCounter})`);\n\treturn newCounter;\n}\n\n/**\n * Get current counter value from the highest N.neuron file.\n */\nexport function getCurrentCounter(dir: string): number {\n\tlet max = 0;\n\ttry {\n\t\tfor (const entry of readdirSync(dir)) {\n\t\t\tif (entry.endsWith('.neuron') && !entry.startsWith('dopamine') && !entry.startsWith('memory') && entry !== 'bomb.neuron') {\n\t\t\t\tconst n = parseInt(entry, 10);\n\t\t\t\tif (!isNaN(n) && n > max) max = n;\n\t\t\t}\n\t\t}\n\t} catch {}\n\treturn max;\n}\n","// hebbian — Tokenizer, Stemmer, Jaccard Similarity\n//\n// Used by growNeuron() to detect similar existing neurons and merge\n// instead of duplicating. Implements synaptic consolidation.\n//\n// \"Neurons that fire together, wire together.\" — if two folder names\n// express the same concept, fire the existing one instead of creating a duplicate.\n\n/**\n * Tokenize a neuron name into stemmed words.\n * Splits on underscores, hyphens, spaces, and CamelCase boundaries.\n */\nexport function tokenize(name: string): string[] {\n\treturn name\n\t\t.replace(/([a-z])([A-Z])/g, '$1_$2') // camelCase → snake\n\t\t.replace(/[_\\-\\s]+/g, ' ') // normalize separators\n\t\t.toLowerCase()\n\t\t.split(' ')\n\t\t.map(stem)\n\t\t.filter((t) => t.length > 1); // drop single chars\n}\n\n/**\n * Simple suffix stemmer — removes common English suffixes.\n * Not a full Porter stemmer, but sufficient for Jaccard comparison.\n */\nexport function stem(word: string): string {\n\tconst suffixes = ['ing', 'tion', 'sion', 'ness', 'ment', 'able', 'ible', 'ful', 'less', 'ous', 'ive', 'ity', 'ies', 'ed', 'er', 'es', 'ly', 'al', 'en'];\n\tfor (const suffix of suffixes) {\n\t\tif (word.length > suffix.length + 2 && word.endsWith(suffix)) {\n\t\t\treturn word.slice(0, -suffix.length);\n\t\t}\n\t}\n\treturn word;\n}\n\n/**\n * Compute Jaccard similarity between two token sets.\n * |A ∩ B| / |A ∪ B|\n */\nexport function jaccardSimilarity(a: string[], b: string[]): number {\n\tif (a.length === 0 && b.length === 0) return 1.0;\n\tif (a.length === 0 || b.length === 0) return 0.0;\n\n\tconst setA = new Set(a);\n\tconst setB = new Set(b);\n\tlet intersection = 0;\n\n\tfor (const item of setA) {\n\t\tif (setB.has(item)) intersection++;\n\t}\n\n\tconst union = new Set([...setA, ...setB]).size;\n\treturn intersection / union;\n}\n","// hebbian — Grow Neuron (with synaptic consolidation)\n//\n// Creates a new neuron (folder + 1.neuron).\n// Before creating, checks for similar existing neurons via Jaccard similarity.\n// If a match is found (>= 0.6), fires the existing neuron instead.\n// This prevents duplication and strengthens existing pathways.\n//\n// \"Consolidation over duplication.\" — Hebb's principle.\n\nimport { mkdirSync, writeFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { REGIONS, JACCARD_THRESHOLD } from './constants';\nimport { tokenize, jaccardSimilarity } from './similarity';\nimport { fireNeuron } from './fire';\n\nexport interface GrowResult {\n\taction: 'grew' | 'fired';\n\tpath: string;\n\tcounter: number;\n}\n\n/**\n * Grow a new neuron at the given path.\n * If a similar neuron already exists in the same region, fires it instead.\n */\nexport function growNeuron(brainRoot: string, neuronPath: string): GrowResult {\n\tconst fullPath = join(brainRoot, neuronPath);\n\n\t// If neuron already exists, just fire it\n\tif (existsSync(fullPath)) {\n\t\tconst counter = fireNeuron(brainRoot, neuronPath);\n\t\treturn { action: 'fired', path: neuronPath, counter };\n\t}\n\n\t// Extract region name and leaf name\n\tconst parts = neuronPath.split('/');\n\tconst regionName = parts[0]!;\n\tif (!(REGIONS as readonly string[]).includes(regionName)) {\n\t\tthrow new Error(`Invalid region: ${regionName}. Valid: ${REGIONS.join(', ')}`);\n\t}\n\n\tconst leafName = parts[parts.length - 1]!;\n\tconst newTokens = tokenize(leafName);\n\n\t// Search for similar neurons in the same region\n\tconst regionPath = join(brainRoot, regionName);\n\tif (existsSync(regionPath)) {\n\t\tconst match = findSimilar(regionPath, regionPath, newTokens);\n\t\tif (match) {\n\t\t\tconst matchRelPath = regionName + '/' + relative(regionPath, match);\n\t\t\tconsole.log(`\\u{1F504} consolidation: \"${neuronPath}\" ≈ \"${matchRelPath}\" (firing existing)`);\n\t\t\tconst counter = fireNeuron(brainRoot, matchRelPath);\n\t\t\treturn { action: 'fired', path: matchRelPath, counter };\n\t\t}\n\t}\n\n\t// No match — create new neuron\n\tmkdirSync(fullPath, { recursive: true });\n\twriteFileSync(join(fullPath, '1.neuron'), '', 'utf8');\n\tconsole.log(`\\u{1F331} grew: ${neuronPath} (1)`);\n\treturn { action: 'grew', path: neuronPath, counter: 1 };\n}\n\n/**\n * Walk a region and find a neuron whose name is similar to the given tokens.\n */\nfunction findSimilar(dir: string, regionRoot: string, targetTokens: string[]): string | null {\n\tlet entries;\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn null;\n\t}\n\n\t// Check if this directory has .neuron files (is a neuron)\n\tconst hasNeuron = entries.some((e) => e.isFile() && e.name.endsWith('.neuron'));\n\tif (hasNeuron) {\n\t\tconst folderName = dir.split('/').pop() || '';\n\t\tconst existingTokens = tokenize(folderName);\n\t\tconst similarity = jaccardSimilarity(targetTokens, existingTokens);\n\t\tif (similarity >= JACCARD_THRESHOLD) {\n\t\t\treturn dir;\n\t\t}\n\t}\n\n\t// Recurse into subdirectories\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_') || entry.name.startsWith('.')) continue;\n\t\tif (entry.isDirectory()) {\n\t\t\tconst match = findSimilar(join(dir, entry.name), regionRoot, targetTokens);\n\t\t\tif (match) return match;\n\t\t}\n\t}\n\n\treturn null;\n}\n","// hebbian — Rollback Neuron (decrement counter)\n//\n// Undo a firing. Counter cannot go below 1 (minimum activation).\n\nimport { renameSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getCurrentCounter } from './fire';\n\n/**\n * Decrement a neuron's counter by 1. Minimum counter is 1.\n */\nexport function rollbackNeuron(brainRoot: string, neuronPath: string): number {\n\tconst fullPath = join(brainRoot, neuronPath);\n\tconst current = getCurrentCounter(fullPath);\n\n\tif (current === 0) {\n\t\tthrow new Error(`Neuron not found: ${neuronPath}`);\n\t}\n\n\tif (current <= 1) {\n\t\tthrow new Error(`Counter already at minimum (1): ${neuronPath}`);\n\t}\n\n\tconst newCounter = current - 1;\n\trenameSync(join(fullPath, `${current}.neuron`), join(fullPath, `${newCounter}.neuron`));\n\n\tconsole.log(`\\u{23EA} rollback: ${neuronPath} (${current} → ${newCounter})`);\n\treturn newCounter;\n}\n","// hebbian — Signal Neuron (dopamine / bomb / memory)\n//\n// Signals are additional trace files placed in a neuron directory:\n// dopamineN.neuron — reward signal (positive reinforcement)\n// bomb.neuron — circuit breaker (halts downstream regions)\n// memoryN.neuron — memory marker (episodic recording)\n\nimport { writeFileSync, existsSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { SIGNAL_TYPES } from './constants';\nimport type { SignalType } from './constants';\n\n/**\n * Add a signal to a neuron.\n */\nexport function signalNeuron(brainRoot: string, neuronPath: string, signalType: SignalType): void {\n\tif (!SIGNAL_TYPES.includes(signalType)) {\n\t\tthrow new Error(`Invalid signal type: ${signalType}. Valid: ${SIGNAL_TYPES.join(', ')}`);\n\t}\n\n\tconst fullPath = join(brainRoot, neuronPath);\n\tif (!existsSync(fullPath)) {\n\t\tthrow new Error(`Neuron not found: ${neuronPath}`);\n\t}\n\n\tswitch (signalType) {\n\t\tcase 'bomb': {\n\t\t\twriteFileSync(join(fullPath, 'bomb.neuron'), '', 'utf8');\n\t\t\tconsole.log(`\\u{1F4A3} bomb planted: ${neuronPath}`);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'dopamine': {\n\t\t\tconst level = getNextSignalLevel(fullPath, 'dopamine');\n\t\t\twriteFileSync(join(fullPath, `dopamine${level}.neuron`), '', 'utf8');\n\t\t\tconsole.log(`\\u{1F7E2} dopamine +${level}: ${neuronPath}`);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'memory': {\n\t\t\tconst level = getNextSignalLevel(fullPath, 'memory');\n\t\t\twriteFileSync(join(fullPath, `memory${level}.neuron`), '', 'utf8');\n\t\t\tconsole.log(`\\u{1F4BE} memory +${level}: ${neuronPath}`);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Get the next signal level (current max + 1).\n */\nfunction getNextSignalLevel(dir: string, prefix: string): number {\n\tlet max = 0;\n\ttry {\n\t\tfor (const entry of readdirSync(dir)) {\n\t\t\tif (entry.startsWith(prefix) && entry.endsWith('.neuron')) {\n\t\t\t\tconst n = parseInt(entry.replace(prefix, ''), 10);\n\t\t\t\tif (!isNaN(n) && n > max) max = n;\n\t\t\t}\n\t\t}\n\t} catch {}\n\treturn max + 1;\n}\n","// hebbian — Decay (dormancy sweep)\n//\n// Neurons that haven't been touched in N days are marked dormant.\n// Dormancy = *.dormant file in the neuron directory.\n// Dormant neurons are excluded from emission and activation counts.\n//\n// \"Most neurons die. Only the repeatedly fired ones survive.\" — Natural selection on OS.\n\nimport { readdirSync, statSync, writeFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { REGIONS, MAX_DEPTH } from './constants';\n\nexport interface DecayResult {\n\tscanned: number;\n\tdecayed: number;\n}\n\n/**\n * Sweep the brain and mark inactive neurons as dormant.\n */\nexport function runDecay(brainRoot: string, days: number): DecayResult {\n\tconst threshold = Date.now() - days * 24 * 60 * 60 * 1000;\n\tlet scanned = 0;\n\tlet decayed = 0;\n\n\tfor (const regionName of REGIONS) {\n\t\tconst regionPath = join(brainRoot, regionName);\n\t\tif (!existsSync(regionPath)) continue;\n\t\tconst result = decayWalk(regionPath, threshold, 0);\n\t\tscanned += result.scanned;\n\t\tdecayed += result.decayed;\n\t}\n\n\tconsole.log(`\\u{1F4A4} decay: scanned ${scanned} neurons, decayed ${decayed} (>${days} days inactive)`);\n\treturn { scanned, decayed };\n}\n\nfunction decayWalk(dir: string, threshold: number, depth: number): DecayResult {\n\tif (depth > MAX_DEPTH) return { scanned: 0, decayed: 0 };\n\n\tlet scanned = 0;\n\tlet decayed = 0;\n\tlet entries;\n\n\ttry {\n\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn { scanned: 0, decayed: 0 };\n\t}\n\n\t// Check if this directory is a neuron (has .neuron files)\n\tlet hasNeuronFile = false;\n\tlet isDormant = false;\n\tlet latestMod = 0;\n\n\tfor (const entry of entries) {\n\t\tif (entry.isFile()) {\n\t\t\tif (entry.name.endsWith('.neuron')) {\n\t\t\t\thasNeuronFile = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst st = statSync(join(dir, entry.name));\n\t\t\t\t\tif (st.mtimeMs > latestMod) latestMod = st.mtimeMs;\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (entry.name.endsWith('.dormant')) {\n\t\t\t\tisDormant = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (hasNeuronFile) {\n\t\tscanned++;\n\t\tif (!isDormant && latestMod < threshold) {\n\t\t\tconst age = Math.floor((Date.now() - latestMod) / (24 * 60 * 60 * 1000));\n\t\t\twriteFileSync(\n\t\t\t\tjoin(dir, 'decay.dormant'),\n\t\t\t\t`Dormant since ${new Date().toISOString()} (${age} days inactive)`,\n\t\t\t\t'utf8',\n\t\t\t);\n\t\t\tdecayed++;\n\t\t}\n\t}\n\n\t// Recurse\n\tfor (const entry of entries) {\n\t\tif (entry.name.startsWith('_') || entry.name.startsWith('.')) continue;\n\t\tif (entry.isDirectory()) {\n\t\t\tconst sub = decayWalk(join(dir, entry.name), threshold, depth + 1);\n\t\t\tscanned += sub.scanned;\n\t\t\tdecayed += sub.decayed;\n\t\t}\n\t}\n\n\treturn { scanned, decayed };\n}\n","// hebbian — Batch Deduplication\n//\n// Scans all neurons in a region and merges duplicates via Jaccard similarity.\n// When a match is found (>= threshold), fires the higher-counter neuron\n// and marks the lower-counter one dormant.\n\nimport { writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { JACCARD_THRESHOLD } from './constants';\nimport { tokenize, jaccardSimilarity } from './similarity';\nimport { fireNeuron } from './fire';\nimport { scanBrain } from './scanner';\n\nexport interface DedupResult {\n\tscanned: number;\n\tmerged: number;\n}\n\n/**\n * Run batch deduplication across all regions.\n */\nexport function runDedup(brainRoot: string): DedupResult {\n\tconst brain = scanBrain(brainRoot);\n\tlet scanned = 0;\n\tlet merged = 0;\n\n\tfor (const region of brain.regions) {\n\t\tconst neurons = region.neurons.filter((n) => !n.isDormant);\n\t\tscanned += neurons.length;\n\n\t\t// O(n^2) pairwise comparison within each region\n\t\tconst consumed = new Set<number>();\n\t\tfor (let i = 0; i < neurons.length; i++) {\n\t\t\tif (consumed.has(i)) continue;\n\t\t\tconst ni = neurons[i]!;\n\t\t\tconst tokensI = tokenize(ni.name);\n\n\t\t\tfor (let j = i + 1; j < neurons.length; j++) {\n\t\t\t\tif (consumed.has(j)) continue;\n\t\t\t\tconst nj = neurons[j]!;\n\t\t\t\tconst tokensJ = tokenize(nj.name);\n\t\t\t\tconst sim = jaccardSimilarity(tokensI, tokensJ);\n\n\t\t\t\tif (sim >= JACCARD_THRESHOLD) {\n\t\t\t\t\t// Keep the one with higher counter, mark other dormant\n\t\t\t\t\tconst [keep, drop] = ni.counter >= nj.counter\n\t\t\t\t\t\t? [ni, nj] : [nj, ni];\n\n\t\t\t\t\t// Fire the keeper to absorb the dropped counter\n\t\t\t\t\tconst relKeep = `${region.name}/${keep.path}`;\n\t\t\t\t\tfireNeuron(brainRoot, relKeep);\n\n\t\t\t\t\t// Mark the dropped neuron dormant\n\t\t\t\t\twriteFileSync(\n\t\t\t\t\t\tjoin(drop.fullPath, 'dedup.dormant'),\n\t\t\t\t\t\t`Merged into ${keep.path} on ${new Date().toISOString()}`,\n\t\t\t\t\t\t'utf8',\n\t\t\t\t\t);\n\n\t\t\t\t\tconsumed.add(ni === drop ? i : j);\n\t\t\t\t\tmerged++;\n\t\t\t\t\tconsole.log(`\\u{1F500} merged: \"${drop.path}\" → \"${keep.path}\" (sim=${sim.toFixed(2)})`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tconsole.log(`\\u{1F9F9} dedup: scanned ${scanned} neurons, merged ${merged}`);\n\treturn { scanned, merged };\n}\n","// hebbian — Git Snapshot\n//\n// Creates a git commit of the current brain state for audit trail.\n// Only commits if there are changes.\n\nimport { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Create a git snapshot of the brain directory.\n */\nexport function gitSnapshot(brainRoot: string): boolean {\n\t// Check if brain is inside a git repo\n\tif (!existsSync(join(brainRoot, '.git'))) {\n\t\t// Try parent directories\n\t\ttry {\n\t\t\texecSync('git rev-parse --is-inside-work-tree', { cwd: brainRoot, stdio: 'pipe' });\n\t\t} catch {\n\t\t\tconsole.log('\\u{26A0}\\uFE0F Not a git repository. Run `git init` in the brain directory first.');\n\t\t\treturn false;\n\t\t}\n\t}\n\n\ttry {\n\t\t// Check for changes\n\t\tconst status = execSync('git status --porcelain .', { cwd: brainRoot, encoding: 'utf8' });\n\t\tif (!status.trim()) {\n\t\t\tconsole.log('\\u{2705} No changes to snapshot.');\n\t\t\treturn false;\n\t\t}\n\n\t\t// Stage and commit\n\t\texecSync('git add .', { cwd: brainRoot, stdio: 'pipe' });\n\t\tconst ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);\n\t\texecSync(`git commit -m \"hebbian snapshot ${ts}\"`, { cwd: brainRoot, stdio: 'pipe' });\n\n\t\tconsole.log(`\\u{1F4F8} snapshot: committed brain state at ${ts}`);\n\t\treturn true;\n\t} catch (err: unknown) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tconsole.error(`\\u{274C} snapshot failed: ${message}`);\n\t\treturn false;\n\t}\n}\n","// hebbian — Watch Mode\n//\n// Watches the brain directory for filesystem changes and auto-recompiles\n// all tiers when changes are detected. Uses hash-based change detection\n// to avoid redundant writes.\n\nimport { watch } from 'node:fs';\nimport { scanBrain } from './scanner';\nimport { runSubsumption } from './subsumption';\nimport { writeAllTiers } from './emit';\nimport type { SubsumptionResult } from './types';\n\n/**\n * Start watching a brain directory for changes.\n * Auto-recompiles tiers when neurons are added/modified/removed.\n */\nexport async function startWatch(brainRoot: string): Promise<void> {\n\tlet lastHash = '';\n\tlet debounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n\t/** Scan brain and recompile if state changed. */\n\tfunction recompile(): void {\n\t\tconst brain = scanBrain(brainRoot);\n\t\tconst result = runSubsumption(brain);\n\t\tconst hash = computeHash(result);\n\n\t\tif (hash === lastHash) return;\n\t\tlastHash = hash;\n\n\t\twriteAllTiers(brainRoot, result, brain);\n\t\tconst ts = new Date().toLocaleTimeString();\n\t\tconsole.log(`[${ts}] \\u{1F504} recompiled — ${result.firedNeurons} neurons, activation ${result.totalCounter}${result.bombSource ? ` \\u{1F4A3} BOMB: ${result.bombSource}` : ''}`);\n\t}\n\n\t// Initial compilation\n\trecompile();\n\tconsole.log(`\\u{1F440} watching: ${brainRoot}`);\n\tconsole.log(' Press Ctrl+C to stop.\\n');\n\n\t// Watch for filesystem changes\n\ttry {\n\t\tconst watcher = watch(brainRoot, { recursive: true }, (eventType, filename) => {\n\t\t\tif (!filename) return;\n\t\t\t// Ignore _index.md and _rules.md (our own output)\n\t\t\tif (filename.endsWith('_index.md') || filename.endsWith('_rules.md')) return;\n\t\t\t// Ignore hidden/internal\n\t\t\tif (filename.startsWith('.') || filename.includes('/_') || filename.includes('\\\\_')) return;\n\n\t\t\t// Debounce: wait 200ms after last change before recompiling\n\t\t\tif (debounceTimer) clearTimeout(debounceTimer);\n\t\t\tdebounceTimer = setTimeout(recompile, 200);\n\t\t});\n\n\t\t// Keep process alive\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tprocess.on('SIGINT', () => {\n\t\t\t\twatcher.close();\n\t\t\t\tconsole.log('\\n\\u{1F44B} watch stopped.');\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t} catch (err: unknown) {\n\t\tif (err && typeof err === 'object' && 'code' in err && err.code === 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM') {\n\t\t\tconsole.error('Recursive fs.watch not supported on this platform. Use Node.js >= 22.');\n\t\t} else {\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\n/**\n * Compute a simple hash from the subsumption result for change detection.\n */\nfunction computeHash(result: SubsumptionResult): string {\n\treturn `${result.firedNeurons}:${result.totalCounter}:${result.bombSource}:${result.activeRegions.length}`;\n}\n","// hebbian — Episode Logging (Circular Buffer)\n//\n// Writes events to hippocampus/session_log/ as memoryN.neuron files.\n// Circular buffer: max 100 entries. When full, overwrites oldest.\n//\n// Port from: NeuronFS/runtime/main.go lines 1300-1342\n\nimport { readdirSync, readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst MAX_EPISODES = 100;\nconst SESSION_LOG_DIR = 'hippocampus/session_log';\n\nexport interface Episode {\n\tts: string;\n\ttype: string;\n\tpath: string;\n\tdetail: string;\n}\n\n/**\n * Log an episode to the hippocampus session log.\n * Circular buffer — writes to memoryN.neuron, wraps at MAX_EPISODES.\n */\nexport function logEpisode(brainRoot: string, type: string, path: string, detail: string): void {\n\tconst logDir = join(brainRoot, SESSION_LOG_DIR);\n\tif (!existsSync(logDir)) {\n\t\tmkdirSync(logDir, { recursive: true });\n\t}\n\n\tconst nextSlot = getNextSlot(logDir);\n\tconst episode: Episode = {\n\t\tts: new Date().toISOString(),\n\t\ttype,\n\t\tpath,\n\t\tdetail,\n\t};\n\n\twriteFileSync(\n\t\tjoin(logDir, `memory${nextSlot}.neuron`),\n\t\tJSON.stringify(episode),\n\t\t'utf8',\n\t);\n}\n\n/**\n * Read all episodes from the session log, sorted by timestamp.\n */\nexport function readEpisodes(brainRoot: string): Episode[] {\n\tconst logDir = join(brainRoot, SESSION_LOG_DIR);\n\tif (!existsSync(logDir)) return [];\n\n\tconst episodes: Episode[] = [];\n\tlet entries;\n\ttry {\n\t\tentries = readdirSync(logDir);\n\t} catch {\n\t\treturn [];\n\t}\n\n\tfor (const entry of entries) {\n\t\tif (!entry.startsWith('memory') || !entry.endsWith('.neuron')) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(join(logDir, entry), 'utf8');\n\t\t\tif (content.trim()) {\n\t\t\t\tepisodes.push(JSON.parse(content) as Episode);\n\t\t\t}\n\t\t} catch {\n\t\t\t// skip malformed entries\n\t\t}\n\t}\n\n\tepisodes.sort((a, b) => a.ts.localeCompare(b.ts));\n\treturn episodes;\n}\n\n/**\n * Find the next circular buffer slot (1-based, wraps at MAX_EPISODES).\n */\nfunction getNextSlot(logDir: string): number {\n\tlet maxSlot = 0;\n\ttry {\n\t\tfor (const entry of readdirSync(logDir)) {\n\t\t\tif (entry.startsWith('memory') && entry.endsWith('.neuron')) {\n\t\t\t\tconst n = parseInt(entry.replace('memory', '').replace('.neuron', ''), 10);\n\t\t\t\tif (!isNaN(n) && n > maxSlot) maxSlot = n;\n\t\t\t}\n\t\t}\n\t} catch {}\n\n\tconst next = maxSlot + 1;\n\t// Wrap around: if we exceed max, start overwriting from 1\n\treturn next > MAX_EPISODES ? ((maxSlot % MAX_EPISODES) + 1) : next;\n}\n","// hebbian — Inbox Processing\n//\n// Parses _inbox/corrections.jsonl and auto-creates/fires neurons from\n// AI corrections. Security checks prevent path traversal. Only PM/admin\n// roles can award dopamine (inflation filter).\n//\n// Port from: NeuronFS/runtime/main.go lines 1425-1544\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { REGIONS } from './constants';\nimport { growNeuron } from './grow';\nimport { fireNeuron } from './fire';\nimport { signalNeuron } from './signal';\nimport { logEpisode } from './episode';\n\nconst INBOX_DIR = '_inbox';\nconst CORRECTIONS_FILE = 'corrections.jsonl';\nconst DOPAMINE_ALLOWED_ROLES = ['pm', 'admin', 'lead'];\n\nexport interface Correction {\n\tts: string;\n\ttype: 'correction';\n\ttext: string;\n\tpath: string;\n\tcounter_add: number;\n\tauthor: string;\n\tdopamine?: number;\n}\n\nexport interface InboxResult {\n\tprocessed: number;\n\tskipped: number;\n\terrors: string[];\n}\n\n/**\n * Process the inbox corrections file.\n * Each line is a JSON object describing a correction to apply.\n */\nexport function processInbox(brainRoot: string): InboxResult {\n\tconst inboxPath = join(brainRoot, INBOX_DIR, CORRECTIONS_FILE);\n\n\tif (!existsSync(inboxPath)) {\n\t\treturn { processed: 0, skipped: 0, errors: [] };\n\t}\n\n\tconst content = readFileSync(inboxPath, 'utf8').trim();\n\tif (!content) {\n\t\treturn { processed: 0, skipped: 0, errors: [] };\n\t}\n\n\tconst lines = content.split('\\n').filter(Boolean);\n\tlet processed = 0;\n\tlet skipped = 0;\n\tconst errors: string[] = [];\n\n\tfor (const line of lines) {\n\t\tlet correction: Correction;\n\t\ttry {\n\t\t\tcorrection = JSON.parse(line) as Correction;\n\t\t} catch {\n\t\t\terrors.push(`Malformed JSON: ${line.slice(0, 80)}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Validate required fields\n\t\tif (!correction.path || !correction.type) {\n\t\t\terrors.push(`Missing path or type: ${line.slice(0, 80)}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Security: path traversal check\n\t\tif (!isPathSafe(correction.path)) {\n\t\t\terrors.push(`Path traversal blocked: ${correction.path}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Security: validate region\n\t\tconst region = correction.path.split('/')[0];\n\t\tif (!region || !(REGIONS as readonly string[]).includes(region)) {\n\t\t\terrors.push(`Invalid region in path: ${correction.path}`);\n\t\t\tskipped++;\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tapplyCorrection(brainRoot, correction);\n\t\t\tprocessed++;\n\t\t} catch (err) {\n\t\t\terrors.push(`Failed to apply ${correction.path}: ${(err as Error).message}`);\n\t\t\tskipped++;\n\t\t}\n\t}\n\n\t// Clear the inbox file after processing\n\twriteFileSync(inboxPath, '', 'utf8');\n\n\tconsole.log(`📥 inbox: processed ${processed}, skipped ${skipped}`);\n\tif (errors.length > 0) {\n\t\tfor (const err of errors) {\n\t\t\tconsole.log(` ⚠️ ${err}`);\n\t\t}\n\t}\n\n\treturn { processed, skipped, errors };\n}\n\n/**\n * Apply a single correction entry.\n */\nfunction applyCorrection(brainRoot: string, correction: Correction): void {\n\tconst neuronPath = correction.path;\n\tconst fullPath = join(brainRoot, neuronPath);\n\tconst counterAdd = Math.max(1, correction.counter_add || 1);\n\n\tif (existsSync(fullPath)) {\n\t\t// Neuron exists — fire N times\n\t\tfor (let i = 0; i < counterAdd; i++) {\n\t\t\tfireNeuron(brainRoot, neuronPath);\n\t\t}\n\t} else {\n\t\t// Neuron doesn't exist — grow + fire (N-1)\n\t\tgrowNeuron(brainRoot, neuronPath);\n\t\tfor (let i = 1; i < counterAdd; i++) {\n\t\t\tfireNeuron(brainRoot, neuronPath);\n\t\t}\n\t}\n\n\t// Dopamine inflation filter: only allowed roles can award dopamine\n\tif (correction.dopamine && correction.dopamine > 0) {\n\t\tconst author = (correction.author || '').toLowerCase();\n\t\tif (DOPAMINE_ALLOWED_ROLES.includes(author)) {\n\t\t\tsignalNeuron(brainRoot, neuronPath, 'dopamine');\n\t\t}\n\t}\n\n\tlogEpisode(brainRoot, 'inbox', neuronPath, correction.text || '');\n}\n\n/**\n * Security: check path for traversal attacks.\n */\nfunction isPathSafe(path: string): boolean {\n\tif (path.includes('..')) return false;\n\tif (path.startsWith('/')) return false;\n\tif (path.includes('\\\\')) return false;\n\t// Block null bytes\n\tif (path.includes('\\0')) return false;\n\treturn true;\n}\n\n/**\n * Ensure the inbox directory and corrections file exist.\n */\nexport function ensureInbox(brainRoot: string): string {\n\tconst inboxDir = join(brainRoot, INBOX_DIR);\n\tif (!existsSync(inboxDir)) {\n\t\tmkdirSync(inboxDir, { recursive: true });\n\t}\n\tconst filePath = join(inboxDir, CORRECTIONS_FILE);\n\tif (!existsSync(filePath)) {\n\t\twriteFileSync(filePath, '', 'utf8');\n\t}\n\treturn filePath;\n}\n\n/**\n * Append a correction entry to the inbox.\n */\nexport function appendCorrection(brainRoot: string, correction: Correction): void {\n\tconst filePath = ensureInbox(brainRoot);\n\tconst line = JSON.stringify(correction) + '\\n';\n\tconst existing = readFileSync(filePath, 'utf8');\n\twriteFileSync(filePath, existing + line, 'utf8');\n}\n","// hebbian — REST API Server\n//\n// Programmatic brain manipulation via HTTP. Zero dependencies (node:http).\n// Enables external tools (n8n, webhooks, dashboards) to interact with hebbian.\n//\n// Port from: NeuronFS/runtime/main.go lines 2099-2434\n\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport { scanBrain } from './scanner';\nimport { runSubsumption } from './subsumption';\nimport { fireNeuron } from './fire';\nimport { rollbackNeuron } from './rollback';\nimport { growNeuron } from './grow';\nimport { signalNeuron } from './signal';\nimport { runDecay } from './decay';\nimport { runDedup } from './dedup';\nimport { writeAllTiers } from './emit';\nimport { processInbox } from './inbox';\nimport { REGIONS, REGION_ICONS, REGION_KO, type SignalType } from './constants';\nimport type { RegionName } from './constants';\n\nlet lastAPIActivity = Date.now();\n\nexport interface ReportEntry {\n\tts: string;\n\tmessage: string;\n\tpriority: 'low' | 'normal' | 'high' | 'critical';\n}\n\nconst pendingReports: ReportEntry[] = [];\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// JSON Response Builders\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nfunction buildHealthJSON(brainRoot: string) {\n\tconst brain = scanBrain(brainRoot);\n\tconst result = runSubsumption(brain);\n\treturn {\n\t\tstatus: 'ok',\n\t\tbrain: brainRoot,\n\t\tneurons: result.totalNeurons,\n\t\tactiveNeurons: result.firedNeurons,\n\t\ttotalActivation: result.totalCounter,\n\t\tbombSource: result.bombSource || null,\n\t\tlastActivity: new Date(lastAPIActivity).toISOString(),\n\t\tuptime: process.uptime(),\n\t};\n}\n\nfunction buildBrainJSON(brainRoot: string) {\n\tconst brain = scanBrain(brainRoot);\n\tconst result = runSubsumption(brain);\n\treturn {\n\t\troot: brain.root,\n\t\tregions: brain.regions.map((region) => ({\n\t\t\tname: region.name,\n\t\t\ticon: REGION_ICONS[region.name as RegionName] || '',\n\t\t\tko: REGION_KO[region.name as RegionName] || '',\n\t\t\tpriority: region.priority,\n\t\t\thasBomb: region.hasBomb,\n\t\t\tneurons: region.neurons.map((n) => ({\n\t\t\t\tname: n.name,\n\t\t\t\tpath: n.path,\n\t\t\t\tcounter: n.counter,\n\t\t\t\tcontra: n.contra,\n\t\t\t\tdopamine: n.dopamine,\n\t\t\t\thasBomb: n.hasBomb,\n\t\t\t\thasMemory: n.hasMemory,\n\t\t\t\tisDormant: n.isDormant,\n\t\t\t\tdepth: n.depth,\n\t\t\t\tmodTime: n.modTime.getTime(),\n\t\t\t})),\n\t\t\taxons: region.axons,\n\t\t})),\n\t\tbombSource: result.bombSource || null,\n\t\tfiredNeurons: result.firedNeurons,\n\t\ttotalNeurons: result.totalNeurons,\n\t\ttotalCounter: result.totalCounter,\n\t};\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// HTTP Helpers\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nfunction json(res: ServerResponse, data: unknown, status = 200): void {\n\tconst body = JSON.stringify(data);\n\tres.writeHead(status, {\n\t\t'Content-Type': 'application/json',\n\t\t'Access-Control-Allow-Origin': '*',\n\t\t'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n\t\t'Access-Control-Allow-Headers': 'Content-Type',\n\t});\n\tres.end(body);\n}\n\nfunction error(res: ServerResponse, message: string, status = 400): void {\n\tjson(res, { error: message }, status);\n}\n\nasync function readBody(req: IncomingMessage): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks: Buffer[] = [];\n\t\treq.on('data', (chunk: Buffer) => chunks.push(chunk));\n\t\treq.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n\t\treq.on('error', reject);\n\t});\n}\n\nasync function parseJSON(req: IncomingMessage): Promise<Record<string, unknown>> {\n\tconst body = await readBody(req);\n\tif (!body.trim()) return {};\n\treturn JSON.parse(body) as Record<string, unknown>;\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// Route Handlers\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\nasync function handleRequest(\n\treq: IncomingMessage,\n\tres: ServerResponse,\n\tbrainRoot: string,\n): Promise<void> {\n\tconst url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);\n\tconst path = url.pathname;\n\tconst method = req.method || 'GET';\n\n\t// CORS preflight\n\tif (method === 'OPTIONS') {\n\t\tjson(res, null, 204);\n\t\treturn;\n\t}\n\n\t// Track activity on mutations\n\tconst isMutation = method === 'POST';\n\tif (isMutation) lastAPIActivity = Date.now();\n\n\ttry {\n\t\t// GET endpoints\n\t\tif (method === 'GET') {\n\t\t\tswitch (path) {\n\t\t\t\tcase '/api/health':\n\t\t\t\t\tjson(res, buildHealthJSON(brainRoot));\n\t\t\t\t\treturn;\n\t\t\t\tcase '/api/brain':\n\t\t\t\t\tjson(res, buildBrainJSON(brainRoot));\n\t\t\t\t\treturn;\n\t\t\t\tcase '/api/read': {\n\t\t\t\t\tconst region = url.searchParams.get('region');\n\t\t\t\t\tif (!region || !(REGIONS as readonly string[]).includes(region)) {\n\t\t\t\t\t\terror(res, `Invalid region. Valid: ${REGIONS.join(', ')}`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst brain = scanBrain(brainRoot);\n\t\t\t\t\tconst result = runSubsumption(brain);\n\t\t\t\t\tconst regionData = result.activeRegions.find((r) => r.name === region);\n\t\t\t\t\tif (!regionData) {\n\t\t\t\t\t\terror(res, `Region \"${region}\" is blocked or empty`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Auto-fire top 3 for RAG retrieval\n\t\t\t\t\tconst top3 = [...regionData.neurons]\n\t\t\t\t\t\t.filter((n) => !n.isDormant)\n\t\t\t\t\t\t.sort((a, b) => b.counter - a.counter)\n\t\t\t\t\t\t.slice(0, 3);\n\t\t\t\t\tfor (const n of top3) {\n\t\t\t\t\t\tfireNeuron(brainRoot, `${region}/${n.path}`);\n\t\t\t\t\t}\n\t\t\t\t\tjson(res, {\n\t\t\t\t\t\tregion: region,\n\t\t\t\t\t\tneurons: regionData.neurons,\n\t\t\t\t\t\tfired: top3.map((n) => n.path),\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/reports':\n\t\t\t\t\tjson(res, { reports: pendingReports });\n\t\t\t\t\treturn;\n\t\t\t\tdefault:\n\t\t\t\t\terror(res, 'Not found', 404);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// POST endpoints\n\t\tif (method === 'POST') {\n\t\t\tconst body = await parseJSON(req);\n\n\t\t\tswitch (path) {\n\t\t\t\tcase '/api/grow': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tif (!neuronPath) { error(res, 'Missing \"path\"'); return; }\n\t\t\t\t\tconst result = growNeuron(brainRoot, neuronPath);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/fire': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tif (!neuronPath) { error(res, 'Missing \"path\"'); return; }\n\t\t\t\t\tconst counter = fireNeuron(brainRoot, neuronPath);\n\t\t\t\t\tjson(res, { path: neuronPath, counter });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/signal': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tconst signalType = body.type as string;\n\t\t\t\t\tif (!neuronPath || !signalType) { error(res, 'Missing \"path\" or \"type\"'); return; }\n\t\t\t\t\tsignalNeuron(brainRoot, neuronPath, signalType as SignalType);\n\t\t\t\t\tjson(res, { path: neuronPath, type: signalType });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/rollback': {\n\t\t\t\t\tconst neuronPath = body.path as string;\n\t\t\t\t\tif (!neuronPath) { error(res, 'Missing \"path\"'); return; }\n\t\t\t\t\tconst counter = rollbackNeuron(brainRoot, neuronPath);\n\t\t\t\t\tjson(res, { path: neuronPath, counter });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/decay': {\n\t\t\t\t\tconst days = typeof body.days === 'number' ? body.days : 30;\n\t\t\t\t\tconst result = runDecay(brainRoot, days);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/dedup': {\n\t\t\t\t\tconst result = runDedup(brainRoot);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/inject': {\n\t\t\t\t\tconst brain = scanBrain(brainRoot);\n\t\t\t\t\tconst result = runSubsumption(brain);\n\t\t\t\t\twriteAllTiers(brainRoot, result, brain);\n\t\t\t\t\tjson(res, { injected: true });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/inbox': {\n\t\t\t\t\tconst result = processInbox(brainRoot);\n\t\t\t\t\tjson(res, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase '/api/report': {\n\t\t\t\t\tconst message = body.message as string;\n\t\t\t\t\tconst priority = (body.priority as string) || 'normal';\n\t\t\t\t\tif (!message) { error(res, 'Missing \"message\"'); return; }\n\t\t\t\t\tconst entry: ReportEntry = {\n\t\t\t\t\t\tts: new Date().toISOString(),\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tpriority: priority as ReportEntry['priority'],\n\t\t\t\t\t};\n\t\t\t\t\tpendingReports.push(entry);\n\t\t\t\t\tjson(res, entry);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\terror(res, 'Not found', 404);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\terror(res, 'Method not allowed', 405);\n\t} catch (err) {\n\t\terror(res, (err as Error).message, 500);\n\t}\n}\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// Server\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Start the hebbian REST API server.\n */\nexport function startAPI(brainRoot: string, port = 9090): ReturnType<typeof createServer> {\n\tconst server = createServer((req, res) => {\n\t\thandleRequest(req, res, brainRoot).catch((err) => {\n\t\t\terror(res, (err as Error).message, 500);\n\t\t});\n\t});\n\n\tserver.listen(port, () => {\n\t\tconsole.log(`🧠 hebbian API listening on http://localhost:${port}`);\n\t\tconsole.log(` Brain: ${brainRoot}`);\n\t\tconsole.log('');\n\t\tconsole.log(' Endpoints:');\n\t\tconsole.log(' GET /api/health Process health + brain stats');\n\t\tconsole.log(' GET /api/brain Full brain state JSON');\n\t\tconsole.log(' GET /api/read?region=X Read region (auto-fires top 3)');\n\t\tconsole.log(' GET /api/reports List pending reports');\n\t\tconsole.log(' POST /api/grow {\"path\":\"cortex/...\"}');\n\t\tconsole.log(' POST /api/fire {\"path\":\"cortex/...\"}');\n\t\tconsole.log(' POST /api/signal {\"path\":\"...\",\"type\":\"dopamine\"}');\n\t\tconsole.log(' POST /api/rollback {\"path\":\"cortex/...\"}');\n\t\tconsole.log(' POST /api/decay {\"days\":30}');\n\t\tconsole.log(' POST /api/dedup Batch merge similar neurons');\n\t\tconsole.log(' POST /api/inject Force re-emit all tiers');\n\t\tconsole.log(' POST /api/inbox Process corrections inbox');\n\t\tconsole.log(' POST /api/report {\"message\":\"...\",\"priority\":\"normal\"}');\n\t});\n\n\treturn server;\n}\n\n/**\n * Get the last API activity timestamp.\n */\nexport function getLastActivity(): number {\n\treturn lastAPIActivity;\n}\n\n/**\n * Get pending reports (for external access).\n */\nexport function getPendingReports(): ReportEntry[] {\n\treturn pendingReports;\n}\n\n/**\n * Clear pending reports.\n */\nexport function clearReports(): void {\n\tpendingReports.length = 0;\n}\n","// hebbian — Claude Code Hooks Integration\n//\n// Manages Claude Code hooks in .claude/settings.local.json.\n// Uses [hebbian] statusMessage marker for ownership tracking.\n//\n// SessionStart hook: refreshes CLAUDE.md with latest brain state\n// Stop hook: digests conversation transcript for corrections\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { HOOK_MARKER, REGIONS } from './constants';\nimport { initBrain } from './init';\n\nconst SETTINGS_DIR = '.claude';\nconst SETTINGS_FILE = 'settings.local.json';\n\nexport interface HookStatus {\n\tinstalled: boolean;\n\tpath: string;\n\tevents: string[];\n}\n\ninterface HookEntry {\n\ttype: string;\n\tcommand: string;\n\ttimeout?: number;\n\tstatusMessage?: string;\n}\n\ninterface HookGroup {\n\tmatcher?: string;\n\thooks: HookEntry[];\n}\n\n/**\n * Install hebbian hooks into .claude/settings.local.json.\n * Deep-merges with existing settings. Uses statusMessage marker for ownership.\n */\nexport function installHooks(brainRoot: string, projectRoot?: string): void {\n\tconst root = projectRoot || process.cwd();\n\tconst resolvedBrain = resolve(brainRoot);\n\n\t// Auto-init brain if it doesn't exist\n\tif (!existsSync(resolvedBrain) || !hasBrainRegions(resolvedBrain)) {\n\t\tinitBrain(resolvedBrain);\n\t}\n\n\tconst settingsDir = join(root, SETTINGS_DIR);\n\tconst settingsPath = join(settingsDir, SETTINGS_FILE);\n\n\t// Determine if we need --brain flag\n\tconst defaultBrain = resolve(root, 'brain');\n\tconst brainFlag = resolvedBrain === defaultBrain ? '' : ` --brain ${resolvedBrain}`;\n\n\t// Read existing settings or start fresh\n\tlet settings: Record<string, unknown> = {};\n\tif (existsSync(settingsPath)) {\n\t\ttry {\n\t\t\tsettings = JSON.parse(readFileSync(settingsPath, 'utf8'));\n\t\t} catch {\n\t\t\tconsole.log(`\\u26A0\\uFE0F settings.local.json was malformed, overwriting`);\n\t\t}\n\t}\n\n\t// Ensure hooks object exists\n\tif (!settings.hooks || typeof settings.hooks !== 'object') {\n\t\tsettings.hooks = {};\n\t}\n\tconst hooks = settings.hooks as Record<string, HookGroup[]>;\n\n\t// Define hebbian hooks\n\tconst hebbianHooks: Array<{ event: string; matcher?: string; entry: HookEntry }> = [\n\t\t{\n\t\t\tevent: 'SessionStart',\n\t\t\tmatcher: 'startup|resume',\n\t\t\tentry: {\n\t\t\t\ttype: 'command',\n\t\t\t\tcommand: `hebbian emit claude${brainFlag}`,\n\t\t\t\ttimeout: 10,\n\t\t\t\tstatusMessage: `${HOOK_MARKER} refreshing brain`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tevent: 'Stop',\n\t\t\tentry: {\n\t\t\t\ttype: 'command',\n\t\t\t\tcommand: `hebbian digest${brainFlag}`,\n\t\t\t\ttimeout: 30,\n\t\t\t\tstatusMessage: `${HOOK_MARKER} digesting session`,\n\t\t\t},\n\t\t},\n\t];\n\n\t// Install each hook\n\tfor (const { event, matcher, entry } of hebbianHooks) {\n\t\tif (!hooks[event]) {\n\t\t\thooks[event] = [];\n\t\t}\n\n\t\t// Find existing hebbian group for this event\n\t\tconst existingIdx = hooks[event]!.findIndex((group) =>\n\t\t\tgroup.hooks.some((h) => h.statusMessage?.startsWith(HOOK_MARKER)),\n\t\t);\n\n\t\tconst group: HookGroup = {\n\t\t\t...(matcher ? { matcher } : {}),\n\t\t\thooks: [entry],\n\t\t};\n\n\t\tif (existingIdx >= 0) {\n\t\t\t// Update existing entry\n\t\t\thooks[event]![existingIdx] = group;\n\t\t} else {\n\t\t\t// Append new entry\n\t\t\thooks[event]!.push(group);\n\t\t}\n\t}\n\n\t// Write back\n\tif (!existsSync(settingsDir)) {\n\t\tmkdirSync(settingsDir, { recursive: true });\n\t}\n\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf8');\n\n\tconsole.log(`\\u2705 hebbian hooks installed at ${settingsPath}`);\n\tconsole.log(` SessionStart \\u2192 hebbian emit claude${brainFlag}`);\n\tconsole.log(` Stop \\u2192 hebbian digest${brainFlag}`);\n}\n\n/**\n * Remove hebbian hooks from .claude/settings.local.json.\n * Preserves non-hebbian hooks and other settings.\n */\nexport function uninstallHooks(projectRoot?: string): void {\n\tconst root = projectRoot || process.cwd();\n\tconst settingsPath = join(root, SETTINGS_DIR, SETTINGS_FILE);\n\n\tif (!existsSync(settingsPath)) {\n\t\tconsole.log('No hooks installed (settings.local.json not found)');\n\t\treturn;\n\t}\n\n\tlet settings: Record<string, unknown>;\n\ttry {\n\t\tsettings = JSON.parse(readFileSync(settingsPath, 'utf8'));\n\t} catch {\n\t\tconsole.log('settings.local.json is malformed, nothing to uninstall');\n\t\treturn;\n\t}\n\n\tif (!settings.hooks || typeof settings.hooks !== 'object') {\n\t\tconsole.log('No hooks found in settings.local.json');\n\t\treturn;\n\t}\n\n\tconst hooks = settings.hooks as Record<string, HookGroup[]>;\n\tlet removed = 0;\n\n\tfor (const event of Object.keys(hooks)) {\n\t\tconst before = hooks[event]!.length;\n\t\thooks[event] = hooks[event]!.filter(\n\t\t\t(group) => !group.hooks.some((h) => h.statusMessage?.startsWith(HOOK_MARKER)),\n\t\t);\n\t\tremoved += before - hooks[event]!.length;\n\n\t\t// Clean up empty event arrays\n\t\tif (hooks[event]!.length === 0) {\n\t\t\tdelete hooks[event];\n\t\t}\n\t}\n\n\t// Clean up empty hooks object\n\tif (Object.keys(hooks).length === 0) {\n\t\tdelete settings.hooks;\n\t}\n\n\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n', 'utf8');\n\tconsole.log(`\\u2705 removed ${removed} hebbian hook(s) from ${settingsPath}`);\n}\n\n/**\n * Check if hebbian hooks are installed.\n */\nexport function checkHooks(projectRoot?: string): HookStatus {\n\tconst root = projectRoot || process.cwd();\n\tconst settingsPath = join(root, SETTINGS_DIR, SETTINGS_FILE);\n\n\tconst status: HookStatus = {\n\t\tinstalled: false,\n\t\tpath: settingsPath,\n\t\tevents: [],\n\t};\n\n\tif (!existsSync(settingsPath)) {\n\t\tconsole.log(`\\u274C hebbian hooks not installed (${settingsPath} not found)`);\n\t\treturn status;\n\t}\n\n\tlet settings: Record<string, unknown>;\n\ttry {\n\t\tsettings = JSON.parse(readFileSync(settingsPath, 'utf8'));\n\t} catch {\n\t\tconsole.log(`\\u274C settings.local.json is malformed`);\n\t\treturn status;\n\t}\n\n\tif (!settings.hooks || typeof settings.hooks !== 'object') {\n\t\tconsole.log(`\\u274C no hooks in ${settingsPath}`);\n\t\treturn status;\n\t}\n\n\tconst hooks = settings.hooks as Record<string, HookGroup[]>;\n\n\tfor (const event of Object.keys(hooks)) {\n\t\tconst hasHebbian = hooks[event]!.some((group) =>\n\t\t\tgroup.hooks.some((h) => h.statusMessage?.startsWith(HOOK_MARKER)),\n\t\t);\n\t\tif (hasHebbian) {\n\t\t\tstatus.events.push(event);\n\t\t}\n\t}\n\n\tstatus.installed = status.events.length > 0;\n\n\tif (status.installed) {\n\t\tconsole.log(`\\u2705 hebbian hooks installed at ${settingsPath}`);\n\t\tfor (const event of status.events) {\n\t\t\tconsole.log(` ${event} \\u2714`);\n\t\t}\n\t} else {\n\t\tconsole.log(`\\u274C hebbian hooks not found in ${settingsPath}`);\n\t}\n\n\treturn status;\n}\n\n/**\n * Check if a directory contains brain regions.\n */\nfunction hasBrainRegions(dir: string): boolean {\n\tif (!existsSync(dir)) return false;\n\ttry {\n\t\tconst entries = readdirSync(dir);\n\t\treturn (REGIONS as readonly string[]).some((r) => entries.includes(r));\n\t} catch {\n\t\treturn false;\n\t}\n}\n","// hebbian — Conversation Digest (Correction Extraction)\n//\n// Parses Claude Code conversation transcripts (JSONL) and extracts\n// user corrections via pattern matching. Writes corrections to inbox,\n// auto-processes them, and logs an audit trail.\n//\n// Correction detection is deliberately heuristic — WS3 candidate staging\n// is the quality safety net for false positives.\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join, basename } from 'node:path';\nimport { MAX_CORRECTIONS_PER_SESSION, MIN_CORRECTION_LENGTH, DIGEST_LOG_DIR } from './constants';\nimport { growNeuron } from './grow';\nimport { logEpisode } from './episode';\nimport { tokenize } from './similarity';\n\nexport interface DigestResult {\n\tcorrections: number;\n\tskipped: number;\n\ttranscriptPath: string;\n\tsessionId: string;\n}\n\nexport interface ExtractedCorrection {\n\ttext: string;\n\tpath: string;\n\tprefix: 'NO' | 'DO';\n\tkeywords: string[];\n}\n\ninterface TranscriptLine {\n\ttype?: string;\n\tmessage?: {\n\t\trole?: string;\n\t\tcontent?: string | Array<{ type: string; text?: string }>;\n\t};\n\tsessionId?: string;\n\tuuid?: string;\n}\n\n// Negation patterns — user is telling the AI NOT to do something\nconst NEGATION_PATTERNS = [\n\t/\\bdon[''\\u2019]?t\\b/i,\n\t/\\bdo not\\b/i,\n\t/\\bstop\\s+\\w+ing\\b/i,\n\t/\\bnever\\b/i,\n\t/\\binstead\\b/i,\n\t/^no[,.\\s!]/i,\n\t/\\bdon[''\\u2019]?t\\s+use\\b/i,\n\t/\\bavoid\\b/i,\n\t// Korean negation\n\t/하지\\s*마/,\n\t/안\\s*돼/,\n\t/대신/,\n\t/쓰지\\s*마/,\n\t/않/,\n];\n\n// Affirmation patterns — user is telling the AI TO do something\nconst AFFIRMATION_PATTERNS = [\n\t/\\balways\\b/i,\n\t/\\bmust\\b/i,\n\t/\\bshould\\s+always\\b/i,\n\t/\\buse\\s+\\w+\\s+instead\\b/i,\n\t// Korean affirmation\n\t/항상/,\n\t/반드시/,\n];\n\n/**\n * Parse hook input from stdin to extract transcript path and session ID.\n */\nexport function readHookInput(stdin: string): { transcriptPath: string; sessionId: string } | null {\n\tif (!stdin.trim()) return null;\n\ttry {\n\t\tconst input = JSON.parse(stdin);\n\t\tif (input.transcript_path) {\n\t\t\tconst sessionId = input.session_id || basename(input.transcript_path, '.jsonl');\n\t\t\treturn { transcriptPath: input.transcript_path, sessionId };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Digest a conversation transcript and extract corrections.\n * Auto-processes inbox and writes audit log.\n */\nexport function digestTranscript(brainRoot: string, transcriptPath: string, sessionId?: string): DigestResult {\n\tif (!existsSync(transcriptPath)) {\n\t\tthrow new Error(`Transcript not found: ${transcriptPath}`);\n\t}\n\n\tconst resolvedSessionId = sessionId || basename(transcriptPath, '.jsonl');\n\n\t// Dedup check: skip if already digested\n\tconst logDir = join(brainRoot, DIGEST_LOG_DIR);\n\tconst logPath = join(logDir, `${resolvedSessionId}.jsonl`);\n\tif (existsSync(logPath)) {\n\t\tconsole.log(`\\u23ED already digested session ${resolvedSessionId}, skip`);\n\t\treturn { corrections: 0, skipped: 0, transcriptPath, sessionId: resolvedSessionId };\n\t}\n\n\t// Parse transcript\n\tconst messages = parseTranscript(transcriptPath);\n\n\t// Extract corrections\n\tconst corrections = extractCorrections(messages);\n\n\tif (corrections.length === 0) {\n\t\tconsole.log(`\\uD83D\\uDCDD digest: no corrections found in session ${resolvedSessionId}`);\n\t\t// Write empty audit log to mark as digested\n\t\twriteAuditLog(brainRoot, resolvedSessionId, []);\n\t\treturn { corrections: 0, skipped: messages.length, transcriptPath, sessionId: resolvedSessionId };\n\t}\n\n\t// Apply corrections via growNeuron (handles Jaccard dedup internally)\n\tlet applied = 0;\n\tconst auditEntries: Array<{ correction: ExtractedCorrection; applied: boolean }> = [];\n\n\tfor (const correction of corrections) {\n\t\ttry {\n\t\t\tgrowNeuron(brainRoot, correction.path);\n\t\t\tlogEpisode(brainRoot, 'digest', correction.path, correction.text);\n\t\t\tauditEntries.push({ correction, applied: true });\n\t\t\tapplied++;\n\t\t} catch (err) {\n\t\t\tconsole.log(` \\u26A0\\uFE0F failed to apply: ${correction.path} — ${(err as Error).message}`);\n\t\t\tauditEntries.push({ correction, applied: false });\n\t\t}\n\t}\n\n\t// Write audit log\n\twriteAuditLog(brainRoot, resolvedSessionId, auditEntries);\n\n\tconsole.log(`\\uD83D\\uDCDD digest: ${applied} correction(s) from session ${resolvedSessionId}`);\n\treturn {\n\t\tcorrections: applied,\n\t\tskipped: messages.length - corrections.length,\n\t\ttranscriptPath,\n\t\tsessionId: resolvedSessionId,\n\t};\n}\n\n/**\n * Parse a Claude Code conversation JSONL transcript.\n * Returns user message texts only.\n */\nfunction parseTranscript(transcriptPath: string): string[] {\n\tconst content = readFileSync(transcriptPath, 'utf8');\n\tconst lines = content.split('\\n').filter(Boolean);\n\tconst messages: string[] = [];\n\n\tfor (const line of lines) {\n\t\tlet entry: TranscriptLine;\n\t\ttry {\n\t\t\tentry = JSON.parse(line);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Only process user messages\n\t\tif (entry.type !== 'user') continue;\n\t\tif (!entry.message || entry.message.role !== 'user') continue;\n\n\t\tconst text = extractText(entry.message.content);\n\t\tif (text) messages.push(text);\n\t}\n\n\treturn messages;\n}\n\n/**\n * Extract text from message content (handles string or content block array).\n */\nfunction extractText(content: string | Array<{ type: string; text?: string }> | undefined): string | null {\n\tif (!content) return null;\n\tif (typeof content === 'string') return content;\n\tif (Array.isArray(content)) {\n\t\tconst texts = content\n\t\t\t.filter((block) => block.type === 'text' && block.text)\n\t\t\t.map((block) => block.text!);\n\t\treturn texts.length > 0 ? texts.join('\\n') : null;\n\t}\n\treturn null;\n}\n\n/**\n * Extract corrections from user messages using pattern matching.\n * Returns up to MAX_CORRECTIONS_PER_SESSION corrections.\n */\nexport function extractCorrections(messages: string[]): ExtractedCorrection[] {\n\tconst corrections: ExtractedCorrection[] = [];\n\n\tfor (const text of messages) {\n\t\tif (corrections.length >= MAX_CORRECTIONS_PER_SESSION) break;\n\n\t\t// Skip short messages\n\t\tif (text.length < MIN_CORRECTION_LENGTH) continue;\n\n\t\t// Skip commands (start with / or !)\n\t\tif (/^[\\/!]/.test(text.trim())) continue;\n\n\t\t// Skip questions (end with ?)\n\t\tif (text.trim().endsWith('?')) continue;\n\n\t\t// Check for correction patterns\n\t\tconst correction = detectCorrection(text);\n\t\tif (correction) {\n\t\t\tcorrections.push(correction);\n\t\t}\n\t}\n\n\treturn corrections;\n}\n\n/**\n * Detect if a message is a correction and extract structured data.\n */\nfunction detectCorrection(text: string): ExtractedCorrection | null {\n\tconst isNegation = NEGATION_PATTERNS.some((p) => p.test(text));\n\tconst isAffirmation = AFFIRMATION_PATTERNS.some((p) => p.test(text));\n\n\tif (!isNegation && !isAffirmation) return null;\n\n\tconst prefix = isNegation ? 'NO' : 'DO';\n\tconst keywords = extractKeywords(text);\n\n\tif (keywords.length === 0) return null;\n\n\t// Build neuron path: cortex/{PREFIX}_{keyword1}_{keyword2}\n\tconst pathSegment = `${prefix}_${keywords.slice(0, 4).join('_')}`;\n\tconst path = `cortex/${pathSegment}`;\n\n\treturn { text, path, prefix, keywords };\n}\n\n/**\n * Extract meaningful keywords from correction text.\n * Filters out common stop words and correction-specific words.\n */\nfunction extractKeywords(text: string): string[] {\n\tconst STOP_WORDS = new Set([\n\t\t'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',\n\t\t'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',\n\t\t'should', 'may', 'might', 'shall', 'can', 'need', 'dare', 'ought',\n\t\t'to', 'of', 'in', 'for', 'on', 'with', 'at', 'by', 'from', 'as',\n\t\t'into', 'through', 'during', 'before', 'after', 'above', 'below',\n\t\t'and', 'but', 'or', 'nor', 'not', 'so', 'yet', 'both', 'either',\n\t\t'neither', 'each', 'every', 'all', 'any', 'few', 'more', 'most',\n\t\t'other', 'some', 'such', 'no', 'only', 'own', 'same', 'than',\n\t\t'too', 'very', 'just', 'because', 'until', 'while', 'that', 'this',\n\t\t'these', 'those', 'it', 'its', 'i', 'me', 'my', 'we', 'us', 'you',\n\t\t'your', 'he', 'she', 'they', 'them', 'what', 'which', 'who', 'whom',\n\t\t// Correction-specific stop words\n\t\t'don', 'dont', 'stop', 'never', 'always', 'instead', 'use', 'avoid',\n\t\t'please', 'must', 'should', 'like', 'want', 'think',\n\t]);\n\n\tconst tokens = tokenize(text);\n\treturn tokens.filter((t) => !STOP_WORDS.has(t) && t.length > 2);\n}\n\n/**\n * Write audit log for digest session.\n */\nfunction writeAuditLog(\n\tbrainRoot: string,\n\tsessionId: string,\n\tentries: Array<{ correction: ExtractedCorrection; applied: boolean }>,\n): void {\n\tconst logDir = join(brainRoot, DIGEST_LOG_DIR);\n\tif (!existsSync(logDir)) {\n\t\tmkdirSync(logDir, { recursive: true });\n\t}\n\n\tconst logPath = join(logDir, `${sessionId}.jsonl`);\n\tconst lines = entries.map((e) =>\n\t\tJSON.stringify({\n\t\t\tts: new Date().toISOString(),\n\t\t\tpath: e.correction.path,\n\t\t\ttext: e.correction.text,\n\t\t\tprefix: e.correction.prefix,\n\t\t\tkeywords: e.correction.keywords,\n\t\t\tapplied: e.applied,\n\t\t}),\n\t);\n\n\t// Even if no entries, write empty file as dedup marker\n\twriteFileSync(logPath, lines.join('\\n') + (lines.length > 0 ? '\\n' : ''), 'utf8');\n}\n","// hebbian — Folder-as-Neuron Brain for Any AI Agent\n//\n// \"Neurons that fire together, wire together.\" — Donald Hebb (1949)\n//\n// USAGE:\n// hebbian init <path> Create brain with 7 regions\n// hebbian emit <target> [--brain <path>] Compile rules (claude/cursor/gemini/copilot/generic/all)\n// hebbian fire <neuron-path> Increment neuron counter\n// hebbian grow <neuron-path> Create neuron (with merge detection)\n// hebbian rollback <neuron-path> Decrement counter (min=1)\n// hebbian signal <type> <neuron-path> Add dopamine/bomb/memory signal\n// hebbian decay [--days N] Mark inactive neurons dormant (default 30 days)\n// hebbian watch [--brain <path>] Watch for changes + auto-recompile\n// hebbian claude install|uninstall|status Manage Claude Code hooks\n// hebbian digest [--transcript <path>] Extract corrections from conversation\n// hebbian diag Print brain diagnostics\n// hebbian stats Print brain statistics\n\nimport { parseArgs } from 'node:util';\nimport { resolve } from 'node:path';\nimport type { SignalType } from './constants';\nimport { resolveBrainRoot } from './constants';\n\nconst VERSION = '0.3.2';\n\nconst HELP = `\nhebbian v${VERSION} — Folder-as-neuron brain for any AI agent.\n\n \"Neurons that fire together, wire together.\" — Donald Hebb (1949)\n\nUSAGE:\n hebbian <command> [options]\n\nCOMMANDS:\n init <path> Create brain with 7 regions\n emit <target> [--brain <path>] Compile rules (claude/cursor/gemini/copilot/generic/all)\n fire <neuron-path> Increment neuron counter (+1)\n grow <neuron-path> Create neuron (with merge detection)\n rollback <neuron-path> Decrement neuron counter (min=1)\n signal <type> <neuron-path> Add signal (dopamine/bomb/memory)\n decay [--days N] Mark inactive neurons dormant (default 30)\n dedup Batch merge similar neurons (Jaccard >= 0.6)\n snapshot Git commit current brain state\n watch Watch for changes + auto-recompile\n api [--port N] Start REST API server (default 9090)\n inbox Process corrections inbox\n claude install|uninstall|status Manage Claude Code hooks\n digest [--transcript <path>] Extract corrections from conversation\n diag Print brain diagnostics\n stats Print brain statistics\n\nOPTIONS:\n --brain <path> Brain directory (default: $HEBBIAN_BRAIN or ./brain)\n --help, -h Show this help\n --version, -v Show version\n\nEXAMPLES:\n hebbian init ./my-brain\n hebbian grow cortex/frontend/NO_console_log --brain ./my-brain\n hebbian fire cortex/frontend/NO_console_log --brain ./my-brain\n hebbian emit claude --brain ./my-brain\n hebbian emit all\n`.trim();\n\n/** Read all data from stdin (non-blocking, returns empty string if no data). */\nfunction readStdin(): Promise<string> {\n\treturn new Promise((resolve) => {\n\t\tif (process.stdin.isTTY) {\n\t\t\tresolve('');\n\t\t\treturn;\n\t\t}\n\t\tconst chunks: Buffer[] = [];\n\t\tprocess.stdin.on('data', (chunk: Buffer) => chunks.push(chunk));\n\t\tprocess.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n\t\tprocess.stdin.on('error', () => resolve(''));\n\t\t// Timeout after 1s to avoid hanging\n\t\tsetTimeout(() => {\n\t\t\tprocess.stdin.destroy();\n\t\t\tresolve(Buffer.concat(chunks).toString('utf8'));\n\t\t}, 1000);\n\t});\n}\n\nasync function main(argv: string[]): Promise<void> {\n\tconst { values, positionals } = parseArgs({\n\t\targs: argv,\n\t\toptions: {\n\t\t\tbrain: { type: 'string', short: 'b' },\n\t\t\tdays: { type: 'string', short: 'd' },\n\t\t\tport: { type: 'string', short: 'p' },\n\t\t\ttranscript: { type: 'string', short: 't' },\n\t\t\thelp: { type: 'boolean', short: 'h' },\n\t\t\tversion: { type: 'boolean', short: 'v' },\n\t\t},\n\t\tallowPositionals: true,\n\t\tstrict: false,\n\t});\n\n\tif (values.version) {\n\t\tconsole.log(`hebbian v${VERSION}`);\n\t\treturn;\n\t}\n\n\tconst command = positionals[0];\n\n\tif (values.help || !command) {\n\t\tconsole.log(HELP);\n\t\treturn;\n\t}\n\n\tconst brainRoot = resolveBrainRoot(values.brain as string | undefined);\n\n\tswitch (command) {\n\t\tcase 'init': {\n\t\t\tconst target = positionals[1];\n\t\t\tif (!target) {\n\t\t\t\tconsole.error('Usage: hebbian init <path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { initBrain } = await import('./init');\n\t\t\tawait initBrain(resolve(target));\n\t\t\tbreak;\n\t\t}\n\t\tcase 'emit': {\n\t\t\tconst target = positionals[1];\n\t\t\tif (!target) {\n\t\t\t\tconsole.error('Usage: hebbian emit <target> (claude/cursor/gemini/copilot/generic/all)');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { emitToTarget } = await import('./emit');\n\t\t\tawait emitToTarget(brainRoot, target);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'fire': {\n\t\t\tconst neuronPath = positionals[1];\n\t\t\tif (!neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian fire <neuron-path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { fireNeuron } = await import('./fire');\n\t\t\tawait fireNeuron(brainRoot, neuronPath);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'grow': {\n\t\t\tconst neuronPath = positionals[1];\n\t\t\tif (!neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian grow <neuron-path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { growNeuron } = await import('./grow');\n\t\t\tawait growNeuron(brainRoot, neuronPath);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'rollback': {\n\t\t\tconst neuronPath = positionals[1];\n\t\t\tif (!neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian rollback <neuron-path>');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { rollbackNeuron } = await import('./rollback');\n\t\t\tawait rollbackNeuron(brainRoot, neuronPath);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'signal': {\n\t\t\tconst signalType = positionals[1];\n\t\t\tconst neuronPath = positionals[2];\n\t\t\tif (!signalType || !neuronPath) {\n\t\t\t\tconsole.error('Usage: hebbian signal <type> <neuron-path> (type: dopamine/bomb/memory)');\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tconst { signalNeuron } = await import('./signal');\n\t\t\tawait signalNeuron(brainRoot, neuronPath, signalType as SignalType);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'decay': {\n\t\t\tconst days = values.days ? parseInt(values.days as string, 10) : 30;\n\t\t\tconst { runDecay } = await import('./decay');\n\t\t\tawait runDecay(brainRoot, days);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'dedup': {\n\t\t\tconst { runDedup } = await import('./dedup');\n\t\t\trunDedup(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'snapshot': {\n\t\t\tconst { gitSnapshot } = await import('./snapshot');\n\t\t\tgitSnapshot(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'watch': {\n\t\t\tconst { startWatch } = await import('./watch');\n\t\t\tawait startWatch(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'api': {\n\t\t\tconst port = values.port ? parseInt(values.port as string, 10) : 9090;\n\t\t\tconst { startAPI } = await import('./api');\n\t\t\tstartAPI(brainRoot, port);\n\t\t\t// Keep process alive — server handles shutdown\n\t\t\tawait new Promise(() => {});\n\t\t\tbreak;\n\t\t}\n\t\tcase 'inbox': {\n\t\t\tconst { processInbox } = await import('./inbox');\n\t\t\tprocessInbox(brainRoot);\n\t\t\tbreak;\n\t\t}\n\t\tcase 'claude': {\n\t\t\tconst sub = positionals[1];\n\t\t\tconst { installHooks, uninstallHooks, checkHooks } = await import('./hooks');\n\t\t\tswitch (sub) {\n\t\t\t\tcase 'install': {\n\t\t\t\t\t// For install: default to ./brain in project root, not home dir fallback\n\t\t\t\t\tconst installBrain = values.brain\n\t\t\t\t\t\t? resolve(values.brain as string)\n\t\t\t\t\t\t: resolve('./brain');\n\t\t\t\t\tinstallHooks(installBrain);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'uninstall':\n\t\t\t\t\tuninstallHooks();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'status':\n\t\t\t\t\tcheckHooks();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tconsole.error('Usage: hebbian claude <install|uninstall|status>');\n\t\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'digest': {\n\t\t\tconst transcriptFlag = values.transcript as string | undefined;\n\t\t\tconst { digestTranscript, readHookInput } = await import('./digest');\n\t\t\tif (transcriptFlag) {\n\t\t\t\tdigestTranscript(brainRoot, resolve(transcriptFlag));\n\t\t\t} else {\n\t\t\t\t// Read stdin for hook input\n\t\t\t\tconst stdin = await readStdin();\n\t\t\t\tconst hookInput = readHookInput(stdin);\n\t\t\t\tif (hookInput) {\n\t\t\t\t\tdigestTranscript(brainRoot, hookInput.transcriptPath, hookInput.sessionId);\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error('Usage: hebbian digest --transcript <path>');\n\t\t\t\t\tconsole.error(' Or pipe hook input via stdin (Claude Code Stop hook)');\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'diag':\n\t\tcase 'stats': {\n\t\t\tconst { scanBrain } = await import('./scanner');\n\t\t\tconst { runSubsumption } = await import('./subsumption');\n\t\t\tconst brain = scanBrain(brainRoot);\n\t\t\tconst result = runSubsumption(brain);\n\t\t\tconst { printDiag } = await import('./emit');\n\t\t\tprintDiag(brain, result);\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tconsole.error(`Unknown command: ${command}`);\n\t\t\tconsole.log(H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ACD;AAAA,IACA,KAAK,UAAU;AACd,YAAM,iBAAiB,OAAO;AAC9B,YAAM,EAAE,kBAAAC,mBAAkB,eAAAC,eAAc,IAAI,MAAM;AAClD,UAAI,gBAAgB;AACnB,QAAAD,kBAAiB,WAAWhB,SAAQ,cAAc,CAAC;AAAA,MACpD,OAAO;AAEN,cAAM,QAAQ,MAAM,UAAU;AAC9B,cAAM,YAAYiB,eAAc,KAAK;AACrC,YAAI,WAAW;AACd,UAAAD,kBAAiB,WAAW,UAAU,gBAAgB,UAAU,SAAS;AAAA,QAC1E,OAAO;AACN,kBAAQ,MAAM,2CAA2C;AACzD,kBAAQ,MAAM,wDAAwD;AACtE,kBAAQ,KAAK,CAAC;AAAA,QACf;AAAA,MACD;AACA;AAAA,IACD;AAAA,IACA,KAAK;AAAA,IACL,KAAK,SAAS;AACb,YAAM,EAAE,WAAAE,WAAU,IAAI,MAAM;AAC5B,YAAM,EAAE,gBAAAC,gBAAe,IAAI,MAAM;AACjC,YAAM,QAAQD,WAAU,SAAS;AACjC,YAAM,SAASC,gBAAe,KAAK;AACnC,YAAM,EAAE,WAAAC,WAAU,IAAI,MAAM;AAC5B,MAAAA,WAAU,OAAO,MAAM;AACvB;AAAA,IACD;AAAA,IACA;AACC,cAAQ,MAAM,oBAAoB,OAAO,EAAE;AAC3C,cAAQ,IAAI,IAAI;AAChB,cAAQ,KAAK,CAAC;AAAA,EAChB;AACD;AAEA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,QAAe;AACjD,UAAQ,MAAM,IAAI,OAAO;AACzB,UAAQ,KAAK,CAAC;AACf,CAAC;","names":["existsSync","readdirSync","existsSync","join","existsSync","readFileSync","writeFileSync","mkdirSync","join","readdirSync","writeFileSync","existsSync","mkdirSync","join","mkdirSync","writeFileSync","existsSync","readdirSync","join","relative","renameSync","join","writeFileSync","existsSync","readdirSync","join","readdirSync","statSync","writeFileSync","existsSync","join","writeFileSync","join","existsSync","join","resolve","readdirSync","readFileSync","writeFileSync","mkdirSync","existsSync","join","readFileSync","writeFileSync","existsSync","mkdirSync","join","resolve","readFileSync","writeFileSync","existsSync","mkdirSync","readdirSync","join","resolve","group","readFileSync","writeFileSync","existsSync","mkdirSync","join","resolve","initBrain","emitToTarget","fireNeuron","growNeuron","rollbackNeuron","signalNeuron","runDecay","runDedup","gitSnapshot","startWatch","startAPI","processInbox","installHooks","uninstallHooks","checkHooks","digestTranscript","readHookInput","scanBrain","runSubsumption","printDiag"]}