{"id":43769151,"url":"https://github.com/kluth/synapse","last_synced_at":"2026-02-05T16:09:47.496Z","repository":{"id":322785746,"uuid":"1090838257","full_name":"kluth/synapse","owner":"kluth","description":null,"archived":false,"fork":false,"pushed_at":"2025-11-06T11:00:22.000Z","size":91,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-06T11:16:31.831Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kluth.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-06T07:51:53.000Z","updated_at":"2025-11-06T11:00:26.000Z","dependencies_parsed_at":null,"dependency_job_id":"b2fd7bf6-18f4-4c30-be67-b7beb1c0f1c8","html_url":"https://github.com/kluth/synapse","commit_stats":null,"previous_names":["kluth/synapse"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/kluth/synapse","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kluth%2Fsynapse","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kluth%2Fsynapse/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kluth%2Fsynapse/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kluth%2Fsynapse/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kluth","download_url":"https://codeload.github.com/kluth/synapse/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kluth%2Fsynapse/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29125135,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-05T14:05:12.718Z","status":"ssl_error","status_checked_at":"2026-02-05T14:03:53.078Z","response_time":65,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-02-05T16:09:46.351Z","updated_at":"2026-02-05T16:09:47.490Z","avatar_url":"https://github.com/kluth.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Synapse Framework\n\n**A Neural-Inspired TypeScript Framework for Building Distributed Systems**\n\n[![CI](https://github.com/kluth/synapse/actions/workflows/ci.yml/badge.svg)](https://github.com/kluth/synapse/actions/workflows/ci.yml)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue)](https://www.typescriptlang.org/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nSynapse is a TypeScript framework that brings biological intelligence patterns to distributed software architecture. Inspired by the nervous system's 3 billion years of evolution, it models applications as neural networks where components communicate through type-safe connections, adapt to changing conditions, and self-heal from failures.\n\n## 🧠 Core Concept\n\nJust as the nervous system processes billions of signals with remarkable efficiency and resilience, Synapse provides architectural patterns for building scalable, fault-tolerant distributed systems. The framework models:\n\n- **Neurons** → Microservices/Functions (processing units)\n- **Synapses** → Communication channels (type-safe connections)\n- **Glial Cells** → Support infrastructure (caching, monitoring, routing)\n- **Neural Circuits** → Service orchestration (network topology)\n- **Neuroplasticity** → Self-healing and optimization (adaptive resilience)\n\n## 🚀 Current Status (v0.1.0)\n\n**Production-Ready Core Components:**\n- ✅ **6,266** lines of TypeScript code\n- ✅ **160** passing tests across 11 test suites\n- ✅ **100%** strict TypeScript with full type safety\n- ✅ Comprehensive CI/CD with GitHub Actions\n- ✅ Automated dependency management with Dependabot\n\n## 📦 What's Implemented\n\n### Core Processing Units\n\n#### NeuralNode\nBase processing abstraction with biological neuron behavior:\n```typescript\nimport { NeuralNode } from '@synapse-framework/core';\n\nconst node = new NeuralNode({\n  id: 'user-service',\n  threshold: 0.7,  // Activation threshold\n});\n\nawait node.activate();\n\n// Receive signals (dendrite behavior)\nawait node.receive({\n  id: crypto.randomUUID(),\n  sourceId: 'auth-service',\n  type: 'excitatory',\n  strength: 0.8,\n  payload: { userId: '123' },\n  timestamp: new Date(),\n});\n\n// Check if threshold exceeded\nconst decision = node.integrate();\nif (decision.shouldFire) {\n  const result = await node.process(input);\n}\n```\n\n#### CorticalNeuron (Stateful Services)\nFor long-running, stateful microservices:\n```typescript\nimport { CorticalNeuron } from '@synapse-framework/core';\n\nconst userService = new CorticalNeuron({\n  id: 'user-service',\n  threshold: 0.5,\n});\n\n// Maintains state across processing\nconst result = await userService.process({\n  data: { action: 'login', userId: '123' }\n});\n\n// State persists between calls\nconsole.log(userService.getState());  // Access accumulated state\n```\n\n#### ReflexNeuron (Serverless Functions)\nFor event-driven, stateless operations:\n```typescript\nimport { ReflexNeuron } from '@synapse-framework/core';\n\nconst imageProcessor = new ReflexNeuron({\n  id: 'image-resize',\n  threshold: 0.8,\n});\n\n// Activates on demand, scales to zero when idle\nawait imageProcessor.process({\n  data: { imageUrl: 'https://...', size: '200x200' }\n});\n\n// Automatically deactivates after processing\n```\n\n### Connection System\n\n#### Synaptic Connections\nType-safe communication with plasticity:\n```typescript\nimport { Connection } from '@synapse-framework/core';\n\nconst connection = new Connection({\n  source: sourceNeuron,\n  target: targetNeuron,\n  weight: 0.8,           // Signal amplification\n  type: 'excitatory',    // Activation type\n  speed: 'myelinated',   // Fast transmission\n});\n\n// Transmit signals\nawait connection.transmit(signal);\n\n// Connections adapt based on usage (Hebbian learning)\nconnection.strengthen();  // Increase weight\nconnection.weaken();      // Decrease weight\n\n// Prune unused connections\nif (connection.shouldPrune(threshold)) {\n  connection.prune();\n}\n```\n\n### Glial Cell Support Systems\n\n#### Astrocyte - State Management\nLRU cache with TTL and namespace support:\n```typescript\nimport { Astrocyte } from '@synapse-framework/core';\n\nconst stateManager = new Astrocyte({\n  id: 'state-manager',\n  maxSize: 1000,        // Max cached items\n  defaultTTL: 300000,   // 5 minutes\n});\n\nawait stateManager.activate();\n\n// Store with automatic expiration\nstateManager.set('user:123', userData, 60000);  // 1 minute TTL\n\n// Retrieve\nconst user = stateManager.get('user:123');\n\n// Pattern matching\nconst allUsers = stateManager.getKeysByPattern('user:*');\n\n// Statistics\nconst stats = stateManager.getStatistics();\nconsole.log(`Hit rate: ${stats.hitRate}%`);\n```\n\n#### Oligodendrocyte - Performance Optimization\nConnection pooling and resource caching:\n```typescript\nimport { Oligodendrocyte } from '@synapse-framework/core';\n\nconst optimizer = new Oligodendrocyte({\n  id: 'performance-optimizer',\n  maxConnections: 10,\n  connectionTTL: 300000,\n});\n\nawait optimizer.activate();\n\n// Connection pooling\nconst conn = await optimizer.acquireConnection('db-pool');\n// Use connection...\noptimizer.releaseConnection('db-pool', conn);\n\n// Resource caching with memoization\nconst result = await optimizer.cacheResource(\n  'expensive-computation',\n  async () =\u003e performExpensiveOperation(),\n  { ttl: 60000 }\n);\n\n// Track optimized paths (myelination)\noptimizer.trackMyelination('auth-service', 'user-service');\nconst stats = optimizer.getMyelinationStats();\n```\n\n#### Microglia - Health Monitoring\nError tracking and metrics collection:\n```typescript\nimport { Microglia } from '@synapse-framework/core';\n\nconst monitor = new Microglia({\n  id: 'health-monitor',\n  errorThreshold: 10,  // Alert after 10 errors\n});\n\nawait monitor.activate();\n\n// Error tracking\nmonitor.recordError('user-service', new Error('Connection failed'));\n\n// Metrics collection\nmonitor.recordMetric('user-service', 'response_time', 125);\n\n// Health checks\nmonitor.registerHealthCheck('user-service', async () =\u003e {\n  // Check if service is healthy\n  return service.isHealthy();\n});\n\n// Alert handling\nmonitor.onAlert((alert) =\u003e {\n  console.log(`🚨 Alert: ${alert.message}`);\n  // Send to monitoring system\n});\n\n// System health\nconst health = monitor.getSystemHealth();\nconsole.log(`Healthy entities: ${health.healthyCount}/${health.totalCount}`);\n```\n\n#### Ependymal - API Gateway\nRequest routing and rate limiting:\n```typescript\nimport { Ependymal } from '@synapse-framework/core';\n\nconst gateway = new Ependymal({\n  id: 'api-gateway',\n  rateLimit: { requests: 100, window: 60000 },  // 100 req/min\n});\n\nawait gateway.activate();\n\n// Route registration\ngateway.registerRoute('POST', '/users', async (req) =\u003e {\n  return { status: 201, data: await createUser(req.data) };\n});\n\n// Middleware pipeline\ngateway.addMiddleware(async (req, next) =\u003e {\n  // Authentication, logging, etc.\n  console.log(`${req.method} ${req.path}`);\n  return next(req);\n});\n\n// Handle requests\nconst response = await gateway.handleRequest({\n  method: 'POST',\n  path: '/users',\n  data: { name: 'Alice' },\n  clientId: 'client-123',\n});\n\n// Statistics\nconst stats = gateway.getStatistics();\nconsole.log(`Total requests: ${stats.totalRequests}`);\n```\n\n### Network Organization\n\n#### NeuralCircuit\nManage neuron topology and connections:\n```typescript\nimport { NeuralCircuit } from '@synapse-framework/core';\n\nconst circuit = new NeuralCircuit({\n  id: 'user-management-circuit',\n});\n\n// Add neurons\ncircuit.addNeuron(authService);\ncircuit.addNeuron(userService);\ncircuit.addNeuron(emailService);\n\n// Connect neurons\ncircuit.connect(authService, userService, { weight: 0.9 });\ncircuit.connect(userService, emailService, { weight: 0.7 });\n\n// Activate entire circuit\nawait circuit.activateAll();\n\n// Analyze topology\nconst hasCycles = circuit.hasCycles();\nconst isFeedForward = circuit.isFeedForward();\n\n// Statistics\nconst stats = circuit.getStatistics();\nconsole.log(`Neurons: ${stats.neuronCount}, Connections: ${stats.connectionCount}`);\n```\n\n### Self-Healing System\n\n#### Neuroplasticity\nAdaptive optimization and resilience:\n```typescript\nimport { Neuroplasticity } from '@synapse-framework/core';\n\nconst plasticity = new Neuroplasticity({\n  pruningThreshold: 0.3,      // Remove weak connections\n  trainingIterations: 100,     // Learning cycles\n});\n\n// Synaptic pruning - remove weak connections\nconst pruned = plasticity.pruneWeakConnections(circuit);\nconsole.log(`Pruned ${pruned.length} weak connections`);\n\n// Strengthen frequently used paths\nplasticity.trainConnection(connection, 10);  // Simulate 10 uses\n\n// Detect failures and create bypass routes\nconst failedNeurons = circuit.neurons.filter(n =\u003e !n.isHealthy());\nconst bypasses = plasticity.rewireAroundFailure(circuit, failedNeurons);\nconsole.log(`Created ${bypasses.length} bypass connections`);\n\n// Network health assessment\nconst health = plasticity.assessNetworkHealth(circuit);\nconsole.log(`Network health: ${(health.healthPercentage * 100).toFixed(1)}%`);\n```\n\n### Event System\n\n#### EventBus\nType-safe pub-sub with schema validation:\n```typescript\nimport { EventBus } from '@synapse-framework/core';\nimport { z } from 'zod';\n\nconst eventBus = new EventBus();\n\n// Define event schema\nconst UserRegisteredSchema = z.object({\n  id: z.string().uuid(),\n  type: z.literal('user:registered'),\n  source: z.string(),\n  data: z.object({\n    userId: z.string(),\n    email: z.string().email(),\n  }),\n  timestamp: z.date(),\n});\n\n// Subscribe with schema validation\neventBus.subscribe(\n  'user:registered',\n  async (event) =\u003e {\n    console.log(`New user: ${event.data.email}`);\n    await sendWelcomeEmail(event.data.email);\n  },\n  { schema: UserRegisteredSchema }\n);\n\n// Wildcard subscriptions\neventBus.subscribe('user:*', async (event) =\u003e {\n  // Handle all user events\n});\n\n// Emit events\nawait eventBus.emit('user:registered', {\n  id: crypto.randomUUID(),\n  type: 'user:registered',\n  source: 'user-service',\n  data: { userId: '123', email: 'user@example.com' },\n  timestamp: new Date(),\n});\n\n// One-time listeners\neventBus.once('system:shutdown', async () =\u003e {\n  await cleanup();\n});\n```\n\n## 🏗️ Architecture Patterns\n\n### Threshold-Based Activation\nNeurons only process when accumulated signals exceed their threshold, providing natural backpressure and preventing unnecessary computation.\n\n### Synaptic Plasticity\nConnections strengthen with repeated use (Long-Term Potentiation) and weaken with disuse (Long-Term Depression), optimizing communication patterns over time.\n\n### Hebbian Learning\n\"Neurons that fire together, wire together\" - frequently co-activated components automatically optimize their connections.\n\n### Self-Healing Networks\nFailed neurons are automatically routed around using redundant pathways and compensatory mechanisms, similar to brain injury recovery.\n\n## 🧪 Development\n\n### Installation\n\n```bash\nnpm install\n```\n\n### Running Tests\n\n```bash\nnpm test              # Run all tests\nnpm run test:watch    # Watch mode\nnpm run test:coverage # With coverage report\n```\n\n### Building\n\n```bash\nnpm run build         # TypeScript compilation\nnpm run type-check    # Type checking only\n```\n\n### Code Quality\n\n```bash\nnpm run lint          # ESLint\nnpm run lint:fix      # Auto-fix issues\nnpm run format        # Prettier formatting\n```\n\n## 📊 Test Coverage\n\n- **11** test suites covering all major components\n- **160** tests ensuring comprehensive behavior validation\n- **Test categories:**\n  - Core: 29 tests (NeuralNode, Connection)\n  - Neurons: 19 tests (Cortical, Reflex)\n  - Glial: 86 tests (Astrocyte, Oligodendrocyte, Microglia, Ependymal)\n  - Network: 16 tests (NeuralCircuit)\n  - Communication: 19 tests (EventBus)\n  - Plasticity: 8 tests (Neuroplasticity)\n\n## 🔧 Technology Stack\n\n- **Runtime:** Node.js + Bun support\n- **Language:** TypeScript 5.3+ (strict mode)\n- **Testing:** Jest with ts-jest\n- **Validation:** Zod for runtime schema validation\n- **Code Quality:** ESLint + Prettier\n- **CI/CD:** GitHub Actions\n- **Security:** CodeQL analysis, Dependabot\n\n## 🎯 Use Cases\n\n### Microservices Architecture\nModel each service as a neuron with typed synaptic connections, automatic health monitoring, and self-healing capabilities.\n\n### Event-Driven Systems\nUse RefexNeurons for serverless functions, CorticalNeurons for stateful services, with EventBus for pub-sub communication.\n\n### Distributed Caching\nLeverage Astrocyte's LRU cache with TTL and Oligodendrocyte's connection pooling for multi-level performance optimization.\n\n### API Gateway\nDeploy Ependymal as your gateway with built-in rate limiting, request validation, and middleware pipeline support.\n\n### Observability\nMicroglia provides comprehensive health monitoring, error tracking, and metrics collection out of the box.\n\n## 🗺️ Roadmap\n\n### Planned Features\n- [ ] Distributed state synchronization across Astrocytes\n- [ ] gRPC/tRPC integration for fast synapses\n- [ ] Kafka/RabbitMQ adapters for event synapses\n- [ ] Advanced ML-based plasticity algorithms\n- [ ] Visual circuit debugger and topology viewer\n- [ ] Kubernetes operators for deployment\n- [ ] Performance benchmarking suite\n- [ ] Real-world example applications\n\n### Current Limitations\n- In-memory only (no distributed coordination yet)\n- No persistent storage adapters\n- No built-in service discovery\n- Limited protocol implementations\n\n## 📚 Biological Inspiration\n\nThe framework draws from these neurological concepts:\n\n- **Neurons:** Specialized processing units (cortical vs reflex)\n- **Synapses:** Chemical/electrical communication with plasticity\n- **Glial Cells:** Support infrastructure (90% of brain cells)\n  - Astrocytes: Metabolic support and homeostasis\n  - Oligodendrocytes: Myelination for speed optimization\n  - Microglia: Immune system and health monitoring\n  - Ependymal: CSF circulation and waste removal\n- **Neural Circuits:** Organized networks with feedback loops\n- **Neuroplasticity:** Adaptive rewiring and self-healing\n- **CNS/PNS:** Central processing vs edge distribution\n\n## 🤝 Contributing\n\nContributions welcome! This framework is in active development.\n\n### Development Setup\n\n1. Clone the repository\n2. Run `npm install`\n3. Make changes with tests\n4. Run `npm test` and `npm run lint`\n5. Submit a pull request\n\nGit hooks enforce code quality:\n- **pre-commit:** Linting, formatting, type checking, tests\n- **pre-push:** Full test suite with coverage\n\n## 📄 License\n\nMIT License - see LICENSE file for details\n\n## 🙏 Acknowledgments\n\nBuilt with inspiration from:\n- Biological neuroscience and neural networks\n- Akka/Orleans actor model patterns\n- Modern microservices best practices\n- Functional reactive programming concepts\n\n---\n\n**Status:** Active Development | **Version:** 0.1.0 | **TypeScript:** 5.3+ | **Tests:** 160 passing\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkluth%2Fsynapse","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkluth%2Fsynapse","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkluth%2Fsynapse/lists"}